summaryrefslogtreecommitdiffstats
path: root/contrib/bmake/var.c
blob: 43429e28dc3db17b4360305fd618c92a071c574a (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
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
/*	$NetBSD: var.c,v 1.200 2015/12/01 07:26:08 sjg Exp $	*/

/*
 * Copyright (c) 1988, 1989, 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Adam de Boor.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Copyright (c) 1989 by Berkeley Softworks
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Adam de Boor.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef MAKE_NATIVE
static char rcsid[] = "$NetBSD: var.c,v 1.200 2015/12/01 07:26:08 sjg Exp $";
#else
#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 3/19/94";
#else
__RCSID("$NetBSD: var.c,v 1.200 2015/12/01 07:26:08 sjg Exp $");
#endif
#endif /* not lint */
#endif

/*-
 * var.c --
 *	Variable-handling functions
 *
 * Interface:
 *	Var_Set		    Set the value of a variable in the given
 *			    context. The variable is created if it doesn't
 *			    yet exist. The value and variable name need not
 *			    be preserved.
 *
 *	Var_Append	    Append more characters to an existing variable
 *			    in the given context. The variable needn't
 *			    exist already -- it will be created if it doesn't.
 *			    A space is placed between the old value and the
 *			    new one.
 *
 *	Var_Exists	    See if a variable exists.
 *
 *	Var_Value 	    Return the value of a variable in a context or
 *			    NULL if the variable is undefined.
 *
 *	Var_Subst 	    Substitute named variable, or all variables if
 *			    NULL in a string using
 *			    the given context as the top-most one. If the
 *			    third argument is non-zero, Parse_Error is
 *			    called if any variables are undefined.
 *
 *	Var_Parse 	    Parse a variable expansion from a string and
 *			    return the result and the number of characters
 *			    consumed.
 *
 *	Var_Delete	    Delete a variable in a context.
 *
 *	Var_Init  	    Initialize this module.
 *
 * Debugging:
 *	Var_Dump  	    Print out all variables defined in the given
 *			    context.
 *
 * XXX: There's a lot of duplication in these functions.
 */

#include    <sys/stat.h>
#ifndef NO_REGEX
#include    <sys/types.h>
#include    <regex.h>
#endif
#include    <ctype.h>
#include    <stdlib.h>
#include    <limits.h>
#include    <time.h>

#include    "make.h"
#include    "buf.h"
#include    "dir.h"
#include    "job.h"
#include    "metachar.h"

extern int makelevel;
/*
 * This lets us tell if we have replaced the original environ
 * (which we cannot free).
 */
char **savedEnv = NULL;

/*
 * This is a harmless return value for Var_Parse that can be used by Var_Subst
 * to determine if there was an error in parsing -- easier than returning
 * a flag, as things outside this module don't give a hoot.
 */
char 	var_Error[] = "";

/*
 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
 * set false. Why not just use a constant? Well, gcc likes to condense
 * identical string instances...
 */
static char	varNoError[] = "";

/*
 * Internally, variables are contained in four different contexts.
 *	1) the environment. They may not be changed. If an environment
 *	    variable is appended-to, the result is placed in the global
 *	    context.
 *	2) the global context. Variables set in the Makefile are located in
 *	    the global context. It is the penultimate context searched when
 *	    substituting.
 *	3) the command-line context. All variables set on the command line
 *	   are placed in this context. They are UNALTERABLE once placed here.
 *	4) the local context. Each target has associated with it a context
 *	   list. On this list are located the structures describing such
 *	   local variables as $(@) and $(*)
 * The four contexts are searched in the reverse order from which they are
 * listed.
 */
GNode          *VAR_INTERNAL; /* variables from make itself */
GNode          *VAR_GLOBAL;   /* variables from the makefile */
GNode          *VAR_CMD;      /* variables defined on the command-line */

#define FIND_CMD	0x1   /* look in VAR_CMD when searching */
#define FIND_GLOBAL	0x2   /* look in VAR_GLOBAL as well */
#define FIND_ENV  	0x4   /* look in the environment also */

typedef struct Var {
    char          *name;	/* the variable's name */
    Buffer	  val;		/* its value */
    int		  flags;    	/* miscellaneous status flags */
#define VAR_IN_USE	1   	    /* Variable's value currently being used.
				     * Used to avoid recursion */
#define VAR_FROM_ENV	2   	    /* Variable comes from the environment */
#define VAR_JUNK  	4   	    /* Variable is a junk variable that
				     * should be destroyed when done with
				     * it. Used by Var_Parse for undefined,
				     * modified variables */
#define VAR_KEEP	8	    /* Variable is VAR_JUNK, but we found
				     * a use for it in some modifier and
				     * the value is therefore valid */
#define VAR_EXPORTED	16 	    /* Variable is exported */
#define VAR_REEXPORT	32	    /* Indicate if var needs re-export.
				     * This would be true if it contains $'s
				     */
#define VAR_FROM_CMD	64 	    /* Variable came from command line */
}  Var;

/*
 * Exporting vars is expensive so skip it if we can
 */
#define VAR_EXPORTED_NONE	0
#define VAR_EXPORTED_YES	1
#define VAR_EXPORTED_ALL	2
static int var_exportedVars = VAR_EXPORTED_NONE;
/*
 * We pass this to Var_Export when doing the initial export
 * or after updating an exported var.
 */
#define VAR_EXPORT_PARENT 1

/* Var*Pattern flags */
#define VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
#define VAR_SUB_ONE	0x02	/* Apply substitution to one word */
#define VAR_SUB_MATCHED	0x04	/* There was a match */
#define VAR_MATCH_START	0x08	/* Match at start of word */
#define VAR_MATCH_END	0x10	/* Match at end of word */
#define VAR_NOSUBST	0x20	/* don't expand vars in VarGetPattern */

/* Var_Set flags */
#define VAR_NO_EXPORT	0x01	/* do not export */

typedef struct {
    /*
     * The following fields are set by Var_Parse() when it
     * encounters modifiers that need to keep state for use by
     * subsequent modifiers within the same variable expansion.
     */
    Byte	varSpace;	/* Word separator in expansions */
    Boolean	oneBigWord;	/* TRUE if we will treat the variable as a
				 * single big word, even if it contains
				 * embedded spaces (as opposed to the
				 * usual behaviour of treating it as
				 * several space-separated words). */
} Var_Parse_State;

/* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
 * to VarSYSVMatch() for ":lhs=rhs". */
typedef struct {
    const char   *lhs;	    /* String to match */
    int		  leftLen; /* Length of string */
    const char   *rhs;	    /* Replacement string (w/ &'s removed) */
    int		  rightLen; /* Length of replacement */
    int		  flags;
} VarPattern;

/* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
typedef struct {
    GNode	*ctxt;		/* variable context */
    char	*tvar;		/* name of temp var */
    int		tvarLen;
    char	*str;		/* string to expand */
    int		strLen;
    int		errnum;		/* errnum for not defined */
} VarLoop_t;

#ifndef NO_REGEX
/* struct passed as 'void *' to VarRESubstitute() for ":C///" */
typedef struct {
    regex_t	   re;
    int		   nsub;
    regmatch_t 	  *matches;
    char 	  *replace;
    int		   flags;
} VarREPattern;
#endif

/* struct passed to VarSelectWords() for ":[start..end]" */
typedef struct {
    int		start;		/* first word to select */
    int		end;		/* last word to select */
} VarSelectWords_t;

