summaryrefslogtreecommitdiff
path: root/Source/build.cpp
blob: 56eeebae7d8d6da74696f940999fb31198b45f66 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
#include "Platform.h"
#include <stdio.h>
#include "exehead/config.h"

#include "version.h"

#include "build.h"
#include "util.h"
#include "fileform.h"
#include "writer.h"
#include "crc32.h"

#include <stdexcept>

#include "exehead/resource.h"
#include "ResourceEditor.h"
#include "DialogTemplate.h"
#include "ResourceVersionInfo.h"

#ifndef _WIN32
#  include <locale.h>
#  include <unistd.h>
#  include <limits.h>
#  include <stdlib.h>
#  include <stdarg.h>
#endif

#include <cassert> // for assert

#define RET_UNLESS_OK( function_rc ) do { \
  int rc = (function_rc); \
  if ( rc != PS_OK) \
    return rc; \
} while (false)

using namespace std;

namespace { // begin anonymous namespace

bool isSimpleChar(char ch)
{
  return (ch == '.' ) || (ch == '_' ) || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
}

} // end of anonymous namespace

void CEXEBuild::define(const char *p, const char *v)
{
  definedlist.add(p,v);
}

CEXEBuild::~CEXEBuild()
{
  free(m_unicon_data);

  delete [] m_exehead;

  int nlt = lang_tables.getlen() / sizeof(LanguageTable);
  LanguageTable *nla = (LanguageTable*)lang_tables.get();

  for (int i = 0; i < nlt; i++) {
    DeleteLangTable(nla+i);
  }
}

CEXEBuild::CEXEBuild() :
    m_exehead(0),
    m_exehead_size(0)
{
  linecnt = 0;
  fp = 0;
  curfilename = 0;

  display_info=1;
  display_script=1;
  display_errors=1;
  display_warnings=1;

  cur_ifblock=NULL;
  last_line_had_slash=0;
  inside_comment=false;
  multiple_entries_instruction=0;

  build_include_depth=0;

  has_called_write_output=false;

  ns_func.add("",0); // make sure offset 0 is special on these (i.e. never used by a label)
  ns_label.add("",0);

  definedlist.add("NSIS_VERSION", NSIS_VERSION);

  // automatically generated header file containing all defines
#include "defines.h"

  // no longer optional
  definedlist.add("NSIS_SUPPORT_STANDARD_PREDEFINES");
  definedlist.add("NSIS_SUPPORT_NAMED_USERVARS");
  definedlist.add("NSIS_SUPPORT_LANG_IN_STRINGS");

#ifdef _WIN32
  definedlist.add("NSIS_WIN32_MAKENSIS");
#endif

  db_opt_save=db_comp_save=db_full_size=db_opt_save_u=db_comp_save_u=db_full_size_u=0;

  // Added by Amir Szekely 31st July 2002
#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
  compressor = &zlib_compressor;
#endif
  build_compressor_set = false;
  build_compressor_final = false;
#ifdef NSIS_ZLIB_COMPRESS_WHOLE
  build_compress_whole = true;
#else
  build_compress_whole = false;
#endif
  build_compress=1;
  build_compress_level=9;
  build_compress_dict_size=1<<23;

  cur_entries=&build_entries;
  cur_instruction_entry_map=&build_instruction_entry_map;
  cur_datablock=&build_datablock;
  cur_datablock_cache=&build_datablock_cache;
  cur_functions=&build_functions;
  cur_labels=&build_labels;
  cur_sections=&build_sections;
  cur_header=&build_header;
  cur_strlist=&build_strlist;
  cur_langtables=&build_langtables;
  cur_ctlcolors=&build_ctlcolors;
  cur_pages=&build_pages;
  cur_page=0;
  cur_page_type=-1;

  build_filebuflen=32<<20; // 32mb

  sectiongroup_open_cnt=0;
  build_cursection_isfunc=0;
  build_cursection=NULL;
  // init public data.
  build_packname[0]=build_packcmd[0]=build_output_filename[0]=0;

  // Added by ramon 23 May 2003
  build_allowskipfiles=1;

  // Added by ramon 6 jun 2003
#ifdef NSIS_SUPPORT_VERSION_INFO
  version_product_v[0]=0;
#endif

  build_overwrite=build_last_overwrite=0;
  build_crcchk=1;
  build_datesave=1;
  build_optimize_datablock=1;

  memset(&build_header,-1,sizeof(build_header));

  build_header.install_reg_rootkey=0;
  build_header.flags=CH_FLAGS_NO_ROOT_DIR;
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  build_header.lb_bg=RGB(0,0,0);
  build_header.lb_fg=RGB(0,255,0);
#endif
#ifdef NSIS_CONFIG_LICENSEPAGE
  build_header.license_bg=-COLOR_BTNFACE;
#endif
  build_header.install_directory_ptr=0;
  build_header.install_directory_auto_append=0;
  build_header.install_reg_key_ptr=0;
  build_header.install_reg_value_ptr=0;
#ifdef NSIS_CONFIG_COMPONENTPAGE
  memset(build_header.install_types,0,sizeof(build_header.install_types));
#endif
  memset(&build_header.blocks,0,sizeof(build_header.blocks));

  uninstall_mode=0;
  uninstall_size_full=0;
  uninstall_size=-1;

  memset(&build_uninst,-1,sizeof(build_uninst));

  build_header.install_reg_rootkey=0;
  build_uninst.flags=0;
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  build_uninst.lb_bg=RGB(0,0,0);
  build_uninst.lb_fg=RGB(0,255,0);
#endif
#ifdef NSIS_CONFIG_LICENSEPAGE
  build_uninst.license_bg=-COLOR_BTNFACE;
#endif
  build_uninst.install_directory_ptr=0;
  build_uninst.install_directory_auto_append=0;
  build_uninst.install_reg_key_ptr=0;
  build_uninst.install_reg_value_ptr=0;
#ifdef NSIS_CONFIG_COMPONENTPAGE
  memset(build_uninst.install_types,0,sizeof(build_uninst.install_types));
#endif
  memset(&build_uninst.blocks,0,sizeof(build_uninst.blocks));

  uninstaller_writes_used=0;

  build_strlist.add("",0);
  ubuild_strlist.add("",0);

  build_langstring_num=0;
  ubuild_langstring_num=0;

  build_font[0]=0;
  build_font_size=0;

  m_unicon_data=NULL;
  m_unicon_size=0;

  branding_image_found=false;

  no_space_texts=false;

#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
  build_plugin_unload=0;
  plugins_processed=0;
#endif

  last_used_lang=NSIS_DEFAULT_LANG;

  res_editor=0;

  enable_last_page_cancel=0;
  uenable_last_page_cancel=0;

  license_res_id=IDD_LICENSE;

  disable_window_icon=0;

#ifdef _WIN32
  notify_hwnd=0;
#endif

#ifdef NSIS_SUPPORT_BGBG
  bg_default_font.lfHeight=40;
  bg_default_font.lfWidth=0;
  bg_default_font.lfEscapement=0;
  bg_default_font.lfOrientation=0;
  bg_default_font.lfWeight=FW_BOLD;
  bg_default_font.lfItalic=TRUE;
  bg_default_font.lfUnderline=FALSE;
  bg_default_font.lfStrikeOut=FALSE;
  bg_default_font.lfCharSet=DEFAULT_CHARSET;
  bg_default_font.lfOutPrecision=OUT_DEFAULT_PRECIS;
  bg_default_font.lfClipPrecision=CLIP_DEFAULT_PRECIS;
  bg_default_font.lfQuality=DEFAULT_QUALITY;
  bg_default_font.lfPitchAndFamily=DEFAULT_PITCH;
  strncpy(bg_default_font.lfFaceName,"Times New Roman",LF_FACESIZE);
  memcpy(&bg_font,&bg_default_font,sizeof(LOGFONT));
#endif

  defcodepage_set=false;
  uDefCodePage=CP_ACP;

  InitLangTables();

  // Register static user variables $0, $1 and so on
  // with ONE of reference count, to avoid warning on this vars
  char Aux[3];
  int i;
  for (i = 0; i < 10; i++)    // 0 - 9
  {
    sprintf(Aux, "%d", i);
    m_UserVarNames.add(Aux,1);
  }
  for (i = 0; i < 10; i++)        // 10 - 19
  {
    sprintf(Aux, "R%d", i);
    m_UserVarNames.add(Aux,1);
  }
  m_UserVarNames.add("CMDLINE",1);       // 20 everything before here doesn't have trailing slash removal
  m_UserVarNames.add("INSTDIR",1);       // 21
  m_UserVarNames.add("OUTDIR",1);        // 22
  m_UserVarNames.add("EXEDIR",1);        // 23
  m_UserVarNames.add("LANGUAGE",1);      // 24
  m_UserVarNames.add("TEMP",-1);         // 25
  m_UserVarNames.add("PLUGINSDIR",-1);   // 26
  m_UserVarNames.add("HWNDPARENT",-1);   // 27
  m_UserVarNames.add("_CLICK",-1);       // 28
  m_UserVarNames.add("_OUTDIR",1);       // 29

  m_iBaseVarsNum = m_UserVarNames.getnum();

  m_ShellConstants.add("WINDIR",CSIDL_WINDOWS,CSIDL_WINDOWS);
  m_ShellConstants.add("SYSDIR",CSIDL_SYSTEM,CSIDL_SYSTEM);
  m_ShellConstants.add("PROGRAMFILES",CSIDL_PROGRAM_FILES, CSIDL_PROGRAM_FILES);
  m_ShellConstants.add("SMPROGRAMS",CSIDL_PROGRAMS, CSIDL_COMMON_PROGRAMS);
  m_ShellConstants.add("SMSTARTUP",CSIDL_STARTUP, CSIDL_COMMON_STARTUP);
  m_ShellConstants.add("DESKTOP",CSIDL_DESKTOPDIRECTORY, CSIDL_COMMON_DESKTOPDIRECTORY);
  m_ShellConstants.add("STARTMENU",CSIDL_STARTMENU, CSIDL_COMMON_STARTMENU);
  m_ShellConstants.add("QUICKLAUNCH", CSIDL_APPDATA, CSIDL_PRINTERS);
  m_ShellConstants.add("COMMONFILES",CSIDL_PROGRAM_FILES_COMMON, CSIDL_PROGRAM_FILES_COMMON);
  m_ShellConstants.add("DOCUMENTS",CSIDL_PERSONAL, CSIDL_COMMON_DOCUMENTS);
  m_ShellConstants.add("SENDTO",CSIDL_SENDTO, CSIDL_SENDTO);
  m_ShellConstants.add("RECENT",CSIDL_RECENT, CSIDL_RECENT);
  m_ShellConstants.add("FAVORITES",CSIDL_FAVORITES, CSIDL_COMMON_FAVORITES);
  m_ShellConstants.add("MUSIC",CSIDL_MYMUSIC, CSIDL_COMMON_MUSIC);
  m_ShellConstants.add("PICTURES",CSIDL_MYPICTURES, CSIDL_COMMON_PICTURES);
  m_ShellConstants.add("VIDEOS",CSIDL_MYVIDEO, CSIDL_COMMON_VIDEO);
  m_ShellConstants.add("NETHOOD", CSIDL_NETHOOD, CSIDL_NETHOOD);
  m_ShellConstants.add("FONTS", CSIDL_FONTS, CSIDL_FONTS);
  m_ShellConstants.add("TEMPLATES", CSIDL_TEMPLATES, CSIDL_COMMON_TEMPLATES);
  m_ShellConstants.add("APPDATA", CSIDL_APPDATA, CSIDL_COMMON_APPDATA);
  m_ShellConstants.add("LOCALAPPDATA", CSIDL_LOCAL_APPDATA, CSIDL_LOCAL_APPDATA);
  m_ShellConstants.add("PRINTHOOD", CSIDL_PRINTHOOD, CSIDL_PRINTHOOD);
  //m_ShellConstants.add("ALTSTARTUP", CSIDL_ALTSTARTUP, CSIDL_COMMON_ALTSTARTUP);
  m_ShellConstants.add("INTERNET_CACHE", CSIDL_INTERNET_CACHE, CSIDL_INTERNET_CACHE);
  m_ShellConstants.add("COOKIES", CSIDL_COOKIES, CSIDL_COOKIES);
  m_ShellConstants.add("HISTORY", CSIDL_HISTORY, CSIDL_HISTORY);
  m_ShellConstants.add("PROFILE", CSIDL_PROFILE, CSIDL_PROFILE);
  m_ShellConstants.add("ADMINTOOLS", CSIDL_ADMINTOOLS, CSIDL_COMMON_ADMINTOOLS);
  m_ShellConstants.add("RESOURCES", CSIDL_RESOURCES, CSIDL_RESOURCES);
  m_ShellConstants.add("RESOURCES_LOCALIZED", CSIDL_RESOURCES_LOCALIZED, CSIDL_RESOURCES_LOCALIZED);
  m_ShellConstants.add("CDBURN_AREA", CSIDL_CDBURN_AREA, CSIDL_CDBURN_AREA);
}

void CEXEBuild::initialize(const char *makensis_path)
{
  string nsis_dir;
  const char *dir = getenv("NSISDIR");
  if (dir) nsis_dir = dir;
  else {
#ifndef NSIS_CONFIG_CONST_DATA_PATH
    nsis_dir = get_executable_dir(makensis_path);
#else
    nsis_dir = PREFIX_DATA;
#endif
  }
  definedlist.add("NSISDIR", nsis_dir.c_str());

  string includes_dir = nsis_dir;
  includes_dir += PLATFORM_PATH_SEPARATOR_STR"Include";
  include_dirs.add(includes_dir.c_str(),0);

  stubs_dir = nsis_dir;
  stubs_dir += PLATFORM_PATH_SEPARATOR_STR"Stubs";

  if (set_compressor("zlib", false) != PS_OK)
  {
    throw runtime_error("error setting default stub");
  }

  string uninst = stubs_dir + PLATFORM_PATH_SEPARATOR_STR + "uninst";
  m_unicon_data = generate_uninstall_icon_data(uninst.c_str(), m_unicon_size);
  if (!m_unicon_data)
  {
    throw runtime_error("invalid default uninstall icon");
  }
}


