forked from kichik/nsis
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathscript.cpp
5518 lines (5248 loc) · 214 KB
/
script.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* script.cpp
*
* This file is a part of NSIS.
*
* Copyright (C) 1999-2023 Nullsoft and Contributors
*
* Licensed under the zlib/libpng license (the "License");
* you may not use this file except in compliance with the License.
*
* Licence details can be found in the file COPYING.
*
* This software is provided 'as-is', without any express or implied
* warranty.
*/
#include "Platform.h"
#include <stdio.h>
#include <ctype.h>
#include "tokens.h"
#include "build.h"
#include "util.h"
#include "winchar.h"
#include "ResourceEditor.h"
#include "DialogTemplate.h"
#include "BinInterop.h"
#include "lang.h"
#include "dirreader.h"
#include <nsis-version.h>
#include "icon.h"
#include "exehead/api.h"
#include "exehead/resource.h"
#include <cassert> // for assert(3)
#include <time.h>
#include "tstring.h"
#include "utf.h"
#include <algorithm>
#include "boost/scoped_ptr.hpp"
using namespace std;
#ifndef _WIN32
# include <sys/stat.h> // for stat and umask
# include <sys/types.h> // for mode_t
# include <fcntl.h> // for O_RDONLY
# include <unistd.h>
# include <stdlib.h> // for mkstemp
#endif
#define REGROOTKEYTOINT(hk) ( (INT) (((INT_PTR)(hk)) & 0xffffffff) ) // Masking off non-existing top bits to make GCC happy
#define REGROOTKEYTOINTEX(hk, removeviewbits) ( REGROOTKEYTOINT(hk) & ~(removeviewbits ? (REGROOTVIEW32|REGROOTVIEW64) : 0) )
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
typedef enum { LU_INVALID = -1, LU_PIXEL = 0, LU_DIALOG } LAYOUTUNIT;
static int ParseLayoutUnit(const TCHAR*Str, LAYOUTUNIT&LU)
{
TCHAR buf[200];
int succ, val = LineParser::parse_int(Str, &succ);
if (succ) return (LU = LU_PIXEL, val);
size_t cch = my_strncpy(buf, Str, COUNTOF(buf));
if (cch > 1 && S7IsChEqualI('u', buf[cch-1])) // Something with a 'u' suffix?
{
buf[cch-1] = _T('\0');
val = LineParser::parse_int(buf, &succ);
if (succ) return (LU = LU_DIALOG, val);
}
return (LU = LU_INVALID, -1);
}
#endif
#ifdef NSIS_CONFIG_ENHANCEDUI_SUPPORT
static bool LookupWinSysColorId(const TCHAR*Str, UINT&Clr)
{
static const struct { const TCHAR*Name; UINT Id; } map[] = { // Note: This list is incomplete.
{ _T("WINDOW"), 5 }, { _T("WINDOWTEXT"), 8 },
{ _T("3DFACE"), 15 }, { _T("BTNTEXT"), 18 }, // "Three-dimensional display elements and dialog box"
{ _T("HIGHLIGHT"), 13 }, { _T("HIGHLIGHTTEXT"), 14 }, // "Item(s) selected in a control"
{ _T("GRAYTEXT"), 17 }, // "Grayed (disabled) text"
{ _T("HOTLIGHT"), 26 }, // "Color for a hyperlink or hot-tracked item" (Win98+)
};
for (UINT i = 0; i < COUNTOF(map); ++i)
if (!_tcsicmp(map[i].Name, Str)) return (Clr = map[i].Id, true);
return false;
}
static UINT ParseCtlColor(const TCHAR*Str, int&CCFlags, int CCFlagmask)
{
UINT clr, v;
TCHAR buf[7+!0], *pEnd;
my_strncpy(buf, Str, 7+!0), buf[7] = '\0';
if (!_tcscmp(_T("SYSCLR:"), buf))
{
CCFlags |= ((CC_TEXT_SYS|CC_BK_SYS) & CCFlagmask); // ExeHead must call GetSysColor
if (!LookupWinSysColorId(Str+7, clr)) clr = _tcstoul(Str+7, &pEnd, 0);
}
else
v = _tcstoul(Str, &pEnd, 16), clr = ((v&0xff)<<16)|(v&0xff00)|((v&0xff0000)>>16);
return clr;
}
#endif //~ NSIS_CONFIG_ENHANCEDUI_SUPPORT
static LANGID ParseLangId(const TCHAR*Str)
{
const TCHAR *p = Str;
if (_T('+') == *p || _T('-') == *p) ++p;
return _T('0') == p[0] && _T('x') == (p[1]|32) ? LineParser::parse_int(Str) : _ttoi(Str);
}
LANGID CEXEBuild::ParseLangIdParameter(const LineParser&line, int token)
{
int succ, lid = line.gettoken_int(token, &succ);
if (!lid) lid = last_used_lang;
if (!succ)
warning_fl(DW_BAD_LANGID, _T("\"%") NPRIs _T("\" is not a valid language id, using language id %u!"), line.gettoken_str(token), lid);
return lid;
}
int CEXEBuild::process_script(NIStream&Strm, const TCHAR *filename)
{
NStreamLineReader linereader(Strm);
curlinereader = &linereader;
curfilename = filename;
linecnt = 0;
if (has_called_write_output)
{
ERROR_MSG(_T("Error (process_script): write_output already called, can't continue\n"));
return PS_ERROR;
}
#ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
set_date_time_predefines();
TCHAR *oldfilename = set_file_predefine(curfilename);
TCHAR *oldtimestamp = set_timestamp_predefine(curfilename);
#endif
int ret=parseScript();
#ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
restore_file_predefine(oldfilename);
restore_timestamp_predefine(oldtimestamp);
del_date_time_predefines();
#endif
curlinereader = 0;
curfilename = 0;
if (m_linebuild.getlen())
{
ERROR_MSG(_T("Error: invalid script: last line ended with \\\n"));
return PS_ERROR;
}
if (ret == PS_EOF && num_ifblock())
{
ERROR_MSG(_T("!if[macro][n]def: open at EOF - need !endif\n"));
return PS_ERROR;
}
return ret;
}
#define PRINTHELPEX(cmdname) { print_help((cmdname)); return PS_ERROR; }
#define PRINTHELP() PRINTHELPEX(line.gettoken_str(0))
void CEXEBuild::start_ifblock()
{
ifblock ib = {0, };
if (cur_ifblock)
ib.inherited_ignore = cur_ifblock->ignore || cur_ifblock->inherited_ignore;
int num = build_preprocessor_data.getlen() / sizeof(ifblock);
build_preprocessor_data.add(&ib, sizeof(ifblock));
cur_ifblock = (ifblock *) build_preprocessor_data.get() + num;
}
void CEXEBuild::end_ifblock()
{
if (build_preprocessor_data.getlen())
{
cur_ifblock--;
build_preprocessor_data.resize(build_preprocessor_data.getlen() - sizeof(ifblock));
if (!build_preprocessor_data.getlen())
cur_ifblock = 0;
}
}
int CEXEBuild::num_ifblock()
{
return build_preprocessor_data.getlen() / sizeof(ifblock);
}
int CEXEBuild::doParse(int verbosity, const TCHAR *fmt, ...)
{
ExpandoString<TCHAR, NSIS_MAX_STRLEN> buf;
int orgv = get_verbosity(), res;
va_list val;
va_start(val, fmt);
buf.StrVFmt(fmt, val);
va_end(val);
if (verbosity >= 0) set_verbosity(verbosity);
res = doParse(buf.GetPtr());
set_verbosity(orgv);
return res;
}
int CEXEBuild::doParse(const TCHAR *str)
{
LineParser line(inside_comment);
int res;
while (*str == _T(' ') || *str == _T('\t')) str++;
// remove trailing slash and null, if there's a previous line
if (m_linebuild.getlen()>1)
m_linebuild.resize(m_linebuild.getlen()-(2*sizeof(TCHAR)));
// warn of comment with line-continuation
if (m_linebuild.getlen())
{
LineParser prevline(inside_comment);
prevline.parse((TCHAR*)m_linebuild.get());
LineParser thisline(inside_comment);
thisline.parse(str);
if (prevline.inComment() && !thisline.inComment())
{
warning_fl(DW_COMMENT_NEWLINE, _T("comment contains line-continuation character, following line will be ignored"));
}
}
// add new line to line buffer
const unsigned int cchstr = (unsigned int) _tcslen(str);
m_linebuild.add(str,(cchstr+1)*sizeof(TCHAR));
// keep waiting for more lines if this line ends with a backslash
if (str[0] && CharPrev(str,str+cchstr)[0] == _T('\\'))
{
return PS_OK;
}
// parse before checking if the line should be ignored, so block comments won't be missed
// escaped quotes should be ignored for compile time commands that set defines
// because defines can be inserted in commands at a later stage
bool ignore_escaping = (!_tcsnicmp((TCHAR*)m_linebuild.get(),_T("!define"),7) || !_tcsncicmp((TCHAR*)m_linebuild.get(),_T("!insertmacro"),12));
NStreamEncoding enc(NStreamEncoding::UNKNOWN);
res=line.parse((TCHAR*)m_linebuild.get(), ignore_escaping, linecnt < 3 ? &enc : NULL);
if (enc.GetCodepage() != NStreamEncoding::UNKNOWN && curlinereader)
curlinereader->StreamEncoding().SafeSetCodepage(enc.GetCodepage());
inside_comment = line.inCommentBlock();
// if ignoring, ignore all lines that don't begin with an exclamation mark
{
bool ignore_line = cur_ifblock && (cur_ifblock->ignore || cur_ifblock->inherited_ignore);
if (ignore_line)
{
TCHAR *rawline = (TCHAR*) m_linebuild.get(), first_char = *rawline, buf[30], *first_token = buf;
if (!res)
first_token = line.gettoken_str(0);
else // LineParser::parse() failed so we cannot call gettoken_str but we still might need to ignore this line
for (size_t i = 0; i < COUNTOF(buf); ++i) if ((buf[i] = rawline[i]) <= ' ') { buf[i] = _T('\0'); break; }
if (first_char!=_T('!') || !is_ppbranch_token(first_token))
{
m_linebuild.resize(0);
return PS_OK;
}
}
}
GrowBuf ppoline;
if (preprocessonly) m_linebuild.swap(ppoline); // LineParser strips quotes and we need to display them
m_linebuild.resize(0);
if (res)
{
if (res==-2) ERROR_MSG(_T("Error: unterminated string parsing line at %") NPRIs _T(":%d\n"),curfilename,linecnt);
else ERROR_MSG(_T("Error: error parsing line (%") NPRIs _T(":%d)\n"),curfilename,linecnt);
return PS_ERROR;
}
parse_again:
if (line.getnumtokens() < 1) return PS_OK;
const TCHAR* const tokstr0 = line.gettoken_str(0);
int np,op,pos;
int tkid=get_commandtoken(tokstr0,&np,&op,&pos);
if (tkid == -1)
{
const TCHAR *p=tokstr0;
if (p[0] && p[_tcslen(p)-1]==_T(':'))
{
if (p[0] == _T('!') || (p[0] >= _T('0') && p[0] <= _T('9')) || p[0] == _T('$') || p[0] == _T('-') || p[0] == _T('+'))
{
ERROR_MSG(_T("Invalid label: %") NPRIs _T(" (labels cannot begin with !, $, -, +, or 0-9)\n"),tokstr0);
return PS_ERROR;
}
extern FILE *g_output;
if (preprocessonly)
_ftprintf(g_output,_T("%") NPRIs _T("\n"),tokstr0);
else
if (add_label(tokstr0)) return PS_ERROR;
line.eattoken();
goto parse_again;
}
#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
// We didn't recognise this command, could it be the name of a function exported from a dll?
// Plugins cannot be called in global scope so there is no need to initialize the list first
if (m_pPlugins && m_pPlugins->IsPluginCommand(tokstr0))
{
np = 0; // parameters are optional
op = -1; // unlimited number of optional parameters
pos = -1; // placement will tested later
tkid = TOK__PLUGINCOMMAND;
}
else
#endif
{
#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
if (Plugins::IsPluginCallSyntax(tokstr0))
{
if (m_pPlugins && display_warnings) m_pPlugins->PrintPluginDirs();
ERROR_MSG(_T("Plugin%") NPRIs _T(" not found, cannot call %") NPRIs _T("\n"),m_pPlugins && m_pPlugins->IsKnownPlugin(tokstr0) ? _T(" function") : _T(""),tokstr0);
}
else
#endif
ERROR_MSG(_T("Invalid command: \"%") NPRIs _T("\"\n"),tokstr0);
return PS_ERROR;
}
}
if (IsTokenPlacedRight(pos, tokstr0) != PS_OK)
return PS_ERROR;
int v=line.getnumtokens()-(np+1);
if (v < 0 || (op >= 0 && v > op)) // opt_parms is -1 for unlimited
{
ERROR_MSG(_T("%") NPRIs _T(" expects %d"),tokstr0,np);
if (op < 0) ERROR_MSG(_T("+"));
if (op > 0) ERROR_MSG(_T("-%d"),op+np);
ERROR_MSG(_T(" parameters, got %d.\n"),line.getnumtokens()-1);
PRINTHELP()
}
int if_from_else = 0;
if (tkid == TOK_P_ELSE)
{
if (cur_ifblock && cur_ifblock->inherited_ignore)
return PS_OK;
if (!num_ifblock())
{
ERROR_MSG(_T("!else: no if block open (!if[macro][n][def])\n"));
return PS_ERROR;
}
if (cur_ifblock->elseused)
{
ERROR_MSG(_T("!else: else already used in current if block\n"));
return PS_ERROR;
}
if (cur_ifblock->hasexeced)
{
cur_ifblock->ignore++;
return PS_OK;
}
if (line.getnumtokens() == 1)
{
cur_ifblock->ignore = !cur_ifblock->ignore;
// if not executed up until now, it will now
cur_ifblock->hasexeced++;
cur_ifblock->elseused++;
return PS_OK;
}
line.eattoken();
int v=line.gettoken_enum(0,_T("if\0ifdef\0ifndef\0ifmacrodef\0ifmacrondef\0"));
if (v < 0) PRINTHELP()
if (line.getnumtokens() == 1) PRINTHELP()
const int cmds[] = {TOK_P_IF, TOK_P_IFDEF, TOK_P_IFNDEF, TOK_P_IFMACRODEF, TOK_P_IFMACRONDEF};
tkid = cmds[v];
if_from_else++;
}
if (tkid == TOK_P_IFNDEF || tkid == TOK_P_IFDEF ||
tkid == TOK_P_IFMACRODEF || tkid == TOK_P_IFMACRONDEF ||
tkid == TOK_P_IF)
{
if (!if_from_else)
start_ifblock();
if (cur_ifblock && cur_ifblock->inherited_ignore)
{
return PS_OK;
}
int istrue=0, mod=0;
if (tkid == TOK_P_IF) {
res = pp_boolifyexpression(line, istrue, true);
if (res != PS_OK) return res;
}
else {
// pure left to right precedence. Not too powerful, but useful.
for (int p = 1; p < line.getnumtokens(); p++)
{
if (p & 1)
{
bool new_s;
if (tkid == TOK_P_IFNDEF || tkid == TOK_P_IFDEF)
new_s=!!definedlist.find(line.gettoken_str(p));
else
new_s=MacroExists(line.gettoken_str(p));
if (tkid == TOK_P_IFNDEF || tkid == TOK_P_IFMACRONDEF)
new_s=!new_s;
if (mod == 0) istrue = istrue || new_s;
else istrue = istrue && new_s;
}
else
{
mod=line.gettoken_enum(p,_T("|\0&\0||\0&&\0"));
if (mod == -1) PRINTHELP()
mod &= 1;
}
}
}
if (istrue)
{
cur_ifblock->hasexeced++;
cur_ifblock->ignore = 0;
}
else
cur_ifblock->ignore++;
return PS_OK;
}
if (tkid == TOK_P_ENDIF) {
if (!num_ifblock())
{
ERROR_MSG(_T("!endif: no if block open (!if[macro][n][def])\n"));
return PS_ERROR;
}
end_ifblock();
return PS_OK;
}
if (!cur_ifblock || (!cur_ifblock->ignore && !cur_ifblock->inherited_ignore))
{
if (preprocessonly)
{
extern FILE *g_output;
bool pptok = is_pp_token(tkid), docmd = pptok;
bool both = TOK_P_VERBOSE == tkid || TOK_P_WARNING == tkid || TOK_P_ECHO == tkid;
if (TOK_P_FINALIZE == tkid || TOK_P_UNINSTFINALIZE == tkid || TOK_P_PACKEXEHEADER == tkid) docmd = false;
if (docmd && is_unsafe_pp_token(tkid) && preprocessonly > 0) docmd = false;
if (!docmd || both) _ftprintf(g_output,(_T("%") NPRIs _T("\n")),ppoline.get());
if (!docmd && !both) return PS_OK;
}
return doCommand(tkid,line);
}
return PS_OK;
}
#ifdef NSIS_FIX_DEFINES_IN_STRINGS
void CEXEBuild::ps_addtoline(const TCHAR *str, GrowBuf &linedata, StringList &hist, bool bIgnoreDefines /*= false*/)
#else
void CEXEBuild::ps_addtoline(const TCHAR *str, GrowBuf &linedata, StringList &hist)
#endif
{
// convert $\r, $\n to their literals
// preprocessor replace ${VAR} and $%VAR% with whatever value
// note that if VAR does not exist, ${VAR} or $%VAR% will go through unmodified
const TCHAR *in=str;
while (*in)
{
int add=1;
TCHAR c=*in, *t=CharNext(in);
if (t-in > 1) // handle multibyte chars (no escape)
{
linedata.add((void*)in,truncate_cast(int, (size_t)((t-in)*sizeof(TCHAR))));
in=t;
continue;
}
in=t;
if (c == _T('$'))
{
if (in[0] == _T('\\'))
{
if (in[1] == _T('r'))
in+=2, c=_T('\r');
else if (in[1] == _T('n'))
in+=2, c=_T('\n');
else if (in[1] == _T('t'))
in+=2, c=_T('\t');
}
else if (in[0] == _T('{'))
{
TCHAR *s=_tcsdup(in+1), *t=s;
MANAGE_WITH(s, free);
unsigned int bn = 0;
while (*t)
{
if (*t == _T('{')) bn++;
if (*t == _T('}') && bn-- == 0) break;
t=CharNext(t);
}
if (*t && t!=s
#ifdef NSIS_FIX_DEFINES_IN_STRINGS
&& !bIgnoreDefines
#endif
)
{
*t=0;
// check for defines inside the define name - ${bla${blo}}
GrowBuf defname;
ps_addtoline(s,defname,hist);
defname.add(_T(""),sizeof(_T("")));
t=definedlist.find((TCHAR*)defname.get());
TCHAR dyndefbuf[10+1];
if (!t)
{
if (_T('_')==s[0] && _T('_')==s[1])
{
if (!_tcscmp(s,_T("__COUNTER__")))
{
static unsigned long cntr=0;
_stprintf(dyndefbuf,_T("%lu"),cntr++);
t=dyndefbuf;
}
}
if (_T('U')==s[0] && _T('+')==s[1])
{
TCHAR *n=s+2;
UINT32 utf32=_tcstoul(n,&t,16);
// We only want to accept "${U+HEXDIGITS}" and not "${U+ -HEXDIGITS }"
if (*t || _T('-')==*n || _T('+')==*n) t=0;
if (_T(' ')==*n || _T('\t')==*n) t=0; // TODO: _istspace()?
if (!utf32) t=0; // Don't allow "${U+0}"
if (t)
{
UINT32 codpts[]={utf32,UNICODE_REPLACEMENT_CHARACTER,'?'};
for(size_t i=0, cch; i < COUNTOF(codpts); ++i)
{
cch = WCFromCodePoint(dyndefbuf,COUNTOF(dyndefbuf),codpts[i]);
if (cch) { dyndefbuf[cch] = _T('\0'); break; }
}
t=dyndefbuf;
}
}
}
if (t && hist.find((TCHAR*)defname.get(),0)<0)
{
in+=_tcslen(s)+2;
add=0;
hist.add((TCHAR*)defname.get(),0);
#ifdef NSIS_FIX_DEFINES_IN_STRINGS
ps_addtoline(t,linedata,hist,true);
#else
ps_addtoline(t,linedata,hist);
#endif
hist.delbypos(hist.find((TCHAR*)defname.get(),0));
}
}
}
else if (in[0] == _T('%'))
{
TCHAR *s=_tcsdup(in+1);
MANAGE_WITH(s, free);
TCHAR *t=s;
while (*t)
{
if (*t == _T('%')) break;
t=CharNext(t);
}
if (*t && t!=s)
{
*t=0;
// check for defines inside the define name - ${bla${blo}}
GrowBuf defname;
ps_addtoline(s,defname,hist);
defname.add(_T(""),sizeof(_T("")));
t=_tgetenv((TCHAR*)defname.get());
if (t && hist.find((TCHAR*)defname.get(),0)<0)
{
in+=_tcslen(s)+2;
add=0;
hist.add((TCHAR*)defname.get(),0);
#ifdef NSIS_FIX_DEFINES_IN_STRINGS
ps_addtoline(t,linedata,hist,true);
#else
ps_addtoline(t,linedata,hist);
#endif
hist.delbypos(hist.find((TCHAR*)defname.get(),0));
}
}
}
#ifdef NSIS_FIX_DEFINES_IN_STRINGS
else if (in[0] == _T('$'))
{
if (in[1] == _T('{')) // Found $$ before - Don't replace this define
{
TCHAR *s=_tcsdup(in+2);
MANAGE_WITH(s, free);
TCHAR *t=s;
unsigned int bn = 0;
while (*t)
{
if (*t == _T('{')) bn++;
if (*t == _T('}') && bn-- == 0) break;
t=CharNext(t);
}
if (*t && t!=s)
{
*t=0;
// add text unchanged
GrowBuf defname;
ps_addtoline(s,defname,hist);
in++;
}
}
else
{
linedata.add((void*)&c,1*sizeof(TCHAR));
in++;
}
}
#endif
}
if (add) linedata.add((void*)&c,1*sizeof(TCHAR));
}
}
int CEXEBuild::parseScript()
{
assert(curlinereader);
TCHAR *str = m_templinebuf;
NStreamLineReader &linereader = *curlinereader;
for (;;)
{
UINT lrres = linereader.ReadLine(str,MAX_LINELENGTH);
linecnt++;
if (NStream::OK != lrres)
{
if (linereader.IsEOF())
{
if (!str[0]) break;
}
else
{
ERROR_MSG(linereader.GetErrorMessage(lrres,curfilename,linecnt).c_str());
return PS_ERROR;
}
}
// remove trailing whitespace
TCHAR *p = str;
while (*p) p++;
if (p > str) p--;
while (p >= str && (*p == _T('\r') || *p == _T('\n') || *p == _T(' ') || *p == _T('\t'))) p--;
*++p=0;
StringList hist;
GrowBuf linedata;
#ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
TCHAR *oldline = set_line_predefine(linecnt, FALSE);
#endif
ps_addtoline(str,linedata,hist);
linedata.add(_T(""),sizeof(_T("")));
int ret=doParse((TCHAR*)linedata.get());
#ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
restore_line_predefine(oldline);
#endif
if (ret != PS_OK) return ret;
}
return PS_EOF;
}
int CEXEBuild::LoadLicenseFile(const TCHAR *file, TCHAR** pdata, const TCHAR *cmdname, WORD AnsiCP) // caller must free *pdata, even on error result
{
NIStream strm;
if (!strm.OpenFileForReading(file))
{
ERROR_MSG(_T("%") NPRIs _T(": open failed \"%") NPRIs _T("\"\n"),cmdname,file);
print_help(cmdname);
return PS_ERROR;
}
FILE *f=strm.GetHandle();
UINT cbBOMOffset=ftell(f); // We might be positioned after a BOM
UINT32 cbFileSize=get_file_size32(f);
UINT cbFileData=(invalid_file_size32 == cbFileSize) ? 0 : cbFileSize - cbBOMOffset;
if (!cbFileData)
{
warning_fl(DW_LICENSE_EMPTY, _T("%") NPRIs _T(": empty license file \"%") NPRIs _T("\"\n"),cmdname,file);
}
else
build_lockedunicodetarget=true;
fseek(f,cbBOMOffset,SEEK_SET);
UINT cbTotalData=sizeof(TCHAR)+cbFileData+sizeof(TCHAR); // SF_*+file+\0
TCHAR*data=(TCHAR*)malloc(cbTotalData);
*pdata=data; // memory will be released by caller
if (!data)
{
ERROR_MSG(_T("Internal compiler error #12345: %") NPRIs _T(" malloc(%d) failed.\n"),cmdname,cbTotalData);
return PS_ERROR;
}
*((TCHAR*)((char*)data+cbTotalData-sizeof(TCHAR)))=_T('\0');
TCHAR*ldata=data+1;
if (!strm.ReadOctets(ldata,&cbFileData))
{
ERROR_MSG(_T("%") NPRIs _T(": can't read file.\n"),cmdname);
return PS_ERROR;
}
// We have to convert the content of the license file to wchar_t
const WORD srccp=strm.StreamEncoding().IsUnicode() ? strm.StreamEncoding().GetCodepage() : AnsiCP;
const UINT cbcu=NStreamEncoding::GetCodeUnitSize(srccp);
if (sizeof(TCHAR) < cbcu)
{
l_errwcconv:
ERROR_MSG(_T("%") NPRIs _T(": wchar_t conversion failed!\n"),cmdname);
return PS_ERROR;
}
// Create a fake character in the "header" part of the buffer (For DupWCFromBytes)
char*lichdr=((char*)ldata) - cbcu;
*((char*)lichdr)='X';
if (cbcu > 1) *((WORD*)lichdr)='X';
//BUGBUG: No room, cannot support UTF-32: if (cbcu > 2) *((UINT32*)lichdr)='X';
const bool canOptRet = (char*)data == lichdr;
wchar_t*wcdata=DupWCFromBytes(lichdr,cbcu+cbFileData,srccp|(canOptRet?DWCFBF_ALLOWOPTIMIZEDRETURN:0));
if (!wcdata) goto l_errwcconv;
if (wcdata != data) free(data);
*pdata=data=wcdata, ldata=data+1;
const bool isRTF=!memcmp(ldata,_T("{\\rtf"),5*sizeof(TCHAR));
if (isRTF)
*data=SF_RTF;
else
*data=build_unicode ? (SF_TEXT|SF_UNICODE) : (SF_TEXT);
return PS_OK;
}
int CEXEBuild::process_oneline(const TCHAR *line, const TCHAR *filename, int linenum, unsigned int plflags)
{
const TCHAR *last_filename = curfilename;
int last_linecnt = linecnt;
curfilename = filename, linecnt = linenum;
StringList hist;
GrowBuf linedata;
#ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
TCHAR *oldfilename = NULL, *oldtimestamp = NULL, *oldline = NULL;
bool realfile = !(plflags & PLF_VIRTUALFILE);
bool is_macro = (plflags & PLF_MACRO);
bool setline = linenum != 0;
if (setline) {
if (!is_macro) {
oldfilename = set_file_predefine(curfilename);
if (realfile) oldtimestamp = set_timestamp_predefine(curfilename);
}
oldline = set_line_predefine(linecnt, is_macro);
}
#endif
ps_addtoline(line,linedata,hist);
linedata.add(_T(""),sizeof(_T("")));
int ret = doParse((TCHAR*)linedata.get());
#ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
if (setline) {
if (!is_macro) {
restore_file_predefine(oldfilename);
if (realfile) restore_timestamp_predefine(oldtimestamp);
}
restore_line_predefine(oldline);
}
#endif
curfilename = last_filename, linecnt = last_linecnt;
return ret;
}
int CEXEBuild::process_jump(LineParser &line, int wt, int *offs)
{
const TCHAR *s=line.gettoken_str(wt);
int v;
if (!_tcsicmp(s,_T("0")) || !_tcsicmp(s,_T(""))) *offs=0;
else if ((v=GetUserVarIndex(line, wt))>=0)
{
*offs=-v-1; // to jump to a user variable target, -variable_index-1 is stored.
}
else
{
if ((s[0] == _T('-') || s[0] == _T('+')) && !_ttoi(s+1))
{
ERROR_MSG(_T("Error: Goto targets beginning with '+' or '-' must be followed by nonzero integer (relative jump)\n"));
return 1;
}
if ((s[0] >= _T('0') && s[0] <= _T('9')) || s[0] == _T('$') || s[0] == _T('!'))
{
ERROR_MSG(_T("Error: Goto targets cannot begin with 0-9, $, !\n"));
return 1;
}
*offs=ns_label.add(s,0);
}
return 0;
}
#define SECTION_FIELD_GET(field) (FIELD_OFFSET(section, field)/sizeof(int))
#define SECTION_FIELD_SET(field) (-1 - (int)(FIELD_OFFSET(section, field)/sizeof(int)))
#define INVALIDREGROOT ( (HKEY) (UINT_PTR) 0x8000baad )
static HKEY ParseRegRootKey(LineParser &line, int tok)
{
static const TCHAR *rootkeys[2] = {
_T("HKCR\0HKLM\0HKCU\0HKU\0HKCC\0HKDD\0HKPD\0SHCTX\0HKCR32\0HKCR64\0HKCU32\0HKCU64\0HKLM32\0HKLM64\0HKCRANY\0HKCUANY\0HKLMANY\0SHCTX32\0SHCTX64\0SHCTXANY\0"),
_T("HKEY_CLASSES_ROOT\0HKEY_LOCAL_MACHINE\0HKEY_CURRENT_USER\0HKEY_USERS\0HKEY_CURRENT_CONFIG\0HKEY_DYN_DATA\0HKEY_PERFORMANCE_DATA\0SHELL_CONTEXT\0")
};
static const HKEY rootkey_tab[] = {
HKEY_CLASSES_ROOT,HKEY_LOCAL_MACHINE,HKEY_CURRENT_USER,HKEY_USERS,HKEY_CURRENT_CONFIG,HKEY_DYN_DATA,HKEY_PERFORMANCE_DATA,HKSHCTX,HKCR32,HKCR64,HKCU32,HKCU64,HKLM32,HKLM64,HKCRANY,HKCUANY,HKLMANY,HKSHCTX32,HKSHCTX64,HKSHCTXANY
};
int k = line.gettoken_enum(tok, rootkeys[0]);
if (k == -1) k = line.gettoken_enum(tok, rootkeys[1]);
return k == -1 ? INVALIDREGROOT : rootkey_tab[k];
}
#define AFIE_LASTUSED ( -1 )
int CEXEBuild::add_flag_instruction_entry(int which_token, int opcode, LineParser &line, int offset, int data)
{
entry ent = { opcode, };
switch(opcode)
{
case EW_SETFLAG:
ent.offsets[0] = offset;
if (data != AFIE_LASTUSED) ent.offsets[1] = data; else ent.offsets[2] = 1;
if (display_script) SCRIPT_MSG(_T("%") NPRIs _T(": %") NPRIs _T("\n"), get_commandtoken_name(which_token), line.gettoken_str(1));
return add_entry(&ent);
case EW_IFFLAG:
if (process_jump(line, 1, &ent.offsets[0]) || process_jump(line, 2, &ent.offsets[1])) PRINTHELP()
ent.offsets[2]=offset;
ent.offsets[3]=data;
if (display_script) SCRIPT_MSG(_T("%") NPRIs _T(" ?%") NPRIs _T(":%") NPRIs _T("\n"), get_commandtoken_name(which_token), line.gettoken_str(1), line.gettoken_str(2));
return add_entry(&ent);
case EW_GETFLAG:
if ((ent.offsets[0] = GetUserVarIndex(line, 1)) < 0) PRINTHELP();
ent.offsets[1] = offset;
if (display_script) SCRIPT_MSG(_T("%") NPRIs _T(": %") NPRIs _T("\n"), get_commandtoken_name(which_token), line.gettoken_str(1));
return add_entry(&ent);
}
return PS_ERROR;
}
int CEXEBuild::doCommand(int which_token, LineParser &line)
{
#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
if (PS_OK != initialize_default_plugins()) return PS_ERROR;
#endif
multiple_entries_instruction=0;
entry ent={0,};
switch (which_token)
{
// macro stuff
///////////////////////////////////////////////////////////////////////////////
case TOK_P_MACRO:
return pp_macro(line);
case TOK_P_MACROEND:
return (ERROR_MSG(_T("!macroend: no macro currently open.\n")), PS_ERROR);
case TOK_P_MACROUNDEF:
return pp_macroundef(line);
case TOK_P_INSERTMACRO:
return pp_insertmacro(line);
// preprocessor files fun
///////////////////////////////////////////////////////////////////////////////
case TOK_P_TEMPFILE:
return pp_tempfile(line);
case TOK_P_DELFILE:
return pp_delfile(line);
case TOK_P_APPENDFILE:
return pp_appendfile(line);
case TOK_P_APPENDMEMFILE:
return pp_appendmemfile(line);
case TOK_P_GETDLLVERSION:
case TOK_P_GETTLBVERSION:
return pp_getversion(which_token, line);
// page ordering stuff
///////////////////////////////////////////////////////////////////////////////
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
case TOK_UNINSTPAGE:
set_uninstall_mode(1);
case TOK_PAGE:
{
if (!uninstall_mode) {
enable_last_page_cancel = 0;
if (!_tcsicmp(line.gettoken_str(line.getnumtokens()-1),_T("/ENABLECANCEL")))
enable_last_page_cancel = 1;
}
else {
uenable_last_page_cancel = 0;
if (!_tcsicmp(line.gettoken_str(line.getnumtokens()-1),_T("/ENABLECANCEL")))
uenable_last_page_cancel = 1;
}
int k = line.gettoken_enum(1,_T("custom\0license\0components\0directory\0instfiles\0uninstConfirm\0"));
if (k < 0) PRINTHELP();
if (add_page(k) != PS_OK)
return PS_ERROR;
#ifndef NSIS_SUPPORT_CODECALLBACKS
if (!k) {
ERROR_MSG(_T("Error: custom page specified, NSIS_SUPPORT_CODECALLBACKS not defined.\n"));
return PS_ERROR;
}
#endif //~ NSIS_SUPPORT_CODECALLBACKS
if (k) { // not custom
#ifdef NSIS_SUPPORT_CODECALLBACKS
switch (line.getnumtokens() - enable_last_page_cancel) {
case 6:
PRINTHELP();
case 5:
if (*line.gettoken_str(4))
cur_page->leavefunc = ns_func.add(line.gettoken_str(4),0);
case 4:
if (*line.gettoken_str(3))
cur_page->showfunc = ns_func.add(line.gettoken_str(3),0);
case 3:
if (*line.gettoken_str(2))
cur_page->prefunc = ns_func.add(line.gettoken_str(2),0);
}
#endif //~ NSIS_SUPPORT_CODECALLBACKS
}
#ifdef NSIS_SUPPORT_CODECALLBACKS
else { // a custom page
switch (line.getnumtokens() - enable_last_page_cancel) {
case 6:
PRINTHELP();
case 5:
cur_page->caption = add_string(line.gettoken_str(4));
case 4:
if (*line.gettoken_str(3))
cur_page->leavefunc = ns_func.add(line.gettoken_str(3),0);
case 3:
if (*line.gettoken_str(2))
cur_page->prefunc = ns_func.add(line.gettoken_str(2),0);
break;
case 2:
ERROR_MSG(_T("Error: custom page must have a creator function!\n"));
PRINTHELP();
}
}
#endif //~ NSIS_SUPPORT_CODECALLBACKS
SCRIPT_MSG(_T("%") NPRIs _T("Page: %") NPRIs, uninstall_mode?_T("Uninst"):_T(""), line.gettoken_str(1));
#ifdef NSIS_SUPPORT_CODECALLBACKS
if (cur_page->prefunc>=0)
SCRIPT_MSG(_T(" (%") NPRIs _T(":%") NPRIs _T(")"), k?_T("pre"):_T("creator"), line.gettoken_str(2));
if (cur_page->showfunc>=0 && k)
SCRIPT_MSG(_T(" (show:%") NPRIs _T(")"), line.gettoken_str(3));
if (cur_page->leavefunc>=0)
SCRIPT_MSG(_T(" (leave:%") NPRIs _T(")"), line.gettoken_str(4-!k));
else if (cur_page->caption && !k)
SCRIPT_MSG(_T(" (caption:%") NPRIs _T(")"), line.gettoken_str(3));
#endif
SCRIPT_MSG(_T("\n"));
page_end();
if (k == PAGE_INSTFILES) {
add_page(PAGE_COMPLETED);
page_end();
}
set_uninstall_mode(0);
}
return PS_OK;
case TOK_PAGEEX: // extended page setting
{
int k = line.gettoken_enum(1,_T("custom\0license\0components\0directory\0instfiles\0uninstConfirm\0"));
if (k < 0) {
k = line.gettoken_enum(1,_T("un.custom\0un.license\0un.components\0un.directory\0un.instfiles\0un.uninstConfirm\0"));