static Var *VarFind(const char *, GNode *, int);
static void VarAdd(const char *, const char *, GNode *);
static Boolean VarHead(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
static Boolean VarTail(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
static Boolean VarSuffix(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
static Boolean VarRoot(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
static Boolean VarMatch(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
#ifdef SYSVVARSUB
static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
#endif
static Boolean VarNoMatch(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
#ifndef NO_REGEX
static void VarREError(int, regex_t *, const char *);
static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
#endif
static Boolean VarSubstitute(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
			char *, Boolean, Buffer *, void *);
static char *VarGetPattern(GNode *, Var_Parse_State *,
			   int, const char **, int, int *, int *,
			   VarPattern *);
static char *VarQuote(char *);
static char *VarHash(char *);
static char *VarModify(GNode *, Var_Parse_State *,
    const char *,
    Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
    void *);
static char *VarOrder(const char *, const char);
static char *VarUniq(const char *);
static int VarWordCompare(const void *, const void *);
static void VarPrintVar(void *);

#define BROPEN	'{'
#define BRCLOSE	'}'
#define PROPEN	'('
#define PRCLOSE	')'

/*-
 *-----------------------------------------------------------------------
 * VarFind --
 *	Find the given variable in the given context and any other contexts
 *	indicated.
 *
 * Input:
 *	name		name to find
 *	ctxt		context in which to find it
 *	flags		FIND_GLOBAL set means to look in the
 *			VAR_GLOBAL context as well. FIND_CMD set means
 *			to look in the VAR_CMD context also. FIND_ENV
 *			set means to look in the environment
 *
 * Results:
 *	A pointer to the structure describing the desired variable or
 *	NULL if the variable does not exist.
 *
 * Side Effects:
 *	None
 *-----------------------------------------------------------------------
 */
static Var *
VarFind(const char *name, GNode *ctxt, int flags)
{
    Hash_Entry         	*var;
    Var			*v;

	/*
	 * If the variable name begins with a '.', it could very well be one of
	 * the local ones.  We check the name against all the local variables
	 * and substitute the short version in for 'name' if it matches one of
	 * them.
	 */
	if (*name == '.' && isupper((unsigned char) name[1]))
		switch (name[1]) {
		case 'A':
			if (!strcmp(name, ".ALLSRC"))
				name = ALLSRC;
			if (!strcmp(name, ".ARCHIVE"))
				name = ARCHIVE;
			break;
		case 'I':
			if (!strcmp(name, ".IMPSRC"))
				name = IMPSRC;
			break;
		case 'M':
			if (!strcmp(name, ".MEMBER"))
				name = MEMBER;
			break;
		case 'O':
			if (!strcmp(name, ".OODATE"))
				name = OODATE;
			break;
		case 'P':
			if (!strcmp(name, ".PREFIX"))
				name = PREFIX;
			break;
		case 'T':
			if (!strcmp(name, ".TARGET"))
				name = TARGET;
			break;
		}
#ifdef notyet
    /* for compatibility with gmake */
    if (name[0] == '^' && name[1] == '\0')
	    name = ALLSRC;
#endif

    /*
     * First look for the variable in the given context. If it's not there,
     * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
     * depending on the FIND_* flags in 'flags'
     */
    var = Hash_FindEntry(&ctxt->context, name);

    if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
	var = Hash_FindEntry(&VAR_CMD->context, name);
    }
    if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
	(ctxt != VAR_GLOBAL))
    {
	var = Hash_FindEntry(&VAR_GLOBAL->context, name);
	if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
	    /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
	    var = Hash_FindEntry(&VAR_INTERNAL->context, name);
	}
    }
    if ((var == NULL) && (flags & FIND_ENV)) {
	char *env;

	if ((env = getenv(name)) != NULL) {
	    int		len;

	    v = bmake_malloc(sizeof(Var));
	    v->name = bmake_strdup(name);

	    len = strlen(env);

	    Buf_Init(&v->val, len + 1);
	    Buf_AddBytes(&v->val, len, env);

	    v->flags = VAR_FROM_ENV;
	    return (v);
	} else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
		   (ctxt != VAR_GLOBAL))
	{
	    var = Hash_FindEntry(&VAR_GLOBAL->context, name);
	    if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
		var = Hash_FindEntry(&VAR_INTERNAL->context, name);
	    }
	    if (var == NULL) {
		return NULL;
	    } else {
		return ((Var *)Hash_GetValue(var));
	    }
	} else {
	    return NULL;
	}
    } else if (var == NULL) {
	return NULL;
    } else {
	return ((Var *)Hash_GetValue(var));
    }
}

/*-
 *-----------------------------------------------------------------------
 * VarFreeEnv  --
 *	If the variable is an environment variable, free it
 *
 * Input:
 *	v		the variable
 *	destroy		true if the value buffer should be destroyed.
 *
 * Results:
 *	1 if it is an environment variable 0 ow.
 *
 * Side Effects:
 *	The variable is free'ed if it is an environent variable.
 *-----------------------------------------------------------------------
 */
static Boolean
VarFreeEnv(Var *v, Boolean destroy)
{
    if ((v->flags & VAR_FROM_ENV) == 0)
	return FALSE;
    free(v->name);
    Buf_Destroy(&v->val, destroy);
    free(v);
    return TRUE;
}

/*-
 *-----------------------------------------------------------------------
 * VarAdd  --
 *	Add a new variable of name name and value val to the given context
 *
 * Input:
 *	name		name of variable to add
 *	val		value to set it to
 *	ctxt		context in which to set it
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	The new variable is placed at the front of the given context
 *	The name and val arguments are duplicated so they may
 *	safely be freed.
 *-----------------------------------------------------------------------
 */
static void
VarAdd(const char *name, const char *val, GNode *ctxt)
{
    Var   	  *v;
    int		  len;
    Hash_Entry    *h;

    v = bmake_malloc(sizeof(Var));

    len = val ? strlen(val) : 0;
    Buf_Init(&v->val, len+1);
    Buf_AddBytes(&v->val, len, val);

    v->flags = 0;

    h = Hash_CreateEntry(&ctxt->context, name, NULL);
    Hash_SetValue(h, v);
    v->name = h->name;
    if (DEBUG(VAR)) {
	fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
    }
}

/*-
 *-----------------------------------------------------------------------
 * Var_Delete --
 *	Remove a variable from a context.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	The Var structure is removed and freed.
 *
 *-----------------------------------------------------------------------
 */
void
Var_Delete(const char *name, GNode *ctxt)
{
    Hash_Entry 	  *ln;
    char *cp;
    
    if (strchr(name, '$')) {
	cp = Var_Subst(NULL, name, VAR_GLOBAL, FALSE, TRUE);
    } else {
	cp = (char *)name;
    }
    ln = Hash_FindEntry(&ctxt->context, cp);
    if (DEBUG(VAR)) {
	fprintf(debug_file, "%s:delete %s%s\n",
	    ctxt->name, cp, ln ? "" : " (not found)");
    }
    if (cp != name) {
	free(cp);
    }
    if (ln != NULL) {
	Var 	  *v;

	v = (Var *)Hash_GetValue(ln);
	if ((v->flags & VAR_EXPORTED)) {
	    unsetenv(v->name);
	}
	if (strcmp(MAKE_EXPORTED, v->name) == 0) {
	    var_exportedVars = VAR_EXPORTED_NONE;
	}
	if (v->name != ln->name)
		free(v->name);
	Hash_DeleteEntry(&ctxt->context, ln);
	Buf_Destroy(&v->val, TRUE);
	free(v);
    }
}


/*
 * Export a var.
 * We ignore make internal variables (those which start with '.')
 * Also we jump through some hoops to avoid calling setenv
 * more than necessary since it can leak.
 * We only manipulate flags of vars if 'parent' is set.
 */
static int
Var_Export1(const char *name, int parent)
{
    char tmp[BUFSIZ];
    Var *v;
    char *val = NULL;
    int n;

    if (*name == '.')
	return 0;			/* skip internals */
    if (!name[1]) {
	/*
	 * A single char.
	 * If it is one of the vars that should only appear in
	 * local context, skip it, else we can get Var_Subst
	 * into a loop.
	 */
	switch (name[0]) {
	case '@':
	case '%':
	case '*':
	case '!':
	    return 0;
	}
    }
    v = VarFind(name, VAR_GLOBAL, 0);
    if (v == NULL) {
	return 0;
    }
    if (!parent &&
	(v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
	return 0;			/* nothing to do */
    }
    val = Buf_GetAll(&v->val, NULL);
    if (strchr(val, '$')) {
	if (parent) {
	    /*
	     * Flag this as something we need to re-export.
	     * No point actually exporting it now though,
	     * the child can do it at the last minute.
	     */
	    v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
	    return 1;
	}
	if (v->flags & VAR_IN_USE) {
	    /*
	     * We recursed while exporting in a child.
	     * This isn't going to end well, just skip it.
	     */
	    return 0;
	}
	n = snprintf(tmp, sizeof(tmp), "${%s}", name);
	if (n < (int)sizeof(tmp)) {
	    val = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
	    setenv(name, val, 1);
	    free(val);
	}
    } else {
	if (parent) {
	    v->flags &= ~VAR_REEXPORT;	/* once will do */
	}
	if (parent || !(v->flags & VAR_EXPORTED)) {
	    setenv(name, val, 1);
	}
    }
    /*
     * This is so Var_Set knows to call Var_Export again...
     */
    if (parent) {
	v->flags |= VAR_EXPORTED;
    }
    return 1;
}

/*
 * This gets called from our children.
 */
void
Var_ExportVars(void)
{
    char tmp[BUFSIZ];
    Hash_Entry         	*var;
    Hash_Search 	state;
    Var *v;
    char *val;
    int n;

    /*
     * Several make's support this sort of mechanism for tracking
     * recursion - but each uses a different name.
     * We allow the makefiles to update MAKELEVEL and ensure
     * children see a correctly incremented value.
     */
    snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
    setenv(MAKE_LEVEL_ENV, tmp, 1);

    if (VAR_EXPORTED_NONE == var_exportedVars)
	return;

    if (VAR_EXPORTED_ALL == var_exportedVars) {
	/*
	 * Ouch! This is crazy...
	 */
	for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
	     var != NULL;
	     var = Hash_EnumNext(&state)) {
	    v = (Var *)Hash_GetValue(var);
	    Var_Export1(v->name, 0);
	}
	return;
    }
    /*
     * We have a number of exported vars,
     */
    n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
    if (n < (int)sizeof(tmp)) {
	char **av;
	char *as;
	int ac;
	int i;

	val = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
	if (*val) {
	    av = brk_string(val, &ac, FALSE, &as);
	    for (i = 0; i < ac; i++) {
		Var_Export1(av[i], 0);
	    }
	    free(as);
	    free(av);
	}
	free(val);
    }
}

/*
 * This is called when .export is seen or
 * .MAKE.EXPORTED is modified.
 * It is also called when any exported var is modified.
 */
void
Var_Export(char *str, int isExport)
{
    char *name;
    char *val;
    char **av;
    char *as;
    int track;
    int ac;
    int i;

    if (isExport && (!str || !str[0])) {
	var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
	return;
    }

    if (strncmp(str, "-env", 4) == 0) {
	track = 0;
	str += 4;
    } else {
	track = VAR_EXPORT_PARENT;
    }
    val = Var_Subst(NULL, str, VAR_GLOBAL, FALSE, TRUE);
    if (*val) {
	av = brk_string(val, &ac, FALSE, &as);
	for (i = 0; i < ac; i++) {
	    name = av[i];
	    if (!name[1]) {
		/*
		 * A single char.
		 * If it is one of the vars that should only appear in
		 * local context, skip it, else we can get Var_Subst
		 * into a loop.
		 */
		switch (name[0]) {
		case '@':
		case '%':
		case '*':
		case '!':
		    continue;
		}
	    }
	    if (Var_Export1(name, track)) {
		if (VAR_EXPORTED_ALL != var_exportedVars)
		    var_exportedVars = VAR_EXPORTED_YES;
		if (isExport && track) {
		    Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
		}
	    }
	}
	free(as);
	free(av);
    }
    free(val);
}


/*
 * This is called when .unexport[-env] is seen.
 */
extern char **environ;

void
Var_UnExport(char *str)
{
    char tmp[BUFSIZ];
    char *vlist;
    char *cp;
    Boolean unexport_env;
    int n;

    if (!str || !str[0]) {
	return; 			/* assert? */
    }

    vlist = NULL;

    str += 8;
    unexport_env = (strncmp(str, "-env", 4) == 0);
    if (unexport_env) {
	char **newenv;

	cp = getenv(MAKE_LEVEL_ENV);	/* we should preserve this */
	if (environ == savedEnv) {
	    /* we have been here before! */
	    newenv = bmake_realloc(environ, 2 * sizeof(char *));
	} else {
	    if (savedEnv) {
		free(savedEnv);
		savedEnv = NULL;
	    }
	    newenv = bmake_malloc(2 * sizeof(char *));
	}
	if (!newenv)
	    return;
	/* Note: we cannot safely free() the original environ. */
	environ = savedEnv = newenv;
	newenv[0] = NULL;
	newenv[1] = NULL;
	setenv(MAKE_LEVEL_ENV, cp, 1);
    } else {
	for (; *str != '\n' && isspace((unsigned char) *str); str++)
	    continue;
	if (str[0] && str[0] != '\n') {
	    vlist = str;
	}
    }

    if (!vlist) {
	/* Using .MAKE.EXPORTED */
	n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
	if (n < (int)sizeof(tmp)) {
	    vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
	}
    }
    if (vlist) {
	Var *v;
	char **av;
	char *as;
	int ac;
	int i;

	av = brk_string(vlist, &ac, FALSE, &as);
	for (i = 0; i < ac; i++) {
	    v = VarFind(av[i], VAR_GLOBAL, 0);
	    if (!v)
		continue;
	    if (!unexport_env &&
		(v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
		unsetenv(v->name);
	    }
	    v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
	    /*
	     * If we are unexporting a list,
	     * remove each one from .MAKE.EXPORTED.
	     * If we are removing them all,
	     * just delete .MAKE.EXPORTED below.
	     */
	    if (vlist == str) {
		n = snprintf(tmp, sizeof(tmp),
			     "${" MAKE_EXPORTED ":N%s}", v->name);
		if (n < (int)sizeof(tmp)) {
		    cp = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
		    Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
		    free(cp);
		}
	    }
	}
	free(as);
	free(av);
	if (vlist != str) {
	    Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
	    free(vlist);
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * Var_Set --
 *	Set the variable name to the value val in the given context.
 *
 * Input:
 *	name		name of variable to set
 *	val		value to give to the variable
 *	ctxt		context in which to set it
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	If the variable doesn't yet exist, a new record is created for it.
 *	Else the old value is freed and the new one stuck in its place
 *
 * Notes:
 *	The variable is searched for only in its context before being
 *	created in that context. I.e. if the context is VAR_GLOBAL,
 *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
 *	VAR_CMD->context is searched. This is done to avoid the literally
 *	thousands of unnecessary strcmp's that used to be done to
 *	set, say, $(@) or $(<).
 *	If the context is VAR_GLOBAL though, we check if the variable
 *	was set in VAR_CMD from the command line and skip it if so.
 *-----------------------------------------------------------------------
 */
void
Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
{
    Var   *v;
    char *expanded_name = NULL;

    /*
     * We only look for a variable in the given context since anything set
     * here will override anything in a lower context, so there's not much
     * point in searching them all just to save a bit of memory...
     */
    if (strchr(name, '$') != NULL) {
	expanded_name = Var_Subst(NULL, name, ctxt, FALSE, TRUE);
	if (expanded_name[0] == 0) {
	    if (DEBUG(VAR)) {
		fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
			"name expands to empty string - ignored\n",
			name, val);
	    }
	    free(expanded_name);
	    return;
	}
	name = expanded_name;
    }
    if (ctxt == VAR_GLOBAL) {
	v = VarFind(name, VAR_CMD, 0);
	if (v != NULL) {
	    if ((v->flags & VAR_FROM_CMD)) {
		if (DEBUG(VAR)) {
		    fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
		}
		goto out;
	    }
	    VarFreeEnv(v, TRUE);
	}
    }
    v = VarFind(name, ctxt, 0);
    if (v == NULL) {
	if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
	    /*
	     * This var would normally prevent the same name being added
	     * to VAR_GLOBAL, so delete it from there if needed.
	     * Otherwise -V name may show the wrong value.
	     */
	    Var_Delete(name, VAR_GLOBAL);
	}
	VarAdd(name, val, ctxt);
    } else {
	Buf_Empty(&v->val);
	Buf_AddBytes(&v->val, strlen(val), val);

	if (DEBUG(VAR)) {
	    fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
	}
	if ((v->flags & VAR_EXPORTED)) {
	    Var_Export1(name, VAR_EXPORT_PARENT);
	}
    }
    /*
     * Any variables given on the command line are automatically exported
     * to the environment (as per POSIX standard)
     */
    if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
	if (v == NULL) {
	    /* we just added it */
	    v = VarFind(name, ctxt, 0);
	}
	if (v != NULL)
	    v->flags |= VAR_FROM_CMD;
	/*
	 * If requested, don't export these in the environment
	 * individually.  We still put them in MAKEOVERRIDES so
	 * that the command-line settings continue to override
	 * Makefile settings.
	 */
	if (varNoExportEnv != TRUE)
	    setenv(name, val, 1);

	Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
    }


 out:
    free(expanded_name);
    if (v != NULL)
	VarFreeEnv(v, TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * Var_Append --
 *	The variable of the given name has the given value appended to it in
 *	the given context.
 *
 * Input:
 *	name		name of variable to modify
 *	val		String to append to it
 *	ctxt		Context in which this should occur
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	If the variable doesn't exist, it is created. Else the strings
 *	are concatenated (with a space in between).
 *
 * Notes:
 *	Only if the variable is being sought in the global context is the
 *	environment searched.
 *	XXX: Knows its calling circumstances in that if called with ctxt
 *	an actual target, it will only search that context since only
 *	a local variable could be being appended to. This is actually
 *	a big win and must be tolerated.
 *-----------------------------------------------------------------------
 */
void
Var_Append(const char *name, const char *val, GNode *ctxt)
{
    Var		   *v;
    Hash_Entry	   *h;
    char *expanded_name = NULL;

    if (strchr(name, '$') != NULL) {
	expanded_name = Var_Subst(NULL, name, ctxt, FALSE, TRUE);
	if (expanded_name[0] == 0) {
	    if (DEBUG(VAR)) {
		fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
			"name expands to empty string - ignored\n",
			name, val);
	    }
	    free(expanded_name);
	    return;
	}
	name = expanded_name;
    }

    v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);

    if (v == NULL) {
	VarAdd(name, val, ctxt);
    } else {
	Buf_AddByte(&v->val, ' ');
	Buf_AddBytes(&v->val, strlen(val), val);

	if (DEBUG(VAR)) {
	    fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
		   Buf_GetAll(&v->val, NULL));
	}

	if (v->flags & VAR_FROM_ENV) {
	    /*
	     * If the original variable came from the environment, we
	     * have to install it in the global context (we could place
	     * it in the environment, but then we should provide a way to
	     * export other variables...)
	     */
	    v->flags &= ~VAR_FROM_ENV;
	    h = Hash_CreateEntry(&ctxt->context, name, NULL);
	    Hash_SetValue(h, v);
	}
    }
    free(expanded_name);
}

/*-
 *-----------------------------------------------------------------------
 * Var_Exists --
 *	See if the given variable exists.
 *
 * Input:
 *	name		Variable to find
 *	ctxt		Context in which to start search
 *
 * Results:
 *	TRUE if it does, FALSE if it doesn't
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
Boolean
Var_Exists(const char *name, GNode *ctxt)
{
    Var		  *v;
    char          *cp;

    if ((cp = strchr(name, '$')) != NULL) {
	cp = Var_Subst(NULL, name, ctxt, FALSE, TRUE);
    }
    v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
    free(cp);
    if (v == NULL) {
	return(FALSE);
    } else {
	(void)VarFreeEnv(v, TRUE);
    }
    return(TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * Var_Value --
 *	Return the value of the named variable in the given context
 *
 * Input:
 *	name		name to find
 *	ctxt		context in which to search for it
 *
 * Results:
 *	The value if the variable exists, NULL if it doesn't
 *
 * Side Effects:
 *	None
 *-----------------------------------------------------------------------
 */
char *
Var_Value(const char *name, GNode *ctxt, char **frp)
{
    Var            *v;

    v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
    *frp = NULL;
    if (v != NULL) {
	char *p = (Buf_GetAll(&v->val, NULL));
	if (VarFreeEnv(v, FALSE))
	    *frp = p;
	return p;
    } else {
	return NULL;
    }
}

/*-
 *-----------------------------------------------------------------------
 * VarHead --
 *	Remove the tail of the given word and place the result in the given
 *	buffer.
 *
 * Input:
 *	word		Word to trim
 *	addSpace	True if need to add a space to the buffer
 *			before sticking in the head
 *	buf		Buffer in which to store it
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The trimmed word is added to the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	char *word, Boolean addSpace, Buffer *buf,
	void *dummy)
{
    char *slash;

    slash = strrchr(word, '/');
    if (slash != NULL) {
	if (addSpace && vpstate->varSpace) {
	    Buf_AddByte(buf, vpstate->varSpace);
	}
	*slash = '\0';
	Buf_AddBytes(buf, strlen(word), word);
	*slash = '/';
	return (TRUE);
    } else {
	/*
	 * If no directory part, give . (q.v. the POSIX standard)
	 */
	if (addSpace && vpstate->varSpace)
	    Buf_AddByte(buf, vpstate->varSpace);
	Buf_AddByte(buf, '.');
    }
    return(dummy ? TRUE : TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * VarTail --
 *	Remove the head of the given word and place the result in the given
 *	buffer.
 *
 * Input:
 *	word		Word to trim
 *	addSpace	True if need to add a space to the buffer
 *			before adding the tail
 *	buf		Buffer in which to store it
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The trimmed word is added to the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	char *word, Boolean addSpace, Buffer *buf,
	void *dummy)
{
    char *slash;

    if (addSpace && vpstate->varSpace) {
	Buf_AddByte(buf, vpstate->varSpace);
    }

    slash = strrchr(word, '/');
    if (slash != NULL) {
	*slash++ = '\0';
	Buf_AddBytes(buf, strlen(slash), slash);
	slash[-1] = '/';
    } else {
	Buf_AddBytes(buf, strlen(word), word);
    }
    return (dummy ? TRUE : TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * VarSuffix --
 *	Place the suffix of the given word in the given buffer.
 *
 * Input:
 *	word		Word to trim
 *	addSpace	TRUE if need to add a space before placing the
 *			suffix in the buffer
 *	buf		Buffer in which to store it
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The suffix from the word is placed in the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	  char *word, Boolean addSpace, Buffer *buf,
	  void *dummy)
{
    char *dot;

    dot = strrchr(word, '.');
    if (dot != NULL) {
	if (addSpace && vpstate->varSpace) {
	    Buf_AddByte(buf, vpstate->varSpace);
	}
	*dot++ = '\0';
	Buf_AddBytes(buf, strlen(dot), dot);
	dot[-1] = '.';
	addSpace = TRUE;
    }
    return (dummy ? addSpace : addSpace);
}

/*-
 *-----------------------------------------------------------------------
 * VarRoot --
 *	Remove the suffix of the given word and place the result in the
 *	buffer.
 *
 * Input:
 *	word		Word to trim
 *	addSpace	TRUE if need to add a space to the buffer
 *			before placing the root in it
 *	buf		Buffer in which to store it
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The trimmed word is added to the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	char *word, Boolean addSpace, Buffer *buf,
	void *dummy)
{
    char *dot;

    if (addSpace && vpstate->varSpace) {
	Buf_AddByte(buf, vpstate->varSpace);
    }

    dot = strrchr(word, '.');
    if (dot != NULL) {
	*dot = '\0';
	Buf_AddBytes(buf, strlen(word), word);
	*dot = '.';
    } else {
	Buf_AddBytes(buf, strlen(word), word);
    }
    return (dummy ? TRUE : TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * VarMatch --
 *	Place the word in the buffer if it matches the given pattern.
 *	Callback function for VarModify to implement the :M modifier.
 *
 * Input:
 *	word		Word to examine
 *	addSpace	TRUE if need to add a space to the buffer
 *			before adding the word, if it matches
 *	buf		Buffer in which to store it
 *	pattern		Pattern the word must match
 *
 * Results:
 *	TRUE if a space should be placed in the buffer before the next
 *	word.
 *
 * Side Effects:
 *	The word may be copied to the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	 char *word, Boolean addSpace, Buffer *buf,
	 void *pattern)
{
    if (DEBUG(VAR))
	fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
    if (Str_Match(word, (char *)pattern)) {
	if (addSpace && vpstate->varSpace) {
	    Buf_AddByte(buf, vpstate->varSpace);
	}
	addSpace = TRUE;
	Buf_AddBytes(buf, strlen(word), word);
    }
    return(addSpace);
}

#ifdef SYSVVARSUB
/*-
 *-----------------------------------------------------------------------
 * VarSYSVMatch --
 *	Place the word in the buffer if it matches the given pattern.
 *	Callback function for VarModify to implement the System V %
 *	modifiers.
 *
 * Input:
 *	word		Word to examine
 *	addSpace	TRUE if need to add a space to the buffer
 *			before adding the word, if it matches
 *	buf		Buffer in which to store it
 *	patp		Pattern the word must match
 *
 * Results:
 *	TRUE if a space should be placed in the buffer before the next
 *	word.
 *
 * Side Effects:
 *	The word may be copied to the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
	     char *word, Boolean addSpace, Buffer *buf,
	     void *patp)
{
    int len;
    char *ptr;
    VarPattern 	  *pat = (VarPattern *)patp;
    char *varexp;

    if (addSpace && vpstate->varSpace)
	Buf_AddByte(buf, vpstate->varSpace);

    addSpace = TRUE;

    if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
        varexp = Var_Subst(NULL, pat->rhs, ctx, FALSE, TRUE);
	Str_SYSVSubst(buf, varexp, ptr, len);
	free(varexp);
    } else {
	Buf_AddBytes(buf, strlen(word), word);
    }

    return(addSpace);
}
#endif


/*-
 *-----------------------------------------------------------------------
 * VarNoMatch --
 *	Place the word in the buffer if it doesn't match the given pattern.
 *	Callback function for VarModify to implement the :N modifier.
 *
 * Input:
 *	word		Word to examine
 *	addSpace	TRUE if need to add a space to the buffer
 *			before adding the word, if it matches
 *	buf		Buffer in which to store it
 *	pattern		Pattern the word must match
 *
 * Results:
 *	TRUE if a space should be placed in the buffer before the next
 *	word.
 *
 * Side Effects:
 *	The word may be copied to the buffer.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	   char *word, Boolean addSpace, Buffer *buf,
	   void *pattern)
{
    if (!Str_Match(word, (char *)pattern)) {
	if (addSpace && vpstate->varSpace) {
	    Buf_AddByte(buf, vpstate->varSpace);
	}
	addSpace = TRUE;
	Buf_AddBytes(buf, strlen(word), word);
    }
    return(addSpace);
}


/*-
 *-----------------------------------------------------------------------
 * VarSubstitute --
 *	Perform a string-substitution on the given word, placing the
 *	result in the passed buffer.
 *
 * Input:
 *	word		Word to modify
 *	addSpace	True if space should be added before
 *			other characters
 *	buf		Buffer for result
 *	patternp	Pattern for substitution
 *
 * Results:
 *	TRUE if a space is needed before more characters are added.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	      char *word, Boolean addSpace, Buffer *buf,
	      void *patternp)
{
    int  	wordLen;    /* Length of word */
    char 	*cp;	    /* General pointer */
    VarPattern	*pattern = (VarPattern *)patternp;

    wordLen = strlen(word);
    if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
	(VAR_SUB_ONE|VAR_SUB_MATCHED)) {
	/*
	 * Still substituting -- break it down into simple anchored cases
	 * and if none of them fits, perform the general substitution case.
	 */
	if ((pattern->flags & VAR_MATCH_START) &&
	    (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
		/*
		 * Anchored at start and beginning of word matches pattern
		 */
		if ((pattern->flags & VAR_MATCH_END) &&
		    (wordLen == pattern->leftLen)) {
			/*
			 * Also anchored at end and matches to the end (word
			 * is same length as pattern) add space and rhs only
			 * if rhs is non-null.
			 */
			if (pattern->rightLen != 0) {
			    if (addSpace && vpstate->varSpace) {
				Buf_AddByte(buf, vpstate->varSpace);
			    }
			    addSpace = TRUE;
			    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
			}
			pattern->flags |= VAR_SUB_MATCHED;
		} else if (pattern->flags & VAR_MATCH_END) {
		    /*
		     * Doesn't match to end -- copy word wholesale
		     */
		    goto nosub;
		} else {
		    /*
		     * Matches at start but need to copy in trailing characters
		     */
		    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
			if (addSpace && vpstate->varSpace) {
			    Buf_AddByte(buf, vpstate->varSpace);
			}
			addSpace = TRUE;
		    }
		    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
		    Buf_AddBytes(buf, wordLen - pattern->leftLen,
				 (word + pattern->leftLen));
		    pattern->flags |= VAR_SUB_MATCHED;
		}
	} else if (pattern->flags & VAR_MATCH_START) {
	    /*
	     * Had to match at start of word and didn't -- copy whole word.
	     */
	    goto nosub;
	} else if (pattern->flags & VAR_MATCH_END) {
	    /*
	     * Anchored at end, Find only place match could occur (leftLen
	     * characters from the end of the word) and see if it does. Note
	     * that because the $ will be left at the end of the lhs, we have
	     * to use strncmp.
	     */
	    cp = word + (wordLen - pattern->leftLen);
	    if ((cp >= word) &&
		(strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
		/*
		 * Match found. If we will place characters in the buffer,
		 * add a space before hand as indicated by addSpace, then
		 * stuff in the initial, unmatched part of the word followed
		 * by the right-hand-side.
		 */
		if (((cp - word) + pattern->rightLen) != 0) {
		    if (addSpace && vpstate->varSpace) {
			Buf_AddByte(buf, vpstate->varSpace);
		    }
		    addSpace = TRUE;
		}
		Buf_AddBytes(buf, cp - word, word);
		Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
		pattern->flags |= VAR_SUB_MATCHED;
	    } else {
		/*
		 * Had to match at end and didn't. Copy entire word.
		 */
		goto nosub;
	    }
	} else {
	    /*
	     * Pattern is unanchored: search for the pattern in the word using
	     * String_FindSubstring, copying unmatched portions and the
	     * right-hand-side for each match found, handling non-global
	     * substitutions correctly, etc. When the loop is done, any
	     * remaining part of the word (word and wordLen are adjusted
	     * accordingly through the loop) is copied straight into the
	     * buffer.
	     * addSpace is set FALSE as soon as a space is added to the
	     * buffer.
	     */
	    Boolean done;
	    int origSize;

	    done = FALSE;
	    origSize = Buf_Size(buf);
	    while (!done) {
		cp = Str_FindSubstring(word, pattern->lhs);
		if (cp != NULL) {
		    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
			Buf_AddByte(buf, vpstate->varSpace);
			addSpace = FALSE;
		    }
		    Buf_AddBytes(buf, cp-word, word);
		    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
		    wordLen -= (cp - word) + pattern->leftLen;
		    word = cp + pattern->leftLen;
		    if (wordLen == 0) {
			done = TRUE;
		    }
		    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
			done = TRUE;
		    }
		    pattern->flags |= VAR_SUB_MATCHED;
		} else {
		    done = TRUE;
		}
	    }
	    if (wordLen != 0) {
		if (addSpace && vpstate->varSpace) {
		    Buf_AddByte(buf, vpstate->varSpace);
		}
		Buf_AddBytes(buf, wordLen, word);
	    }
	    /*
	     * If added characters to the buffer, need to add a space
	     * before we add any more. If we didn't add any, just return
	     * the previous value of addSpace.
	     */
	    return ((Buf_Size(buf) != origSize) || addSpace);
	}
	return (addSpace);
    }
 nosub:
    if (addSpace && vpstate->varSpace) {
	Buf_AddByte(buf, vpstate->varSpace);
    }
    Buf_AddBytes(buf, wordLen, word);
    return(TRUE);
}