int CEXEBuild::getcurdbsize() { return cur_datablock->getlen(); }

// returns offset in stringblock
int CEXEBuild::add_string(const char *string, int process/*=1*/, WORD codepage/*=CP_ACP*/)
{
  if (!string || !*string) return 0;

  if (*string == '$' && *(string+1) == '(') {
    int idx = 0;
    char *cp = strdup(string+2);
    char *p = strchr(cp, ')');
    if (p && p[1] == '\0' ) { // if string is only a language str identifier
      *p = 0;
      idx = DefineLangString(cp, process);
    }
    free(cp);
    if (idx < 0) return idx;
  }

  if (!process) return cur_strlist->add(string,2);

  char buf[NSIS_MAX_STRLEN*4];
  preprocess_string(buf,string,codepage);
  return cur_strlist->add(buf,2);
}

int CEXEBuild::add_intstring(const int i) // returns offset in stringblock
{
  char i_str[128];
#ifdef _WIN32
  wsprintf(i_str, "%d", i);
#else
  snprintf(i_str, 128, "%d", i);
#endif
  return add_string(i_str);
}

// based on Dave Laundon's code
int CEXEBuild::preprocess_string(char *out, const char *in, WORD codepage/*=CP_ACP*/)
{
  const char *p=in;
  while (*p)
  {
    const char *np;
#ifdef _WIN32
    np = CharNextExA(codepage, p, 0);
#else
    {
      char buf[1024];
      snprintf(buf, 1024, "CP%d", codepage);
      setlocale(LC_CTYPE, buf);
      int len = mblen(p, strlen(p));
      if (len > 0)
        np = p + len;
      else
        np = p + 1;
      setlocale(LC_CTYPE, "");
    }
#endif
    if (np - p > 1) // multibyte char
    {
      int l = np - p;
      while (l--)
      {
        int i = (unsigned char)*p++;
        if (i >= NS_CODES_START) {
          *out++ = (char)NS_SKIP_CODE;
        }
        *out++=i;
      }
      continue;
    }

    int i = (unsigned char)*p;

    p=np;

    // Test for characters extending into the variable codes
    if (i >= NS_CODES_START) {
      *out++ = (char)NS_SKIP_CODE;
    }
    else if (i == '$')
    {
      if (*p == '$')
        p++; // Can simply convert $$ to $ now
      else
      {
        {
          bool bProceced=false;
          if ( *p )
          {
            const char *pUserVarName = p;
            while (isSimpleChar(*pUserVarName))
              pUserVarName++;

            while (pUserVarName > p)
            {
              if (m_ShellConstants.get((char*)p, pUserVarName-p) >= 0)
                break; // Upps it's a shell constant

              int idxUserVar = m_UserVarNames.get((char*)p, pUserVarName-p);
              if (idxUserVar >= 0)
              {
                // Well, using variables inside string formating doens't mean
                // using the variable, beacuse it will be always an empty string
                // which is also memory wasting
                // So the line below must be commented !??
                //m_UserVarNames.inc_reference(idxUserVar);
                *out++ = (unsigned int) NS_VAR_CODE; // Named user variable;
                WORD w = FIX_ENDIAN_INT16(CODE_SHORT(idxUserVar));
                memcpy(out, &w, sizeof(WORD));
                out += sizeof(WORD);
                p += pUserVarName-p;
                bProceced = true;
                break;
              }
              pUserVarName--;
            }
          }
          if (!bProceced && *p)
          {
            const char *pShellConstName = p;
            while (isSimpleChar(*pShellConstName))
              pShellConstName++;

            while (pShellConstName > p)
            {
              int idxConst = m_ShellConstants.get((char*)p, pShellConstName - p);
              if (idxConst >= 0)
              {
                int CSIDL_Value_current = m_ShellConstants.get_value1(idxConst);
                int CSIDL_Value_all = m_ShellConstants.get_value2(idxConst);
                *out++=(unsigned int)NS_SHELL_CODE; // Constant code identifier
                *out++=(char)CSIDL_Value_current;
                *out++=(char)CSIDL_Value_all;
                p = pShellConstName;
                bProceced = true;
                break;
              }
              pShellConstName--;
            }
          }
          if ( !bProceced && *p == '(' )
          {
            int idx = -1;
            char *cp = strdup(p+1);
            char *pos = strchr(cp, ')');
            if (pos)
            {
              *pos = 0;
              idx = DefineLangString(cp);
              if (idx < 0)
              {
                *out++ = (unsigned int)NS_LANG_CODE; // Next word is lang-string Identifier
                WORD w = FIX_ENDIAN_INT16(CODE_SHORT(-idx-1));
                memcpy(out, &w, sizeof(WORD));
                out += sizeof(WORD);
                p += strlen(cp) + 2;
                bProceced = true;
              }
            }
            free(cp);
          }
          if ( bProceced )
            continue;
          else
          {
            char tbuf[64];
            char cBracket = '\0';
            bool bDoWarning = true;

            if ( *p == '[' )
              cBracket = ']';
            else if ( *p == '(' )
              cBracket = ')';
            else if ( *p == '{' )
              cBracket = '}';

            strncpy(tbuf,p,63);
            tbuf[63]=0;

            if ( cBracket != 0 )
            {
              if (strchr(tbuf,cBracket)) (strchr(tbuf,cBracket)+1)[0]=0;
              if ( tbuf[0] == '{' && tbuf[strlen(tbuf)-1] == '}' )
              {
                char *tstIfDefine = strdup(tbuf+1);
                tstIfDefine[strlen(tstIfDefine)-1] = '\0';
                bDoWarning = definedlist.find(tstIfDefine) == NULL;
              }
            }
            else
            {
              if (strstr(tbuf," ")) strstr(tbuf," ")[0]=0;
            }
            if ( bDoWarning )
              warning_fl("unknown variable/constant \"%s\" detected, ignoring",tbuf);
            i = '$';
          }
        }
      }
    }
    *out++=i;
  }
  *out=0;
  return 0;
}

// what it does is, when you pass it the offset of the last item added, it will determine if
// that data is already present in the datablock, and if so, reference it instead (and shorten
// the datablock as necessary). Reduces overhead if you want to add files to a couple places.
// Woo, an optimizing installer generator, now we're styling.

int CEXEBuild::datablock_optimize(int start_offset, int first_int)
{
  int this_len = cur_datablock->getlen() - start_offset;

  cached_db_size this_size = {first_int, start_offset};
  cur_datablock_cache->add(&this_size, sizeof(cached_db_size));

  if (!build_optimize_datablock || this_len < (int) sizeof(int))
    return start_offset;

  MMapBuf *db = (MMapBuf *) cur_datablock;
  db->setro(TRUE);

  cached_db_size *db_sizes = (cached_db_size *) cur_datablock_cache->get();
  int db_sizes_num = cur_datablock_cache->getlen() / sizeof(cached_db_size);
  db_sizes_num--; // don't compare with the one we just added

  for (int i = 0; i < db_sizes_num; i++)
  {
    if (db_sizes[i].first_int == first_int)
    {
      int pos = db_sizes[i].start_offset;
      int left = this_len;
      while (left > 0)
      {
        int l = min(left, build_filebuflen);
        int la = l;
        void *newstuff = db->get(start_offset + this_len - left, l);
        void *oldstuff = db->getmore(pos + this_len - left, &la);

        int res = memcmp(newstuff, oldstuff, l);

        db->release(oldstuff, la);
        db->release();

        if (res)
        {
          break;
        }

        left -= l;
      }

      if (!left)
      {
        db_opt_save += this_len;
        db->resize(max(start_offset, pos + this_len));
        db->setro(FALSE);
        cur_datablock_cache->resize(cur_datablock_cache->getlen() - sizeof(cached_db_size));
        return pos;
      }
    }
  }

  db->setro(FALSE);

  return start_offset;
}

int CEXEBuild::add_db_data(IMMap *mmap) // returns offset
{
  build_compressor_set = true;

  int done = 0;

  if (!mmap)
  {
    ERROR_MSG("Error: add_db_data() called with invalid mapped file\n");
    return -1;
  }

  int length = mmap->getsize();

  if (length < 0)
  {
    ERROR_MSG("Error: add_db_data() called with length=%d\n", length);
    return -1;
  }

  MMapBuf *db = (MMapBuf *) cur_datablock;

  int st = db->getlen();

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
  if (length && !build_compress_whole && build_compress)
  {
    // grow datablock so that there is room to compress into
    int bufferlen = length + 1024 + length / 4; // give a nice 25% extra space
    db->resize(st + bufferlen + sizeof(int));

    int n = compressor->Init(build_compress_level, build_compress_dict_size);
    if (n != C_OK)
    {
      ERROR_MSG("Internal compiler error #12345: deflateInit() failed(%s [%d]).\n", compressor->GetErrStr(n), n);
      extern void quit(); quit();
    }

    int avail_in = length;
    int avail_out = bufferlen;
    int ret;
    while (avail_in > 0)
    {
      int in_len = min(build_filebuflen, avail_in);
      int out_len = min(build_filebuflen, avail_out);

      compressor->SetNextIn((char *) mmap->get(length - avail_in, in_len), in_len);
      compressor->SetNextOut((char *) db->get(st + sizeof(int) + bufferlen - avail_out, out_len), out_len);
      if ((ret = compressor->Compress(0)) < 0)
      {
        ERROR_MSG("Error: add_db_data() - compress() failed(%s [%d])\n", compressor->GetErrStr(ret), ret);
        return -1;
      }
      mmap->release();
      db->flush(out_len);
      db->release();
      avail_in -= in_len - compressor->GetAvailIn();
      avail_out -= out_len - compressor->GetAvailOut();

      if (!avail_out)
        // not enough space in the output buffer - no compression is better
        break;
    }

    // if not enough space in the output buffer - no compression is better
    if (avail_out)
    {
      char *out;

      char a;
      compressor->SetNextIn(&a,0);

      do
      {
        int out_len = min(build_filebuflen, avail_out);

        out = (char *) db->get(st + sizeof(int) + bufferlen - avail_out, out_len);

        compressor->SetNextOut(out, out_len);
        if ((ret = compressor->Compress(C_FINISH)) < 0)
        {
          ERROR_MSG("Error: add_db_data() - compress() failed(%s [%d])\n", compressor->GetErrStr(ret), ret);
          return -1;
        }

        db->flush(out_len);
        db->release();

        avail_out -= out_len - compressor->GetAvailOut();
      }
      while (compressor->GetNextOut() - out > 0 && avail_out > 0);

      compressor->End();

      int used = bufferlen - avail_out;

      // never store compressed if output buffer is full (compression increased the size...)
      if (avail_out && (build_compress == 2 || used < length))
      {
        done=1;
        db->resize(st + used + sizeof(int));

        *(int*)db->get(st, sizeof(int)) = FIX_ENDIAN_INT32(used | 0x80000000);
        db->release();

        int nst = datablock_optimize(st, used | 0x80000000);
        if (nst == st) db_comp_save += length - used;
        else st = nst;
      }
    }
    else
      compressor->End();
  }
#endif // NSIS_CONFIG_COMPRESSION_SUPPORT

  if (!done)
  {
    db->resize(st + length + sizeof(int));
    int *plen = (int *) db->get(st, sizeof(int));
    *plen = FIX_ENDIAN_INT32(length);
    db->release();

    int left = length;
    while (left > 0)
    {
      int l = min(build_filebuflen, left);
      int *p = (int *) db->get(st + sizeof(int) + length - left, l);
      memcpy(p, mmap->get(length - left, l), l);
      db->flush(l);
      db->release();
      mmap->release();
      left -= l;
    }

    st = datablock_optimize(st, length);
  }

  db_full_size += length + sizeof(int);

  return st;
}

int CEXEBuild::add_db_data(const char *data, int length) // returns offset
{
  MMapFake fakemap;
  fakemap.set(data, length);
  return add_db_data(&fakemap);
}

int CEXEBuild::add_data(const char *data, int length, IGrowBuf *dblock) // returns offset
{
  build_compressor_set=true;

  int done=0;

  if (length < 0)
  {
    ERROR_MSG("Error: add_data() called with length=%d\n",length);
    return -1;
  }

  int st=dblock->getlen();

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
  if (!build_compress_whole && build_compress)
  {
    // grow datablock so that there is room to compress into
    int bufferlen=length+1024+length/4; // give a nice 25% extra space
    dblock->resize(st+bufferlen+sizeof(int));

    int n = compressor->Init(build_compress_level, build_compress_dict_size);
    if (n != C_OK)
    {
      ERROR_MSG("Internal compiler error #12345: deflateInit() failed(%s [%d]).\n", compressor->GetErrStr(n), n);
      extern void quit(); quit();
    }

    compressor->SetNextIn((char*)data, length);
    compressor->SetNextOut((char*)dblock->get() + st + sizeof(int), bufferlen);

    compressor->Compress(C_FINISH);

    int used=bufferlen-compressor->GetAvailOut();

    // never store compressed if output buffer is full
    if (compressor->GetAvailOut() && (build_compress == 2 || used < length))
    {
      done=1;
      dblock->resize(st+used+sizeof(int));

      *((int*)((char *)dblock->get()+st)) = FIX_ENDIAN_INT32(used|0x80000000);
    }
    compressor->End();
  }
#endif // NSIS_CONFIG_COMPRESSION_SUPPORT

  if (!done)
  {
    dblock->resize(st);
    int rl = FIX_ENDIAN_INT32(length);
    dblock->add(&rl,sizeof(int));
    dblock->add(data,length);
  }

  return st;
}

