Debian Codegraph @

Source/util.cpp

raw
1 /*
2 * util.cpp
3 *
4 * This file is a part of NSIS.
5 *
6 * Copyright (C) 1999-2026 Nullsoft and Contributors
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 #include "Platform.h"
18 #include <stdio.h>
19 #include <stdarg.h>
20 #include <time.h>
21 #include <string.h>
22 #include "tchar.h"
23 #include "exehead/fileform.h"
24 #include "util.h"
25 #include "strlist.h"
26 #include "winchar.h"
27 #include "utf.h"
28 #include "BinInterop.h"
29
30 #ifndef _WIN32
31 # include <ctype.h>
32 # include <unistd.h> // for close(2)
33 # include <fcntl.h> // for open(2)
34 # include <iconv.h>
35 # include <locale.h>
36 # include <stdlib.h>
37 # include <limits.h>
38 # ifdef _UNICODE
39 # include <wchar.h>
40 # endif
41 #endif
42
43 #ifdef __APPLE__
44 namespace Apple { // defines struct section
45 # include <mach-o/dyld.h> // for _NSGetExecutablePath
46 };
47 # define FALSE 0 // bugs #1851365, #2497290
48 # define TRUE 1
49 # include <sys/param.h> // for MAXPATHLEN
50 #endif
51
52 #include <cassert> // for assert
53 #include <algorithm>
54 #include <stdexcept>
55 #include <errno.h>
56
57 using namespace std;
58
59 extern int g_display_errors;
60 extern FILE *g_output, *g_errout;
61
62
63 #ifdef _WIN32
64 static char* CreateMappedFileView(LPCTSTR Path, DWORD FAccess, DWORD FShare, DWORD FMode, DWORD PProtect, DWORD MAccess, size_t &FSize)
65 {
66 char *pView = NULL, restoreGLE = false, validSize;
67 HANDLE hFile = CreateFile(Path, FAccess, FShare, NULL, FMode, 0, NULL);
68 if (hFile == INVALID_HANDLE_VALUE) return pView;
69 ULARGE_INTEGER fs;
70 validSize = GetFileSize64(hFile, fs) && (sizeof(size_t) >= 8 || !fs.HighPart);
71 FSize = sizeof(size_t) >= 8 ? (size_t) fs.QuadPart : fs.LowPart;
72 HANDLE hMap = validSize ? CreateFileMapping(hFile, NULL, PProtect, 0, 0, NULL) : INVALID_HANDLE_VALUE;
73 if (hMap != INVALID_HANDLE_VALUE)
74 {
75 CloseHandle(hFile);
76 if ((pView = (char*) MapViewOfFile(hMap, MAccess, 0, 0, 0)))
77 {
78 CloseHandle(hMap);
79 }
80 else
81 {
82 DWORD error = restoreGLE ? GetLastError() : 0;
83 CloseHandle(hMap);
84 if (restoreGLE) SetLastError(error);
85 }
86 }
87 else
88 {
89 DWORD error = restoreGLE ? GetLastError() : 0;
90 CloseHandle(hFile);
91 if (restoreGLE) SetLastError(error);
92 }
93 return pView;
94 }
95 #else
96 #include <sys/stat.h>
97 #include <sys/mman.h>
98 static char* CreateMappedFileView(const TCHAR *Path, const char *FMode, int PProtect, int MFlags, size_t &FSize)
99 {
100 char *pView = NULL;
101 FILE *pFile = FOPEN(Path, FMode);
102 if (pFile)
103 {
104 struct stat fs;
105 int fd = fileno(pFile), toobig;
106 if (-1 != fd && 0 == fstat(fd, &fs))
107 {
108 FSize = (size_t) fs.st_size, toobig = sizeof(size_t) < sizeof(fs.st_size) && (INT64)FSize != fs.st_size;
109 void *p = !toobig ? mmap(NULL, FSize, PProtect, MFlags, fd, 0) : MAP_FAILED;
110 if (p != MAP_FAILED) pView = (char*) p;
111 }
112 fclose(pFile);
113 }
114 return pView;
115 }
116 #endif //~ _WIN32
117
118
119 double my_wtof(const wchar_t *str)
120 {
121 char buf[100];
122 WideCharToMultiByte(0,0,str,-1,buf,100,0,0);
123 return atof(buf);
124 }
125
126 size_t my_strncpy(TCHAR*Dest, const TCHAR*Src, size_t cchMax)
127 {
128 // Dest and Src must be valid, Dest is always \0 terminated.
129 // Returns number of TCHARs copied to Dest (not counting \0); min(strlen(Src),cchMax-1).
130 size_t cch = 0;
131 if (cchMax) for (TCHAR c; --cchMax;) { if (!(c = Src[cch])) break; Dest[cch++] = c; }
132 Dest[cch] = _T('\0');
133 return cch;
134 }
135
136 size_t my_strftime(TCHAR *s, size_t max, const TCHAR *fmt, const struct tm *tm)
137 {
138 return _tcsftime(s, max, fmt, tm);
139 }
140
141 // Returns 0 if everything is OK
142 // Returns -1 if can't find the file
143 // Returns -2 if the file is an invalid bitmap
144 // Returns -3 if the size doesn't match
145 // Returns -4 if the bpp doesn't match
146 int update_bitmap(CResourceEditor* re, WORD id, const TCHAR* filename, int width/*=0*/, int height/*=0*/, int maxbpp/*=0*/) {
147 FILE *f = FOPEN(filename, ("rb"));
148 if (!f) return -1;
149 signed char hdr[14+124], retval = -2;
150 size_t size = fread(hdr, 1, sizeof(hdr), f);
151 GENERICIMAGEINFO info;
152 if (IsBMPFile(hdr, size, &info) && 0 == fseek(f, 0, SEEK_SET) && LoadImageCanLoadFileFromResource(hdr, size))
153 {
154 if ((width && width != (int) info.Width) || (height && height != (int) info.Height))
155 retval = -3;
156 else if (maxbpp && maxbpp < info.BPP)
157 retval = -4;
158 else if (re->UpdateResource(RT_BITMAP, id, NSIS_DEFAULT_LANG, f, CResourceEditor::TM_AUTO))
159 retval = 0;
160 }
161 fclose(f);
162 return retval;
163 }
164
165 tstring make_friendly_resource_path(const TCHAR*rt, const TCHAR*rn, LANGID rl)
166 {
167 tstring s = _T("");
168 TCHAR buf[42], sep = _T('\\');
169 s += IS_INTRESOURCE(rt) ? (wsprintf(buf, _T("#%d"), (int)(size_t) rt), buf) : rt;
170 s += sep;
171 s += IS_INTRESOURCE(rn) ? (wsprintf(buf, _T("#%d"), (int)(size_t) rn), buf) : rn;
172 s += sep;
173 if (rl == CResourceEditor::ALLLANGID)
174 s += _T("All");
175 else
176 s += (wsprintf(buf, _T("%d"), (int)(size_t) rl), buf);
177 return s;
178 }
179
180 #ifndef _WIN32
181 void PathConvertWinToPosix(char*p);
182
183 BOOL IsDBCSLeadByteEx(unsigned int CodePage, unsigned char TestChar)
184 {
185 if (CP_UTF8 == CodePage) return false; //blogs.msdn.com/b/michkap/archive/2007/04/19/2190207.aspx
186 const char buf[] = {(char)TestChar, 'a', 'b', '\0'}; // Untested and probably not the best way to do this!
187 return CharNextExA(CodePage, buf, 0) > &buf[1];
188 }
189 TCHAR *CharPrev(const TCHAR *s, const TCHAR *p) {
190 if (!s || !p || p < s)
191 return NULL;
192 while (*s) {
193 TCHAR *n = CharNext(s);
194 if (n >= p)
195 break;
196 s = n;
197 }
198 return const_cast<TCHAR*>(s);
199 }
200
201 char *CharNextA(const char *s) {
202 int l = 0, mbl;
203 if (s && *s)
204 mbl = mblen(s, MB_CUR_MAX), l = max(1, mbl);
205 return const_cast<char*>(s + l);
206 }
207
208 wchar_t *CharNextW(const wchar_t *s) {
209 if (sizeof(*s) == 2 && IsLeadSurrogateUTF16(*s)) ++s; //BUGBUG: This assumes that 16bit wchar_t == UTF16
210 // else if (...) BUGBUG: Is this the best we can do? What about combining characters/diacritics etc?
211 return const_cast<wchar_t*>(s + 1);
212 }
213
214 char *CharNextExA(WORD codepage, const char *s, int flags) {
215 // blogs.msdn.com/b/michkap/archive/2007/04/19/2190207.aspx implies that
216 // CharNextExA uses IsDBCSLeadByteEx, should we do the same?
217 const char* orglocct = NSISRT_setlocale_wincp(LC_CTYPE, codepage), *np;
218 int len = mblen(s, strlen(s));
219 if (len > 0) np = s + len; else np = s + 1;
220 setlocale(LC_CTYPE, orglocct);
221 return const_cast<char*>(np);
222 }
223
224 int wsprintf(TCHAR *s, const TCHAR *format, ...) {
225 va_list val;
226 va_start(val, format);
227 int res = _vsntprintf(s, 1024+1, format, val);
228 if (res >= 0) s[res] = _T('\0');
229 va_end(val);
230 return res;
231 }
232
233 static char g_nrt_iconv_narrowlocbuf[50], *g_nrt_iconv_narrowloc = 0;
234 #define setlocale_ACP(cat) setlocale((cat), "")
235 #define iconv_ACP g_nrt_iconv_narrowloc
236 #define setlocale_OEM(cat) NSISRT_setlocale_wincp((cat), 1252)
237 #define iconv_OEM "CP1252"
238
239 #ifdef HAVE_LANGINFO_H // BUGBUG: scons needs to check for HAVE_LANGINFO_H and HAVE_NL_LANGINFO support?
240 #include <langinfo.h>
241 #endif
242 bool NSISRT_Initialize() // Init function for POSIX
243 {
244 iconvdescriptor id;
245 g_nrt_iconv_narrowloc = const_cast<char*>(""); // Use "" and not "char", "char" is a GNU extension?
246 if (!id.Open("wchar_t", g_nrt_iconv_narrowloc))
247 {
248 unsigned int cchmax = COUNTOF(g_nrt_iconv_narrowlocbuf);
249 const char *tmp = "";
250 #ifdef HAVE_NL_LANGINFO
251 tmp = nl_langinfo(CODESET); // TODO: Use libcharset or locale_charset if possible
252 if (strlen(tmp) >= cchmax) tmp = "";
253 #endif
254 strcpy(g_nrt_iconv_narrowloc = g_nrt_iconv_narrowlocbuf, tmp);
255 if (!id.Open("wchar_t", g_nrt_iconv_narrowloc))
256 {
257 // Unable to determine the iconv narrow string code, UTF-8 is the best we can do
258 create_code_page_string(g_nrt_iconv_narrowloc, cchmax, CP_UTF8);
259 }
260 }
261 return nsis_iconv_get_host_endian_ucs4_code() && IsValidCodePage(NSISRT_GetASCIICodepage());
262 }
263
264 const char* NSISRT_setlocale_wincp(int cat, unsigned int cp)
265 {
266 if (cp <= 1) return CP_ACP == cp ? setlocale_ACP(cat) : setlocale_OEM(cat);
267 char buf[40];
268 const char *p, *p1 = 0, *p2 = 0;
269 sprintf(buf, ".CP%u", cp);
270 p = setlocale(cat, &buf[1]); // "CP%u"
271 if (!p) p = setlocale(cat, buf); // ".CP%u" this is the format used by MSVCRT?
272 if (!p)
273 {
274 switch(cp) // This list is probably incomplete
275 {
276 case 932: p1 = "SJIS"; break; // Not an exact match but CP932 already failed, this is the best we can do
277 case 936: p1 = "EUCCN", p2 = "euc-CN"; break;
278 case 949: p1 = "EUCKR", p2 = "euc-KR"; break;
279 case 950: p1 = "Big5"; break;
280 case 20866: p1 = "KOI8-R"; break;
281 case 20932: p1 = "EUCJP", p2 = "euc-JP"; break;
282 case 65001: p1 = "UTF-8", p2 = "utf8"; break;
283 default:
284 if (cp >= 28591 && cp <= 28599) sprintf(buf, "ISO-8859-%u", cp - 28590), p1 = buf;
285 if (cp == 28603 || cp == 28605) sprintf(buf, "ISO-8859-%u", (cp - 28600) + 10), p1 = buf;
286 }
287 if (!(p = setlocale(cat, p1))) p = setlocale(cat, p2);
288 }
289 return p;
290 }
291
292 wchar_t* NSISRT_mbtowc(const char *Str)
293 {
294 const char *orglocct = setlocale(LC_CTYPE, "");
295 wchar_t *d = 0;
296 const char *s = Str;
297 size_t cch = mbsrtowcs(0, &s, 0, 0);
298 if ((size_t)-1 != cch && (d = (wchar_t*) malloc(++cch * sizeof(wchar_t))))
299 {
300 cch = mbsrtowcs(d, &Str, cch, 0);
301 if ((size_t) -1 == cch) { NSISRT_free(d); d = 0; }
302 }
303 if (!errno) errno = ENOMEM;
304 setlocale(LC_CTYPE, orglocct);
305 return d;
306 }
307 char* NSISRT_wctomb(const wchar_t *Str)
308 {
309 const char *orglocct = setlocale(LC_CTYPE, "");
310 char *d = 0;
311 const wchar_t *s = Str;
312 errno = 0;
313 size_t cb = wcsrtombs(0, &s, 0, 0);
314 if ((size_t) -1 != cb && (d = (char*) malloc(++cb)))
315 {
316 cb = wcsrtombs(d, &Str, cb, 0);
317 if ((size_t) -1 == cb) { NSISRT_free(d); d = 0; }
318 }
319 if (!errno) errno = ENOMEM;
320 setlocale(LC_CTYPE, orglocct);
321 return d;
322 }
323 char* NSISRT_wctombpath(const wchar_t *Path)
324 {
325 char *p = NSISRT_wctomb(Path);
326 if (p) PathConvertWinToPosix(p);
327 return p;
328 }
329 char* NSISRT_ttombpath(const TCHAR *Path)
330 {
331 #ifdef _UNICODE
332 return NSISRT_wctombpath(Path);
333 #else
334 char *p = _tcsdup(Path);
335 if (p) PathConvertWinToPosix(p); else errno = ENOMEM;
336 return p;
337 #endif
338 }
339
340 #include <wctype.h>
341 int _wcsnicmp(const wchar_t *a, const wchar_t *b, size_t n)
342 {
343 // Note: Behavior depends on the LC_CTYPE category of the current locale.
344 #if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
345 return wcsncasecmp(a, b, n);
346 #else
347 int diff = 0;
348 for ( ; n--; ++a, ++b )
349 if ((diff = (int) towlower(*a) - (int) towlower(*b)) || !*a) break;
350 return diff;
351 #endif
352 }
353 int _wcsicmp(const wchar_t *a, const wchar_t *b)
354 {
355 return _wcsnicmp(a, b, (size_t)-1);
356 }
357
358 long _wtol(const wchar_t *s) { return wcstol(s, 0, 10); }
359 int _wtoi(const wchar_t *s)
360 {
361 errno = 0;
362 long int r = _wtol(s);
363 if (errno) r = 0;
364 if (LONG_MIN == r) r = INT_MIN;
365 if (LONG_MAX == r) r = INT_MAX;
366 return (int) r;
367 }
368
369 int _swprintf(wchar_t *d, const wchar_t *f, ...)
370 {
371 va_list val;
372 va_start(val, f);
373 int res = _vsnwprintf(d, INT_MAX / sizeof(*d), f, val);
374 va_end(val);
375 return res;
376 }
377
378 wchar_t* _wcsdup(const wchar_t *s)
379 {
380 wchar_t *d = (wchar_t*) malloc((wcslen(s)+1) * sizeof(wchar_t));
381 if (d) wcscpy(d, s);
382 return d;
383 }
384
385 wchar_t* _wgetenv(const wchar_t *wname)
386 {
387 mbstate_t mbs;
388 memset(&mbs,0,sizeof(mbs));
389 char *nval, *nval2, nname[200]; // Hopefully this is enough
390 size_t cbnn = wcsrtombs(nname, &wname, sizeof(nname), &mbs);
391 if ((size_t)-1 == cbnn || !(nval = getenv(nname))) return NULL;
392 static wchar_t *g_wval = 0; // Not thread safe!
393 for ( unsigned int cch = 200;; cch *= 2 )
394 {
395 if (!(g_wval = (wchar_t*) realloc(g_wval, cch * sizeof(wchar_t)))) break;
396 nval2 = nval;
397 memset(&mbs,0,sizeof(mbs));
398 size_t cchwv = mbsrtowcs(g_wval, const_cast<const char**>(&nval2), cch, &mbs);
399 if ((size_t)-1 == cchwv) return NULL;
400 if (!nval2) return g_wval;
401 }
402 errno = ENOMEM;
403 return 0;
404 }
405
406 int _wremove(const wchar_t *Path)
407 {
408 const char *path = NSISRT_wctomb(Path); // Caller should have converted to POSIX path
409 if (!path) return -1;
410 const int retval = remove(path);
411 NSISRT_free(path);
412 return retval;
413 }
414
415 int _wchdir(const wchar_t *Path)
416 {
417 const char *path = NSISRT_wctomb(Path); // Caller should have converted to POSIX path
418 if (!path) return -1;
419 const int retval = chdir(path);
420 NSISRT_free(path);
421 return retval;
422 }
423
424 #include <sys/types.h>
425 #include <sys/stat.h>
426 int _wstat(const wchar_t *Path, struct stat *pS)
427 {
428 const char *path = NSISRT_wctomb(Path); // Caller should have converted to POSIX path
429 if (!path) return -1;
430 const int retval = stat(path, pS);
431 NSISRT_free(path);
432 return retval;
433 }
434
435 #ifdef _UNICODE
436 static int NSISRT_wsystem(const wchar_t *wcmd)
437 {
438 if (!wcmd) return system(NULL);
439 // NOTE: Only the first drive in the path will be converted to posix style (c:\foo d:\bar > /c/foo d:/bar)
440 const char *cmd = NSISRT_wctombpath(wcmd);
441 if (!cmd) return -1;
442 const int retval = system(cmd);
443 NSISRT_free(cmd);
444 return retval;
445 }
446 #endif
447
448 const char* nsis_iconv_get_host_endian_ucs4_code()
449 {
450 static const char* ucs4 = 0;
451 if (!ucs4)
452 {
453 iconvdescriptor id;
454 #define NRT_TMP_IGHEUC(s) if (id.Open("wchar_t", (s))) return ucs4 = (s)
455 NRT_TMP_IGHEUC("UCS-4-INTERNAL");
456 NRT_TMP_IGHEUC(Platform_IsBigEndian() ? "UCS-4BE" : "UCS-4LE");
457 NRT_TMP_IGHEUC(Platform_IsBigEndian() ? "UTF-32BE" : "UTF-32LE");
458 #undef NRT_TMP_IGHEUC
459 }
460 return ucs4;
461 }
462
463 bool nsis_iconv_reallociconv(iconv_t CD, char**In, size_t*cbInLeft, char**Mem, size_t&cbConverted)
464 {
465 char *in, *heap = *Mem;
466 UINT cbMem = 512;
467 size_t inleft, outleft, icvret = (size_t) -1;
468 for(;;)
469 {
470 in = *In, inleft = *cbInLeft, outleft = cbMem - sizeof(UINT32); // Leave room for \0
471 char *p = (char*) realloc(heap, cbMem), *out = p;
472 if (!p) break;
473 heap = p, icvret = nsis_iconv_adaptor(iconv, CD, &in, &inleft, &out, &outleft);
474 if ((size_t) -1 != icvret || E2BIG != errno) break;
475 cbMem *= 4;
476 }
477 *In = in, *Mem = heap;
478 cbConverted = cbMem - (outleft + sizeof(UINT32)), *cbInLeft = inleft;
479 if ((size_t) -1 != icvret)
480 {
481 *((UINT32*)(&heap[cbConverted])) = 0;
482 return true;
483 }
484 return false;
485 }
486
487 const unsigned short CODEPAGESTR_MAXLEN = 50; // Should be plenty
488 void create_code_page_string(TCHAR *buf, size_t len, UINT code_page)
489 {
490 if (!g_nrt_iconv_narrowloc) NSISRT_Initialize(); // For winchar.cpp unit test
491 switch(code_page)
492 {
493 case CP_ACP: _sntprintf(buf, len, _T("%") NPRIns, iconv_ACP); return;
494 case CP_OEMCP: _sntprintf(buf, len, _T("%") NPRIns, iconv_OEM); return;
495 case CP_UTF8: _sntprintf(buf, len, _T("UTF-8")); return;
496 case 1200: // UTF16LE
497 case 1201: // UTF16BE
498 _sntprintf(buf, len, _T("UTF-16%cE"), 1200 == code_page ? 'L' : 'B');
499 return;
500 }
501 _sntprintf(buf, len, _T("CP%d//TRANSLIT"), code_page);
502 }
503 #ifdef _UNICODE
504 void create_code_page_string(char*buf, size_t len, UINT code_page)
505 {
506 TCHAR t[CODEPAGESTR_MAXLEN];
507 create_code_page_string(t, COUNTOF(t), code_page);
508 RawTStrToASCII(t, buf, len);
509 }
510 #endif
511
512 int WideCharToMultiByte(UINT CodePage, DWORD dwFlags, const wchar_t* lpWideCharStr,
513 int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar,
514 LPBOOL lpUsedDefaultChar) {
515 static char buffer[4096]; // BUGBUG: Should this be 4*NSIS_MAX_STRLEN for large string build?
516
517 char cp[CODEPAGESTR_MAXLEN];
518 create_code_page_string(cp, COUNTOF(cp), CodePage);
519 iconv_t cd = iconv_open(cp, "wchar_t");
520 size_t cchNull = 0;
521 if (cd == (iconv_t) -1) return 0;
522 if (cchWideChar < 0) cchWideChar = (int) wcslen(lpWideCharStr), ++cchNull;
523 if (cbMultiByte == 0) cbMultiByte = COUNTOF(buffer) - cchNull, lpMultiByteStr = buffer;
524
525 char *in = (char *) lpWideCharStr, *out = lpMultiByteStr;
526 size_t inbytes = cchWideChar * sizeof(wchar_t), outbytes = cbMultiByte;
527 if (nsis_iconv_adaptor(iconv, cd, &in, &inbytes, &out, &outbytes) == (size_t) -1) {
528 iconv_close(cd);
529 return 0;
530 }
531 iconv_close(cd);
532
533 size_t cConv = (cbMultiByte - outbytes);
534 if (cchNull && cbMultiByte) lpMultiByteStr[cConv] = '\0';
535 return cConv + cchNull;
536 }
537
538 int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr,
539 int cbMultiByte, wchar_t* lpWideCharStr, int cchWideChar) {
540 static wchar_t buffer[4096]; // BUGBUG: Should this be 4*NSIS_MAX_STRLEN for large string build?
541
542 char cp[CODEPAGESTR_MAXLEN];
543 create_code_page_string(cp, COUNTOF(cp), CodePage);
544 iconv_t cd = iconv_open("wchar_t", cp);
545 size_t cchNull = 0; // iconv on MacOS 14 & 15 does not parse the \0, we have to keep track of it.
546 if (cd == (iconv_t) -1) return 0;
547 if (cbMultiByte < 0) cbMultiByte = strlen(lpMultiByteStr), ++cchNull;
548 if (cchWideChar == 0) cchWideChar = COUNTOF(buffer) - cchNull, lpWideCharStr = buffer;
549
550 char *in = (char *) lpMultiByteStr, *out = (char *) lpWideCharStr;
551 size_t inbytes = cbMultiByte, outbytes = cchWideChar * sizeof(wchar_t);
552 if (nsis_iconv_adaptor(iconv, cd, &in, &inbytes, &out, &outbytes) == (size_t) -1) {
553 iconv_close(cd);
554 return 0;
555 }
556 iconv_close(cd);
557
558 size_t cConv = cchWideChar - (outbytes / sizeof (wchar_t));
559 if (cchNull && cchWideChar) lpWideCharStr[cConv] = '\0';
560 return cConv + cchNull;
561 }
562
563 BOOL IsValidCodePage(UINT CodePage)
564 {
565 char cp[CODEPAGESTR_MAXLEN];
566 create_code_page_string(cp, COUNTOF(cp), CodePage);
567 iconv_t cd = iconv_open("wchar_t", cp);
568 if (cd == (iconv_t) -1) return FALSE;
569 iconv_close(cd);
570 return TRUE;
571 }
572
573 #ifdef _UNICODE
574 void PathConvertWinToPosix(char*p)
575 {
576 if ('\"' == *p) ++p; // Skip opening quote if any (For !system)
577 size_t len = strlen(p);
578 /* Replace drive letter X: by /x */
579 if (len >= 2 && ':' == p[1]) p[1] = (char) tolower((int) p[0]), p[0] = '/';
580 do if ('\\' == *p) *p = '/'; while (*(p = CharNextA(p)));
581 }
582 #endif
583 void PathConvertWinToPosix(TCHAR*p)
584 {
585 if (_T('\"') == *p) ++p; // Skip opening quote if any (For !system)
586 size_t len = _tcsclen(p);
587 /* Replace drive letter X: by /x */
588 if (len >= 2 && _T(':') == p[1]) p[1] = (TCHAR) tolower((int) p[0]), p[0] = _T('/');
589 do if (_T('\\') == *p) *p = _T('/'); while (*(p = CharNext(p)));
590 }
591
592 #define MY_ERROR_MSG(x) {if (g_display_errors) {PrintColorFmtMsg_ERR(_T("%") NPRIs, x);}}
593
594 TCHAR *my_convert(const TCHAR *path)
595 {
596 TCHAR *converted_path = _tcsdup(path);
597 if (!converted_path)
598 {
599 MY_ERROR_MSG(_T("Error: could not allocate memory in my_convert()\n"));
600 return 0;
601 }
602 PathConvertWinToPosix(converted_path);
603 return converted_path;
604 }
605
606 void my_convert_free(TCHAR *converted_path)
607 {
608 free(converted_path);
609 }
610
611 int my_open(const TCHAR *pathname, int flags)
612 {
613 #ifndef _UNICODE
614 int result = open(pathname, flags);
615 #else
616 char *nativepath = NSISRT_ttombpath(pathname);
617 if (!nativepath) return -1;
618 int result = open(nativepath, flags);
619 NSISRT_free(nativepath);
620 #endif
621 return result;
622 }
623 #endif //! _WIN32
624
625 FILE* my_fopen(const TCHAR *path, const char *mode)
626 {
627 FILE*f = 0;
628 #ifndef _UNICODE
629 f = fopen(path, mode);
630 #else
631 #ifdef _WIN32
632 TCHAR tmode[20];
633 for (int i=0; ; ++i) if (0 == (tmode[i] = mode[i])) break;
634 f = _wfopen(path, tmode);
635 #else
636 char *nativepath = NSISRT_wctombpath(path);
637 if (nativepath)
638 {
639 f = fopen(nativepath, mode);
640 NSISRT_free(nativepath);
641 }
642 #endif
643 #endif
644 return f;
645 }
646
647 static inline const TCHAR* getptrstrfmt_tstr()
648 {
649 #ifdef _WIN32
650 return sizeof(void*) > 4 ? _T("%I64u") : _T("%u");
651 #else
652 assert(sizeof(void*) <= sizeof(unsigned long long));
653 return sizeof(void*) > sizeof(unsigned long) ? _T("%llu") : _T("%lu");
654 #endif
655 }
656
657 static inline const char* getptrstrfmt_cstr()
658 {
659 #ifdef _WIN32
660 return sizeof(void*) > 4 ? "%I64u" : "%u";
661 #else
662 assert(sizeof(void*) <= sizeof(unsigned long long));
663 return sizeof(void*) > sizeof(unsigned long) ? "%llu" : "%lu";
664 #endif
665 }
666
667 int ptrtostr(const void* Src, TCHAR*Dst)
668 {
669 return wsprintf(Dst, getptrstrfmt_tstr(), Src);
670 }
671
672 void* strtoptr(const TCHAR*Src)
673 {
674 #ifdef _WIN32
675 void*v;
676 return _stscanf(Src, getptrstrfmt_tstr(), &v) == 1 ? v : 0;
677 #else
678 #ifdef _UNICODE
679 char buf[42];
680 size_t cb = wcsrtombs(buf, &Src, sizeof(buf), 0);
681 if (cb >= sizeof(buf)) return 0;
682 #else
683 const char* buf = Src;
684 #endif
685 if (sizeof(void*) > sizeof(unsigned long))
686 {
687 unsigned long long v;
688 return sscanf(buf, getptrstrfmt_cstr(), &v) == 1 ? (void*) v : 0;
689 }
690 else
691 {
692 unsigned long v;
693 return sscanf(buf, getptrstrfmt_cstr(), &v) == 1 ? (void*) v : 0;
694 }
695 #endif
696 }
697
698 #include <sys/types.h>
699 #include <sys/stat.h>
700 #if (defined(_MSC_VER) && (_MSC_VER >= 1200)) || defined(__MINGW32__)
701 #include <io.h>
702 UINT64 get_file_size64(FILE *f)
703 {
704 INT64 s = _filelengthi64(_fileno(f)); // Could also use _get_osfhandle+GetFileSize64
705 return (INT64) -1L != s ? s : invalid_file_size64;
706 }
707 #else
708 UINT64 get_file_size64(FILE *f)
709 {
710 UINT64 result = invalid_file_size64;
711 // 32bit platforms require _FILE_OFFSET_BITS = 64 to correctly return the size
712 #if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200112L || defined(__APPLE__) || defined(__FreeBSD__)
713 struct stat st;
714 if (0 == fstat(fileno(f), &st) && st.st_size <= (sizeof(st.st_size) >= 8 ? (off_t)0x7fffffffffffffffLL : LONG_MAX))
715 result = (UINT64) st.st_size;
716 #else
717 long cb, restoreseek = true;
718 fpos_t orgpos;
719 if (!restoreseek || 0 == fgetpos(f, &orgpos))
720 if (0 == fseek(f, 0, SEEK_END)) // Not fully portable!
721 if ((cb = ftell(f)) != -1L) // This might not be correct for files in text mode!
722 if (!restoreseek || 0 == fsetpos(f, &orgpos))
723 result = cb;
724 #endif
725 return result;
726 }
727 #endif
728
729 UINT32 get_file_size32(FILE *f)
730 {
731 UINT32 result = invalid_file_size32;
732 #if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200112L
733 struct stat st;
734 if (0 == fstat(fileno(f), &st) && st.st_size <= (sizeof(st.st_size) >= 8 ? (off_t)0xffffffffUL : LONG_MAX))
735 result = (UINT32) st.st_size;
736 #else
737 UINT64 size64 = get_file_size64(f);
738 if (size64 <= 0xffffffffUL && invalid_file_size64 != size64)
739 result = (UINT32) size64;
740 #endif
741 return result;
742 }
743
744 UINT64 Platform_GetMaxFileSize()
745 {
746 #ifdef _WIN32
747 return ~(UINT64)0;
748 #elif _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200112L || defined(__APPLE__) || defined(__FreeBSD__)
749 struct stat st;
750 if (sizeof(st.st_size) >= 8)
751 {
752 #ifdef LLONG_MAX
753 return (UINT64)(off_t)LLONG_MAX;
754 #endif
755 const UINT64 sixthree = (~(UINT64)0) >> 1;
756 return (off_t)sixthree > 0 ? sixthree : (UINT32)(off_t)0xffffffffUL;
757 }
758 return (UINT64)(off_t)LONG_MAX;
759 #endif
760 return (UINT)INT_MAX;
761 }
762
763 BYTE* alloc_and_read_file(FILE *f, unsigned long &size)
764 {
765 BYTE *result = 0, *mem = 0;
766 if (!f) return result;
767 UINT32 size32 = get_file_size32(f);
768 mem = (invalid_file_size32 != size32) ? (BYTE*) malloc(size = size32) : 0;
769 if (mem)
770 if (0 == fseek(f, 0, SEEK_SET))
771 if (fread(mem, 1, size, f) == size)
772 result = mem, mem = 0;
773 free(mem);
774 return result;
775 }
776
777 BYTE* alloc_and_read_file(const TCHAR *filepath, unsigned long &size)
778 {
779 BYTE *result = 0;
780 FILE*f = FOPEN(filepath, ("rb"));
781 if (f)
782 {
783 result = alloc_and_read_file(f, size);
784 fclose(f);
785 }
786 return result;
787 }
788
789 void close_file_view(FILEVIEW&mmfv)
790 {
791 #ifdef _WIN32
792 if (mmfv.base) UnmapViewOfFile(mmfv.base);
793 #else
794 if (mmfv.base) munmap(mmfv.base, mmfv.size);
795 #endif
796 }
797 char* create_file_view_readonly(const TCHAR *filepath, FILEVIEW&mmfv)
798 {
799 #ifdef _WIN32
800 return mmfv.base = CreateMappedFileView(filepath, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, PAGE_READONLY, FILE_MAP_READ, mmfv.size);
801 #else
802 return mmfv.base = CreateMappedFileView(filepath, "rb", PROT_READ, MAP_SHARED, mmfv.size);
803 #endif
804 }
805
806 size_t write_octets_to_file(const TCHAR *filename, const void *data, size_t cb)
807 {
808 FILE *hfile = FOPEN(filename, ("wb"));
809 if (!hfile) return 0;
810 size_t ret = fwrite(data, 1, cb, hfile);
811 fclose(hfile);
812 return ret;
813 }
814
815 TCHAR* create_tempfile_path()
816 {
817 TCHAR *tfpath = NULL;
818 #ifdef _WIN32
819 TCHAR buftmpdir[MAX_PATH], buf[MAX_PATH];
820 DWORD cch = GetTempPath(COUNTOF(buftmpdir), buftmpdir);
821 if (cch && cch < COUNTOF(buftmpdir) && GetTempFileName(buftmpdir, _T("nst"), 0, buf))
822 tfpath = _tcsdup(buf);
823 #else //! _WIN32
824 char narrowpath[] = ("/tmp/makensisXXXXXX");
825 const mode_t org_umask = umask(0077);
826 int fd = mkstemp(narrowpath);
827 umask(org_umask);
828 if (fd != -1)
829 {
830 #ifdef _UNICODE
831 assert(NSISRT_free_is_STDC_free());
832 tfpath = NSISRT_mbtowc(narrowpath);
833 #else
834 tfpath = _tcsdup(narrowpath);
835 #endif
836 close(fd);
837 }
838 #endif //~ _WIN32
839 return tfpath;
840 }
841
842 tstring get_full_path(const tstring &path) {
843 #ifdef _WIN32
844 TCHAR real_path[1024], *fnpart;
845 DWORD rc = GetFullPathName(path.c_str(), COUNTOF(real_path), real_path, &fnpart);
846 assert(rc <= 1024); // path size is limited by MAX_PATH (260)
847 assert(rc != 0); // rc==0 in case of error
848 return tstring(real_path);
849 #else // !_WIN32
850 tstring result;
851 char *rpret = 0, *inputpath = NSISRT_ttombpath(path.c_str());
852 if (!inputpath) return tstring(path);
853 #ifdef PATH_MAX
854 static char buffer[PATH_MAX];
855 #else // !PATH_MAX
856 #if _POSIX_C_SOURCE >= 200809L
857 char *buffer = NULL; // realpath can malloc
858 #else
859 int path_max = pathconf(inputpath, _PC_PATH_MAX);
860 if (path_max <= 0) path_max = 4096;
861 char *buffer = (char *) malloc(path_max * sizeof(char));
862 if (buffer)
863 #endif
864 #endif // ~PATH_MAX
865 {
866 rpret = realpath(inputpath, buffer);
867 }
868 result = CtoTString(rpret ? rpret : inputpath);
869 #ifndef PATH_MAX
870 free(rpret ? rpret : buffer);
871 #endif
872 NSISRT_free(inputpath);
873 return result;
874 #endif // ~_WIN32
875 }
876
877 tstring get_string_prefix(const tstring& str, const tstring& separator) {
878 const tstring::size_type last_separator_pos = str.rfind(separator);
879 if (last_separator_pos == string::npos) return str;
880 return str.substr(0, last_separator_pos);
881 }
882
883 tstring get_string_suffix(const tstring& str, const tstring& separator) {
884 const tstring::size_type last_separator_pos = str.rfind(separator);
885 if (last_separator_pos == tstring::npos) return str;
886 return str.substr(last_separator_pos + separator.size(), tstring::npos);
887 }
888
889 tstring get_dir_name(const tstring& path) {
890 return get_string_prefix(path, PLATFORM_PATH_SEPARATOR_STR); // BUGBUG: Windows should support "\" and "/"
891 }
892
893 tstring get_file_name(const tstring& path) {
894 return get_string_suffix(path, PLATFORM_PATH_SEPARATOR_STR); // BUGBUG: Windows should support "\" and "/"
895 }
896
897 tstring get_executable_path(const TCHAR* argv0) {
898 #ifdef _WIN32
899 TCHAR temp_buf[MAX_PATH+1];
900 temp_buf[0] = _T('\0');
901 int rc = GetModuleFileName(NULL,temp_buf,MAX_PATH);
902 assert(rc != 0);
903 return tstring(temp_buf);
904 #elif __APPLE__
905 char temp_buf[MAXPATHLEN+1];
906 unsigned int buf_len = MAXPATHLEN;
907 int rc = Apple::_NSGetExecutablePath(temp_buf, &buf_len);
908 assert(rc == 0);
909 return tstring(CtoTString(temp_buf));
910 #else /* Linux/BSD/POSIX/etc */
911 char *path = NULL, *pathtmp;
912 size_t len = 100;
913 int nchars;
914 while(1){
915 pathtmp = (char*)realloc(path,len+1);
916 if (!pathtmp) {
917 basic:
918 free(path);
919 // Note: Not using _tgetenv(_T("_")) here because it is not always set correctly. !makensis instruction in SVN r7372 will execute "/usr/bin/scons"!
920 return get_full_path(argv0);
921 }
922 path = pathtmp;
923 nchars = readlink("/proc/self/exe", path, len);
924 if (nchars == -1) {
925 goto basic;
926 }
927 if (nchars < (int) len) {
928 path[nchars] = '\0';
929 tstring result;
930 result = CtoTString(path);
931 free(path);
932 return result;
933 }
934 len *= 2;
935 }
936 #endif
937 }
938
939 tstring get_executable_dir(const TCHAR *argv0) {
940 return get_dir_name(get_executable_path(argv0));
941 }
942
943 tstring remove_file_extension(const tstring& path) {
944 return get_string_prefix(path, _T("."));
945 }
946
947 tstring& path_append_separator(tstring& path)
948 {
949 tstring::iterator ib = path.begin(), ie = path.end();
950 if (ib != ie && !IsPathSeparator(*--ie))
951 path += PLATFORM_PATH_SEPARATOR_STR;
952 return path;
953 }
954
955 tstring& path_append(tstring& base, const TCHAR* more)
956 {
957 if (IsPathSeparator(*more)) ++more;
958 return path_append_separator(base) += more;
959 }
960
961 static int PathGetDosDriveNumber(const TCHAR *p)
962 {
963 // Note: Unlike PathGetDriveNumber(), we require a path separator after the colon.
964 if (p[0] && _T(':') == p[1] && IsAgnosticPathSeparator(p[2]))
965 {
966 const TCHAR loch = p[0]|32;
967 if (loch >= _T('a') && loch <= _T('z')) return loch - _T('a');
968 }
969 return -1;
970 }
971 bool IsWindowsPathRelative(const TCHAR *p)
972 {
973 if (_T('\\') == p[0]) return _T('\\') != p[1]; // Current drive relative, not (unverified) UNC
974 return PathGetDosDriveNumber(p) < 0;
975 }
976
977 tstring replace_all(const TCHAR *str, const TCHAR *find, const TCHAR *repl)
978 {
979 tstring out = str;
980 for (size_t cchF = _tcslen(find), cchR = _tcslen(repl), i = 0; ; i += cchR)
981 if ((i = out.find(find, i)) == tstring::npos)
982 return out;
983 else
984 out.replace(i, cchF, repl);
985 }
986
987 struct ToLower
988 {
989 TCHAR operator() (TCHAR c) const { return _totlower(c); }
990 };
991
992 tstring lowercase(const tstring &str) {
993 tstring result = str;
994 transform(str.begin(), str.end(), result.begin(), ToLower());
995 return result;
996 }
997
998 void RawTStrToASCII(const TCHAR*in,char*out,UINT maxcch)
999 {
1000 const bool empty = !maxcch;
1001 for(; maxcch && *in; --maxcch) *out++ = (char) *in++;
1002 if (!empty) *out = 0;
1003 }
1004
1005 /*
1006 * ExpandoStrFmtVaList returns the number of characters written excluding
1007 * the \0 terminator or 0 on error.
1008 * realloc() is used on *ppMalloc if cchStack is not
1009 * large enough to hold the formatted string.
1010 */
1011 size_t ExpandoStrFmtVaList(wchar_t*Stack, size_t cchStack, wchar_t**ppMalloc, const wchar_t*FmtStr, va_list Args)
1012 {
1013 #ifdef _WIN32
1014 static size_t qlen = INT_MAX;
1015 // For _vsnwprintf, the \0 terminator is not part of the input size
1016 # if _MSC_VER < 1310
1017 const bool have__vscwprintf = false;
1018 # define ExpandoStrFmtVaList_vsnwprintf(d,c,f,v) _vsnwprintf((d),(c)?(c)-1:0,(f),(v)) // Allow INT_MAX hack on MinGW and older versions of VC that don't have _vscwprintf
1019 # else
1020 const bool have__vscwprintf = true;
1021 # define ExpandoStrFmtVaList_vsnwprintf(d,c,f,v) ( INT_MAX==(c) ? _vscwprintf((f),(v)) : _vsnwprintf((d),(c)?(c)-1:0,(f),(v)) )
1022 # endif
1023 #else
1024 const size_t qlen = INT_MAX;
1025 # define ExpandoStrFmtVaList_vsnwprintf vswprintf
1026 #endif
1027 #if defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
1028 const bool cansizecalc = true, msvcbackdoor = false;
1029 #else
1030 static char testedsizecalc = 0;
1031 if (!testedsizecalc)
1032 {
1033 #ifdef _WIN32
1034 int cch = have__vscwprintf ? 0 : ExpandoStrFmtVaList_vsnwprintf(0, qlen = 0, L"333", Args);
1035 if (cch != 3) cch = ExpandoStrFmtVaList_vsnwprintf(0, qlen = INT_MAX, L"333", Args); // Is this actually necessary? Just set qlen = INT_MAX if have__vscwprintf?
1036 #else
1037 wchar_t testbuf[1+!0];
1038 int cch = ExpandoStrFmtVaList_vsnwprintf(testbuf, COUNTOF(testbuf), L"333", Args);
1039 #endif
1040 testedsizecalc = (3 == cch) + 1;
1041 }
1042 #ifdef _WIN32
1043 const bool msvcbackdoor = !!(testedsizecalc - 1), cansizecalc = false;
1044 #else
1045 const bool cansizecalc = !!(testedsizecalc - 1), msvcbackdoor = false;
1046 #endif
1047 #endif
1048 size_t &cchAvail = cchStack, cch;
1049 wchar_t *&dest = Stack, *mem = *ppMalloc;
1050 for(;;)
1051 {
1052 cch = ExpandoStrFmtVaList_vsnwprintf(dest, cchAvail, FmtStr, Args);
1053 if ((int)cch < 0)
1054 {
1055 cch = 0;
1056 if (cansizecalc) break; // vswprintf error, abort!
1057 if (msvcbackdoor)
1058 cchAvail = ExpandoStrFmtVaList_vsnwprintf(0, qlen, FmtStr, Args) + 1;
1059 else
1060 cchAvail = 4 * STD_MAX(cchAvail, (size_t)500);
1061 }
1062 else
1063 {
1064 if (cch < cchAvail) break; // We are done.
1065 cchAvail = ++cch; // cch from vswprintf did not include the \0 terminator
1066 }
1067 dest = mem = (wchar_t*) realloc(mem, cchAvail * sizeof(wchar_t));
1068 if (!mem) return 0;
1069 }
1070 *ppMalloc = mem;
1071 return cch;
1072 }
1073
1074 const TCHAR* GetFriendlySize(UINT64 n, unsigned int&fn, GETFRIENDLYSIZEFLAGS f)
1075 {
1076 static const TCHAR* scale[] = {
1077 _T(" bytes"), _T(" KiB"), _T(" MiB"), _T(" GiB"), _T(" TiB")
1078 };
1079 unsigned char s = 0, accurate = f&GFSF_BYTESIFPOSSIBLE;
1080 while(n > ((s || !accurate) ? (1024*1024)-1 : UINT_MAX)) n /= 1024, ++s;
1081 fn = (unsigned int) n;
1082 if (!s) return (f&GFSF_HIDEBYTESCALE) ? _T("") : 1 == fn ? _T(" byte") : scale[s];
1083 return s >= COUNTOF(scale) ? _T(" ?") : scale[s];
1084 }
1085
1086 #ifdef _WIN32
1087 #ifdef _UNICODE
1088 int RunChildProcessRedirected(LPCWSTR cmdprefix, LPCWSTR cmdmain, bool ForceUTF8)
1089 {
1090 // We have to deliver the requested output encoding to our host (if any) and the
1091 // only way to do that is to convert the pipe content from what we hope is UTF-8.
1092 // The reason we need a pipe in the first place is because we cannot trust the
1093 // child to call GetConsoleOutputCP(), and even if we could, UTF-16 is not valid there.
1094 UINT cp = CP_UTF8, mbtwcf = MB_ERR_INVALID_CHARS, oemcp = GetOEMCP();
1095 errno = ENOMEM;
1096 if (!cmdprefix) cmdprefix = L"";
1097 size_t cch1 = _tcslen(cmdprefix), cch2 = _tcslen(cmdmain);
1098 WCHAR *cmd = (WCHAR*) malloc( (cch1 + cch2 + 1) * sizeof(WCHAR) );
1099 if (!cmd) return -1;
1100 _tcscpy(cmd, cmdprefix);
1101 _tcscat(cmd, cmdmain);
1102 SECURITY_DESCRIPTOR sd = { 1, 0, SE_DACL_PRESENT, NULL, };
1103 SECURITY_ATTRIBUTES sa = { sizeof(sa), &sd, TRUE };
1104 const UINT orgwinconcp = GetConsoleCP(), orgwinconoutcp = GetConsoleOutputCP();
1105 if (orgwinconoutcp == oemcp && !ForceUTF8) cp = oemcp, mbtwcf = 0; // Bug #1092: Batch files not a fan of UTF-8
1106 HANDLE hSIRd, hSIWr, hSORd, hSOWr;
1107 PROCESS_INFORMATION pi;
1108 if (!CreatePipe(&hSIRd, &hSIWr, &sa, 0)) // XCopy.exe does not work without a valid StdIn!
1109 hSIRd = hSIWr = INVALID_HANDLE_VALUE;
1110 BOOL ok = CreatePipe(&hSORd, &hSOWr, &sa, 0);
1111 if (!ok)
1112 hSORd = hSOWr = 0;
1113 else
1114 {
1115 STARTUPINFO si = {sizeof(si)};
1116 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1117 si.wShowWindow = SW_HIDE;
1118 si.hStdOutput = si.hStdError = hSOWr;
1119 si.hStdInput = hSIRd;
1120 errno = ECHILD;
1121 SetConsoleOutputCP(cp);
1122 ok = CreateProcess(0, cmd, 0, 0, TRUE, 0, 0, 0, &si, &pi);
1123 CloseHandle(hSOWr); // We want ERROR_BROKEN_PIPE when the child is done
1124 }
1125 free(cmd);
1126 DWORD childec = -1;
1127 if (ok)
1128 {
1129 bool fullbuf = false, utf8 = CP_UTF8 == cp, okt;
1130 char iobuf[512];
1131 DWORD cbRead, cbOfs = 0, cchwb = 0, i;
1132 WCHAR wbuf[100], wchbuf[2+1]; // A surrogate pair + \0
1133 for(;;)
1134 {
1135 BOOL okr = ReadFile(hSORd, iobuf+cbOfs, sizeof(iobuf)-cbOfs, &cbRead, 0);
1136 cbRead += cbOfs, cbOfs = 0;
1137 unsigned char cbTrail, cch;
1138 for(i = 0; i < cbRead;)
1139 {
1140 cch = 0;
1141 if (utf8)
1142 {
1143 okt = UTF8_GetTrailCount(iobuf[i], cbTrail);
1144 if (!okt) // Not UTF-8? Switching to a MBCS CP
1145 {
1146 switchcp: cp = orgwinconoutcp, mbtwcf = 0, utf8 = false;
1147 SetConsoleOutputCP(cp = (CP_UTF8 == cp ? CP_ACP : cp));
1148 continue;
1149 }
1150 if (!cbTrail) cch++, wchbuf[0] = iobuf[i]; // ASCII
1151 }
1152 else
1153 {
1154 cbTrail = !!IsDBCSLeadByteEx(cp, iobuf[i]);
1155 }
1156 if (i+cbTrail >= cbRead) // Read more first?
1157 {
1158 memmove(iobuf, iobuf+i, cbOfs = cbRead - i);
1159 if (okr) break; else i = 0;
1160 }
1161 if (!cch)
1162 {
1163 cch = MultiByteToWideChar(cp, mbtwcf, &iobuf[i], 1+cbTrail, wchbuf, COUNTOF(wchbuf)-1);
1164 if (!cch)
1165 {
1166 if (utf8) goto switchcp;
1167 cch++, wchbuf[0] = UNICODE_REPLACEMENT_CHARACTER;
1168 }
1169 }
1170 i += 1+cbTrail;
1171 if (0xfeff == wchbuf[0] && 1 == cch) cch = 0; // MakeNsisW is not a fan of the BOM, eat it.
1172 if (!cch) continue;
1173 wbuf[cchwb++] = wchbuf[0];
1174 if (--cch) wbuf[cchwb++] = wchbuf[1];
1175 fullbuf = cchwb+cch >= COUNTOF(wbuf)-1; // cch is 1 for surrogate pairs
1176 if (!okr || fullbuf || L'\n' == wchbuf[0]) // Stop on \n so \r\n conversion has enough context (...\r\n vs ...\n)
1177 { finalwrite:
1178 #ifdef MAKENSIS
1179 extern WINSIO_OSDATA g_osdata_stdout;
1180 WinStdIO_OStreamWrite(g_osdata_stdout, wbuf, cchwb); // Faster than _ftprintf
1181 #else
1182 wbuf[cchwb] = L'\0';
1183 _ftprintf(g_output, _T("%") NPRIs, wbuf);
1184 #endif
1185 cchwb = 0;
1186 }
1187 }
1188 if (!okr)
1189 {
1190 if (cchwb) goto finalwrite; // End of stream without a ending newline, write out the remaining data.
1191 break;
1192 }
1193 }
1194 fflush(g_output);
1195 WaitForSingleObject(pi.hProcess, INFINITE);
1196 GetExitCodeProcess(pi.hProcess, &childec);
1197 CloseHandle(pi.hThread);
1198 CloseHandle(pi.hProcess);
1199 }
1200 SetConsoleCP(orgwinconcp), SetConsoleOutputCP(orgwinconoutcp);
1201 CloseHandle(hSIRd), CloseHandle(hSIWr);
1202 CloseHandle(hSORd);
1203 return childec;
1204 }
1205 #else
1206 int RunChildProcessRedirected(LPCSTR cmd, bool ForceUTF8)
1207 {
1208 STARTUPINFO si = { sizeof(STARTUPINFO), };
1209 PROCESS_INFORMATION pi;
1210 if (!CreateProcess(NULL, const_cast<LPSTR>(cmd), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
1211 return GetLastError();
1212 WaitForSingleObject(pi.hProcess, INFINITE);
1213 GetExitCodeProcess(pi.hProcess, &si.cb);
1214 CloseHandle(pi.hThread), CloseHandle(pi.hProcess);
1215 return (int) si.cb;
1216 }
1217 #endif //~ _UNICODE
1218 #endif //~ _WIN32
1219
1220 int sane_system(const TCHAR *command)
1221 {
1222 #ifdef _WIN32
1223
1224 // workaround for bug #1509909
1225 // http://sf.net/tracker/?func=detail&atid=373085&aid=1509909&group_id=22049
1226 //
1227 // cmd.exe /C has some weird handling for quotes. it strips
1228 // the surrounding quotes, if they exist. if there are quotes
1229 // around the program path and its arguments, it will strip
1230 // the outer quotes. this may result in something like:
1231 // `program files\nsis\makensis.exe" "args`
1232 // which obviously fails...
1233 //
1234 // to avoid the stripping, a harmless string is prefixed to the command line.
1235 const TCHAR*const prefix = _T("IF 1==1 ");
1236 #ifdef _UNICODE
1237 if (!command) return 0; else if (!*command) return 1;
1238 tstring fixedcmd = _tgetenv(_T("COMSPEC"));
1239 if (!fixedcmd.length()) fixedcmd = _T("CMD.EXE");
1240 fixedcmd += _T(" /C "), fixedcmd += prefix;
1241 return RunChildProcessRedirected(fixedcmd.c_str(), command);
1242 #else
1243 tstring fixedcmd = prefix;
1244 fixedcmd += _T(""), fixedcmd += command;
1245 return _tsystem(fixedcmd.c_str());
1246 #endif // ~_UNICODE
1247 #else // !_WIN32
1248 #ifndef _UNICODE
1249 TCHAR* cmd = const_cast<TCHAR*>(command);
1250 PATH_CONVERT(cmd);
1251 return _tsystem(cmd);
1252 #else
1253 return NSISRT_wsystem(command);
1254 #endif
1255 #endif // ~_WIN32
1256 }
1257
1258 #ifdef _WIN32
1259 bool GetFileSize64(HANDLE hFile, ULARGE_INTEGER &uli)
1260 {
1261 uli.LowPart = GetFileSize(hFile, &uli.HighPart);
1262 return INVALID_FILE_SIZE != uli.LowPart || !GetLastError();
1263 }
1264 #endif //~ _WIN32
1265 #if defined(_WIN32) && defined(_UNICODE) && defined(MAKENSIS)
1266 #include <io.h> // for _get_osfhandle
1267 bool WINAPI WinStdIO_OStreamInit(WINSIO_OSDATA&osd, FILE*strm, WORD cp, int bom)
1268 {
1269 // bom < 0: override cp if UTF detected but never write BOM
1270 // bom = 0: ignore BOM and force cp
1271 // bom > 0: override cp if UTF detected, write BOM if it does not already exist
1272 const int fd = _fileno(strm);
1273 osd.mode = 0, osd.hCRT = strm, osd.hNative = (HANDLE) _get_osfhandle(fd);
1274 if (INVALID_HANDLE_VALUE == osd.hNative) return false;
1275 DWORD conmode;
1276 if (GetConsoleMode(osd.hNative, &conmode)) osd.mode++; else osd.mode--;
1277 bool succ = NStream::SetBinaryMode(fd);
1278 DWORD cbio = 0;
1279 ULARGE_INTEGER uli;
1280 if (succ && 0 != bom && GetFileSize64(osd.hNative, uli) && uli.QuadPart)
1281 {
1282 OVERLAPPED olap = {0}; // Used to read from start of file
1283 unsigned char bufbom[4];
1284 if (ReadFile(osd.hNative, bufbom, sizeof(bufbom), &cbio, &olap))
1285 {
1286 UINT detbom = DetectUTFBOM(bufbom, cbio);
1287 if (detbom) cp = (WORD) detbom, bom = 0;
1288 }
1289 SetFilePointer(osd.hNative, 0, 0, FILE_END);
1290 }
1291 osd.mustwritebom = bom > 0 && !cbio, osd.cp = cp;
1292 return succ || (sizeof(TCHAR) > 1 && WinStdIO_IsConsole(osd)); // Don't care about BOM for WriteConsoleW
1293 }
1294 bool WINAPI WinStdIO_OStreamWrite(WINSIO_OSDATA&osd, const wchar_t *Str, UINT cch)
1295 {
1296 if ((UINT)-1 == cch) cch = (UINT)_tcslen(Str);
1297 DWORD cbio;
1298 if (WinStdIO_IsConsole(osd))
1299 return WriteConsoleW(osd.hNative, Str, cch, &cbio, 0) || !cch;
1300 NOStream strm(osd.hCRT);
1301 NStreamEncoding &enc = strm.StreamEncoding();
1302 enc.SetCodepage(osd.cp);
1303 bool retval = false;
1304 if (osd.mustwritebom)
1305 {
1306 osd.mustwritebom = false;
1307 if (enc.IsUnicode() && !strm.WriteBOM(enc))
1308 {
1309 osd.mode = 1, osd.hNative = 0; // Something is wrong, stop writing!
1310 goto end;
1311 }
1312 }
1313 retval = strm.WritePlatformNLString(Str, cch);
1314 end:
1315 strm.Detach();
1316 return retval;
1317 }
1318 static WINSIO_OSDATA*WinStdIO_GetNativeStreamData(FILE*strm)
1319 {
1320 extern WINSIO_OSDATA g_osdata_stdout, g_osdata_stderr;
1321 if (g_output == strm) return &g_osdata_stdout;
1322 return g_errout == strm ? &g_osdata_stderr : NULL;
1323 }
1324 int WINAPI WinStdIO_vfwprintf(FILE*strm, const wchar_t*Fmt, va_list val)
1325 {
1326 WINSIO_OSDATA*pOSD;
1327 if (Fmt && (pOSD = WinStdIO_GetNativeStreamData(strm)))
1328 {
1329 ExpandoString<wchar_t, NSIS_MAX_STRLEN> buf;
1330 errno = ENOMEM;
1331 const size_t cchfmt = buf.StrVFmt(Fmt, val, false);
1332 UINT cch = (UINT) cchfmt;
1333 assert(sizeof(size_t) <= 4 || cchfmt == cch);
1334 if (cch && !WinStdIO_OStreamWrite(*pOSD, buf, cch))
1335 {
1336 cch = 0, errno = EIO;
1337 }
1338 return cch ? cch : (*Fmt ? -1 : 0);
1339 }
1340 return vfwprintf(strm, Fmt, val);
1341 }
1342 int WinStdIO_fwprintf(FILE*strm, const wchar_t*Fmt, ...)
1343 {
1344 va_list val;
1345 va_start(val, Fmt);
1346 int rv = _vftprintf(strm, Fmt, val);
1347 va_end(val);
1348 return rv;
1349 }
1350 int WinStdIO_wprintf(const wchar_t*Fmt, ...)
1351 {
1352 va_list val;
1353 va_start(val, Fmt);
1354 int rv = _vftprintf(g_output, Fmt, val);
1355 va_end(val);
1356 return rv;
1357 }
1358 static HANDLE NSISRT_FastGetConsoleScreenHandle()
1359 {
1360 extern WINSIO_OSDATA g_osdata_stdout, g_osdata_stderr;
1361 return WinStdIO_IsConsole(g_osdata_stdout) ? g_osdata_stdout.hNative : g_osdata_stderr.hNative;
1362 }
1363 bool NSISRT_Initialize() // Init function for MakeNSIS Win32
1364 {
1365 static bool inited = false;
1366 if (inited) return inited;
1367 extern WINSIO_OSDATA g_osdata_stdout, g_osdata_stderr;
1368 g_osdata_stderr.mode = g_osdata_stdout.mode = 0, g_osdata_stderr.hNative = g_osdata_stdout.hNative = 0;
1369 return (inited = true);
1370 }
1371 #elif defined(_WIN32)
1372 #define NSISRT_FastGetConsoleScreenHandle NSISRT_GetConsoleScreenHandle
1373 bool NSISRT_Initialize() { return true; } // Init function for non-MakeNSIS Win32 (NSISRT_DEFINEGLOBALS sets g_output and g_errout)
1374 static HANDLE NSISRT_GetConsoleScreenHandle()
1375 {
1376 DWORD cm;
1377 HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
1378 return GetConsoleMode(hCon, &cm) ? hCon : GetStdHandle(STD_ERROR_HANDLE);
1379 }
1380 #endif
1381
1382 void PrintColorFmtErrMsg(const TCHAR *fmtstr, va_list args)
1383 {
1384 PrintColorFmtMsg_WARN(_T("")); // flush g_output
1385 SetPrintColorERR();
1386 _vftprintf(g_errout, fmtstr, args), fflush(g_errout);
1387 ResetPrintColor();
1388 }
1389
1390 void PrintColorFmtMsg(unsigned int type, const TCHAR *fmtstr, va_list args)
1391 {
1392 #ifdef _WIN32
1393 HANDLE hWin32Con = NSISRT_FastGetConsoleScreenHandle();
1394 static INT32 contxtattrbak = -1;
1395 WORD txtattr = 0;
1396 if (contxtattrbak < 0)
1397 {
1398 if (-1 == contxtattrbak)
1399 {
1400 CONSOLE_SCREEN_BUFFER_INFO csbi;
1401 contxtattrbak = -2;
1402 if (GetConsoleScreenBufferInfo(hWin32Con, &csbi))
1403 {
1404 contxtattrbak = csbi.wAttributes;
1405 goto gottxtattrbak;
1406 }
1407 }
1408 }
1409 else
1410 {
1411 gottxtattrbak:
1412 switch(type & 0xF)
1413 {
1414 case 0: goto resettxtattr;
1415 case 1: txtattr = FOREGROUND_INTENSITY|FOREGROUND_GREEN|FOREGROUND_RED; break;
1416 case 2: txtattr = FOREGROUND_INTENSITY|FOREGROUND_RED; break;
1417 }
1418 // Use original background color if our text will still be readable
1419 if ((contxtattrbak & 0xF0) != (txtattr<<4)) txtattr |= (contxtattrbak & 0xF0);
1420 if ((txtattr & 0xFF) == 0xFE) txtattr &= ~FOREGROUND_INTENSITY; // BrightYellow on BrightWhite is hard to read
1421 SetConsoleTextAttribute(hWin32Con, txtattr);
1422 }
1423 #endif
1424
1425 if (fmtstr) _vftprintf(g_output, fmtstr, args);
1426 fflush(g_output);
1427
1428 #ifdef _WIN32
1429 if (contxtattrbak >= 0 && !(0x10 & type))
1430 {
1431 resettxtattr:
1432 SetConsoleTextAttribute(hWin32Con, contxtattrbak);
1433 }
1434 #endif
1435 }
1436
1437 void FlushOutputAndResetPrintColor()
1438 {
1439 fflush(g_output);
1440 #ifdef _WIN32
1441 PrintColorFmtMsg(0, NULL, (va_list)NULL); //va_list is just a pointer on windows so this is ok
1442 #endif
1443 }
1444
1445 unsigned char Platform_SupportsUTF8Conversion()
1446 {
1447 static unsigned char cached = 0;
1448 if (0 == cached) cached = 1 + !!IsValidCodePage(CP_UTF8);
1449 return (cached - 1);
1450 }
1451
1452 void *operator new(size_t size) NSIS_CXX_THROWSPEC(bad_alloc)
1453 {
1454 void *p = malloc(size);
1455 if (!p) throw bad_alloc();
1456 return p;
1457 }
1458 void *operator new[](size_t size) NSIS_CXX_THROWSPEC(bad_alloc)
1459 {
1460 return operator new(size);
1461 }
1462 void operator delete(void *p) NSIS_CXX_NOEXCEPT() { if (p) free(p); }
1463 void operator delete [](void *p) NSIS_CXX_NOEXCEPT() { if (p) free(p); }