#ifndef NO_REGEX
/*-
 *-----------------------------------------------------------------------
 * VarREError --
 *	Print the error caused by a regcomp or regexec call.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	An error gets printed.
 *
 *-----------------------------------------------------------------------
 */
static void
VarREError(int errnum, regex_t *pat, const char *str)
{
    char *errbuf;
    int errlen;

    errlen = regerror(errnum, pat, 0, 0);
    errbuf = bmake_malloc(errlen);
    regerror(errnum, pat, errbuf, errlen);
    Error("%s: %s", str, errbuf);
    free(errbuf);
}


/*-
 *-----------------------------------------------------------------------
 * VarRESubstitute --
 *	Perform a regex substitution on the given word, placing the
 *	result in the passed buffer.
 *
 * Results:
 *	TRUE if a space is needed before more characters are added.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
		Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
		char *word, Boolean addSpace, Buffer *buf,
		void *patternp)
{
    VarREPattern *pat;
    int xrv;
    char *wp;
    char *rp;
    int added;
    int flags = 0;

#define MAYBE_ADD_SPACE()		\
	if (addSpace && !added)		\
	    Buf_AddByte(buf, ' ');	\
	added = 1

    added = 0;
    wp = word;
    pat = patternp;

    if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
	(VAR_SUB_ONE|VAR_SUB_MATCHED))
	xrv = REG_NOMATCH;
    else {
    tryagain:
	xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
    }

    switch (xrv) {
    case 0:
	pat->flags |= VAR_SUB_MATCHED;
	if (pat->matches[0].rm_so > 0) {
	    MAYBE_ADD_SPACE();
	    Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
	}

	for (rp = pat->replace; *rp; rp++) {
	    if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
		MAYBE_ADD_SPACE();
		Buf_AddByte(buf,rp[1]);
		rp++;
	    }
	    else if ((*rp == '&') ||
		((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
		int n;
		const char *subbuf;
		int sublen;
		char errstr[3];

		if (*rp == '&') {
		    n = 0;
		    errstr[0] = '&';
		    errstr[1] = '\0';
		} else {
		    n = rp[1] - '0';
		    errstr[0] = '\\';
		    errstr[1] = rp[1];
		    errstr[2] = '\0';
		    rp++;
		}

		if (n > pat->nsub) {
		    Error("No subexpression %s", &errstr[0]);
		    subbuf = "";
		    sublen = 0;
		} else if ((pat->matches[n].rm_so == -1) &&
			   (pat->matches[n].rm_eo == -1)) {
		    Error("No match for subexpression %s", &errstr[0]);
		    subbuf = "";
		    sublen = 0;
	        } else {
		    subbuf = wp + pat->matches[n].rm_so;
		    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
		}

		if (sublen > 0) {
		    MAYBE_ADD_SPACE();
		    Buf_AddBytes(buf, sublen, subbuf);
		}
	    } else {
		MAYBE_ADD_SPACE();
		Buf_AddByte(buf, *rp);
	    }
	}
	wp += pat->matches[0].rm_eo;
	if (pat->flags & VAR_SUB_GLOBAL) {
	    flags |= REG_NOTBOL;
	    if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
		MAYBE_ADD_SPACE();
		Buf_AddByte(buf, *wp);
		wp++;

	    }
	    if (*wp)
		goto tryagain;
	}
	if (*wp) {
	    MAYBE_ADD_SPACE();
	    Buf_AddBytes(buf, strlen(wp), wp);
	}
	break;
    default:
	VarREError(xrv, &pat->re, "Unexpected regex error");
       /* fall through */
    case REG_NOMATCH:
	if (*wp) {
	    MAYBE_ADD_SPACE();
	    Buf_AddBytes(buf,strlen(wp),wp);
	}
	break;
    }
    return(addSpace||added);
}
#endif