int CEXEBuild::add_label(const char *name)
{
  if (!build_cursection)
  {
    ERROR_MSG("Error: Label declaration not valid outside of function/section\n");
    return PS_ERROR;
  }
  if ((name[0] >= '0' && name[0] <= '9') || name[0] == '-' || name[0] == ' ' || name[0] == ':')
  {
    ERROR_MSG("Error: labels must not begin with 0-9, -, :, or a space.\n");
    return PS_ERROR;
  }

  int cs=build_cursection->code;
  int ce=cs+build_cursection->code_size;

  char *p=strdup(name);
  if (p[strlen(p)-1] == ':') p[strlen(p)-1]=0;
  int offs=ns_label.add(p,0);
  free(p);

  int n=cur_labels->getlen()/sizeof(section);
  if (n)
  {
    section *t=(section*)cur_labels->get();
    while (n--)
    {
      if ((*name == '.' || (t->code >= cs && t->code <= ce))  &&
          t->name_ptr==offs)
      {
        if (*name == '.') ERROR_MSG("Error: global label \"%s\" already declared\n",name);
        else
        {
          char *t = "section";
          if (build_cursection_isfunc)
            t = "function";
          ERROR_MSG("Error: label \"%s\" already declared in %s\n",name,t);
        }
        return PS_ERROR;
      }
      t++;
    }
  }

  section s={0};
  s.name_ptr = offs;
  s.code = ce;
  cur_labels->add(&s,sizeof(s));

  return PS_OK;
}

int CEXEBuild::add_function(const char *funname)
{
  if (build_cursection_isfunc)
  {
    ERROR_MSG("Error: Function open when creating function (use FunctionEnd first)\n");
    return PS_ERROR;
  }
  if (build_cursection)
  {
    ERROR_MSG("Error: Section open when creating function (use SectionEnd first)\n");
    return PS_ERROR;
  }
  if (cur_page)
  {
    ERROR_MSG("Error: PageEx open when creating function (use PageExEnd first)\n");
    return PS_ERROR;
  }
  if (!funname[0])
  {
    ERROR_MSG("Error: Function must have a name\n");
    return PS_ERROR;
  }

  set_uninstall_mode(!strnicmp(funname,"un.",3));

  int addr=ns_func.add(funname,0);
  int x;
  int n=cur_functions->getlen()/sizeof(section);
  section *tmp=(section*)cur_functions->get();
  for (x = 0; x < n; x ++)
  {
    if (tmp[x].name_ptr == addr)
  {
    ERROR_MSG("Error: Function named \"%s\" already exists.\n",funname);
    return PS_ERROR;
  }
  }

  cur_functions->resize((n+1)*sizeof(section));
  build_cursection=((section*)cur_functions->get())+n;
  build_cursection_isfunc=1;
  build_cursection->name_ptr=addr;
  build_cursection->code=cur_entries->getlen()/sizeof(entry);
  build_cursection->code_size=0;
  build_cursection->install_types=0;
  build_cursection->flags=0;
  build_cursection->size_kb=0;
  memset(build_cursection->name,0,sizeof(build_cursection->name));
  return PS_OK;
}

int CEXEBuild::function_end()
{
  if (!build_cursection_isfunc)
  {
    ERROR_MSG("Error: No function open, FunctionEnd called\n");
    return PS_ERROR;
  }
  // add ret.
  add_entry_direct(EW_RET);

  build_cursection_isfunc=0;
  build_cursection=NULL;

  set_uninstall_mode(0);
  return PS_OK;
}


int CEXEBuild::section_add_flags(int flags)
{
  if (!build_cursection || build_cursection_isfunc)
  {
    ERROR_MSG("Error: can't modify flags when no section is open\n");
    return PS_ERROR;
  }
  build_cursection->flags |= flags;
  return PS_OK;
}

int CEXEBuild::section_add_install_type(int inst_type)
{
  if (!build_cursection || build_cursection_isfunc)
  {
    ERROR_MSG("Error: can't modify flags when no section is open\n");
    return PS_ERROR;
  }
  if (build_cursection->install_types == ~0)
    build_cursection->install_types = 0;
  build_cursection->install_types |= inst_type;
  return PS_OK;
}

void CEXEBuild::section_add_size_kb(int kb)
{
  if (build_cursection)
  {
    build_cursection->size_kb+=kb;
  }
}

int CEXEBuild::section_end()
{
  if (build_cursection_isfunc)
  {
    ERROR_MSG("Error: SectionEnd specified in function (not section)\n");
    return PS_ERROR;
  }
  if (!build_cursection)
  {
    ERROR_MSG("Error: SectionEnd specified and no sections open\n");
    return PS_ERROR;
  }
  add_entry_direct(EW_RET);
  build_cursection->code_size--;
  build_cursection=NULL;
  if (!sectiongroup_open_cnt)
    set_uninstall_mode(0);
  return PS_OK;
}

int CEXEBuild::add_section(const char *secname, const char *defname, int expand/*=0*/)
{
  if (build_cursection_isfunc)
  {
    ERROR_MSG("Error: Section can't create section (already in function, use FunctionEnd first)\n");
    return PS_ERROR;
  }
  if (cur_page) {
    ERROR_MSG("Error: PageEx already open, call PageExEnd first\n");
    return PS_ERROR;
  }
  if (build_cursection)
  {
    ERROR_MSG("Error: Section already open, call SectionEnd first\n");
    return PS_ERROR;
  }

  section new_section;
  new_section.flags = SF_SELECTED;
  new_section.flags |= expand ? SF_EXPAND : 0;
  new_section.code_size = 0;
  new_section.size_kb = 0;

  char *name = (char*)secname;

  if (secname[0] == '-')
  {
    if (secname[1])
    {
      new_section.flags |= SF_SECGRP;
      name++;
    }
    else
      new_section.flags |= SF_SECGRPEND;
  }

  if (name[0] == '!')
  {
    name++;
    new_section.flags |= SF_BOLD;
  }

  int old_uninstall_mode = uninstall_mode;

  set_uninstall_mode(0);

  if (!strnicmp(name, "un.", 3))
  {
    set_uninstall_mode(1);
    name += 3;
  }

  if (!stricmp(name, "uninstall"))
  {
    set_uninstall_mode(1);
  }

  if ((new_section.flags & SF_SECGRPEND) && sectiongroup_open_cnt && old_uninstall_mode)
  {
    set_uninstall_mode(1);
  }

  if (sectiongroup_open_cnt)
  {
    if (uninstall_mode != old_uninstall_mode)
    {
      ERROR_MSG("Error: Can't create %s section in %s section group (use SectionGroupEnd first)\n", uninstall_mode ? "uninstaller" : "installer", old_uninstall_mode ? "uninstaller" : "installer");
      return PS_ERROR;
    }
  }

  new_section.code = cur_entries->getlen() / sizeof(entry);

  new_section.install_types = *name ? 0 : ~0;
  new_section.name_ptr = add_string(name);
  memset(&new_section.name,0,sizeof(new_section.name));

  cur_sections->add(&new_section, sizeof(section));
  build_cursection = (section *) cur_sections->get() + cur_header->blocks[NB_SECTIONS].num;

  if (defname[0])
  {
    char buf[128];
#ifdef _WIN32
    wsprintf(buf, "%d", cur_header->blocks[NB_SECTIONS].num);
#else
    snprintf(buf, 128, "%d", cur_header->blocks[NB_SECTIONS].num);
#endif
    if (definedlist.add(defname, buf))
    {
      ERROR_MSG("Error: \"%s\" already defined, can't assign section index!\n", defname);
      return PS_ERROR;
    }
  }

  cur_header->blocks[NB_SECTIONS].num++;

  if (new_section.flags & (SF_SECGRP | SF_SECGRPEND))
  {
    add_entry_direct(EW_RET);
    build_cursection->code_size = 0;

    build_cursection = 0;

    if (new_section.flags & SF_SECGRPEND)
    {
      sectiongroup_open_cnt--;
      if (sectiongroup_open_cnt < 0)
      {
        ERROR_MSG("SectionGroupEnd: no SectionGroups are open\n");
        return PS_ERROR;
      }
      if (!sectiongroup_open_cnt)
      {
        set_uninstall_mode(0);
      }
    }
    else
      sectiongroup_open_cnt++;
  }

  return PS_OK;
}

int CEXEBuild::add_entry(const entry *ent)
{
  if (!build_cursection && !uninstall_mode)
  {
    ERROR_MSG("Error: Can't add entry, no section or function is open!\n");
    return PS_ERROR;
  }

  cur_entries->add(ent,sizeof(entry));
  cur_instruction_entry_map->add(&multiple_entries_instruction,sizeof(int));
  build_cursection->code_size++;
  cur_header->blocks[NB_ENTRIES].num++;

  multiple_entries_instruction=1;

  return PS_OK;
}

int CEXEBuild::add_entry_direct(int which, int o0, int o1, int o2, int o3, int o4, int o5 /*o#=0*/)
{
  entry ent;
  ent.which = which;
  ent.offsets[0] = o0;
  ent.offsets[1] = o1;
  ent.offsets[2] = o2;
  ent.offsets[3] = o3;
  ent.offsets[4] = o4;
  ent.offsets[5] = o5;
  return add_entry(&ent);
}

int CEXEBuild::resolve_jump_int(const char *fn, int *a, int offs, int start, int end)
{
  if (*a > 0)
  {
    char *lname=(char*)ns_label.get()+*a;
    if (lname[0] == '-' || lname[0]=='+')
    {
      int jump = atoi(lname);
      int *skip_map = (int *) cur_instruction_entry_map->get();
      int maxoffs = cur_instruction_entry_map->getlen() / (int) sizeof(int);

      int direction = 1;
      if (jump < 0)
        direction = -1;

      for (; jump != 0; jump -= direction)
      {
        offs += direction;
        if (offs >= 0 && offs < maxoffs)
        {
          while (skip_map[offs])
          {
            offs += direction;
          }
        }
      }

      *a = offs + 1;
    }
    else
    {
      section *s = (section*)cur_labels->get();
      int n=cur_labels->getlen()/sizeof(section);
      while (n-->0)
      {
        if ((*lname == '.' || (s->code >= start && s->code <= end)) && s->name_ptr == *a)
        {
          *a = s->code+1;     // jumps are to the absolute position, +1 (to differentiate between no jump, and jumping to offset 0)
          s->flags++;
          return 0;
        }
        s++;
      }

      ERROR_MSG("Error: could not resolve label \"%s\" in %s\n",lname,fn);
      return 1;
    }
  }
  else if (*a < 0) // to jump to a user variable target, -variable_index-1 is already stored.
  {
  }
  // otherwise, *a is 0, which means no jump and we also leave it intact
  return 0;
}

int CEXEBuild::resolve_call_int(const char *fn, const char *str, int fptr, int *ofs)
{
  if (fptr < 0) return 0;
  int nf=cur_functions->getlen()/sizeof(section);
  section *sec=(section *)cur_functions->get();
  while (nf-- > 0)
  {
    if (sec->name_ptr>0 && sec->name_ptr == fptr)
    {
      ofs[0]=sec->code;
      sec->flags++;
      return 0;
    }
    sec++;
  }
  ERROR_MSG("Error: resolving %s function \"%s\" in %s\n",str,(char*)ns_func.get()+fptr,fn);
  ERROR_MSG("Note: uninstall functions must begin with \"un.\", and install functions must not\n");
  return 1;
}

int CEXEBuild::resolve_instruction(const char *fn, const char *str, entry *w, int offs, int start, int end)
{
  if (w->which == EW_NOP)
  {
    if (resolve_jump_int(fn,&w->offsets[0],offs,start,end)) return 1;
  }
#ifdef NSIS_SUPPORT_MESSAGEBOX
  else if (w->which == EW_MESSAGEBOX)
  {
    if (resolve_jump_int(fn,&w->offsets[3],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[5],offs,start,end)) return 1;
  }
#endif
  else if (w->which == EW_IFFILEEXISTS)
  {
    if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
  }
  else if (w->which == EW_IFFLAG)
  {
    if (resolve_jump_int(fn,&w->offsets[0],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
  }
#ifdef NSIS_SUPPORT_STROPTS
  else if (w->which == EW_STRCMP)
  {
    if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[3],offs,start,end)) return 1;
  }
#endif
#ifdef NSIS_SUPPORT_INTOPTS
  else if (w->which == EW_INTCMP)
  {
    if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[3],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[4],offs,start,end)) return 1;
  }
#endif
#ifdef NSIS_SUPPORT_HWNDS
  else if (w->which == EW_ISWINDOW)
  {
    if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
    if (resolve_jump_int(fn,&w->offsets[2],offs,start,end)) return 1;
  }
#endif
  else if (w->which == EW_CALL)
  {
    if (w->offsets[0] >= 0 && w->offsets[1]) // get as jump
    {
      if (resolve_jump_int(fn,&w->offsets[0],offs,start,end)) return 1;
    }
    else
    {
      if (w->offsets[0] >= 0 && resolve_call_int(fn,str,w->offsets[0],w->offsets)) return 1;
      // if w->offsets[0] >= 0, EW_CALL requires that it 1-based.
      // otherwise, if < 0, it needs an increment anyway (since it
      // was encoded with a -2 base, to prevent it looking like an
      // empty string "")
      w->offsets[0]++;
    }
  }
