Debian Codegraph @

Source/scriptpp.cpp

raw
1 /*
2 * scriptpp.cpp
3 *
4 * This file is a part of NSIS.
5 *
6 * Copyright (C) 1999-2026 Nullsoft and Contributors
7 *
8 * Licensed under the zlib/libpng license (the "License");
9 * you may not use this file except in compliance with the License.
10 *
11 * Licence details can be found in the file COPYING.
12 *
13 * This software is provided 'as-is', without any express or implied
14 * warranty.
15 */
16
17 #include "Platform.h"
18 #include <stdio.h>
19 #include <ctype.h>
20 #include "tstring.h"
21 #include "lineparse.h"
22 #include <nsis-version.h>
23 #include "tokens.h"
24 #include "build.h"
25 #include "utf.h"
26 #include "util.h"
27 #include "BinInterop.h"
28 #include "dirreader.h"
29 #include <cassert> // for assert(3)
30 #include <time.h>
31 #include <algorithm>
32 #include "boost/scoped_ptr.hpp"
33
34 using namespace std;
35
36 #ifdef _WIN32
37 # include <direct.h> // for chdir
38 #else
39 # include <sys/stat.h> // for stat and umask
40 # include <sys/types.h> // for mode_t
41 # include <fcntl.h> // for O_RDONLY
42 # include <unistd.h>
43 # include <stdlib.h> // for mkstemp
44 #endif
45
46 #define MAX_INCLUDEDEPTH 10
47
48 #define PRINTHELPEX(cmdname) { print_help((cmdname)); return PS_ERROR; }
49 #define PRINTHELP() PRINTHELPEX(line.gettoken_str(0))
50 static void PREPROCESSONLY_BEGINCOMMENT() { extern FILE *g_output; _ftprintf(g_output, _T("!if 0 /*\n")); }
51 static void PREPROCESSONLY_ENDCOMMENT() { extern FILE *g_output; _ftprintf(g_output, _T("*/\n!endif\n")); }
52
53
54 static UINT read_line_helper(NStreamLineReader&lr, TCHAR*buf, UINT cch)
55 {
56 // Helper function for reading lines from text files. buf MUST be valid and cch MUST be > 1!
57 // Returns 0 on error or the number of characters read including the first \n, \r or \0.
58 // When it returns 0, buf[0] is 0 for EOF and NStream::ERR_* for errors.
59 UINT lrr = lr.ReadLine(buf, cch), eof = 0;
60 if (NStream::OK != lrr)
61 {
62 ++eof;
63 if (!lr.IsEOF())
64 {
65 buf[0] = (TCHAR) lrr;
66 return 0;
67 }
68 }
69 const bool unicode = lr.IsUnicode();
70 for(cch = 0;; ++cch)
71 if (!buf[cch] || NStream::IsNewline(buf[cch], unicode))
72 break;
73 if (cch) eof = 0; // Read something, postpone EOF
74 return ++cch - eof;
75 }
76
77 #ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
78 TCHAR *CEXEBuild::set_file_predefine(const TCHAR *filename)
79 {
80 TCHAR *oldfileinfo = NULL;
81 TCHAR *oldfilename = definedlist.find(_T("__FILE__"));
82 TCHAR *oldfiledir = definedlist.find(_T("__FILEDIR__"));
83 if (oldfilename && oldfiledir)
84 {
85 oldfileinfo = new TCHAR[_tcslen(oldfilename)+1+_tcslen(oldfiledir)+1];
86 _tcscpy(oldfileinfo, oldfilename);
87 _tcscat(oldfileinfo, _T("|"));
88 _tcscat(oldfileinfo, oldfiledir);
89 definedlist.del(_T("__FILE__"));
90 definedlist.del(_T("__FILEDIR__"));
91 }
92 const TCHAR *p = _tcsrchr(filename,_T('\\')), *p2 = _tcsrchr(filename,_T('/'));
93 if (p2 > p) p = p2;
94 if (p) p++; else p = filename;
95 definedlist.add(_T("__FILE__"),p);
96 TCHAR dir[260]; // BUGBUG: MAX_PATH outside #ifdef _WIN32, should be PATH/NAME_MAX on POSIX?
97 #ifdef _WIN32
98 LPTSTR lpFilePart;
99 if (!GetFullPathName(filename, COUNTOF(dir), dir, &lpFilePart)) *dir = _T('\0');
100 PathRemoveFileSpec(dir);
101 #else
102 if (p == filename)
103 _tcscpy(dir, _T("."));
104 else
105 my_strncpy(dir, filename, p-filename+!0);
106 #endif
107 definedlist.add(_T("__FILEDIR__"),dir);
108 return oldfileinfo;
109 }
110 void CEXEBuild::restore_file_predefine(TCHAR *oldfilename)
111 {
112 definedlist.del(_T("__FILEDIR__"));
113 definedlist.del(_T("__FILE__"));
114 if (oldfilename)
115 {
116 TCHAR *oldfiledir = _tcschr(oldfilename, _T('|'));
117 definedlist.add(_T("__FILEDIR__"),oldfiledir+1);
118 *oldfiledir = '\0';
119 definedlist.add(_T("__FILE__"),oldfilename);
120 delete[] oldfilename;
121 }
122 }
123
124 TCHAR *CEXEBuild::set_timestamp_predefine(const TCHAR *filename)
125 {
126 TCHAR *oldtimestamp = definedlist.find(_T("__TIMESTAMP__"));
127 if (oldtimestamp)
128 {
129 oldtimestamp = _tcsdup(oldtimestamp);
130 definedlist.del(_T("__TIMESTAMP__"));
131 }
132 #ifdef _WIN32
133 TCHAR datebuf[128] = _T(""), timebuf[128] = _T(""), timestampbuf[256];
134 WIN32_FIND_DATA fd;
135 FILETIME floctime;
136 SYSTEMTIME stime;
137
138 HANDLE hSearch = FindFirstFile(filename, &fd);
139 if (hSearch != INVALID_HANDLE_VALUE)
140 {
141 FindClose(hSearch);
142
143 FileTimeToLocalFileTime(&fd.ftLastWriteTime, &floctime);
144 FileTimeToSystemTime(&floctime, &stime);
145 GetDateFormat(LOCALE_USER_DEFAULT, DATE_LONGDATE, &stime, NULL, datebuf, COUNTOF(datebuf));
146 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &stime, NULL, timebuf, COUNTOF(timebuf));
147 wsprintf(timestampbuf,_T("%") NPRIs _T(" %") NPRIs,datebuf,timebuf);
148 definedlist.add(_T("__TIMESTAMP__"),timestampbuf);
149 }
150 #else
151 struct stat st;
152 if (!_tstat(filename, &st))
153 definedlist.add(_T("__TIMESTAMP__"),PosixBug_CtoTString(ctime(&st.st_mtime)));
154 #endif
155 return oldtimestamp;
156 }
157 void CEXEBuild::restore_timestamp_predefine(TCHAR *oldtimestamp)
158 {
159 definedlist.del(_T("__TIMESTAMP__"));
160 if (oldtimestamp)
161 {
162 definedlist.add(_T("__TIMESTAMP__"),oldtimestamp);
163 free(oldtimestamp);
164 }
165 }
166
167 TCHAR *CEXEBuild::set_line_predefine(int linecnt, BOOL is_macro)
168 {
169 TCHAR* linebuf = NULL;
170 MANAGE_WITH(linebuf, free);
171
172 TCHAR temp[128] = _T("");
173 _stprintf(temp,_T("%d"),linecnt);
174
175 TCHAR *oldline = definedlist.find(_T("__LINE__"));
176 if (oldline)
177 {
178 oldline = _tcsdup(oldline);
179 definedlist.del(_T("__LINE__"));
180 }
181 if (is_macro && oldline)
182 {
183 linebuf = (TCHAR *)malloc((_tcslen(oldline)+_tcslen(temp)+2)*sizeof(TCHAR));
184 _stprintf(linebuf,_T("%") NPRIs _T(".%") NPRIs,oldline,temp);
185 }
186 else
187 {
188 linebuf = _tcsdup(temp);
189 }
190 definedlist.add(_T("__LINE__"),linebuf);
191
192 return oldline;
193 }
194 void CEXEBuild::restore_line_predefine(TCHAR *oldline)
195 {
196 definedlist.del(_T("__LINE__"));
197 if (oldline)
198 {
199 definedlist.add(_T("__LINE__"),oldline);
200 free(oldline);
201 }
202 }
203
204 void CEXEBuild::set_date_time_predefines()
205 {
206 time_t etime;
207 struct tm *ltime;
208 TCHAR datebuf[128], timebuf[128];
209
210 time(&etime);
211 ltime = localtime(&etime);
212 #ifdef _WIN32
213 SYSTEMTIME st;
214 st.wYear = ltime->tm_year+1900, st.wMonth = ltime->tm_mon + 1, st.wDay = ltime->tm_mday;
215 st.wHour = ltime->tm_hour, st.wMinute = ltime->tm_min, st.wSecond = ltime->tm_sec;
216 st.wMilliseconds = 0;
217 GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, datebuf, sizeof(datebuf));
218 definedlist.add(_T("__DATE__"), datebuf);
219 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, timebuf, sizeof(timebuf));
220 definedlist.add(_T("__TIME__"), timebuf);
221 #else
222 my_strftime(datebuf, sizeof(datebuf), _T("%x"), ltime);
223 definedlist.add(_T("__DATE__"), datebuf);
224 my_strftime(timebuf, sizeof(timebuf), _T("%X"), ltime);
225 definedlist.add(_T("__TIME__"), timebuf);
226 #endif
227 }
228 void CEXEBuild::del_date_time_predefines()
229 {
230 definedlist.del(_T("__DATE__"));
231 definedlist.del(_T("__TIME__"));
232 }
233 #endif
234
235 TCHAR* CEXEBuild::GetMacro(const TCHAR *macroname, TCHAR**macroend /*= 0*/)
236 {
237 TCHAR *t = (TCHAR*)m_macros.get(), *mbeg, *mbufbeg = t;
238 size_t cbAll = m_macros.getlen();
239 for (; t && *t; ++t)
240 {
241 mbeg = t;
242 if ((size_t)t - (size_t)mbufbeg >= cbAll) break;
243 const bool foundit = !_tcsicmp(mbeg, macroname);
244 t += _tcslen(t) + 1; // advance over macro name
245
246 // advance over parameters
247 while (*t) t += _tcslen(t) + 1;
248 t++; // Separator between parameters and data
249
250 // advance over data
251 while (*t) t += _tcslen(t) + 1;
252
253 if (foundit)
254 {
255 if (macroend) *macroend = ++t;
256 return mbeg;
257 }
258 }
259 return 0;
260 }
261
262 TCHAR* CEXEBuild::GetMacro(size_t idx)
263 {
264 TCHAR *t = (TCHAR*)m_macros.get(), *mbufbeg = t;
265 for (size_t i = 0, cbAll = m_macros.getlen(); t && *t; ++t)
266 {
267 if ((size_t)t - (size_t)mbufbeg >= cbAll) break;
268 if (i++ == idx) return t;
269 t += _tcslen(t) + 1; // advance over macro name
270 while (*t) t += _tcslen(t) + 1; // advance over parameters
271 t++; // Separator between parameters and data
272 while (*t) t += _tcslen(t) + 1; // advance over data
273 }
274 return 0;
275 }
276
277 int CEXEBuild::pp_macro(LineParser&line)
278 {
279 const TCHAR*const macroname = line.gettoken_str(1), *tokstr;
280 if (!macroname[0]) PRINTHELP()
281 if (MacroExists(macroname))
282 {
283 ERROR_MSG(_T("!macro: macro named \"%") NPRIs _T("\" already exists!\n"), macroname);
284 return PS_ERROR;
285 }
286 m_macros.add(macroname, (int)(_tcslen(macroname)+1)*sizeof(TCHAR));
287
288 for (int pc=2; pc < line.getnumtokens(); pc++)
289 {
290 if (!(tokstr = line.gettoken_str(pc))[0])
291 {
292 ERROR_MSG(_T("!macro: macro parameter %d is empty, not valid!\n"), pc-1);
293 return PS_ERROR;
294 }
295 for (int a = 2; a < pc; a++)
296 {
297 if (!_tcsicmp(tokstr, line.gettoken_str(a)))
298 {
299 ERROR_MSG(_T("!macro: macro parameter named %") NPRIs _T(" is used multiple times!\n"), tokstr);
300 return PS_ERROR;
301 }
302 }
303 m_macros.add(tokstr, (int)(_tcslen(tokstr)+1)*sizeof(TCHAR));
304 }
305 m_macros.add(_T(""), sizeof(_T(""))); // Separator between parameters and data
306
307 for (;;)
308 {
309 TCHAR *str = m_templinebuf, *p = str;
310 UINT lrres = curlinereader->ReadLine(str, MAX_LINELENGTH);
311 if (NStream::OK != lrres)
312 {
313 if (curlinereader->IsEOF())
314 {
315 if (!str[0])
316 {
317 ERROR_MSG(_T("!macro \"%") NPRIs _T("\": unterminated (no !macroend found in file)!\n"), macroname);
318 return PS_ERROR;
319 }
320 }
321 else
322 {
323 ERROR_MSG(curlinereader->GetErrorMessage(lrres).c_str());
324 return PS_ERROR;
325 }
326 }
327 //SCRIPT_MSG(_T("%") NPRIs _T("%") NPRIs, str, str[_tcslen(str)-1] == _T('\n') ? _T("") : _T("\n"));
328 // remove trailing whitespace
329 while (*p) p++;
330 if (p > str) p--;
331 while (p >= str && (*p == _T('\r') || *p == _T('\n') || *p == _T(' ') || *p == _T('\t'))) p--;
332 *++p = 0;
333 LineParser l2(false);
334 if (!l2.parse(str))
335 {
336 if (!_tcsicmp(l2.gettoken_str(0), _T("!macroend")))
337 {
338 linecnt++;
339 break;
340 }
341 if (!_tcsicmp(l2.gettoken_str(0), _T("!macro")))
342 {
343 ERROR_MSG(_T("Error: can't define a macro inside a macro!\n"));
344 return PS_ERROR;
345 }
346 }
347 if (str[0]) m_macros.add(str, (int)(_tcslen(str)+1)*sizeof(TCHAR));
348 else m_macros.add(_T(" "), sizeof(_T(" ")));
349 linecnt++;
350 }
351 m_macros.add(_T(""), sizeof(_T(""))); // End of data
352 return PS_OK;
353 }
354
355 int CEXEBuild::pp_macroundef(LineParser&line)
356 {
357 const TCHAR*const mname = line.gettoken_str(1);
358 if (!mname[0]) PRINTHELP()
359 TCHAR *mend, *mbeg = GetMacro(mname, &mend);
360 if (!mbeg)
361 {
362 ERROR_MSG(_T("!macroundef: \"%") NPRIs _T("\" does not exist!\n"), mname);
363 return PS_ERROR;
364 }
365 TCHAR *mbufb = (TCHAR*)m_macros.get();
366 const size_t mcb = ((mend)-mbeg)*sizeof(TCHAR), mbufcb = m_macros.getlen();
367 memmove(mbeg, mend, mbufcb-(((mbeg-mbufb)*sizeof(TCHAR))+mcb));
368 m_macros.resize(truncate_cast(int,(size_t)(mbufcb-mcb)));
369 SCRIPT_MSG(_T("!macroundef: %") NPRIs _T("\n"), mname);
370 return PS_OK;
371 }
372
373 int CEXEBuild::pp_insertmacro(LineParser&line)
374 {
375 static unsigned char g_insertmacrorecursion = 0;
376 const TCHAR*const macroname = line.gettoken_str(1);
377 if (!macroname[0]) PRINTHELP()
378 TCHAR *t = GetMacro(macroname), *m = (TCHAR *)m_macros.get();
379 SCRIPT_MSG(_T("!insertmacro: %") NPRIs _T("\n"), macroname);
380 if (!t)
381 {
382 ERROR_MSG(_T("!insertmacro: macro named \"%") NPRIs _T("\" not found!\n"), macroname);
383 return PS_ERROR;
384 }
385 t+=_tcslen(t)+1;
386
387 GrowBuf l_define_names;
388 DefineList l_define_saves;
389 int npr = 0;
390 // advance over params
391 while (*t)
392 {
393 TCHAR *v = definedlist.find(t);
394 if (v)
395 {
396 l_define_saves.add(t,v);
397 definedlist.del(t);
398 }
399 l_define_names.add(t, (int)(_tcslen(t)+1)*sizeof(TCHAR));
400 definedlist.add(t, line.gettoken_str(npr+2));
401
402 npr++;
403 t += _tcslen(t)+1;
404 }
405 l_define_names.add(_T(""), sizeof(_T("")));
406 t++;
407 if (npr != line.getnumtokens()-2)
408 {
409 ERROR_MSG(_T("!insertmacro: macro \"%") NPRIs _T("\" requires %d parameter(s), passed %d!\n"), macroname, npr,line.getnumtokens()-2);
410 return PS_ERROR;
411 }
412 if (++g_insertmacrorecursion > MAX_MACRORECURSION)
413 {
414 ERROR_MSG(_T("!insertmacro: insert depth is limited to %u macros!\n"), MAX_MACRORECURSION);
415 return PS_ERROR;
416 }
417 const bool oldparserinsidecomment = inside_comment;
418 inside_comment = false; // "!insertmacro foo /*" does not mean that the macro body is a comment
419 TCHAR str[1024];
420 wsprintf(str, _T("macro:%") NPRIs, macroname);
421 const TCHAR *oldmacroname = m_currentmacroname;
422 m_currentmacroname = macroname;
423 definedlist.set(_T("__MACRO__"), m_currentmacroname);
424 int lp = 0;
425 while (*t)
426 {
427 lp++;
428 if (_tcscmp(t, _T(" ")))
429 {
430 int ret = process_oneline(t, str, lp, PLF_MACRO);
431 if (ret != PS_OK)
432 {
433 ERROR_MSG(_T("Error in macro %") NPRIs _T(" on macroline %d\n"), macroname, lp);
434 return ret;
435 }
436 }
437 {
438 // fix t if process_oneline changed m_macros
439 TCHAR *nm = (TCHAR*)m_macros.get();
440 if (nm != m) t += nm - m, m = nm;
441 }
442 t += _tcslen(t)+1;
443 }
444 {
445 TCHAR *p = (TCHAR*)l_define_names.get();
446 while (*p)
447 {
448 definedlist.del(p);
449 TCHAR *v;
450 if ((v = l_define_saves.find(p)))
451 definedlist.add(p,v);
452 p += _tcslen(p)+1;
453 }
454 }
455 definedlist.del(_T("__MACRO__"));
456 m_currentmacroname = oldmacroname;
457 if (oldmacroname) definedlist.add(_T("__MACRO__"), oldmacroname);
458 inside_comment = oldparserinsidecomment;
459 --g_insertmacrorecursion;
460 SCRIPT_MSG(_T("!insertmacro: end of %") NPRIs _T("\n"), macroname);
461 return PS_OK;
462 }
463
464 int CEXEBuild::pp_tempfile(LineParser&line)
465 {
466 TCHAR *symbol = line.gettoken_str(1);
467 TCHAR *tfpath = create_tempfile_path();
468 if (!tfpath)
469 {
470 ERROR_MSG(_T("!tempfile: Unable to create temporary file!\n"));
471 return PS_ERROR;
472 }
473 int symexisted = definedlist.add(symbol, tfpath);
474 free(tfpath);
475 if (symexisted)
476 {
477 ERROR_MSG(_T("!tempfile: \"%") NPRIs _T("\" already defined!\n"), symbol);
478 return PS_ERROR;
479 }
480 return PS_OK;
481 }
482
483 int CEXEBuild::pp_delfile(LineParser&line)
484 {
485 UINT fatal = true, a = 1, matchcount = 0;
486 const TCHAR *fc = line.gettoken_str(a);
487 if (line.getnumtokens()==3)
488 {
489 if (!_tcsicmp(fc,_T("/nonfatal")))
490 fatal = 0, fc = line.gettoken_str(++a);
491 else
492 PRINTHELP();
493 }
494
495 SCRIPT_MSG(_T("!delfile: \"%") NPRIs _T("\"\n"), fc);
496 const TCHAR *fmt = _T("!delfile: \"%") NPRIs _T("\" couldn't be deleted.\n");
497
498 tstring dir = get_dir_name(fc), spec = get_file_name(fc);
499 tstring basedir = dir + PLATFORM_PATH_SEPARATOR_STR;
500 if (dir == spec) dir = _T("."), basedir = _T(""); // no path, just file name
501
502 boost::scoped_ptr<dir_reader> dr( new_dir_reader() );
503 dr->read(dir); // BUGBUG: PATH_CONVERT?
504 dir_reader::iterator files_itr = dr->files().begin();
505 for (; files_itr != dr->files().end(); files_itr++)
506 {
507 if (!dir_reader::matches(*files_itr, spec))
508 continue;
509
510 ++matchcount;
511 tstring file = basedir + *files_itr; // BUGBUG: PATH_CONVERT?
512 fc = file.c_str();
513 if (-1 == _tunlink(fc))
514 {
515 if (fatal)
516 return (ERROR_MSG(fmt, fc), PS_ERROR);
517 else
518 warning_fl(DW_PP_DELFILE_DELERROR, fmt, fc);
519 }
520 else
521 SCRIPT_MSG(_T("!delfile: deleted \"%") NPRIs _T("\"\n"), fc);
522 }
523
524 if (!matchcount)
525 {
526 if (fatal)
527 return (ERROR_MSG(fmt, fc), PS_ERROR);
528 else
529 warning_fl(DW_PP_DELFILE_NOMATCH, fmt, fc);
530 }
531 return PS_OK;
532 }
533
534 int CEXEBuild::pp_appendfile(LineParser&line)
535 {
536 WORD tok = 0, cp = 0, forceEnc = false, rawnl = false;
537 bool bom = false;
538 TCHAR *param, buf[9+!0];
539 for (;;)
540 {
541 param = line.gettoken_str(++tok);
542 my_strncpy(buf, param, COUNTOF(buf));
543 if (!_tcsicmp(param,_T("/RawNL")))
544 ++rawnl;
545 else if (!_tcsicmp(buf,_T("/CharSet=")))
546 {
547 ++forceEnc, cp = GetEncodingFromString(param+9, bom);
548 if (NStreamEncoding::UNKNOWN == cp)
549 {
550 ERROR_MSG(_T("!appendfile: Invalid parameter \"%") NPRIs _T("\"!\n"), param);
551 return PS_ERROR;
552 }
553 }
554 else
555 break;
556 }
557 if (line.getnumtokens() != 2 + tok)
558 {
559 PRINTHELP();
560 return PS_ERROR;
561 }
562 param = line.gettoken_str(tok);
563 NOStream ostrm;
564 if (!ostrm.CreateFileForAppending(param, NStreamEncoding::ACP))
565 {
566 ERROR_MSG(_T("!appendfile: \"%") NPRIs _T("\" couldn't be opened.\n"), param);
567 return PS_ERROR;
568 }
569 if (ostrm.IsUnicode()) bom = false;
570 if (forceEnc) ostrm.StreamEncoding().SetCodepage(cp);
571 const TCHAR *const text = line.gettoken_str(++tok);
572 bool succ = bom ? ostrm.WriteBOM(ostrm.StreamEncoding()) : true;
573 if (!succ || (rawnl ? !ostrm.WriteString(text) : !ostrm.WritePlatformNLString(text)))
574 {
575 ERROR_MSG(_T("!appendfile: error writing to \"%") NPRIs _T("\".\n"), param);
576 return PS_ERROR;
577 }
578 SCRIPT_MSG(_T("!appendfile: \"%") NPRIs _T("\" \"%") NPRIs _T("\"\n"), param, text);
579 return PS_OK;
580 }
581
582
583 static TinyGrowBuf* getmemfileinfo(CEXEBuild&bld, const TCHAR *id, const TCHAR **start = 0, const TCHAR **end = 0)
584 {
585 id = bld.definedlist.find(id);
586 if (!id || id[0] != _T('~') || id[1] != _T('M')) return 0;
587 TinyGrowBuf *buf;
588 if (strtoptr(id + 2, buf) && start)
589 {
590 *start = (TCHAR*) buf->get();
591 *end = *start + (buf->getlen() / sizeof(TCHAR));
592 }
593 return buf;
594 }
595
596 int CEXEBuild::pp_appendmemfile(LineParser&line)
597 {
598 bool del = line.gettoken_str(1)[0] == _T('\0');
599 const TCHAR *name = line.gettoken_str(1 + del);
600 TinyGrowBuf *file;
601
602 if (line.getnumtokens() == 2) // Create file
603 {
604 if (!*name) return PS_ERROR;
605 file = new TinyGrowBuf;
606 TCHAR buf[42];
607 buf[0] = _T('~'), buf[1] = _T('M');
608 ptrtostr(file, buf + 2);
609 definedlist.set(name, buf);
610 return PS_OK;
611 }
612
613 file = getmemfileinfo(*this, name);
614 if (!file) return PS_ERROR;
615 if (del) // Delete file
616 {
617 delete file;
618 definedlist.del(name);
619 }
620 else
621 {
622 const TCHAR *data = line.gettoken_str(2);
623 file->add(data, GrowBuf::size_type(_tcslen(data) * sizeof(*data)));
624 }
625 return PS_OK;
626 }
627
628 enum { PPGVHF_VALID = 0x01, PPGVHF_NOERRORS = 0x02, PPGVHF_PACKED = 0x04, PPGVHF_TLB = 0x08 };
629 int CEXEBuild::pp_getversionhelper(const TCHAR *cmdname, const TCHAR *path, const TCHAR *basesymname, DWORD high, DWORD low, DWORD flags)
630 {
631 TCHAR *symbuf = m_templinebuf;
632 DWORD tlb = (flags & PPGVHF_TLB), noerrors = (flags & PPGVHF_NOERRORS);
633 FILE *pF = tlb ? MSTLB_fopen(path) : FOPEN(path, ("rb"));
634 if (pF) fclose(pF);
635 bool vnum = pF && (flags & PPGVHF_VALID); // LibraryLocal users want to detect "file not found" vs "no version info"
636 if (!vnum) high = low = 0;
637 DWORD vals[] = { high >> 16, high & 0xffff, low >> 16, low & 0xffff }, count = 4;
638 if (tlb) count = 2, vals[0] = high, vals[1] = low, vals[2] = vals[3] = 0;
639
640 if (!pF)
641 {
642 if (noerrors) return PS_OK;
643 ERROR_MSG(_T("%") NPRIs _T(": error reading version info from \"%") NPRIs _T("\"\n"), cmdname, path);
644 return PS_ERROR;
645 }
646
647 if (flags & PPGVHF_PACKED)
648 {
649 SCRIPT_MSG(_T("%") NPRIs _T(": %") NPRIs _T(" (%lu.%lu)->(%") NPRIs _T("<HIGH/LOW>)\n"),
650 cmdname, path, high, low, basesymname);
651 _stprintf(symbuf,_T("%") NPRIs _T("HIGH"), basesymname), vnum ? definedlist.set_ui32(symbuf, high) : definedlist.set(symbuf, _T(""));
652 _stprintf(symbuf,_T("%") NPRIs _T("LOW"), basesymname), vnum ? definedlist.set_ui32(symbuf, low) : definedlist.set(symbuf, _T(""));
653 }
654 else
655 {
656 SCRIPT_MSG(_T("%") NPRIs _T(": %") NPRIs _T(" (%u.%u.%u.%u)->(%") NPRIs _T("<1..%d>)\n"),
657 cmdname, path, vals[0], vals[1], vals[2], vals[3], basesymname, (int) count);
658 for (UINT i = 0; i < count; ++i)
659 {
660 _stprintf(symbuf,_T("%") NPRIs _T("%u"), basesymname, i+1);
661 vnum ? definedlist.set_ui32(symbuf, vals[i]) : definedlist.set(symbuf, _T(""));
662 }
663 }
664 return PS_OK;
665 }
666
667 int CEXEBuild::pp_getversion(int which_token, LineParser&line)
668 {
669 const bool tlb = TOK_P_GETTLBVERSION == which_token;
670 const TCHAR *cmdname = tlb ? _T("!gettlbversion") : _T("!getdllversion"), *path;
671 DWORD ti = 1, flags = tlb ? PPGVHF_TLB : 0, low, high, prod = 0;
672 for (;; ++ti)
673 {
674 if (!_tcsicmp(line.gettoken_str(ti), _T("/noerrors")))
675 flags |= PPGVHF_NOERRORS;
676 else if (!_tcsicmp(line.gettoken_str(ti), _T("/packed")))
677 flags |= PPGVHF_PACKED;
678 else if (!_tcsicmp(line.gettoken_str(ti), _T("/productversion")))
679 ++prod;
680 else
681 break;
682 }
683 if ((tlb ? GetTLBVersion : GetDLLVersion)(path = line.gettoken_str(ti), high, low, !!prod)) flags |= PPGVHF_VALID;
684 return pp_getversionhelper(cmdname, path, line.gettoken_str(ti+1), high, low, flags);
685 }
686
687 int CEXEBuild::pp_searchreplacestring(LineParser&line)
688 {
689 int ignoreCase = !_tcsicmp(line.gettoken_str(1), _T("/ignorecase"));
690 if (line.getnumtokens() != 5+ignoreCase) PRINTHELP()
691
692 TCHAR *define = line.gettoken_str(1+ignoreCase);
693 TCHAR *src = line.gettoken_str(2+ignoreCase);
694 TCHAR *search = line.gettoken_str(3+ignoreCase);
695 TCHAR *replace = line.gettoken_str(4+ignoreCase);
696 int searchlen = (int)_tcslen(search), replacelen = (int)_tcslen(replace);
697 if (!searchlen)
698 {
699 ERROR_MSG(_T("!searchreplace: search string must not be empty for search/replace!\n"));
700 return PS_ERROR;
701 }
702
703 GrowBuf valout;
704 while (*src)
705 {
706 if (ignoreCase ? _tcsnicmp(src, search, searchlen) : _tcsncmp(src, search, searchlen))
707 valout.add(src++, sizeof(TCHAR));
708 else
709 {
710 valout.add(replace, sizeof(TCHAR)*replacelen);
711 src += searchlen;
712 }
713 }
714 valout.add(_T(""),sizeof(TCHAR));
715
716 definedlist.del(define); // allow changing variables since we'll often use this in series
717 if (definedlist.add(define, (TCHAR*)valout.get()))
718 {
719 ERROR_MSG(_T("!searchreplace: error defining \"%") NPRIs _T("\"!\n"), define);
720 return PS_ERROR;
721 }
722 SCRIPT_MSG(_T("!searchreplace: \"%") NPRIs _T("\"=\"%") NPRIs _T("\"\n"), define,(TCHAR*)valout.get());
723 return S_OK;
724 }
725
726 int CEXEBuild::pp_searchparsestring(LineParser&line)
727 {
728 bool ignCase = false, noErrors = false, isFile = false;
729 int parmOffs = 1;
730 while (parmOffs < line.getnumtokens())
731 {
732 if (!_tcsicmp(line.gettoken_str(parmOffs), _T("/ignorecase"))) { ignCase = true; parmOffs++; }
733 else if (!_tcsicmp(line.gettoken_str(parmOffs), _T("/noerrors"))) { noErrors = true; parmOffs++; }
734 else if (!_tcsicmp(line.gettoken_str(parmOffs), _T("/file"))) { isFile = true; parmOffs++; }
735 else break;
736 }
737 if (parmOffs+3 > line.getnumtokens())
738 {
739 ERROR_MSG(_T("!searchparse: not enough parameters\n"));
740 return PS_ERROR;
741 }
742 const TCHAR *source_string = line.gettoken_str(parmOffs++);
743 DefineList *list = 0;
744
745 if (isFile)
746 {
747 const TCHAR *const filename = source_string;
748 NIStream filestrm;
749 if (!filestrm.OpenFileForReading(filename))
750 {
751 ERROR_MSG(_T("!searchparse /file: error opening \"%") NPRIs _T("\"\n"), filename);
752 return PS_ERROR;
753 }
754 UINT req_parm = (line.getnumtokens() - parmOffs)/2, fail_parm = 0, linnum = 0;
755 NStreamLineReader lr(filestrm);
756 GrowBuf tmpstr;
757 TCHAR *str = m_templinebuf;
758 for (;;)
759 {
760 tmpstr.resize(0);
761 for (;;)
762 {
763 ++linnum;
764 UINT cch = read_line_helper(lr, str, MAX_LINELENGTH);
765 if (!cch)
766 {
767 if (*str)
768 {
769 tstring lrmsg = lr.GetErrorMessage((UINT)*str, filename, linnum);
770 ERROR_MSG(_T("!searchparse: %") NPRIs, lrmsg.c_str());
771 return PS_ERROR;
772 }
773 break; // EOF
774 }
775 str[--cch] = _T('\0'); // remove newline
776
777 const bool endSlash = (cch && _T('\\') == str[cch-1]);
778 if (endSlash) --cch; // don't include the slash character
779 if (tmpstr.getlen() || endSlash) tmpstr.add(str,cch*sizeof(TCHAR));
780
781 // if we have valid contents and not ending on slash, then done
782 if (!endSlash && (str[0] || tmpstr.getlen())) break;
783 }
784
785 if (!str[0] && !tmpstr.getlen()) break; // reached eof
786
787 TCHAR *thisline = str;
788 if (tmpstr.getlen())
789 {
790 tmpstr.add(_T("\0"),sizeof(TCHAR));
791 thisline = (TCHAR*)tmpstr.get();
792 }
793 UINT linefailparm;
794 DefineList *tlist = searchParseString(thisline, line, parmOffs, ignCase, true, &linefailparm);
795 if (linefailparm > fail_parm) fail_parm = linefailparm;
796 if (tlist && tlist->getnum())
797 {
798 if (!list || tlist->getnum() > list->getnum())
799 {
800 delete list;
801 list = tlist, tlist = 0;
802 if ((unsigned)list->getnum() >= req_parm)
803 {
804 fail_parm = -1; // success
805 break; // we found all the tokens, stop parsing the file
806 }
807 }
808 }
809 delete tlist;
810 // parse line
811 }
812 if ((UINT)-1 != fail_parm && !noErrors)
813 {
814 const TCHAR *msgprefix = !fail_parm ? _T("starting ") : _T("");
815 TCHAR *p = line.gettoken_str(parmOffs + (fail_parm*2));
816 ERROR_MSG(_T("!searchparse: %") NPRIs _T("string \"%") NPRIs _T("\" not found in file!\n"), msgprefix, p ? p : _T("(null)"));
817 return PS_ERROR;
818 }
819 }
820 else
821 {
822 list = searchParseString(source_string, line, parmOffs, ignCase, noErrors);
823 if (!list && !noErrors) return PS_ERROR;
824 }
825
826 if (list) // if we got our list, merge them defines in
827 {
828 for (int i=0; i < list->getnum(); i++)
829 {
830 TCHAR *def = list->getname(i), *val = list->getvalue(i);
831 if (def && val) definedlist.set(def,val);
832 }
833 }
834 delete list;
835 return PS_OK;
836 }
837
838 DefineList *CEXEBuild::searchParseString(const TCHAR *source_string, LineParser&line, int parmOffs, bool ignCase, bool noErrors, UINT*failParam)
839 {
840 const bool allowEmptyFirstTok = true;
841 if (failParam) *failParam = 0;
842 DefineList *ret = NULL;
843 const TCHAR *defout = 0, *src_start = 0, *tok;
844 int toklen = 0, maxlen;
845 for (;;)
846 {
847 tok = line.gettoken_str(parmOffs++);
848 const bool lasttoken = parmOffs > line.getnumtokens();
849 if (!*tok)
850 tok = 0, maxlen = -1; // No more tokens to search for, save the rest of the string
851 else
852 {
853 toklen = (int) _tcslen(tok);
854 while (*source_string && (ignCase?_tcsnicmp(source_string, tok, toklen):_tcsncmp(source_string, tok, toklen))) source_string++;
855 maxlen = (int)(source_string - src_start); // Length of previous string
856 }
857 if (defout && defout[0]) // We now know the start and length of the previous string, add it to the list
858 {
859 if (!ret) ret = new DefineList();
860 if (maxlen < 0)
861 ret->add(defout, src_start);
862 else
863 ret->addn(defout, maxlen, src_start);
864 }
865 if (!tok && lasttoken) break;
866 if (!*source_string || (allowEmptyFirstTok ? false : !tok)) // We did not find the requested token!
867 {
868 if (failParam) *failParam = ret ? ret->getnum() : 0;
869 if (noErrors) break; // Caller is OK with a incomplete list of matched strings
870 const TCHAR *msgprefix = src_start ? _T("") : _T("starting ");
871 ERROR_MSG(_T("!searchparse: %") NPRIs _T("string \"%") NPRIs _T("\" not found, aborted search!\n"), msgprefix, tok ? tok : _T("(null)"));
872 delete ret;
873 return NULL;
874 }
875 defout = line.gettoken_str(parmOffs++), src_start = source_string += toklen;
876 }
877 return ret;
878 }
879
880 int CEXEBuild::pp_verbose(LineParser&line)
881 {
882 for(int argi = 1; argi < line.getnumtokens(); ++argi)
883 {
884 int k = line.gettoken_enum(argi, _T("push\0pop\0")), v, convsucc;
885 if (k < 0) // not push/pop, just set the level
886 {
887 v = line.gettoken_int(argi, &convsucc);
888 if (!convsucc || v < 0 || v > 4 )
889 {
890 // < 2.47 would reset level to 0 without warning!
891 ERROR_MSG(_T("!verbose: Invalid verbose level\n"));
892 return PS_ERROR;
893 }
894 }
895 else
896 {
897 if (k) // pop
898 {
899 int l = verbose_stack.getlen();
900 if (l)
901 {
902 v= ((int*)verbose_stack.get())[(l/sizeof(int))-1];
903 verbose_stack.resize(l-sizeof(int));
904 }
905 else
906 {
907 warning_fl(DW_PP_VERBOSE_POP_EMPTY_STACK, _T("!verbose: Pop failed, stack is empty"));
908 continue; // Pop failed, should still process the next parameter
909 }
910 }
911 else // push
912 {
913 v = get_verbosity();
914 verbose_stack.add(&v,sizeof(int));
915 continue;
916 }
917 }
918 set_verbosity(v);
919 }
920 return PS_OK;
921 }
922
923 int CEXEBuild::pp_define(LineParser&line)
924 {
925 const TCHAR *cmdnam = line.gettoken_str(0), *define = line.gettoken_str(1);
926 GrowBuf file_buf;
927 TCHAR datebuf[256], mathbuf[256], *value;
928 int dupemode = 0;
929
930 if (!_tcsicmp(define, _T("/ifndef")))
931 dupemode = 1;
932 else if (!_tcsicmp(define, _T("/redef")))
933 dupemode = 2;
934
935 if (dupemode != 0)
936 {
937 line.eattoken();
938 define = line.gettoken_str(1);
939 }
940
941 if (!_tcsicmp(define, _T("/date")) || !_tcsicmp(define, _T("/utcdate")))
942 {
943 if (line.getnumtokens() != 4) PRINTHELPEX(cmdnam)
944
945 const TCHAR *date_type = define;
946 time_t rawtime;
947 time(&rawtime);
948 define = line.gettoken_str(2), value = line.gettoken_str(3);
949
950 if (!_tcsicmp(date_type, _T("/utcdate")))
951 rawtime = mktime(gmtime(&rawtime));
952
953 datebuf[0] = 0;
954 size_t s = _tcsftime(datebuf, COUNTOF(datebuf), value, localtime(&rawtime));
955 if (s == 0)
956 datebuf[0] = _T('\0');
957 else
958 datebuf[max(s, COUNTOF(datebuf)-1)] = _T('\0');
959
960 value = datebuf;
961 }
962 else if (!_tcsicmp(define, _T("/file")) || !_tcsicmp(define, _T("/file_noerr")))
963 {
964 if (line.getnumtokens() != 4) PRINTHELPEX(cmdnam)
965 const TCHAR *const filename = line.gettoken_str(3), *const swit = define;
966 NIStream filestrm;
967 if (!filestrm.OpenFileForReading(filename))
968 {
969 if (!swit[5])
970 { // "/file" vs "/file_noerr"
971 ERROR_MSG(_T("!define /file: file not found (\"%") NPRIs _T("\")\n"), filename);
972 return PS_ERROR;
973 }
974 }
975 else
976 {
977 NStreamLineReader lr(filestrm);
978 TCHAR *str = m_templinebuf;
979 for (UINT linnum = 0;;) {
980 ++linnum;
981 UINT cch = read_line_helper(lr, str, MAX_LINELENGTH);
982 if (!cch) {
983 if (*str) {
984 tstring lrmsg = lr.GetErrorMessage((UINT)*str, filename, linnum);
985 ERROR_MSG(_T("!define %") NPRIs _T(": %") NPRIs, swit, lrmsg.c_str());
986 return PS_ERROR;
987 }
988 break; // EOF
989 }
990 str[--cch] = _T('\0'); // Remove \r or \n, we always append \n
991 if (file_buf.getlen()) file_buf.add(_T("\n"), sizeof(TCHAR));
992 file_buf.add(str, cch*sizeof(TCHAR));
993 }
994 }
995 define = line.gettoken_str(2);
996 file_buf.add(_T("\0"), sizeof(TCHAR));
997 value = (TCHAR *)file_buf.get();
998 }
999 else if (!_tcsicmp(define, _T("/math")))
1000 {
1001 int value1, value2, tc = line.getnumtokens(), onlyval1 = 0;
1002 TCHAR *mathop;
1003
1004 if (tc != 5 && tc != 6) badmathsyntax: PRINTHELPEX(cmdnam)
1005 define = line.gettoken_str(2);
1006 value1 = line.gettoken_int(3);
1007 mathop = line.gettoken_str(4);
1008 value2 = line.gettoken_int(5);
1009 value = mathbuf;
1010
1011 if (!_tcscmp(mathop,_T("+"))) {
1012 _stprintf(value, _T("%d"), value1 + value2);
1013 } else if (!_tcscmp(mathop, _T("-"))) {
1014 _stprintf(value, _T("%d"), value1 - value2);
1015 } else if (!_tcscmp(mathop, _T("*"))) {
1016 _stprintf(value, _T("%d"), value1 * value2);
1017 } else if (!_tcscmp(mathop, _T("&"))) {
1018 _stprintf(value, _T("%d"), value1 & value2);
1019 } else if (!_tcscmp(mathop, _T("|"))) {
1020 _stprintf(value, _T("%d"), value1 | value2);
1021 } else if (!_tcscmp(mathop, _T("^"))) {
1022 _stprintf(value, _T("%d"), value1 ^ value2);
1023 } else if (!_tcscmp(mathop, _T("~"))) {
1024 _stprintf(value, _T("%d"), ~ value1), ++onlyval1;
1025 } else if (!_tcscmp(mathop, _T("!"))) {
1026 _stprintf(value, _T("%d"), ! value1), ++onlyval1;
1027 } else if (!_tcscmp(mathop, _T("&&"))) {
1028 _stprintf(value, _T("%d"), value1 && value2);
1029 } else if (!_tcscmp(mathop, _T("||"))) {
1030 _stprintf(value, _T("%d"), value1 || value2);
1031 } else if (!_tcscmp(mathop, _T("<<")) || !_tcscmp(mathop, _T("<<<")) ) {
1032 _stprintf(value, _T("%d"), value1 << value2);
1033 } else if (!_tcscmp(mathop, _T(">>"))) {
1034 _stprintf(value, _T("%d"), (signed int)value1 >> (signed int)value2);
1035 } else if (!_tcscmp(mathop, _T(">>>"))) {
1036 _stprintf(value, _T("%u"), (unsigned int)value1 >> (unsigned int)value2);
1037 } else if (!_tcscmp(mathop, _T("/"))) {
1038 if (value2 == 0)
1039 {
1040 ERROR_MSG(_T("!define /math: division by zero! (\"%i %") NPRIs _T(" %i\")\n"), value1, mathop, value2);
1041 return PS_ERROR;
1042 }
1043 _stprintf(value, _T("%d"), value1 / value2);
1044 } else if (!_tcscmp(mathop, _T("%"))) {
1045 if (value2 == 0)
1046 {
1047 ERROR_MSG(_T("!define /math: division by zero! (\"%i %") NPRIs _T(" %i\")\n"),value1,mathop,value2);
1048 return PS_ERROR;
1049 }
1050 _stprintf(value, _T("%d"), value1 % value2);
1051 }
1052 else
1053 goto badmathsyntax;
1054
1055 if (tc + onlyval1 != 6) goto badmathsyntax;
1056 }
1057 else if (!_tcsicmp(define, _T("/intfmt")))
1058 {
1059 if (line.getnumtokens() != 5) PRINTHELPEX(cmdnam)
1060 define = line.gettoken_str(2);
1061 _stprintf(value = mathbuf, line.gettoken_str(3), line.gettoken_int(4));
1062 }
1063 else
1064 {
1065 if (line.getnumtokens() >= 4) PRINTHELPEX(cmdnam)
1066 value = line.gettoken_str(2);
1067 }
1068
1069 if (dupemode == 2) definedlist.del(define);
1070 if (definedlist.add(define, value))
1071 {
1072 if (dupemode == 1) return PS_OK;
1073 ERROR_MSG(_T("!define: \"%") NPRIs _T("\" already defined!\n"), define);
1074 return PS_ERROR;
1075 }
1076 SCRIPT_MSG(_T("!define: \"%") NPRIs _T("\"=\"%") NPRIs _T("\"\n"), define, value);
1077 return PS_OK;
1078 }
1079
1080 int CEXEBuild::pp_undef(LineParser&line)
1081 {
1082 UINT noerr = false, stopswitch = false, handled = 0;
1083 for (int ti = 1; ti < line.getnumtokens(); ++ti)
1084 {
1085 const TCHAR *name = line.gettoken_str(ti);
1086 if (!stopswitch && !_tcsicmp(name, _T("/noerrors")))
1087 {
1088 ++noerr;
1089 continue;
1090 }
1091 stopswitch = ++handled;
1092 if (definedlist.del(name) && !noerr)
1093 warning_fl(DW_PP_UNDEF_UNDEFINED, _T("!undef: \"%") NPRIs _T("\" not defined!"), name);
1094 else
1095 SCRIPT_MSG(_T("!undef: \"%") NPRIs _T("\"\n"), name);
1096 }
1097 if (!handled)
1098 {
1099 PRINTHELP();
1100 return PS_ERROR;
1101 }
1102 return PS_OK;
1103 }
1104
1105 int CEXEBuild::pp_packhdr(LineParser&line)
1106 {
1107 unsigned int bufOf = false;
1108 TCHAR *packname = line.gettoken_str(1);
1109 PATH_CONVERT(packname);
1110 if (!strtrycpy(build_packname, packname, COUNTOF(build_packname))) ++bufOf;
1111 if (!strtrycpy(build_packcmd, line.gettoken_str(2), COUNTOF(build_packcmd))) ++bufOf;
1112 SCRIPT_MSG(_T("!packhdr: filename=\"%") NPRIs _T("\", command=\"%") NPRIs _T("\"\n"), build_packname, build_packcmd);
1113 return bufOf ? PS_ERROR : PS_OK;
1114 }
1115
1116 template<class T> void slist_append(T&list, T&item)
1117 {
1118 T prev;
1119 for (prev = list; prev && prev->next;)
1120 prev = prev->next;
1121 (prev ? prev->next : list) = item;
1122 }
1123
1124 int CEXEBuild::pp_finalize(int which_token, LineParser&line)
1125 {
1126 #ifndef NSIS_CONFIG_UNINSTALL_SUPPORT
1127 if (which_token == TOK_P_UNINSTFINALIZE)
1128 {
1129 ERROR_MSG(_T("Error: %") NPRIs _T(" specified, %") NPRIns _T(" not defined.\n"), line.gettoken_str(0), "NSIS_CONFIG_UNINSTALL_SUPPORT");
1130 return PS_ERROR;
1131 }
1132 #endif
1133 TCHAR* cmdstr = line.gettoken_str(1);
1134 int validparams = false;
1135 postbuild_cmd *newcmd = postbuild_cmd::make(cmdstr, line.gettoken_enum(2, _T("<\0>\0<>\0=\0ignore\0")), line.gettoken_int(3, &validparams));
1136 if (line.getnumtokens() == 1+1)
1137 newcmd->cmpop = 4, validparams = true; // Just a command, ignore the exit code
1138 if (newcmd->cmpop == -1 || !validparams)
1139 PRINTHELP();
1140 slist_append(which_token == TOK_P_UNINSTFINALIZE ? postubuild_cmds : postbuild_cmds, newcmd);
1141 SCRIPT_MSG(_T("!%") NPRIns _T("finalize: \"%") NPRIs _T("\"\n"), which_token == TOK_P_UNINSTFINALIZE ? "uninst" : "", cmdstr);
1142 return PS_OK;
1143 }
1144
1145 int CEXEBuild::pp_execute(int which_token, LineParser&line)
1146 {
1147 const TCHAR *cmdname=get_commandtoken_name(which_token);
1148 const TCHAR *exec=line.gettoken_str(1), *define=0;
1149 TCHAR buf[33];
1150 int comp=line.gettoken_enum(2,_T("<\0>\0<>\0=\0ignore\0"));
1151 int validparams=true, ret=-1, cmpv=0, forceutf8=0;
1152 switch(line.getnumtokens()-1)
1153 {
1154 case 1: comp=4; break;
1155 case 2: comp=5, validparams=!!*(define=line.gettoken_str(2)); break;
1156 case 3: cmpv=line.gettoken_int(3,&validparams); break;
1157 default: forceutf8=comp=-1;
1158 }
1159 if (!validparams || comp == -1) PRINTHELP()
1160 tstring compile;
1161 if (TOK_P_MAKENSIS == which_token)
1162 {
1163 extern const TCHAR *g_argv0;
1164 compile=_T("\""), compile+=get_executable_path(g_argv0), compile+= _T("\"");
1165 compile+= _T(" ") OPT_STR _T("v"), wsprintf(buf,_T("%d"),get_verbosity()), compile+=buf;
1166 #if defined(_WIN32) && defined(_UNICODE) // POSIX does not support -OUTPUTCHARSET
1167 compile+= _T(" ") OPT_STR _T("OCS UTF8"), forceutf8++; // Force UTF-8 and disable batch-file workaround in RunChildProcessRedirected
1168 #endif
1169 if (*exec) compile+= _T(" "), compile+=exec;
1170 exec=compile.c_str();
1171 }
1172 SCRIPT_MSG(_T("%") NPRIs _T(": \"%") NPRIs _T("\"\n"),cmdname,exec);
1173 if (preprocessonly) PREPROCESSONLY_BEGINCOMMENT();
1174 #ifdef _WIN32
1175 if (TOK_P_SYSTEMEXEC != which_token)
1176 ret=RunChildProcessRedirected(exec, forceutf8 ? true : false);
1177 else
1178 #endif //~ _WIN32
1179 ret=sane_system(exec), (void)forceutf8; // forceutf8 is not used on POSIX
1180
1181 if (comp == 5)
1182 {
1183 definedlist.set_si32(define,ret);
1184 }
1185 else if (!check_external_exitcode(ret,comp,cmpv))
1186 {
1187 ERROR_MSG(_T("%") NPRIs _T(": returned %d, aborting\n"),cmdname,ret);
1188 return PS_ERROR;
1189 }
1190 if (preprocessonly) PREPROCESSONLY_ENDCOMMENT();
1191 SCRIPT_MSG(_T("%") NPRIs _T(": returned %d\n"),cmdname,ret);
1192 return PS_OK;
1193 }
1194
1195 int CEXEBuild::pp_addincludedir(LineParser&line)
1196 {
1197 TCHAR *f = line.gettoken_str(1);
1198 PATH_CONVERT(f);
1199 include_dirs.add(f, 0);
1200 return PS_OK;
1201 }
1202
1203 static const TCHAR *g_incerrfmtstr = _T("!include: error in script: \"%") NPRIs _T("\" on line %d\n");
1204 static const TCHAR *g_incerrlvlfmtstr = _T("!include: too many levels of includes (%d max).\n");
1205
1206 int CEXEBuild::includeScript(const TCHAR *file, NStreamEncoding&enc)
1207 {
1208 NIStream incstrm;
1209 const bool openok = incstrm.OpenFileForReading(file, enc);
1210 if (NStreamEncoding::AUTO == enc.GetCodepage()
1211 && build_unicode && !enc.IsUnicodeCodepage(enc.GetPlatformDefaultCodepage())
1212 && enc.GetPlatformDefaultCodepage() == incstrm.StreamEncoding().GetCodepage() )
1213 {
1214 incstrm.StreamEncoding().SetCodepage(NStreamEncoding::UTF8); // !include defaults to UTF-8 after "Unicode true"
1215 }
1216 enc = incstrm.StreamEncoding();
1217
1218 TCHAR bufcpdisp[20];
1219 incstrm.StreamEncoding().GetCPDisplayName(bufcpdisp);
1220 SCRIPT_MSG(_T("!include: \"%") NPRIs _T("\" (%") NPRIs _T(")\n"), file, bufcpdisp);
1221 if (!openok)
1222 {
1223 ERROR_MSG(_T("!include: could not open file: \"%") NPRIs _T("\"\n"), file);
1224 return PS_ERROR;
1225 }
1226
1227 if (build_include_depth >= MAX_INCLUDEDEPTH)
1228 {
1229 ERROR_MSG(g_incerrlvlfmtstr, MAX_INCLUDEDEPTH);
1230 return PS_ERROR;
1231 }
1232 build_include_depth++;
1233
1234 const int last_linecnt = linecnt;
1235 const TCHAR *last_filename = curfilename;
1236 curfilename = file, linecnt = 0;
1237 NStreamLineReader linereader(incstrm);
1238 NStreamLineReader *last_linereader = curlinereader;
1239 curlinereader = &linereader;
1240 #ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
1241 TCHAR *oldfilename = set_file_predefine(curfilename);
1242 TCHAR *oldtimestamp = set_timestamp_predefine(curfilename);
1243 #endif
1244
1245 int r = parseScript();
1246 const int errline = linecnt;
1247
1248 #ifdef NSIS_SUPPORT_STANDARD_PREDEFINES
1249 restore_file_predefine(oldfilename);
1250 restore_timestamp_predefine(oldtimestamp);
1251 #endif
1252 curfilename = last_filename, linecnt = last_linecnt;
1253 curlinereader = last_linereader;
1254
1255 build_include_depth--;
1256 if (r != PS_EOF && r != PS_OK)
1257 {
1258 ERROR_MSG(g_incerrfmtstr, file, errline);
1259 return PS_ERROR;
1260 }
1261 SCRIPT_MSG(_T("!include: closed: \"%") NPRIs _T("\"\n"), file);
1262 return PS_OK;
1263 }
1264
1265 int CEXEBuild::includeScriptLines(const TCHAR *start, const TCHAR *end, const TCHAR *name)
1266 {
1267 if (build_include_depth >= MAX_INCLUDEDEPTH)
1268 {
1269 ERROR_MSG(g_incerrlvlfmtstr, MAX_INCLUDEDEPTH);
1270 return PS_ERROR;
1271 }
1272
1273 build_include_depth++;
1274 tstring buf;
1275 int ret = PS_OK;
1276 bool unicode = sizeof(*start) > sizeof(char);
1277 for (unsigned int ln = 0; start < end && ret == PS_OK;)
1278 {
1279 const TCHAR *line = start, eot = 4;
1280 size_t i, nl;
1281 for (i = 0, nl = 0;; ++i)
1282 {
1283 nl = &line[i] < end ? NStream::IsNewline(line[i], unicode) : eot;
1284 if (nl || !line[i]) break;
1285 }
1286 if (nl)
1287 {
1288 buf.assign(line, i);
1289 line = buf.c_str();
1290 }
1291 if (*line) ret = process_oneline(line, name, ++ln, PLF_VIRTUALFILE);
1292 if (ret != PS_OK) ERROR_MSG(g_incerrfmtstr, name, ln);
1293 start += i + 1;
1294 }
1295 build_include_depth--;
1296 return ret;
1297 }
1298
1299 int CEXEBuild::pp_include(LineParser&line)
1300 {
1301 bool required = true, memfile = false, done = false;
1302 NStreamEncoding enc(NStreamEncoding::AUTO);
1303 const TCHAR *f;
1304 unsigned int toks = line.getnumtokens() - 1, included = 0;
1305 for(unsigned int tok = 0; toks;)
1306 {
1307 f = line.gettoken_str(++tok);
1308 if (tok >= toks) break;
1309 if (!_tcsicmp(f,_T("/memfile"))) memfile = true;
1310 if (!_tcsicmp(f,_T("/nonfatal"))) required = false;
1311 TCHAR buf[9+1];
1312 my_strncpy(buf, f, COUNTOF(buf));
1313 if (!_tcsicmp(buf,_T("/charset=")))
1314 {
1315 WORD cp = GetEncodingFromString(f+9);
1316 if (NStreamEncoding::UNKNOWN == cp) toks = 0;
1317 enc.SafeSetCodepage(cp);
1318 }
1319 }
1320 if (!toks || !*f) PRINTHELP();
1321
1322 if (memfile)
1323 {
1324 const TCHAR *s, *e, *n = get_memorycode_filename();
1325 if (getmemfileinfo(*this, f, &s, &e))
1326 {
1327 return includeScriptLines(s, e, n);
1328 }
1329 done = true, f = n;
1330 }
1331
1332 const TCHAR *fc = my_convert(f);
1333 tstring dir = get_dir_name(fc), spec = get_file_name(fc), basedir = dir;
1334 my_convert_free(const_cast<TCHAR*>(fc));
1335 path_append_separator(basedir);
1336 if (dir == spec) basedir = _T(""), dir = _T("."); // no path, just file name
1337
1338 // search working directory
1339 boost::scoped_ptr<dir_reader> dr( new_dir_reader() );
1340 dr->read(dir);
1341 for (dir_reader::iterator files_itr = dr->files().begin();
1342 !done && files_itr != dr->files().end();
1343 files_itr++)
1344 {
1345 if (!dir_reader::matches(*files_itr, spec)) continue;
1346
1347 tstring incfile = basedir + *files_itr;
1348 if (includeScript(incfile.c_str(), enc) != PS_OK)
1349 return PS_ERROR;
1350 else
1351 included++;
1352 }
1353 if (included) return PS_OK;
1354
1355 // search include dirs
1356 TCHAR *incdir = include_dirs.get();
1357 int incdirs = include_dirs.getnum();
1358 for (int i = 0; !done && i < incdirs; i++, incdir += _tcslen(incdir) + 1)
1359 {
1360 tstring curincdir(incdir), incfile;
1361 if (_T(".") != dir) path_append(curincdir, dir);
1362
1363 boost::scoped_ptr<dir_reader> dr( new_dir_reader() );
1364 dr->read(curincdir);
1365 for (dir_reader::iterator incdir_itr = dr->files().begin();
1366 incdir_itr != dr->files().end();
1367 incdir_itr++)
1368 {
1369 if (!dir_reader::matches(*incdir_itr, spec)) continue;
1370
1371 path_append(incfile = curincdir, *incdir_itr);
1372 if (includeScript(incfile.c_str(), enc) != PS_OK)
1373 return PS_ERROR;
1374 else
1375 included++;
1376 }
1377 if (included) return PS_OK;
1378 }
1379
1380 if (!included) // nothing found?
1381 {
1382 if (required)
1383 {
1384 ERROR_MSG(_T("!include: could not find: \"%") NPRIs _T("\"\n"), f);
1385 return PS_ERROR;
1386 }
1387 else
1388 warning_fl(DW_INCLUDE_NONFATAL_NOT_FOUND, _T("!include: could not find: \"%") NPRIs _T("\""), f);
1389 }
1390 return PS_OK;
1391 }
1392
1393 int CEXEBuild::pp_cd(LineParser&line)
1394 {
1395 const TCHAR *dir = line.gettoken_str(1);
1396 if (!dir[0] || _tchdir(dir))
1397 {
1398 ERROR_MSG(_T("!cd: error changing to: \"%") NPRIs _T("\"\n"), dir);
1399 return PS_ERROR;
1400 }
1401 return PS_OK;
1402 }
1403
1404 int CEXEBuild::pp_boolifyexpression(LineParser&line, int &result, bool allow_logicneg, int ignore_last_tokens)
1405 {
1406 const TCHAR *cmdnam = line.gettoken_str(0); // Must save name now before eattoken!
1407 int istrue = 0, mod = 0, logicneg = 0;
1408
1409 if (allow_logicneg && !_tcscmp(line.gettoken_str(1),_T("!")))
1410 logicneg++, line.eattoken();
1411
1412 int numtokens = line.getnumtokens() - ignore_last_tokens;
1413 if (numtokens == 2)
1414 {
1415 istrue = line.gettoken_number(1) || line.gettoken_int(1);
1416 }
1417 else if (numtokens == 3)
1418 {
1419 if (!_tcsicmp(line.gettoken_str(1),_T("/fileexists")))
1420 {
1421 TCHAR *fc = my_convert(line.gettoken_str(2));
1422 tstring dir = get_dir_name(fc), spec = get_file_name(fc);
1423 my_convert_free(fc);
1424 if (dir == spec) dir = _T(".");
1425
1426 boost::scoped_ptr<dir_reader> dr( new_dir_reader() );
1427 dr->hack_simpleexcluded().erase(_T("."));
1428 dr->read(dir);
1429
1430 for (dir_reader::iterator fit = dr->files().begin();
1431 fit != dr->files().end() && !istrue; fit++)
1432 {
1433 if (dir_reader::matches(*fit, spec)) istrue = true;
1434 }
1435 if (!istrue) for (dir_reader::iterator dit = dr->dirs().begin();
1436 dit != dr->dirs().end() && !istrue; dit++)
1437 {
1438 if (dir_reader::matches(*dit, spec)) istrue = true;
1439 }
1440 }
1441 else
1442 PRINTHELPEX(cmdnam)
1443 }
1444 else if (numtokens == 4)
1445 {
1446 int cnv1 = 1, cnv2 = 1;
1447 mod = line.gettoken_enum(2,_T("==\0!=\0S==\0S!=\0=\0<>\0<=\0<\0>\0>=\0&\0&&\0|\0||\0"));
1448 switch(mod)
1449 {
1450 case 0:
1451 istrue = _tcsicmp(line.gettoken_str(1),line.gettoken_str(3)) == 0; break;
1452 case 1:
1453 istrue = _tcsicmp(line.gettoken_str(1),line.gettoken_str(3)) != 0; break;
1454 case 2:
1455 istrue = _tcscmp(line.gettoken_str(1),line.gettoken_str(3)) == 0; break;
1456 case 3:
1457 istrue = _tcscmp(line.gettoken_str(1),line.gettoken_str(3)) != 0; break;
1458 case 4:
1459 istrue = line.gettoken_number(1,&cnv1) == line.gettoken_number(3,&cnv2); break;
1460 case 5:
1461 istrue = line.gettoken_number(1,&cnv1) != line.gettoken_number(3,&cnv2); break;
1462 case 6:
1463 istrue = line.gettoken_number(1,&cnv1) <= line.gettoken_number(3,&cnv2); break;
1464 case 7:
1465 istrue = line.gettoken_number(1,&cnv1) < line.gettoken_number(3,&cnv2); break;
1466 case 8:
1467 istrue = line.gettoken_number(1,&cnv1) > line.gettoken_number(3,&cnv2); break;
1468 case 9:
1469 istrue = line.gettoken_number(1,&cnv1) >= line.gettoken_number(3,&cnv2); break;
1470 case 10:
1471 istrue = (line.gettoken_int(1,&cnv1) & line.gettoken_int(3,&cnv2)) != 0; break;
1472 case 11:
1473 istrue = line.gettoken_int(1,&cnv1) && line.gettoken_int(3,&cnv2); break;
1474 case 12:
1475 case 13:
1476 istrue = line.gettoken_int(1,&cnv1) || line.gettoken_int(3,&cnv2); break;
1477 default:
1478 PRINTHELPEX(cmdnam)
1479 }
1480 if (!cnv1 || !cnv2)
1481 warning_fl(DW_PARSE_BADNUMBER, _T("Invalid number: \"%") NPRIs _T("\""), line.gettoken_str(!cnv1 ? 1 : 3));
1482 }
1483 else
1484 {
1485 PRINTHELPEX(cmdnam)
1486 }
1487
1488 result = logicneg ? !istrue : istrue;
1489 return PS_OK;
1490 }
1491
1492 int CEXEBuild::pp_assert(LineParser&line)
1493 {
1494 const TCHAR *message = line.gettoken_str(line.getnumtokens() - 1);
1495 int istrue, ec = pp_boolifyexpression(line, istrue, false, 1);
1496
1497 if (ec != PS_ERROR && !istrue)
1498 {
1499 tstring buf = _T("");
1500 if (!*message)
1501 {
1502 for (int i = 1, c = line.getnumtokens() - 1, any = 0; i < c; ++i)
1503 buf += (_T(" ") + !(any++)), buf += line.gettoken_str(i);
1504 message = buf.c_str();
1505 }
1506 ERROR_MSG(_T("%") NPRIs _T(": %") NPRIs _T("\n"), get_commandtoken_name(TOK_P_ASSERT), message);
1507 return PS_ERROR;
1508 }
1509 return ec;
1510 }