/*-
 *-----------------------------------------------------------------------
 * VarLoopExpand --
 *	Implements the :@<temp>@<string>@ modifier of ODE make.
 *	We set the temp variable named in pattern.lhs to word and expand
 *	pattern.rhs storing the result in the passed buffer.
 *
 * Input:
 *	word		Word to modify
 *	addSpace	True if space should be added before
 *			other characters
 *	buf		Buffer for result
 *	pattern		Datafor substitution
 *
 * Results:
 *	TRUE if a space is needed before more characters are added.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
	      Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
	      char *word, Boolean addSpace, Buffer *buf,
	      void *loopp)
{
    VarLoop_t	*loop = (VarLoop_t *)loopp;
    char *s;
    int slen;

    if (word && *word) {
        Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
        s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum, TRUE);
        if (s != NULL && *s != '\0') {
            if (addSpace && *s != '\n')
                Buf_AddByte(buf, ' ');
            Buf_AddBytes(buf, (slen = strlen(s)), s);
            addSpace = (slen > 0 && s[slen - 1] != '\n');
            free(s);
        }
    }
    return addSpace;
}


/*-
 *-----------------------------------------------------------------------
 * VarSelectWords --
 *	Implements the :[start..end] modifier.
 *	This is a special case of VarModify since we want to be able
 *	to scan the list backwards if start > end.
 *
 * Input:
 *	str		String whose words should be trimmed
 *	seldata		words to select
 *
 * Results:
 *	A string of all the words selected.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static char *
VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	       const char *str, VarSelectWords_t *seldata)
{
    Buffer  	  buf;		    /* Buffer for the new string */
    Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
				     * buffer before adding the trimmed
				     * word */
    char **av;			    /* word list */
    char *as;			    /* word list memory */
    int ac, i;
    int start, end, step;

    Buf_Init(&buf, 0);
    addSpace = FALSE;

    if (vpstate->oneBigWord) {
	/* fake what brk_string() would do if there were only one word */
	ac = 1;
    	av = bmake_malloc((ac + 1) * sizeof(char *));
	as = bmake_strdup(str);
	av[0] = as;
	av[1] = NULL;
    } else {
	av = brk_string(str, &ac, FALSE, &as);
    }

    /*
     * Now sanitize seldata.
     * If seldata->start or seldata->end are negative, convert them to
     * the positive equivalents (-1 gets converted to argc, -2 gets
     * converted to (argc-1), etc.).
     */
    if (seldata->start < 0)
	seldata->start = ac + seldata->start + 1;
    if (seldata->end < 0)
	seldata->end = ac + seldata->end + 1;

    /*
     * We avoid scanning more of the list than we need to.
     */
    if (seldata->start > seldata->end) {
	start = MIN(ac, seldata->start) - 1;
	end = MAX(0, seldata->end - 1);
	step = -1;
    } else {
	start = MAX(0, seldata->start - 1);
	end = MIN(ac, seldata->end);
	step = 1;
    }

    for (i = start;
	 (step < 0 && i >= end) || (step > 0 && i < end);
	 i += step) {
	if (av[i] && *av[i]) {
	    if (addSpace && vpstate->varSpace) {
		Buf_AddByte(&buf, vpstate->varSpace);
	    }
	    Buf_AddBytes(&buf, strlen(av[i]), av[i]);
	    addSpace = TRUE;
	}
    }

    free(as);
    free(av);

    return Buf_Destroy(&buf, FALSE);
}


/*-
 * VarRealpath --
 *	Replace each word with the result of realpath()
 *	if successful.
 */
static Boolean
VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
	    char *word, Boolean addSpace, Buffer *buf,
	    void *patternp MAKE_ATTR_UNUSED)
{
	struct stat st;
	char rbuf[MAXPATHLEN];
	char *rp;
			    
	if (addSpace && vpstate->varSpace) {
	    Buf_AddByte(buf, vpstate->varSpace);
	}
	addSpace = TRUE;
	rp = realpath(word, rbuf);
	if (rp && *rp == '/' && stat(rp, &st) == 0)
		word = rp;
	
	Buf_AddBytes(buf, strlen(word), word);
	return(addSpace);
}

/*-
 *-----------------------------------------------------------------------
 * VarModify --
 *	Modify each of the words of the passed string using the given
 *	function. Used to implement all modifiers.
 *
 * Input:
 *	str		String whose words should be trimmed
 *	modProc		Function to use to modify them
 *	datum		Datum to pass it
 *
 * Results:
 *	A string of all the words modified appropriately.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static char *
VarModify(GNode *ctx, Var_Parse_State *vpstate,
    const char *str,
    Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
		       Boolean, Buffer *, void *),
    void *datum)
{
    Buffer  	  buf;		    /* Buffer for the new string */
    Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
				     * buffer before adding the trimmed
				     * word */
    char **av;			    /* word list */
    char *as;			    /* word list memory */
    int ac, i;

    Buf_Init(&buf, 0);
    addSpace = FALSE;

    if (vpstate->oneBigWord) {
	/* fake what brk_string() would do if there were only one word */
	ac = 1;
    	av = bmake_malloc((ac + 1) * sizeof(char *));
	as = bmake_strdup(str);
	av[0] = as;
	av[1] = NULL;
    } else {
	av = brk_string(str, &ac, FALSE, &as);
    }

    for (i = 0; i < ac; i++) {
	addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
    }

    free(as);
    free(av);

    return Buf_Destroy(&buf, FALSE);
}


static int
VarWordCompare(const void *a, const void *b)
{
	int r = strcmp(*(const char * const *)a, *(const char * const *)b);
	return r;
}

/*-
 *-----------------------------------------------------------------------
 * VarOrder --
 *	Order the words in the string.
 *
 * Input:
 *	str		String whose words should be sorted.
 *	otype		How to order: s - sort, x - random.
 *
 * Results:
 *	A string containing the words ordered.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static char *
VarOrder(const char *str, const char otype)
{
    Buffer  	  buf;		    /* Buffer for the new string */
    char **av;			    /* word list [first word does not count] */
    char *as;			    /* word list memory */
    int ac, i;

    Buf_Init(&buf, 0);

    av = brk_string(str, &ac, FALSE, &as);

    if (ac > 0)
	switch (otype) {
	case 's':	/* sort alphabetically */
	    qsort(av, ac, sizeof(char *), VarWordCompare);
	    break;
	case 'x':	/* randomize */
	{
	    int rndidx;
	    char *t;

	    /*
	     * We will use [ac..2] range for mod factors. This will produce
	     * random numbers in [(ac-1)..0] interval, and minimal
	     * reasonable value for mod factor is 2 (the mod 1 will produce
	     * 0 with probability 1).
	     */
	    for (i = ac-1; i > 0; i--) {
		rndidx = random() % (i + 1);
		if (i != rndidx) {
		    t = av[i];
		    av[i] = av[rndidx];
		    av[rndidx] = t;
		}
	    }
	}
	} /* end of switch */

    for (i = 0; i < ac; i++) {
	Buf_AddBytes(&buf, strlen(av[i]), av[i]);
	if (i != ac - 1)
	    Buf_AddByte(&buf, ' ');
    }

    free(as);
    free(av);

    return Buf_Destroy(&buf, FALSE);
}


/*-
 *-----------------------------------------------------------------------
 * VarUniq --
 *	Remove adjacent duplicate words.
 *
 * Input:
 *	str		String whose words should be sorted
 *
 * Results:
 *	A string containing the resulting words.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static char *
VarUniq(const char *str)
{
    Buffer	  buf;		    /* Buffer for new string */
    char 	**av;		    /* List of words to affect */
    char 	 *as;		    /* Word list memory */
    int 	  ac, i, j;

    Buf_Init(&buf, 0);
    av = brk_string(str, &ac, FALSE, &as);

    if (ac > 1) {
	for (j = 0, i = 1; i < ac; i++)
	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
		av[j] = av[i];
	ac = j + 1;
    }

    for (i = 0; i < ac; i++) {
	Buf_AddBytes(&buf, strlen(av[i]), av[i]);
	if (i != ac - 1)
	    Buf_AddByte(&buf, ' ');
    }

    free(as);
    free(av);

    return Buf_Destroy(&buf, FALSE);
}


/*-
 *-----------------------------------------------------------------------
 * VarGetPattern --
 *	Pass through the tstr looking for 1) escaped delimiters,
 *	'$'s and backslashes (place the escaped character in
 *	uninterpreted) and 2) unescaped $'s that aren't before
 *	the delimiter (expand the variable substitution unless flags
 *	has VAR_NOSUBST set).
 *	Return the expanded string or NULL if the delimiter was missing
 *	If pattern is specified, handle escaped ampersands, and replace
 *	unescaped ampersands with the lhs of the pattern.
 *
 * Results:
 *	A string of all the words modified appropriately.
 *	If length is specified, return the string length of the buffer
 *	If flags is specified and the last character of the pattern is a
 *	$ set the VAR_MATCH_END bit of flags.
 *
 * Side Effects:
 *	None.
 *-----------------------------------------------------------------------
 */
static char *
VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
	      int errnum, const char **tstr, int delim, int *flags,
	      int *length, VarPattern *pattern)
{
    const char *cp;
    char *rstr;
    Buffer buf;
    int junk;

    Buf_Init(&buf, 0);
    if (length == NULL)
	length = &junk;

#define IS_A_MATCH(cp, delim) \
    ((cp[0] == '\\') && ((cp[1] == delim) ||  \
     (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))

    /*
     * Skim through until the matching delimiter is found;
     * pick up variable substitutions on the way. Also allow
     * backslashes to quote the delimiter, $, and \, but don't
     * touch other backslashes.
     */
    for (cp = *tstr; *cp && (*cp != delim); cp++) {
	if (IS_A_MATCH(cp, delim)) {
	    Buf_AddByte(&buf, cp[1]);
	    cp++;
	} else if (*cp == '$') {
	    if (cp[1] == delim) {
		if (flags == NULL)
		    Buf_AddByte(&buf, *cp);
		else
		    /*
		     * Unescaped $ at end of pattern => anchor
		     * pattern at end.
		     */
		    *flags |= VAR_MATCH_END;
	    } else {
		if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
		    char   *cp2;
		    int     len;
		    void   *freeIt;

		    /*
		     * If unescaped dollar sign not before the
		     * delimiter, assume it's a variable
		     * substitution and recurse.
		     */
		    cp2 = Var_Parse(cp, ctxt, errnum, TRUE, &len, &freeIt);
		    Buf_AddBytes(&buf, strlen(cp2), cp2);
		    free(freeIt);
		    cp += len - 1;
		} else {
		    const char *cp2 = &cp[1];

		    if (*cp2 == PROPEN || *cp2 == BROPEN) {
			/*
			 * Find the end of this variable reference
			 * and suck it in without further ado.
			 * It will be interperated later.
			 */
			int have = *cp2;
			int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
			int depth = 1;

			for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
			    if (cp2[-1] != '\\') {
				if (*cp2 == have)
				    ++depth;
				if (*cp2 == want)
				    --depth;
			    }
			}
			Buf_AddBytes(&buf, cp2 - cp, cp);
			cp = --cp2;
		    } else
			Buf_AddByte(&buf, *cp);
		}
	    }
	}
	else if (pattern && *cp == '&')
	    Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
	else
	    Buf_AddByte(&buf, *cp);
    }

    if (*cp != delim) {
	*tstr = cp;
	*length = 0;
	return NULL;
    }

    *tstr = ++cp;
    *length = Buf_Size(&buf);
    rstr = Buf_Destroy(&buf, FALSE);
    if (DEBUG(VAR))
	fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
    return rstr;
}

