Debian Codegraph @

Source/build.cpp

raw
1 /*
2 * build.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 * Unicode support added by Jim Park -- 08/07/2007
17 */
18
19 #include "tchar.h"
20 #include "Platform.h"
21 #include <stdio.h>
22 #include "exehead/config.h"
23
24 #include <nsis-version.h>
25
26 #include "build.h"
27 #include "util.h"
28 #include "fileform.h"
29 #include "writer.h"
30 #include "crc32.h"
31 #include "manifest.h"
32 #include "icon.h"
33 #include "utf.h" // For NStream
34 #include "BinInterop.h"
35
36 #include "exehead/api.h"
37 #include "exehead/resource.h"
38
39 #include <stdexcept>
40
41 #include "ResourceEditor.h"
42 #include "DialogTemplate.h"
43 #include "ResourceVersionInfo.h"
44 #include "tstring.h"
45
46 #include <stdio.h>
47 #include <stdarg.h>
48 #ifndef _WIN32
49 # include <locale.h>
50 # include <unistd.h>
51 # include <limits.h>
52 # include <stdlib.h>
53 #endif
54
55 #include <cassert> // for assert
56
57 #define RET_UNLESS_OK( function_rc ) do { \
58 int rc = (function_rc); \
59 if ( rc != PS_OK) \
60 return rc; \
61 } while (false)
62
63 using namespace std;
64
65 namespace { // begin anonymous namespace
66
67 bool isSimpleChar(TCHAR ch)
68 {
69 return (ch == _T('.') ) || (ch == _T('_') ) || (ch >= _T('0') && ch <= _T('9')) || (ch >= _T('A') && ch <= _T('Z')) || (ch >= _T('a') && ch <= _T('z'));
70 }
71
72 } // end of anonymous namespace
73
74 namespace MakensisAPI {
75 #ifdef _WIN64
76 const TCHAR* SigintEventNameFmt = _T("makensis win32 sigint event %Iu"); // %u is the notify HWND, this is to make sure we abort the correct instance
77 #else
78 const TCHAR* SigintEventNameFmt = _T("makensis win32 sigint event %u");
79 #endif
80 const TCHAR* SigintEventNameLegacy = _T("makensis win32 signint event"); // "sigNint" typo is part of the API now and cannot be changed
81 }
82
83 const WORD DefaultPEDllCharacteristics = IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE|IMAGE_DLLCHARACTERISTICS_NO_SEH|IMAGE_DLLCHARACTERISTICS_NX_COMPAT|IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE; //forums.winamp.com/showthread.php?t=344755
84
85 void CEXEBuild::define(const TCHAR *p, const TCHAR *v)
86 {
87 definedlist.add(p,v);
88 }
89
90 CEXEBuild::~CEXEBuild()
91 {
92 free_loaded_icon(installer_icon);
93 free_loaded_icon(uninstaller_icon);
94
95 delete [] m_exehead;
96
97 int nlt = lang_tables.getlen() / sizeof(LanguageTable);
98 LanguageTable *nla = (LanguageTable*)lang_tables.get();
99
100 for (int i = 0; i < nlt; i++)
101 DeleteLangTable(nla+i);
102
103 if (postbuild_cmds) postbuild_cmds->delete_all();
104 if (postubuild_cmds) postubuild_cmds->delete_all();
105 }
106
107 CEXEBuild::CEXEBuild(signed char pponly, bool warnaserror) :
108 preprocessonly(pponly),
109 m_exehead(0),
110 m_exehead_size(0)
111 {
112 set_verbosity(3);
113 if (warnaserror) diagstate.set_warning_as_error();
114
115 curlinereader=0;
116 curfilename=0, linecnt=0;
117 cur_ifblock=NULL;
118 last_line_had_slash=0;
119 inside_comment=false;
120 multiple_entries_instruction=0;
121
122 build_include_depth=0;
123
124 has_called_write_output=false;
125
126 ns_func.add(_T(""),0); // make sure offset 0 is special on these (i.e. never used by a label)
127 ns_label.add(_T(""),0);
128
129 definedlist.add(_T("NSIS_VERSION"), NSIS_VERSION);
130 definedlist.add(_T("NSIS_PACKEDVERSION"), NSIS_PACKEDVERSION);
131
132 m_target_type=TARGET_X86UNICODE;
133 #ifdef _WIN32
134 if (sizeof(void*) > 4) m_target_type = TARGET_AMD64; // BUGBUG: scons 'TARGET_ARCH' should specify the default
135 #endif
136 #ifdef _M_ARM64
137 m_target_type = TARGET_ARM64; // BUGBUG: scons 'TARGET_ARCH' should specify the default
138 #endif
139 build_unicode=TARGET_X86ANSI != m_target_type;
140 build_lockedunicodetarget=false;
141
142 // automatically generated header file containing all defines
143 #include <nsis-defines.h>
144
145 // no longer optional
146 definedlist.add(_T("NSIS_SUPPORT_STANDARD_PREDEFINES"));
147 definedlist.add(_T("NSIS_SUPPORT_NAMED_USERVARS"));
148 definedlist.add(_T("NSIS_SUPPORT_LANG_IN_STRINGS"));
149
150 #ifdef _WIN32
151 definedlist.add(_T("NSIS_WIN32_MAKENSIS"));
152 #endif
153 #ifdef _UNICODE
154 definedlist.add(_T("NSIS_UNICODE_MAKENSIS")); // This define might go away once makensis.exe is always unicode
155 #endif
156 if (sizeof(void*) > 4) definedlist.add(_T("NSIS_MAKENSIS64"));
157
158 db_opt_save=db_opt_save_u=db_full_size=db_full_size_u=0;
159 db_comp_save=db_comp_save_u=0;
160
161 // Added by Amir Szekely 31st July 2002
162 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
163 compressor = &zlib_compressor;
164 #endif
165 build_compressor_set = false;
166 build_compressor_final = false;
167 build_compress_whole = false;
168 build_compress=1;
169 build_compress_level=9;
170 build_compress_dict_size=1<<23;
171
172 cur_entries=&build_entries;
173 cur_instruction_entry_map=&build_instruction_entry_map;
174 cur_datablock=&build_datablock;
175 cur_datablock_cache=&build_datablock_cache;
176 cur_functions=&build_functions;
177 cur_labels=&build_labels;
178 cur_sections=&build_sections;
179 cur_header=&build_header;
180 cur_strlist=&build_strlist;
181 cur_langtables=&build_langtables;
182 cur_ctlcolors=&build_ctlcolors;
183 cur_pages=&build_pages;
184 cur_page=0;
185 cur_page_type=-1;
186
187 build_filebuflen=32<<20; // 32mb
188
189 sectiongroup_open_cnt=0;
190 build_cursection_isfunc=0;
191 build_cursection=NULL;
192 // init public data.
193 build_packname[0]=build_packcmd[0]=build_output_filename[0]=0;
194 postbuild_cmds=postubuild_cmds=NULL;
195
196 // Added by ramon 23 May 2003
197 build_allowskipfiles=1;
198
199 // Added by ramon 6 jun 2003
200 #ifdef NSIS_SUPPORT_VERSION_INFO
201 version_fixedflags=0;
202 #endif
203
204 build_overwrite=build_last_overwrite=0;
205 build_crcchk=1;
206 build_datesave=1;
207 build_optimize_datablock=1;
208
209 memset(&build_header,-1,sizeof(build_header));
210
211 build_header.install_reg_rootkey=0;
212 build_header.flags=CH_FLAGS_NO_ROOT_DIR;
213 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
214 build_header.lb_bg=RGB(0,0,0);
215 build_header.lb_fg=RGB(0,255,0);
216 #endif
217 #ifdef NSIS_CONFIG_LICENSEPAGE
218 build_header.license_bg=-COLOR_BTNFACE;
219 #endif
220 build_header.install_directory_ptr=0;
221 build_header.install_directory_auto_append=0;
222 build_header.install_reg_key_ptr=0;
223 build_header.install_reg_value_ptr=0;
224 #ifdef NSIS_CONFIG_COMPONENTPAGE
225 memset(build_header.install_types,0,sizeof(build_header.install_types));
226 #endif
227 memset(&build_header.blocks,0,sizeof(build_header.blocks));
228
229 uninstall_mode=0;
230 uninstall_size_full=0;
231 uninstall_size=UINT_MAX;
232
233 memset(&build_uninst,-1,sizeof(build_uninst));
234
235 build_header.install_reg_rootkey=0;
236 build_uninst.flags=0;
237 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
238 build_uninst.lb_bg=RGB(0,0,0);
239 build_uninst.lb_fg=RGB(0,255,0);
240 #endif
241 #ifdef NSIS_CONFIG_LICENSEPAGE
242 build_uninst.license_bg=-COLOR_BTNFACE;
243 #endif
244 build_uninst.install_directory_ptr=0;
245 build_uninst.install_directory_auto_append=0;
246 build_uninst.install_reg_key_ptr=0;
247 build_uninst.install_reg_value_ptr=0;
248 #ifdef NSIS_CONFIG_COMPONENTPAGE
249 memset(build_uninst.install_types,0,sizeof(build_uninst.install_types));
250 #endif
251 memset(&build_uninst.blocks,0,sizeof(build_uninst.blocks));
252
253 uninstaller_writes_used=0;
254
255 build_strlist.addemptystring();
256 ubuild_strlist.addemptystring();
257
258 build_langstring_num=0;
259 ubuild_langstring_num=0;
260
261 build_font[0]=0;
262 build_font_size=0;
263
264 m_unicon_size=0;
265
266 branding_image_found=false;
267
268 no_space_texts=false;
269
270 m_currentmacroname=NULL;
271
272 #ifdef NSIS_CONFIG_PLUGIN_SUPPORT
273 build_plugin_unload=0;
274 m_pPlugins=0;
275 #endif
276
277 last_used_lang=NSIS_DEFAULT_LANG;
278
279 res_editor=0;
280
281 PEDllCharacteristics = DefaultPEDllCharacteristics;
282 PESubsysVerMaj = PESubsysVerMin = (WORD) -1;
283 manifest_flags = manifest::flags_default;
284 manifest_comctl = manifest::comctl_old;
285 manifest_exec_level = manifest::exec_level_admin;
286 manifest_dpiaware = manifest::dpiaware_notset;
287 manifest_lpaware = manifest::lpaware_notset;
288 manifest_sosl.setdefault();
289
290 enable_last_page_cancel=0;
291 uenable_last_page_cancel=0;
292
293 license_res_id=IDD_LICENSE;
294
295 disable_window_icon=0;
296
297 notify_hwnd=0;
298
299 #ifdef NSIS_SUPPORT_BGBG
300 bg_default_font.lfHeight=40;
301 bg_default_font.lfWidth=0;
302 bg_default_font.lfEscapement=0;
303 bg_default_font.lfOrientation=0;
304 bg_default_font.lfWeight=FW_BOLD;
305 bg_default_font.lfItalic=TRUE;
306 bg_default_font.lfUnderline=FALSE;
307 bg_default_font.lfStrikeOut=FALSE;
308 bg_default_font.lfCharSet=DEFAULT_CHARSET;
309 bg_default_font.lfOutPrecision=OUT_DEFAULT_PRECIS;
310 bg_default_font.lfClipPrecision=CLIP_DEFAULT_PRECIS;
311 bg_default_font.lfQuality=DEFAULT_QUALITY;
312 bg_default_font.lfPitchAndFamily=DEFAULT_PITCH;
313 my_strncpy(bg_default_font.lfFaceName,_T("Times New Roman"),LF_FACESIZE);
314 memcpy(&bg_font,&bg_default_font,sizeof(LOGFONT));
315 #endif
316
317 defcodepage_set=false;
318 uDefCodePage=CP_ACP;
319
320 InitLangTables();
321
322 // Register static user variables $0, $1 and so on
323 // with ONE of reference count, to avoid warning on these vars
324 TCHAR Aux[3];
325 int i;
326 for (i = 0; i < 10; i++) // 0 - 9
327 {
328 wsprintf(Aux, _T("%d"), i);
329 m_UserVarNames.add(Aux,1);
330 }
331 for (i = 0; i < 10; i++) // 10 - 19
332 {
333 wsprintf(Aux, _T("R%d"), i);
334 m_UserVarNames.add(Aux,1);
335 }
336 m_UserVarNames.add(_T("CMDLINE"),1); // 20 everything before here doesn't have trailing slash removal
337 m_UserVarNames.add(_T("INSTDIR"),1); // 21
338 m_UserVarNames.add(_T("OUTDIR"),1); // 22
339 m_UserVarNames.add(_T("EXEDIR"),1); // 23
340 m_UserVarNames.add(_T("LANGUAGE"),1); // 24
341 m_UserVarNames.add(_T("TEMP"),-1); // 25
342 m_UserVarNames.add(_T("PLUGINSDIR"),-1); // 26
343 m_UserVarNames.add(_T("EXEPATH"),-1); // 27
344 m_UserVarNames.add(_T("EXEFILE"),-1); // 28
345 m_UserVarNames.add(_T("HWNDPARENT"),-1); // 29
346 m_UserVarNames.add(_T("_CLICK"),-1); // 30
347 m_UserVarNames.add(_T("_OUTDIR"),1); // 31 Note: nsDialogs also uses this
348
349 m_iBaseVarsNum = m_UserVarNames.getnum();
350
351 m_ShellConstants.add(_T("WINDIR"),CSIDL_WINDOWS,CSIDL_WINDOWS);
352 m_ShellConstants.add(_T("SYSDIR"),CSIDL_SYSTEM,CSIDL_SYSTEM);
353 m_ShellConstants.add(_T("SMPROGRAMS"),CSIDL_PROGRAMS, CSIDL_COMMON_PROGRAMS);
354 m_ShellConstants.add(_T("SMSTARTUP"),CSIDL_STARTUP, CSIDL_COMMON_STARTUP);
355 m_ShellConstants.add(_T("DESKTOP"),CSIDL_DESKTOPDIRECTORY, CSIDL_COMMON_DESKTOPDIRECTORY);
356 m_ShellConstants.add(_T("STARTMENU"),CSIDL_STARTMENU, CSIDL_COMMON_STARTMENU);
357 m_ShellConstants.add(_T("QUICKLAUNCH"), CSIDL_APPDATA, CSIDL_APPDATA);
358 m_ShellConstants.add(_T("DOCUMENTS"),CSIDL_PERSONAL, CSIDL_COMMON_DOCUMENTS);
359 m_ShellConstants.add(_T("SENDTO"),CSIDL_SENDTO, CSIDL_SENDTO);
360 m_ShellConstants.add(_T("RECENT"),CSIDL_RECENT, CSIDL_RECENT);
361 m_ShellConstants.add(_T("FAVORITES"),CSIDL_FAVORITES, CSIDL_COMMON_FAVORITES);
362 m_ShellConstants.add(_T("MUSIC"),CSIDL_MYMUSIC, CSIDL_COMMON_MUSIC);
363 m_ShellConstants.add(_T("PICTURES"),CSIDL_MYPICTURES, CSIDL_COMMON_PICTURES);
364 m_ShellConstants.add(_T("VIDEOS"),CSIDL_MYVIDEO, CSIDL_COMMON_VIDEO);
365 m_ShellConstants.add(_T("NETHOOD"), CSIDL_NETHOOD, CSIDL_NETHOOD);
366 m_ShellConstants.add(_T("FONTS"), CSIDL_FONTS, CSIDL_FONTS);
367 m_ShellConstants.add(_T("TEMPLATES"), CSIDL_TEMPLATES, CSIDL_COMMON_TEMPLATES);
368 m_ShellConstants.add(_T("APPDATA"), CSIDL_APPDATA, CSIDL_COMMON_APPDATA); // Note: There is no all-users roaming appdata folder.
369 m_ShellConstants.add(_T("LOCALAPPDATA"), CSIDL_LOCAL_APPDATA, CSIDL_COMMON_APPDATA);
370 m_ShellConstants.add(_T("PRINTHOOD"), CSIDL_PRINTHOOD, CSIDL_PRINTHOOD);
371 //m_ShellConstants.add(_T("ALTSTARTUP"), CSIDL_ALTSTARTUP, CSIDL_COMMON_ALTSTARTUP);
372 m_ShellConstants.add(_T("INTERNET_CACHE"), CSIDL_INTERNET_CACHE, CSIDL_INTERNET_CACHE);
373 m_ShellConstants.add(_T("COOKIES"), CSIDL_COOKIES, CSIDL_COOKIES);
374 m_ShellConstants.add(_T("HISTORY"), CSIDL_HISTORY, CSIDL_HISTORY);
375 m_ShellConstants.add(_T("PROFILE"), CSIDL_PROFILE, CSIDL_PROFILE);
376 m_ShellConstants.add(_T("ADMINTOOLS"), CSIDL_ADMINTOOLS, CSIDL_COMMON_ADMINTOOLS);
377 m_ShellConstants.add(_T("RESOURCES"), CSIDL_RESOURCES, CSIDL_RESOURCES);
378 m_ShellConstants.add(_T("RESOURCES_LOCALIZED"), CSIDL_RESOURCES_LOCALIZED, CSIDL_RESOURCES_LOCALIZED);
379 m_ShellConstants.add(_T("CDBURN_AREA"), CSIDL_CDBURN_AREA, CSIDL_CDBURN_AREA);
380
381 // Constants that are not affected by SetShellVarContext
382 m_ShellConstants.add(_T("USERAPPDATA"), CSIDL_APPDATA, CSIDL_APPDATA|0x40); // 0x40 to differentiate it from $QUICKLAUNCH
383 m_ShellConstants.add(_T("USERLOCALAPPDATA"), CSIDL_LOCAL_APPDATA, CSIDL_LOCAL_APPDATA);
384 m_ShellConstants.add(_T("USERTEMPLATES"), CSIDL_TEMPLATES, CSIDL_TEMPLATES);
385 m_ShellConstants.add(_T("USERSTARTMENU"), CSIDL_STARTMENU, CSIDL_STARTMENU);
386 m_ShellConstants.add(_T("USERSMPROGRAMS"), CSIDL_PROGRAMS, CSIDL_PROGRAMS);
387 m_ShellConstants.add(_T("USERDESKTOP"), CSIDL_DESKTOPDIRECTORY, CSIDL_DESKTOPDIRECTORY);
388 m_ShellConstants.add(_T("COMMONLOCALAPPDATA"), CSIDL_COMMON_APPDATA, CSIDL_COMMON_APPDATA);
389 m_ShellConstants.add(_T("COMMONPROGRAMDATA"), CSIDL_COMMON_APPDATA, CSIDL_COMMON_APPDATA); // a.k.a. %ProgramData%
390 m_ShellConstants.add(_T("COMMONTEMPLATES"), CSIDL_COMMON_TEMPLATES, CSIDL_COMMON_TEMPLATES);
391 m_ShellConstants.add(_T("COMMONSTARTMENU"), CSIDL_COMMON_STARTMENU, CSIDL_COMMON_STARTMENU);
392 m_ShellConstants.add(_T("COMMONSMPROGRAMS"), CSIDL_COMMON_PROGRAMS, CSIDL_COMMON_PROGRAMS);
393 m_ShellConstants.add(_T("COMMONDESKTOP"), CSIDL_COMMON_DESKTOPDIRECTORY, CSIDL_COMMON_DESKTOPDIRECTORY);
394
395 // PROGRAMFILES&COMMONFILES does a registry lookup and the required string offsets are filled in later.
396 // We do this later because the unicode mode has to be locked when we call add_string...
397 m_ShellConstants.add(_T("PROGRAMFILES"), 0, 0);
398 m_ShellConstants.add(_T("PROGRAMFILES32"), 0, 0);
399 m_ShellConstants.add(_T("PROGRAMFILES64"), 0, 0);
400 m_ShellConstants.add(_T("COMMONFILES"), 0, 0);
401 m_ShellConstants.add(_T("COMMONFILES32"), 0, 0);
402 m_ShellConstants.add(_T("COMMONFILES64"), 0, 0);
403
404 set_uninstall_mode(0);
405 set_code_type_predefines();
406 }
407
408 void CEXEBuild::initialize(const TCHAR *makensis_path)
409 {
410 tstring nsis_dir;
411 const TCHAR *dir = _tgetenv(_T("NSISDIR"));
412 if (dir) nsis_dir = dir;
413 else {
414 #ifndef NSIS_CONFIG_CONST_DATA_PATH
415 nsis_dir = get_dir_name(get_executable_dir(makensis_path));
416 #else
417 nsis_dir = _T(PREFIX_DATA);
418 #endif
419 }
420 definedlist.add(_T("NSISDIR"), nsis_dir.c_str());
421
422 tstring includes_dir = nsis_dir;
423 includes_dir += PLATFORM_PATH_SEPARATOR_STR _T("Include");
424 include_dirs.add(includes_dir.c_str(),0);
425
426 stubs_dir = nsis_dir;
427 stubs_dir += PLATFORM_PATH_SEPARATOR_STR _T("Stubs");
428
429 if (set_compressor(_T("zlib"), false) != PS_OK || set_target_architecture_data() != PS_OK)
430 {
431 throw runtime_error("error setting default stub");
432 }
433
434 tstring uninst = stubs_dir + PLATFORM_PATH_SEPARATOR_STR + _T("uninst");
435 uninstaller_icon = load_icon_file(uninst.c_str());
436 changed_target = false;
437 }
438
439
440 int CEXEBuild::getcurdbsize() { return cur_datablock->getlen(); }
441
442
443 void CEXEBuild::init_shellconstantvalues()
444 {
445 static bool done = false;
446 if (done) return ; else done = true;
447
448 const int orgunmode = uninstall_mode, t64 = is_target_64bit(), reg = 0x80, r32 = t64 ? 0xC0 : reg, r64 = r32 ^ 0x40;
449 set_uninstall_mode(0);
450 // Note: The order matters because some of the strings are preprocessed and cf must be <= 0x40
451 unsigned int pf = add_asciistring(_T("ProgramFilesDir"), 0);
452 unsigned int cf = add_asciistring(_T("CommonFilesDir"), 0);
453 unsigned int pf_def = add_asciistring(_T("C:\\Program Files")); // Ultimate fallback
454 // TODO: 64-bit targets could use CSIDL_PROGRAM_FILES+CSIDL_PROGRAM_FILESX86?
455 m_ShellConstants.set_values(_T("PROGRAMFILES"), reg | pf, pf_def);
456 unsigned int pf_var = add_asciistring(_T("$PROGRAMFILES")); // Fallback for the 32/64 specific constants if the WOW registry view fails
457 m_ShellConstants.set_values(_T("PROGRAMFILES32"), r32 | pf, reg != r32 ? pf_var : pf_def);
458 m_ShellConstants.set_values(_T("PROGRAMFILES64"), r64 | pf, reg != r64 ? pf_var : pf_def);
459 unsigned int cf_def = add_asciistring(_T("$PROGRAMFILES\\Common Files"));
460 m_ShellConstants.set_values(_T("COMMONFILES"), reg | cf, cf_def);
461 unsigned int cf_var = add_asciistring(_T("$COMMONFILES"));
462 m_ShellConstants.set_values(_T("COMMONFILES32"), r32 | cf, reg != r32 ? cf_var : cf_def);
463 m_ShellConstants.set_values(_T("COMMONFILES64"), r64 | cf, reg != r64 ? cf_var : cf_def);
464
465 if ( (pf >= 0x40 || pf_def >= 0xFF || pf_var > 0xFF) // BUGBUG: pf_def should be ">"?
466 || (cf > 0x40 || cf_def > 0xFF || cf_var > 0xFF) )
467 {
468 // see Source\exehead\util.c for implementation details
469 // basically, it knows it needs to get folders from the registry when the 0x80 is on
470 const char* msg = "Internal compiler error: too many strings added to strings block before adding shell constants!";
471 ERROR_MSG(_T("%") NPRIns, msg);
472 throw out_of_range(msg);
473 }
474
475 set_uninstall_mode(1);
476 unsigned int unpf = add_asciistring(_T("ProgramFilesDir"), 0);
477 unsigned int uncf = add_asciistring(_T("CommonFilesDir"), 0);
478 unsigned int unpf_def = add_asciistring(_T("C:\\Program Files"));
479 unsigned int unpf_var = add_asciistring(_T("$PROGRAMFILES"));
480 unsigned int uncf_def = add_asciistring(_T("$PROGRAMFILES\\Common Files"));
481 unsigned int uncf_var = add_asciistring(_T("$COMMONFILES"));
482 set_uninstall_mode(orgunmode);
483
484 if ( unpf != pf || unpf_def != pf_def || unpf_var != pf_var
485 || uncf != cf || uncf_def != cf_def || uncf_var != cf_var )
486 {
487 const char* msg = "Internal compiler error: installer's shell constants are different than uninstallers!";
488 ERROR_MSG(_T("%") NPRIns, msg);
489 throw out_of_range(msg);
490 }
491 }
492
493 // returns offset in stringblock
494 int CEXEBuild::add_string(const TCHAR *string, int process/*=1*/, UINT codepage/*=-2*/)
495 {
496 if (!string || !*string) return 0;
497 build_lockedunicodetarget = true;
498 init_shellconstantvalues();
499 if ((UINT)-2 == codepage)
500 {
501 codepage = curlinereader ? curlinereader->StreamEncoding().GetCodepage() : CP_UTF8;
502 // If the current source file is Unicode we have to pick a real codepage for ANSI!
503 // It might not be the correct codepage but it's the best we can do.
504 // Not using CP_ACP to avoid heisenbugs when compiled on a different system.
505 if (NStreamEncoding::IsUnicodeCodepage(codepage)) codepage = 1252;
506 }
507 if (*string == _T('$') && *(string+1) == _T('('))
508 {
509 int idx = 0;
510 TCHAR *cp = _tcsdup(string+2);
511 TCHAR *p = _tcschr(cp, _T(')'));
512 if (p && p[1] == _T('\0') ) { // if string is only a language str identifier
513 *p = 0;
514 idx = DefineLangString(cp, process);
515 }
516 free(cp);
517 if (idx < 0) return idx;
518 }
519
520 int i;
521 if (process)
522 {
523 ExpandoString<TCHAR, NSIS_MAX_STRLEN*4> buf;
524 // NOTE: It is impossible to know how much preprocessing will increase the size, we have to guess
525 buf.Reserve(_tcsclen(string) * 2);
526 preprocess_string(buf, string, codepage); // BUGBUG: This could overflow buf
527 i = cur_strlist->add(buf, (WORD)codepage, true);
528 }
529 else
530 i = cur_strlist->add(string, (WORD)codepage, false);
531 return i;
532 }
533
534 int CEXEBuild::add_asciistring(const TCHAR *string, int process/*=1*/)
535 {
536 return add_string(string, process, 1252);
537 }
538
539 int CEXEBuild::add_intstring(const int i) // returns offset in stringblock
540 {
541 TCHAR buf[32];
542 wsprintf(buf, _T("%d"), i);
543 return add_asciistring(buf, false);
544 }
545
546 #ifdef _UNICODE
547 char* convert_processed_string_to_ansi(char *out, const TCHAR *in, WORD codepage)
548 {
549 const TCHAR *p=in;
550 for (;;)
551 {
552 _TUCHAR i = (_TUCHAR)*p++;
553 if (NS_IS_CODE(i)) // Note: this includes '\0'
554 {
555 // convert all character up to, and including this code
556 int c = (int)(p-in), cb = WideCharToMultiByte(codepage, 0, in, c, out, c*2, NULL, NULL);
557 if (!cb && i) return 0;
558 out += cb;
559 if (i == _T('\0'))
560 break;
561 else if (i == NS_SKIP_CODE)
562 // BUGBUG: Shouldn't the escaped code be converted from wchar_t to codepage as well?
563 *out++ = (char) *in++; // simply copy escaped code (01..04)
564 else
565 {
566 WORD w = *p++; // special NSIS code is following by a WORD we need to output unchanged
567 *out++ = LOBYTE(w);
568 *out++ = HIBYTE(w);
569 }
570 in = p;
571 }
572 }
573 return out;
574 }
575 #endif
576
577 // based on Dave Laundon's code
578 int CEXEBuild::preprocess_string(TCHAR *out, const TCHAR *in, WORD codepage/*=CP_ACP*/)
579 {
580 const TCHAR *p=in;
581 while (*p)
582 {
583 const TCHAR *np;
584 #ifdef _UNICODE
585 np = CharNext(p);
586 #else
587 np = CharNextExA(codepage, p, 0);
588 #endif
589 if (np - p > 1) // multibyte TCHAR
590 {
591 size_t len = np - p;
592 while (len--)
593 {
594 _TUCHAR i = (_TUCHAR)*p++;
595 if (NS_IS_CODE(i)) {
596 *out++ = (TCHAR)NS_SKIP_CODE;
597 }
598 *out++=(TCHAR)i;
599 }
600 continue;
601 }
602
603 _TUCHAR i = (_TUCHAR)*p;
604
605 p=np; // increment p.
606
607 // Test for characters extending into the variable codes
608 if (NS_IS_CODE(i)) {
609 *out++ = (TCHAR)NS_SKIP_CODE;
610 // out does get the NS_CODE as well because of
611 // "*out++=(TCHAR)i" at the end.
612 }
613 else if (i == _T('$'))
614 {
615 if (*p == _T('$'))
616 p++; // Can simply convert $$ to $ now
617 else
618 {
619 // starts with a $ but not $$.
620 bool bProceced=false;
621 if (*p)
622 {
623 const TCHAR *pUserVarName = p;
624 while (isSimpleChar(*pUserVarName))
625 pUserVarName++;
626
627 while (pUserVarName > p)
628 {
629 if (m_ShellConstants.get(p, truncate_cast(int, (size_t)(pUserVarName - p))) >= 0)
630 break; // Woops it's a shell constant
631
632 int idxUserVar = m_UserVarNames.get(p, truncate_cast(int, (size_t)(pUserVarName - p)));
633 if (idxUserVar >= 0)
634 {
635 // Well, using variables inside string formatting doesn't mean
636 // using the variable, because it will be always an empty string
637 // which is also memory wasting
638 // So the line below must be commented !??
639 //m_UserVarNames.inc_reference(idxUserVar);
640 *out++ = (TCHAR) NS_VAR_CODE; // Named user variable;
641 WORD w = FIX_ENDIAN_INT16(CODE_SHORT(idxUserVar));
642 unsigned int w4 = sizeof(TCHAR) > 2 ? FIX_ENDIAN_INT32(CODE_SHORT(idxUserVar)) : w; // Maybe this is too much endian fixing?
643 if (sizeof(TCHAR) < 2) *((WORD*)out) = w, out += 2; else *out = (TCHAR) w4, out++;
644 p += pUserVarName-p; // zip past the user var string.
645 bProceced = true;
646 break;
647 }
648 pUserVarName--;
649 }
650 }// if ( *p )
651 if (!bProceced && *p)
652 {
653 const TCHAR *pShellConstName = p;
654 while (isSimpleChar(*pShellConstName))
655 pShellConstName++;
656
657 while (pShellConstName > p)
658 {
659 // Look for the identifier in the shell constants list of strings.
660 int idxConst = m_ShellConstants.get((TCHAR*)p, truncate_cast(int, (size_t)(pShellConstName - p)));
661
662 // If found...
663 if (idxConst >= 0)
664 {
665 init_shellconstantvalues();
666 int CSIDL_Value_current = m_ShellConstants.get_value1(idxConst);
667 int CSIDL_Value_all = m_ShellConstants.get_value2(idxConst);
668 *out++=(TCHAR)NS_SHELL_CODE; // Constant code identifier
669 #ifdef _UNICODE
670 *out++=MAKEWORD(CSIDL_Value_current, CSIDL_Value_all);
671 #else
672 *out++=(TCHAR)CSIDL_Value_current;
673 *out++=(TCHAR)CSIDL_Value_all;
674 #endif
675 p = pShellConstName; // zip past the shell constant string.
676 bProceced = true;
677 break;
678 }
679
680 // We are looking from the longest identifier first and work
681 // smaller.
682 pShellConstName--;
683 }
684 }
685 if ( !bProceced && *p == _T('(') )
686 {
687 int idx = -1;
688 TCHAR *cp = _tcsdup(p+1); // JP: Bad... should avoid memory alloc.
689 TCHAR *pos = _tcschr(cp, _T(')'));
690 if (pos)
691 {
692 *pos = 0;
693 idx = DefineLangString(cp);
694 if (idx < 0)
695 {
696 *out++ = (TCHAR)NS_LANG_CODE; // Next word is lang-string Identifier
697 WORD w = FIX_ENDIAN_INT16(CODE_SHORT(-idx-1));
698 unsigned int w4 = sizeof(TCHAR) > 2 ? FIX_ENDIAN_INT32(CODE_SHORT(-idx-1)) : w; // Maybe this is too much endian fixing?
699 if (sizeof(TCHAR) < 2) *((WORD*)out) = w, out += 2; else *out = (TCHAR) w4, out++;
700 p += _tcslen(cp) + 2;
701 bProceced = true;
702 }
703 }
704 free(cp);
705 }
706 if ( bProceced )
707 continue; // outermost while
708 else
709 {
710 TCHAR tbuf[64], cBracket = _T('\0');
711 bool bDoWarning = true;
712
713 if ( *p == _T('[') ) cBracket = _T(']');
714 else if ( *p == _T('(') ) cBracket = _T(')');
715 else if ( *p == _T('{') ) cBracket = _T('}');
716
717 my_strncpy(tbuf,p,COUNTOF(tbuf));
718
719 if ( cBracket != 0 )
720 {
721 if (_tcschr(tbuf,cBracket)) (_tcschr(tbuf,cBracket)+1)[0]=0;
722 if ( tbuf[0] == _T('{') && tbuf[_tcslen(tbuf)-1] == _T('}') )
723 {
724 TCHAR *tstIfDefine = _tcsdup(tbuf+1);
725 tstIfDefine[_tcslen(tstIfDefine)-1] = _T('\0');
726 bDoWarning = definedlist.find(tstIfDefine) == NULL;
727 // If it's a defined identifier, then don't warn.
728 }
729 }
730 else
731 {
732 if (_tcsstr(tbuf,_T(" "))) _tcsstr(tbuf,_T(" "))[0]=0;
733 }
734 if ( bDoWarning )
735 warning_fl(DW_VAR_IGNORED_UNKNOWN, _T("unknown variable/constant \"%") NPRIs _T("\" detected, ignoring"),tbuf);
736 i = _T('$'); // redundant since i is already '$' and has not changed.
737 }
738 } // else
739 } // else if (i == _T('$'))
740 *out++=(TCHAR)i;
741 } // outside while
742 *out=0;
743 return 0;
744 }
745
746 // what it does is, when you pass it the offset of the last item added, it will determine if
747 // that data is already present in the datablock, and if so, reference it instead (and shorten
748 // the datablock as necessary). Reduces overhead if you want to add files to a couple places.
749 // Woo, an optimizing installer generator, now we're styling.
750
751 int CEXEBuild::datablock_optimize(int start_offset, int first_int)
752 {
753 int this_len = cur_datablock->getlen() - start_offset;
754
755 cached_db_size this_size = {first_int, start_offset};
756 this->cur_datablock_cache->add(&this_size, sizeof(cached_db_size));
757
758 if (!this->build_optimize_datablock || this_len < (int) sizeof(int))
759 return start_offset;
760
761 #ifdef DEBUG
762 assert(dynamic_cast<MMapBuf*>(cur_datablock));
763 #endif
764 MMapBuf *db = static_cast<MMapBuf*>(cur_datablock);
765 db->setro(TRUE);
766
767 cached_db_size *db_sizes = (cached_db_size *) this->cur_datablock_cache->get();
768 int db_sizes_num = this->cur_datablock_cache->getlen() / sizeof(cached_db_size);
769 db_sizes_num--; // don't compare with the one we just added
770
771 for (int i = 0; i < db_sizes_num; i++)
772 {
773 if (db_sizes[i].first_int == first_int)
774 {
775 int pos = db_sizes[i].start_offset;
776 int left = this_len;
777 while (left > 0)
778 {
779 int l = min(left, build_filebuflen);
780 void *newstuff = db->get(start_offset + this_len - left, l);
781 void *oldstuff = db->getmore(pos + this_len - left, l);
782
783 int res = memcmp(newstuff, oldstuff, l);
784
785 db->release(oldstuff, l);
786 db->release();
787
788 if (res) break;
789
790 left -= l;
791 }
792
793 if (!left)
794 {
795 db_opt_save += this_len;
796 db->resize(max(start_offset, pos + this_len));
797 db->setro(FALSE);
798 this->cur_datablock_cache->resize(cur_datablock_cache->getlen() - sizeof(cached_db_size));
799 return pos;
800 }
801 }
802 }
803
804 db->setro(FALSE);
805 return start_offset;
806 }
807
808 bool CEXEBuild::datablock_finddata(IMMap&mmap, int mmstart, int size, int*ofs)
809 {
810 const int first_int = size;
811 size &= ~ 0x80000000;
812 #ifdef DEBUG
813 assert(dynamic_cast<MMapBuf*>(cur_datablock));
814 #endif
815 MMapBuf *db = static_cast<MMapBuf*>(cur_datablock);
816 cached_db_size *db_sizes = (cached_db_size *) this->cur_datablock_cache->get();
817 int db_sizes_num = this->cur_datablock_cache->getlen() / sizeof(cached_db_size);
818 for (int i = 0; i < db_sizes_num; i++)
819 {
820 if (db_sizes[i].first_int != first_int) continue;
821 int left = size, oldpos = db_sizes[i].start_offset;
822 while (left > 0)
823 {
824 int cbCmp = min(left, build_filebuflen);
825 void *newstuff = mmap.get(mmstart + size - left, cbCmp);
826 void *oldstuff = db->get(sizeof(int) + oldpos + size - left, cbCmp);
827 int res = memcmp(newstuff, oldstuff, cbCmp);
828 mmap.release(), db->release();
829 if (res) break;
830 left -= cbCmp;
831 }
832 if (!left)
833 {
834 if (ofs) *ofs = oldpos;
835 return true;
836 }
837 }
838 return false;
839 }
840
841 int CEXEBuild::add_db_data(IMMap *mmap) // returns offset
842 {
843 build_compressor_set = true;
844
845 int done = 0;
846
847 if (!mmap)
848 {
849 ERROR_MSG(_T("Error: add_db_data() called with invalid mapped file\n"));
850 return -1;
851 }
852
853 int length = mmap->getsize();
854
855 if (length < 0)
856 {
857 ERROR_MSG(_T("Error: add_db_data() called with length=%d\n"), length);
858 return -1;
859 }
860
861 // Jim Park: This kind of stuff looks scary and it is. cur_datablock is
862 // most likely to point to a MMapBuf type right now so it works.
863 MMapBuf *db = (MMapBuf *) this->cur_datablock;
864
865 int st = db->getlen();
866
867 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
868 if (length && !build_compress_whole && build_compress)
869 {
870 // grow datablock so that there is room to compress into
871 int bufferlen, of = false, tmp = 0;
872 of |= !si_add(tmp, length, 1024);
873 of |= !si_add(tmp, tmp, length / 4); // give a nice 25% extra space
874 if (!of)
875 {
876 bufferlen = tmp;
877 of |= !si_add(tmp, st, bufferlen);
878 of |= !si_add(tmp, tmp, sizeof(int));
879 }
880 if (of) // we've hit a signed integer overflow (file is over 1.6 GB)
881 bufferlen = INT_MAX - st - sizeof(int); // so maximize compressor room and hope the file compresses well
882
883 db->resize(st + bufferlen + sizeof(int));
884
885 int n = compressor->Init(build_compress_level, build_compress_dict_size);
886 if (n != C_OK)
887 {
888 ERROR_MSG(_T("Internal compiler error #12345: deflateInit() failed(%") NPRIs _T(" [%d]).\n"), compressor->GetErrStr(n), n);
889 extern void quit(); quit();
890 }
891
892 int avail_in = length;
893 int avail_out = bufferlen;
894 int ret;
895 while (avail_in > 0)
896 {
897 int in_len = min(this->build_filebuflen, avail_in);
898 int out_len = min(this->build_filebuflen, avail_out);
899
900 compressor->SetNextIn((char*) mmap->get(length - avail_in, in_len), in_len);
901 compressor->SetNextOut((char*) db->get(st + sizeof(int) + bufferlen - avail_out, out_len), out_len);
902 if ((ret = compressor->Compress(0)) < 0)
903 {
904 ERROR_MSG(_T("Error: add_db_data() - compress() failed(%") NPRIs _T(" [%d])\n"), compressor->GetErrStr(ret), ret);
905 return -1;
906 }
907 mmap->release();
908 db->flush(out_len);
909 db->release();
910 avail_in -= in_len - compressor->GetAvailIn();
911 avail_out -= out_len - compressor->GetAvailOut();
912
913 if (!avail_out)
914 // not enough space in the output buffer - no compression is better
915 break;
916 }
917
918 // if not enough space in the output buffer - no compression is better
919 if (avail_out)
920 {
921 char *out;
922
923 char a;
924 compressor->SetNextIn(&a,0);
925
926 do
927 {
928 int out_len = min(build_filebuflen, avail_out);
929
930 out = (char *) db->get(st + sizeof(int) + bufferlen - avail_out, out_len);
931
932 compressor->SetNextOut(out, out_len);
933 if ((ret = compressor->Compress(C_FINISH)) < 0)
934 {
935 ERROR_MSG(_T("Error: add_db_data() - compress() failed(%") NPRIs _T(" [%d])\n"), compressor->GetErrStr(ret), ret);
936 return -1;
937 }
938
939 db->flush(out_len);
940 db->release();
941
942 avail_out -= out_len - compressor->GetAvailOut();
943 }
944 while (compressor->GetNextOut() - out > 0 && avail_out > 0);
945
946 compressor->End();
947
948 int used = bufferlen - avail_out;
949
950 // never store compressed if output buffer is full (compression increased the size...)
951 if (avail_out && (build_compress == 2 || used < length))
952 {
953 done=1;
954 db->resize(st + used + sizeof(int));
955
956 *(int*)db->get(st, sizeof(int)) = FIX_ENDIAN_INT32(used | 0x80000000);
957 db->release();
958
959 int nst = datablock_optimize(st, used | 0x80000000);
960 if (nst == st) db_comp_save += length - used;
961 else st = nst;
962 }
963 }
964 else
965 compressor->End();
966 }
967 #endif // NSIS_CONFIG_COMPRESSION_SUPPORT
968
969 if (!done)
970 {
971 // Adding the same file twice can push cur_datablock over the limit
972 // because datablock_optimize() happens too late. Let's try to find a dupe early.
973 if (this->build_optimize_datablock && st + length < 0)
974 {
975 int oldst;
976 if (datablock_finddata(*mmap, 0, length, &oldst))
977 return (db_full_size += length, db_opt_save += length, oldst);
978 }
979
980 db->resize(st + sizeof(int) + length);
981 int *plen = (int *) db->get(st, sizeof(int));
982 *plen = FIX_ENDIAN_INT32(length);
983 db->release();
984
985 int left = length;
986 while (left > 0)
987 {
988 int l = min(build_filebuflen, left);
989 int *p = (int *) db->get(st + sizeof(int) + length - left, l);
990 memcpy(p, mmap->get(length - left, l), l);
991 db->flush(l);
992 db->release();
993 mmap->release();
994 left -= l;
995 }
996
997 st = datablock_optimize(st, length);
998 }
999
1000 db_full_size += length + sizeof(int);
1001 return st;
1002 }
1003
1004 int CEXEBuild::add_db_data(const char *data, int length) // returns offset
1005 {
1006 MMapFake fakemap;
1007 fakemap.set(data, length);
1008 return add_db_data(&fakemap);
1009 }
1010
1011 int CEXEBuild::add_data(const char *data, int length, IGrowBuf *dblock) // returns offset
1012 {
1013 build_compressor_set=true;
1014
1015 int done=0;
1016
1017 if (length < 0)
1018 {
1019 ERROR_MSG(_T("Error: add_data() called with length=%d\n"),length);
1020 return -1;
1021 }
1022
1023 int st=dblock->getlen();
1024
1025 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
1026 if (!build_compress_whole && build_compress)
1027 {
1028 // grow datablock so that there is room to compress into
1029 int bufferlen=length+1024+length/4; // give a nice 25% extra space
1030 dblock->resize(st+bufferlen+sizeof(int));
1031
1032 int n = compressor->Init(build_compress_level, build_compress_dict_size);
1033 if (n != C_OK)
1034 {
1035 ERROR_MSG(_T("Internal compiler error #12345: deflateInit() failed(%") NPRIs _T(" [%d]).\n"), compressor->GetErrStr(n), n);
1036 extern void quit(); quit();
1037 }
1038
1039 compressor->SetNextIn((char*)data, length);
1040 compressor->SetNextOut((char*)dblock->get() + st + sizeof(int), bufferlen);
1041
1042 compressor->Compress(C_FINISH);
1043
1044 int used=bufferlen-compressor->GetAvailOut();
1045
1046 // never store compressed if output buffer is full
1047 if (compressor->GetAvailOut() && (build_compress == 2 || used < length))
1048 {
1049 done=1;
1050 dblock->resize(st+used+sizeof(int));
1051
1052 *((int*)((char *)dblock->get()+st)) = FIX_ENDIAN_INT32(used|0x80000000);
1053 }
1054 compressor->End();
1055 }
1056 #endif // NSIS_CONFIG_COMPRESSION_SUPPORT
1057
1058 if (!done)
1059 {
1060 dblock->resize(st);
1061 int rl = FIX_ENDIAN_INT32(length);
1062 dblock->add(&rl,sizeof(int));
1063 dblock->add(data,length);
1064 }
1065
1066 return st;
1067 }
1068
1069 int CEXEBuild::add_label(const TCHAR *name)
1070 {
1071 if (!build_cursection)
1072 {
1073 ERROR_MSG(_T("Error: Label declaration not valid outside of function/section\n"));
1074 return PS_ERROR;
1075 }
1076 if ((name[0] >= _T('0') && name[0] <= _T('9')) || name[0] == _T('-') || name[0] == _T(' ') || name[0] == _T(':'))
1077 {
1078 ERROR_MSG(_T("Error: labels must not begin with 0-9, -, :, or a space.\n"));
1079 return PS_ERROR;
1080 }
1081
1082 int cs=build_cursection->code;
1083 int ce=cs+build_cursection->code_size;
1084
1085 TCHAR *p=_tcsdup(name);
1086 if (p[_tcslen(p)-1] == _T(':')) p[_tcslen(p)-1]=0;
1087 int offs=ns_label.add(p,0);
1088 free(p);
1089
1090 int n=cur_labels->getlen()/sizeof(section);
1091
1092 // Check to see if the label already exists.
1093 if (n)
1094 {
1095 section *t=(section*)cur_labels->get();
1096 while (n--)
1097 {
1098 // Labels beginning with '.' are global and can be jumped to from any function or section.
1099 if ((*name == _T('.') || (t->code >= cs && t->code <= ce)) &&
1100 t->name_ptr==offs)
1101 {
1102 if (*name == _T('.')) ERROR_MSG(_T("Error: global label \"%") NPRIs _T("\" already declared\n"),name);
1103 else
1104 {
1105 const TCHAR *szType = _T("section");
1106 if (build_cursection_isfunc)
1107 szType = _T("function");
1108 ERROR_MSG(_T("Error: label \"%") NPRIs _T("\" already declared in %") NPRIs _T("\n"),name,szType);
1109 }
1110 return PS_ERROR;
1111 }
1112 t++;
1113 }
1114 }
1115
1116 section s={0};
1117 s.name_ptr = offs;
1118 s.code = ce;
1119 cur_labels->add(&s,sizeof(s));
1120
1121 return PS_OK;
1122 }
1123
1124 int CEXEBuild::add_function(const TCHAR *funname)
1125 {
1126 if (build_cursection_isfunc)
1127 {
1128 ERROR_MSG(_T("Error: Function open when creating function (use FunctionEnd first)\n"));
1129 return PS_ERROR;
1130 }
1131 if (build_cursection)
1132 {
1133 ERROR_MSG(_T("Error: Section open when creating function (use SectionEnd first)\n"));
1134 return PS_ERROR;
1135 }
1136 if (cur_page)
1137 {
1138 ERROR_MSG(_T("Error: PageEx open when creating function (use PageExEnd first)\n"));
1139 return PS_ERROR;
1140 }
1141 if (!funname[0])
1142 {
1143 ERROR_MSG(_T("Error: Function must have a name\n"));
1144 return PS_ERROR;
1145 }
1146
1147 set_uninstall_mode(!_tcsnicmp(funname,_T("un."),3));
1148
1149 // ns_func contains all the function names defined.
1150 int addr=ns_func.add(funname,0);
1151 int n=cur_functions->getlen()/sizeof(section), x;
1152 section *tmp=(section*)cur_functions->get();
1153 for (x = 0; x < n; x ++)
1154 {
1155 if (tmp[x].name_ptr == addr)
1156 {
1157 ERROR_MSG(_T("Error: Function named \"%") NPRIs _T("\" already exists.\n"),funname);
1158 return PS_ERROR;
1159 }
1160 }
1161
1162 cur_functions->resize((n+1)*sizeof(section));
1163 build_cursection=((section*)cur_functions->get())+n;
1164 build_cursection_isfunc=1;
1165 build_cursection->name_ptr=addr;
1166 build_cursection->code=cur_entries->getlen()/sizeof(entry);
1167 build_cursection->code_size=0;
1168 build_cursection->install_types=0;
1169 build_cursection->flags=0;
1170 build_cursection->size_kb=0;
1171 memset(build_cursection->name,0,sizeof(build_cursection->name));
1172
1173 if (uninstall_mode)
1174 set_code_type_predefines(funname+3);
1175 else
1176 set_code_type_predefines(funname);
1177
1178 return PS_OK;
1179 }
1180
1181 int CEXEBuild::function_end()
1182 {
1183 if (!build_cursection_isfunc)
1184 {
1185 ERROR_MSG(_T("Error: No function open, FunctionEnd called\n"));
1186 return PS_ERROR;
1187 }
1188 // add ret.
1189 add_entry_direct(EW_RET);
1190
1191 build_cursection_isfunc=0;
1192 build_cursection=NULL;
1193
1194 set_uninstall_mode(0);
1195
1196 set_code_type_predefines();
1197 return PS_OK;
1198 }
1199
1200
1201 int CEXEBuild::section_add_flags(int flags)
1202 {
1203 if (!build_cursection || build_cursection_isfunc)
1204 {
1205 ERROR_MSG(_T("Error: can't modify flags when no section is open\n"));
1206 return PS_ERROR;
1207 }
1208 build_cursection->flags |= flags;
1209 return PS_OK;
1210 }
1211
1212 int CEXEBuild::section_add_install_type(int inst_type)
1213 {
1214 if (!build_cursection || build_cursection_isfunc)
1215 {
1216 ERROR_MSG(_T("Error: can't modify flags when no section is open\n"));
1217 return PS_ERROR;
1218 }
1219 if (build_cursection->install_types == ~0)
1220 build_cursection->install_types = 0;
1221 build_cursection->install_types |= inst_type;
1222 return PS_OK;
1223 }
1224
1225 void CEXEBuild::section_add_size_kb(int kb)
1226 {
1227 if (build_cursection)
1228 {
1229 build_cursection->size_kb+=kb;
1230 }
1231 }
1232
1233 int CEXEBuild::section_end()
1234 {
1235 if (build_cursection_isfunc)
1236 {
1237 ERROR_MSG(_T("Error: SectionEnd specified in function (not section)\n"));
1238 return PS_ERROR;
1239 }
1240 if (!build_cursection)
1241 {
1242 ERROR_MSG(_T("Error: SectionEnd specified and no sections open\n"));
1243 return PS_ERROR;
1244 }
1245 add_entry_direct(EW_RET);
1246 build_cursection->code_size--;
1247 build_cursection=NULL;
1248 if (!sectiongroup_open_cnt)
1249 set_uninstall_mode(0);
1250
1251 set_code_type_predefines();
1252 return PS_OK;
1253 }
1254
1255 int CEXEBuild::add_section(const TCHAR *secname, const TCHAR *defname, int expand/*=0*/)
1256 {
1257 if (build_cursection_isfunc)
1258 {
1259 ERROR_MSG(_T("Error: Section can't create section (already in function, use FunctionEnd first)\n"));
1260 return PS_ERROR;
1261 }
1262 if (cur_page) {
1263 ERROR_MSG(_T("Error: PageEx already open, call PageExEnd first\n"));
1264 return PS_ERROR;
1265 }
1266 if (build_cursection)
1267 {
1268 ERROR_MSG(_T("Error: Section already open, call SectionEnd first\n"));
1269 return PS_ERROR;
1270 }
1271
1272 section new_section;
1273 new_section.flags = SF_SELECTED;
1274 new_section.flags |= expand ? SF_EXPAND : 0;
1275 new_section.code_size = 0;
1276 new_section.size_kb = 0;
1277
1278 TCHAR *name = (TCHAR*)secname;
1279
1280 if (name[0] == _T('\x1F')) // SectionGroup/SectionGroupEnd
1281 {
1282 if (name[1])
1283 {
1284 new_section.flags |= SF_SECGRP;
1285 name++;
1286 }
1287 else
1288 new_section.flags |= SF_SECGRPEND;
1289 }
1290
1291 int hidden = (name[0] == _T('-'));
1292 if (hidden)
1293 name++;
1294
1295 if (name[0] == _T('!'))
1296 {
1297 name++;
1298 new_section.flags |= SF_BOLD;
1299 }
1300
1301 int old_uninstall_mode = uninstall_mode;
1302
1303 set_uninstall_mode(0);
1304
1305 if (!_tcsnicmp(name, _T("un."), 3))
1306 {
1307 set_uninstall_mode(1);
1308 name += 3;
1309 }
1310
1311 if (!_tcsicmp(name, _T("uninstall")))
1312 {
1313 set_uninstall_mode(1);
1314 }
1315
1316 if ((new_section.flags & SF_SECGRPEND) && sectiongroup_open_cnt && old_uninstall_mode)
1317 {
1318 set_uninstall_mode(1);
1319 }
1320
1321 if (sectiongroup_open_cnt)
1322 {
1323 if (uninstall_mode != old_uninstall_mode)
1324 {
1325 ERROR_MSG(_T("Error: Can't create %") NPRIs _T(" section in %") NPRIs _T(" section group (use SectionGroupEnd first)\n"), uninstall_mode ? _T("uninstaller") : _T("installer"), old_uninstall_mode ? _T("uninstaller") : _T("installer"));
1326 return PS_ERROR;
1327 }
1328 }
1329
1330 new_section.code = cur_entries->getlen() / sizeof(entry);
1331
1332 new_section.install_types = (!hidden && *name) ? 0 : ~0;
1333 new_section.name_ptr = hidden ? 0 : add_string(name);
1334 memset(&new_section.name,0,sizeof(new_section.name));
1335
1336 cur_sections->add(&new_section, sizeof(section));
1337 build_cursection = (section *) cur_sections->get() + cur_header->blocks[NB_SECTIONS].num;
1338
1339 if (defname[0])
1340 {
1341 TCHAR buf[1024];
1342 wsprintf(buf, _T("%d"), cur_header->blocks[NB_SECTIONS].num);
1343 if (definedlist.add(defname, buf))
1344 {
1345 ERROR_MSG(_T("Error: \"%") NPRIs _T("\" already defined, can't assign section index!\n"), defname);
1346 return PS_ERROR;
1347 }
1348 }
1349
1350 cur_header->blocks[NB_SECTIONS].num++;
1351
1352 if (new_section.flags & (SF_SECGRP | SF_SECGRPEND))
1353 {
1354 add_entry_direct(EW_RET);
1355 build_cursection->code_size = 0;
1356
1357 build_cursection = 0;
1358
1359 if (new_section.flags & SF_SECGRPEND)
1360 {
1361 sectiongroup_open_cnt--;
1362 if (sectiongroup_open_cnt < 0)
1363 {
1364 ERROR_MSG(_T("SectionGroupEnd: no SectionGroups are open\n"));
1365 return PS_ERROR;
1366 }
1367 if (!sectiongroup_open_cnt)
1368 {
1369 set_uninstall_mode(0);
1370 }
1371 }
1372 else
1373 sectiongroup_open_cnt++;
1374 }
1375
1376 set_code_type_predefines(name);
1377
1378 return PS_OK;
1379 }
1380
1381 int CEXEBuild::add_entry(const entry *ent)
1382 {
1383 if (!build_cursection && !uninstall_mode)
1384 {
1385 ERROR_MSG(_T("Error: Can't add entry, no section or function is open!\n"));
1386 return PS_ERROR;
1387 }
1388
1389 cur_entries->add(ent,sizeof(entry));
1390 cur_instruction_entry_map->add(&multiple_entries_instruction,sizeof(int));
1391 build_cursection->code_size++;
1392 cur_header->blocks[NB_ENTRIES].num++;
1393
1394 multiple_entries_instruction=1;
1395
1396 return PS_OK;
1397 }
1398
1399 int CEXEBuild::add_entry_direct(int which, int o0, int o1, int o2, int o3, int o4, int o5 /*o#=0*/)
1400 {
1401 entry ent;
1402 ent.which = which;
1403 ent.offsets[0] = o0;
1404 ent.offsets[1] = o1;
1405 ent.offsets[2] = o2;
1406 ent.offsets[3] = o3;
1407 ent.offsets[4] = o4;
1408 ent.offsets[5] = o5;
1409 return add_entry(&ent);
1410 }
1411
1412 int CEXEBuild::resolve_jump_int(const TCHAR *fn, int *a, int offs, int start, int end)
1413 {
1414 if (*a > 0)
1415 {
1416 TCHAR *lname=(TCHAR*)ns_label.get()+*a;
1417 if (lname[0] == _T('-') || lname[0]==_T('+'))
1418 {
1419 int jump = _ttoi(lname);
1420 int *skip_map = (int *) cur_instruction_entry_map->get();
1421 int maxoffs = cur_instruction_entry_map->getlen() / (int) sizeof(int);
1422
1423 int direction = 1;
1424 if (jump < 0)
1425 direction = -1;
1426
1427 for (; jump != 0; jump -= direction)
1428 {
1429 offs += direction;
1430 if (offs >= 0 && offs < maxoffs)
1431 {
1432 while (skip_map[offs])
1433 {
1434 offs += direction;
1435 }
1436 }
1437 }
1438
1439 *a = offs + 1;
1440 }
1441 else
1442 {
1443 section *s = (section*)cur_labels->get();
1444 int n=cur_labels->getlen()/sizeof(section);
1445 while (n-->0)
1446 {
1447 if ((*lname == _T('.') || (s->code >= start && s->code <= end)) && s->name_ptr == *a)
1448 {
1449 *a = s->code+1; // jumps are to the absolute position, +1 (to differentiate between no jump, and jumping to offset 0)
1450 s->flags++;
1451 if (*lname == _T('.'))
1452 {
1453 // bug #2593369 - mark functions with used global labels as used
1454 // XXX this puts another hole in function reference counting
1455 // a recursive function, for example, will never be optimized
1456 int nf=cur_functions->getlen()/sizeof(section);
1457 section *func=(section *)cur_functions->get();
1458 while (nf-- > 0)
1459 {
1460 int fstart = func->code;
1461 int fend = func->code + func->code_size;
1462 if (s->code >= fstart && s->code <= fend)
1463 {
1464 func->flags++;
1465 break;
1466 }
1467 func++;
1468 }
1469 }
1470 return 0;
1471 }
1472 s++;
1473 }
1474
1475 ERROR_MSG(_T("Error: could not resolve label \"%") NPRIs _T("\" in %") NPRIs _T("\n"),lname,fn);
1476 return 1;
1477 }
1478 }
1479 else if (*a < 0) // to jump to a user variable target, -variable_index-1 is already stored.
1480 {
1481 }
1482 // otherwise, *a is 0, which means no jump and we also leave it intact
1483 return 0;
1484 }
1485
1486 int CEXEBuild::resolve_call_int(const TCHAR *fn, const TCHAR *str, int fptr, int *ofs)
1487 {
1488 if (fptr < 0) return 0;
1489 int nf=cur_functions->getlen()/sizeof(section);
1490 section *sec=(section *)cur_functions->get();
1491 while (nf-- > 0)
1492 {
1493 if (sec->name_ptr>0 && sec->name_ptr == fptr)
1494 {
1495 ofs[0]=sec->code;
1496 sec->flags++;
1497 return 0;
1498 }
1499 sec++;
1500 }
1501 ERROR_MSG(_T("Error: resolving %") NPRIs _T(" function \"%") NPRIs _T("\" in %") NPRIs _T("\n"),str,(TCHAR*)ns_func.get()+fptr,fn);
1502 ERROR_MSG(_T("Note: uninstall functions must begin with \"un.\", and install functions must not\n"));
1503 return 1;
1504 }
1505
1506 int CEXEBuild::resolve_instruction(const TCHAR *fn, const TCHAR *str, entry *w, int offs, int start, int end)
1507 {
1508 if (w->which == EW_NOP)
1509 {
1510 if (resolve_jump_int(fn,&w->offsets[0],offs,start,end)) return 1;
1511 }
1512 #ifdef NSIS_SUPPORT_MESSAGEBOX
1513 else if (w->which == EW_MESSAGEBOX)
1514 {
1515 if (resolve_jump_int(fn,&w->offsets[3],offs,start,end)) return 1;
1516 if (resolve_jump_int(fn,&w->offsets[5],offs,start,end)) return 1;
1517 }
1518 #endif
1519 else if (w->which == EW_IFFILEEXISTS)
1520 {
1521 if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
1522 if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
1523 }
1524 else if (w->which == EW_IFFLAG)
1525 {
1526 if (resolve_jump_int(fn,&w->offsets[0],offs,start,end)) return 1;
1527 if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
1528 }
1529 #ifdef NSIS_SUPPORT_STROPTS
1530 else if (w->which == EW_STRCMP)
1531 {
1532 if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
1533 if (resolve_jump_int(fn,&w->offsets[3],offs,start,end)) return 1;
1534 }
1535 #endif
1536 #ifdef NSIS_SUPPORT_INTOPTS
1537 else if (w->which == EW_INTCMP)
1538 {
1539 if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
1540 if (resolve_jump_int(fn,&w->offsets[3],offs,start,end)) return 1;
1541 if (resolve_jump_int(fn,&w->offsets[4],offs,start,end)) return 1;
1542 }
1543 #endif
1544 #ifdef NSIS_SUPPORT_HWNDS
1545 else if (w->which == EW_ISWINDOW)
1546 {
1547 if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
1548 if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
1549 }
1550 #endif
1551 else if (w->which == EW_CALL)
1552 {
1553 if (w->offsets[0] >= 0 && w->offsets[1]) // get as jump
1554 {
1555 if (resolve_jump_int(fn,&w->offsets[0],offs,start,end)) return 1;
1556 }
1557 else
1558 {
1559 if (w->offsets[0] >= 0 && resolve_call_int(fn,str,w->offsets[0],w->offsets)) return 1;
1560 // if w->offsets[0] >= 0, EW_CALL requires that it 1-based.
1561 // otherwise, if < 0, it needs an increment anyway (since it
1562 // was encoded with a -2 base, to prevent it looking like an
1563 // empty string "")
1564 w->offsets[0]++;
1565 }
1566 }
1567 #ifdef NSIS_SUPPORT_STROPTS
1568 else if (w->which == EW_GETFUNCTIONADDR)
1569 {
1570 if (w->offsets[1] < 0)
1571 {
1572 ERROR_MSG(_T("Error: GetFunctionAddress requires a real function to get address of.\n"));
1573 return 1;
1574 }
1575
1576 if (resolve_call_int(fn,str,w->offsets[1],&w->offsets[1])) return 1;
1577
1578 w->which=EW_ASSIGNVAR;
1579 w->offsets[1]=add_intstring(w->offsets[1]+1); // +1 here to make 1-based.
1580 }
1581 else if (w->which == EW_GETLABELADDR)
1582 {
1583 if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
1584 w->which=EW_ASSIGNVAR;
1585 w->offsets[1]=add_intstring(w->offsets[1]);
1586 }
1587 #endif
1588 return 0;
1589 }
1590
1591 int CEXEBuild::resolve_coderefs(const TCHAR *str)
1592 {
1593 // resolve jumps&calls
1594 {
1595 section *sec=(section *)cur_functions->get();
1596 int l=cur_functions->getlen()/sizeof(section);
1597 entry *w=(entry *)cur_entries->get();
1598 while (l-- > 0)
1599 {
1600 int x;
1601 for (x = sec->code; x < sec->code+sec->code_size; x ++)
1602 {
1603 TCHAR fname[1024];
1604 wsprintf(fname,_T("function \"%") NPRIs _T("\""),ns_func.get()+sec->name_ptr);
1605 if (resolve_instruction(fname,str,w+x,x,sec->code,sec->code+sec->code_size)) return 1;
1606 }
1607 sec++;
1608 }
1609
1610 int cnt=0;
1611 sec=(section *)cur_sections->get();
1612 l=cur_sections->getlen()/sizeof(section);
1613 while (l-- > 0)
1614 {
1615 int x=sec->name_ptr;
1616 TCHAR fname[1024];
1617 tstring section_name;
1618 if (x < 0)
1619 {
1620 // lang string
1621 section_name = _T("$(lang string)");
1622 }
1623 else
1624 {
1625 // normal string
1626 cur_strlist->get(x,section_name);
1627 }
1628 if (x) wsprintf(fname,_T("%") NPRIs _T(" section \"%") NPRIs _T("\" (%d)"),str,section_name.c_str(),cnt);
1629 else wsprintf(fname,_T("unnamed %") NPRIs _T(" section (%d)"),str,cnt);
1630 for (x = sec->code; x < sec->code+sec->code_size; x ++)
1631 {
1632 if (resolve_instruction(fname,str,w+x,x,sec->code,sec->code+sec->code_size))
1633 return 1;
1634 }
1635 sec++;
1636 cnt++;
1637 }
1638 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
1639 #ifdef NSIS_SUPPORT_CODECALLBACKS
1640 if (cur_pages->getlen()) {
1641 page *p=(page *)cur_pages->get();
1642 int i = 0;
1643 while (i < cur_header->blocks[NB_PAGES].num) {
1644 TCHAR pagestr[1024];
1645 wsprintf(pagestr, _T("%") NPRIs _T(" pages"), str);
1646 if (resolve_call_int(pagestr,p->dlg_id?_T("pre-page"):_T("create-page"),p->prefunc,&p->prefunc)) return 1;
1647 if (resolve_call_int(pagestr,_T("show-page"),p->showfunc,&p->showfunc)) return 1;
1648 if (resolve_call_int(pagestr,_T("leave-page"),p->leavefunc,&p->leavefunc)) return 1;
1649 p++;
1650 i++;
1651 }
1652 }
1653 #endif
1654 #endif
1655 }
1656
1657 #ifdef NSIS_SUPPORT_CODECALLBACKS
1658 // resolve callbacks
1659 {
1660 struct {
1661 const TCHAR *name;
1662 int *p;
1663 } callbacks[] = {
1664 {_T("%") NPRIs _T(".onInit"), &cur_header->code_onInit},
1665 {_T("%") NPRIs _T(".on%") NPRIs _T("InstSuccess"), &cur_header->code_onInstSuccess},
1666 {_T("%") NPRIs _T(".on%") NPRIs _T("InstFailed"), &cur_header->code_onInstFailed},
1667 {_T("%") NPRIs _T(".onUserAbort"), &cur_header->code_onUserAbort},
1668 {_T("%") NPRIs _T(".onVerifyInstDir"), &cur_header->code_onVerifyInstDir},
1669 #ifdef NSIS_CONFIG_ENHANCEDUI_SUPPORT
1670 {_T("%") NPRIs _T(".onGUIInit"), &cur_header->code_onGUIInit},
1671 {_T("%") NPRIs _T(".onGUIEnd"), &cur_header->code_onGUIEnd},
1672 {_T("%") NPRIs _T(".onMouseOverSection"), &cur_header->code_onMouseOverSection},
1673 #endif//NSIS_CONFIG_ENHANCEDUI_SUPPORT
1674 #ifdef NSIS_CONFIG_COMPONENTPAGE
1675 {_T("%") NPRIs _T(".onSelChange"), &cur_header->code_onSelChange},
1676 #endif//NSIS_CONFIG_COMPONENTPAGE
1677 #ifdef NSIS_SUPPORT_REBOOT
1678 {_T("%") NPRIs _T(".onRebootFailed"), &cur_header->code_onRebootFailed},
1679 #endif//NSIS_SUPPORT_REBOOT
1680 {0, 0}
1681 };
1682
1683 for (int i = 0; callbacks[i].name; i++) {
1684 const TCHAR *un = uninstall_mode ? _T("un") : _T("");
1685 TCHAR fname[1024];
1686 wsprintf(fname, callbacks[i].name, un, un);
1687 TCHAR cbstr[1024];
1688 wsprintf(cbstr, _T("%") NPRIs _T(" callback"), str);
1689 TCHAR cbstr2[1024];
1690 wsprintf(cbstr2, _T("%") NPRIs _T(".callbacks"), un);
1691
1692 if (resolve_call_int(cbstr,cbstr2,ns_func.find(fname,0),callbacks[i].p))
1693 return PS_ERROR;
1694 }
1695 }
1696 #endif//NSIS_SUPPORT_CODECALLBACKS
1697
1698 // optimize unused functions
1699 {
1700 section *sec=(section *)cur_functions->get();
1701 int l=cur_functions->getlen()/sizeof(section);
1702 entry *w=(entry*)cur_entries->get();
1703 while (l-- > 0)
1704 {
1705 if (sec->name_ptr)
1706 {
1707 if (!sec->flags)
1708 {
1709 if (sec->code_size>0)
1710 {
1711 warning(DW_UNUSED_FUNCTION, _T("%") NPRIs _T(" function \"%") NPRIs _T("\" not referenced - zeroing code (%d-%d) out\n"),str,
1712 ns_func.get()+sec->name_ptr,
1713 sec->code,sec->code+sec->code_size);
1714 memset(w+sec->code,0,sec->code_size*sizeof(entry));
1715 }
1716 }
1717 }
1718 sec++;
1719 }
1720 }
1721
1722 // give warnings on unused labels
1723 {
1724 section *t=(section*)cur_labels->get();
1725 int n=cur_labels->getlen()/sizeof(section);
1726 while (n-->0)
1727 {
1728 if (!t->flags)
1729 {
1730 TCHAR *n=(TCHAR*)ns_label.get()+t->name_ptr;
1731 if (*n == _T('.')) warning(DW_UNUSED_GLOBALLABEL, _T("global label \"%") NPRIs _T("\" not used"),n);
1732 else warning(DW_UNUSED_LABEL, _T("label \"%") NPRIs _T("\" not used"),n);
1733 }
1734 t++;
1735 }
1736 }
1737
1738 return 0;
1739 }
1740
1741 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
1742 int CEXEBuild::add_page(int type)
1743 {
1744 page pg = {
1745 0,
1746 0,
1747 #ifdef NSIS_SUPPORT_CODECALLBACKS
1748 -1,
1749 -1,
1750 -1,
1751 #endif
1752 0,
1753 };
1754
1755 #ifndef NSIS_CONFIG_LICENSEPAGE
1756 if (type == PAGE_LICENSE)
1757 {
1758 ERROR_MSG(_T("Error: can't add %") NPRIns _T(" page, %") NPRIns _T(" not defined.\n"), "license", "NSIS_CONFIG_LICENSEPAGE");
1759 return PS_ERROR;
1760 }
1761 #endif
1762 #ifndef NSIS_CONFIG_COMPONENTPAGE
1763 if (type == PAGE_COMPONENTS)
1764 {
1765 ERROR_MSG(_T("Error: can't add %") NPRIns _T(" page, %") NPRIns _T(" not defined.\n"), "components", "NSIS_CONFIG_COMPONENTPAGE");
1766 return PS_ERROR;
1767 }
1768 #endif
1769 #ifndef NSIS_CONFIG_UNINSTALL_SUPPORT
1770 if (type == PAGE_COMPONENTS)
1771 {
1772 ERROR_MSG(_T("Error: can't add %") NPRIns _T(" page, %") NPRIns _T(" not defined.\n"), "uninstConfirm", "NSIS_CONFIG_UNINSTALL_SUPPORT");
1773 return PS_ERROR;
1774 }
1775 #endif
1776
1777 struct {
1778 int wndproc_id;
1779 int dlg_id;
1780 const TCHAR *name;
1781 } ids[] = {
1782 {PWP_CUSTOM, 0, _T("custom")}, // custom
1783 #ifdef NSIS_CONFIG_LICENSEPAGE
1784 {PWP_LICENSE, IDD_LICENSE, _T("license")}, // license
1785 #else
1786 {0, IDD_LICENSE, _T("license")}, // license
1787 #endif
1788 #ifdef NSIS_CONFIG_COMPONENTPAGE
1789 {PWP_SELCOM, IDD_SELCOM, _T("components")}, // components
1790 #else
1791 {0, IDD_SELCOM, _T("components")}, // components
1792 #endif
1793 {PWP_DIR, IDD_DIR, _T("directory")}, // directory
1794 {PWP_INSTFILES, IDD_INSTFILES, _T("instfiles")}, // instfiles
1795 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
1796 {PWP_UNINST, IDD_UNINST, _T("uninstConfirm")}, // uninstConfirm
1797 #else
1798 {0, IDD_UNINST, _T("uninstConfirm")}, // uninstConfirm
1799 #endif
1800 {PWP_COMPLETED, -1, NULL} // completed
1801 };
1802
1803 pg.wndproc_id = ids[type].wndproc_id;
1804 pg.dlg_id = ids[type].dlg_id;
1805
1806 cur_pages->add(&pg,sizeof(page));
1807
1808 cur_page = (page *)cur_pages->get() + cur_header->blocks[NB_PAGES].num++;
1809 cur_page_type = type;
1810
1811 set_code_type_predefines(ids[type].name);
1812 return PS_OK;
1813 }
1814
1815 int CEXEBuild::page_end()
1816 {
1817 cur_page = 0;
1818
1819 set_code_type_predefines();
1820 return PS_OK;
1821 }
1822 #endif
1823
1824 #ifdef NSIS_SUPPORT_VERSION_INFO
1825 int CEXEBuild::AddVersionInfo()
1826 {
1827 GrowBuf VerInfoStream;
1828
1829 // Should probably check for (4 & version_fixedflags) here, but VIProductVersion without VIAddVersionKey
1830 // fails silently, so VIFileVersion does the same...
1831 if ( rVersionInfo.GetStringTablesCount() > 0 )
1832 {
1833 if ( !(1 & version_fixedflags) )
1834 {
1835 ERROR_MSG(_T("Error: VIProductVersion is required when other version information functions are used.\n"));
1836 return PS_ERROR;
1837 }
1838 else
1839 {
1840 if ( !(2 & version_fixedflags) )
1841 {
1842 // This error string should match the one used by the TOK_VI_SETFILEVERSION handler
1843 ERROR_MSG(_T("Error: invalid %") NPRIs _T(" format, should be X.X.X.X\n"),_T("VIProductVersion"));
1844 return PS_ERROR;
1845 }
1846
1847 try
1848 {
1849 init_res_editor();
1850 for ( int i = 0; i < rVersionInfo.GetStringTablesCount(); i++ )
1851 {
1852 LANGID lang_id = rVersionInfo.GetLangID(i);
1853 int code_page = rVersionInfo.GetCodePage(i);
1854
1855 const TCHAR *lang_name = GetLangNameAndCPForVersionResource(lang_id, NULL, false);
1856
1857 const TCHAR *recverkeys =
1858 _T("FileVersion\0")
1859 _T("FileDescription\0")
1860 _T("LegalCopyright\0");
1861 for(;;)
1862 {
1863 if ( !*recverkeys ) break;
1864 if ( !rVersionInfo.FindKey(lang_id, code_page, recverkeys) )
1865 warning(DW_VI_MISSINGSTDKEY, _T("Generating version information for language \"%04d-%") NPRIs _T("\" without standard key \"%") NPRIs _T("\""), lang_id, lang_name, recverkeys);
1866 recverkeys += _tcsclen(recverkeys) + 1;
1867 }
1868
1869 rVersionInfo.ExportToStream(VerInfoStream, i);
1870 res_editor->UpdateResource(RT_VERSION, 1, lang_id, (BYTE*)VerInfoStream.get(), VerInfoStream.getlen());
1871 }
1872 }
1873 catch (exception& err) {
1874 ERROR_MSG(_T("Error adding version information: %") NPRIs _T("\n"), CtoTStrParam(err.what()));
1875 return PS_ERROR;
1876 }
1877 }
1878 }
1879
1880 return PS_OK;
1881 }
1882 #endif // NSIS_SUPPORT_VERSION_INFO
1883
1884 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
1885
1886 int CEXEBuild::ProcessPages()
1887 {
1888 SCRIPT_MSG(_T("Processing pages... "));
1889
1890 int license_normal=0;
1891 int license_fsrb=0;
1892 int license_fscb=0;
1893 int selcom=0;
1894 int dir=0;
1895 int uninstconfirm=0;
1896 int instlog=0, instlog_used;
1897 int main=0;
1898
1899 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
1900 again:
1901 #endif
1902
1903 instlog_used = 0;
1904
1905 #ifdef NSIS_CONFIG_SILENT_SUPPORT
1906 if ((cur_header->flags & (CH_FLAGS_SILENT|CH_FLAGS_SILENT_LOG)) == 0)
1907 #endif
1908 {
1909 main++;
1910
1911 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
1912 #define LS(inst, uninst) (uninstall_mode ? uninst : inst)
1913 #else
1914 #define LS(inst, uninst) inst
1915 #endif
1916
1917 DefineInnerLangString(NLF_BRANDING);
1918
1919 if (!cur_pages->getlen()) {
1920 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
1921 if (uninstall_mode) {
1922 if (HasUserDefined(NLF_UNINST_TEXT)) {
1923 add_page(PAGE_UNINSTCONFIRM);
1924 page_end();
1925 }
1926 add_page(PAGE_INSTFILES);
1927 page_end();
1928 add_page(PAGE_COMPLETED);
1929 page_end();
1930 }
1931 else
1932 #endif
1933 {
1934 #ifdef NSIS_CONFIG_LICENSEPAGE
1935 if (HasUserDefined(NLF_LICENSE_TEXT) && HasUserDefined(NLF_LICENSE_DATA)) {
1936 add_page(PAGE_LICENSE);
1937 page_end();
1938 }
1939 #endif
1940 #ifdef NSIS_CONFIG_COMPONENTPAGE
1941 if (HasUserDefined(NLF_COMP_TEXT)) {
1942 add_page(PAGE_COMPONENTS);
1943 page_end();
1944 }
1945 #endif
1946 if (HasUserDefined(NLF_DIR_TEXT)) {
1947 add_page(PAGE_DIRECTORY);
1948 page_end();
1949 }
1950 add_page(PAGE_INSTFILES);
1951 page_end();
1952 add_page(PAGE_COMPLETED);
1953 page_end();
1954 }
1955 }
1956 // start processing the pages
1957 {
1958 int i = 0;
1959 page *p = (page *) cur_pages->get();
1960
1961 for (i = 0; i < cur_header->blocks[NB_PAGES].num; i++, p++) {
1962 page *pp = 0;
1963
1964 if (i) {
1965 pp = p - 1;
1966
1967 // set back button
1968 p->flags |= PF_BACK_SHOW;
1969 if (pp->wndproc_id != PWP_COMPLETED && p->wndproc_id != PWP_COMPLETED && p->wndproc_id != PWP_INSTFILES)
1970 p->flags |= PF_BACK_ENABLE;
1971 if (!p->back)
1972 p->back = DefineInnerLangString(NLF_BTN_BACK);
1973
1974 // set previous page's next button
1975 if (!pp->next) {
1976 int str = 0;
1977
1978 #ifdef NSIS_CONFIG_LICENSEPAGE
1979 if (pp->wndproc_id == PWP_LICENSE && (!(pp->flags & PF_LICENSE_FORCE_SELECTION) || HasUserDefined(NLF_BTN_LICENSE)))
1980 str = NLF_BTN_LICENSE;
1981 else
1982 #endif
1983 if (p->wndproc_id == PWP_INSTFILES)
1984 str = LS(NLF_BTN_INSTALL, NLF_BTN_UNINSTALL);
1985 else
1986 str = NLF_BTN_NEXT;
1987
1988 pp->next = DefineInnerLangString(str);
1989 }
1990
1991 // set previous page's click next text
1992 if (!pp->clicknext) {
1993 int str = 0;
1994
1995 if (p->wndproc_id == PWP_INSTFILES)
1996 str = LS(NLF_CLICK_INSTALL, NLF_CLICK_UNINSTALL);
1997 else
1998 str = NLF_CLICK_NEXT;
1999
2000 pp->clicknext = DefineInnerLangString(str);
2001 }
2002 }
2003
2004 // enable next button
2005 if (p->wndproc_id != PWP_INSTFILES)
2006 p->flags |= PF_NEXT_ENABLE;
2007
2008 // set cancel button
2009 if (!p->cancel)
2010 p->cancel = DefineInnerLangString(NLF_BTN_CANCEL);
2011 if (p->wndproc_id != PWP_INSTFILES && p->wndproc_id != PWP_COMPLETED)
2012 p->flags |= PF_CANCEL_ENABLE;
2013
2014 // set caption
2015 struct {
2016 int caption;
2017 int ucaption;
2018 } captions[] = {
2019 #ifdef NSIS_CONFIG_LICENSEPAGE
2020 {NLF_SUBCAPTION_LICENSE, NLF_SUBCAPTION_LICENSE},
2021 #endif
2022 #ifdef NSIS_CONFIG_COMPONENTPAGE
2023 {NLF_SUBCAPTION_OPTIONS, NLF_SUBCAPTION_OPTIONS},
2024 #endif
2025 {NLF_SUBCAPTION_DIR, NLF_SUBCAPTION_DIR},
2026 {NLF_SUBCAPTION_INSTFILES, NLF_USUBCAPTION_INSTFILES},
2027 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
2028 {NLF_USUBCAPTION_CONFIRM, NLF_USUBCAPTION_CONFIRM},
2029 #endif
2030 {NLF_SUBCAPTION_COMPLETED, NLF_USUBCAPTION_COMPLETED}
2031 };
2032
2033 if (!p->caption && p->wndproc_id != PWP_CUSTOM) {
2034 p->caption = DefineInnerLangString(LS(captions[p->wndproc_id].caption, captions[p->wndproc_id].ucaption));
2035 }
2036
2037 // set texts
2038 switch (p->dlg_id) {
2039 #ifdef NSIS_CONFIG_LICENSEPAGE
2040 case IDD_LICENSE:
2041 case IDD_LICENSE_FSRB:
2042 case IDD_LICENSE_FSCB:
2043 {
2044 if (!(p->flags & PF_PAGE_EX))
2045 p->dlg_id = license_res_id;
2046 if (!(p->flags & (PF_LICENSE_FORCE_SELECTION | PF_LICENSE_NO_FORCE_SELECTION)))
2047 p->dlg_id = license_res_id;
2048
2049 p->flags |= PF_NO_NEXT_FOCUS;
2050
2051 if (!p->parms[1])
2052 p->parms[1] = DefineInnerLangString(NLF_LICENSE_DATA, 0);
2053
2054 if (p->dlg_id == IDD_LICENSE) {
2055 if (!p->parms[0])
2056 p->parms[0] = DefineInnerLangString(LS(NLF_LICENSE_TEXT, NLF_ULICENSE_TEXT));
2057
2058 license_normal++;
2059 }
2060 else if (p->dlg_id == IDD_LICENSE_FSCB) {
2061 p->flags |= PF_LICENSE_FORCE_SELECTION;
2062
2063 if (!p->parms[0])
2064 p->parms[0] = DefineInnerLangString(LS(NLF_LICENSE_TEXT_FSCB, NLF_ULICENSE_TEXT_FSCB));
2065 if (!p->parms[2])
2066 p->parms[2] = DefineInnerLangString(NLF_BTN_LICENSE_AGREE);
2067
2068 license_fscb++;
2069 }
2070 else if (p->dlg_id == IDD_LICENSE_FSRB) {
2071 p->flags |= PF_LICENSE_FORCE_SELECTION;
2072
2073 if (!p->parms[0])
2074 p->parms[0] = DefineInnerLangString(LS(NLF_LICENSE_TEXT_FSRB, NLF_ULICENSE_TEXT_FSRB));
2075 if (!p->parms[2])
2076 p->parms[2] = DefineInnerLangString(NLF_BTN_LICENSE_AGREE);
2077 if (!p->parms[3])
2078 p->parms[3] = DefineInnerLangString(NLF_BTN_LICENSE_DISAGREE);
2079
2080 license_fsrb++;
2081 }
2082 break;
2083 }
2084 #endif
2085 #ifdef NSIS_CONFIG_COMPONENTPAGE
2086 case IDD_SELCOM:
2087 {
2088 if (!p->parms[0])
2089 p->parms[0] = DefineInnerLangString(LS(NLF_COMP_TEXT, NLF_UCOMP_TEXT));
2090 if (!p->parms[1])
2091 p->parms[1] = DefineInnerLangString(LS(NLF_COMP_SUBTEXT1, NLF_UCOMP_SUBTEXT1));
2092 if (!p->parms[2])
2093 p->parms[2] = DefineInnerLangString(LS(NLF_COMP_SUBTEXT2, NLF_UCOMP_SUBTEXT2));
2094 if (!p->parms[3] && !uninstall_mode && HasUserDefined(NLF_COMP_SUBTEXT1))
2095 p->parms[3] = p->parms[1];
2096 if (!p->parms[4] && !uninstall_mode && HasUserDefined(NLF_COMP_SUBTEXT2))
2097 p->parms[4] = p->parms[2];
2098 else if (!p->parms[4])
2099 p->parms[4] = DefineInnerLangString(LS(NLF_COMP_SUBTEXT1_NO_INST_TYPES, NLF_UCOMP_SUBTEXT1_NO_INST_TYPES));
2100
2101 DefineInnerLangString(NLF_SPACE_REQ);
2102 DefineInnerLangString(NLF_BYTE);
2103 DefineInnerLangString(NLF_KILO);
2104 DefineInnerLangString(NLF_MEGA);
2105 DefineInnerLangString(NLF_GIGA);
2106
2107 selcom++;
2108 break;
2109 }
2110 #endif
2111 case IDD_DIR:
2112 {
2113 if (!p->parms[0])
2114 p->parms[0] = DefineInnerLangString(LS(NLF_DIR_TEXT, NLF_UDIR_TEXT));
2115 if (!p->parms[1])
2116 p->parms[1] = DefineInnerLangString(LS(NLF_DIR_SUBTEXT, NLF_UDIR_SUBTEXT));
2117 if (!p->parms[2])
2118 p->parms[2] = DefineInnerLangString(NLF_BTN_BROWSE);
2119 if (!p->parms[3])
2120 p->parms[3] = DefineInnerLangString(LS(NLF_DIR_BROWSETEXT, NLF_UDIR_BROWSETEXT));
2121 if (!p->parms[4])
2122 p->parms[4] = m_UserVarNames.get(_T("INSTDIR"));
2123 else
2124 p->parms[4]--;
2125
2126 DefineInnerLangString(NLF_SPACE_AVAIL);
2127 DefineInnerLangString(NLF_SPACE_REQ);
2128 DefineInnerLangString(NLF_BYTE);
2129 DefineInnerLangString(NLF_KILO);
2130 DefineInnerLangString(NLF_MEGA);
2131 DefineInnerLangString(NLF_GIGA);
2132 #ifdef NSIS_CONFIG_LOG
2133 DefineInnerLangString(NLF_LOG_INSTALL_PROCESS);
2134 #endif
2135
2136 dir++;
2137 break;
2138 }
2139 case IDD_INSTFILES:
2140 {
2141 if (!p->parms[1])
2142 p->parms[1] = DefineInnerLangString(NLF_BTN_DETAILS);
2143 if (!p->parms[2])
2144 p->parms[2] = DefineInnerLangString(NLF_COMPLETED);
2145
2146 DefineInnerLangString(NLF_COPY_DETAILS);
2147
2148 instlog++;
2149 instlog_used++;
2150 break;
2151 }
2152 case IDD_UNINST:
2153 {
2154 if (!p->parms[0])
2155 p->parms[0] = DefineInnerLangString(NLF_UNINST_TEXT);
2156 if (!p->parms[1])
2157 p->parms[1] = DefineInnerLangString(NLF_UNINST_SUBTEXT);
2158 if (!p->parms[4])
2159 p->parms[4] = m_UserVarNames.get(_T("INSTDIR"));
2160 else
2161 p->parms[4]--;
2162
2163 uninstconfirm++;
2164 break;
2165 }
2166 }
2167
2168 p->flags &= ~PF_PAGE_EX;
2169 }
2170
2171 p--;
2172
2173 if (!p->next)
2174 p->next = DefineInnerLangString(NLF_BTN_CLOSE);
2175 if (p->wndproc_id == PWP_COMPLETED)
2176 (p-1)->next = DefineInnerLangString(NLF_BTN_CLOSE);
2177
2178 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
2179 if (uninstall_mode) {
2180 if (!uenable_last_page_cancel && instlog_used)
2181 p->flags &= ~PF_CANCEL_ENABLE;
2182 }
2183 else
2184 #endif
2185 {
2186 if (!enable_last_page_cancel && instlog_used)
2187 p->flags &= ~PF_CANCEL_ENABLE;
2188 }
2189
2190 if (!instlog_used) {
2191 warning(DW_INSTFILESPAGE_NOT_USED, _T("%") NPRIs _T("age instfiles not used, no sections will be executed!"), uninstall_mode ? _T("Uninstall p") : _T("P"));
2192 }
2193 }
2194 }
2195
2196 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
2197 if (!uninstall_mode) {
2198 set_uninstall_mode(1);
2199 goto again;
2200 }
2201 else
2202 set_uninstall_mode(0);
2203 #endif//NSIS_CONFIG_UNINSTALL_SUPPORT
2204
2205
2206 SCRIPT_MSG(_T("Done!\n"));
2207
2208 #define REMOVE_ICON(id) if (disable_window_icon) { \
2209 BYTE* dlg = res_editor->GetResource(RT_DIALOG, id, NSIS_DEFAULT_LANG); \
2210 if (dlg) { \
2211 CDialogTemplate dt(dlg,build_unicode,uDefCodePage); \
2212 res_editor->FreeResource(dlg); \
2213 if (dt.RemoveItem(IDC_ULICON)) { \
2214 DialogItemTemplate* text = dt.GetItem(IDC_INTROTEXT); \
2215 DialogItemTemplate* prog = dt.GetItem(IDC_PROGRESS); \
2216 if (text) { \
2217 text->sWidth += text->sX; \
2218 text->sX = 0; \
2219 } \
2220 if (prog) { \
2221 prog->sWidth += prog->sX; \
2222 prog->sX = 0; \
2223 } \
2224 \
2225 DWORD dwSize; \
2226 dlg = dt.Save(dwSize); \
2227 res_editor->UpdateResource(RT_DIALOG, id, NSIS_DEFAULT_LANG, dlg, dwSize); \
2228 dt.FreeSavedTemplate(dlg); \
2229 } \
2230 } \
2231 }
2232
2233 try {
2234 SCRIPT_MSG(_T("Removing unused resources... "));
2235 init_res_editor();
2236 #ifdef NSIS_CONFIG_LICENSEPAGE
2237 if (!license_normal) {
2238 res_editor->UpdateResource(RT_DIALOG, IDD_LICENSE, NSIS_DEFAULT_LANG, 0, 0);
2239 }
2240 else REMOVE_ICON(IDD_LICENSE);
2241 if (!license_fsrb) {
2242 res_editor->UpdateResource(RT_DIALOG, IDD_LICENSE_FSRB, NSIS_DEFAULT_LANG, 0, 0);
2243 }
2244 else REMOVE_ICON(IDD_LICENSE_FSRB);
2245 if (!license_fscb) {
2246 res_editor->UpdateResource(RT_DIALOG, IDD_LICENSE_FSCB, NSIS_DEFAULT_LANG, 0, 0);
2247 }
2248 else REMOVE_ICON(IDD_LICENSE_FSCB);
2249 #endif // NSIS_CONFIG_LICENSEPAGE
2250 #ifdef NSIS_CONFIG_COMPONENTPAGE
2251 if (!selcom) {
2252 res_editor->UpdateResource(RT_DIALOG, IDD_SELCOM, NSIS_DEFAULT_LANG, 0, 0);
2253 res_editor->UpdateResource(RT_BITMAP, IDB_BITMAP1, NSIS_DEFAULT_LANG, 0, 0);
2254 }
2255 else REMOVE_ICON(IDD_SELCOM);
2256 #endif // NSIS_CONFIG_COMPONENTPAGE
2257 if (!dir) {
2258 res_editor->UpdateResource(RT_DIALOG, IDD_DIR, NSIS_DEFAULT_LANG, 0, 0);
2259 }
2260 else REMOVE_ICON(IDD_DIR);
2261 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
2262 if (!uninstconfirm) {
2263 res_editor->UpdateResource(RT_DIALOG, IDD_UNINST, NSIS_DEFAULT_LANG, 0, 0);
2264 }
2265 else REMOVE_ICON(IDD_UNINST);
2266 #endif // NSIS_CONFIG_UNINSTALL_SUPPORT
2267 if (!instlog) {
2268 res_editor->UpdateResource(RT_DIALOG, IDD_INSTFILES, NSIS_DEFAULT_LANG, 0, 0);
2269 }
2270 else REMOVE_ICON(IDD_INSTFILES);
2271 if (!main) {
2272 res_editor->UpdateResource(RT_DIALOG, IDD_INST, NSIS_DEFAULT_LANG, 0, 0);
2273 if (!build_compress_whole && !build_crcchk)
2274 res_editor->UpdateResource(RT_DIALOG, IDD_VERIFY, NSIS_DEFAULT_LANG, 0, 0);
2275 }
2276
2277 SCRIPT_MSG(_T("Done!\n"));
2278 }
2279 catch (exception& err) {
2280 ERROR_MSG(_T("\nError: %") NPRIs _T("\n"), CtoTStrParam(err.what()));
2281 return PS_ERROR;
2282 }
2283
2284 return PS_OK;
2285 }
2286 #endif // NSIS_CONFIG_VISIBLE_SUPPORT
2287
2288 #ifdef NSIS_CONFIG_COMPONENTPAGE
2289 void CEXEBuild::PrepareInstTypes()
2290 {
2291 if (!(cur_header->flags & CH_FLAGS_NO_CUSTOM))
2292 cur_header->install_types[NSIS_MAX_INST_TYPES] = DefineInnerLangString(NLF_COMP_CUSTOM);
2293
2294 // set insttype list for RO sections that didn't use SectionIn
2295 int i = cur_header->blocks[NB_SECTIONS].num;
2296 section *sections = (section *) cur_sections->get();
2297
2298 while (i--)
2299 {
2300 if (sections[i].flags & SF_RO && !sections[i].install_types)
2301 sections[i].install_types = ~0;
2302 }
2303
2304 // set selection to first insttype
2305 if (cur_header->install_types[0])
2306 {
2307 int i = cur_header->blocks[NB_SECTIONS].num;
2308 section *sections = (section *) cur_sections->get();
2309
2310 // if /o was used abort since the user did his manual choice
2311 while (i--)
2312 if ((sections[i].flags & SF_SELECTED) == 0)
2313 return;
2314
2315 i = cur_header->blocks[NB_SECTIONS].num;
2316
2317 while (i--)
2318 if ((sections[i].install_types & 1) == 0)
2319 sections[i].flags &= ~SF_SELECTED;
2320 }
2321 }
2322 #endif
2323
2324 void CEXEBuild::AddStandardStrings()
2325 {
2326 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
2327 if (uninstall_mode)
2328 {
2329 cur_header->str_uninstchild = add_asciistring(_T("$TEMP\\Un.exe"));
2330 cur_header->str_uninstcmd = add_asciistring(_T("\"$TEMP\\Un.exe\" $0 _?=$INSTDIR\\"));
2331 }
2332 #endif//NSIS_CONFIG_UNINSTALL_SUPPORT
2333 #ifdef NSIS_SUPPORT_MOVEONREBOOT
2334 cur_header->str_wininit = is_target_64bit() ? 0 : add_asciistring(_T("$WINDIR\\wininit.ini"));
2335 #endif//NSIS_SUPPORT_MOVEONREBOOT
2336 }
2337
2338 writer_target_info CEXEBuild::mk_writer_target_info() { return writer_target_info(build_unicode, is_target_64bit()); }
2339
2340 void CEXEBuild::PrepareHeaders(IGrowBuf *hdrbuf)
2341 {
2342 const writer_target_info ti = mk_writer_target_info();
2343 const unsigned int cbHdr = get_header_size();
2344 GrowBuf blocks_buf;
2345 growbuf_writer_sink sink(&blocks_buf, ti);
2346
2347 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
2348 cur_header->blocks[NB_PAGES].offset = cbHdr + blocks_buf.getlen();
2349 page_writer::write_block(cur_pages, &sink);
2350 #endif
2351
2352 cur_header->blocks[NB_SECTIONS].offset = cbHdr + blocks_buf.getlen();
2353 section_writer::write_block(cur_sections, &sink);
2354
2355 cur_header->blocks[NB_ENTRIES].offset = cbHdr + blocks_buf.getlen();
2356 entry_writer::write_block(cur_entries, &sink);
2357
2358 cur_header->blocks[NB_STRINGS].offset = cbHdr + blocks_buf.getlen();
2359 blocks_buf.add(cur_strlist->getstorageptr(), cur_strlist->gettotalsize());
2360
2361 cur_header->blocks[NB_LANGTABLES].offset = cbHdr + blocks_buf.getlen();
2362 lang_table_writer::write_block(cur_langtables, &sink, cur_header->langtable_size);
2363
2364 cur_header->blocks[NB_CTLCOLORS].offset = cbHdr + blocks_buf.getlen();
2365 ctlcolors_writer::write_block(cur_ctlcolors, &sink);
2366
2367 #ifdef NSIS_SUPPORT_BGBG
2368 if (cur_header->bg_color1 != -1)
2369 {
2370 bg_font.lfFaceName[LF_FACESIZE-1] = 0;
2371
2372 cur_header->blocks[NB_BGFONT].offset = cbHdr + blocks_buf.getlen();
2373
2374 LOGFONT_writer w(&sink);
2375 w.write(&bg_font);
2376 }
2377 #endif
2378
2379 growbuf_writer_sink sink2(hdrbuf, ti);
2380 header_writer header(&sink2);
2381 header.write(cur_header, ti);
2382
2383 sink2.write_growbuf(&blocks_buf);
2384 }
2385
2386 int CEXEBuild::SetVarsSection()
2387 {
2388 try {
2389 init_res_editor();
2390
2391 VerifyDeclaredUserVarRefs(&m_UserVarNames);
2392 int MaxUserVars = m_UserVarNames.getnum();
2393 int stringSize = NSIS_MAX_STRLEN * (build_unicode?2:1);
2394 if (!res_editor->SetPESectionVirtualSize(NSIS_VARS_SECTION, MaxUserVars * stringSize))
2395 {
2396 ERROR_MSG(_T("Internal compiler error #12346: invalid exehead cannot find section \"%") NPRIs _T("\"!\n"), _T(NSIS_VARS_SECTION));
2397 return PS_ERROR;
2398 }
2399 }
2400 catch (exception& err) {
2401 ERROR_MSG(_T("\nError: %") NPRIs _T("\n"), CtoTStrParam(err.what()));
2402 return PS_ERROR;
2403 }
2404
2405 return PS_OK;
2406 }
2407
2408 int CEXEBuild::SetManifest()
2409 {
2410 try {
2411 init_res_editor();
2412 manifest::SPECIFICATION spec = { (manifest::flags) manifest_flags, manifest_dpiaware, manifest_dpiawareness.c_str(), manifest_lpaware, &manifest_sosl, manifest_maxversiontested.c_str() };
2413 string manifest = manifest::generate(manifest_comctl, manifest_exec_level, spec);
2414
2415 if (manifest == "")
2416 return PS_OK;
2417
2418 if (!build_unicode && manifest_lpaware >= manifest::lpaware_true)
2419 throw std::runtime_error("Incompatible option");
2420
2421 // TODO: Ideally we should allow this but we must be sure that the manifest is custom and not a manifest from the stub
2422 //if (res_editor->ResourceExists(MAKEINTRESOURCE(24), 1, CResourceEditor::ANYLANGID))
2423 // return PS_OK; // Allow user to completely override the manifest with PEAddResource
2424
2425 // Saved directly as binary into the exe.
2426 res_editor->UpdateResource(MAKEINTRESOURCE(24), 1, NSIS_DEFAULT_LANG, (LPBYTE) const_cast<char*>(manifest.c_str()), (DWORD) manifest.length());
2427 }
2428 catch (exception& err) {
2429 ERROR_MSG(_T("Error setting manifest: %") NPRIs _T("\n"), CtoTStrParam(err.what()));
2430 return PS_ERROR;
2431 }
2432
2433 return PS_OK;
2434 }
2435
2436 int CEXEBuild::UpdatePEHeader()
2437 {
2438 try {
2439 PIMAGE_NT_HEADERS headers = CResourceEditor::GetNTHeaders(m_exehead);
2440 // workaround for bug #2697027, #2725883, #2803097
2441 *GetCommonMemberFromPEOptHdr(headers->OptionalHeader, MajorImageVersion) = FIX_ENDIAN_INT16(6);
2442 *GetCommonMemberFromPEOptHdr(headers->OptionalHeader, MinorImageVersion) = FIX_ENDIAN_INT16(0);
2443 // Override SubsystemVersion?
2444 if (PESubsysVerMaj != (WORD) -1)
2445 {
2446 *GetCommonMemberFromPEOptHdr(headers->OptionalHeader, MajorSubsystemVersion) = FIX_ENDIAN_INT16(PESubsysVerMaj);
2447 *GetCommonMemberFromPEOptHdr(headers->OptionalHeader, MinorSubsystemVersion) = FIX_ENDIAN_INT16(PESubsysVerMin);
2448 }
2449 // DllCharacteristics
2450 *GetCommonMemberFromPEOptHdr(headers->OptionalHeader, DllCharacteristics) = FIX_ENDIAN_INT16(PEDllCharacteristics);
2451 } catch (std::runtime_error& err) {
2452 ERROR_MSG(_T("Error updating PE headers: %") NPRIs _T("\n"), CtoTStrParam(err.what()));
2453 return PS_ERROR;
2454 }
2455
2456 return PS_OK;
2457 }
2458
2459 void CEXEBuild::set_default_output_filename(const tstring& filename)
2460 {
2461 if (build_output_filename[0] == 0)
2462 my_strncpy(build_output_filename,filename.c_str(),COUNTOF(build_output_filename));
2463 }
2464
2465 int CEXEBuild::check_write_output_errors() const
2466 {
2467 if (has_called_write_output)
2468 {
2469 ERROR_MSG(_T("Error (write_output): write_output already called, can't continue\n"));
2470 return PS_ERROR;
2471 }
2472
2473 if (!build_output_filename[0])
2474 {
2475 ERROR_MSG(_T("Error: invalid script: never had OutFile command\n"));
2476 return PS_ERROR;
2477 }
2478
2479 if (!build_sections.getlen())
2480 {
2481 ERROR_MSG(_T("Error: invalid script: no sections specified\n"));
2482 return PS_ERROR;
2483 }
2484
2485 if (!build_entries.getlen())
2486 {
2487 ERROR_MSG(_T("Error: invalid script: no entries specified\n"));
2488 return PS_ERROR;
2489 }
2490
2491 if (build_cursection)
2492 {
2493 ERROR_MSG(_T("Error: Section left open at EOF\n"));
2494 return PS_ERROR;
2495 }
2496
2497 if (sectiongroup_open_cnt)
2498 {
2499 ERROR_MSG(_T("Error: SectionGroup left open at EOF\n"));
2500 return PS_ERROR;
2501 }
2502
2503 if (cur_page)
2504 {
2505 ERROR_MSG(_T("Error: PageEx left open at EOF\n"));
2506 return PS_ERROR;
2507 }
2508
2509 // deal with functions, for both install and uninstall modes.
2510 if (build_cursection_isfunc)
2511 {
2512 ERROR_MSG(_T("Error: Function left open at EOF\n"));
2513 return PS_ERROR;
2514 }
2515
2516 return PS_OK;
2517 }
2518
2519 int CEXEBuild::prepare_uninstaller() {
2520 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
2521 if (ubuild_entries.getlen())
2522 {
2523 if (!uninstaller_writes_used)
2524 {
2525 warning(DW_UNCODE_WITHOUT_UNEXE, _T("Uninstaller script code found but WriteUninstaller never used - no uninstaller will be created."));
2526 return PS_OK;
2527 }
2528
2529 build_uninst.flags|=build_header.flags&(CH_FLAGS_PROGRESS_COLORED|CH_FLAGS_NO_ROOT_DIR);
2530
2531 set_uninstall_mode(1);
2532
2533 DefineInnerLangString(NLF_UCAPTION);
2534
2535 if (resolve_coderefs(_T("uninstall")))
2536 return PS_ERROR;
2537
2538 #ifdef NSIS_CONFIG_COMPONENTPAGE
2539 // set sections to the first insttype
2540 PrepareInstTypes();
2541 #endif
2542
2543 // Add standard strings to string table
2544 AddStandardStrings();
2545
2546 set_uninstall_mode(0);
2547 }
2548 else if (uninstaller_writes_used)
2549 {
2550 ERROR_MSG(_T("Error: no Uninstall section specified, but WriteUninstaller used %d time(s)\n"),uninstaller_writes_used);
2551 return PS_ERROR;
2552 }
2553 #endif//NSIS_CONFIG_UNINSTALL_SUPPORT
2554 return PS_OK;
2555 }
2556
2557 int CEXEBuild::pack_exe_header()
2558 {
2559 if (!(build_packname[0] && build_packcmd[0])) {
2560 // header not asked to be packed
2561 return PS_OK;
2562 }
2563
2564 // write out exe header, pack, read back in, and
2565 // update the header info
2566 if (m_exehead_size != write_octets_to_file(build_packname, m_exehead, m_exehead_size))
2567 {
2568 ERROR_MSG(_T("Error: writing temporary file \"%") NPRIs _T("\" for pack\n"),build_packname);
2569 return PS_ERROR;
2570 }
2571 int ec = sane_system(build_packcmd);
2572 if (ec == -1)
2573 {
2574 _tremove(build_packname);
2575 ERROR_MSG(_T("Error: calling packer on \"%") NPRIs _T("\"\n"),build_packname);
2576 return PS_ERROR;
2577 }
2578 if (ec != 0)
2579 warning(DW_PACKHDR_RETNONZERO, _T("Packer returned %d, \"%") NPRIs _T("\" might still be unpacked\n"),ec,build_packname);
2580
2581 int result = update_exehead(build_packname);
2582 _tremove(build_packname);
2583
2584 if (result != PS_OK)
2585 {
2586 ERROR_MSG(_T("Error: reading temporary file \"%") NPRIs _T("\" after pack\n"),build_packname);
2587 return result;
2588 }
2589
2590 return PS_OK;
2591 }
2592
2593 int CEXEBuild::write_output(void)
2594 {
2595 #ifndef NSIS_CONFIG_CRC_SUPPORT
2596 build_crcchk=0;
2597 #endif
2598
2599 RET_UNLESS_OK( check_write_output_errors() );
2600
2601 has_called_write_output=true;
2602 if (!changed_target && !build_unicode)
2603 warning(DW_GENERIC_DEPRECATED, _T("ANSI targets are deprecated"));
2604
2605 #ifdef NSIS_CONFIG_PLUGIN_SUPPORT
2606 RET_UNLESS_OK( add_plugins_dir_initializer() );
2607 #endif //NSIS_CONFIG_PLUGIN_SUPPORT
2608
2609 #ifdef NSIS_SUPPORT_VERSION_INFO
2610 RET_UNLESS_OK( AddVersionInfo() );
2611 #endif //NSIS_SUPPORT_VERSION_INFO
2612
2613 RET_UNLESS_OK( prepare_uninstaller() );
2614
2615 DefineInnerLangString(NLF_CAPTION);
2616 if (resolve_coderefs(_T("install")))
2617 return PS_ERROR;
2618
2619 #ifdef NSIS_CONFIG_COMPONENTPAGE
2620 // set sections to the first insttype
2621 PrepareInstTypes();
2622 #endif
2623
2624 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
2625 RET_UNLESS_OK( ProcessPages() );
2626 #endif //NSIS_CONFIG_VISIBLE_SUPPORT
2627
2628 // Generate language tables
2629 RET_UNLESS_OK( GenerateLangTables() );
2630
2631 // Setup user variables PE section
2632 RET_UNLESS_OK( SetVarsSection() );
2633
2634 // Set XML manifest
2635 RET_UNLESS_OK( SetManifest() );
2636
2637 // Add standard strings to string table
2638 AddStandardStrings();
2639
2640 try {
2641 // Load icon from exe, if needed
2642 if (installer_icon.empty())
2643 {
2644 init_res_editor();
2645 installer_icon = load_icon_res(res_editor, IDI_ICON2);
2646 }
2647
2648 // Set icon
2649 set_main_icon(res_editor, IDI_ICON2, installer_icon, uninstaller_icon);
2650
2651 // Save all changes to the exe header
2652 close_res_editor();
2653 }
2654 catch (exception& err) {
2655 ERROR_MSG(_T("\nError: %") NPRIs _T("\n"), CtoTStrParam(err.what()));
2656 return PS_ERROR;
2657 }
2658
2659 // Final PE touch-ups
2660 RET_UNLESS_OK( UpdatePEHeader() );
2661
2662 RET_UNLESS_OK( pack_exe_header() );
2663
2664
2665 build_optimize_datablock=0;
2666
2667 UINT data_block_size_before_uninst = build_datablock.getlen();
2668
2669 RET_UNLESS_OK( uninstall_generate() );
2670
2671 unsigned char limit = 0; // Limit the number of retries in case the host has some kind of bug
2672 retry_output:
2673 {
2674 tstring full_path = get_full_path(build_output_filename), fnamebuf = get_file_name(build_output_filename);
2675 notify(MakensisAPI::NOTIFY_OUTPUT, full_path.c_str());
2676 INFO_MSG(_T("\nOutput: \"%") NPRIs _T("\"\n"), full_path.c_str());
2677 const TCHAR *fname = fnamebuf.c_str();
2678 // Warn when special compatibility names are used. See also: http://github.com/wixtoolset/wix4/commit/3f4341b8ac4d13dffb1d6ba773d48ccc0ab07cf8
2679 if (!_tcsicmp(fname, _T("setup.exe")))
2680 {
2681 const bool orgdispwarn = display_warnings;
2682 display_warnings = false; // Don't display warning inline in the middle of our statistics output.
2683 warning(DW_INSECURE_OUTFILENAME, _T("Insecure filename \"%") NPRIs _T("\", Windows will unsafely load compatibility shims into the process."), fname);
2684 display_warnings = orgdispwarn;
2685 }
2686 }
2687
2688 FILE *fp = FOPEN(build_output_filename,("w+b"));
2689 if (!fp)
2690 {
2691 ERROR_MSG(_T("Can't open output file\n"));
2692 if (++limit && prompt_for_output_path(build_output_filename, COUNTOF(CEXEBuild::build_output_filename))) goto retry_output;
2693 return PS_ERROR;
2694 }
2695
2696 if (fwrite(m_exehead,1,m_exehead_size,fp) != m_exehead_size)
2697 {
2698 ERROR_MSG(_T("Error: can't write %d bytes to output\n"),m_exehead_size);
2699 fclose(fp);
2700 return PS_ERROR;
2701 }
2702
2703 crc32_t crc=0;
2704 #ifdef NSIS_CONFIG_CRC_SUPPORT
2705 #ifdef NSIS_CONFIG_CRC_ANAL
2706 crc=CRC32(crc,m_exehead,(DWORD)m_exehead_size);
2707 #else
2708 crc=CRC32(crc,m_exehead+512,(DWORD)m_exehead_size-512);
2709 #endif
2710 #endif
2711
2712 firstheader fh={0,};
2713 fh.nsinst[0]=FH_INT1;
2714 fh.nsinst[1]=FH_INT2;
2715 fh.nsinst[2]=FH_INT3;
2716
2717 #ifdef NSIS_CONFIG_CRC_SUPPORT
2718 fh.flags=(build_crcchk?(build_crcchk==2?FH_FLAGS_FORCE_CRC:0):FH_FLAGS_NO_CRC);
2719 #else
2720 fh.flags=0;
2721 #endif
2722 #ifdef NSIS_CONFIG_SILENT_SUPPORT
2723 if (build_header.flags&(CH_FLAGS_SILENT|CH_FLAGS_SILENT_LOG)) fh.flags |= FH_FLAGS_SILENT;
2724 #endif
2725 fh.siginfo=FH_SIG;
2726
2727 int installinfo_compressed;
2728 int fd_start = 0;
2729
2730 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
2731 if (build_compress_whole)
2732 {
2733 int n = compressor->Init(build_compress_level, build_compress_dict_size);
2734 if (n != C_OK)
2735 {
2736 ERROR_MSG(_T("Internal compiler error #12345: deflateInit() failed(%") NPRIs _T(" [%d]).\n"), compressor->GetErrStr(n), n);
2737 return PS_ERROR;
2738 }
2739 }
2740 #endif
2741
2742 {
2743 GrowBuf ihd;
2744 {
2745 GrowBuf hdrcomp;
2746
2747 PrepareHeaders(&hdrcomp);
2748
2749 if (add_data((char*)hdrcomp.get(),hdrcomp.getlen(),&ihd) < 0)
2750 return PS_ERROR;
2751
2752 fh.length_of_header=hdrcomp.getlen();
2753 installinfo_compressed=ihd.getlen();
2754 }
2755
2756 if (!build_compress_whole)
2757 fh.length_of_all_following_data=ihd.getlen()+build_datablock.getlen()+(int)sizeof(firstheader)+(build_crcchk?sizeof(crc32_t):0);
2758 else
2759 fd_start=ftell(fp);
2760
2761 try
2762 {
2763 file_writer_sink sink(fp, mk_writer_target_info());
2764 firstheader_writer w(&sink);
2765 w.write(&fh);
2766 }
2767 catch (...)
2768 {
2769 ERROR_MSG(_T("Error: can't write %d bytes to output\n"),sizeof(fh));
2770 fclose(fp);
2771 return PS_ERROR;
2772 }
2773
2774 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
2775 if (build_compress_whole) {
2776 if (deflateToFile(fp,(char*)ihd.get(),ihd.getlen()))
2777 {
2778 fclose(fp);
2779 return PS_ERROR;
2780 }
2781 }
2782 else
2783 #endif
2784 {
2785 if (fwrite(ihd.get(),1,ihd.getlen(),fp) != (unsigned int)ihd.getlen())
2786 {
2787 ERROR_MSG(_T("Error: can't write %d bytes to output\n"),ihd.getlen());
2788 fclose(fp);
2789 return PS_ERROR;
2790 }
2791 #ifdef NSIS_CONFIG_CRC_SUPPORT
2792 crc_writer_sink crc_sink((crc32_t *) &crc);
2793 firstheader_writer w(&crc_sink);
2794 w.write(&fh);
2795
2796 crc=CRC32(crc,(unsigned char*)ihd.get(),ihd.getlen());
2797 #endif
2798 }
2799 }
2800
2801 INFO_MSG(_T("Install: "));
2802 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
2803 int np=build_header.blocks[NB_PAGES].num;
2804 if (PAGE_COMPLETED != PAGE_INSTFILES && np) --np; // Special page not part of count
2805 INFO_MSG(_T("%d page%") NPRIs _T(" (%d bytes), "),np,np==1?_T(""):_T("s"),np*sizeof(page));
2806 #endif
2807 #define IsRequiredSection(s) ( (!(s).name_ptr && ((s).flags & SF_SELECTED)) || (((s).flags & (SF_RO|SF_SELECTED)) == (SF_RO|SF_SELECTED)))
2808 {
2809 int ns=build_sections.getlen()/sizeof(section), x;
2810 section *s=(section*)build_sections.get();
2811 unsigned int req=0;
2812 for (x = 0; x < ns; x ++) if (IsRequiredSection(s[x])) ++req;
2813 INFO_MSG(_T("%d section%") NPRIs,ns,ns==1?_T(""):_T("s"));
2814 if (req) INFO_MSG(_T(" (%u required)"),req);
2815 INFO_MSG(_T(" (%d bytes), "), build_sections.getlen());
2816 }
2817 int ne=build_header.blocks[NB_ENTRIES].num;
2818 INFO_MSG(_T("%d instruction%") NPRIs _T(" (%d bytes), "),ne,ne==1?_T(""):_T("s"),ne*sizeof(entry));
2819 int ns=build_strlist.getnum();
2820 INFO_MSG(_T("%d string%") NPRIs _T(" (%d bytes), "),ns,ns==1?_T(""):_T("s"),build_strlist.gettotalsize());
2821 int nlt=build_header.blocks[NB_LANGTABLES].num;
2822 INFO_MSG(_T("%d language table%") NPRIs _T(" (%d bytes).\n"),nlt,nlt==1?_T(""):_T("s"),build_langtables.getlen());
2823 if (ubuild_entries.getlen())
2824 {
2825 INFO_MSG(_T("Uninstall: "));
2826 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
2827 np=build_uninst.blocks[NB_PAGES].num;
2828 if (PAGE_COMPLETED != PAGE_INSTFILES && np) --np; // Special page not part of count
2829 INFO_MSG(_T("%d page%") NPRIs _T(" (%d bytes), "),np,np==1?_T(""):_T("s"),ubuild_pages.getlen());
2830 #endif
2831 {
2832 int ns=ubuild_sections.getlen()/sizeof(section), x;
2833 section *s=(section*)ubuild_sections.get();
2834 unsigned int req=0;
2835 for (x = 0; x < ns; x ++) if (IsRequiredSection(s[x])) ++req;
2836 INFO_MSG(_T("%d section%") NPRIs,ns,ns==1?_T(""):_T("s"));
2837 if (req) INFO_MSG(_T(" (%u required)"),req);
2838 INFO_MSG(_T(" (%d bytes), "), ubuild_sections.getlen());
2839 }
2840 ne=build_uninst.blocks[NB_ENTRIES].num;
2841 INFO_MSG(_T("%d instruction%") NPRIs _T(" (%d bytes), "),ne,ne==1?_T(""):_T("s"),ubuild_entries.getlen());
2842 ns=ubuild_strlist.getnum();
2843 INFO_MSG(_T("%d string%") NPRIs _T(" (%d bytes), "),ns,ns==1?_T(""):_T("s"),ubuild_strlist.gettotalsize());
2844 nlt=build_uninst.blocks[NB_LANGTABLES].num;
2845 INFO_MSG(_T("%d language table%") NPRIs _T(" (%d bytes).\n"),nlt,nlt==1?_T(""):_T("s"),ubuild_langtables.getlen());
2846 }
2847
2848
2849 if (db_opt_save)
2850 {
2851 size_t total_out_size_estimate=
2852 m_exehead_size+sizeof(fh)+build_datablock.getlen()+(build_crcchk?sizeof(crc32_t):0);
2853 int pc=(int)((db_opt_save*1000)/(db_opt_save+total_out_size_estimate));
2854 FriendlySize fs(db_opt_save);
2855 INFO_MSG(_T("Datablock optimizer saved %u%") NPRIs _T(" (~%d.%d%%).\n"),
2856 fs.UInt(),fs.Scale(),pc/10,pc%10);
2857 }
2858
2859 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
2860 INFO_MSG(_T("\nUsing %") NPRIs _T("%") NPRIs _T(" compression.\n\n"), compressor->GetName(), build_compress_whole?_T(" (compress whole)"):_T(""));
2861 #endif
2862
2863 unsigned int total_usize=(unsigned int) m_exehead_original_size;
2864
2865 INFO_MSG(_T("EXE header size: %10u / %u bytes\n"),m_exehead_size,m_exehead_original_size);
2866
2867 if (build_compress_whole) {
2868 INFO_MSG(_T("Install code: (%d bytes)\n"),
2869 sizeof(fh)+fh.length_of_header);
2870 }
2871 else {
2872 INFO_MSG(_T("Install code: %10d / %d bytes\n"),
2873 sizeof(fh)+installinfo_compressed,
2874 sizeof(fh)+fh.length_of_header);
2875 }
2876
2877 total_usize+=sizeof(fh)+fh.length_of_header;
2878
2879 {
2880 unsigned int dbsize;
2881 UINT64 dbsizeu;
2882 dbsize = build_datablock.getlen();
2883 if (uninstall_size > 0 && uninstall_size < UINT_MAX) dbsize -= uninstall_size;
2884
2885 if (build_compress_whole) {
2886 dbsizeu = dbsize;
2887 INFO_MSG(_T("Install data: (%u bytes)\n"),dbsize); // dbsize==dbsizeu and is easy to print
2888 }
2889 else {
2890 dbsizeu = db_full_size - uninstall_size_full;
2891 FriendlySize us(dbsizeu, GFSF_BYTESIFPOSSIBLE); // uncompressed installer size
2892 FriendlySize cs(dbsize, GFSF_BYTESIFPOSSIBLE | (us.UInt()==dbsizeu ? GFSF_HIDEBYTESCALE : 0)); // compressed installer size
2893 INFO_MSG(_T("Install data: %10u%") NPRIs _T(" / %u%") NPRIs _T("\n"),
2894 cs.UInt(),cs.Scale(),us.UInt(),us.Scale()); // "123 / 456 bytes" or "123 KiB / 456 MiB"
2895 }
2896 UINT future = (build_crcchk ? sizeof(int) : 0) + (uninstall_size > 0 && uninstall_size < UINT_MAX ? uninstall_size_full : 0);
2897 UINT maxsize = (~(UINT)0) - (total_usize + future), totsizadd = dbsizeu < maxsize ? (UINT)dbsizeu : maxsize;
2898 total_usize += totsizadd; // Might not be accurate, it is more important to not overflow the additions coming up
2899 }
2900
2901 if (uninstall_size < UINT_MAX)
2902 {
2903 if (build_compress_whole)
2904 INFO_MSG(_T("Uninstall code+data: (%u bytes)\n"),uninstall_size_full);
2905 else
2906 INFO_MSG(_T("Uninstall code+data: %10u / %u bytes\n"),uninstall_size,uninstall_size_full);
2907 total_usize += uninstall_size_full;
2908 }
2909
2910 if (build_compress_whole) {
2911 INFO_MSG(_T("Compressed data: "));
2912 }
2913
2914 if (build_datablock.getlen())
2915 {
2916 build_datablock.setro(TRUE);
2917 int dbl = build_datablock.getlen();
2918 int left = dbl;
2919 while (left > 0)
2920 {
2921 int l = min(build_filebuflen, left);
2922 char *dbptr = (char *) build_datablock.get(dbl - left, l);
2923 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
2924 if (build_compress_whole)
2925 {
2926 if (deflateToFile(fp,dbptr,l))
2927 {
2928 fclose(fp);
2929 return PS_ERROR;
2930 }
2931 }
2932 else
2933 #endif
2934 {
2935 #ifdef NSIS_CONFIG_CRC_SUPPORT
2936 crc=CRC32(crc,(unsigned char *)dbptr,l);
2937 #endif
2938 if ((int)fwrite(dbptr,1,l,fp) != l)
2939 {
2940 ERROR_MSG(_T("Error: can't write %d bytes to output\n"),l);
2941 fclose(fp);
2942 return PS_ERROR;
2943 }
2944 fflush(fp);
2945 }
2946 build_datablock.release();
2947 left -= l;
2948 }
2949 build_datablock.setro(FALSE);
2950 build_datablock.clear();
2951 }
2952 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
2953 if (build_compress_whole)
2954 {
2955 if (deflateToFile(fp,NULL,0))
2956 {
2957 fclose(fp);
2958 return PS_ERROR;
2959 }
2960 compressor->End();
2961
2962 unsigned fend = ftell(fp);
2963
2964 fh.length_of_all_following_data=ftell(fp)-fd_start+(build_crcchk?sizeof(crc32_t):0);
2965 INFO_MSG(
2966 _T("%10d / %d bytes\n"),
2967 ftell(fp) - fd_start,
2968 data_block_size_before_uninst + fh.length_of_header + sizeof(firstheader) + uninstall_size_full
2969 );
2970
2971 fseek(fp,fd_start,SEEK_SET);
2972
2973 try
2974 {
2975 file_writer_sink sink(fp, mk_writer_target_info());
2976 firstheader_writer w(&sink);
2977 w.write(&fh);
2978 }
2979 catch (...)
2980 {
2981 ERROR_MSG(_T("Error: can't write %d bytes to output\n"),sizeof(fh));
2982 fclose(fp);
2983 return PS_ERROR;
2984 }
2985
2986 #ifdef NSIS_CONFIG_CRC_SUPPORT
2987 if (build_crcchk)
2988 {
2989 // check rest of CRC
2990 fseek(fp,fd_start,SEEK_SET);
2991 for (;;)
2992 {
2993 char buf[32768];
2994 unsigned int l=(unsigned int)fread(buf,1,sizeof(buf),fp);
2995 if (!l) break;
2996 crc=CRC32(crc,(unsigned char *)buf,l);
2997 }
2998 }
2999 #endif
3000 fseek(fp,fend,SEEK_SET); // reset eof flag
3001 }
3002 #endif
3003
3004 if (build_crcchk)
3005 {
3006 total_usize+=sizeof(int);
3007 int rcrc = FIX_ENDIAN_INT32(crc);
3008 if (fwrite(&rcrc,1,sizeof(crc32_t),fp) != sizeof(crc32_t))
3009 {
3010 ERROR_MSG(_T("Error: can't write %d bytes to output\n"),sizeof(crc32_t));
3011 fclose(fp);
3012 return PS_ERROR;
3013 }
3014 INFO_MSG(_T("CRC (0x%08X): 4 / 4 bytes\n"),crc);
3015 }
3016 INFO_MSG(_T("\n"));
3017 {
3018 long fileend = ftell(fp);
3019 UINT pc=(UINT)(((UINT64)fileend*1000)/(total_usize));
3020 INFO_MSG(_T("Total size: %10u / %u bytes (%u.%u%%)\n"),
3021 fileend,total_usize,pc/10,pc%10);
3022 }
3023 fclose(fp);
3024 RET_UNLESS_OK(run_postbuild_cmds(postbuild_cmds, build_output_filename, _T("Finalize")));
3025 print_warnings();
3026 return PS_OK;
3027 }
3028
3029 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
3030 int CEXEBuild::deflateToFile(FILE *fp, char *buf, int len) // len==0 to flush
3031 {
3032 build_compressor_set=true;
3033
3034 char obuf[65536];
3035 bool flush=false;
3036 compressor->SetNextIn(buf,len);
3037 if (!buf||!len)
3038 {
3039 char a;
3040 compressor->SetNextIn(&a,0);
3041 flush=C_FINISH;
3042 }
3043 for (;;)
3044 {
3045 compressor->SetNextOut(obuf,sizeof(obuf));
3046 int ret=compressor->Compress(flush);
3047 if (ret<0 && (ret!=-1 || !flush))
3048 {
3049 ERROR_MSG(_T("Error: deflateToFile: deflate() failed(%") NPRIs _T(" [%d])\n"), compressor->GetErrStr(ret), ret);
3050 return 1;
3051 }
3052 size_t l=compressor->GetNextOut()-obuf;
3053 if (l)
3054 {
3055 if (fwrite(obuf,1,l,fp) != l)
3056 {
3057 ERROR_MSG(_T("Error: deflateToFile fwrite(%lu) failed\n"),(unsigned long)l);
3058 return 1;
3059 }
3060 fflush(fp);
3061 }
3062 if (!compressor->GetAvailIn() && (!flush || !l)) break;
3063 }
3064 return 0;
3065 }
3066 #endif
3067
3068 int CEXEBuild::uninstall_generate()
3069 {
3070 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
3071 if (ubuild_entries.getlen() && uninstaller_writes_used)
3072 {
3073 SCRIPT_MSG(_T("Generating uninstaller... "));
3074
3075 const int start_offset = postubuild_cmds ? truncate_cast(int, m_exehead_size) : 0;
3076 entry *ent = (entry *) build_entries.get();
3077 if (!ent) return PS_ERROR; // Check this early
3078
3079 MMapBuf udata;
3080 firstheader fh={0,};
3081
3082 GrowBuf uhd;
3083 {
3084 GrowBuf udata_exehead;
3085
3086 set_uninstall_mode(1);
3087
3088 PrepareHeaders(&udata_exehead);
3089
3090 fh.length_of_header=udata_exehead.getlen();
3091 int err=add_data((char*)udata_exehead.get(),udata_exehead.getlen(),&uhd);
3092 set_uninstall_mode(0);
3093 if (err < 0) return PS_ERROR;
3094 }
3095
3096 crc32_t crc=0;
3097 #ifdef NSIS_CONFIG_CRC_SUPPORT
3098 bool calc_crc = true;
3099 #else
3100 bool calc_crc = false;
3101 #endif
3102
3103 // Get offsets of icons to replace for uninstall
3104 // Also makes sure that the icons are there and in the right size.
3105 LPBYTE unicon_data = generate_uninstall_icon_data(installer_icon, uninstaller_icon, m_unicon_size);
3106 if (generate_unicons_offsets(m_exehead, m_exehead_size, unicon_data, IDI_ICON2) == 0)
3107 {
3108 delete [] unicon_data;
3109 return PS_ERROR;
3110 }
3111
3112 int uns = uninstaller_writes_used;
3113 int uninstdata_offset = build_datablock.getlen();
3114 for (int ents = build_header.blocks[NB_ENTRIES].num; ents--; ent++)
3115 {
3116 if (ent->which == EW_WRITEUNINSTALLER)
3117 {
3118 ent->offsets[1] = uninstdata_offset;
3119 ent->offsets[2] = start_offset ? 0 : (int) m_unicon_size;
3120 if (!--uns)
3121 break;
3122 }
3123 }
3124
3125 if (!start_offset && add_db_data((char *)unicon_data,m_unicon_size) < 0)
3126 {
3127 delete [] unicon_data;
3128 return PS_ERROR;
3129 }
3130
3131 if (start_offset || calc_crc)
3132 {
3133 // create the uninstaller
3134 LPBYTE uninst_header = (LPBYTE) malloc(m_exehead_size);
3135 if (!uninst_header)
3136 {
3137 delete [] unicon_data;
3138 return PS_ERROR;
3139 }
3140
3141 memcpy(uninst_header, m_exehead, m_exehead_size);
3142
3143 // patch the icons
3144 LPBYTE seeker = unicon_data;
3145 while (*seeker) {
3146 DWORD dwSize = FIX_ENDIAN_INT32(*(LPDWORD) seeker);
3147 seeker += sizeof(DWORD);
3148 DWORD dwOffset = FIX_ENDIAN_INT32(*(LPDWORD) seeker);
3149 seeker += sizeof(DWORD);
3150 memcpy(uninst_header + dwOffset, seeker, dwSize);
3151 seeker += dwSize;
3152 }
3153
3154 if (calc_crc)
3155 {
3156 #ifdef NSIS_CONFIG_CRC_SUPPORT
3157 #ifdef NSIS_CONFIG_CRC_ANAL
3158 crc=CRC32(crc, uninst_header, (DWORD)m_exehead_size);
3159 #else
3160 crc=CRC32(crc, uninst_header + 512, (DWORD)m_exehead_size - 512);
3161 #endif
3162 #endif
3163 }
3164
3165 // write the exehead
3166 if (start_offset)
3167 udata.add((char *)uninst_header, truncate_cast(int, m_exehead_size));
3168
3169 free(uninst_header);
3170 }
3171 delete [] unicon_data;
3172
3173 fh.nsinst[0]=FH_INT1;
3174 fh.nsinst[1]=FH_INT2;
3175 fh.nsinst[2]=FH_INT3;
3176 fh.flags=FH_FLAGS_UNINSTALL;
3177 #ifdef NSIS_CONFIG_CRC_SUPPORT
3178 fh.flags|=(build_crcchk?(build_crcchk==2?FH_FLAGS_FORCE_CRC:0):FH_FLAGS_NO_CRC);
3179 #endif
3180 #ifdef NSIS_CONFIG_SILENT_SUPPORT
3181 if (build_uninst.flags&(CH_FLAGS_SILENT|CH_FLAGS_SILENT_LOG)) fh.flags |= FH_FLAGS_SILENT;
3182 #endif
3183 fh.siginfo=FH_SIG;
3184 fh.length_of_all_following_data=
3185 uhd.getlen()+ubuild_datablock.getlen()+(int)sizeof(firstheader)+(build_crcchk?sizeof(crc32_t):0);
3186
3187 {
3188 growbuf_writer_sink sink(&udata, mk_writer_target_info());
3189 firstheader_writer w(&sink);
3190 w.write(&fh);
3191 }
3192
3193 ubuild_datablock.setro(TRUE);
3194
3195 #ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
3196 if (build_compress_whole) {
3197 // compress uninstaller too
3198 {
3199 char obuf[65536];
3200 int n = compressor->Init(build_compress_level, build_compress_dict_size);
3201 if (n != C_OK)
3202 {
3203 ERROR_MSG(_T("Internal compiler error #12345: deflateInit() failed(%") NPRIs _T(" [%d]).\n"), compressor->GetErrStr(n), n);
3204 extern void quit(); quit();
3205 }
3206
3207 compressor->SetNextIn((char*)uhd.get(), uhd.getlen());
3208 while (compressor->GetAvailIn())
3209 {
3210 compressor->SetNextOut(obuf, sizeof(obuf));
3211 compressor->Compress(0);
3212 if (compressor->GetNextOut() - obuf > 0)
3213 {
3214 udata.add(obuf, truncate_cast(int, (size_t)(compressor->GetNextOut() - obuf)));
3215 }
3216 }
3217
3218 int avail_in = ubuild_datablock.getlen();
3219 int in_pos = 0;
3220 while (avail_in > 0) {
3221 int l = min(avail_in, build_filebuflen);
3222
3223 char *p = (char*)ubuild_datablock.get(in_pos, l);
3224 compressor->SetNextIn(p, l);
3225
3226 while (compressor->GetAvailIn())
3227 {
3228 compressor->SetNextOut(obuf, sizeof(obuf));
3229 compressor->Compress(0);
3230 if (compressor->GetNextOut() - obuf > 0)
3231 udata.add(obuf, truncate_cast(int, (size_t)(compressor->GetNextOut() - obuf)));
3232 }
3233
3234 ubuild_datablock.release();
3235
3236 avail_in -= l;
3237 in_pos += l;
3238 }
3239
3240 for (;;)
3241 {
3242 compressor->SetNextOut(obuf, sizeof(obuf));
3243 compressor->Compress(C_FINISH);
3244 if (compressor->GetNextOut() - obuf > 0)
3245 udata.add(obuf, truncate_cast(int, (size_t)(compressor->GetNextOut() - obuf)));
3246 else break;
3247 }
3248 compressor->End();
3249 }
3250
3251 firstheader *ufh=(firstheader *)udata.get(start_offset, sizeof(firstheader));
3252 ufh->length_of_all_following_data=FIX_ENDIAN_INT32((udata.getlen()-start_offset)+(build_crcchk?sizeof(crc32_t):0));
3253 udata.release();
3254 }
3255 else
3256 #endif//NSIS_CONFIG_COMPRESSION_SUPPORT
3257 {
3258 udata.add(uhd.get(), uhd.getlen());
3259
3260 int st = udata.getlen();
3261 int length = ubuild_datablock.getlen();
3262 int left = length;
3263 udata.resize(st + left);
3264 while (left > 0)
3265 {
3266 int l = min(build_filebuflen, left);
3267 void *p = ubuild_datablock.get(length - left, l);
3268 memcpy(udata.get(st + length - left, l), p, l);
3269 udata.flush(l);
3270 udata.release();
3271 ubuild_datablock.release();
3272 left -= l;
3273 }
3274 }
3275
3276 ubuild_datablock.clear();
3277
3278 udata.setro(TRUE);
3279
3280 #ifdef NSIS_CONFIG_CRC_SUPPORT
3281 if (build_crcchk)
3282 {
3283 int pos = 0;
3284 int left = udata.getlen() - start_offset;
3285 while (left > 0)
3286 {
3287 int l = min(build_filebuflen, left);
3288 crc = CRC32(crc, (unsigned char *) udata.get(pos + start_offset, l), l);
3289 udata.release();
3290 pos += l;
3291 left -= l;
3292 }
3293 udata.setro(FALSE);
3294 FIX_ENDIAN_INT32_INPLACE(crc);
3295 udata.add(&crc, sizeof(crc));
3296 udata.setro(TRUE);
3297 }
3298 #endif
3299
3300 if (start_offset)
3301 {
3302 TCHAR* fpath;
3303 if (!(fpath = create_tempfile_path()))
3304 {
3305 ERROR_MSG(_T("Error: can't get temporary path\n"));
3306 return PS_ERROR;
3307 }
3308 MANAGE_WITH(fpath, free);
3309 FILE *hfile = FOPEN(fpath, ("wb"));
3310 if (!hfile)
3311 {
3312 ERROR_MSG(_T("Error: failed opening file \"%") NPRIs _T("\"\n"), fpath);
3313 return PS_ERROR;
3314 }
3315 int succ = udata.write_to_external_file(hfile);
3316 fclose(hfile);
3317 if (!succ)
3318 {
3319 ERROR_MSG(_T("Error: can't write %d bytes to output\n"), udata.getlen());
3320 return PS_ERROR;
3321 }
3322 udata.clear();
3323
3324 if (PS_OK != run_postbuild_cmds(postubuild_cmds, fpath, _T("UninstFinalize")))
3325 {
3326 return PS_ERROR;
3327 }
3328
3329 MMapFile udata_in;
3330 UINT64 udata_size;
3331 if (!(udata_size = udata_in.setfile(fpath)))
3332 {
3333 ERROR_MSG(_T("Error: failed creating mmap of \"%") NPRIs _T("\"\n"), fpath);
3334 return PS_ERROR;
3335 }
3336 if (udata_size > NSIS_MAX_EXEFILESIZE || add_db_data(&udata_in) < 0)
3337 return PS_ERROR;
3338
3339 assert(NSIS_MAX_EXEFILESIZE <= ~(UINT32)0);
3340 uninstall_size_full = (UINT32) udata_size;
3341 udata_in.clear();
3342 _tremove(fpath);
3343 }
3344 else
3345 {
3346 if (add_db_data(&udata) < 0)
3347 return PS_ERROR;
3348
3349 //uninstall_size_full=fh.length_of_all_following_data + sizeof(int) + unicondata_size - 32 + sizeof(int);
3350 uninstall_size_full = fh.length_of_all_following_data+(int)m_unicon_size;
3351 }
3352
3353 // compressed size
3354 uninstall_size=build_datablock.getlen()-uninstdata_offset;
3355 SCRIPT_MSG(_T("Done!\n"));
3356 }
3357 #endif
3358 return PS_OK;
3359 }
3360
3361 #define SWAP(x,y,i) { i _ii; _ii=x; x=y; y=_ii; }
3362
3363 void CEXEBuild::set_uninstall_mode(int un)
3364 {
3365 if (un != uninstall_mode)
3366 {
3367 uninstall_mode=un;
3368 if (un)
3369 {
3370 cur_datablock=&ubuild_datablock;
3371 cur_datablock_cache=&ubuild_datablock_cache;
3372 cur_entries=&ubuild_entries;
3373 cur_instruction_entry_map=&ubuild_instruction_entry_map;
3374 cur_functions=&ubuild_functions;
3375 cur_labels=&ubuild_labels;
3376 cur_pages=&ubuild_pages;
3377 cur_sections=&ubuild_sections;
3378 cur_header=&build_uninst;
3379 cur_strlist=&ubuild_strlist;
3380 cur_langtables=&ubuild_langtables;
3381 cur_ctlcolors=&ubuild_ctlcolors;
3382
3383 definedlist.add(_T("__UNINSTALL__"));
3384 }
3385 else
3386 {
3387 cur_datablock=&build_datablock;
3388 cur_datablock_cache=&build_datablock_cache;
3389 cur_entries=&build_entries;
3390 cur_instruction_entry_map=&build_instruction_entry_map;
3391 cur_functions=&build_functions;
3392 cur_labels=&build_labels;
3393 cur_pages=&build_pages;
3394 cur_sections=&build_sections;
3395 cur_header=&build_header;
3396 cur_strlist=&build_strlist;
3397 cur_langtables=&build_langtables;
3398 cur_ctlcolors=&build_ctlcolors;
3399
3400 definedlist.del(_T("__UNINSTALL__"));
3401 }
3402
3403 SWAP(db_opt_save_u,db_opt_save,UINT64);
3404 SWAP(db_comp_save_u,db_comp_save,int);
3405 SWAP(db_full_size_u,db_full_size,UINT64);
3406 }
3407 }
3408
3409 extern FILE *g_output;
3410
3411 /* Useful for debugging.
3412 bool IsStringASCII(const TCHAR* s)
3413 {
3414 while (*s) { if (!_istascii(*s++)) return false; }
3415 return true;
3416 }
3417 */
3418
3419 int CEXEBuild::get_verbosity() const
3420 {
3421 int v = 0;
3422 if (display_errors)
3423 {
3424 v++;
3425 if (display_warnings)
3426 {
3427 v++;
3428 if (display_info)
3429 {
3430 v++;
3431 if (display_script)
3432 {
3433 v++;
3434 }
3435 }
3436 }
3437 }
3438 return v;
3439 }
3440
3441 void CEXEBuild::set_verbosity(int lvl)
3442 {
3443 if (preprocessonly) lvl = STD_MIN(lvl, 1);
3444 display_errors = lvl > 0;
3445 display_warnings = lvl > 1;
3446 display_info = lvl > 2;
3447 display_script = lvl > 3;
3448 extern int g_display_errors;
3449 g_display_errors = display_errors;
3450 }
3451
3452 int CEXEBuild::parse_pragma(LineParser &line)
3453 {
3454 const int rvSucc = PS_OK, rvWarn = PS_WARNING, rvErr = PS_WARNING; // rvErr is not PS_ERROR because we want !pragma parsing to be very forgiving.
3455 const TCHAR badParamMsg[] = _T("Unknown pragma");
3456
3457 if (line.gettoken_enum(1, _T("internal\0")) == 0)
3458 {
3459 if (line.gettoken_enum(2, _T("x\0")) == 0)
3460 {
3461 const TCHAR *name = line.gettoken_str(3);
3462 int succ, num = line.gettoken_intx(4, &succ);SCRIPT_MSG(_T("%#x %d\n"),num,succ);
3463 return ((succ ? definedlist.set_si32(name, num) : definedlist.set(name, _T(""))), rvSucc);
3464 }
3465 if (line.gettoken_enum(2, _T("dump\0")) == 0)
3466 {
3467 if (line.gettoken_enum(3, _T("defines\0")) == 0)
3468 {
3469 for (UINT i = 0, c = definedlist.getnum(); i < c; ++i)
3470 SCRIPT_MSG(_T("%") NPRIs _T("=%") NPRIs _T("\n"), definedlist.getname(i), definedlist.getvalue(i));
3471 }
3472 else if (line.gettoken_enum(3, _T("macros\0")) == 0)
3473 {
3474 const TCHAR *mnam;
3475 for (size_t i = 0; (mnam = GetMacro(i)) != 0; ++i)
3476 SCRIPT_MSG(_T("%") NPRIs _T("\n"), mnam);
3477 }
3478 else
3479 {
3480 SCRIPT_MSG(_T("V=%d\n"), get_verbosity());
3481 }
3482 }
3483 return rvErr;
3484 }
3485
3486 if (line.gettoken_enum(1, _T("verifyloadimage\0")) == 0)
3487 {
3488 bool valid = LoadImageCanLoadFile(line.gettoken_str(2));
3489 return valid ? rvSucc : (warning_fl(DW_BADFORMAT_EXTERNAL_FILE, _T("Unsupported format %") NPRIs, line.gettoken_str(2)), rvWarn);
3490 }
3491
3492 // 2.47 shipped with a corrupted CHM file (bug #1129). This minimal verification command exists because the !searchparse hack we added does not work with codepage 936!
3493 if (line.gettoken_enum(1, _T("verifychm\0")) == 0)
3494 {
3495 struct { UINT32 Sig, Ver, cbH; } chm;
3496 NIStream f;
3497 bool valid = f.OpenFileForReading(line.gettoken_str(2), NStreamEncoding::BINARY);
3498 valid = valid && 12 == f.ReadOctets(&chm, 12);
3499 valid = valid && FIX_ENDIAN_INT32(chm.Sig) == 0x46535449 && (FIX_ENDIAN_INT32(chm.Ver)|1) == 3; // 'ITSF' v2..3
3500 return valid ? rvSucc : (ERROR_MSG(_T("Error: Invalid format\n")), PS_ERROR);
3501 }
3502
3503 if (line.gettoken_enum(1, _T("w\150i\160\0")) == 0)
3504 {
3505 int succ, ec = line.gettoken_int(2, &succ);
3506 SCRIPT_MSG(_T("%") NPRIns _T("\n"), "N\123I\123, i\164 \162eall\171 install\163 ll\141\155as wit\150o\165t s\141fety \147l\141\163s!");
3507 exit(succ ? ec : 1);
3508 }
3509
3510 if (line.gettoken_enum(1, _T("warning\0")) == -1)
3511 return (warning_fl(DW_PP_PRAGMA_UNKNOWN, _T("Unknown pragma")), rvErr);
3512
3513 enum { woperr = 0, wopwar, wopdis, wopena, wopdef, woppus, woppop, invalidwop };
3514 int warnOp = line.gettoken_enum(2, _T("error\0warning\0disable\0enable\0default\0push\0pop\0")), ret = rvSucc;
3515 if (warnOp < 0)
3516 ret = rvErr, warning_fl(DW_PP_PRAGMA_UNKNOWN, badParamMsg); // Unknown warning pragma action
3517 else if (warnOp == woppus) // warning: push
3518 diagstate.push();
3519 else if (warnOp == woppop) // warning: pop
3520 {
3521 if (!diagstate.pop())
3522 ret = rvWarn, warning_fl(DW_PP_PRAGMA_INVALID, _T("Unexpected"));
3523 }
3524 else // warning: error/warning/disable/enable/default <%code%|all> [..]
3525 {
3526 for (int ti = 3; ti < line.getnumtokens(); ++ti)
3527 {
3528 DIAGCODE code = static_cast<DIAGCODE>(line.gettoken_int(ti));
3529 bool all = line.gettoken_enum(ti, _T("all\0")) == 0, isCode = diagstate.is_valid_code(code);
3530 switch((isCode||all) ? warnOp : invalidwop)
3531 {
3532 case woperr: all ? diagstate.set_all(DiagState::werror) : diagstate.error(code); break;
3533 case wopwar: all ? diagstate.set_all(DiagState::wwarning) : diagstate.warning(code); break;
3534 case wopdis: all ? diagstate.set_all(DiagState::wdisabled) : diagstate.disable(code); break;
3535 case wopena: all ? diagstate.set_all(DiagState::wenabled) : diagstate.enable(code); break;
3536 case wopdef: all ? diagstate.set_all(DiagState::get_default_state()) : diagstate.def(code); break;
3537 default: ret = rvWarn, warning_fl(DW_PP_PRAGMA_INVALID, _T("Invalid number: \"%") NPRIs _T("\""), line.gettoken_str(ti));
3538 }
3539 }
3540 }
3541 return ret;
3542 }
3543
3544 void DiagState::push()
3545 {
3546 DiagState *p = new DiagState();
3547 *p = *this; // Copy the current state
3548 p->m_pStack = m_pStack, m_pStack = p; // ...and push it on the stack
3549 }
3550 bool DiagState::pop()
3551 {
3552 if (!m_pStack) return false;
3553 DiagState *pPop = m_pStack; // Get the item on the top of the stack
3554 *this = *pPop; // ...and assign it as the current state
3555 pPop->m_pStack = 0; // The pop'ed item no longer owns the next item on the stack
3556 delete pPop;
3557 return true;
3558 }
3559
3560 void CEXEBuild::warninghelper(DIAGCODE dc, bool fl, const TCHAR *fmt, va_list args)
3561 {
3562 bool showcode = dc != DIAGCODE_INTERNAL_HIDEDIAGCODE;
3563 if (diagstate.is_disabled(dc)) return ;
3564 bool aserror = diagstate.is_error(dc);
3565
3566 TCHAR codbuf[11+2+!0];
3567 _stprintf(codbuf, showcode ? _T("%u: ") : _T(""), static_cast<unsigned int>(dc));
3568 ExpandoString<TCHAR, COUNTOF(codbuf) + NSIS_MAX_STRLEN + 100> msgbuf;
3569 ExpandoString<TCHAR, COUNTOF(codbuf) + 200> fmtbuf;
3570 fmtbuf.StrFmt(_T("%") NPRIs _T("%") NPRIs, codbuf, fmt);
3571 size_t cchMsg = msgbuf.StrVFmt(fmtbuf.GetPtr(), args);
3572 if (fl)
3573 {
3574 msgbuf.Reserve(cchMsg+2+_tcslen(curfilename)+1+11+1+!0);
3575 _stprintf(&msgbuf[cchMsg], _T(" (%") NPRIs _T(":%u)"), curfilename, linecnt);
3576 }
3577 const TCHAR *msg = msgbuf.GetPtr();
3578
3579 m_warnings.add(msg,0); // Add to list of warnings to display at the end
3580
3581 MakensisAPI::datatransfer_e hostevent = MakensisAPI::NOTIFY_WARNING;
3582 if (aserror)
3583 hostevent = MakensisAPI::NOTIFY_ERROR, display_warnings = display_errors;
3584
3585 notify(hostevent, msg); // Notify the host
3586
3587 if (display_warnings) // Print "warning %msgwithcodeprefix%" or "warning: %msg%"
3588 PrintColorFmtMsg_WARN(_T("warning%") NPRIs _T("%") NPRIs _T("\n"), showcode ? _T(" ") : _T(": "), msg);
3589
3590 if (aserror)
3591 {
3592 ERROR_MSG(_T("Error: warning treated as error\n"));
3593 extern int g_display_errors;
3594 if (!has_called_write_output) g_display_errors = false; // This is a hack to avoid the "stale file in %temp%" warning.
3595 extern void quit(); quit();
3596 }
3597 }
3598
3599 void CEXEBuild::warning(DIAGCODE dc, const TCHAR *s, ...)
3600 {
3601 va_list val;
3602 va_start(val, s);
3603 warninghelper(dc, false, s, val);
3604 va_end(val);
3605 }
3606
3607 void CEXEBuild::warning_fl(DIAGCODE dc, const TCHAR *s, ...)
3608 {
3609 va_list val;
3610 va_start(val, s);
3611 warninghelper(dc, true, s, val);
3612 va_end(val);
3613 }
3614
3615 void CEXEBuild::ERROR_MSG(const TCHAR *s, ...) const
3616 {
3617 if (display_errors || notify_hwnd)
3618 {
3619 ExpandoString<TCHAR, NSIS_MAX_STRLEN + 100> buf;
3620 va_list val;
3621 va_start(val,s);
3622 buf.StrVFmt(s,val);
3623 va_end(val);
3624
3625 notify(MakensisAPI::NOTIFY_ERROR, buf.GetPtr());
3626 if (display_errors)
3627 {
3628 PrintColorFmtMsg_ERR(_T("%") NPRIs, buf.GetPtr());
3629 }
3630 }
3631 }
3632
3633 void CEXEBuild::SCRIPT_MSG(const TCHAR *s, ...) const
3634 {
3635 if (display_script)
3636 {
3637 va_list val;
3638 va_start(val,s);
3639 _vftprintf(g_output,s,val);
3640 va_end(val);
3641 fflush(g_output);
3642 }
3643 }
3644
3645 void CEXEBuild::INFO_MSG(const TCHAR *s, ...) const
3646 {
3647 if (display_info)
3648 {
3649 va_list val;
3650 va_start(val,s);
3651 _vftprintf(g_output,s,val);
3652 va_end(val);
3653 fflush(g_output);
3654 }
3655 }
3656
3657 void CEXEBuild::print_warnings()
3658 {
3659 int nw=0,x=m_warnings.getcount();
3660 if (!x || !display_warnings) return;
3661 TCHAR *p=m_warnings.get();
3662 while (x>0) if (!p[--x]) nw++;
3663 SetPrintColorWARN();
3664 _ftprintf(g_output,_T("\n%d warning%") NPRIs _T(":\n"),nw,nw==1?_T(""):_T("s"));
3665 for (x = 0; x < nw; x ++)
3666 {
3667 _ftprintf(g_output,_T(" %") NPRIs _T("\n"),p);
3668 p+=_tcslen(p)+1;
3669 }
3670 FlushOutputAndResetPrintColor();
3671 }
3672
3673 void CEXEBuild::notify(MakensisAPI::datatransfer_e code, const TCHAR *data) const
3674 {
3675 #ifdef _WIN32
3676 if (notify_hwnd)
3677 {
3678 DWORD cb = (DWORD) (_tcslen(data)+1) * sizeof(TCHAR);
3679 #ifdef _UNICODE
3680 extern NStreamEncoding g_outputenc;
3681 extern void quit();
3682 CharEncConv cec;
3683 if (!g_outputenc.IsUTF16LE())
3684 {
3685 size_t cbConv;
3686 if (!cec.Initialize(g_outputenc.GetCodepage(), -1) || !(data = (const TCHAR*) cec.Convert(data, cb, &cbConv)))
3687 PrintColorFmtMsg_ERR(_T("conversion failed!\n")), quit(); // Cannot use ERROR_MSG() here!
3688 cb = (DWORD) (cbConv + NStreamEncoding::GetCodeUnitSize(g_outputenc.GetCodepage())); // cbConv does not include the \0.
3689 }
3690 #endif
3691 COPYDATASTRUCT cds = {(DWORD) code, cb, (void*) data};
3692 SendMessage(notify_hwnd, WM_COPYDATA, 0, (LPARAM)&cds);
3693 }
3694 #endif
3695 }
3696
3697 bool CEXEBuild::hostapi_request_data(MakensisAPI::datatransfer_e operation, UINT minver, HOSTAPIREQUESTDATAPROC proc, void*cookie, const void* input, size_t inputsize) const
3698 {
3699 using namespace MakensisAPI;
3700 #ifdef _WIN32
3701 struct helper {
3702 static INT_PTR CALLBACK Proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
3703 {
3704 size_t *data = (size_t*) GetWindowLongPtr(hWnd, DWLP_USER);
3705 if (Msg == WM_CLOSE)
3706 {
3707 if (lParam) SendMessage((HWND) wParam, WM_COPYDATA, (SIZE_T) hWnd, lParam);
3708 return DestroyWindow(hWnd) | PostMessage(NULL, WM_QUIT, 0, 0);
3709 }
3710 return data && ((CEXEBuild::HOSTAPIREQUESTDATAPROC)data[0])((void*) data[1], hWnd, Msg, wParam, lParam); // We don't set DWLP_MSGRESULT nor care about the return value
3711 }
3712 };
3713 if (!notify_hwnd || (minver && (UINT) SendMessage(notify_hwnd, QUERYHOST, QH_SUPPORTEDVERSION, 0) < minver)) return false;
3714 size_t data[] = { (size_t) proc, (size_t) cookie };
3715 COPYDATASTRUCT cds = { (DWORD) operation, (DWORD) inputsize, (void*) input };
3716 HWND hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, WC_DIALOG, NULL, WS_POPUP|WS_DISABLED, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
3717 SetWindowLongPtr(hWnd, DWLP_USER, (LONG_PTR) data);
3718 SetWindowLongPtr(hWnd, DWLP_DLGPROC, (LONG_PTR) helper::Proc);
3719 SendMessage(hWnd, WM_CLOSE, (SIZE_T) notify_hwnd, (SIZE_T) &cds);
3720 if (hWnd) for (MSG msg; (int) GetMessage(&msg, NULL, 0, 0) > 0;) DispatchMessage(&msg);
3721 return !!hWnd;
3722 #else
3723 return false;
3724 #endif
3725 }
3726
3727 bool CEXEBuild::prompt_for_output_path(TCHAR*path, UINT pathcap) const
3728 {
3729 using namespace MakensisAPI;
3730 #ifdef _WIN32
3731 struct handler {
3732 static bool CALLBACK proc(void*cookie, HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
3733 {
3734 size_t *io = (size_t*) cookie;
3735 COPYDATASTRUCT*pCDS = (COPYDATASTRUCT*) lParam;
3736 if (Msg == WM_COPYDATA && pCDS->cbData > sizeof(TCHAR) && pCDS->cbData <= io[2] * sizeof(TCHAR))
3737 {
3738 _tcscpy((TCHAR*) io[1], (TCHAR*) ((COPYDATASTRUCT*)lParam)->lpData);
3739 return (io[0] = (pCDS->dwData == MakensisAPI::PROMPT_FILEPATH));
3740 }
3741 return false;
3742 }
3743 };
3744 size_t io[] = { false, (size_t) path, pathcap }, cb;
3745 TinyGrowBuf inputbuf((IGrowBuf::size_type) (cb = FIELD_OFFSET(PROMPT_FILEPATH_DATA, Path[pathcap])));
3746 PROMPT_FILEPATH_DATA *p = (PROMPT_FILEPATH_DATA*) inputbuf.get();
3747 p->Platform = (sizeof(void*) * 8) | sizeof(TCHAR), p->Reserved = 0;
3748 _tcscpy(p->Path, path);
3749 return hostapi_request_data(PROMPT_FILEPATH, 0x03006000, handler::proc, io, p, cb) && io[0];
3750 #else
3751 return false;
3752 #endif
3753 }
3754
3755 #ifdef NSIS_CONFIG_PLUGIN_SUPPORT
3756 int CEXEBuild::initialize_default_plugins(bool newtargetarc)
3757 {
3758 if (!m_pPlugins)
3759 {
3760 plugin_used = uninst_plugin_used = false;
3761 newtargetarc = true;
3762 }
3763 if (!newtargetarc) return PS_OK;
3764
3765 m_pPlugins = &m_plugins[m_target_type];
3766
3767 tstring searchPath = definedlist.find(_T("NSISDIR"));
3768 searchPath += PLATFORM_PATH_SEPARATOR_STR _T("Plugins") PLATFORM_PATH_SEPARATOR_STR;
3769 searchPath += get_target_suffix();
3770
3771 SCRIPT_MSG(_T("Processing default plugins: \"%") NPRIs PLATFORM_PATH_SEPARATOR_STR _T("*.dll\"\n"), searchPath.c_str());
3772 if (!m_pPlugins->Initialize(searchPath.c_str(), is_target_64bit(), !!display_script))
3773 {
3774 ERROR_MSG(_T("Error initializing default plugins!\n"));
3775 return PS_ERROR;
3776 }
3777 SCRIPT_MSG(_T("\n"));
3778 return PS_OK;
3779 }
3780
3781 int CEXEBuild::add_plugins_dir_initializer(void)
3782 {
3783 if (!plugin_used && !uninst_plugin_used) return PS_OK;
3784
3785 SCRIPT_MSG(_T("Adding plug-ins initializing function... "));
3786
3787 bool uninstall = !plugin_used;
3788
3789 int ret;
3790 int var_r0=m_UserVarNames.get(_T("0")), r0_offset;
3791 int var_r1=m_UserVarNames.get(_T("1")), r1_offset;
3792
3793 again:
3794 // Function [un.]Initialize_____Plugins
3795 ret=add_function(uninstall?_T("un.Initialize_____Plugins"):_T("Initialize_____Plugins"));
3796 if (ret != PS_OK) return ret;
3797
3798 // don't move this, depends on [un.]
3799 r0_offset=add_asciistring(_T("$0"));
3800 r1_offset=add_asciistring(_T("$1"));
3801
3802 // SetDetailsPrint none (special)
3803 ret=add_entry_direct(EW_SETFLAG, FLAG_OFFSET(status_update), add_intstring(6), -1);
3804 if (ret != PS_OK) return ret;
3805
3806 // StrCmp $PLUGINSDIR ""
3807 ret=add_entry_direct(EW_STRCMP, add_asciistring(_T("$PLUGINSDIR")), 0, 0, ns_label.add(_T("Initialize_____Plugins_done"),0));
3808 if (ret != PS_OK) return ret;
3809 // Push $0
3810 ret=add_entry_direct(EW_PUSHPOP, r0_offset);
3811 if (ret != PS_OK) return ret;
3812 // Push $1
3813 ret=add_entry_direct(EW_PUSHPOP, r1_offset);
3814 if (ret != PS_OK) return ret;
3815 // Copy "" to $1
3816 ret=add_entry_direct(EW_ASSIGNVAR, var_r1, r0_offset, 0, -1);
3817 if (ret != PS_OK) return ret;
3818
3819 // retry:
3820 if (add_label(_T("Initialize_____Plugins_retry"))) return PS_ERROR;
3821 // ClearErrors
3822 ret=add_entry_direct(EW_SETFLAG, FLAG_OFFSET(exec_error));
3823 if (ret != PS_OK) return ret;
3824 // GetTempFileName $0
3825 ret=add_entry_direct(EW_GETTEMPFILENAME, var_r0, add_asciistring(_T("$TEMP")));
3826 if (ret != PS_OK) return ret;
3827 // Delete $0 [simple, nothing that could clash with special temp permissions]
3828 ret=add_entry_direct(EW_DELETEFILE, r0_offset, DEL_SIMPLE);
3829 if (ret != PS_OK) return ret;
3830 // CreateDirectory $0 - a dir instead of that temp file
3831 ret=add_entry_direct(EW_CREATEDIR, r0_offset, 0, 1);
3832 if (ret != PS_OK) return ret;
3833 // IfErrors Initialize_____Plugins_error - detect errors
3834 ret=add_entry_direct(EW_IFFLAG, ns_label.add(_T("Initialize_____Plugins_error"),0), 0, FLAG_OFFSET(exec_error));
3835 if (ret != PS_OK) return ret;
3836 // Copy $0 to $PLUGINSDIR
3837 ret=add_entry_direct(EW_ASSIGNVAR, m_UserVarNames.get(_T("PLUGINSDIR")), r0_offset);
3838 if (ret != PS_OK) return ret;
3839 // Pop $1
3840 ret=add_entry_direct(EW_PUSHPOP, var_r1, 1);
3841 if (ret != PS_OK) return ret;
3842 // Pop $0
3843 ret=add_entry_direct(EW_PUSHPOP, var_r0, 1);
3844 if (ret != PS_OK) return ret;
3845
3846 // done:
3847 if (add_label(_T("Initialize_____Plugins_done"))) return PS_ERROR;
3848 // Return
3849 ret=add_entry_direct(EW_RET);
3850 if (ret != PS_OK) return ret;
3851
3852 // error:
3853 if (add_label(_T("Initialize_____Plugins_error"))) return PS_ERROR;
3854 // IntOp $1 $1 + 1
3855 ret=add_entry_direct(EW_INTOP, var_r1, r1_offset, add_asciistring(_T("1")), 0);
3856 if (ret != PS_OK) return ret;
3857 // StrCmp $1 "9"
3858 ret=add_entry_direct(EW_STRCMP, r1_offset, add_asciistring(_T("9")), 0, ns_label.add(_T("Initialize_____Plugins_retry"),0));
3859 if (ret != PS_OK) return ret;
3860 // error message box
3861 ret=add_entry_direct(EW_MESSAGEBOX, MB_OK|MB_ICONSTOP|(IDOK<<21), add_asciistring(_T("Error! Can't initialize plug-ins directory. Please try again later.")));
3862 if (ret != PS_OK) return ret;
3863 // Quit
3864 ret=add_entry_direct(EW_QUIT);
3865 if (ret != PS_OK) return ret;
3866
3867 // FunctionEnd
3868 ret=function_end();
3869 if (ret != PS_OK) return ret;
3870
3871 if (uninst_plugin_used && !uninstall) {
3872 uninstall = true;
3873 goto again;
3874 }
3875
3876 SCRIPT_MSG(_T("Done!\n"));
3877
3878 return PS_OK;
3879 }
3880 #endif // NSIS_CONFIG_PLUGIN_SUPPORT
3881
3882 void CEXEBuild::init_res_editor()
3883 {
3884 build_compressor_set = true;
3885 if (!res_editor)
3886 res_editor = new CResourceEditor(m_exehead, (DWORD)m_exehead_size);
3887 }
3888
3889 void CEXEBuild::close_res_editor()
3890 {
3891 if (!res_editor) return;
3892 DWORD newsize;
3893
3894 // get size
3895 newsize = res_editor->Save(NULL, newsize);
3896 unsigned char *new_header = new unsigned char[newsize];
3897
3898 // save
3899 int rc = res_editor->Save(new_header, newsize);
3900 assert(rc == 0);
3901
3902 update_exehead(new_header, newsize);
3903
3904 // TODO: resource-controlling class
3905 delete [] new_header;
3906
3907 delete res_editor;
3908 res_editor=0;
3909 }
3910
3911 int CEXEBuild::DeclaredUserVar(const TCHAR *szVarName)
3912 {
3913 if (m_ShellConstants.get((TCHAR*)szVarName) >= 0)
3914 {
3915 ERROR_MSG(_T("Error: name \"%") NPRIs _T("\" in use by constant\n"), szVarName);
3916 return PS_ERROR;
3917 }
3918
3919 int idxUserVar = m_UserVarNames.get((TCHAR*)szVarName);
3920 if (idxUserVar >= 0)
3921 {
3922 ERROR_MSG(_T("Error: variable \"%") NPRIs _T("\" already declared\n"), szVarName);
3923 return PS_ERROR;
3924 }
3925 const TCHAR *pVarName = szVarName;
3926 size_t iVarLen = _tcslen(szVarName);
3927
3928 if (iVarLen > 60)
3929 {
3930 ERROR_MSG(_T("Error: variable name too long!\n"));
3931 return PS_ERROR;
3932 }
3933 else if (!iVarLen)
3934 {
3935 ERROR_MSG(_T("Error: variable with empty name!\n"));
3936 return PS_ERROR;
3937 }
3938 else
3939 {
3940 while (*pVarName)
3941 {
3942 if (!isSimpleChar(*pVarName))
3943 {
3944 ERROR_MSG(_T("Error: invalid characters in variable name \"%") NPRIs _T("\", use only characters [a-z][A-Z][0-9], '.' and '_'\n"), szVarName);
3945 return PS_ERROR;
3946 }
3947 pVarName++;
3948 }
3949 }
3950
3951 m_UserVarNames.add(szVarName);
3952 if (m_UserVarNames.getnum() > MAX_CODED)
3953 {
3954 ERROR_MSG(_T("Error: too many user variables declared. Maximum allowed is %u.\n"), MAX_CODED - m_iBaseVarsNum);
3955 return PS_ERROR;
3956 }
3957 return PS_OK;
3958 }
3959
3960
3961 int CEXEBuild::GetUnsafeUserVarIndex(LineParser &line, int token)
3962 {
3963 TCHAR *p = line.gettoken_str(token);
3964 int idx = IsVarPrefix(p) ? m_UserVarNames.get(++p) : -1;
3965 if (idx >= 0 && m_UserVarNames.get_reference(idx) >= 0) m_UserVarNames.inc_reference(idx);
3966 return idx;
3967 }
3968 int CEXEBuild::GetUserVarIndex(LineParser &line, int token)
3969 {
3970 TCHAR *p = line.gettoken_str(token);
3971 if (IsVarPrefix(p))
3972 {
3973 int idxUserVar = m_UserVarNames.get(p+1);
3974 if (idxUserVar >= 0 && m_UserVarNames.get_reference(idxUserVar) >= 0)
3975 {
3976 m_UserVarNames.inc_reference(idxUserVar);
3977 return idxUserVar;
3978 }
3979 else
3980 {
3981 int idxConst = m_ShellConstants.get(p+1);
3982 if (idxConst >= 0)
3983 {
3984 ERROR_MSG(_T("Error: cannot change constants : %") NPRIs _T("\n"), p);
3985 }
3986 }
3987 }
3988 return -1;
3989 }
3990
3991 void CEXEBuild::VerifyDeclaredUserVarRefs(UserVarsStringList *pVarsStringList)
3992 {
3993 for (int i = m_iBaseVarsNum; i < pVarsStringList->getnum(); i++)
3994 {
3995 if (!pVarsStringList->get_reference(i))
3996 {
3997 warning(DW_VAR_NOREF, _T("Variable \"%") NPRIs _T("\" not referenced or never set, wasting memory!"), pVarsStringList->idx2name(i));
3998 }
3999 }
4000 }
4001
4002 bool CEXEBuild::IsIntOrUserVar(const LineParser &line, int token) const
4003 {
4004 const TCHAR *p = line.gettoken_str(token);
4005 if (IsVarPrefix(p))
4006 {
4007 int idxUserVar = m_UserVarNames.get(p+1);
4008 return (idxUserVar >= 0 && m_UserVarNames.get_reference(idxUserVar) >= 0);
4009 }
4010 int succ;
4011 line.gettoken_int(token, &succ);
4012 return succ != false;
4013 }
4014
4015 int CEXEBuild::set_target_architecture_data()
4016 {
4017 build_strlist.setunicode(build_unicode), ubuild_strlist.setunicode(build_unicode);
4018 size_t t64 = is_target_64bit(), i;
4019
4020 WORD dc = DefaultPEDllCharacteristics;
4021 if ((dc & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) && t64) dc |= IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA;
4022 if (m_target_type == TARGET_ARM64) dc &= ~IMAGE_DLLCHARACTERISTICS_NO_SEH; // ARM64 forces exception directory?
4023 PEDllCharacteristics = dc;
4024
4025 if (build_unicode)
4026 {
4027 definedlist.set(_T("NSIS_UNICODE"));
4028 definedlist.set(_T("NSIS_CHAR_SIZE"), _T("2"));
4029 }
4030 else
4031 {
4032 definedlist.del(_T("NSIS_UNICODE"));
4033 definedlist.set(_T("NSIS_CHAR_SIZE"), _T("1"));
4034 }
4035 definedlist.set(_T("NSIS_PTR_SIZE"), t64 ? _T("8") : _T("4"));
4036
4037 const TCHAR* tsuff = get_target_suffix(m_target_type, _T(""));
4038 if (!*tsuff) return PS_ERROR;
4039 tstring cpu = get_string_prefix(tsuff, _T("-"));
4040 definedlist.set(_T("NSIS_CPU"), cpu.c_str()); // Used by Library.nsh to pick the correct RegTool
4041
4042 struct { TARGETTYPE tt; const TCHAR *def; const TCHAR *val; } static const tdef[] = {
4043 { TARGET_X86ANSI, _T("NSIS_IX86"), _T("300") },
4044 { TARGET_X86UNICODE, _T("NSIS_IX86"), _T("400") },
4045 { TARGET_AMD64, _T("NSIS_AMD64"), _T("1") },
4046 { TARGET_ARM64, _T("NSIS_ARM64"), _T("1") }
4047 };
4048 for (i = 0; i < COUNTOF(tdef); ++i) definedlist.del(tdef[i].def);
4049 unsigned int success = false;
4050 for (i = 0; i < COUNTOF(tdef); ++i) if (tdef[i].tt == m_target_type) definedlist.set(tdef[i].def, tdef[i].val), ++success;
4051
4052 return success ? PS_OK : PS_ERROR;
4053 }
4054
4055 const TCHAR* CEXEBuild::get_target_suffix(CEXEBuild::TARGETTYPE tt, const TCHAR*defval) const
4056 {
4057 switch(tt)
4058 {
4059 case TARGET_X86ANSI : return _T("x86-ansi");
4060 case TARGET_X86UNICODE: return _T("x86-unicode");
4061 case TARGET_AMD64 : return _T("amd64-unicode");
4062 case TARGET_ARM64 : return _T("arm64-unicode");
4063 default: return defval;
4064 }
4065 }
4066
4067 int CEXEBuild::change_target_architecture(TARGETTYPE tt)
4068 {
4069 const bool wide = TARGET_X86ANSI != tt;
4070 if (build_compressor_set || (build_unicode != wide && build_lockedunicodetarget))
4071 {
4072 ERROR_MSG(_T("Error: Can't change target %") NPRIs _T(" after data already got compressed or header already changed!\n"), _T("architecture"));
4073 return PS_ERROR;
4074 }
4075
4076 if (TARGET_X86ANSI == m_target_type || TARGET_X86UNICODE == m_target_type)
4077 m_previous_x86_unicode = build_unicode;
4078 m_target_type = tt;
4079 build_unicode = wide;
4080
4081 int ec = set_target_architecture_data();
4082 if (PS_OK == ec) ec = load_stub();
4083 #ifdef NSIS_CONFIG_PLUGIN_SUPPORT
4084 if (PS_OK == ec) ec = initialize_default_plugins(true);
4085 #endif
4086 changed_target = true;
4087 return ec;
4088 }
4089
4090 int CEXEBuild::set_compressor(const tstring& compressor, const bool solid) {
4091 stub_filename = stubs_dir + PLATFORM_PATH_SEPARATOR_STR + compressor;
4092 if (solid)
4093 stub_filename += _T("_solid");
4094 return load_stub();
4095 }
4096
4097 CEXEBuild::TARGETTYPE CEXEBuild::get_target_type(const TCHAR*s) const
4098 {
4099 for(int i = CEXEBuild::TARGETFIRST; i < CEXEBuild::TARGETCOUNT; ++i)
4100 {
4101 CEXEBuild::TARGETTYPE tt = (CEXEBuild::TARGETTYPE) i;
4102 if (!_tcsicmp(get_target_suffix(tt, _T("")),s) && *s) return tt;
4103 }
4104 return TARGET_UNKNOWN;
4105 }
4106
4107 void CEXEBuild::print_bad_targettype_parameter(const TCHAR*cmdname, const TCHAR*prefix) const
4108 {
4109 tstring errstr = cmdname;
4110 errstr += _T(": Target parameter must be one of: "), errstr += prefix;
4111 for(int comma = 0, i = CEXEBuild::TARGETFIRST; i < CEXEBuild::TARGETCOUNT; ++i)
4112 {
4113 const TCHAR *ts = get_target_suffix((CEXEBuild::TARGETTYPE) i, 0);
4114 if (!ts) continue;
4115 if (comma++) errstr += _T(", "), errstr += prefix;
4116 errstr += ts;
4117 }
4118 ERROR_MSG(_T("Error: %") NPRIs _T("\n"), errstr.c_str());
4119 }
4120
4121 int CEXEBuild::load_stub()
4122 {
4123 return update_exehead(stub_filename+_T("-")+get_target_suffix(), &m_exehead_original_size);
4124 }
4125
4126 int CEXEBuild::update_exehead(const tstring& file, size_t *size/*=NULL*/) {
4127 unsigned long exehead_size;
4128 unsigned char *exehead = alloc_and_read_file(file.c_str(), exehead_size);
4129 if (!exehead)
4130 {
4131 ERROR_MSG(_T("Error: reading stub \"%") NPRIs _T("\"\n"), file.c_str());
4132 return PS_ERROR;
4133 }
4134 update_exehead(exehead, exehead_size);
4135 if (size) *size = exehead_size;
4136 free(exehead);
4137 return PS_OK;
4138 }
4139
4140 void CEXEBuild::update_exehead(const unsigned char *new_exehead, size_t new_size) {
4141 assert(m_exehead != new_exehead);
4142
4143 // align exehead to 512
4144 m_exehead_size = align_to_512(new_size);
4145
4146 delete [] m_exehead;
4147 m_exehead = new unsigned char[m_exehead_size];
4148
4149 // copy exehead
4150 memcpy(m_exehead, new_exehead, new_size);
4151
4152 // zero rest of exehead
4153 memset(m_exehead + new_size, 0, m_exehead_size - new_size);
4154 }
4155
4156 void CEXEBuild::set_code_type_predefines(const TCHAR *value)
4157 {
4158 definedlist.del(_T("__SECTION__"));
4159 definedlist.del(_T("__FUNCTION__"));
4160 definedlist.del(_T("__PAGEEX__"));
4161 definedlist.del(_T("__GLOBAL__"));
4162
4163 switch (GetCurrentTokenPlace())
4164 {
4165 case TP_SEC:
4166 definedlist.add(_T("__SECTION__"), value==NULL?_T(""):value);
4167 break;
4168 case TP_FUNC:
4169 definedlist.add(_T("__FUNCTION__"), value==NULL?_T(""):value);
4170 break;
4171 case TP_PAGEEX:
4172 definedlist.add(_T("__PAGEEX__"), value==NULL?_T(""):value);
4173 break;
4174 default:
4175 definedlist.add(_T("__GLOBAL__"));
4176 }
4177 }
4178
4179 void CEXEBuild::postbuild_cmd::delete_all()
4180 {
4181 for (struct postbuild_cmd *p = this, *tmp; p;)
4182 {
4183 tmp = p, p = p->next;
4184 delete [] tmp;
4185 }
4186 }
4187
4188 CEXEBuild::postbuild_cmd* CEXEBuild::postbuild_cmd::make(const TCHAR *cmdstr, int cmpop, int cmpval)
4189 {
4190 postbuild_cmd *p = (postbuild_cmd*) (new BYTE[FIELD_OFFSET(postbuild_cmd, cmd[_tcsclen(cmdstr)+!0])]);
4191 p->next = NULL, _tcscpy(p->cmd, cmdstr);
4192 p->cmpop = cmpop, p->cmpval = cmpval;
4193 return p;
4194 }
4195
4196 int CEXEBuild::run_postbuild_cmds(const postbuild_cmd *cmds, const TCHAR *templatearg_pc1, const TCHAR* commandname)
4197 {
4198 for (const postbuild_cmd *cmd = cmds; cmd; cmd = cmd->next)
4199 {
4200 const TCHAR *cmdstr = cmd->cmd, *searchstart = cmdstr;
4201 TCHAR *arg, *cmdstrbuf = NULL, *tmpbuf;
4202 for (; (arg = _tcsstr(const_cast<TCHAR*>(searchstart), _T("%1")));) // While found, replace %1 with templatearg_pc1
4203 {
4204 const size_t cchtpc1 = _tcslen(templatearg_pc1);
4205 tmpbuf = (TCHAR*) malloc((_tcslen(cmdstr) + cchtpc1 + !0) * sizeof(TCHAR));
4206 if (!tmpbuf)
4207 {
4208 ERROR_MSG(_T("Error: Can't allocate memory for %") NPRIs _T(" command\n"), commandname);
4209 return PS_ERROR;
4210 }
4211 arg -= ((UINT_PTR)cmdstr)/sizeof(TCHAR), arg += ((UINT_PTR)tmpbuf)/sizeof(TCHAR);
4212 _tcscpy(tmpbuf, cmdstr);
4213 free(cmdstrbuf);
4214 memmove(arg + cchtpc1, arg + 2, (_tcslen(arg + 2) + !0) * sizeof(TCHAR));
4215 memmove(arg, templatearg_pc1, cchtpc1 * sizeof(TCHAR));
4216 // BUGBUG: Should we call PathConvertWinToPosix on templatearg_pc1?
4217 cmdstr = cmdstrbuf = tmpbuf, searchstart = arg + cchtpc1;
4218 }
4219 SCRIPT_MSG(_T("\n%") NPRIs _T(" command: %") NPRIs _T("\n"), commandname, cmdstr);
4220 int ret = sane_system(cmdstr);
4221 if (!check_external_exitcode(ret, cmd->cmpop, cmd->cmpval))
4222 {
4223 ERROR_MSG(_T("%") NPRIs _T(" command returned %d, aborting\n"), commandname, ret);
4224 return PS_ERROR;
4225 }
4226 if (ret != 0) INFO_MSG(_T("%") NPRIs _T(" command returned %d\n"), commandname, ret);
4227 free(cmdstrbuf);
4228 }
4229 return PS_OK;
4230 }
4231
4232 int CEXEBuild::check_external_exitcode(int exitcode, int op, int val)
4233 {
4234 switch(op)
4235 {
4236 case 0: return exitcode < val;
4237 case 1: return exitcode > val;
4238 case 2: return exitcode != val;
4239 case 3: return exitcode == val;
4240 case 4: return -1; // ignore
4241 }
4242 return 0;
4243 }