Debian Codegraph @

Source/util.h

raw
1 /*
2 * util.h
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 * Unicode support by Jim Park -- 08/10/2007
17 */
18
19 #ifndef _UTIL_H_
20 #define _UTIL_H_
21
22 #include "tstring.h" // for std::string
23
24 #include "boost/scoped_ptr.hpp" // for boost::scoped_ptr
25 #include "ResourceEditor.h"
26
27 #ifndef _WIN32
28 # include <iconv.h>
29 # include <stdio.h>
30 # include <unistd.h>
31 #endif
32 #include <stdarg.h>
33 #include <stdio.h>
34
35 static inline bool ui_add(unsigned int &r, unsigned int a, unsigned int b) { return (r = a + b) >= a; }
36 static inline bool si_add(int &r, int a, int b)
37 {
38 unsigned int na = a < 0, aa = na ? a * -1 : a, nb = b < 0, ab = nb ? b * -1 : b, t = aa + ab, uz = 0;
39 return na == nb && (t > INT_MAX || (~uz / 2 > INT_MAX && t < aa)) ? false : (r = a + b, true); // Good enough for our use
40 }
41
42 extern double my_wtof(const wchar_t *str);
43 extern size_t my_strncpy(TCHAR*Dest, const TCHAR*Src, size_t cchMax);
44 template<class T> bool strtrycpy(T*Dest, const T*Src, size_t cchCap) { size_t c = my_strncpy(Dest, Src, cchCap); return c < cchCap && !Src[c]; }
45 size_t my_strftime(TCHAR *s, size_t max, const TCHAR *fmt, const struct tm *tm);
46 template<class T> bool ChIsHex(T c) { return (c >= '0' && c <= '9') || ((c|32) >= 'a' && (c|32) <= 'f'); }
47
48 // Adds the bitmap in filename using resource editor re as id id.
49 // If width or height are specified it will also make sure the bitmap is in that size
50 int update_bitmap(CResourceEditor* re, WORD id, const TCHAR* filename, int width=0, int height=0, int maxbpp=0);
51 tstring make_friendly_resource_path(const TCHAR*rt, const TCHAR*rn, LANGID rl);
52
53 TCHAR* create_tempfile_path();
54 tstring get_full_path(const tstring& path);
55 tstring get_dir_name(const tstring& path);
56 tstring get_file_name(const tstring& path);
57 tstring get_executable_path(const TCHAR* argv0);
58 tstring get_executable_dir(const TCHAR *argv0);
59 tstring remove_file_extension(const tstring& path);
60 tstring& path_append_separator(tstring& path);
61 tstring& path_append(tstring& base, const TCHAR* more);
62 inline tstring& path_append(tstring& base, const tstring& more) { return path_append(base, more.c_str()); }
63 #ifdef _WIN32
64 #define IsPathSeparator IsAgnosticPathSeparator
65 #else
66 #define IsPathSeparator(c) ( PLATFORM_PATH_SEPARATOR_C == (c) )
67 #endif
68 inline bool IsAgnosticPathSeparator(const TCHAR c) { return _T('\\') == c || _T('/') == c; }
69 bool IsWindowsPathRelative(const TCHAR *p);
70
71 tstring replace_all(const TCHAR*str, const TCHAR*find, const TCHAR* replace);
72 tstring lowercase(const tstring&);
73 tstring get_string_prefix(const tstring& str, const tstring& separator);
74 tstring get_string_suffix(const tstring& str, const tstring& separator);
75 void RawTStrToASCII(const TCHAR*in,char*out,UINT maxcch);
76 size_t ExpandoStrFmtVaList(wchar_t*Stack, size_t cchStack, wchar_t**ppMalloc, const wchar_t*FmtStr, va_list Args);
77
78 template<typename T, size_t S> class ExpandoString {
79 T m_stack[S ? S : 1], *m_heap;
80 public:
81 ExpandoString() : m_heap(0) {}
82 ~ExpandoString() { free(m_heap); }
83 void Reserve(size_t cch)
84 {
85 if (S && cch <= S) return ;
86 void *p = realloc(m_heap, cch * sizeof(T));
87 if (!p) throw std::bad_alloc();
88 m_heap = (T*) p;
89 }
90 size_t StrFmt(const T*f, ...) { va_list v; va_start(v, f); size_t r = StrVFmt(f, v); va_end(v); return r; }
91 size_t StrVFmt(const T*FmtStr, va_list Args, bool throwonerr = true)
92 {
93 size_t n = ExpandoStrFmtVaList(m_stack, COUNTOF(m_stack), &m_heap, FmtStr, Args);
94 if (throwonerr && !n && *FmtStr) throw std::bad_alloc();
95 return n;
96 }
97 T* GetPtr() { return m_heap ? m_heap : m_stack; }
98 operator T*() { return GetPtr(); }
99 };
100
101 typedef enum {
102 GFSF_BYTESIFPOSSIBLE = 0x1,
103 GFSF_HIDEBYTESCALE = 0x2,
104 GFSF_DEFAULT = 0
105 } GETFRIENDLYSIZEFLAGS;
106 const TCHAR* GetFriendlySize(UINT64 n, unsigned int&fn, GETFRIENDLYSIZEFLAGS f = GFSF_DEFAULT);
107 class FriendlySize {
108 const TCHAR* m_s;
109 unsigned int m_n;
110 public:
111 FriendlySize(UINT64 n, size_t f = GFSF_DEFAULT) { Calculate(n, f); }
112 void Calculate(UINT64 n, size_t f) { m_s = GetFriendlySize(n, m_n, (GETFRIENDLYSIZEFLAGS)f); }
113 unsigned int UInt() const { return m_n; }
114 const TCHAR* Scale() const { return m_s; }
115 };
116
117 int sane_system(const TCHAR *command);
118
119 template<class S> static size_t freadall(void*b, size_t cb, S*s) { return cb == fread(b, 1, cb, s) ? cb : 0; }
120 template<class T, class S> static inline size_t freadpod(T&b, S*s) { return freadall(b, sizeof(T), s); }
121
122 struct CStdFileStreamOnMemory
123 {
124 typedef CStdFileStreamOnMemory S_t;
125 BYTE*m_Base;
126 size_t m_cb, m_pos;
127 template<class T> CStdFileStreamOnMemory(T*p, size_t cb) : m_Base((BYTE*)p), m_cb(cb), m_pos(0) {}
128 template<class V> static inline bool assignfp(fpos_t*p, V v)
129 {
130 if (sizeof(p) >= sizeof(v)) return (*(V*)p = v, true);
131 UINT t = (UINT) v;
132 return t == v && sizeof(p) >= sizeof(t) && assignfp(p, t);
133 }
134 template<class V> static inline void readfp(V&v, const fpos_t*p) { v = sizeof(p) >= sizeof(v) ? *(V*)p : *(UINT*)p; }
135 friend inline size_t fclose(S_t*s) { return 0; }
136 friend int fgetpos(S_t*s, fpos_t*pos) { return assignfp(pos, s->m_pos) ? 0 : 1; }
137 friend int fsetpos(S_t*s, const fpos_t*pos) { size_t v; readfp(v, pos); return v < s->m_cb ? (s->m_pos = v, 0) : 1; }
138 friend int fseek(S_t*s, long int offset, int origin)
139 {
140 if ((unsigned long) offset != (size_t) offset) return 1; // long int will usually fit in our size_t
141 size_t newpos, invalid = 0;
142 switch(origin)
143 {
144 case SEEK_SET: newpos = (size_t) offset, invalid = offset < 0; break;
145 case SEEK_CUR: newpos = s->m_pos + offset; break;
146 case SEEK_END: newpos = s->m_cb + offset; break;
147 default: newpos = ++invalid; // Assigning to newpos to avoid warning on Mac
148 }
149 if (!(invalid += s->m_cb <= newpos)) s->m_pos = newpos;
150 return (int) invalid;
151 }
152 friend size_t fread(void*b, size_t e, size_t c, S_t*s)
153 {
154 size_t cb = e * c, endpos = s->m_pos + cb;
155 if (endpos < s->m_pos || cb < c) return 0; // EOF/Overflow
156 if (s->m_cb < endpos) cb = s->m_cb - s->m_pos; // EOF
157 memcpy(b, s->m_Base + s->m_pos, cb);
158 return (s->m_pos += cb, cb);
159 }
160 };
161
162 #define NSISRT_DEFINEGLOBALS() int g_display_errors=1; FILE *g_output=stdout, *g_errout=stderr
163 void PrintColorFmtErrMsg(const TCHAR *fmtstr, va_list args);
164 void PrintColorFmtMsg(unsigned int type, const TCHAR *fmtstr, va_list args);
165 void FlushOutputAndResetPrintColor();
166 #ifdef _WIN32
167 #ifdef _UNICODE
168 int RunChildProcessRedirected(LPCWSTR cmdprefix, LPCWSTR cmdmain, bool ForceUTF8 = false);
169 inline int RunChildProcessRedirected(LPCWSTR cmd, bool ForceUTF8 = false) { return RunChildProcessRedirected(0, cmd, ForceUTF8); }
170 #ifdef MAKENSIS
171 typedef struct {
172 HANDLE hNative;
173 FILE*hCRT;
174 WORD cp;
175 signed char mode; // -1 = redirected, 0 = unknown, 1 = console
176 bool mustwritebom;
177 } WINSIO_OSDATA;
178 inline bool WinStdIO_IsConsole(WINSIO_OSDATA&osd) { return osd.mode > 0; }
179 inline bool WinStdIO_IsRedirected(WINSIO_OSDATA&osd) { return osd.mode < 0; }
180 bool WINAPI WinStdIO_OStreamInit(WINSIO_OSDATA&osd, FILE*strm, WORD cp, int bom = 1);
181 bool WINAPI WinStdIO_OStreamWrite(WINSIO_OSDATA&osd, const wchar_t *Str, UINT cch = -1);
182 int WINAPI WinStdIO_vfwprintf(FILE*strm, const wchar_t*Fmt, va_list val);
183 int WinStdIO_fwprintf(FILE*strm, const wchar_t*Fmt, ...);
184 int WinStdIO_wprintf(const wchar_t*Fmt, ...);
185 #ifndef _MSC_VER // our tchar.h already defined everything...
186 #include <tchar.h> // Make sure we include the CRTs tchar.h in case it is pulled in by something else later.
187 #endif
188 // We don't hook fflush since the native handle is only used with WriteConsoleW
189 #undef _vsntprintf
190 #define _vsntprintf Error: TODO
191 #undef _tprintf
192 #define _tprintf WinStdIO_wprintf
193 #undef _ftprintf
194 #define _ftprintf WinStdIO_fwprintf
195 #undef _vftprintf
196 #define _vftprintf WinStdIO_vfwprintf
197 #endif // ~MAKENSIS
198 #else
199 int RunChildProcessRedirected(LPCSTR cmd, bool ForceUTF8 = false);
200 #endif // ~_UNICODE
201 #define ResetPrintColor() FlushOutputAndResetPrintColor() // For reset ONLY, use PrintColorFmtMsg(0,NULL ...
202 #define SetPrintColorWARN() PrintColorFmtMsg(1|0x10, NULL, (va_list)NULL)
203 #define SetPrintColorERR() PrintColorFmtMsg(2|0x10, NULL, (va_list)NULL)
204 #else
205 #define ResetPrintColor()
206 #define SetPrintColorWARN()
207 #define SetPrintColorERR()
208 #endif // ~_WIN32
209 inline void PrintColorFmtMsg_WARN(const TCHAR *fmtstr, ...)
210 {
211 va_list val;
212 va_start(val,fmtstr);
213 PrintColorFmtMsg(1, fmtstr, val);
214 va_end(val);
215 }
216 inline void PrintColorFmtMsg_ERR(const TCHAR *fmtstr, ...)
217 {
218 va_list val;
219 va_start(val,fmtstr);
220 PrintColorFmtErrMsg(fmtstr, val);
221 va_end(val);
222 }
223
224
225 bool NSISRT_Initialize();
226 #define NSISRT_GetASCIICodepage() ( 1252 )
227 #ifndef _WIN32
228 // iconv const inconsistency workaround by Alexandre Oliva
229 template <typename T>
230 inline size_t nsis_iconv_adaptor
231 (size_t (*iconv_func)(iconv_t, T, size_t *, char**,size_t*),
232 iconv_t cd, char **inbuf, size_t *inbytesleft,
233 char **outbuf, size_t *outbytesleft)
234 {
235 return iconv_func (cd, (T)inbuf, inbytesleft, outbuf, outbytesleft);
236 }
237
238 const char* nsis_iconv_get_host_endian_ucs4_code();
239 bool nsis_iconv_reallociconv(iconv_t CD, char**In, size_t*cbInLeft, char**Mem, size_t&cbConverted);
240 void create_code_page_string(char*buf, size_t len, UINT code_page); // Create iconv code from Windows codepage
241
242 class iconvdescriptor {
243 iconv_t m_cd;
244 public:
245 iconvdescriptor(iconv_t cd = (iconv_t)-1) : m_cd(cd) {}
246 ~iconvdescriptor() { Close(); }
247 void Close()
248 {
249 if ((iconv_t)-1 != m_cd)
250 {
251 iconv_close(m_cd);
252 m_cd = (iconv_t)-1;
253 }
254 }
255 bool Open(const char*tocode, const char*fromcode)
256 {
257 m_cd = iconv_open(tocode, fromcode);
258 return (iconv_t)-1 != m_cd;
259 }
260 UINT Convert(void*inbuf, size_t*pInLeft, void*outbuf, size_t outLeft)
261 {
262 char *in = (char*) inbuf, *out = (char*) outbuf;
263 size_t orgOutLeft = outLeft;
264 size_t ret = nsis_iconv_adaptor(iconv, *this, &in, pInLeft, &out, &outLeft);
265 if ((size_t)(-1) == ret)
266 ret = 0, *pInLeft = 1;
267 else
268 ret = orgOutLeft - outLeft;
269 return ret;
270 }
271 iconv_t GetDescriptor() const { return m_cd; }
272 operator iconv_t() const { return m_cd; }
273
274 static const char* GetHostEndianUCS4Code() { return nsis_iconv_get_host_endian_ucs4_code(); }
275 };
276
277 BOOL IsDBCSLeadByteEx(unsigned int CodePage, unsigned char TestChar);
278 TCHAR *CharPrev(const TCHAR *s, const TCHAR *p);
279 char *CharNextA(const char *s);
280 wchar_t *CharNextW(const wchar_t *s);
281 char *CharNextExA(WORD codepage, const char *s, int flags);
282 int wsprintf(TCHAR *s, const TCHAR *format, ...);
283 int WideCharToMultiByte(UINT CodePage, DWORD dwFlags, const wchar_t* lpWideCharStr,
284 int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar,
285 LPBOOL lpUsedDefaultChar);
286 int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr,
287 int cbMultiByte, wchar_t* lpWideCharStr, int cchWideChar);
288 BOOL IsValidCodePage(UINT CodePage);
289 #ifdef _UNICODE
290 #define CharNext CharNextW
291 #else
292 #define CharNext CharNextA
293 #endif
294 #define NSISRT_free_is_STDC_free() 1 // NSISRT_free == free
295 #define NSISRT_free(p) ( free((void*)(p)) )
296 wchar_t* NSISRT_mbtowc(const char *Str);
297 char* NSISRT_wctomb(const wchar_t *Str);
298 char* NSISRT_wctombpath(const wchar_t *Path);
299 char* NSISRT_ttombpath(const TCHAR *Path);
300 const char* NSISRT_setlocale_wincp(int cat, unsigned int cp);
301 int _wcsicmp(const wchar_t *a, const wchar_t *b);
302 int _wcsnicmp(const wchar_t *a, const wchar_t *b, size_t n);
303 long _wtol(const wchar_t *s);
304 int _wtoi(const wchar_t *s);
305 int _swprintf(wchar_t *d, const wchar_t *f, ...);
306 wchar_t* _wcsdup(const wchar_t *s);
307 wchar_t* _wgetenv(const wchar_t *wname);
308 int _wremove(const wchar_t *Path);
309 #define _wunlink _wremove // BUGBUG: This is not 100% correct, _wremove can also call rmdir
310 int _wchdir(const wchar_t *Path);
311 int _wstat(const wchar_t *Path, struct stat *pS);
312
313 TCHAR *my_convert(const TCHAR *path);
314 void my_convert_free(TCHAR *converted_path);
315
316 int my_open(const TCHAR *pathname, int flags);
317 #define OPEN(a, b) my_open(a, b)
318
319 #else // _WIN32
320 bool GetFileSize64(HANDLE hFile, ULARGE_INTEGER &uli);
321
322 #define my_convert(x) (x)
323 #define my_convert_free(x)
324
325 #define OPEN(a, b) _topen(a, b)
326
327 #endif //~ _WIN32
328
329 FILE* my_fopen(const TCHAR *path, const char *mode);
330 #define FOPEN(a, b) my_fopen((a), (b))
331
332 int ptrtostr(const void* Src, TCHAR*Dst);
333 void* strtoptr(const TCHAR*Src);
334 template<class T> T strtoptr(const TCHAR*Src, T&Dst) { return Dst = (T) strtoptr(Src); }
335
336 UINT64 Platform_GetMaxFileSize();
337 const UINT32 invalid_file_size32 = ~ (UINT32) 0;
338 UINT32 get_file_size32(FILE *f);
339 const UINT64 invalid_file_size64 = ~ (UINT64) 0;
340 UINT64 get_file_size64(FILE *f);
341 BYTE* alloc_and_read_file(FILE *f, unsigned long &size);
342 BYTE* alloc_and_read_file(const TCHAR *filepath, unsigned long &size);
343
344 typedef struct { char*base; size_t size; } FILEVIEW;
345 void close_file_view(FILEVIEW&mmfv);
346 char* create_file_view_readonly(const TCHAR *filepath, FILEVIEW&mmfv);
347
348 size_t write_octets_to_file(const TCHAR *filename, const void *data, size_t cb);
349
350 // round a value up to be a multiple of 512
351 // assumption: T is an int type
352 template <class T> inline T align_to_512(const T x) { return (x+511) & ~511; }
353
354 template<class T> inline T read_ptr_as(const void*p)
355 {
356 #if defined(_MSC_VER) && (_MSC_VER-0 < 1400) // TODO: Figure out which versions are able to optimize the memcpy
357 return *(T*)(p);
358 #else
359 T t; memcpy(&t, p, sizeof(T)); return t;
360 #endif
361 }
362
363 // some values need to be truncated from size_t to [unsigned] int, using this function is better than a plain cast
364 template<class R, class T> inline R internaltruncate_cast(T t) {
365 assert((~((T)0)) > T(0)); // Only unsigned types supported right now
366 if (sizeof(T) > sizeof(R)) assert(t <= (T)(~((R)0))); // BUGBUG: What if R is a signed type?
367 return (R) t;
368 }
369 template<class R, class T> inline R debugtruncate_cast(T t,const char*f,unsigned int l) {
370 #ifdef MAKENSIS
371 if (sizeof(T) > sizeof(R) && !( (t <= (T)(~((R)0))) )) {
372 _tprintf(_T("unsafe truncate_cast: %") NPRIns _T(":%u\n"),f,l);
373 if (sizeof(T) <= sizeof(void*)) _tprintf(_T("\t%ph > %ph\n"),(void*)(UINT_PTR)(t),(void*)(UINT_PTR)(~((R)0)));
374 }
375 #endif
376 return internaltruncate_cast<R>(t);
377 }
378 #if defined(DEBUG) || defined(_WIN64) // Always enabled for experimental 64-bit builds
379 #define truncate_cast(ret_t,input) debugtruncate_cast<ret_t>((input),__FILE__,__LINE__)
380 #else
381 #define truncate_cast(ret_t,input) internaltruncate_cast<ret_t>((input))
382 #endif
383
384 // ================
385 // ResourceManagers
386 // ================
387
388 // When a ResourceManager instance goes out of scope, it will run
389 // _FREE_RESOURCE on the resource.
390 // Example use:
391 // int fd = open(..);
392 // assert(fd != -1);
393 // MANAGE_WITH(fd, close);
394
395 class BaseResourceManager {
396 protected:
397 BaseResourceManager() {}
398 public:
399 virtual ~BaseResourceManager() {}
400 };
401
402 template <typename _RESOURCE, typename _FREE_RESOURCE>
403 class ResourceManager : public BaseResourceManager {
404 public:
405 ResourceManager(_RESOURCE& resource) : m_resource(resource) {}
406 virtual ~ResourceManager() { m_free_resource(m_resource); };
407 private: // members
408 _RESOURCE& m_resource;
409 _FREE_RESOURCE m_free_resource;
410 private: // don't copy instances
411 ResourceManager(const ResourceManager&);
412 void operator=(const ResourceManager&);
413 };
414
415 #define RM_MANGLE_FREEFUNC(freefunc) __free_with_##freefunc
416 #define RM_DEFINE_FREEFUNC(freefunc) \
417 struct RM_MANGLE_FREEFUNC(freefunc) { \
418 template <typename T> void operator()(T& x) { freefunc(x); } \
419 }
420
421 typedef boost::scoped_ptr<BaseResourceManager> ResourceManagerPtr;
422
423 template<typename _FREE_RESOURCE, typename _RESOURCE>
424 void createResourceManager(_RESOURCE& resource, ResourceManagerPtr& ptr) {
425 ptr.reset(new ResourceManager<_RESOURCE, _FREE_RESOURCE>(resource));
426 }
427
428 #define RM_MANGLE_RESOURCE(resource) resource##_autoManager
429 #define MANAGE_WITH(resource, freefunc) \
430 ResourceManagerPtr RM_MANGLE_RESOURCE(resource); \
431 createResourceManager<RM_MANGLE_FREEFUNC(freefunc)>( \
432 resource, RM_MANGLE_RESOURCE(resource))
433
434 // Add more resource-freeing functions here when you need them
435 RM_DEFINE_FREEFUNC(close);
436 RM_DEFINE_FREEFUNC(CloseHandle);
437 RM_DEFINE_FREEFUNC(fclose);
438 RM_DEFINE_FREEFUNC(free);
439 RM_DEFINE_FREEFUNC(my_convert_free);
440
441 // Auto path conversion
442 #ifndef _WIN32
443 # define PATH_CONVERT(x) x = my_convert(x); MANAGE_WITH(x, my_convert_free);
444 #else
445 # define PATH_CONVERT(x)
446 #endif
447
448 // Platform detection
449 inline bool Platform_IsBigEndian() { return FIX_ENDIAN_INT16(0x00ff) != 0x00ff; }
450 unsigned char Platform_SupportsUTF8Conversion();
451 #ifdef _WIN32
452 #define Platform_IsWindows() ( !0 )
453 #else
454 #define Platform_IsWindows() ( 0 )
455 #endif
456
457 #endif //_UTIL_H_