/*-
 *-----------------------------------------------------------------------
 * VarQuote --
 *	Quote shell meta-characters and space characters in the string
 *
 * Results:
 *	The quoted string
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static char *
VarQuote(char *str)
{

    Buffer  	  buf;
    const char	*newline;
    size_t nlen;

    if ((newline = Shell_GetNewline()) == NULL)
	    newline = "\\\n";
    nlen = strlen(newline);

    Buf_Init(&buf, 0);

    for (; *str != '\0'; str++) {
	if (*str == '\n') {
	    Buf_AddBytes(&buf, nlen, newline);
	    continue;
	}
	if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
	    Buf_AddByte(&buf, '\\');
	Buf_AddByte(&buf, *str);
    }

    str = Buf_Destroy(&buf, FALSE);
    if (DEBUG(VAR))
	fprintf(debug_file, "QuoteMeta: [%s]\n", str);
    return str;
}

/*-
 *-----------------------------------------------------------------------
 * VarHash --
 *      Hash the string using the MurmurHash3 algorithm.
 *      Output is computed using 32bit Little Endian arithmetic.
 *
 * Input:
 *	str		String to modify
 *
 * Results:
 *      Hash value of str, encoded as 8 hex digits.
 *
 * Side Effects:
 *      None.
 *
 *-----------------------------------------------------------------------
 */
static char *
VarHash(char *str)
{
    static const char    hexdigits[16] = "0123456789abcdef";
    Buffer         buf;
    size_t         len, len2;
    unsigned char  *ustr = (unsigned char *)str;
    unsigned int   h, k, c1, c2;

    h  = 0x971e137bU;
    c1 = 0x95543787U;
    c2 = 0x2ad7eb25U;
    len2 = strlen(str);

    for (len = len2; len; ) {
	k = 0;
	switch (len) {
	default:
	    k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
	    len -= 4;
	    ustr += 4;
	    break;
	case 3:
	    k |= (ustr[2] << 16);
	case 2:
	    k |= (ustr[1] << 8);
	case 1:
	    k |= ustr[0];
	    len = 0;
	}
	c1 = c1 * 5 + 0x7b7d159cU;
	c2 = c2 * 5 + 0x6bce6396U;
	k *= c1;
	k = (k << 11) ^ (k >> 21);
	k *= c2;
	h = (h << 13) ^ (h >> 19);
	h = h * 5 + 0x52dce729U;
	h ^= k;
   }
   h ^= len2;
   h *= 0x85ebca6b;
   h ^= h >> 13;
   h *= 0xc2b2ae35;
   h ^= h >> 16;

   Buf_Init(&buf, 0);
   for (len = 0; len < 8; ++len) {
       Buf_AddByte(&buf, hexdigits[h & 15]);
       h >>= 4;
   }

   return Buf_Destroy(&buf, FALSE);
}

static char *
VarStrftime(const char *fmt, int zulu)
{
    char buf[BUFSIZ];
    time_t utc;

    time(&utc);
    if (!*fmt)
	fmt = "%c";
    strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
    
    buf[sizeof(buf) - 1] = '\0';
    return bmake_strdup(buf);
}

/*
 * Now we need to apply any modifiers the user wants applied.
 * These are:
 *  	  :M<pattern>	words which match the given <pattern>.
 *  			<pattern> is of the standard file
 *  			wildcarding form.
 *  	  :N<pattern>	words which do not match the given <pattern>.
 *  	  :S<d><pat1><d><pat2><d>[1gW]
 *  			Substitute <pat2> for <pat1> in the value
 *  	  :C<d><pat1><d><pat2><d>[1gW]
 *  			Substitute <pat2> for regex <pat1> in the value
 *  	  :H		Substitute the head of each word
 *  	  :T		Substitute the tail of each word
 *  	  :E		Substitute the extension (minus '.') of
 *  			each word
 *  	  :R		Substitute the root of each word
 *  			(pathname minus the suffix).
 *	  :O		("Order") Alphabeticaly sort words in variable.
 *	  :Ox		("intermiX") Randomize words in variable.
 *	  :u		("uniq") Remove adjacent duplicate words.
 *	  :tu		Converts the variable contents to uppercase.
 *	  :tl		Converts the variable contents to lowercase.
 *	  :ts[c]	Sets varSpace - the char used to
 *			separate words to 'c'. If 'c' is
 *			omitted then no separation is used.
 *	  :tW		Treat the variable contents as a single
 *			word, even if it contains spaces.
 *			(Mnemonic: one big 'W'ord.)
 *	  :tw		Treat the variable contents as multiple
 *			space-separated words.
 *			(Mnemonic: many small 'w'ords.)
 *	  :[index]	Select a single word from the value.
 *	  :[start..end]	Select multiple words from the value.
 *	  :[*] or :[0]	Select the entire value, as a single
 *			word.  Equivalent to :tW.
 *	  :[@]		Select the entire value, as multiple
 *			words.	Undoes the effect of :[*].
 *			Equivalent to :tw.
 *	  :[#]		Returns the number of words in the value.
 *
 *	  :?<true-value>:<false-value>
 *			If the variable evaluates to true, return
 *			true value, else return the second value.
 *    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
 *    			the invocation.
 *	  :sh		Treat the current value as a command
 *			to be run, new value is its output.
 * The following added so we can handle ODE makefiles.
 *	  :@<tmpvar>@<newval>@
 *			Assign a temporary local variable <tmpvar>
 *			to the current value of each word in turn
 *			and replace each word with the result of
 *			evaluating <newval>
 *	  :D<newval>	Use <newval> as value if variable defined
 *	  :U<newval>	Use <newval> as value if variable undefined
 *	  :L		Use the name of the variable as the value.
 *	  :P		Use the path of the node that has the same
 *			name as the variable as the value.  This
 *			basically includes an implied :L so that
 *			the common method of refering to the path
 *			of your dependent 'x' in a rule is to use
 *			the form '${x:P}'.
 *	  :!<cmd>!	Run cmd much the same as :sh run's the
 *			current value of the variable.
 * The ::= modifiers, actually assign a value to the variable.
 * Their main purpose is in supporting modifiers of .for loop
 * iterators and other obscure uses.  They always expand to
 * nothing.  In a target rule that would otherwise expand to an
 * empty line they can be preceded with @: to keep make happy.
 * Eg.
 *
 * foo:	.USE
 * .for i in ${.TARGET} ${.TARGET:R}.gz
 * 	@: ${t::=$i}
 *	@echo blah ${t:T}
 * .endfor
 *
 *	  ::=<str>	Assigns <str> as the new value of variable.
 *	  ::?=<str>	Assigns <str> as value of variable if
 *			it was not already set.
 *	  ::+=<str>	Appends <str> to variable.
 *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
 *			variable.
 */

/* we now have some modifiers with long names */
#define STRMOD_MATCH(s, want, n) \
    (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))