#ifdef NSIS_SUPPORT_STROPTS
  else if (w->which == EW_GETFUNCTIONADDR)
  {
    if (w->offsets[1] < 0)
    {
      ERROR_MSG("Error: GetFunctionAddress requires a real function to get address of.\n");
      return 1;
    }

    if (resolve_call_int(fn,str,w->offsets[1],&w->offsets[1])) return 1;

    w->which=EW_ASSIGNVAR;
    w->offsets[1]=add_intstring(w->offsets[1]+1); // +1 here to make 1-based.
  }
  else if (w->which == EW_GETLABELADDR)
  {
    if (resolve_jump_int(fn,&w->offsets[1],offs,start,end)) return 1;
    w->which=EW_ASSIGNVAR;
    w->offsets[1]=add_intstring(w->offsets[1]);
  }
#endif
  return 0;
}

int CEXEBuild::resolve_coderefs(const char *str)
{
  // resolve jumps&calls
  {
    section *sec=(section *)cur_functions->get();
    int l=cur_functions->getlen()/sizeof(section);
    entry *w=(entry *)cur_entries->get();
    while (l-- > 0)
    {
      int x;
      for (x = sec->code; x < sec->code+sec->code_size; x ++)
      {
        char fname[1024];
        wsprintf(fname,"function \"%s\"",ns_func.get()+sec->name_ptr);
        if (resolve_instruction(fname,str,w+x,x,sec->code,sec->code+sec->code_size)) return 1;
      }
      sec++;
    }

    int cnt=0;
    sec=(section *)cur_sections->get();
    l=cur_sections->getlen()/sizeof(section);
    while (l-- > 0)
    {
      int x=sec->name_ptr;
      char fname[1024];
      const char *section_name;
      if (x < 0)
      {
        // lang string
        section_name = "$(lang string)";
      }
      else
      {
        // normal string
        section_name = cur_strlist->get() + x;
      }
      if (x) wsprintf(fname,"%s section \"%s\" (%d)",str,section_name,cnt);
      else wsprintf(fname,"unnamed %s section (%d)",str,cnt);
      for (x = sec->code; x < sec->code+sec->code_size; x ++)
      {
        if (resolve_instruction(fname,str,w+x,x,sec->code,sec->code+sec->code_size))
          return 1;
      }
      sec++;
      cnt++;
    }
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
#ifdef NSIS_SUPPORT_CODECALLBACKS
    if (cur_pages->getlen()) {
      page *p=(page *)cur_pages->get();
      int i = 0;
      while (i < cur_header->blocks[NB_PAGES].num) {
        char pagestr[1024];
        wsprintf(pagestr, "%s pages", str);
        if (resolve_call_int(pagestr,p->dlg_id?"pre-page":"create-page",p->prefunc,&p->prefunc)) return 1;
        if (resolve_call_int(pagestr,"show-page",p->showfunc,&p->showfunc)) return 1;
        if (resolve_call_int(pagestr,"leave-page",p->leavefunc,&p->leavefunc)) return 1;
        p++;
        i++;
      }
    }
#endif
#endif
  }

#ifdef NSIS_SUPPORT_CODECALLBACKS
  // resolve callbacks
  {
    struct {
      char *name;
      int *p;
    } callbacks[] = {
      {"%s.onInit", &cur_header->code_onInit},
      {"%s.on%sInstSuccess", &cur_header->code_onInstSuccess},
      {"%s.on%sInstFailed", &cur_header->code_onInstFailed},
      {"%s.onUserAbort", &cur_header->code_onUserAbort},
      {"%s.onVerifyInstDir", &cur_header->code_onVerifyInstDir},
#ifdef NSIS_CONFIG_ENHANCEDUI_SUPPORT
      {"%s.onGUIInit", &cur_header->code_onGUIInit},
      {"%s.onGUIEnd", &cur_header->code_onGUIEnd},
      {"%s.onMouseOverSection", &cur_header->code_onMouseOverSection},
#endif//NSIS_CONFIG_ENHANCEDUI_SUPPORT
#ifdef NSIS_CONFIG_COMPONENTPAGE
      {"%s.onSelChange", &cur_header->code_onSelChange},
#endif//NSIS_CONFIG_COMPONENTPAGE
#ifdef NSIS_SUPPORT_REBOOT
      {"%s.onRebootFailed", &cur_header->code_onRebootFailed},
#endif//NSIS_SUPPORT_REBOOT
      {0, 0}
    };

    for (int i = 0; callbacks[i].name; i++) {
      const char *un = uninstall_mode ? "un" : "";
      char fname[1024];
      wsprintf(fname, callbacks[i].name, un, un);
      char cbstr[1024];
      wsprintf(cbstr, "%s callback", str);
      char cbstr2[1024];
      wsprintf(cbstr2, "%s.callbacks", un);

      if (resolve_call_int(cbstr,cbstr2,ns_func.find(fname,0),callbacks[i].p))
        return PS_ERROR;
    }
  }
#endif//NSIS_SUPPORT_CODECALLBACKS

  // optimize unused functions
  {
    section *sec=(section *)cur_functions->get();
    int l=cur_functions->getlen()/sizeof(section);
    entry *w=(entry*)cur_entries->get();
    while (l-- > 0)
    {
      if (sec->name_ptr)
      {
        if (!sec->flags)
        {
          if (sec->code_size>0)
          {
            warning("%s function \"%s\" not referenced - zeroing code (%d-%d) out\n",str,
              ns_func.get()+sec->name_ptr,
              sec->code,sec->code+sec->code_size);
            memset(w+sec->code,0,sec->code_size*sizeof(entry));
          }
        }
      }
      sec++;
    }
  }

  // give warnings on unused labels
  {
    section *t=(section*)cur_labels->get();
    int n=cur_labels->getlen()/sizeof(section);
    while (n-->0)
    {
      if (!t->flags)
      {
        char *n=(char*)ns_label.get()+t->name_ptr;
        if (*n == '.') warning("global label \"%s\" not used",n);
        else warning("label \"%s\" not used",n);
      }
      t++;
    }
  }

  return 0;
}

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
int CEXEBuild::add_page(int type)
{
  page pg = {
    0,
    0,
#ifdef NSIS_SUPPORT_CODECALLBACKS
    -1,
    -1,
    -1,
#endif
    0,
  };

#ifndef NSIS_CONFIG_LICENSEPAGE
  if (type == PAGE_LICENSE)
  {
    ERROR_MSG("Error: can't add license page, NSIS_CONFIG_LICENSEPAGE not defined.\n");
    return PS_ERROR;
  }
#endif
#ifndef NSIS_CONFIG_COMPONENTPAGE
  if (type == PAGE_COMPONENTS)
  {
    ERROR_MSG("Error: can't add components page, NSIS_CONFIG_COMPONENTPAGE not defined.\n");
    return PS_ERROR;
  }
#endif
#ifndef NSIS_CONFIG_UNINSTALL_SUPPORT
  if (type == PAGE_COMPONENTS)
  {
    ERROR_MSG("Error: can't add uninstConfirm page, NSIS_CONFIG_UNINSTALL_SUPPORT not defined.\n");
    return PS_ERROR;
  }
#endif

  struct {
    int wndproc_id;
    int dlg_id;
  } ids[] = {
    {PWP_CUSTOM, 0}, // custom
#ifdef NSIS_CONFIG_LICENSEPAGE
    {PWP_LICENSE, IDD_LICENSE}, // license
#else
    {0, IDD_LICENSE}, // license
#endif
#ifdef NSIS_CONFIG_COMPONENTPAGE
    {PWP_SELCOM, IDD_SELCOM}, // components
#else
    {0, IDD_SELCOM}, // components
#endif
    {PWP_DIR, IDD_DIR}, // directory
    {PWP_INSTFILES, IDD_INSTFILES}, // instfiles
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
    {PWP_UNINST, IDD_UNINST}, // uninstConfirm
#else
    {0, IDD_UNINST}, // uninstConfirm
#endif
    {PWP_COMPLETED, -1} // completed
  };

  pg.wndproc_id = ids[type].wndproc_id;
  pg.dlg_id = ids[type].dlg_id;

  cur_pages->add(&pg,sizeof(page));

  cur_page = (page *)cur_pages->get() + cur_header->blocks[NB_PAGES].num++;

  cur_page_type = type;

  return PS_OK;
}

int CEXEBuild::page_end()
{
  cur_page = 0;

  return PS_OK;
}
#endif

