Debian Codegraph @

Source/utf.h

raw
1 /*
2 * utf.h
3 *
4 * This file is a part of NSIS.
5 *
6 * Copyright (C) 2011-2026 Anders Kjersem
7 *
8 * Licensed under the zlib/libpng license (the "License");
9 * you may not use this file except in compliance with the License.
10 *
11 * Licence details can be found in the file COPYING.
12 *
13 * This software is provided 'as-is', without any express or implied
14 * warranty.
15 *
16 */
17
18 #ifndef NSIS_UTF_H
19 #define NSIS_UTF_H
20
21 #include "Platform.h"
22
23 const WORD UNICODE_REPLACEMENT_CHARACTER = 0xfffd;
24
25 #define TSTR_INPUTCHARSET _T("ACP|OEM|CP#|UTF8|UTF16<LE|BE>")
26 #define TSTR_OUTPUTCHARSET _T("ACP|OEM|CP#|UTF8[SIG]|UTF16<LE|BE>[BOM]")
27
28 template<typename T> T S7ChLwr(T c) { return c>='A' && c<='Z' ? (T)(c|32) : c; }
29 template<typename T> T S7ChUpr(T c) { return c>='a' && c<='z' ? (T)(c-'a'+'A') : c; }
30 template<typename T> bool S7IsChEqualI(char ch,T cmp)
31 {
32 return S7ChLwr((T)ch) == S7ChLwr(cmp);
33 }
34
35 inline bool IsValidUnicodeCodePoint(UINT32 c,bool StrictUTF32=false)
36 {
37 // Unicode 6.1: 16.7 Noncharacters
38 if ((c&0xfffe) == 0xfffe) return false; // ..FFFE & ..FFFF is reserved in each plane
39 if (c >= 0xfdd0 && c <= 0xfdef) return false; // Reserved in BMP
40 if (StrictUTF32 && c > 0x10ffff) return false;
41 return true;
42 }
43 inline bool IsLeadSurrogateUTF16(unsigned short c) { return c >= 0xd800 && c <= 0xdbff; }
44 inline bool IsTrailSurrogateUTF16(unsigned short c) { return c >= 0xdc00 && c <= 0xdfff; }
45 inline UINT32 CodePointFromUTF16SurrogatePair(unsigned short lea,unsigned short tra)
46 {
47 const UINT32 surrogate_offset = 0x10000 - (0xD800 << 10) - 0xDC00;
48 return ((UINT32)lea << 10) + tra + surrogate_offset;
49 }
50
51 inline bool UTF8_GetTrailCount(unsigned char chFirst, unsigned char &cb)
52 {
53 // This function should only be used to get a rough idea of how large the encoded
54 // codepoint is, just because it returns true does not mean that it is valid UTF-8!
55 cb = 0;
56 if (0xC0 == (0xC0 & chFirst))
57 {
58 ++cb;
59 if (0xE0 == (0xE0 & chFirst))
60 {
61 ++cb;
62 if (0xF0 == (0xF0 & chFirst))
63 {
64 ++cb;
65 if (0xF8 == (0xF8 & chFirst))
66 {
67 ++cb;
68 if (0xFC == (0xFE & chFirst)) ++cb; else return 0xFC >= (0xFE & chFirst);
69 }
70 }
71 }
72 return true;
73 }
74 return (signed char)chFirst >= 0;
75 }
76
77 inline UINT InlineStrLenUTF16(const void*str)
78 {
79 unsigned short *p = (unsigned short *) str;
80 UINT cch = 0;
81 for(;p[cch];) ++cch;
82 return cch;
83 }
84
85 #ifdef MAKENSIS
86 #include <stdlib.h>
87 #include <stdio.h>
88 #include "tstring.h"
89 #include "util.h" // iconvdescriptor & my_fopen
90 #ifdef _WIN32
91 #include <io.h> // For _setmode
92 #include <fcntl.h> // For _O_BINARY
93 #endif
94
95 FILE* my_fopen(const TCHAR *path, const char *mode); // from util.h
96
97 void UTF16InplaceEndianSwap(void*Buffer, UINT cch);
98 UINT StrLenUTF16(const void*str);
99 bool StrSetUTF16LE(tstring&dest, const void*src);
100
101 UINT WCFromCodePoint(wchar_t*Dest,UINT cchDest,UINT32 CodPt);
102 #define DWCFBF_ALLOWOPTIMIZEDRETURN 0x80000000 // DupWCFromBytes can return input Buffer
103 wchar_t* DupWCFromBytes(void*Buffer,UINT cbBuffer,UINT32 SrcCP);
104 UINT DetectUTFBOM(void*Buffer,UINT cb);
105 UINT DetectUTFBOM(FILE*strm);
106 WORD GetEncodingFromString(const TCHAR*s, bool&BOM);
107 WORD GetEncodingFromString(const TCHAR*s);
108
109 class CharEncConv {
110 char *m_Result;
111 WORD m_TE, m_FE;
112 #ifdef _WIN32
113 bool m_AllowOptimizedReturn; // Can Convert() return Src buffer?
114 bool m_OptimizedReturn;
115 #else
116 iconvdescriptor m_iconvd;
117 #endif
118 protected:
119 size_t GuessOutputSize(size_t cbConverted);
120 static bool IsWE(WORD Encoding) { return (WORD)-1 == Encoding; }
121 static bool IsWE(UINT32 Encoding) { return (UINT32)-1 == Encoding; }
122 public:
123 CharEncConv() : m_Result(0) { SetAllowOptimizedReturn(false); }
124 ~CharEncConv() { Close(); }
125 void Close()
126 {
127 #ifdef _WIN32
128 if (!m_OptimizedReturn)
129 #endif
130 free(m_Result);
131 m_Result = 0;
132 #ifndef _WIN32
133 m_iconvd.Close();
134 #endif
135 }
136 void* Detach() { void *p = m_Result; m_Result = 0; return p; }
137 bool Initialize(UINT32 ToEnc, UINT32 FromEnc);
138 void* Convert(const void*Src, size_t cbSrc = -1, size_t*cbOut = 0);
139 #ifdef _WIN32
140 void SetAllowOptimizedReturn(bool val = true) { m_AllowOptimizedReturn = val; }
141 #else
142 void SetAllowOptimizedReturn(bool val = false) {}
143 #endif
144 static BOOL IsValidCodePage(UINT cp);
145 };
146
147 class WCToUTF16LEHlpr {
148 unsigned short* m_s;
149 public:
150 WCToUTF16LEHlpr() : m_s(0) {}
151
152 bool Create(const TCHAR*in, unsigned int codepage = CP_ACP)
153 #if !defined(_WIN32) || !defined(_UNICODE)
154 ;
155 #else
156 {
157 m_s = (unsigned short*) in;
158 return true;
159 }
160 #endif
161 void Destroy()
162 {
163 #if !defined(_WIN32) || !defined(_UNICODE)
164 free(m_s);
165 #endif
166 }
167 const unsigned short* Get() const { return m_s; }
168 UINT GetLen() const { return StrLenUTF16(m_s); }
169 UINT GetSize() const { return (GetLen()+1) * 2; }
170 unsigned short* Detach() { unsigned short *r = m_s; m_s = 0; return r; }
171 void CopyTo(unsigned short*Dest) const { memcpy(Dest, Get(), GetSize()); }
172 };
173
174 class NStreamEncoding {
175 protected:
176 WORD m_cp;
177 public:
178 enum {
179 ACP = CP_ACP,
180 OEMCP = 1,
181 UTF16LE = 1200,
182 UTF16BE = 1201,
183 UTF32LE = 12000,
184 UTF32BE = 12001,
185 UTF8 = CP_UTF8,
186 UNKNOWN = (0xffff-0),
187 AUTO = (0xffff-1),
188 BINARY = (0xffff-2),
189 CPCOUNT = (0xffff-3) // Must be less than our other magic numbers
190 };
191
192 NStreamEncoding() { Reset(); }
193 NStreamEncoding(WORD cp) { Reset(), SetCodepage(cp); }
194 WORD GetCodepage() const { return m_cp; }
195 void SetCodepage(WORD cp) { m_cp = cp; }
196 void SafeSetCodepage(WORD cp)
197 {
198 if (NStreamEncoding::AUTO==cp) cp = GetPlatformDefaultCodepage();
199 SetCodepage(cp);
200 }
201 void Reset() { SetCodepage(GetPlatformDefaultCodepage()); }
202 WORD GetPlatformDefaultCodepage() const
203 {
204 #ifdef _WIN32
205 return ACP;
206 #else
207 return UTF8;
208 #endif
209 }
210 bool IsUTF8() const { return UTF8==GetCodepage(); }
211 bool IsUTF16() const { return (UTF16LE|1)==(GetCodepage()|1); }
212 bool IsUTF16LE() const { return UTF16LE==GetCodepage(); }
213 bool IsUTF16BE() const { return UTF16BE==GetCodepage(); }
214 bool IsUnicode() const { return IsUnicodeCodepage(GetCodepage()); }
215 void GetCPDisplayName(TCHAR*Buf) { GetCPDisplayName(m_cp, Buf); }
216
217 static UINT GetCodeUnitSize(WORD cp)
218 {
219 if ((UTF16LE|1)==(cp|1)) return 2;
220 if ((UTF32LE|1)==(cp|1)) return 4;
221 return 1;
222 }
223 static bool IsUnicodeCodepage(WORD cp)
224 {
225 return UTF8==cp || (UTF16LE|1)==(cp|1) || (UTF32LE|1)==(cp|1);
226 }
227 static void GetCPDisplayName(WORD CP, TCHAR*Buf);
228 };
229
230 class NStream {
231 public:
232 enum {
233 OK = 0,
234 ERR_BUFFEROVERFLOW,
235 ERR_IOERROR,
236 ERR_INVALIDENCODING,
237 ERR_UNSUPPORTEDENCODING,
238 };
239 static bool IsNewline(wchar_t chW, bool HandleUnicodeNL)
240 {
241 if (L'\n'==chW || L'\r'==chW) return true;
242 if (HandleUnicodeNL)
243 {
244 // www.unicode.org/standard/reports/tr13/tr13-5.html#UNICODE NEWLINE GUIDELINES
245 if (L'\f'==chW) return true; // FF/Form Feed
246 if (L'\v'==chW) return true; // VT/Vertical Tab
247 // NOTIMPLEMENTED: NEL/Next Line/U+0085
248 // NOTIMPLEMENTED: LS/Line Separator/U+2028
249 // NOTIMPLEMENTED: PS/Paragraph Separator/U+2029
250 }
251 return false;
252 }
253 #ifdef _WIN32
254 static bool SetBinaryMode(int fd) { return -1 != _setmode(fd, _O_BINARY); }
255 static bool SetBinaryMode(FILE*f) { return SetBinaryMode(_fileno(f)); }
256 #else
257 static bool SetBinaryMode(int fd) { return true; }
258 static bool SetBinaryMode(FILE*f) { return true; }
259 #endif
260 };
261
262 class NBaseStream {
263 protected:
264 FILE* m_hFile;
265 NStreamEncoding m_Enc;
266
267 public:
268 NBaseStream(FILE *hFile = 0) : m_hFile(hFile) {}
269 ~NBaseStream() { Close(); }
270
271 FILE* GetHandle() const { return m_hFile; }
272 NStreamEncoding& StreamEncoding() { return m_Enc; }
273 bool IsEOF() const { return feof(m_hFile) != 0; }
274 bool IsError() const { return ferror(m_hFile) != 0; }
275 bool IsUnicode() const { return m_Enc.IsUnicode(); }
276
277 void Close()
278 {
279 FILE*hF = Detach();
280 if (hF) fclose(hF);
281 }
282
283 bool OpenFileForReading(const TCHAR* Path, WORD enc = NStreamEncoding::AUTO)
284 {
285 return Attach(my_fopen(Path, "rb"), enc);
286 }
287 bool OpenFileForReading(const TCHAR* Path, NStreamEncoding&Enc)
288 {
289 return OpenFileForReading(Path, Enc.GetCodepage());
290 }
291
292 FILE* Detach()
293 {
294 FILE *hFile = m_hFile;
295 m_hFile = 0;
296 return hFile;
297 }
298 bool Attach(FILE*hFile, WORD enc, bool Seek = true);
299
300 UINT ReadOctets(void*Buffer, UINT cbBuf)
301 {
302 size_t cb = fread(Buffer, 1, cbBuf, m_hFile);
303 return (UINT) cb;
304 }
305 bool ReadOctets(void*Buffer, UINT*pcbBuf)
306 {
307 UINT cbReq = *pcbBuf, cb = ReadOctets(Buffer, cbReq);
308 *pcbBuf = cb;
309 return cbReq == cb;
310 }
311 bool ReadOctet(void*Buffer) { return 1 == ReadOctets(Buffer, 1); }
312 bool ReadInt16(void*Buffer) { return 2 == ReadOctets(Buffer, 2); }
313 };
314
315 class NIStream : public NBaseStream {
316 public:
317 bool OpenStdIn(WORD enc = NStreamEncoding::AUTO)
318 {
319 return Attach(stdin, enc, false);
320 }
321 bool OpenStdIn(NStreamEncoding&Enc)
322 {
323 return OpenStdIn(Enc.GetCodepage());
324 }
325 };
326
327 class NOStream : public NBaseStream {
328 public:
329 NOStream(FILE *hFile = 0) : NBaseStream(hFile) {}
330
331 bool CreateFileForWriting(const TCHAR* Path, WORD enc = NStreamEncoding::AUTO)
332 {
333 return Attach(my_fopen(Path, "w+b"), enc);
334 }
335 bool CreateFileForWriting(const TCHAR* Path, NStreamEncoding&Enc)
336 {
337 return CreateFileForWriting(Path, Enc.GetCodepage());
338 }
339 bool CreateFileForAppending(const TCHAR* Path, WORD enc = NStreamEncoding::AUTO)
340 {
341 return Attach(my_fopen(Path, "a+b"), enc);
342 }
343 bool CreateFileForAppending(const TCHAR* Path, NStreamEncoding&Enc)
344 {
345 return CreateFileForAppending(Path, Enc.GetCodepage());
346 }
347
348 bool WriteOctets(void*Buffer, size_t cbBuf)
349 {
350 return cbBuf == fwrite(Buffer, 1, cbBuf, m_hFile);
351 }
352 bool WriteBOM(NStreamEncoding&Enc)
353 {
354 static const unsigned char u8b[] = {0xEF,0xBB,0xBF};
355 static const unsigned char u16lb[] = {0xFF,0xFE}, u16bb[] = {0xFE,0xFF};
356 switch(Enc.GetCodepage())
357 {
358 case NStreamEncoding::UTF8: return WriteOctets((void*) u8b, sizeof(u8b));
359 case NStreamEncoding::UTF16LE: return WriteOctets((void*) u16lb, sizeof(u16lb));
360 case NStreamEncoding::UTF16BE: return WriteOctets((void*) u16bb, sizeof(u16bb));
361 }
362 return false;
363 }
364 bool WriteString(const wchar_t*Str, size_t cch = -1);
365 bool WritePlatformNLString(const wchar_t*Str, size_t cch = -1);
366 };
367
368 class NStreamLineReader {
369 protected:
370 NIStream &m_Strm;
371 wchar_t m_PrevNL;
372
373 public:
374 NStreamLineReader(NIStream &Strm) : m_Strm(Strm), m_PrevNL(0) {}
375
376 NIStream& GetStream() { return m_Strm; }
377 NStreamEncoding& StreamEncoding() { return m_Strm.StreamEncoding(); }
378 bool IsEOF() const { return m_Strm.IsEOF(); }
379 bool IsUnicode() const { return m_Strm.IsUnicode(); }
380
381 UINT ReadLine(wchar_t*Buffer, UINT cchBuf);
382 tstring GetErrorMessage(UINT Error, const TCHAR*Filename=0, UINT Line=0);
383
384 protected:
385 bool CompleteLine(wchar_t*&BufWC, UINT cchWC, UINT&cchRemain, bool HandleUnicodeNL)
386 {
387 const wchar_t chW = *BufWC;
388 BufWC += cchWC, cchRemain -= cchWC;
389 if (0 == --cchWC) // We only care about code points that fit in a single wchar_t
390 return NStream::IsNewline(chW, HandleUnicodeNL);
391 return false;
392 }
393 };
394
395 #endif // MAKENSIS
396 #endif // NSIS_UTF_H