static char *
ApplyModifiers(char *nstr, const char *tstr,
	       int startc, int endc,
	       Var *v, GNode *ctxt, Boolean errnum, Boolean wantit,
	       int *lengthPtr, void **freePtr)
{
    const char 	   *start;
    const char     *cp;    	/* Secondary pointer into str (place marker
				 * for tstr) */
    char	   *newStr;	/* New value to return */
    char	    termc;	/* Character which terminated scan */
    int             cnt;	/* Used to count brace pairs when variable in
				 * in parens or braces */
    char	delim;
    int		modifier;	/* that we are processing */
    Var_Parse_State parsestate; /* Flags passed to helper functions */

    delim = '\0';
    parsestate.oneBigWord = FALSE;
    parsestate.varSpace = ' ';	/* word separator */

    start = cp = tstr;

    while (*tstr && *tstr != endc) {

	if (*tstr == '$') {
	    /*
	     * We may have some complex modifiers in a variable.
	     */
	    void *freeIt;
	    char *rval;
	    int rlen;
	    int c;

	    rval = Var_Parse(tstr, ctxt, errnum, wantit, &rlen, &freeIt);

	    /*
	     * If we have not parsed up to endc or ':',
	     * we are not interested.
	     */
	    if (rval != NULL && *rval &&
		(c = tstr[rlen]) != '\0' &&
		c != ':' &&
		c != endc) {
		free(freeIt);
		goto apply_mods;
	    }

	    if (DEBUG(VAR)) {
		fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
		       rval, rlen, tstr, rlen, tstr + rlen);
	    }

	    tstr += rlen;

	    if (rval != NULL && *rval) {
		int used;

		nstr = ApplyModifiers(nstr, rval,
				      0, 0,
				      v, ctxt, errnum, wantit, &used, freePtr);
		if (nstr == var_Error
		    || (nstr == varNoError && errnum == 0)
		    || strlen(rval) != (size_t) used) {
		    free(freeIt);
		    goto out;		/* error already reported */
		}
	    }
	    free(freeIt);
	    if (*tstr == ':')
		tstr++;
	    else if (!*tstr && endc) {
		Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
		goto out;
	    }
	    continue;
	}
    apply_mods:
	if (DEBUG(VAR)) {
	    fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
		*tstr, nstr);
	}
	newStr = var_Error;
	switch ((modifier = *tstr)) {
	case ':':
	    {
		if (tstr[1] == '=' ||
		    (tstr[2] == '=' &&
		     (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
		    /*
		     * "::=", "::!=", "::+=", or "::?="
		     */
		    GNode *v_ctxt;		/* context where v belongs */
		    const char *emsg;
		    char *sv_name;
		    VarPattern	pattern;
		    int	how;
		    int flags;

		    if (v->name[0] == 0)
			goto bad_modifier;

		    v_ctxt = ctxt;
		    sv_name = NULL;
		    ++tstr;
		    if (v->flags & VAR_JUNK) {
			/*
			 * We need to bmake_strdup() it incase
			 * VarGetPattern() recurses.
			 */
			sv_name = v->name;
			v->name = bmake_strdup(v->name);
		    } else if (ctxt != VAR_GLOBAL) {
			Var *gv = VarFind(v->name, ctxt, 0);
			if (gv == NULL)
			    v_ctxt = VAR_GLOBAL;
			else
			    VarFreeEnv(gv, TRUE);
		    }

		    switch ((how = *tstr)) {
		    case '+':
		    case '?':
		    case '!':
			cp = &tstr[2];
			break;
		    default:
			cp = ++tstr;
			break;
		    }
		    delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
		    pattern.flags = 0;

		    flags = (wantit) ? 0 : VAR_NOSUBST;
		    pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
						&cp, delim, &flags,
						&pattern.rightLen,
						NULL);
		    if (v->flags & VAR_JUNK) {
			/* restore original name */
			free(v->name);
			v->name = sv_name;
		    }
		    if (pattern.rhs == NULL)
			goto cleanup;

		    termc = *--cp;
		    delim = '\0';

		    if (wantit) {
			switch (how) {
			case '+':
			    Var_Append(v->name, pattern.rhs, v_ctxt);
			    break;
			case '!':
			    newStr = Cmd_Exec(pattern.rhs, &emsg);
			    if (emsg)
				Error(emsg, nstr);
			    else
				Var_Set(v->name, newStr,  v_ctxt, 0);
			    free(newStr);
			    break;
			case '?':
			    if ((v->flags & VAR_JUNK) == 0)
				break;
			    /* FALLTHROUGH */
			default:
			    Var_Set(v->name, pattern.rhs, v_ctxt, 0);
			    break;
			}
		    }
		    free(UNCONST(pattern.rhs));
		    newStr = varNoError;
		    break;
		}
		goto default_case; /* "::<unrecognised>" */
	    }
	case '@':
	    {
		VarLoop_t	loop;
		int flags = VAR_NOSUBST;

		cp = ++tstr;
		delim = '@';
		if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
					       &cp, delim,
					       &flags, &loop.tvarLen,
					       NULL)) == NULL)
		    goto cleanup;

		if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
					      &cp, delim,
					      &flags, &loop.strLen,
					      NULL)) == NULL)
		    goto cleanup;

		termc = *cp;
		delim = '\0';

		loop.errnum = errnum;
		loop.ctxt = ctxt;
		newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
				   &loop);
		free(loop.tvar);
		free(loop.str);
		break;
	    }
	case 'D':
	case 'U':
	    {
		Buffer  buf;    	/* Buffer for patterns */
		int	    wantit_;	/* want data in buffer */

		if (wantit) {
		    if (*tstr == 'U')
			wantit_ = ((v->flags & VAR_JUNK) != 0);
		    else
			wantit_ = ((v->flags & VAR_JUNK) == 0);
		} else
		    wantit_ = wantit;
		/*
		 * Pass through tstr looking for 1) escaped delimiters,
		 * '$'s and backslashes (place the escaped character in
		 * uninterpreted) and 2) unescaped $'s that aren't before
		 * the delimiter (expand the variable substitution).
		 * The result is left in the Buffer buf.
		 */
		Buf_Init(&buf, 0);
		for (cp = tstr + 1;
		     *cp != endc && *cp != ':' && *cp != '\0';
		     cp++) {
		    if ((*cp == '\\') &&
			((cp[1] == ':') ||
			 (cp[1] == '$') ||
			 (cp[1] == endc) ||
			 (cp[1] == '\\')))
			{
			    Buf_AddByte(&buf, cp[1]);
			    cp++;
			} else if (*cp == '$') {
			    /*
			     * If unescaped dollar sign, assume it's a
			     * variable substitution and recurse.
			     */
			    char    *cp2;
			    int	    len;
			    void    *freeIt;

			    cp2 = Var_Parse(cp, ctxt, errnum, wantit_, &len, &freeIt);
			    Buf_AddBytes(&buf, strlen(cp2), cp2);
			    free(freeIt);
			    cp += len - 1;
			} else {
			    Buf_AddByte(&buf, *cp);
			}
		}

		termc = *cp;

		if ((v->flags & VAR_JUNK) != 0)
		    v->flags |= VAR_KEEP;
		if (wantit_) {
		    newStr = Buf_Destroy(&buf, FALSE);
		} else {
		    newStr = nstr;
		    Buf_Destroy(&buf, TRUE);
		}
		break;
	    }
	case 'L':
	    {
		if ((v->flags & VAR_JUNK) != 0)
		    v->flags |= VAR_KEEP;
		newStr = bmake_strdup(v->name);
		cp = ++tstr;
		termc = *tstr;
		break;
	    }
	case 'P':
	    {
		GNode *gn;

		if ((v->flags & VAR_JUNK) != 0)
		    v->flags |= VAR_KEEP;
		gn = Targ_FindNode(v->name, TARG_NOCREATE);
		if (gn == NULL || gn->type & OP_NOPATH) {
		    newStr = NULL;
		} else if (gn->path) {
		    newStr = bmake_strdup(gn->path);
		} else {
		    newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
		}
		if (!newStr) {
		    newStr = bmake_strdup(v->name);
		}
		cp = ++tstr;
		termc = *tstr;
		break;
	    }
	case '!':
	    {
		const char *emsg;
		VarPattern 	    pattern;
		pattern.flags = 0;

		delim = '!';
		emsg = NULL;
		cp = ++tstr;
		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
						 &cp, delim,
						 NULL, &pattern.rightLen,
						 NULL)) == NULL)
		    goto cleanup;
		if (wantit)
		    newStr = Cmd_Exec(pattern.rhs, &emsg);
		else
		    newStr = varNoError;
		free(UNCONST(pattern.rhs));
		if (emsg)
		    Error(emsg, nstr);
		termc = *cp;
		delim = '\0';
		if (v->flags & VAR_JUNK) {
		    v->flags |= VAR_KEEP;
		}
		break;
	    }
	case '[':
	    {
		/*
		 * Look for the closing ']', recursively
		 * expanding any embedded variables.
		 *
		 * estr is a pointer to the expanded result,
		 * which we must free().
		 */
		char *estr;

		cp = tstr+1; /* point to char after '[' */
		delim = ']'; /* look for closing ']' */
		estr = VarGetPattern(ctxt, &parsestate,
				     errnum, &cp, delim,
				     NULL, NULL, NULL);
		if (estr == NULL)
		    goto cleanup; /* report missing ']' */
		/* now cp points just after the closing ']' */
		delim = '\0';
		if (cp[0] != ':' && cp[0] != endc) {
		    /* Found junk after ']' */
		    free(estr);
		    goto bad_modifier;
		}
		if (estr[0] == '\0') {
		    /* Found empty square brackets in ":[]". */
		    free(estr);
		    goto bad_modifier;
		} else if (estr[0] == '#' && estr[1] == '\0') {
		    /* Found ":[#]" */

		    /*
		     * We will need enough space for the decimal
		     * representation of an int.  We calculate the
		     * space needed for the octal representation,
		     * and add enough slop to cope with a '-' sign
		     * (which should never be needed) and a '\0'
		     * string terminator.
		     */
		    int newStrSize =
			(sizeof(int) * CHAR_BIT + 2) / 3 + 2;

		    newStr = bmake_malloc(newStrSize);
		    if (parsestate.oneBigWord) {
			strncpy(newStr, "1", newStrSize);
		    } else {
			/* XXX: brk_string() is a rather expensive
			 * way of counting words. */
			char **av;
			char *as;
			int ac;

			av = brk_string(nstr, &ac, FALSE, &as);
			snprintf(newStr, newStrSize,  "%d", ac);
			free(as);
			free(av);
		    }
		    termc = *cp;
		    free(estr);
		    break;
		} else if (estr[0] == '*' && estr[1] == '\0') {
		    /* Found ":[*]" */
		    parsestate.oneBigWord = TRUE;
		    newStr = nstr;
		    termc = *cp;
		    free(estr);
		    break;
		} else if (estr[0] == '@' && estr[1] == '\0') {
		    /* Found ":[@]" */
		    parsestate.oneBigWord = FALSE;
		    newStr = nstr;
		    termc = *cp;
		    free(estr);
		    break;
		} else {
		    /*
		     * We expect estr to contain a single
		     * integer for :[N], or two integers
		     * separated by ".." for :[start..end].
		     */
		    char *ep;

		    VarSelectWords_t seldata = { 0, 0 };

		    seldata.start = strtol(estr, &ep, 0);
		    if (ep == estr) {
			/* Found junk instead of a number */
			free(estr);
			goto bad_modifier;
		    } else if (ep[0] == '\0') {
			/* Found only one integer in :[N] */
			seldata.end = seldata.start;
		    } else if (ep[0] == '.' && ep[1] == '.' &&
			       ep[2] != '\0') {
			/* Expecting another integer after ".." */
			ep += 2;
			seldata.end = strtol(ep, &ep, 0);
			if (ep[0] != '\0') {
			    /* Found junk after ".." */
			    free(estr);
			    goto bad_modifier;
			}
		    } else {
			/* Found junk instead of ".." */
			free(estr);
			goto bad_modifier;
		    }
		    /*
		     * Now seldata is properly filled in,
		     * but we still have to check for 0 as
		     * a special case.
		     */
		    if (seldata.start == 0 && seldata.end == 0) {
			/* ":[0]" or perhaps ":[0..0]" */
			parsestate.oneBigWord = TRUE;
			newStr = nstr;
			termc = *cp;
			free(estr);
			break;
		    } else if (seldata.start == 0 ||
			       seldata.end == 0) {
			/* ":[0..N]" or ":[N..0]" */
			free(estr);
			goto bad_modifier;
		    }
		    /*
		     * Normal case: select the words
		     * described by seldata.
		     */
		    newStr = VarSelectWords(ctxt, &parsestate,
					    nstr, &seldata);

		    termc = *cp;
		    free(estr);
		    break;
		}

	    }
	case 'g':
	    cp = tstr + 1;	/* make sure it is set */
	    if (STRMOD_MATCH(tstr, "gmtime", 6)) {
		newStr = VarStrftime(nstr, 1);
		cp = tstr + 6;
		termc = *cp;
	    } else {
		goto default_case;
	    }
	    break;
	case 'h':
	    cp = tstr + 1;	/* make sure it is set */
	    if (STRMOD_MATCH(tstr, "hash", 4)) {
		newStr = VarHash(nstr);
		cp = tstr + 4;
		termc = *cp;
	    } else {
		goto default_case;
	    }
	    break;
	case 'l':
	    cp = tstr + 1;	/* make sure it is set */
	    if (STRMOD_MATCH(tstr, "localtime", 9)) {
		newStr = VarStrftime(nstr, 0);
		cp = tstr + 9;
		termc = *cp;
	    } else {
		goto default_case;
	    }
	    break;
	case 't':
	    {
		cp = tstr + 1;	/* make sure it is set */
		if (tstr[1] != endc && tstr[1] != ':') {
		    if (tstr[1] == 's') {
			/*
			 * Use the char (if any) at tstr[2]
			 * as the word separator.
			 */
			VarPattern pattern;

			if (tstr[2] != endc &&
			    (tstr[3] == endc || tstr[3] == ':')) {
			    /* ":ts<unrecognised><endc>" or
			     * ":ts<unrecognised>:" */
			    parsestate.varSpace = tstr[2];
			    cp = tstr + 3;
			} else if (tstr[2] == endc || tstr[2] == ':') {
			    /* ":ts<endc>" or ":ts:" */
			    parsestate.varSpace = 0; /* no separator */
			    cp = tstr + 2;
			} else if (tstr[2] == '\\') {
			    switch (tstr[3]) {
			    case 'n':
				parsestate.varSpace = '\n';
				cp = tstr + 4;
				break;
			    case 't':
				parsestate.varSpace = '\t';
				cp = tstr + 4;
				break;
			    default:
				if (isdigit((unsigned char)tstr[3])) {
				    char *ep;

				    parsestate.varSpace =
					strtoul(&tstr[3], &ep, 0);
				    if (*ep != ':' && *ep != endc)
					goto bad_modifier;
				    cp = ep;
				} else {
				    /*
				     * ":ts<backslash><unrecognised>".
				     */
				    goto bad_modifier;
				}
				break;
			    }
			} else {
			    /*
			     * Found ":ts<unrecognised><unrecognised>".
			     */
			    goto bad_modifier;
			}

			termc = *cp;

			/*
			 * We cannot be certain that VarModify
			 * will be used - even if there is a
			 * subsequent modifier, so do a no-op
			 * VarSubstitute now to for str to be
			 * re-expanded without the spaces.
			 */
			pattern.flags = VAR_SUB_ONE;
			pattern.lhs = pattern.rhs = "\032";
			pattern.leftLen = pattern.rightLen = 1;

			newStr = VarModify(ctxt, &parsestate, nstr,
					   VarSubstitute,
					   &pattern);
		    } else if (tstr[2] == endc || tstr[2] == ':') {
			/*
			 * Check for two-character options:
			 * ":tu", ":tl"
			 */
			if (tstr[1] == 'A') { /* absolute path */
			    newStr = VarModify(ctxt, &parsestate, nstr,
					       VarRealpath, NULL);
			    cp = tstr + 2;
			    termc = *cp;
			} else if (tstr[1] == 'u') {
			    char *dp = bmake_strdup(nstr);
			    for (newStr = dp; *dp; dp++)
				*dp = toupper((unsigned char)*dp);
			    cp = tstr + 2;
			    termc = *cp;
			} else if (tstr[1] == 'l') {
			    char *dp = bmake_strdup(nstr);
			    for (newStr = dp; *dp; dp++)
				*dp = tolower((unsigned char)*dp);
			    cp = tstr + 2;
			    termc = *cp;
			} else if (tstr[1] == 'W' || tstr[1] == 'w') {
			    parsestate.oneBigWord = (tstr[1] == 'W');
			    newStr = nstr;
			    cp = tstr + 2;
			    termc = *cp;
			} else {
			    /* Found ":t<unrecognised>:" or
			     * ":t<unrecognised><endc>". */
			    goto bad_modifier;
			}
		    } else {
			/*
			 * Found ":t<unrecognised><unrecognised>".
			 */
			goto bad_modifier;
		    }
		} else {
		    /*
		     * Found ":t<endc>" or ":t:".
		     */
		    goto bad_modifier;
		}
		break;
	    }
	case 'N':
	case 'M':
	    {
		char    *pattern;
		const char *endpat; /* points just after end of pattern */
		char    *cp2;
		Boolean copy;	/* pattern should be, or has been, copied */
		Boolean needSubst;
		int nest;

		copy = FALSE;
		needSubst = FALSE;
		nest = 1;
		/*
		 * In the loop below, ignore ':' unless we are at
		 * (or back to) the original brace level.
		 * XXX This will likely not work right if $() and ${}
		 * are intermixed.
		 */
		for (cp = tstr + 1;
		     *cp != '\0' && !(*cp == ':' && nest == 1);
		     cp++)
		    {
			if (*cp == '\\' &&
			    (cp[1] == ':' ||
			     cp[1] == endc || cp[1] == startc)) {
			    if (!needSubst) {
				copy = TRUE;
			    }
			    cp++;
			    continue;
			}
			if (*cp == '$') {
			    needSubst = TRUE;
			}
			if (*cp == '(' || *cp == '{')
			    ++nest;
			if (*cp == ')' || *cp == '}') {
			    --nest;
			    if (nest == 0)
				break;
			}
		    }
		termc = *cp;
		endpat = cp;
		if (copy) {
		    /*
		     * Need to compress the \:'s out of the pattern, so
		     * allocate enough room to hold the uncompressed
		     * pattern (note that cp started at tstr+1, so
		     * cp - tstr takes the null byte into account) and
		     * compress the pattern into the space.
		     */
		    pattern = bmake_malloc(cp - tstr);
		    for (cp2 = pattern, cp = tstr + 1;
			 cp < endpat;
			 cp++, cp2++)
			{
			    if ((*cp == '\\') && (cp+1 < endpat) &&
				(cp[1] == ':' || cp[1] == endc)) {
				cp++;
			    }
			    *cp2 = *cp;
			}
		    *cp2 = '\0';
		    endpat = cp2;
		} else {
		    /*
		     * Either Var_Subst or VarModify will need a
		     * nul-terminated string soon, so construct one now.
		     */
		    pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
		}
		if (needSubst) {
		    /*
		     * pattern contains embedded '$', so use Var_Subst to
		     * expand it.
		     */
		    cp2 = pattern;
		    pattern = Var_Subst(NULL, cp2, ctxt, errnum, TRUE);
		    free(cp2);
		}
		if (DEBUG(VAR))
		    fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
			v->name, nstr, pattern);
		if (*tstr == 'M') {
		    newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
				       pattern);
		} else {
		    newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
				       pattern);
		}
		free(pattern);
		break;
	    }
	case 'S':
	    {
		VarPattern 	    pattern;
		Var_Parse_State tmpparsestate;

		pattern.flags = 0;
		tmpparsestate = parsestate;
		delim = tstr[1];
		tstr += 2;

		/*
		 * If pattern begins with '^', it is anchored to the
		 * start of the word -- skip over it and flag pattern.
		 */
		if (*tstr == '^') {
		    pattern.flags |= VAR_MATCH_START;
		    tstr += 1;
		}

		cp = tstr;
		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
						 &cp, delim,
						 &pattern.flags,
						 &pattern.leftLen,
						 NULL)) == NULL)
		    goto cleanup;

		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
						 &cp, delim, NULL,
						 &pattern.rightLen,
						 &pattern)) == NULL)
		    goto cleanup;

		/*
		 * Check for global substitution. If 'g' after the final
		 * delimiter, substitution is global and is marked that
		 * way.
		 */
		for (;; cp++) {
		    switch (*cp) {
		    case 'g':
			pattern.flags |= VAR_SUB_GLOBAL;
			continue;
		    case '1':
			pattern.flags |= VAR_SUB_ONE;
			continue;
		    case 'W':
			tmpparsestate.oneBigWord = TRUE;
			continue;
		    }
		    break;
		}

		termc = *cp;
		newStr = VarModify(ctxt, &tmpparsestate, nstr,
				   VarSubstitute,
				   &pattern);

		/*
		 * Free the two strings.
		 */
		free(UNCONST(pattern.lhs));
		free(UNCONST(pattern.rhs));
		delim = '\0';
		break;
	    }
	case '?':
	    {
		VarPattern 	pattern;
		Boolean	value;
		int cond_rc;
		int lhs_flags, rhs_flags;
		
		/* find ':', and then substitute accordingly */
		if (wantit) {
		    cond_rc = Cond_EvalExpression(NULL, v->name, &value, 0, FALSE);
		    if (cond_rc == COND_INVALID) {
			lhs_flags = rhs_flags = VAR_NOSUBST;
		    } else if (value) {
			lhs_flags = 0;
			rhs_flags = VAR_NOSUBST;
		    } else {
			lhs_flags = VAR_NOSUBST;
			rhs_flags = 0;
		    }
		} else {
		    /* we are just consuming and discarding */
		    cond_rc = value = 0;
		    lhs_flags = rhs_flags = VAR_NOSUBST;
		}
		pattern.flags = 0;

		cp = ++tstr;
		delim = ':';
		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
						 &cp, delim, &lhs_flags,
						 &pattern.leftLen,
						 NULL)) == NULL)
		    goto cleanup;

		/* BROPEN or PROPEN */
		delim = endc;
		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
						 &cp, delim, &rhs_flags,
						 &pattern.rightLen,
						 NULL)) == NULL)
		    goto cleanup;

		termc = *--cp;
		delim = '\0';
		if (cond_rc == COND_INVALID) {
		    Error("Bad conditional expression `%s' in %s?%s:%s",
			  v->name, v->name, pattern.lhs, pattern.rhs);
		    goto cleanup;
		}

		if (value) {
		    newStr = UNCONST(pattern.lhs);
		    free(UNCONST(pattern.rhs));
		} else {
		    newStr = UNCONST(pattern.rhs);
		    free(UNCONST(pattern.lhs));
		}
		if (v->flags & VAR_JUNK) {
		    v->flags |= VAR_KEEP;
		}
		break;
	    }