#ifdef NSIS_SUPPORT_VERSION_INFO
int CEXEBuild::AddVersionInfo()
{
  GrowBuf VerInfoStream;

  if ( rVersionInfo.GetStringTablesCount() > 0 )
  {
    if ( !version_product_v[0] )
    {
      ERROR_MSG("Error: VIProductVersion is required when other version information functions are used.\n");
      return PS_ERROR;
    }
    else
    {
      int imm, iml, ilm, ill;
      if ( sscanf(version_product_v, "%d.%d.%d.%d", &imm, &iml, &ilm, &ill) != 4 )
      {
        ERROR_MSG("Error: invalid VIProductVersion format, should be X.X.X.X\n");
        return PS_ERROR;
      }
      rVersionInfo.SetFileVersion(MAKELONG(iml, imm),MAKELONG(ill, ilm));
      rVersionInfo.SetProductVersion(MAKELONG(iml, imm),MAKELONG(ill, ilm));

      try
      {
        init_res_editor();
        for ( int i = 0; i < rVersionInfo.GetStringTablesCount(); i++ )
        {
          LANGID lang_id = rVersionInfo.GetLangID(i);
          int code_page = rVersionInfo.GetCodePage(i);
          LanguageTable *Table = GetLangTable(lang_id);

          if ( !rVersionInfo.FindKey(lang_id, code_page, "FileVersion") )
            warning("Generating version information for language \"%04d-%s\" without standard key \"FileVersion\"", lang_id, Table->nlf.m_bLoaded ? Table->nlf.m_szName : lang_id == 1033 ? "English" : "???");
          if ( !rVersionInfo.FindKey(lang_id, code_page, "FileDescription") )
            warning("Generating version information for language \"%04d-%s\" without standard key \"FileDescription\"", lang_id, Table->nlf.m_bLoaded ? Table->nlf.m_szName : lang_id == 1033 ? "English" : "???");
          if ( !rVersionInfo.FindKey(lang_id, code_page, "LegalCopyright") )
            warning("Generating version information for language \"%04d-%s\" without standard key \"LegalCopyright\"", lang_id, Table->nlf.m_bLoaded ? Table->nlf.m_szName : lang_id == 1033 ? "English" : "???");

          rVersionInfo.ExportToStream(VerInfoStream, i);
          res_editor->UpdateResource(RT_VERSION, 1, lang_id, (BYTE*)VerInfoStream.get(), VerInfoStream.getlen());
        }
      }
      catch (exception& err) {
        ERROR_MSG("Error adding version information: %s\n", err.what());
        return PS_ERROR;
      }
    }
  }

  return PS_OK;
}
#endif // NSIS_SUPPORT_VERSION_INFO

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
int CEXEBuild::ProcessPages()
{
  SCRIPT_MSG("Processing pages... ");

  int license_normal=0;
  int license_fsrb=0;
  int license_fscb=0;
  int selcom=0;
  int dir=0, dir_used;
  int uninstconfirm=0;
  int instlog=0, instlog_used;
  int main=0;

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
again:
#endif

  dir_used = 0;
  instlog_used = 0;

#ifdef NSIS_CONFIG_SILENT_SUPPORT
  if ((cur_header->flags & (CH_FLAGS_SILENT|CH_FLAGS_SILENT_LOG)) == 0)
#endif
  {
    main++;

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
#define LS(inst, uninst) (uninstall_mode ? uninst : inst)
#else
#define LS(inst, uninst) inst
#endif

    DefineInnerLangString(NLF_BRANDING);

    if (!cur_pages->getlen()) {
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
      if (uninstall_mode) {
        if (HasUserDefined(NLF_UNINST_TEXT)) {
          add_page(PAGE_UNINSTCONFIRM);
          page_end();
        }
        add_page(PAGE_INSTFILES);
        page_end();
        add_page(PAGE_COMPLETED);
        page_end();
      }
      else
#endif
      {
#ifdef NSIS_CONFIG_LICENSEPAGE
        if (HasUserDefined(NLF_LICENSE_TEXT) && HasUserDefined(NLF_LICENSE_DATA)) {
          add_page(PAGE_LICENSE);
          page_end();
        }
#endif
#ifdef NSIS_CONFIG_COMPONENTPAGE
        if (HasUserDefined(NLF_COMP_TEXT)) {
          add_page(PAGE_COMPONENTS);
          page_end();
        }
#endif
        if (HasUserDefined(NLF_DIR_TEXT)) {
          add_page(PAGE_DIRECTORY);
          page_end();
        }
        add_page(PAGE_INSTFILES);
        page_end();
        add_page(PAGE_COMPLETED);
        page_end();
      }
    }
    // start processing the pages
    {
      int i = 0;
      page *p = (page *) cur_pages->get();

      for (i = 0; i < cur_header->blocks[NB_PAGES].num; i++, p++) {
        page *pp = 0;

        if (i) {
          pp = p - 1;

          // set back button
          p->flags |= PF_BACK_SHOW;
          if (pp->wndproc_id != PWP_COMPLETED && p->wndproc_id != PWP_COMPLETED && p->wndproc_id != PWP_INSTFILES)
            p->flags |= PF_BACK_ENABLE;
          if (!p->back)
            p->back = DefineInnerLangString(NLF_BTN_BACK);

          // set previous page's next button
          if (!pp->next) {
            int str = 0;

#ifdef NSIS_CONFIG_LICENSEPAGE
            if (pp->wndproc_id == PWP_LICENSE && (!(pp->flags & PF_LICENSE_FORCE_SELECTION) || HasUserDefined(NLF_BTN_LICENSE)))
              str = NLF_BTN_LICENSE;
            else
#endif
            if (p->wndproc_id == PWP_INSTFILES)
              str = LS(NLF_BTN_INSTALL, NLF_BTN_UNINSTALL);
            else
              str = NLF_BTN_NEXT;

            pp->next = DefineInnerLangString(str);
          }

          // set previous page's click next text
          if (!pp->clicknext) {
            int str = 0;

            if (p->wndproc_id == PWP_INSTFILES)
              str = LS(NLF_CLICK_INSTALL, NLF_CLICK_UNINSTALL);
            else
              str = NLF_CLICK_NEXT;

            pp->clicknext = DefineInnerLangString(str);
          }
        }

        // enable next button
        if (p->wndproc_id != PWP_INSTFILES)
          p->flags |= PF_NEXT_ENABLE;

        // set cancel button
        if (!p->cancel)
          p->cancel = DefineInnerLangString(NLF_BTN_CANCEL);
        if (p->wndproc_id != PWP_INSTFILES && p->wndproc_id != PWP_COMPLETED)
          p->flags |= PF_CANCEL_ENABLE;

        // set caption
        struct {
          int caption;
          int ucaption;
        } captions[] = {
#ifdef NSIS_CONFIG_LICENSEPAGE
          {NLF_SUBCAPTION_LICENSE, NLF_SUBCAPTION_LICENSE},
#endif
#ifdef NSIS_CONFIG_COMPONENTPAGE
          {NLF_SUBCAPTION_OPTIONS, NLF_SUBCAPTION_OPTIONS},
#endif
          {NLF_SUBCAPTION_DIR, NLF_SUBCAPTION_DIR},
          {NLF_SUBCAPTION_INSTFILES, NLF_USUBCAPTION_INSTFILES},
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
          {NLF_USUBCAPTION_CONFIRM, NLF_USUBCAPTION_CONFIRM},
#endif
          {NLF_SUBCAPTION_COMPLETED, NLF_USUBCAPTION_COMPLETED}
        };

        if (!p->caption && p->wndproc_id != PWP_CUSTOM) {
          p->caption = DefineInnerLangString(LS(captions[p->wndproc_id].caption, captions[p->wndproc_id].ucaption));
        }

        // set texts
        switch (p->dlg_id) {
#ifdef NSIS_CONFIG_LICENSEPAGE
          case IDD_LICENSE:
          case IDD_LICENSE_FSRB:
          case IDD_LICENSE_FSCB:
          {
            if (!(p->flags & PF_PAGE_EX))
              p->dlg_id = license_res_id;
            if (!(p->flags & (PF_LICENSE_FORCE_SELECTION | PF_LICENSE_NO_FORCE_SELECTION)))
              p->dlg_id = license_res_id;

            p->flags |= PF_NO_NEXT_FOCUS;

            if (!p->parms[1])
              p->parms[1] = DefineInnerLangString(NLF_LICENSE_DATA, 0);

            if (p->dlg_id == IDD_LICENSE) {
              if (!p->parms[0])
                p->parms[0] = DefineInnerLangString(LS(NLF_LICENSE_TEXT, NLF_ULICENSE_TEXT));

              license_normal++;
            }
            else if (p->dlg_id == IDD_LICENSE_FSCB) {
              p->flags |= PF_LICENSE_FORCE_SELECTION;

              if (!p->parms[0])
                p->parms[0] = DefineInnerLangString(LS(NLF_LICENSE_TEXT_FSCB, NLF_ULICENSE_TEXT_FSCB));
              if (!p->parms[2])
                p->parms[2] = DefineInnerLangString(NLF_BTN_LICENSE_AGREE);

              license_fscb++;
            }
            else if (p->dlg_id == IDD_LICENSE_FSRB) {
              p->flags |= PF_LICENSE_FORCE_SELECTION;

              if (!p->parms[0])
                p->parms[0] = DefineInnerLangString(LS(NLF_LICENSE_TEXT_FSRB, NLF_ULICENSE_TEXT_FSRB));
              if (!p->parms[2])
                p->parms[2] = DefineInnerLangString(NLF_BTN_LICENSE_AGREE);
              if (!p->parms[3])
                p->parms[3] = DefineInnerLangString(NLF_BTN_LICENSE_DISAGREE);

              license_fsrb++;
            }
            break;
          }
#endif
#ifdef NSIS_CONFIG_COMPONENTPAGE
          case IDD_SELCOM:
          {
            if (!p->parms[0])
              p->parms[0] = DefineInnerLangString(LS(NLF_COMP_TEXT, NLF_UCOMP_TEXT));
            if (!p->parms[1])
              p->parms[1] = DefineInnerLangString(LS(NLF_COMP_SUBTEXT1, NLF_UCOMP_SUBTEXT1));
            if (!p->parms[2])
              p->parms[2] = DefineInnerLangString(LS(NLF_COMP_SUBTEXT2, NLF_UCOMP_SUBTEXT2));
            if (!p->parms[3] && !uninstall_mode && HasUserDefined(NLF_COMP_SUBTEXT1))
              p->parms[3] = p->parms[1];
            if (!p->parms[4] && !uninstall_mode && HasUserDefined(NLF_COMP_SUBTEXT2))
              p->parms[4] = p->parms[2];
            else if (!p->parms[4])
              p->parms[4] = DefineInnerLangString(LS(NLF_COMP_SUBTEXT1_NO_INST_TYPES, NLF_UCOMP_SUBTEXT1_NO_INST_TYPES));

            DefineInnerLangString(NLF_SPACE_REQ);
            DefineInnerLangString(NLF_BYTE);
            DefineInnerLangString(NLF_KILO);
            DefineInnerLangString(NLF_MEGA);
            DefineInnerLangString(NLF_GIGA);

            selcom++;
            break;
          }
#endif
          case IDD_DIR:
          {
            if (!p->parms[0])
              p->parms[0] = DefineInnerLangString(LS(NLF_DIR_TEXT, NLF_UDIR_TEXT));
            if (!p->parms[1])
              p->parms[1] = DefineInnerLangString(LS(NLF_DIR_SUBTEXT, NLF_UDIR_SUBTEXT));
            if (!p->parms[2])
              p->parms[2] = DefineInnerLangString(NLF_BTN_BROWSE);
            if (!p->parms[3])
              p->parms[3] = DefineInnerLangString(LS(NLF_DIR_BROWSETEXT, NLF_UDIR_BROWSETEXT));
            if (!p->parms[4])
              p->parms[4] = m_UserVarNames.get("INSTDIR");
            else
              p->parms[4]--;

            DefineInnerLangString(NLF_SPACE_AVAIL);
            DefineInnerLangString(NLF_SPACE_REQ);
            DefineInnerLangString(NLF_BYTE);
            DefineInnerLangString(NLF_KILO);
            DefineInnerLangString(NLF_MEGA);
            DefineInnerLangString(NLF_GIGA);
#ifdef NSIS_CONFIG_LOG
            DefineInnerLangString(NLF_LOG_INSTALL_PROCESS);
#endif

            dir++;
            break;
          }
          case IDD_INSTFILES:
          {
            if (!p->parms[1])
              p->parms[1] = DefineInnerLangString(NLF_BTN_DETAILS);
            if (!p->parms[2])
              p->parms[2] = DefineInnerLangString(NLF_COMPLETED);

            DefineInnerLangString(NLF_COPY_DETAILS);

            instlog++;
            instlog_used++;
            break;
          }
          case IDD_UNINST:
          {
            if (!p->parms[0])
              p->parms[0] = DefineInnerLangString(NLF_UNINST_TEXT);
            if (!p->parms[1])
              p->parms[1] = DefineInnerLangString(NLF_UNINST_SUBTEXT);
            if (!p->parms[4])
              p->parms[4] = m_UserVarNames.get("INSTDIR");
            else
              p->parms[4]--;

            uninstconfirm++;
            break;
          }
        }

        p->flags &= ~PF_PAGE_EX;
      }

      p--;

      if (!p->next)
        p->next = DefineInnerLangString(NLF_BTN_CLOSE);
      if (p->wndproc_id == PWP_COMPLETED)
        (p-1)->next = DefineInnerLangString(NLF_BTN_CLOSE);

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
      if (uninstall_mode) {
        if (!uenable_last_page_cancel && instlog_used)
          p->flags &= ~PF_CANCEL_ENABLE;
      }
      else
#endif
      {
        if (!enable_last_page_cancel && instlog_used)
          p->flags &= ~PF_CANCEL_ENABLE;
      }

      if (!instlog_used) {
        warning("%sage instfiles not used, no sections will be executed!", uninstall_mode ? "Uninstall p" : "P");
      }
    }
  }

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
    if (!uninstall_mode) {
      set_uninstall_mode(1);
      goto again;
    }
    else
      set_uninstall_mode(0);
#endif//NSIS_CONFIG_UNINSTALL_SUPPORT


  SCRIPT_MSG("Done!\n");

#define REMOVE_ICON(id) if (disable_window_icon) { \
    BYTE* dlg = res_editor->GetResource(RT_DIALOG, MAKEINTRESOURCE(id), NSIS_DEFAULT_LANG); \
    if (dlg) { \
      CDialogTemplate dt(dlg,uDefCodePage); \
      res_editor->FreeResource(dlg); \
      if (dt.RemoveItem(IDC_ULICON)) { \
        DialogItemTemplate* text = dt.GetItem(IDC_INTROTEXT); \
        DialogItemTemplate* prog = dt.GetItem(IDC_PROGRESS); \
        if (text) { \
          text->sWidth += text->sX; \
          text->sX = 0; \
        } \
        if (prog) { \
          prog->sWidth += prog->sX; \
          prog->sX = 0; \
        } \
         \
        DWORD dwSize; \
        dlg = dt.Save(dwSize); \
        res_editor->UpdateResource(RT_DIALOG, MAKEINTRESOURCE(id), NSIS_DEFAULT_LANG, dlg, dwSize); \
        delete [] dlg; \
      } \
    } \
  }

  try {
    SCRIPT_MSG("Removing unused resources... ");
    init_res_editor();
#ifdef NSIS_CONFIG_LICENSEPAGE
    if (!license_normal) {
      res_editor->UpdateResource(RT_DIALOG, IDD_LICENSE, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_LICENSE);
    if (!license_fsrb) {
      res_editor->UpdateResource(RT_DIALOG, IDD_LICENSE_FSRB, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_LICENSE_FSRB);
    if (!license_fscb) {
      res_editor->UpdateResource(RT_DIALOG, IDD_LICENSE_FSCB, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_LICENSE_FSCB);
#endif // NSIS_CONFIG_LICENSEPAGE
#ifdef NSIS_CONFIG_COMPONENTPAGE
    if (!selcom) {
      res_editor->UpdateResource(RT_DIALOG, IDD_SELCOM, NSIS_DEFAULT_LANG, 0, 0);
      res_editor->UpdateResource(RT_BITMAP, IDB_BITMAP1, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_SELCOM);
#endif // NSIS_CONFIG_COMPONENTPAGE
    if (!dir) {
      res_editor->UpdateResource(RT_DIALOG, IDD_DIR, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_DIR);
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
    if (!uninstconfirm) {
      res_editor->UpdateResource(RT_DIALOG, IDD_UNINST, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_UNINST);
#endif // NSIS_CONFIG_UNINSTALL_SUPPORT
    if (!instlog) {
      res_editor->UpdateResource(RT_DIALOG, IDD_INSTFILES, NSIS_DEFAULT_LANG, 0, 0);
    }
    else REMOVE_ICON(IDD_INSTFILES);
    if (!main) {
      res_editor->UpdateResource(RT_DIALOG, IDD_INST, NSIS_DEFAULT_LANG, 0, 0);
      if (!build_compress_whole && !build_crcchk)
        res_editor->UpdateResource(RT_DIALOG, IDD_VERIFY, NSIS_DEFAULT_LANG, 0, 0);
    }

    SCRIPT_MSG("Done!\n");
  }
  catch (exception& err) {
    ERROR_MSG("\nError: %s\n", err.what());
    return PS_ERROR;
  }

  return PS_OK;
}
#endif // NSIS_CONFIG_VISIBLE_SUPPORT

#ifdef NSIS_CONFIG_COMPONENTPAGE
void CEXEBuild::PrepareInstTypes()
{
  if (!(cur_header->flags & CH_FLAGS_NO_CUSTOM))
    cur_header->install_types[NSIS_MAX_INST_TYPES] = DefineInnerLangString(NLF_COMP_CUSTOM);

  // set insttype list for RO sections that didn't use SectionIn
  int i = cur_header->blocks[NB_SECTIONS].num;
  section *sections = (section *) cur_sections->get();

  while (i--)
  {
    if (sections[i].flags & SF_RO && !sections[i].install_types)
      sections[i].install_types = ~0;
  }

  // set selection to first insttype
  if (cur_header->install_types[0])
  {
    int i = cur_header->blocks[NB_SECTIONS].num;
    section *sections = (section *) cur_sections->get();

    // if /o was used abort since the user did his manual choice
    while (i--)
      if ((sections[i].flags & SF_SELECTED) == 0)
        return;

    i = cur_header->blocks[NB_SECTIONS].num;

    while (i--)
      if ((sections[i].install_types & 1) == 0)
        sections[i].flags &= ~SF_SELECTED;
  }
}
#endif

void CEXEBuild::PrepareHeaders(IGrowBuf *hdrbuf)
{
  GrowBuf blocks_buf;
  growbuf_writer_sink sink(&blocks_buf);

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  cur_header->blocks[NB_PAGES].offset = sizeof(header) + blocks_buf.getlen();
  page_writer::write_block(cur_pages, &sink);
#endif

  cur_header->blocks[NB_SECTIONS].offset = sizeof(header) + blocks_buf.getlen();
  section_writer::write_block(cur_sections, &sink);

  cur_header->blocks[NB_ENTRIES].offset = sizeof(header) + blocks_buf.getlen();
  entry_writer::write_block(cur_entries, &sink);

  cur_header->blocks[NB_STRINGS].offset = sizeof(header) + blocks_buf.getlen();
  blocks_buf.add(cur_strlist->get(), cur_strlist->getlen());

  cur_header->blocks[NB_LANGTABLES].offset = sizeof(header) + blocks_buf.getlen();
  lang_table_writer::write_block(cur_langtables, &sink, cur_header->langtable_size);

  cur_header->blocks[NB_CTLCOLORS].offset = sizeof(header) + blocks_buf.getlen();
  ctlcolors_writer::write_block(cur_ctlcolors, &sink);

#ifdef NSIS_SUPPORT_BGBG
  if (cur_header->bg_color1 != -1)
  {
    bg_font.lfFaceName[LF_FACESIZE-1] = 0;

    cur_header->blocks[NB_BGFONT].offset = sizeof(header) + blocks_buf.getlen();

    LOGFONT_writer w(&sink);
    w.write(&bg_font);
  }
#endif

  growbuf_writer_sink sink2(hdrbuf);
  header_writer header(&sink2);
  header.write(cur_header);

  sink2.write_growbuf(&blocks_buf);
}

int CEXEBuild::check_write_output_errors() const
{
  if (has_called_write_output)
  {
    ERROR_MSG("Error (write_output): write_output already called, can't continue\n");
    return PS_ERROR;
  }

  if (!build_output_filename[0])
  {
    ERROR_MSG("Error: invalid script: never had OutFile command\n");
    return PS_ERROR;
  }

  if (!build_sections.getlen())
  {
    ERROR_MSG("Error: invalid script: no sections specified\n");
    return PS_ERROR;
  }

  if (!build_entries.getlen())
  {
    ERROR_MSG("Error: invalid script: no entries specified\n");
    return PS_ERROR;
  }

  if (build_cursection)
  {
    ERROR_MSG("Error: Section left open at EOF\n");
    return PS_ERROR;
  }

  if (sectiongroup_open_cnt)
  {
    ERROR_MSG("Error: SectionGroup left open at EOF\n");
    return PS_ERROR;
  }

  if (cur_page)
  {
    ERROR_MSG("Error: PageEx still open at EOF, cannot proceed\n");
    return PS_ERROR;
  }

  // deal with functions, for both install and uninstall modes.
  if (build_cursection_isfunc)
  {
    ERROR_MSG("Error: Function still open at EOF, cannot proceed\n");
    return PS_ERROR;
  }

  return PS_OK;
}

int CEXEBuild::prepare_uninstaller() {
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
  if (ubuild_entries.getlen())
  {
    if (!uninstaller_writes_used)
    {
      warning("Uninstall section found but WriteUninstaller never used - no uninstaller will be created.");
      return PS_OK;
    }

    build_uninst.flags|=build_header.flags&(CH_FLAGS_PROGRESS_COLORED|CH_FLAGS_NO_ROOT_DIR);

    set_uninstall_mode(1);
    DefineInnerLangString(NLF_UCAPTION);
    if (resolve_coderefs("uninstall"))
      return PS_ERROR;
#ifdef NSIS_CONFIG_COMPONENTPAGE
    // set sections to the first insttype
    PrepareInstTypes();
#endif
    set_uninstall_mode(0);
  }
  else if (uninstaller_writes_used)
  {
    ERROR_MSG("Error: no Uninstall section specified, but WriteUninstaller used %d time(s)\n",uninstaller_writes_used);
    return PS_ERROR;
  }
#endif//NSIS_CONFIG_UNINSTALL_SUPPORT
  return PS_OK;
}

int CEXEBuild::pack_exe_header()
{
  if (!(build_packname[0] && build_packcmd[0])) {
    // header not asked to be packed
    return PS_OK;
  }

  // write out exe header, pack, read back in, and
  // update the header info
  FILE *tmpfile=FOPEN(build_packname,"wb");
  if (!tmpfile)
  {
    ERROR_MSG("Error: writing temporary file \"%s\" for pack\n",build_packname);
    return PS_ERROR;
  }
  fwrite(m_exehead,1,m_exehead_size,tmpfile);
  fclose(tmpfile);
  if (sane_system(build_packcmd) == -1)
  {
    remove(build_packname);
    ERROR_MSG("Error: calling packer on \"%s\"\n",build_packname);
    return PS_ERROR;
  }

  int result = update_exehead(build_packname);
  remove(build_packname);

  if (result != PS_OK)
  {
    ERROR_MSG("Error: reading temporary file \"%s\" after pack\n",build_packname);
    return result;
  }

  return PS_OK;
}

int CEXEBuild::write_output(void)
{
#ifndef NSIS_CONFIG_CRC_SUPPORT
  build_crcchk=0;
#endif

  RET_UNLESS_OK( check_write_output_errors() );

  has_called_write_output=true;

#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
  RET_UNLESS_OK( add_plugins_dir_initializer() );
#endif //NSIS_CONFIG_PLUGIN_SUPPORT

#ifdef NSIS_SUPPORT_VERSION_INFO
  RET_UNLESS_OK( AddVersionInfo() );
#endif //NSIS_SUPPORT_VERSION_INFO

  RET_UNLESS_OK( prepare_uninstaller() );

  DefineInnerLangString(NLF_CAPTION);
  if (resolve_coderefs("install"))
    return PS_ERROR;

#ifdef NSIS_CONFIG_COMPONENTPAGE
  // set sections to the first insttype
  PrepareInstTypes();
#endif

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  RET_UNLESS_OK( ProcessPages() );
#endif //NSIS_CONFIG_VISIBLE_SUPPORT

  // Generate language tables
  RET_UNLESS_OK( GenerateLangTables() );

  try {
    init_res_editor();

    VerifyDeclaredUserVarRefs(&m_UserVarNames);
    int MaxUserVars = m_UserVarNames.getnum();
    // -1 because the default size is 1
    if (!res_editor->AddExtraVirtualSize2PESection(NSIS_VARS_SECTION, (MaxUserVars - 1) * sizeof(NSIS_STRING)))
    {
      ERROR_MSG("Internal compiler error #12346: invalid exehead cannot find section \"%s\"!\n", NSIS_VARS_SECTION);
      return PS_ERROR;
    }

    // Save all changes to the exe header
    close_res_editor();
  }
  catch (exception& err) {
    ERROR_MSG("\nError: %s\n", err.what());
    return PS_ERROR;
  }

  RET_UNLESS_OK( pack_exe_header() );


  build_optimize_datablock=0;

  int data_block_size_before_uninst = build_datablock.getlen();

  RET_UNLESS_OK( uninstall_generate() );

  crc32_t crc=0;

  {
    string full_path = get_full_path(build_output_filename);
    notify(MAKENSIS_NOTIFY_OUTPUT, full_path.c_str());
    INFO_MSG("\nOutput: \"%s\"\n", full_path.c_str());
  }

  FILE *fp = FOPEN(build_output_filename,"w+b");
  if (!fp)
  {
    ERROR_MSG("Can't open output file\n");
    return PS_ERROR;
  }

  if (fwrite(m_exehead,1,m_exehead_size,fp) != m_exehead_size)
  {
    ERROR_MSG("Error: can't write %d bytes to output\n",m_exehead_size);
    fclose(fp);
    return PS_ERROR;
  }

#ifdef NSIS_CONFIG_CRC_SUPPORT
  #ifdef NSIS_CONFIG_CRC_ANAL
    crc=CRC32(crc,m_exehead,m_exehead_size);
  #else
    crc=CRC32(crc,m_exehead+512,m_exehead_size-512);
  #endif
#endif

  firstheader fh={0,};
  fh.nsinst[0]=FH_INT1;
  fh.nsinst[1]=FH_INT2;
  fh.nsinst[2]=FH_INT3;

#ifdef NSIS_CONFIG_CRC_SUPPORT
  fh.flags=(build_crcchk?(build_crcchk==2?FH_FLAGS_FORCE_CRC:0):FH_FLAGS_NO_CRC);
#else
  fh.flags=0;
#endif
#ifdef NSIS_CONFIG_SILENT_SUPPORT
  if (build_header.flags&(CH_FLAGS_SILENT|CH_FLAGS_SILENT_LOG)) fh.flags |= FH_FLAGS_SILENT;
#endif
  fh.siginfo=FH_SIG;

  int installinfo_compressed;
  int fd_start = 0;

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
  if (build_compress_whole)
  {
    int n = compressor->Init(build_compress_level, build_compress_dict_size);
    if (n != C_OK)
    {
      ERROR_MSG("Internal compiler error #12345: deflateInit() failed(%s [%d]).\n", compressor->GetErrStr(n), n);
      return PS_ERROR;
    }
  }
#endif

  {
    GrowBuf ihd;
    {
      GrowBuf hdrcomp;

      PrepareHeaders(&hdrcomp);

      if (add_data((char*)hdrcomp.get(),hdrcomp.getlen(),&ihd) < 0)
        return PS_ERROR;

      fh.length_of_header=hdrcomp.getlen();
      installinfo_compressed=ihd.getlen();
    }

    if (!build_compress_whole)
      fh.length_of_all_following_data=ihd.getlen()+build_datablock.getlen()+(int)sizeof(firstheader)+(build_crcchk?sizeof(crc32_t):0);
    else
      fd_start=ftell(fp);

    try
    {
      file_writer_sink sink(fp);
      firstheader_writer w(&sink);
      w.write(&fh);
    }
    catch (...)
    {
      ERROR_MSG("Error: can't write %d bytes to output\n",sizeof(fh));
      fclose(fp);
      return PS_ERROR;
    }

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
    if (build_compress_whole) {
      if (deflateToFile(fp,(char*)ihd.get(),ihd.getlen()))
      {
        fclose(fp);
        return PS_ERROR;
      }
    }
    else
#endif
    {
      if (fwrite(ihd.get(),1,ihd.getlen(),fp) != (unsigned int)ihd.getlen())
      {
        ERROR_MSG("Error: can't write %d bytes to output\n",ihd.getlen());
        fclose(fp);
        return PS_ERROR;
      }
#ifdef NSIS_CONFIG_CRC_SUPPORT
      crc_writer_sink crc_sink((crc32_t *) &crc);
      firstheader_writer w(&crc_sink);
      w.write(&fh);

      crc=CRC32(crc,(unsigned char*)ihd.get(),ihd.getlen());
#endif
    }
  }

  INFO_MSG("Install: ");
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  int np=build_header.blocks[NB_PAGES].num;
  INFO_MSG("%d page%s (%d bytes), ",np,np==1?"":"s",np*sizeof(page));
#endif
  {
    int ns=build_sections.getlen()/sizeof(section);
    section *s=(section*)build_sections.get();
    int x;
    int req=0;
    for (x = 1; x < ns; x ++)
    {
      if (!s[x].name_ptr || s[x].flags & SF_RO) req++;
    }
    INFO_MSG("%d section%s",ns,ns==1?"":"s");
    if (req)
    {
      INFO_MSG(" (%d required)",req);
    }
    INFO_MSG(" (%d bytes), ", build_sections.getlen());
  }
  int ne=build_header.blocks[NB_ENTRIES].num;
  INFO_MSG("%d instruction%s (%d bytes), ",ne,ne==1?"":"s",ne*sizeof(entry));
  int ns=build_strlist.getnum();
  INFO_MSG("%d string%s (%d bytes), ",ns,ns==1?"":"s",build_strlist.getlen());
  int nlt=build_header.blocks[NB_LANGTABLES].num;
  INFO_MSG("%d language table%s (%d bytes).\n",nlt,nlt==1?"":"s",build_langtables.getlen());
  if (ubuild_entries.getlen())
  {
    INFO_MSG("Uninstall: ");
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
    np=build_uninst.blocks[NB_PAGES].num;
    INFO_MSG("%d page%s (%d bytes), \n",np,np==1?"":"s",ubuild_pages.getlen());
#endif
    {
      int ns=ubuild_sections.getlen()/sizeof(section);
      section *s=(section*)ubuild_sections.get();
      int x;
      int req=0;
      for (x = 1; x < ns; x ++)
      {
        if (!s[x].name_ptr || s[x].flags & SF_RO) req++;
      }
      INFO_MSG("%d section%s",ns,ns==1?"":"s");
      if (req)
      {
        INFO_MSG(" (%d required)",req);
      }
      INFO_MSG(" (%d bytes), ", ubuild_sections.getlen());
    }
    ne=build_uninst.blocks[NB_ENTRIES].num;
    INFO_MSG("%d instruction%s (%d bytes), ",ne,ne==1?"":"s",ubuild_entries.getlen());
    ns=ubuild_strlist.getnum();
    INFO_MSG("%d string%s (%d bytes), ",ns,ns==1?"":"s",ubuild_strlist.getlen());
    nlt=build_uninst.blocks[NB_LANGTABLES].num;
    INFO_MSG("%d language table%s (%d bytes).\n",nlt,nlt==1?"":"s",ubuild_langtables.getlen());
  }


  if (db_opt_save)
  {
    int total_out_size_estimate=
      m_exehead_size+sizeof(fh)+build_datablock.getlen()+(build_crcchk?sizeof(crc32_t):0);
#ifdef _WIN32
    int pc=MulDiv(db_opt_save,1000,db_opt_save+total_out_size_estimate);
#else
    int pc=(int)(((long long)db_opt_save*1000)/(db_opt_save+total_out_size_estimate));
#endif
    INFO_MSG("Datablock optimizer saved %d bytes (~%d.%d%%).\n",db_opt_save,
      pc/10,pc%10);
  }

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
  INFO_MSG("\nUsing %s%s compression.\n\n", compressor->GetName(), build_compress_whole?" (compress whole)":"");
#endif

  unsigned int total_usize=m_exehead_original_size;

  INFO_MSG("EXE header size:          %10d / %d bytes\n",m_exehead_size,m_exehead_original_size);

  if (build_compress_whole) {
    INFO_MSG("Install code:                          (%d bytes)\n",
      sizeof(fh)+fh.length_of_header);
  }
  else {
    INFO_MSG("Install code:             %10d / %d bytes\n",
      sizeof(fh)+installinfo_compressed,
      sizeof(fh)+fh.length_of_header);
  }

  total_usize+=sizeof(fh)+fh.length_of_header;

  {
    int dbsize, dbsizeu;
    dbsize = build_datablock.getlen();
    if (uninstall_size>0) dbsize-=uninstall_size;

    if (build_compress_whole) {
      dbsizeu=dbsize;
      INFO_MSG("Install data:                          (%d bytes)\n",dbsizeu);
    }
    else {
      dbsizeu = db_full_size - uninstall_size_full;
      INFO_MSG("Install data:             %10d / %d bytes\n",dbsize,dbsizeu);
    }
    total_usize+=dbsizeu;
  }

  if (uninstall_size>=0)
  {
    if (build_compress_whole)
      INFO_MSG("Uninstall code+data:                   (%d bytes)\n",uninstall_size_full);
    else
      INFO_MSG("Uninstall code+data:          %6d / %d bytes\n",uninstall_size,uninstall_size_full);
    total_usize+=uninstall_size_full;
  }

  if (build_compress_whole) {
    INFO_MSG("Compressed data:          ");
  }

  if (build_datablock.getlen())
  {
    build_datablock.setro(TRUE);
    int dbl = build_datablock.getlen();
    int left = dbl;
    while (left > 0)
    {
      int l = min(build_filebuflen, left);
      char *dbptr = (char *) build_datablock.get(dbl - left, l);
#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
      if (build_compress_whole)
      {
        if (deflateToFile(fp,dbptr,l))
        {
          fclose(fp);
          return PS_ERROR;
        }
      }
      else
#endif
      {
#ifdef NSIS_CONFIG_CRC_SUPPORT
        crc=CRC32(crc,(unsigned char *)dbptr,l);
#endif
        if ((int)fwrite(dbptr,1,l,fp) != l)
        {
          ERROR_MSG("Error: can't write %d bytes to output\n",l);
          fclose(fp);
          return PS_ERROR;
        }
        fflush(fp);
      }
      build_datablock.release();
      left -= l;
    }
    build_datablock.setro(FALSE);
    build_datablock.clear();
  }
#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
  if (build_compress_whole)
  {
    if (deflateToFile(fp,NULL,0))
    {
      fclose(fp);
      return PS_ERROR;
    }
    compressor->End();

    unsigned fend = ftell(fp);

    fh.length_of_all_following_data=ftell(fp)-fd_start+(build_crcchk?sizeof(crc32_t):0);
    INFO_MSG(
      "%10d / %d bytes\n",
      ftell(fp) - fd_start,
      data_block_size_before_uninst + fh.length_of_header + sizeof(firstheader) + uninstall_size_full
    );

    fseek(fp,fd_start,SEEK_SET);

    try
    {
      file_writer_sink sink(fp);
      firstheader_writer w(&sink);
      w.write(&fh);
    }
    catch (...)
    {
      ERROR_MSG("Error: can't write %d bytes to output\n",sizeof(fh));
      fclose(fp);
      return PS_ERROR;
    }

#ifdef NSIS_CONFIG_CRC_SUPPORT
    if (build_crcchk)
    {
      // check rest of CRC
      fseek(fp,fd_start,SEEK_SET);
      for (;;)
      {
        char buf[32768];
        int l=fread(buf,1,sizeof(buf),fp);
        if (!l) break;
        crc=CRC32(crc,(unsigned char *)buf,l);
      }
    }
#endif
    fseek(fp,fend,SEEK_SET); // reset eof flag
  }
#endif

  if (build_crcchk)
  {
    total_usize+=sizeof(int);
    int rcrc = FIX_ENDIAN_INT32(crc);
    if (fwrite(&rcrc,1,sizeof(crc32_t),fp) != sizeof(crc32_t))
    {
      ERROR_MSG("Error: can't write %d bytes to output\n",sizeof(crc32_t));
      fclose(fp);
      return PS_ERROR;
    }
    INFO_MSG("CRC (0x%08X):                  4 / 4 bytes\n",crc);
  }
  INFO_MSG("\n");
  {
    UINT pc=(UINT)(((UINT64)ftell(fp)*1000)/(total_usize));
    INFO_MSG("Total size:               %10u / %u bytes (%u.%u%%)\n",
      ftell(fp),total_usize,pc/10,pc%10);
  }
  fclose(fp);
  print_warnings();
  return PS_OK;
}

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
int CEXEBuild::deflateToFile(FILE *fp, char *buf, int len) // len==0 to flush
{
  build_compressor_set=true;

  char obuf[65536];
  bool flush=false;
  compressor->SetNextIn(buf,len);
  if (!buf||!len)
  {
    char a;
    compressor->SetNextIn(&a,0);
    flush=C_FINISH;
  }
  for (;;)
  {
    compressor->SetNextOut(obuf,sizeof(obuf));
    int ret=compressor->Compress(flush);
    if (ret<0 && (ret!=-1 || !flush))
    {
      ERROR_MSG("Error: deflateToFile: deflate() failed(%s [%d])\n", compressor->GetErrStr(ret), ret);
      return 1;
    }
    int l=compressor->GetNextOut()-obuf;
    if (l)
    {
      if (fwrite(obuf,1,l,fp) != (unsigned)l)
      {
        ERROR_MSG("Error: deflateToFile fwrite(%d) failed\n",l);
        return 1;
      }
      fflush(fp);
    }
    if (!compressor->GetAvailIn() && (!flush || !l)) break;
  }
  return 0;
}
#endif

int CEXEBuild::uninstall_generate()
{
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
  if (ubuild_entries.getlen() && uninstaller_writes_used)
  {
    SCRIPT_MSG("Generating uninstaller... ");

    firstheader fh={0,};

    GrowBuf uhd;
    {
      GrowBuf udata;

      set_uninstall_mode(1);

      PrepareHeaders(&udata);

      fh.length_of_header=udata.getlen();
      int err=add_data((char*)udata.get(),udata.getlen(),&uhd);
      set_uninstall_mode(0);
      if (err < 0) return PS_ERROR;
    }

    crc32_t crc=0;

    // Get offsets of icons to replace for uninstall
    // Also makes sure that the icons are there and in the right size.
    if (generate_unicons_offsets(m_exehead, m_exehead_size, m_unicon_data) == 0)
      return PS_ERROR;

    entry *ent = (entry *) build_entries.get();
    if (!ent)
      return PS_ERROR;
    int ents = build_header.blocks[NB_ENTRIES].num;
    int uns = uninstaller_writes_used;
    int uninstdata_offset = build_datablock.getlen();
    while (ents--)
    {
      if (ent->which == EW_WRITEUNINSTALLER)
      {
        ent->offsets[1] = uninstdata_offset;
        ent->offsets[2] = m_unicon_size;
        uns--;
        if (!uns)
          break;
      }
      ent++;
    }

    if (add_db_data((char *)m_unicon_data,m_unicon_size) < 0)
      return PS_ERROR;

#ifdef NSIS_CONFIG_CRC_SUPPORT
    {
      // "create" the uninstaller
      LPBYTE uninst_header = (LPBYTE) malloc(m_exehead_size);
      if (!uninst_header)
        return PS_ERROR;

      memcpy(uninst_header, m_exehead, m_exehead_size);

      // patch the icons
      LPBYTE seeker = m_unicon_data;
      while (*seeker) {
        DWORD dwSize = FIX_ENDIAN_INT32(*(LPDWORD) seeker);
        seeker += sizeof(DWORD);
        DWORD dwOffset = FIX_ENDIAN_INT32(*(LPDWORD) seeker);
        seeker += sizeof(DWORD);
        memcpy(uninst_header + dwOffset, seeker, dwSize);
        seeker += dwSize;
      }

#ifdef NSIS_CONFIG_CRC_ANAL
      crc=CRC32(crc, uninst_header, m_exehead_size);
#else
      crc=CRC32(crc, uninst_header + 512, m_exehead_size - 512);
#endif

      free(uninst_header);
    }
#endif
    fh.nsinst[0]=FH_INT1;
    fh.nsinst[1]=FH_INT2;
    fh.nsinst[2]=FH_INT3;
    fh.flags=FH_FLAGS_UNINSTALL;
#ifdef NSIS_CONFIG_CRC_SUPPORT
    fh.flags|=(build_crcchk?(build_crcchk==2?FH_FLAGS_FORCE_CRC:0):FH_FLAGS_NO_CRC);
#endif
#ifdef NSIS_CONFIG_SILENT_SUPPORT
    if (build_uninst.flags&(CH_FLAGS_SILENT|CH_FLAGS_SILENT_LOG)) fh.flags |= FH_FLAGS_SILENT;
#endif
    fh.siginfo=FH_SIG;
    fh.length_of_all_following_data=
      uhd.getlen()+ubuild_datablock.getlen()+(int)sizeof(firstheader)+(build_crcchk?sizeof(crc32_t):0);

    MMapBuf udata;

    {
      growbuf_writer_sink sink(&udata);
      firstheader_writer w(&sink);
      w.write(&fh);
    }

    ubuild_datablock.setro(TRUE);

#ifdef NSIS_CONFIG_COMPRESSION_SUPPORT
    if (build_compress_whole) {
      // compress uninstaller too
      {
        char obuf[65536];
        int n = compressor->Init(build_compress_level, build_compress_dict_size);
        if (n != C_OK)
        {
          ERROR_MSG("Internal compiler error #12345: deflateInit() failed(%s [%d]).\n", compressor->GetErrStr(n), n);
          extern void quit(); quit();
        }

        compressor->SetNextIn((char*)uhd.get(), uhd.getlen());
        while (compressor->GetAvailIn())
        {
          compressor->SetNextOut(obuf, sizeof(obuf));
          compressor->Compress(0);
          if (compressor->GetNextOut() - obuf > 0)
          {
            udata.add(obuf, compressor->GetNextOut() - obuf);
          }
        }

        int avail_in = ubuild_datablock.getlen();
        int in_pos = 0;
        while (avail_in > 0) {
          int l = min(avail_in, build_filebuflen);

          char *p = (char*)ubuild_datablock.get(in_pos, l);
          compressor->SetNextIn(p, l);

          while (compressor->GetAvailIn())
          {
            compressor->SetNextOut(obuf, sizeof(obuf));
            compressor->Compress(0);
            if (compressor->GetNextOut() - obuf > 0)
              udata.add(obuf, compressor->GetNextOut() - obuf);
          }

          ubuild_datablock.release();

          avail_in -= l;
          in_pos += l;
        }

        for (;;)
        {
          compressor->SetNextOut(obuf, sizeof(obuf));
          compressor->Compress(C_FINISH);
          if (compressor->GetNextOut() - obuf > 0)
            udata.add(obuf, compressor->GetNextOut() - obuf);
          else break;
        }
        compressor->End();
      }

      firstheader *_fh=(firstheader *)udata.get(0, sizeof(firstheader));
      _fh->length_of_all_following_data=FIX_ENDIAN_INT32(udata.getlen()+(build_crcchk?sizeof(crc32_t):0));
      udata.release();
    }
    else
#endif//NSIS_CONFIG_COMPRESSION_SUPPORT
    {
      udata.add(uhd.get(), uhd.getlen());

      int st = udata.getlen();
      int length = ubuild_datablock.getlen();
      int left = length;
      udata.resize(st + left);
      while (left > 0)
      {
        int l = min(build_filebuflen, left);
        void *p = ubuild_datablock.get(length - left, l);
        memcpy(udata.get(st + length - left, l), p, l);
        udata.flush(l);
        udata.release();
        ubuild_datablock.release();
        left -= l;
      }
    }

    ubuild_datablock.clear();

    udata.setro(TRUE);

#ifdef NSIS_CONFIG_CRC_SUPPORT
    if (build_crcchk)
    {
      int pos = 0;
      int left = udata.getlen();
      while (left > 0)
      {
        int l = min(build_filebuflen, left);
        crc = CRC32(crc, (unsigned char *) udata.get(pos, l), l);
        udata.release();
        pos += l;
        left -= l;
      }
      udata.setro(FALSE);
      FIX_ENDIAN_INT32_INPLACE(crc);
      udata.add(&crc, sizeof(crc));
      udata.setro(TRUE);
    }
#endif

    if (add_db_data(&udata) < 0)
      return PS_ERROR;

    udata.clear();

    //uninstall_size_full=fh.length_of_all_following_data + sizeof(int) + unicondata_size - 32 + sizeof(int);
    uninstall_size_full=fh.length_of_all_following_data+m_unicon_size;

    // compressed size
    uninstall_size=build_datablock.getlen()-uninstdata_offset;

    SCRIPT_MSG("Done!\n");
  }
#endif
  return PS_OK;
}

#define SWAP(x,y,i) { i _ii; _ii=x; x=y; y=_ii; }

void CEXEBuild::set_uninstall_mode(int un)
{
  if (un != uninstall_mode)
  {
    uninstall_mode=un;
    if (un)
    {
      cur_datablock=&ubuild_datablock;
      cur_datablock_cache=&ubuild_datablock_cache;
      cur_entries=&ubuild_entries;
      cur_instruction_entry_map=&ubuild_instruction_entry_map;
      cur_functions=&ubuild_functions;
      cur_labels=&ubuild_labels;
      cur_pages=&ubuild_pages;
      cur_sections=&ubuild_sections;
      cur_header=&build_uninst;
      cur_strlist=&ubuild_strlist;
      cur_langtables=&ubuild_langtables;
      cur_ctlcolors=&ubuild_ctlcolors;
    }
    else
    {
      cur_datablock=&build_datablock;
      cur_datablock_cache=&build_datablock_cache;
      cur_entries=&build_entries;
      cur_instruction_entry_map=&build_instruction_entry_map;
      cur_functions=&build_functions;
      cur_labels=&build_labels;
      cur_pages=&build_pages;
      cur_sections=&build_sections;
      cur_header=&build_header;
      cur_strlist=&build_strlist;
      cur_langtables=&build_langtables;
      cur_ctlcolors=&build_ctlcolors;
    }

    SWAP(db_opt_save_u,db_opt_save,int);
    SWAP(db_comp_save_u,db_comp_save,int);
    SWAP(db_full_size_u,db_full_size,int);
  }
}

extern FILE *g_output;

void CEXEBuild::warning(const char *s, ...)
{
  char buf[NSIS_MAX_STRLEN*10];
  va_list val;
  va_start(val,s);
#ifdef _WIN32
  vsprintf(buf,s,val);
#else
  vsnprintf(buf,NSIS_MAX_STRLEN*10,s,val);
#endif
  va_end(val);
  m_warnings.add(buf,0);
  notify(MAKENSIS_NOTIFY_WARNING,buf);
  if (display_warnings)
  {
    fprintf(g_output,"warning: %s\n",buf);
    fflush(g_output);
  }
}

void CEXEBuild::warning_fl(const char *s, ...)
{
  char buf[NSIS_MAX_STRLEN*10];
  va_list val;
  va_start(val,s);
#ifdef _WIN32
  vsprintf(buf,s,val);
#else
  vsnprintf(buf,NSIS_MAX_STRLEN*10,s,val);
#endif
  va_end(val);
  sprintf(buf+strlen(buf)," (%s:%d)",curfilename,linecnt);
  m_warnings.add(buf,0);
  notify(MAKENSIS_NOTIFY_WARNING,buf);
  if (display_warnings)
  {
    fprintf(g_output,"warning: %s\n",buf);
    fflush(g_output);
  }
}

void CEXEBuild::ERROR_MSG(const char *s, ...) const
{
#ifdef _WIN32
  if (display_errors || notify_hwnd)
#else
  if (display_errors)
#endif
  {
    char buf[NSIS_MAX_STRLEN*10];
    va_list val;
    va_start(val,s);
#ifdef _WIN32
    vsprintf(buf,s,val);
#else
    vsnprintf(buf,NSIS_MAX_STRLEN*10,s,val);
#endif
    va_end(val);
    notify(MAKENSIS_NOTIFY_ERROR,buf);
    if (display_errors)
    {
      fprintf(g_output,"%s",buf);
      fflush(g_output);
    }
  }
}

void CEXEBuild::SCRIPT_MSG(const char *s, ...) const
{
  if (display_script)
  {
    va_list val;
    va_start(val,s);
    vfprintf(g_output,s,val);
    va_end(val);
    fflush(g_output);
  }
}

void CEXEBuild::INFO_MSG(const char *s, ...) const
{
  if (display_info)
  {
    va_list val;
    va_start(val,s);
    vfprintf(g_output,s,val);
    va_end(val);
    fflush(g_output);
  }
}

void CEXEBuild::print_warnings()
{
  int nw=0,x=m_warnings.getlen();
  if (!x || !display_warnings) return;
  char *p=m_warnings.get();
  while (x>0) if (!p[--x]) nw++;
  fprintf(g_output,"\n%d warning%s:\n",nw,nw==1?"":"s");
  for (x = 0; x < nw; x ++)
  {
    fprintf(g_output,"  %s\n",p);
    p+=strlen(p)+1;
  }
  fflush(g_output);
}

#ifdef _WIN32
void CEXEBuild::notify(notify_e code, const char *data) const
{
  if (notify_hwnd)
  {
    COPYDATASTRUCT cds = {(DWORD)code, strlen(data)+1, (void *) data};
    SendMessage(notify_hwnd, WM_COPYDATA, 0, (LPARAM)&cds);
  }
}
#endif

// Added by Ximon Eighteen 5th August 2002
#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
void CEXEBuild::build_plugin_table(void)
{
  if (plugins_processed)
    return;
  plugins_processed=1;

  plugin_used = false;
  uninst_plugin_used = false;
  string searchPath = definedlist.find("NSISDIR");
  searchPath += PLATFORM_PATH_SEPARATOR_STR"Plugins";
  INFO_MSG("Processing plugin dlls: \"%s" PLATFORM_PATH_SEPARATOR_STR "*.dll\"\n",searchPath.c_str());
  m_plugins.FindCommands(searchPath, display_info?true:false);
  INFO_MSG("\n");
}

#define FLAG_OFFSET(flag) (FIELD_OFFSET(exec_flags, flag)/sizeof(int))

int CEXEBuild::add_plugins_dir_initializer(void)
{
  if (!plugin_used && !uninst_plugin_used) return PS_OK;

  SCRIPT_MSG("Adding plug-ins initializing function... ");

  bool uninstall = !plugin_used;

  int ret;
  int zero_offset;

  int var_zero;
  var_zero=m_UserVarNames.get("0");

again:
  // Function [un.]Initialize_____Plugins
  ret=add_function(uninstall?"un.Initialize_____Plugins":"Initialize_____Plugins");
  if (ret != PS_OK) return ret;

  // don't move this, depends on [un.]
  zero_offset=add_string("$0");

  // SetDetailsPrint none
  ret=add_entry_direct(EW_UPDATETEXT, 0, 16);
  if (ret != PS_OK) return ret;

  // StrCmp $PLUGINSDIR ""
  ret=add_entry_direct(EW_STRCMP, add_string("$PLUGINSDIR"), 0, 0, ns_label.add("Initialize_____Plugins_done",0));
  if (ret != PS_OK) return ret;
  // Push $0
  ret=add_entry_direct(EW_PUSHPOP, zero_offset);
  if (ret != PS_OK) return ret;
  // ClearErrors
  ret=add_entry_direct(EW_SETFLAG, FLAG_OFFSET(exec_error));
  if (ret != PS_OK) return ret;
  // GetTempFileName $0
  ret=add_entry_direct(EW_GETTEMPFILENAME, var_zero, add_string("$TEMP"));
  if (ret != PS_OK) return ret;
  // Delete $0 [simple, nothing that could clash with special temp permissions]
  ret=add_entry_direct(EW_DELETEFILE, zero_offset, DEL_SIMPLE);
  if (ret != PS_OK) return ret;
  // CraeteDirectory $0 - a dir instead of that temp file
  ret=add_entry_direct(EW_CREATEDIR, zero_offset);
  if (ret != PS_OK) return ret;
  // IfErrors Initialize_____Plugins_error - detect errors
  ret=add_entry_direct(EW_IFFLAG, ns_label.add("Initialize_____Plugins_error",0), 0, FLAG_OFFSET(exec_error));
  if (ret != PS_OK) return ret;
  // Copy $0 to $PLUGINSDIR
  ret=add_entry_direct(EW_ASSIGNVAR, m_UserVarNames.get("PLUGINSDIR"), zero_offset);
  if (ret != PS_OK) return ret;
  // Pop $0
  ret=add_entry_direct(EW_PUSHPOP, var_zero, 1);
  if (ret != PS_OK) return ret;

  // done
  if (add_label("Initialize_____Plugins_done")) return PS_ERROR;
  // Return
  ret=add_entry_direct(EW_RET);
  if (ret != PS_OK) return ret;

  // error
  if (add_label("Initialize_____Plugins_error")) return PS_ERROR;
  // error message box
  ret=add_entry_direct(EW_MESSAGEBOX, MB_OK|MB_ICONSTOP|(IDOK<<21), add_string("Error! Can't initialize plug-ins directory. Please try again later."));
  if (ret != PS_OK) return ret;
  // Quit
  ret=add_entry_direct(EW_QUIT);
  if (ret != PS_OK) return ret;

  // FunctionEnd
  ret=function_end();
  if (ret != PS_OK) return ret;

  if (uninst_plugin_used && !uninstall) {
    uninstall = true;
    goto again;
  }

  SCRIPT_MSG("Done!\n");

  return PS_OK;
}
#endif // NSIS_CONFIG_PLUGIN_SUPPORT

void CEXEBuild::init_res_editor()
{
  build_compressor_set = true;
  if (!res_editor)
    res_editor = new CResourceEditor(m_exehead, m_exehead_size);
}

void CEXEBuild::close_res_editor()
{
  if (!res_editor) return;
  DWORD newsize;

  // get size
  newsize = res_editor->Save(NULL, newsize);
  unsigned char *new_header = new unsigned char[newsize];

  // save
  int rc = res_editor->Save(new_header, newsize);
  assert(rc == 0);

  update_exehead(new_header, newsize);

  // TODO: resource-controlling class
  delete [] new_header;

  delete res_editor;
  res_editor=0;
}

int CEXEBuild::DeclaredUserVar(const char *szVarName)
{
  if (m_ShellConstants.get((char*)szVarName) >= 0)
  {
    ERROR_MSG("Error: name \"%s\" in use by constant\n", szVarName);
    return PS_ERROR;
  }

  int idxUserVar = m_UserVarNames.get((char*)szVarName);
  if (idxUserVar >= 0)
  {
    ERROR_MSG("Error: variable \"%s\" already declared\n", szVarName);
    return PS_ERROR;
  }
  const char *pVarName = szVarName;
  int iVarLen = strlen(szVarName);

  if (iVarLen > 60)
  {
    ERROR_MSG("Error: variable name too long!\n");
    return PS_ERROR;
  }
  else if (!iVarLen)
  {
    ERROR_MSG("Error: variable with empty name!\n");
    return PS_ERROR;
  }
  else
  {
    while (*pVarName)
    {
      if (!isSimpleChar(*pVarName))
      {
        ERROR_MSG("Error: invalid characters in variable name \"%s\", use only characters [a-z][A-Z][0-9] and '_'\n", szVarName);
        return PS_ERROR;
      }
      pVarName++;
    }
  }

  m_UserVarNames.add(szVarName);
  if (m_UserVarNames.getnum() > MAX_CODED)
  {
    ERROR_MSG("Error: too many user variables declared. Maximum allowed is %u.\n", MAX_CODED - m_iBaseVarsNum);
    return PS_ERROR;
  }
  return PS_OK;
}


int CEXEBuild::GetUserVarIndex(LineParser &line, int token)
{
  char *p = line.gettoken_str(token);
  if ( *p == '$' && *(p+1) )
  {
    int idxUserVar = m_UserVarNames.get((char *)p+1);
    if (idxUserVar >= 0 && m_UserVarNames.get_reference(idxUserVar) >= 0)
    {
      m_UserVarNames.inc_reference(idxUserVar);
      return idxUserVar;
    }
    else
    {
      int idxConst = m_ShellConstants.get((char *)p+1);
      if (idxConst >= 0)
      {
        ERROR_MSG("Error: cannot change constants : %s\n", p);
      }
    }
  }
  return -1;
}

void CEXEBuild::VerifyDeclaredUserVarRefs(UserVarsStringList *pVarsStringList)
{
  for (int i = m_iBaseVarsNum; i < pVarsStringList->getnum(); i++)
  {
    if (!pVarsStringList->get_reference(i))
    {
      warning("Variable \"%s\" not referenced, wasting memory!", pVarsStringList->idx2name(i));
    }
  }
}

int CEXEBuild::set_compressor(const string& compressor, const bool solid) {
  string stub = stubs_dir + PLATFORM_PATH_SEPARATOR_STR + compressor;
  if (solid)
    stub += "_solid";

  return update_exehead(stub, &m_exehead_original_size);
}

int CEXEBuild::update_exehead(const string& file, size_t *size/*=NULL*/) {
  FILE *tmpfile = fopen(file.c_str(), "rb");
  if (!tmpfile)
  {
    ERROR_MSG("Error: opening stub \"%s\"\n", file.c_str());
    return PS_ERROR;
  }

  fseek(tmpfile, 0, SEEK_END);
  size_t exehead_size = ftell(tmpfile);

  unsigned char *exehead = new unsigned char[exehead_size];
  fseek(tmpfile, 0, SEEK_SET);
  if (fread(exehead, 1, exehead_size, tmpfile) != exehead_size)
  {
    ERROR_MSG("Error: reading stub \"%s\"\n", file.c_str());
    fclose(tmpfile);
    delete [] exehead;
    return PS_ERROR;
  }
  fclose(tmpfile);

  update_exehead(exehead, exehead_size);

  if (size)
    *size = exehead_size;

  delete [] exehead;

  return PS_OK;
}

void CEXEBuild::update_exehead(const unsigned char *new_exehead, size_t new_size) {
  assert(m_exehead != new_exehead);

  // align exehead to 512
  m_exehead_size = align_to_512(new_size);

  delete [] m_exehead;
  m_exehead = new unsigned char[m_exehead_size];

  // copy exehead
  memcpy(m_exehead, new_exehead, new_size);

  // zero rest of exehead
  memset(m_exehead + new_size, 0, m_exehead_size - new_size);
}