#ifndef NO_REGEX
	case 'C':
	    {
		VarREPattern    pattern;
		char           *re;
		int             error;
		Var_Parse_State tmpparsestate;

		pattern.flags = 0;
		tmpparsestate = parsestate;
		delim = tstr[1];
		tstr += 2;

		cp = tstr;

		if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
					NULL, NULL, NULL)) == NULL)
		    goto cleanup;

		if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
						     errnum, &cp, delim, NULL,
						     NULL, NULL)) == NULL){
		    free(re);
		    goto cleanup;
		}

		for (;; cp++) {
		    switch (*cp) {
		    case 'g':
			pattern.flags |= VAR_SUB_GLOBAL;
			continue;
		    case '1':
			pattern.flags |= VAR_SUB_ONE;
			continue;
		    case 'W':
			tmpparsestate.oneBigWord = TRUE;
			continue;
		    }
		    break;
		}

		termc = *cp;

		error = regcomp(&pattern.re, re, REG_EXTENDED);
		free(re);
		if (error)  {
		    *lengthPtr = cp - start + 1;
		    VarREError(error, &pattern.re, "RE substitution error");
		    free(pattern.replace);
		    goto cleanup;
		}

		pattern.nsub = pattern.re.re_nsub + 1;
		if (pattern.nsub < 1)
		    pattern.nsub = 1;
		if (pattern.nsub > 10)
		    pattern.nsub = 10;
		pattern.matches = bmake_malloc(pattern.nsub *
					  sizeof(regmatch_t));
		newStr = VarModify(ctxt, &tmpparsestate, nstr,
				   VarRESubstitute,
				   &pattern);
		regfree(&pattern.re);
		free(pattern.replace);
		free(pattern.matches);
		delim = '\0';
		break;
	    }
#endif
	case 'Q':
	    if (tstr[1] == endc || tstr[1] == ':') {
		newStr = VarQuote(nstr);
		cp = tstr + 1;
		termc = *cp;
		break;
	    }
	    goto default_case;
	case 'T':
	    if (tstr[1] == endc || tstr[1] == ':') {
		newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
				   NULL);
		cp = tstr + 1;
		termc = *cp;
		break;
	    }
	    goto default_case;
	case 'H':
	    if (tstr[1] == endc || tstr[1] == ':') {
		newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
				   NULL);
		cp = tstr + 1;
		termc = *cp;
		break;
	    }
	    goto default_case;
	case 'E':
	    if (tstr[1] == endc || tstr[1] == ':') {
		newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
				   NULL);
		cp = tstr + 1;
		termc = *cp;
		break;
	    }
	    goto default_case;
	case 'R':
	    if (tstr[1] == endc || tstr[1] == ':') {
		newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
				   NULL);
		cp = tstr + 1;
		termc = *cp;
		break;
	    }
	    goto default_case;
	case 'O':
	    {
		char otype;

		cp = tstr + 1;	/* skip to the rest in any case */
		if (tstr[1] == endc || tstr[1] == ':') {
		    otype = 's';
		    termc = *cp;
		} else if ( (tstr[1] == 'x') &&
			    (tstr[2] == endc || tstr[2] == ':') ) {
		    otype = tstr[1];
		    cp = tstr + 2;
		    termc = *cp;
		} else {
		    goto bad_modifier;
		}
		newStr = VarOrder(nstr, otype);
		break;
	    }
	case 'u':
	    if (tstr[1] == endc || tstr[1] == ':') {
		newStr = VarUniq(nstr);
		cp = tstr + 1;
		termc = *cp;
		break;
	    }
	    goto default_case;
#ifdef SUNSHCMD
	case 's':
	    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
		const char *emsg;
		if (wantit) {
		    newStr = Cmd_Exec(nstr, &emsg);
		    if (emsg)
			Error(emsg, nstr);
		} else
		    newStr = varNoError;
		cp = tstr + 2;
		termc = *cp;
		break;
	    }
	    goto default_case;
#endif
	default:
	default_case:
	{
#ifdef SYSVVARSUB
	    /*
	     * This can either be a bogus modifier or a System-V
	     * substitution command.
	     */
	    VarPattern      pattern;
	    Boolean         eqFound;

	    pattern.flags = 0;
	    eqFound = FALSE;
	    /*
	     * First we make a pass through the string trying
	     * to verify it is a SYSV-make-style translation:
	     * it must be: <string1>=<string2>)
	     */
	    cp = tstr;
	    cnt = 1;
	    while (*cp != '\0' && cnt) {
		if (*cp == '=') {
		    eqFound = TRUE;
		    /* continue looking for endc */
		}
		else if (*cp == endc)
		    cnt--;
		else if (*cp == startc)
		    cnt++;
		if (cnt)
		    cp++;
	    }
	    if (*cp == endc && eqFound) {

		/*
		 * Now we break this sucker into the lhs and
		 * rhs. We must null terminate them of course.
		 */
		delim='=';
		cp = tstr;
		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
						 errnum, &cp, delim, &pattern.flags,
						 &pattern.leftLen, NULL)) == NULL)
		    goto cleanup;
		delim = endc;
		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
						 errnum, &cp, delim, NULL, &pattern.rightLen,
						 &pattern)) == NULL)
		    goto cleanup;

		/*
		 * SYSV modifications happen through the whole
		 * string. Note the pattern is anchored at the end.
		 */
		termc = *--cp;
		delim = '\0';
		if (pattern.leftLen == 0 && *nstr == '\0') {
		    newStr = nstr;	/* special case */
		} else {
		    newStr = VarModify(ctxt, &parsestate, nstr,
				       VarSYSVMatch,
				       &pattern);
		}
		free(UNCONST(pattern.lhs));
		free(UNCONST(pattern.rhs));
	    } else
#endif
		{
		    Error("Unknown modifier '%c'", *tstr);
		    for (cp = tstr+1;
			 *cp != ':' && *cp != endc && *cp != '\0';
			 cp++)
			continue;
		    termc = *cp;
		    newStr = var_Error;
		}
	    }
	}
	if (DEBUG(VAR)) {
	    fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
		v->name, modifier, newStr);
	}

	if (newStr != nstr) {
	    if (*freePtr) {
		free(nstr);
		*freePtr = NULL;
	    }
	    nstr = newStr;
	    if (nstr != var_Error && nstr != varNoError) {
		*freePtr = nstr;
	    }
	}
	if (termc == '\0' && endc != '\0') {
	    Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
	} else if (termc == ':') {
	    cp++;
	}
	tstr = cp;
    }
 out:
    *lengthPtr = tstr - start;
    return (nstr);

 bad_modifier:
    /* "{(" */
    Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
	  v->name);

 cleanup:
    *lengthPtr = cp - start;
    if (delim != '\0')
	Error("Unclosed substitution for %s (%c missing)",
	      v->name, delim);
    free(*freePtr);
    *freePtr = NULL;
    return (var_Error);
}

/*-
 *-----------------------------------------------------------------------
 * Var_Parse --
 *	Given the start of a variable invocation, extract the variable
 *	name and find its value, then modify it according to the
 *	specification.
 *
 * Input:
 *	str		The string to parse
 *	ctxt		The context for the variable
 *	errnum		TRUE if undefined variables are an error
 *	wantit		TRUE if we actually want the result
 *	lengthPtr	OUT: The length of the specification
 *	freePtr		OUT: Non-NULL if caller should free *freePtr
 *
 * Results:
 *	The (possibly-modified) value of the variable or var_Error if the
 *	specification is invalid. The length of the specification is
 *	placed in *lengthPtr (for invalid specifications, this is just
 *	2...?).
 *	If *freePtr is non-NULL then it's a pointer that the caller
 *	should pass to free() to free memory used by the result.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
/* coverity[+alloc : arg-*4] */
char *
Var_Parse(const char *str, GNode *ctxt,
	   Boolean errnum, Boolean wantit,
	   int *lengthPtr, void **freePtr)
{
    const char	   *tstr;    	/* Pointer into str */
    Var		   *v;		/* Variable in invocation */
    Boolean 	    haveModifier;/* TRUE if have modifiers for the variable */
    char	    endc;    	/* Ending character when variable in parens
				 * or braces */
    char	    startc;	/* Starting character when variable in parens
				 * or braces */
    int		    vlen;	/* Length of variable name */
    const char 	   *start;	/* Points to original start of str */
    char	   *nstr;	/* New string, used during expansion */
    Boolean 	    dynamic;	/* TRUE if the variable is local and we're
				 * expanding it in a non-local context. This
				 * is done to support dynamic sources. The
				 * result is just the invocation, unaltered */
    const char     *extramodifiers; /* extra modifiers to apply first */
    char	  name[2];

    *freePtr = NULL;
    extramodifiers = NULL;
    dynamic = FALSE;
    start = str;

    startc = str[1];
    if (startc != PROPEN && startc != BROPEN) {
	/*
	 * If it's not bounded by braces of some sort, life is much simpler.
	 * We just need to check for the first character and return the
	 * value if it exists.
	 */

	/* Error out some really stupid names */
	if (startc == '\0' || strchr(")}:$", startc)) {
	    *lengthPtr = 1;
	    return var_Error;
	}
	name[0] = startc;
	name[1] = '\0';

	v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
	if (v == NULL) {
	    *lengthPtr = 2;

	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
		/*
		 * If substituting a local variable in a non-local context,
		 * assume it's for dynamic source stuff. We have to handle
		 * this specially and return the longhand for the variable
		 * with the dollar sign escaped so it makes it back to the
		 * caller. Only four of the local variables are treated
		 * specially as they are the only four that will be set
		 * when dynamic sources are expanded.
		 */
		switch (str[1]) {
		    case '@':
			return UNCONST("$(.TARGET)");
		    case '%':
			return UNCONST("$(.ARCHIVE)");
		    case '*':
			return UNCONST("$(.PREFIX)");
		    case '!':
			return UNCONST("$(.MEMBER)");
		}
	    }
	    /*
	     * Error
	     */
	    return (errnum ? var_Error : varNoError);
	} else {
	    haveModifier = FALSE;
	    tstr = &str[1];
	    endc = str[1];
	}
    } else {
	Buffer buf;	/* Holds the variable name */
	int depth = 1;

	endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
	Buf_Init(&buf, 0);

	/*
	 * Skip to the end character or a colon, whichever comes first.
	 */
	for (tstr = str + 2; *tstr != '\0'; tstr++)
	{
	    /*
	     * Track depth so we can spot parse errors.
	     */
	    if (*tstr == startc) {
		depth++;
	    }
	    if (*tstr == endc) {
		if (--depth == 0)
		    break;
	    }
	    if (depth == 1 && *tstr == ':') {
		break;
	    }
	    /*
	     * A variable inside a variable, expand
	     */
	    if (*tstr == '$') {
		int rlen;
		void *freeIt;
		char *rval = Var_Parse(tstr, ctxt, errnum, wantit, &rlen, &freeIt);
		if (rval != NULL) {
		    Buf_AddBytes(&buf, strlen(rval), rval);
		}
		free(freeIt);
		tstr += rlen - 1;
	    }
	    else
		Buf_AddByte(&buf, *tstr);
	}
	if (*tstr == ':') {
	    haveModifier = TRUE;
	} else if (*tstr == endc) {
	    haveModifier = FALSE;
	} else {
	    /*
	     * If we never did find the end character, return NULL
	     * right now, setting the length to be the distance to
	     * the end of the string, since that's what make does.
	     */
	    *lengthPtr = tstr - str;
	    Buf_Destroy(&buf, TRUE);
	    return (var_Error);
	}
	str = Buf_GetAll(&buf, &vlen);

	/*
	 * At this point, str points into newly allocated memory from
	 * buf, containing only the name of the variable.
	 *
	 * start and tstr point into the const string that was pointed
	 * to by the original value of the str parameter.  start points
	 * to the '$' at the beginning of the string, while tstr points
	 * to the char just after the end of the variable name -- this
	 * will be '\0', ':', PRCLOSE, or BRCLOSE.
	 */

	v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
	/*
	 * Check also for bogus D and F forms of local variables since we're
	 * in a local context and the name is the right length.
	 */
	if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
		(vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
		strchr("@%?*!<>", str[0]) != NULL) {
	    /*
	     * Well, it's local -- go look for it.
	     */
	    name[0] = *str;
	    name[1] = '\0';
	    v = VarFind(name, ctxt, 0);

	    if (v != NULL) {
		if (str[1] == 'D') {
			extramodifiers = "H:";
		}
		else { /* F */
			extramodifiers = "T:";
		}
	    }
	}

	if (v == NULL) {
	    if (((vlen == 1) ||
		 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
	    {
		/*
		 * If substituting a local variable in a non-local context,
		 * assume it's for dynamic source stuff. We have to handle
		 * this specially and return the longhand for the variable
		 * with the dollar sign escaped so it makes it back to the
		 * caller. Only four of the local variables are treated
		 * specially as they are the only four that will be set
		 * when dynamic sources are expanded.
		 */
		switch (*str) {
		    case '@':
		    case '%':
		    case '*':
		    case '!':
			dynamic = TRUE;
			break;
		}
	    } else if ((vlen > 2) && (*str == '.') &&
		       isupper((unsigned char) str[1]) &&
		       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
	    {
		int	len;

		len = vlen - 1;
		if ((strncmp(str, ".TARGET", len) == 0) ||
		    (strncmp(str, ".ARCHIVE", len) == 0) ||
		    (strncmp(str, ".PREFIX", len) == 0) ||
		    (strncmp(str, ".MEMBER", len) == 0))
		{
		    dynamic = TRUE;
		}
	    }

	    if (!haveModifier) {
		/*
		 * No modifiers -- have specification length so we can return
		 * now.
		 */
		*lengthPtr = tstr - start + 1;
		if (dynamic) {
		    char *pstr = bmake_strndup(start, *lengthPtr);
		    *freePtr = pstr;
		    Buf_Destroy(&buf, TRUE);
		    return(pstr);
		} else {
		    Buf_Destroy(&buf, TRUE);
		    return (errnum ? var_Error : varNoError);
		}
	    } else {
		/*
		 * Still need to get to the end of the variable specification,
		 * so kludge up a Var structure for the modifications
		 */
		v = bmake_malloc(sizeof(Var));
		v->name = UNCONST(str);
		Buf_Init(&v->val, 1);
		v->flags = VAR_JUNK;
		Buf_Destroy(&buf, FALSE);
	    }
	} else
	    Buf_Destroy(&buf, TRUE);
    }

    if (v->flags & VAR_IN_USE) {
	Fatal("Variable %s is recursive.", v->name);
	/*NOTREACHED*/
    } else {
	v->flags |= VAR_IN_USE;
    }
    /*
     * Before doing any modification, we have to make sure the value
     * has been fully expanded. If it looks like recursion might be
     * necessary (there's a dollar sign somewhere in the variable's value)
     * we just call Var_Subst to do any other substitutions that are
     * necessary. Note that the value returned by Var_Subst will have
     * been dynamically-allocated, so it will need freeing when we
     * return.
     */
    nstr = Buf_GetAll(&v->val, NULL);
    if (strchr(nstr, '$') != NULL) {
	nstr = Var_Subst(NULL, nstr, ctxt, errnum, wantit);
	*freePtr = nstr;
    }

    v->flags &= ~VAR_IN_USE;

    if ((nstr != NULL) && (haveModifier || extramodifiers != NULL)) {
	void *extraFree;
	int used;

	extraFree = NULL;
	if (extramodifiers != NULL) {
		nstr = ApplyModifiers(nstr, extramodifiers, '(', ')',
				      v, ctxt, errnum, wantit, &used, &extraFree);
	}

	if (haveModifier) {
		/* Skip initial colon. */
		tstr++;

		nstr = ApplyModifiers(nstr, tstr, startc, endc,
				      v, ctxt, errnum, wantit, &used, freePtr);
		tstr += used;
		free(extraFree);
	} else {
		*freePtr = extraFree;
	}
    }
    if (*tstr) {
	*lengthPtr = tstr - start + 1;
    } else {
	*lengthPtr = tstr - start;
    }

    if (v->flags & VAR_FROM_ENV) {
	Boolean	  destroy = FALSE;

	if (nstr != Buf_GetAll(&v->val, NULL)) {
	    destroy = TRUE;
	} else {
	    /*
	     * Returning the value unmodified, so tell the caller to free
	     * the thing.
	     */
	    *freePtr = nstr;
	}
	VarFreeEnv(v, destroy);
    } else if (v->flags & VAR_JUNK) {
	/*
	 * Perform any free'ing needed and set *freePtr to NULL so the caller
	 * doesn't try to free a static pointer.
	 * If VAR_KEEP is also set then we want to keep str as is.
	 */
	if (!(v->flags & VAR_KEEP)) {
	    if (*freePtr) {
		free(nstr);
		*freePtr = NULL;
	    }
	    if (dynamic) {
		nstr = bmake_strndup(start, *lengthPtr);
		*freePtr = nstr;
	    } else {
		nstr = errnum ? var_Error : varNoError;
	    }
	}
	if (nstr != Buf_GetAll(&v->val, NULL))
	    Buf_Destroy(&v->val, TRUE);
	free(v->name);
	free(v);
    }
    return (nstr);
}

/*-
 *-----------------------------------------------------------------------
 * Var_Subst  --
 *	Substitute for all variables in the given string in the given context
 *	If undefErr is TRUE, Parse_Error will be called when an undefined
 *	variable is encountered.
 *
 * Input:
 *	var		Named variable || NULL for all
 *	str		the string which to substitute
 *	ctxt		the context wherein to find variables
 *	undefErr	TRUE if undefineds are an error
 *	wantit		TRUE if we actually want the result
 *
 * Results:
 *	The resulting string.
 *
 * Side Effects:
 *	None. The old string must be freed by the caller
 *-----------------------------------------------------------------------
 */
char *
Var_Subst(const char *var, const char *str, GNode *ctxt,
	   Boolean undefErr, Boolean wantit)
{
    Buffer  	  buf;		    /* Buffer for forming things */
    char    	  *val;		    /* Value to substitute for a variable */
    int		  length;   	    /* Length of the variable invocation */
    Boolean	  trailingBslash;   /* variable ends in \ */
    void 	  *freeIt = NULL;    /* Set if it should be freed */
    static Boolean errorReported;   /* Set true if an error has already
				     * been reported to prevent a plethora
				     * of messages when recursing */

    Buf_Init(&buf, 0);
    errorReported = FALSE;
    trailingBslash = FALSE;

    while (*str) {
	if (*str == '\n' && trailingBslash)
	    Buf_AddByte(&buf, ' ');
	if (var == NULL && (*str == '$') && (str[1] == '$')) {
	    /*
	     * A dollar sign may be escaped either with another dollar sign.
	     * In such a case, we skip over the escape character and store the
	     * dollar sign into the buffer directly.
	     */
	    str++;
	    Buf_AddByte(&buf, *str);
	    str++;
	} else if (*str != '$') {
	    /*
	     * Skip as many characters as possible -- either to the end of
	     * the string or to the next dollar sign (variable invocation).
	     */
	    const char  *cp;

	    for (cp = str++; *str != '$' && *str != '\0'; str++)
		continue;
	    Buf_AddBytes(&buf, str - cp, cp);
	} else {
	    if (var != NULL) {
		int expand;
		for (;;) {
		    if (str[1] == '\0') {
			/* A trailing $ is kind of a special case */
			Buf_AddByte(&buf, str[0]);
			str++;
			expand = FALSE;
		    } else if (str[1] != PROPEN && str[1] != BROPEN) {
			if (str[1] != *var || strlen(var) > 1) {
			    Buf_AddBytes(&buf, 2, str);
			    str += 2;
			    expand = FALSE;
			}
			else
			    expand = TRUE;
			break;
		    }
		    else {
			const char *p;

			/*
			 * Scan up to the end of the variable name.
			 */
			for (p = &str[2]; *p &&
			     *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
			    if (*p == '$')
				break;
			/*
			 * A variable inside the variable. We cannot expand
			 * the external variable yet, so we try again with
			 * the nested one
			 */
			if (*p == '$') {
			    Buf_AddBytes(&buf, p - str, str);
			    str = p;
			    continue;
			}

			if (strncmp(var, str + 2, p - str - 2) != 0 ||
			    var[p - str - 2] != '\0') {
			    /*
			     * Not the variable we want to expand, scan
			     * until the next variable
			     */
			    for (;*p != '$' && *p != '\0'; p++)
				continue;
			    Buf_AddBytes(&buf, p - str, str);
			    str = p;
			    expand = FALSE;
			}
			else
			    expand = TRUE;
			break;
		    }
		}
		if (!expand)
		    continue;
	    }

	    val = Var_Parse(str, ctxt, undefErr, wantit, &length, &freeIt);

	    /*
	     * When we come down here, val should either point to the
	     * value of this variable, suitably modified, or be NULL.
	     * Length should be the total length of the potential
	     * variable invocation (from $ to end character...)
	     */
	    if (val == var_Error || val == varNoError) {
		/*
		 * If performing old-time variable substitution, skip over
		 * the variable and continue with the substitution. Otherwise,
		 * store the dollar sign and advance str so we continue with
		 * the string...
		 */
		if (oldVars) {
		    str += length;
		} else if (undefErr || val == var_Error) {
		    /*
		     * If variable is undefined, complain and skip the
		     * variable. The complaint will stop us from doing anything
		     * when the file is parsed.
		     */
		    if (!errorReported) {
			Parse_Error(PARSE_FATAL,
				     "Undefined variable \"%.*s\"",length,str);
		    }
		    str += length;
		    errorReported = TRUE;
		} else {
		    Buf_AddByte(&buf, *str);
		    str += 1;
		}
	    } else {
		/*
		 * We've now got a variable structure to store in. But first,
		 * advance the string pointer.
		 */
		str += length;

		/*
		 * Copy all the characters from the variable value straight
		 * into the new string.
		 */
		length = strlen(val);
		Buf_AddBytes(&buf, length, val);
		trailingBslash = length > 0 && val[length - 1] == '\\';
	    }
	    free(freeIt);
	    freeIt = NULL;
	}
    }

    return Buf_DestroyCompact(&buf);
}

/*-
 *-----------------------------------------------------------------------
 * Var_GetTail --
 *	Return the tail from each of a list of words. Used to set the
 *	System V local variables.
 *
 * Input:
 *	file		Filename to modify
 *
 * Results:
 *	The resulting string.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
#if 0
char *
Var_GetTail(char *file)
{
    return(VarModify(file, VarTail, NULL));
}

/*-
 *-----------------------------------------------------------------------
 * Var_GetHead --
 *	Find the leading components of a (list of) filename(s).
 *	XXX: VarHead does not replace foo by ., as (sun) System V make
 *	does.
 *
 * Input:
 *	file		Filename to manipulate
 *
 * Results:
 *	The leading components.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
char *
Var_GetHead(char *file)
{
    return(VarModify(file, VarHead, NULL));
}
#endif

/*-
 *-----------------------------------------------------------------------
 * Var_Init --
 *	Initialize the module
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	The VAR_CMD and VAR_GLOBAL contexts are created
 *-----------------------------------------------------------------------
 */
void
Var_Init(void)
{
    VAR_INTERNAL = Targ_NewGN("Internal");
    VAR_GLOBAL = Targ_NewGN("Global");
    VAR_CMD = Targ_NewGN("Command");

}


void
Var_End(void)
{
}


/****************** PRINT DEBUGGING INFO *****************/
static void
VarPrintVar(void *vp)
{
    Var    *v = (Var *)vp;
    fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
}

/*-
 *-----------------------------------------------------------------------
 * Var_Dump --
 *	print all variables in a context
 *-----------------------------------------------------------------------
 */
void
Var_Dump(GNode *ctxt)
{
    Hash_Search search;
    Hash_Entry *h;

    for (h = Hash_EnumFirst(&ctxt->context, &search);
	 h != NULL;
	 h = Hash_EnumNext(&search)) {
	    VarPrintVar(Hash_GetValue(h));
    }
}
OpenPOWER on IntegriCloud