Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 327551719cafe8e15502c3bd93593debd39c845a (plain) (blame)
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
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
/*******************************************************************************
 * Copyright (c) 2003, 2022 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Rational Software - Initial API and implementation
 *     ARM Ltd. - Minor changes to echo commands
 *     IBM Corporation
 *     Anna Dushistova  (Mentor Graphics) - [307244] extend visibility of fields in GnuMakefileGenerator
 *     James Blackburn (Broadcom Corp.)
 *     Marc-Andre Laperle
 *     Liviu Ionescu - [322168]
 *     Dorothea Pilz-Roeder (Advantest Europe GmbH) - [180451]
 *     John Dallaway - [580441] fix processing on source folder deletion
 *******************************************************************************/
package org.eclipse.cdt.managedbuilder.makegen.gnu2;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.settings.model.CSourceEntry;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICSettingEntry;
import org.eclipse.cdt.core.settings.model.ICSourceEntry;
import org.eclipse.cdt.core.settings.model.util.CDataUtil;
import org.eclipse.cdt.core.settings.model.util.IPathSettingsContainerVisitor;
import org.eclipse.cdt.core.settings.model.util.PathSettingsContainer;
import org.eclipse.cdt.managedbuilder.core.BuildException;
import org.eclipse.cdt.managedbuilder.core.IBuildObject;
import org.eclipse.cdt.managedbuilder.core.IBuilder;
import org.eclipse.cdt.managedbuilder.core.IConfiguration;
import org.eclipse.cdt.managedbuilder.core.IFileInfo;
import org.eclipse.cdt.managedbuilder.core.IFolderInfo;
import org.eclipse.cdt.managedbuilder.core.IInputType;
import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo;
import org.eclipse.cdt.managedbuilder.core.IManagedCommandLineGenerator;
import org.eclipse.cdt.managedbuilder.core.IManagedCommandLineInfo;
import org.eclipse.cdt.managedbuilder.core.IManagedOutputNameProvider;
import org.eclipse.cdt.managedbuilder.core.IOption;
import org.eclipse.cdt.managedbuilder.core.IOutputType;
import org.eclipse.cdt.managedbuilder.core.IResourceInfo;
import org.eclipse.cdt.managedbuilder.core.ITool;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin;
import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages;
import org.eclipse.cdt.managedbuilder.internal.core.Tool;
import org.eclipse.cdt.managedbuilder.internal.macros.BuildMacroProvider;
import org.eclipse.cdt.managedbuilder.internal.macros.FileContextData;
import org.eclipse.cdt.managedbuilder.macros.BuildMacroException;
import org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider;
import org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator;
import org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator2;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyCalculator;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyCommands;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGenerator;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGenerator2;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGeneratorType;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyInfo;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyPreBuild;
import org.eclipse.cdt.managedbuilder.makegen.gnu.DefaultGCCDependencyCalculator3;
import org.eclipse.cdt.managedbuilder.makegen.gnu.GnuDependencyGroupInfo;
import org.eclipse.cdt.utils.EFSExtensionManager;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;

/**
 * This is a specialized makefile generator that takes advantage of the
 * extensions present in Gnu Make.
 * <p>
 * If sub-classing and using {@link DefaultGCCDependencyCalculator3}, make sure to also override
 * {@link DefaultGCCDependencyCalculator3#createMakefileGenerator()} to return the appropriate result.
 *
 * @since 1.2
 * @noinstantiate This class is not intended to be instantiated by clients.
 */
public class GnuMakefileGenerator implements IManagedBuilderMakefileGenerator2 {
	private static final IPath DOT_SLASH_PATH = new Path("./"); //$NON-NLS-1$

	private Pattern doubleQuotedOption = Pattern.compile("--?[a-zA-Z]+.*?\\\".*?\\\".*"); //$NON-NLS-1$
	private Pattern singleQuotedOption = Pattern.compile("--?[a-zA-Z]+.*?'.*?'.*"); //$NON-NLS-1$

	/**
	 * This class walks the delta supplied by the build system to determine
	 * what resources have been changed. The logic is very simple. If a
	 * buildable resource (non-header) has been added or removed, the directories
	 * in which they are located are "dirty" so the makefile fragments for them
	 * have to be regenerated.
	 * <p>
	 * The actual dependencies are recalculated as a result of the build step
	 * itself. We are relying on make to do the right things when confronted
	 * with a dependency on a moved header file. That said, make will treat
	 * the missing header file in a dependency rule as a target it has to build
	 * unless told otherwise. These dummy targets are added to the makefile
	 * to avoid a missing target error.
	 */
	public class ResourceDeltaVisitor implements IResourceDeltaVisitor {
		private final GnuMakefileGenerator generator;
		//		private IManagedBuildInfo info;
		private final IConfiguration config;

		/**
		 * The constructor
		 */
		public ResourceDeltaVisitor(GnuMakefileGenerator generator, IManagedBuildInfo info) {
			this.generator = generator;
			this.config = info.getDefaultConfiguration();
		}

		public ResourceDeltaVisitor(GnuMakefileGenerator generator, IConfiguration cfg) {
			this.generator = generator;
			this.config = cfg;
		}

		/* (non-Javadoc)
		 * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
		 */
		@Override
		public boolean visit(IResourceDelta delta) throws CoreException {
			// Should the visitor keep iterating in current directory
			boolean keepLooking = false;
			IResource resource = delta.getResource();
			IResourceInfo rcInfo = config.getResourceInfo(resource.getProjectRelativePath(), false);
			IFolderInfo fo = null;
			boolean isSource = isSource(resource.getProjectRelativePath());
			if (rcInfo instanceof IFolderInfo) {
				fo = (IFolderInfo) rcInfo;
			}
			// What kind of resource change has occurred
			if (/*!rcInfo.isExcluded() && */isSource) {
				if (resource.getType() == IResource.FILE) {
					String ext = resource.getFileExtension();
					switch (delta.getKind()) {
					case IResourceDelta.ADDED:
						if (!generator.isGeneratedResource(resource)) {
							// This is a source file so just add its container
							if (fo == null || fo.buildsFileType(ext)) {
								generator.appendModifiedSubdirectory(resource);
							}
						}
						break;
					case IResourceDelta.REMOVED:
						// we get this notification if a resource is moved too
						if (!generator.isGeneratedResource(resource)) {
							// This is a source file so just add its container
							if (fo == null || fo.buildsFileType(ext)) {
								generator.appendDeletedFile(resource);
								if (resource.getParent().exists()) {
									generator.appendModifiedSubdirectory(resource);
								}
							}
						}
						break;
					default:
						keepLooking = true;
						break;
					}
				}

				if (resource.getType() == IResource.FOLDER) {
					// I only care about delete event
					switch (delta.getKind()) {
					case IResourceDelta.REMOVED:
						if (!generator.isGeneratedResource(resource)) {
							generator.appendDeletedSubdirectory((IContainer) resource);
						}
						break;
					}
				}
			}
			if (resource.getType() == IResource.PROJECT) {
				// If there is a zero-length delta, something the project depends on has changed so just call make
				IResourceDelta[] children = delta.getAffectedChildren();
				if (children != null && children.length > 0) {
					keepLooking = true;
				}
			} else {
				// If the resource is part of the generated directory structure don't recurse
				if (resource.getType() == IResource.ROOT || (isSource && !generator.isGeneratedResource(resource))) {
					keepLooking = true;
				}
			}

			return keepLooking;
		}
	}

	/**
	 * This class is used to recursively walk the project and determine which
	 * modules contribute buildable source files.
	 */
	protected class ResourceProxyVisitor implements IResourceProxyVisitor {
		private final GnuMakefileGenerator generator;
		private final IConfiguration config;
		//		private IManagedBuildInfo info;

		/**
		 * Constructs a new resource proxy visitor to quickly visit project
		 * resources.
		 */
		public ResourceProxyVisitor(GnuMakefileGenerator generator, IManagedBuildInfo info) {
			this.generator = generator;
			this.config = info.getDefaultConfiguration();
		}

		public ResourceProxyVisitor(GnuMakefileGenerator generator, IConfiguration cfg) {
			this.generator = generator;
			this.config = cfg;
		}

		/* (non-Javadoc)
		 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
		 */
		@Override
		public boolean visit(IResourceProxy proxy) throws CoreException {
			// No point in proceeding, is there
			if (generator == null) {
				return false;
			}

			IResource resource = proxy.requestResource();
			boolean isSource = isSource(resource.getProjectRelativePath());

			// Is this a resource we should even consider
			if (proxy.getType() == IResource.FILE) {
				// If this resource has a Resource Configuration and is not excluded or
				// if it has a file extension that one of the tools builds, add the sudirectory to the list
				//				boolean willBuild = false;
				IResourceInfo rcInfo = config.getResourceInfo(resource.getProjectRelativePath(), false);
				if (isSource/* && !rcInfo.isExcluded()*/) {
					boolean willBuild = false;
					if (rcInfo instanceof IFolderInfo) {
						String ext = resource.getFileExtension();
						if (((IFolderInfo) rcInfo).buildsFileType(ext) &&
						// If this file resource is a generated resource, then it is uninteresting
								!generator.isGeneratedResource(resource)) {
							willBuild = true;
						}
					} else {
						willBuild = true;
					}

					if (willBuild)
						generator.appendBuildSubdirectory(resource);
				}
				//				if (willBuild) {
				//					if ((resConfig == null) || (!(resConfig.isExcluded()))) {
				//						generator.appendBuildSubdirectory(resource);
				//					}
				//				}
				return false;
			} else if (proxy.getType() == IResource.FOLDER) {

				if (!isSource || generator.isGeneratedResource(resource))
					return false;
				return true;
			}

			// Recurse into subdirectories
			return true;
		}

	}

	// String constants for makefile contents and messages
	private static final String COMMENT = "MakefileGenerator.comment"; //$NON-NLS-1$
	//private static final String AUTO_DEP = COMMENT + ".autodeps";	//$NON-NLS-1$
	//private static final String MESSAGE = "ManagedMakeBuilder.message";	//$NON-NLS-1$
	//private static final String BUILD_ERROR = MESSAGE + ".error";	//$NON-NLS-1$

	//private static final String DEP_INCL = COMMENT + ".module.dep.includes";	//$NON-NLS-1$
	private static final String HEADER = COMMENT + ".header"; //$NON-NLS-1$

	protected static final String MESSAGE_FINISH_BUILD = ManagedMakeMessages
			.getResourceString("MakefileGenerator.message.finish.build"); //$NON-NLS-1$
	protected static final String MESSAGE_FINISH_FILE = ManagedMakeMessages
			.getResourceString("MakefileGenerator.message.finish.file"); //$NON-NLS-1$
	protected static final String MESSAGE_START_BUILD = ManagedMakeMessages
			.getResourceString("MakefileGenerator.message.start.build"); //$NON-NLS-1$
	protected static final String MESSAGE_START_FILE = ManagedMakeMessages
			.getResourceString("MakefileGenerator.message.start.file"); //$NON-NLS-1$
	protected static final String MESSAGE_START_DEPENDENCY = ManagedMakeMessages
			.getResourceString("MakefileGenerator.message.start.dependency"); //$NON-NLS-1$
	protected static final String MESSAGE_NO_TARGET_TOOL = ManagedMakeMessages
			.getResourceString("MakefileGenerator.message.no.target"); //$NON-NLS-1$
	//private static final String MOD_INCL = COMMENT + ".module.make.includes";	//$NON-NLS-1$
	private static final String MOD_LIST = COMMENT + ".module.list"; //$NON-NLS-1$
	private static final String MOD_VARS = COMMENT + ".module.variables"; //$NON-NLS-1$
	private static final String MOD_RULES = COMMENT + ".build.rule"; //$NON-NLS-1$
	private static final String BUILD_TOP = COMMENT + ".build.toprules"; //$NON-NLS-1$
	private static final String ALL_TARGET = COMMENT + ".build.alltarget"; //$NON-NLS-1$
	private static final String MAINBUILD_TARGET = COMMENT + ".build.mainbuildtarget"; //$NON-NLS-1$
	private static final String BUILD_TARGETS = COMMENT + ".build.toptargets"; //$NON-NLS-1$
	private static final String SRC_LISTS = COMMENT + ".source.list"; //$NON-NLS-1$

	private static final String EMPTY_STRING = ""; //$NON-NLS-1$
	private static final String[] EMPTY_STRING_ARRAY = new String[0];

	private static final String OBJS_MACRO = "OBJS"; //$NON-NLS-1$
	private static final String MACRO_ADDITION_ADDPREFIX_HEADER = "${addprefix "; //$NON-NLS-1$
	private static final String MACRO_ADDITION_ADDPREFIX_SUFFIX = "," + WHITESPACE + LINEBREAK; //$NON-NLS-1$
	private static final String MACRO_ADDITION_PREFIX_SUFFIX = "+=" + WHITESPACE + LINEBREAK; //$NON-NLS-1$
	private static final String PREBUILD = "pre-build"; //$NON-NLS-1$
	private static final String MAINBUILD = "main-build"; //$NON-NLS-1$
	private static final String POSTBUILD = "post-build"; //$NON-NLS-1$
	private static final String SECONDARY_OUTPUTS = "secondary-outputs"; //$NON-NLS-1$

	/**
	 * On Windows XP and above, the maximum command line length is 8191, on Linux it is at least 131072, but
	 * that includes the environment. We want to limit the invocation of a single command to this number of
	 * characters, and we want to ensure that the number isn't so low as to slow down operation.
	 *
	 * Doing each rm in its own command would be very slow, especially on Windows.
	 */
	private static final int MAX_CLEAN_LENGTH = 6000;

	// Enumerations
	public static final int PROJECT_RELATIVE = 1, PROJECT_SUBDIR_RELATIVE = 2, ABSOLUTE = 3;

	class ToolInfoHolder {
		ITool[] buildTools;
		boolean[] buildToolsUsed;
		ManagedBuildGnuToolInfo[] gnuToolInfos;
		Set<String> outputExtensionsSet;
		List<IPath> dependencyMakefiles;
	}

	// Local variables needed by generator
	private String buildTargetName;
	private String buildTargetExt;
	private IConfiguration config;
	private IBuilder builder;
	//	private ITool[] buildTools;
	//	private boolean[] buildToolsUsed;
	//	private ManagedBuildGnuToolInfo[] gnuToolInfos;
	private PathSettingsContainer toolInfos;
	private Vector<IResource> deletedFileList;
	private Vector<IResource> deletedDirList;
	//	private IManagedBuildInfo info;
	//	private IConfiguration cfg
	private Vector<IResource> invalidDirList;
	/** Collection of Folders in which sources files have been modified */
	private Collection<IContainer> modifiedList;
	private IProgressMonitor monitor;
	private IProject project;
	private IResource[] projectResources;
	private Vector<String> ruleList;
	private Vector<String> depLineList; //  String's of additional dependency lines
	private Vector<String> depRuleList; //  String's of rules for generating dependency files
	/** Collection of Containers which contribute source files to the build */
	private Collection<IContainer> subdirList;
	private IPath topBuildDir; //  Build directory - relative to the workspace
	//	private Set outputExtensionsSet;
	//=== Maps of macro names (String) to values (List)
	//    These are TreeMaps to avoid nondeterministic output because the
	//    makefile output depends on their iteration order (bug 575702).
	//  Map of source file build variable names to a List of source file Path's
	private final Map<String, List<IPath>> buildSrcVars = new TreeMap<>();
	//  Map of output file build variable names to a List of output file Path's
	private final Map<String, List<IPath>> buildOutVars = new TreeMap<>();
	//  Map of dependency file build variable names to a List of GnuDependencyGroupInfo objects
	private final Map<String, GnuDependencyGroupInfo> buildDepVars = new TreeMap<>();
	private final Map<String, Set<String>> topBuildOutVars = new TreeMap<>();
	// Dependency file variables
	//	private Vector dependencyMakefiles;		//  IPath's - relative to the top build directory or absolute

	private ICSourceEntry srcEntries[];

	public GnuMakefileGenerator() {
		super();
	}

	/*************************************************************************
	 *   IManagedBuilderMakefileGenerator   M E T H O D S
	 ************************************************************************/

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#initialize(IProject, IManagedBuildInfo, IProgressMonitor)
	 */
	@Override
	public void initialize(IProject project, IManagedBuildInfo info, IProgressMonitor monitor) {
		// Save the project so we can get path and member information
		this.project = project;
		try {
			projectResources = project.members();
		} catch (CoreException e) {
			projectResources = null;
		}
		// Save the monitor reference for reporting back to the user
		this.monitor = monitor;
		// Get the build info for the project
		//		this.info = info;
		// Get the name of the build target
		buildTargetName = info.getBuildArtifactName();
		// Get its extension
		buildTargetExt = info.getBuildArtifactExtension();

		try {
			//try to resolve the build macros in the target extension
			buildTargetExt = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(buildTargetExt,
					"", //$NON-NLS-1$
					" ", //$NON-NLS-1$
					IBuildMacroProvider.CONTEXT_CONFIGURATION, info.getDefaultConfiguration());
		} catch (BuildMacroException e) {
		}

		try {
			//try to resolve the build macros in the target name
			String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(buildTargetName,
					"", //$NON-NLS-1$
					" ", //$NON-NLS-1$
					IBuildMacroProvider.CONTEXT_CONFIGURATION, info.getDefaultConfiguration());
			if (resolved != null && (resolved = resolved.trim()).length() > 0)
				buildTargetName = resolved;
		} catch (BuildMacroException e) {
		}

		if (buildTargetExt == null) {
			buildTargetExt = ""; //$NON-NLS-1$
		}
		// Cache the build tools
		config = info.getDefaultConfiguration();
		builder = config.getEditableBuilder();
		initToolInfos();
		//set the top build dir path
		initializeTopBuildDir(info.getConfigurationName());
	}

	/**
	 * This method calls the dependency postprocessors defined for the tool chain
	 */
	private void callDependencyPostProcessors(IResourceInfo rcInfo, ToolInfoHolder h, IFile depFile,
			IManagedDependencyGenerator2[] postProcessors, // This array is the same size as the buildTools array and has
			// an entry set when the corresponding tool has a dependency calculator
			boolean callPopulateDummyTargets, boolean force) throws CoreException {
		try {
			//			IPath path = depFile.getFullPath();
			//			path = inFullPathFromOutFullPath(path);
			//			IResourceInfo rcInfo = config.getResourceInfo(path, false);
			//			IFolderInfo fo;
			//			if(rcInfo instanceof IFileInfo){
			//				fo = (IFolderInfo)config.getResourceInfo(path.removeLastSegments(1), false);
			//			} else {
			//				fo = (IFolderInfo)rcInfo;
			//			}
			//			ToolInfoHolder h = getToolInfo(fo.getPath());
			updateMonitor(ManagedMakeMessages.getFormattedString("GnuMakefileGenerator.message.postproc.dep.file", //$NON-NLS-1$
					depFile.getName()));
			if (postProcessors != null) {
				IPath absolutePath = new Path(
						EFSExtensionManager.getDefault().getPathFromURI(depFile.getLocationURI()));
				// Convert to build directory relative
				IPath depPath = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), absolutePath);
				for (int i = 0; i < postProcessors.length; i++) {
					IManagedDependencyGenerator2 depGen = postProcessors[i];
					if (depGen != null) {
						depGen.postProcessDependencyFile(depPath, config, h.buildTools[i], getTopBuildDir());
					}
				}
			}
			if (callPopulateDummyTargets) {
				generateDummyTargets(rcInfo, depFile, force);
			}
		} catch (CoreException e) {
			throw e;
		} catch (IOException e) {
		}
	}

	/**
	 * This method collects the dependency postprocessors and file extensions defined for the tool chain
	 */
	private boolean collectDependencyGeneratorInformation(ToolInfoHolder h, Vector<String> depExts, //  Vector of dependency file extensions
			IManagedDependencyGenerator2[] postProcessors) {

		boolean callPopulateDummyTargets = false;
		for (int i = 0; i < h.buildTools.length; i++) {
			ITool tool = h.buildTools[i];
			IManagedDependencyGeneratorType depType = tool
					.getDependencyGeneratorForExtension(tool.getDefaultInputExtension());
			if (depType != null) {
				int calcType = depType.getCalculatorType();
				if (calcType <= IManagedDependencyGeneratorType.TYPE_OLD_TYPE_LIMIT) {
					if (calcType == IManagedDependencyGeneratorType.TYPE_COMMAND) {
						callPopulateDummyTargets = true;
						depExts.add(DEP_EXT);
					}
				} else {
					if (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS
							|| calcType == IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS) {
						IManagedDependencyGenerator2 depGen = (IManagedDependencyGenerator2) depType;
						String depExt = depGen.getDependencyFileExtension(config, tool);
						if (depExt != null) {
							postProcessors[i] = depGen;
							depExts.add(depExt);
						}
					}
				}
			}
		}
		return callPopulateDummyTargets;
	}

	protected boolean isSource(IPath path) {
		return !CDataUtil.isExcluded(path, srcEntries);
		//		path = path.makeRelative();
		//		for(int i = 0; i < srcPaths.length; i++){
		//			if(srcPaths[i].isPrefixOf(path))
		//				return true;
		//		}
		//		return false;
	}

	private class DepInfo {
		Vector<String> depExts;
		IManagedDependencyGenerator2[] postProcessors;
		boolean callPopulateDummyTargets;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#generateDependencies()
	 */
	@Override
	public void generateDependencies() throws CoreException {
		final PathSettingsContainer postProcs = PathSettingsContainer.createRootContainer();
		// Note: PopulateDummyTargets is a hack for the pre-3.x GCC compilers

		// Collect the methods that will need to be called
		toolInfos.accept(new IPathSettingsContainerVisitor() {
			@Override
			public boolean visit(PathSettingsContainer container) {
				ToolInfoHolder h = (ToolInfoHolder) container.getValue();
				Vector<String> depExts = new Vector<>(); //  Vector of dependency file extensions
				IManagedDependencyGenerator2[] postProcessors = new IManagedDependencyGenerator2[h.buildTools.length];
				boolean callPopulateDummyTargets = collectDependencyGeneratorInformation(h, depExts, postProcessors);

				// Is there anyone to call if we do find dependency files?
				if (!callPopulateDummyTargets) {
					int i;
					for (i = 0; i < postProcessors.length; i++) {
						if (postProcessors[i] != null)
							break;
					}
					if (i == postProcessors.length)
						return true;
				}

				PathSettingsContainer child = postProcs.getChildContainer(container.getPath(), true, true);
				DepInfo di = new DepInfo();
				di.depExts = depExts;
				di.postProcessors = postProcessors;
				di.callPopulateDummyTargets = callPopulateDummyTargets;
				child.setValue(di);

				return true;
			}
		});

		IWorkspaceRoot root = CCorePlugin.getWorkspace().getRoot();
		for (IResource res : getSubdirList()) {
			// The builder creates a subdir with same name as source in the build location
			IContainer subDir = (IContainer) res;
			IPath projectRelativePath = subDir.getProjectRelativePath();
			IResourceInfo rcInfo = config.getResourceInfo(projectRelativePath, false);
			PathSettingsContainer cr = postProcs.getChildContainer(rcInfo.getPath(), false, true);
			if (cr == null || cr.getValue() == null)
				continue;

			DepInfo di = (DepInfo) cr.getValue();

			ToolInfoHolder h = getToolInfo(projectRelativePath);
			IPath buildRelativePath = topBuildDir.append(projectRelativePath);
			IFolder buildFolder = root.getFolder(buildRelativePath);
			if (buildFolder == null)
				continue;

			// Find all of the dep files in the generated subdirectories
			IResource[] files = buildFolder.members();
			for (IResource file : files) {
				String fileExt = file.getFileExtension();
				for (String ext : di.depExts) {
					if (ext.equals(fileExt)) {
						IFile depFile = root.getFile(file.getFullPath());
						if (depFile == null)
							continue;
						callDependencyPostProcessors(rcInfo, h, depFile, di.postProcessors, di.callPopulateDummyTargets,
								false);
					}
				}
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#generateMakefiles(org.eclipse.core.resources.IResourceDelta)
	 */
	@Override
	public MultiStatus generateMakefiles(IResourceDelta delta) throws CoreException {
		/*
		 * Let's do a sanity check right now.
		 *
		 * 1. This is an incremental build, so if the top-level directory is not
		 * there, then a rebuild is needed.
		 */
		IFolder folder = project.getFolder(computeTopBuildDir(config.getName()));
		if (!folder.exists()) {
			return regenerateMakefiles();
		}

		// Return value
		MultiStatus status;

		// Visit the resources in the delta and compile a list of subdirectories to regenerate
		updateMonitor(
				ManagedMakeMessages.getFormattedString("MakefileGenerator.message.calc.delta", project.getName())); //$NON-NLS-1$
		ResourceDeltaVisitor visitor = new ResourceDeltaVisitor(this, config);
		delta.accept(visitor);
		checkCancel();

		// Get all the subdirectories participating in the build
		updateMonitor(
				ManagedMakeMessages.getFormattedString("MakefileGenerator.message.finding.sources", project.getName())); //$NON-NLS-1$
		ResourceProxyVisitor resourceVisitor = new ResourceProxyVisitor(this, config);
		project.accept(resourceVisitor, IResource.NONE);
		checkCancel();

		// Bug 303953: Ensure that if all resources have been removed from a folder, than the folder still
		// appears in the subdir list so it's subdir.mk is correctly regenerated
		getSubdirList().addAll(getModifiedList());

		// Make sure there is something to build
		if (getSubdirList().isEmpty()) {
			String info = ManagedMakeMessages.getFormattedString("MakefileGenerator.warning.no.source", //$NON-NLS-1$
					project.getName());
			updateMonitor(info);
			status = new MultiStatus(ManagedBuilderCorePlugin.getUniqueIdentifier(), IStatus.INFO, "", //$NON-NLS-1$
					null);
			status.add(new Status(IStatus.INFO, ManagedBuilderCorePlugin.getUniqueIdentifier(), NO_SOURCE_FOLDERS, info,
					null));
			return status;
		}

		// Make sure the build directory is available
		ensureTopBuildDir();
		checkCancel();

		// Make sure that there is a makefile containing all the folders participating
		IPath srcsFilePath = topBuildDir.append(SRCSFILE_NAME);
		IFile srcsFileHandle = createFile(srcsFilePath);
		buildSrcVars.clear();
		buildOutVars.clear();
		buildDepVars.clear();
		topBuildOutVars.clear();
		populateSourcesMakefile(srcsFileHandle);
		checkCancel();

		// Regenerate any fragments that are missing for the exisiting directories NOT modified
		for (IResource res : getSubdirList()) {
			IContainer subdirectory = (IContainer) res;
			if (!getModifiedList().contains(subdirectory)) {
				// Make sure the directory exists (it may have been deleted)
				if (!subdirectory.exists()) {
					appendDeletedSubdirectory(subdirectory);
					continue;
				}
				// Make sure a fragment makefile exists
				IPath fragmentPath = getBuildWorkingDir().append(subdirectory.getProjectRelativePath())
						.append(MODFILE_NAME);
				IFile makeFragment = project.getFile(fragmentPath);
				if (!makeFragment.exists()) {
					// If one or both are missing, then add it to the list to be generated
					getModifiedList().add(subdirectory);
				}
			}
		}

		// Delete the old dependency files for any deleted resources
		for (IResource deletedFile : getDeletedFileList()) {
			deleteDepFile(deletedFile);
			deleteBuildTarget(deletedFile);
		}

		// Regenerate any fragments for modified directories
		for (IResource res : getModifiedList()) {
			IContainer subDir = (IContainer) res;
			// Make sure the directory exists (it may have been deleted)
			if (!subDir.exists()) {
				appendDeletedSubdirectory(subDir);
				continue;
			}
			//populateFragmentMakefile(subDir);    //  See below
			checkCancel();
		}

		// Recreate all module makefiles
		// NOTE WELL: For now, always recreate all of the fragment makefile.  This is necessary
		//     in order to re-populate the buildVariable lists.  In the future, the list could
		//     possibly segmented by subdir so that all fragments didn't need to be
		//     regenerated
		for (IResource res : getSubdirList()) {
			IContainer subDir = (IContainer) res;
			try {
				populateFragmentMakefile(subDir);
			} catch (CoreException e) {
				// Probably should ask user if they want to continue
				checkCancel();
				continue;
			}
			checkCancel();
		}

		// Calculate the inputs and outputs of the Tools to be generated in the main makefile
		calculateToolInputsOutputs();
		checkCancel();

		// Re-create the top-level makefile
		IPath makefilePath = topBuildDir.append(MAKEFILE_NAME);
		IFile makefileHandle = createFile(makefilePath);
		populateTopMakefile(makefileHandle, false);
		checkCancel();

		// Remove deleted folders from generated build directory
		for (IResource res : getDeletedDirList()) {
			IContainer subDir = (IContainer) res;
			removeGeneratedDirectory(subDir);
			checkCancel();
		}

		// How did we do
		if (!getInvalidDirList().isEmpty()) {
			status = new MultiStatus(ManagedBuilderCorePlugin.getUniqueIdentifier(), IStatus.WARNING, "", //$NON-NLS-1$
					null);
			// Add a new status for each of the bad folders
			// TODO: fix error message
			for (IResource res : getInvalidDirList()) {
				IContainer subDir = (IContainer) res;
				status.add(new Status(IStatus.WARNING, ManagedBuilderCorePlugin.getUniqueIdentifier(), SPACES_IN_PATH,
						subDir.getFullPath().toString(), null));
			}
		} else {
			status = new MultiStatus(ManagedBuilderCorePlugin.getUniqueIdentifier(), IStatus.OK, "", //$NON-NLS-1$
					null);
		}

		return status;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#getBuildWorkingDir()
	 */
	@Override
	public IPath getBuildWorkingDir() {
		if (topBuildDir != null) {
			return topBuildDir.removeFirstSegments(1);
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#getMakefileName()
	 */
	@Override
	public String getMakefileName() {
		return MAKEFILE_NAME;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#isGeneratedResource(org.eclipse.core.resources.IResource)
	 */
	@Override
	public boolean isGeneratedResource(IResource resource) {
		// Is this a generated directory ...
		IPath path = resource.getProjectRelativePath();
		//TODO: fix to use builder output dir instead
		String[] configNames = ManagedBuildManager.getBuildInfo(project).getConfigurationNames();
		for (String name : configNames) {
			IPath pathOfConfig = computeTopBuildDir(name);
			if (pathOfConfig.isPrefixOf(path)) {
				return true;
			}
		}
		return false;
	}

	private static void save(StringBuffer buffer, IFile file) throws CoreException {
		String encoding = null;
		try {
			encoding = file.getCharset();
		} catch (CoreException ce) {
			// use no encoding
		}

		byte[] bytes = null;
		if (encoding != null) {
			try {
				bytes = buffer.toString().getBytes(encoding);
			} catch (Exception e) {
			}
		} else {
			bytes = buffer.toString().getBytes();
		}

		byte[] oldBytes = null;
		try (InputStream is = file.getContents(true)) {
			oldBytes = is.readAllBytes();
		} catch (IOException e) {
		}

		// Only write file if content differs
		if (!Arrays.equals(oldBytes, bytes)) {
			ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
			// use a platform operation to update the resource contents
			boolean force = true;
			file.setContents(stream, force, false, null); // Don't record history
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#regenerateDependencies()
	 */
	@Override
	public void regenerateDependencies(boolean force) throws CoreException {
		// A hack for the pre-3.x GCC compilers is to put dummy targets for deps
		final IWorkspaceRoot root = CCorePlugin.getWorkspace().getRoot();
		final CoreException[] es = new CoreException[1];

		toolInfos.accept(new IPathSettingsContainerVisitor() {
			@Override
			public boolean visit(PathSettingsContainer container) {
				ToolInfoHolder h = (ToolInfoHolder) container.getValue();
				// Collect the methods that will need to be called
				Vector<String> depExts = new Vector<>(); //  Vector of dependency file extensions
				IManagedDependencyGenerator2[] postProcessors = new IManagedDependencyGenerator2[h.buildTools.length];
				boolean callPopulateDummyTargets = collectDependencyGeneratorInformation(h, depExts, postProcessors);

				// Is there anyone to call if we do find dependency files?
				if (!callPopulateDummyTargets) {
					int i;
					for (i = 0; i < postProcessors.length; i++) {
						if (postProcessors[i] != null)
							break;
					}
					if (i == postProcessors.length)
						return true;
				}

				IResourceInfo rcInfo = config.getResourceInfo(container.getPath(), false);
				for (IPath path : getDependencyMakefiles(h)) {
					// The path to search for the dependency makefile
					IPath relDepFilePath = topBuildDir.append(path);
					IFile depFile = root.getFile(relDepFilePath);
					if (depFile == null || !depFile.isAccessible())
						continue;
					try {
						callDependencyPostProcessors(rcInfo, h, depFile, postProcessors, callPopulateDummyTargets,
								true);
					} catch (CoreException e) {
						es[0] = e;
						return false;
					}
				}
				return true;
			}
		});

		if (es[0] != null)
			throw es[0];
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderMakefileGenerator#regenerateMakefiles()
	 */
	@Override
	public MultiStatus regenerateMakefiles() throws CoreException {
		MultiStatus status;
		// Visit the resources in the project
		ResourceProxyVisitor visitor = new ResourceProxyVisitor(this, config);
		project.accept(visitor, IResource.NONE);

		// See if the user has cancelled the build
		checkCancel();

		// Populate the makefile if any buildable source files have been found in the project
		if (getSubdirList().isEmpty()) {
			String info = ManagedMakeMessages.getFormattedString("MakefileGenerator.warning.no.source", //$NON-NLS-1$
					project.getName());
			updateMonitor(info);
			status = new MultiStatus(ManagedBuilderCorePlugin.getUniqueIdentifier(), IStatus.INFO, "", //$NON-NLS-1$
					null);
			status.add(new Status(IStatus.INFO, ManagedBuilderCorePlugin.getUniqueIdentifier(), NO_SOURCE_FOLDERS, info,
					null));
			return status;
		}

		// Create the top-level directory for the build output
		ensureTopBuildDir();
		checkCancel();

		// Get the list of subdirectories
		IPath srcsFilePath = topBuildDir.append(SRCSFILE_NAME);
		IFile srcsFileHandle = createFile(srcsFilePath);
		buildSrcVars.clear();
		buildOutVars.clear();
		buildDepVars.clear();
		topBuildOutVars.clear();
		populateSourcesMakefile(srcsFileHandle);
		checkCancel();

		// Now populate the module makefiles
		for (IResource res : getSubdirList()) {
			IContainer subDir = (IContainer) res;
			try {
				populateFragmentMakefile(subDir);
			} catch (CoreException e) {
				// Probably should ask user if they want to continue
				checkCancel();
				continue;
			}
			checkCancel();
		}

		// Calculate the inputs and outputs of the Tools to be generated in the main makefile
		calculateToolInputsOutputs();
		checkCancel();

		// Create the top-level makefile
		IPath makefilePath = topBuildDir.append(MAKEFILE_NAME);
		IFile makefileHandle = createFile(makefilePath);
		populateTopMakefile(makefileHandle, true);
		checkCancel();

		// How did we do
		if (!getInvalidDirList().isEmpty()) {
			status = new MultiStatus(ManagedBuilderCorePlugin.getUniqueIdentifier(), IStatus.WARNING, "", //$NON-NLS-1$
					null);
			// Add a new status for each of the bad folders
			// TODO: fix error message
			for (IResource dir : getInvalidDirList()) {
				status.add(new Status(IStatus.WARNING, ManagedBuilderCorePlugin.getUniqueIdentifier(), SPACES_IN_PATH,
						dir.getFullPath().toString(), null));
			}
		} else {
			status = new MultiStatus(ManagedBuilderCorePlugin.getUniqueIdentifier(), IStatus.OK, "", //$NON-NLS-1$
					null);
		}
		return status;
	}

	/*************************************************************************
	 *   M A K E F I L E S   P O P U L A T I O N   M E T H O D S
	 ************************************************************************/

	/**
	 * This method generates a "fragment" make file (subdir.mk).
	 * One of these is generated for each project directory/subdirectory
	 * that contains source files.
	 */
	protected void populateFragmentMakefile(IContainer module) throws CoreException {
		// Calculate the new directory relative to the build output
		IPath moduleRelativePath = module.getProjectRelativePath();
		IPath buildRoot = getBuildWorkingDir();
		if (buildRoot == null) {
			return;
		}

		IPath moduleOutputPath = buildRoot.append(moduleRelativePath);
		updateMonitor(ManagedMakeMessages.getFormattedString("MakefileGenerator.message.gen.source.makefile", //$NON-NLS-1$
				moduleOutputPath.toString()));

		// Now create the directory
		IPath moduleOutputDir = createDirectory(moduleOutputPath.toString());

		// Create a module makefile
		IFile modMakefile = createFile(moduleOutputDir.append(MODFILE_NAME));
		StringBuffer makeBuf = new StringBuffer();
		makeBuf.append(addFragmentMakefileHeader());
		makeBuf.append(addSources(module, toCleanTarget(moduleRelativePath)));

		// Save the files
		save(makeBuf, modMakefile);
	}

	protected void populateSourcesMakefile(IFile fileHandle) throws CoreException {
		// Add the comment
		StringBuffer buffer = addGenericHeader();

		// Determine the set of macros
		toolInfos.accept(new IPathSettingsContainerVisitor() {

			@Override
			public boolean visit(PathSettingsContainer container) {
				ToolInfoHolder h = (ToolInfoHolder) container.getValue();
				ITool[] buildTools = h.buildTools;
				HashSet<String> handledInputExtensions = new HashSet<>();
				String buildMacro;
				for (ITool buildTool : buildTools) {
					if (buildTool.getCustomBuildStep())
						continue;
					// Add the known sources macros
					String[] extensionsList = buildTool.getAllInputExtensions();
					for (String ext : extensionsList) {
						// create a macro of the form "EXTENSION_SRCS :="
						String extensionName = ext;
						if (//!getOutputExtensions().contains(extensionName) &&
						!handledInputExtensions.contains(extensionName)) {
							handledInputExtensions.add(extensionName);
							buildMacro = getSourceMacroName(extensionName).toString();
							if (!buildSrcVars.containsKey(buildMacro)) {
								buildSrcVars.put(buildMacro, new ArrayList<IPath>());
							}
							// Add any generated dependency file macros
							IManagedDependencyGeneratorType depType = buildTool
									.getDependencyGeneratorForExtension(extensionName);
							if (depType != null) {
								int calcType = depType.getCalculatorType();
								if (calcType == IManagedDependencyGeneratorType.TYPE_COMMAND
										|| calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS
										|| calcType == IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS) {
									buildMacro = getDepMacroName(extensionName).toString();
									if (!buildDepVars.containsKey(buildMacro)) {
										buildDepVars.put(buildMacro, new GnuDependencyGroupInfo(buildMacro,
												(calcType != IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS)));
									}
									if (!buildOutVars.containsKey(buildMacro)) {
										buildOutVars.put(buildMacro, new ArrayList<IPath>());
									}
								}
							}
						}
					}
					// Add the specified output build variables
					IOutputType[] outTypes = buildTool.getOutputTypes();
					if (outTypes != null && outTypes.length > 0) {
						for (IOutputType outputType : outTypes) {
							buildMacro = outputType.getBuildVariable();
							if (!buildOutVars.containsKey(buildMacro)) {
								buildOutVars.put(buildMacro, new ArrayList<IPath>());
							}
						}
					} else {
						// For support of pre-CDT 3.0 integrations.
						buildMacro = OBJS_MACRO;
						if (!buildOutVars.containsKey(buildMacro)) {
							buildOutVars.put(buildMacro, new ArrayList<IPath>());
						}
					}
				}
				return true;
			}
		});
		// Add the macros to the makefile
		for (Entry<String, List<IPath>> entry : buildSrcVars.entrySet()) {
			String macroName = entry.getKey();
			buffer.append(macroName).append(WHITESPACE).append(":=").append(WHITESPACE).append(NEWLINE); //$NON-NLS-1$
		}
		Set<Entry<String, List<IPath>>> set = buildOutVars.entrySet();
		for (Entry<String, List<IPath>> entry : set) {
			String macroName = entry.getKey();
			buffer.append(macroName).append(WHITESPACE).append(":=").append(WHITESPACE).append(NEWLINE); //$NON-NLS-1$
		}

		// Add a list of subdirectories to the makefile
		buffer.append(NEWLINE).append(addSubdirectories());

		// Save the file
		save(buffer, fileHandle);
	}

	/**
	 * Create the entire contents of the makefile.
	 *
	 * @param fileHandle The file to place the contents in.
	 * @param rebuild FLag signaling that the user is doing a full rebuild
	 */
	protected void populateTopMakefile(IFile fileHandle, boolean rebuild) throws CoreException {
		StringBuffer buffer = new StringBuffer();

		// Add the header
		buffer.append(addTopHeader());

		// Add the macro definitions
		buffer.append(addMacros());

		// List to collect needed build output variables
		List<String> outputVarsAdditionsList = new ArrayList<>();

		// Determine target rules
		StringBuffer targetRules = addTargets(outputVarsAdditionsList, rebuild);

		// Add outputMacros that were added to by the target rules
		buffer.append(writeTopAdditionMacros(outputVarsAdditionsList, getTopBuildOutputVars()));

		// Add target rules
		buffer.append(targetRules);

		// Save the file
		save(buffer, fileHandle);
	}

	/*************************************************************************
	 *   M A I N (makefile)   M A K E F I L E   M E T H O D S
	 ************************************************************************/

	/**
	 * Answers a <code>StringBuffer</code> containing the comment(s)
	 * for the top-level makefile.
	 */
	protected StringBuffer addTopHeader() {
		return addGenericHeader();
	}

	/**
	 */
	private StringBuffer addMacros() {
		StringBuffer buffer = new StringBuffer();

		// Add the ROOT macro
		//buffer.append("ROOT := ..").append(NEWLINE); //$NON-NLS-1$
		//buffer.append(NEWLINE);

		// include makefile.init supplementary makefile
		buffer.append("-include " + reachProjectRoot() + SEPARATOR + MAKEFILE_INIT).append(NEWLINE); //$NON-NLS-1$
		buffer.append(NEWLINE);

		// Get the clean command from the build model
		buffer.append("RM := "); //$NON-NLS-1$

		// support macros in the clean command
		String cleanCommand = config.getCleanCommand();

		try {
			cleanCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
					config.getCleanCommand(), EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_CONFIGURATION,
					config);
		} catch (BuildMacroException e) {
		}

		buffer.append(cleanCommand).append(NEWLINE);

		buffer.append(NEWLINE);

		// Now add the source providers
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(SRC_LISTS))
				.append(NEWLINE);
		buffer.append("-include sources.mk").append(NEWLINE); //$NON-NLS-1$

		// Add includes for each subdir in child-subdir-first order (required for makefile rule matching to work).
		List<String> subDirList = new ArrayList<>();
		for (IContainer subDir : getSubdirList()) {
			String projectRelativePath = subDir.getProjectRelativePath().toString();
			subDirList.add(0, projectRelativePath);
		}
		Collections.sort(subDirList, Collections.reverseOrder());
		for (String dir : subDirList) {
			buffer.append("-include "); //$NON-NLS-1$
			if (!dir.isEmpty())
				buffer.append(escapeWhitespaces(dir)).append(SEPARATOR);
			buffer.append(MODFILE_NAME).append(NEWLINE);
		}

		// Include generated dependency makefiles if non-empty AND a "clean" has not been requested
		if (!buildDepVars.isEmpty()) {
			buffer.append("ifneq ($(MAKECMDGOALS),clean)").append(NEWLINE); //$NON-NLS-1$

			for (Entry<String, GnuDependencyGroupInfo> entry : buildDepVars.entrySet()) {
				String depsMacro = entry.getKey();
				GnuDependencyGroupInfo info = entry.getValue();
				buffer.append("ifneq ($(strip $(").append(depsMacro).append(")),)").append(NEWLINE); //$NON-NLS-1$ //$NON-NLS-2$
				if (info.conditionallyInclude) {
					buffer.append("-include $(").append(depsMacro).append(')').append(NEWLINE); //$NON-NLS-1$
				} else {
					buffer.append("include $(").append(depsMacro).append(')').append(NEWLINE); //$NON-NLS-1$
				}
				buffer.append("endif").append(NEWLINE); //$NON-NLS-1$
			}

			buffer.append("endif").append(NEWLINE).append(NEWLINE); //$NON-NLS-1$
		}

		// Include makefile.defs supplemental makefile
		buffer.append("-include ").append(reachProjectRoot()).append(SEPARATOR).append(MAKEFILE_DEFS).append(NEWLINE); //$NON-NLS-1$

		final String wildcardFileFmt = "$(wildcard %s)" + WHITESPACE + LINEBREAK; //$NON-NLS-1$
		buffer.append(NEWLINE).append("OPTIONAL_TOOL_DEPS :=").append(WHITESPACE).append(LINEBREAK); //$NON-NLS-1$
		buffer.append(String.format(wildcardFileFmt, reachProjectRoot() + SEPARATOR + MAKEFILE_DEFS));
		buffer.append(String.format(wildcardFileFmt, reachProjectRoot() + SEPARATOR + MAKEFILE_INIT));
		buffer.append(String.format(wildcardFileFmt, reachProjectRoot() + SEPARATOR + MAKEFILE_TARGETS));
		buffer.append(NEWLINE);

		String ext = config.getArtifactExtension();
		// try to resolve the build macros in the artifact extension
		try {
			ext = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(ext, EMPTY_STRING,
					WHITESPACE, IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
		} catch (BuildMacroException e) {
		}

		String name = config.getArtifactName();
		// try to resolve the build macros in the artifact name
		try {
			String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(name,
					EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
			if ((resolved = resolved.trim()).length() > 0) {
				name = resolved;
			}
		} catch (BuildMacroException e) {
		}

		String prefix = EMPTY_STRING;
		ITool targetTool = config.calculateTargetTool();
		if (targetTool != null) {
			prefix = targetTool.getOutputPrefix();
			if (prefix == null) {
				prefix = EMPTY_STRING;
			}
		}
		// try to resolve the build macros in the artifact prefix
		try {
			String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(prefix,
					EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
			if ((resolved = resolved.trim()).length() > 0) {
				prefix = resolved;
			}
		} catch (BuildMacroException e) {
		}

		@SuppressWarnings("nls")
		String[][] buildArtifactVars = new String[][] { //
				{ "BUILD_ARTIFACT_NAME", name }, //
				{ "BUILD_ARTIFACT_EXTENSION", ext }, //
				{ "BUILD_ARTIFACT_PREFIX", prefix }, //
				{ "BUILD_ARTIFACT",
						"$(BUILD_ARTIFACT_PREFIX)$(BUILD_ARTIFACT_NAME)$(if $(BUILD_ARTIFACT_EXTENSION),.$(BUILD_ARTIFACT_EXTENSION),)" }, //
		};

		buffer.append(NEWLINE);
		for (String[] var : buildArtifactVars) {
			buffer.append(var[0]).append(" :="); //$NON-NLS-1$
			if (!var[1].isEmpty()) {
				buffer.append(WHITESPACE).append(var[1]);
			}
			buffer.append(NEWLINE);
		}

		return (buffer.append(NEWLINE));
	}

	/**
	 * Answers a <code>StringBuffer</code> containing all of the required targets to
	 * properly build the project.
	 *
	 * @param outputVarsAdditionsList  list to add needed build output variables to
	 */
	private StringBuffer addTargets(List<String> outputVarsAdditionsList, boolean rebuild) {
		StringBuffer buffer = new StringBuffer();

		//		IConfiguration config = info.getDefaultConfiguration();

		// Assemble the information needed to generate the targets
		String prebuildStep = config.getPrebuildStep();
		try {
			//try to resolve the build macros in the prebuild step
			prebuildStep = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(prebuildStep,
					EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
		} catch (BuildMacroException e) {
		}
		prebuildStep = prebuildStep.trim(); // Remove leading and trailing whitespace (and control characters)

		String postbuildStep = config.getPostbuildStep();
		try {
			//try to resolve the build macros in the postbuild step
			postbuildStep = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(postbuildStep,
					EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_CONFIGURATION, config);

		} catch (BuildMacroException e) {
		}
		postbuildStep = postbuildStep.trim(); // Remove leading and trailing whitespace (and control characters)
		String preannouncebuildStep = config.getPreannouncebuildStep();
		String postannouncebuildStep = config.getPostannouncebuildStep();
		String targets = rebuild ? "clean all" : "all"; //$NON-NLS-1$ //$NON-NLS-2$

		ITool targetTool = config.calculateTargetTool();
		//		if (targetTool == null) {
		//			targetTool = info.getToolFromOutputExtension(buildTargetExt);
		//		}

		// Get all the projects the build target depends on
		// If this configuration produces a static archive, building the archive doesn't depend on the output
		// from any of the referenced configurations
		IConfiguration[] refConfigs = new IConfiguration[0];
		if (config.getBuildArtefactType() == null || !ManagedBuildManager.BUILD_ARTEFACT_TYPE_PROPERTY_STATICLIB
				.equals(config.getBuildArtefactType().getId()))
			refConfigs = ManagedBuildManager.getReferencedConfigurations(config);

		// Add the comment for the "All" target
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(ALL_TARGET))
				.append(NEWLINE);

		if (!prebuildStep.isEmpty() || !postbuildStep.isEmpty()) {
			// all:
			buffer.append("all").append(COLON).append(NEWLINE); //$NON-NLS-1$

			String makeNoPrintDir = MAKE + WHITESPACE + NO_PRINT_DIR + WHITESPACE;
			buffer.append(TAB).append("+@"); //$NON-NLS-1$
			if (!prebuildStep.isEmpty()) {
				buffer.append(makeNoPrintDir).append(PREBUILD).append(WHITESPACE).append(LOGICAL_AND)
						.append(WHITESPACE);
			}
			buffer.append(makeNoPrintDir).append(MAINBUILD);
			if (!postbuildStep.isEmpty()) {
				buffer.append(WHITESPACE).append(LOGICAL_AND).append(WHITESPACE).append(makeNoPrintDir)
						.append(POSTBUILD);
			}

			buffer.append(NEWLINE);

		} else {
			// all: main-build
			buffer.append("all").append(COLON).append(WHITESPACE).append(MAINBUILD).append(NEWLINE); //$NON-NLS-1$
		}
		buffer.append(NEWLINE);

		// Add the comment for the "main-build" target
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(MAINBUILD_TARGET))
				.append(NEWLINE);

		// Write out the main-build target first in case someone just runs make
		// main-build: <target_name>

		String outputPrefix = EMPTY_STRING;
		if (targetTool != null) {
			outputPrefix = targetTool.getOutputPrefix();
		}
		buffer.append(MAINBUILD).append(COLON).append(WHITESPACE).append(outputPrefix)
				.append(ensurePathIsGNUMakeTargetRuleCompatibleSyntax(buildTargetName));
		if (buildTargetExt.length() > 0) {
			buffer.append(DOT).append(buildTargetExt);
		}

		// Add the Secondary Outputs to the all target, if any
		IOutputType[] secondaryOutputs = config.getToolChain().getSecondaryOutputs();
		if (secondaryOutputs.length > 0) {
			buffer.append(WHITESPACE).append(SECONDARY_OUTPUTS);
		}

		buffer.append(NEWLINE).append(NEWLINE);

		/*
		 * The build target may depend on other projects in the workspace. These
		 * are captured in the deps target: deps: <cd <Proj_Dep_1/build_dir>;
		 * $(MAKE) [clean all | all]>
		 */
		//		Vector managedProjectOutputs = new Vector(refdProjects.length);
		//		if (refdProjects.length > 0) {
		Vector<String> managedProjectOutputs = new Vector<>(refConfigs.length);
		if (refConfigs.length > 0) {
			boolean addDeps = true;
			//			if (refdProjects != null) {
			for (IConfiguration depCfg : refConfigs) {
				//					IProject dep = refdProjects[i];
				if (!depCfg.isManagedBuildOn())
					continue;

				//					if (!dep.exists()) continue;
				if (addDeps) {
					buffer.append("dependents:").append(NEWLINE); //$NON-NLS-1$
					addDeps = false;
				}
				String buildDir = depCfg.getOwner().getLocation().toString();
				String depTargets = targets;
				//					if (ManagedBuildManager.manages(dep)) {
				// Add the current configuration to the makefile path
				//						IManagedBuildInfo depInfo = ManagedBuildManager.getBuildInfo(dep);
				buildDir += SEPARATOR + depCfg.getName();

				// Extract the build artifact to add to the dependency list
				String depTarget = depCfg.getArtifactName();
				String depExt = depCfg.getArtifactExtension();

				try {
					//try to resolve the build macros in the artifact extension
					depExt = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(depExt, "", //$NON-NLS-1$
							" ", //$NON-NLS-1$
							IBuildMacroProvider.CONTEXT_CONFIGURATION, depCfg);
				} catch (BuildMacroException e) {
				}

				try {
					//try to resolve the build macros in the artifact name
					String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
							depTarget, "", //$NON-NLS-1$
							" ", //$NON-NLS-1$
							IBuildMacroProvider.CONTEXT_CONFIGURATION, depCfg);
					if ((resolved = resolved.trim()).length() > 0)
						depTarget = resolved;
				} catch (BuildMacroException e) {
				}

				String depPrefix = depCfg.getOutputPrefix(depExt);
				if (depCfg.needsRebuild()) {
					depTargets = "clean all"; //$NON-NLS-1$
				}
				String dependency = buildDir + SEPARATOR + depPrefix + depTarget;
				if (depExt.length() > 0) {
					dependency += DOT + depExt;
				}
				dependency = escapeWhitespaces(dependency);
				managedProjectOutputs.add(dependency);
				//}
				buffer.append(TAB).append("-cd").append(WHITESPACE).append(escapeWhitespaces(buildDir)) //$NON-NLS-1$
						.append(WHITESPACE).append(LOGICAL_AND).append(WHITESPACE).append("$(MAKE) ").append(depTargets) //$NON-NLS-1$
						.append(NEWLINE);
			}
			//			}
			buffer.append(NEWLINE);
		}

		// Add the targets tool rules
		buffer.append(addTargetsRules(targetTool, outputVarsAdditionsList, managedProjectOutputs));

		// Add the prebuild step target, if specified
		if (prebuildStep.length() > 0) {
			buffer.append(PREBUILD).append(COLON).append(NEWLINE);
			if (preannouncebuildStep.length() > 0) {
				buffer.append(TAB).append(DASH).append(AT).append(escapedEcho(preannouncebuildStep));
			}
			buffer.append(TAB).append(DASH).append(prebuildStep).append(NEWLINE);
			buffer.append(TAB).append(DASH).append(AT).append(ECHO_BLANK_LINE).append(NEWLINE);
		}

		// Add the postbuild step, if specified
		if (postbuildStep.length() > 0) {
			buffer.append(POSTBUILD).append(COLON).append(NEWLINE);
			if (postannouncebuildStep.length() > 0) {
				buffer.append(TAB).append(DASH).append(AT).append(escapedEcho(postannouncebuildStep));
			}
			buffer.append(TAB).append(DASH).append(postbuildStep).append(NEWLINE);
			buffer.append(TAB).append(DASH).append(AT).append(ECHO_BLANK_LINE).append(NEWLINE);
		}

		// Add the Secondary Outputs target, if needed
		if (secondaryOutputs.length > 0) {
			buffer.append(SECONDARY_OUTPUTS).append(COLON);
			Vector<String> outs2 = calculateSecondaryOutputs(secondaryOutputs);
			for (int i = 0; i < outs2.size(); i++) {
				buffer.append(WHITESPACE).append("$(").append(outs2.get(i)).append(')'); //$NON-NLS-1$
			}
			buffer.append(NEWLINE).append(NEWLINE);
		}

		// Add all the needed dummy and phony targets
		buffer.append(".PHONY: all clean dependents").append(WHITESPACE).append(MAINBUILD); //$NON-NLS-1$
		if (prebuildStep.length() > 0) {
			buffer.append(WHITESPACE).append(PREBUILD);
		}
		if (postbuildStep.length() > 0) {
			buffer.append(WHITESPACE).append(POSTBUILD);
		}
		buffer.append(NEWLINE);
		for (String output : managedProjectOutputs) {
			buffer.append(output).append(COLON).append(NEWLINE);
		}
		buffer.append(NEWLINE);

		// Include makefile.targets supplemental makefile
		buffer.append("-include ").append(reachProjectRoot()).append(SEPARATOR).append(MAKEFILE_TARGETS) //$NON-NLS-1$
				.append(NEWLINE);

		return buffer;
	}

	/**
	 * Returns the targets rules.  The targets make file (top makefile) contains:
	 *  1  the rule for the final target tool
	 *  2  the rules for all of the tools that use multipleOfType in their primary input type
	 *  3  the rules for all tools that use the output of #2 tools
	 *
	 * @param outputVarsAdditionsList  list to add needed build output variables to
	 * @param managedProjectOutputs  Other projects in the workspace that this project depends upon
	 * @return StringBuffer
	 */
	private StringBuffer addTargetsRules(ITool targetTool, List<String> outputVarsAdditionsList,
			Vector<String> managedProjectOutputs) {
		StringBuffer buffer = new StringBuffer();
		// Add the comment
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(BUILD_TOP))
				.append(NEWLINE);

		ToolInfoHolder h = (ToolInfoHolder) toolInfos.getValue();
		ITool[] buildTools = h.buildTools;
		boolean[] buildToolsUsed = h.buildToolsUsed;
		//  Get the target tool and generate the rule
		if (targetTool != null) {
			// Note that the name of the target we pass to addRuleForTool does not
			// appear to be used there (and tool outputs are consulted directly), but
			// we quote it anyway just in case it starts to use it in future.
			if (addRuleForTool(targetTool, buffer, true, ensurePathIsGNUMakeTargetRuleCompatibleSyntax(buildTargetName),
					buildTargetExt, outputVarsAdditionsList, managedProjectOutputs)) {
				//  Mark the target tool as processed
				for (int i = 0; i < buildTools.length; i++) {
					if (targetTool == buildTools[i]) {
						buildToolsUsed[i] = true;
					}
				}
			}
		} else {
			buffer.append(TAB).append(AT).append(escapedEcho(MESSAGE_NO_TARGET_TOOL + WHITESPACE + OUT_MACRO));
		}

		//  Generate the rules for all Tools that specify InputType.multipleOfType, and any Tools that
		//  consume the output of those tools.  This does not apply to pre-3.0 integrations, since
		//  the only "multipleOfType" tool is the "target" tool
		for (int i = 0; i < buildTools.length; i++) {
			ITool tool = buildTools[i];
			IInputType type = tool.getPrimaryInputType();
			if (type != null && type.getMultipleOfType()) {
				if (!buildToolsUsed[i]) {
					addRuleForTool(tool, buffer, false, null, null, outputVarsAdditionsList, null);
					//  Mark the target tool as processed
					buildToolsUsed[i] = true;
					// Look for tools that consume the output
					generateRulesForConsumers(tool, outputVarsAdditionsList, buffer);
				}
			}
		}

		// Add the comment
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(BUILD_TARGETS))
				.append(NEWLINE);

		// Always add a clean target
		buffer.append("clean:").append(NEWLINE); //$NON-NLS-1$

		Set<String> filesToClean = new HashSet<>();
		String outputPrefix = EMPTY_STRING;
		if (targetTool != null) {
			outputPrefix = targetTool.getOutputPrefix();
		}
		String completeBuildTargetName = outputPrefix + buildTargetName;
		if (buildTargetExt.length() > 0) {
			completeBuildTargetName = completeBuildTargetName + DOT + buildTargetExt;
		}
		completeBuildTargetName = ensurePathIsGNUMakeTargetRuleCompatibleSyntax(completeBuildTargetName);
		filesToClean.add(completeBuildTargetName);

		Map<String, Set<String>> map = getTopBuildOutputVars();
		for (String macroName : outputVarsAdditionsList) {
			Set<String> set = map.getOrDefault(macroName, Collections.emptySet());
			filesToClean.addAll(set);
		}

		if (!filesToClean.isEmpty()) {
			StringBuffer rmLineBuffer = new StringBuffer();
			rmLineBuffer.append(TAB).append("-$(RM)"); //$NON-NLS-1$

			// Convert the set to an ordered list. Without this "unneeded" sorting, the unit tests will fail
			List<String> filesToCleanOrdered = new ArrayList<>(filesToClean);
			filesToCleanOrdered.sort((p1, p2) -> p1.toString().compareTo(p2.toString()));

			for (String path : filesToCleanOrdered) {
				// Bug 417228, ilg@livius.net & freidin.alex@gmail.com
				path = ensurePathIsGNUMakeTargetRuleCompatibleSyntax(path);

				// There is a max length for a command line, wrap to multiple invocations if needed.
				if (rmLineBuffer.length() + path.length() > MAX_CLEAN_LENGTH) {
					// Terminate this RM line
					buffer.append(rmLineBuffer).append(NEWLINE);

					// Start a new RM line
					rmLineBuffer = new StringBuffer();
					rmLineBuffer.append(TAB).append("-$(RM)"); //$NON-NLS-1$
				}
				rmLineBuffer.append(WHITESPACE).append(path);
			}

			buffer.append(rmLineBuffer);
		}

		buffer.append(NEWLINE);
		buffer.append(TAB).append(DASH).append(AT).append(ECHO_BLANK_LINE).append(NEWLINE);

		return buffer;
	}

	/**
	 * Create the rule
	 *
	 * @param buffer  Buffer to add makefile rules to
	 * @param bTargetTool True if this is the target tool
	 * @param targetName  If this is the "targetTool", the target file name, else <code>null</code>
	 * @param targetExt  If this is the "targetTool", the target file extension, else <code>null</code>
	 * @param outputVarsAdditionsList  list to add needed build output variables to
	 * @param managedProjectOutputs  Other projects in the workspace that this project depends upon
	 * @since 9.3
	 */
	protected boolean addRuleForTool(ITool tool, StringBuffer buffer, boolean bTargetTool, String targetName,
			String targetExt, List<String> outputVarsAdditionsList, Vector<String> managedProjectOutputs) {

		//  Get the tool's inputs and outputs
		Vector<String> inputs = new Vector<>();
		Vector<String> dependencies = new Vector<>();
		Vector<String> outputs = new Vector<>();
		Vector<String> enumeratedPrimaryOutputs = new Vector<>();
		Vector<String> enumeratedSecondaryOutputs = new Vector<>();
		Vector<String> outputVariables = new Vector<>();
		Vector<String> additionalTargets = new Vector<>();
		String outputPrefix = EMPTY_STRING;

		if (!getToolInputsOutputs(tool, inputs, dependencies, outputs, enumeratedPrimaryOutputs,
				enumeratedSecondaryOutputs, outputVariables, additionalTargets, bTargetTool, managedProjectOutputs)) {
			return false;
		}

		//  If we have no primary output, make all of the secondary outputs the primary output
		if (enumeratedPrimaryOutputs.size() == 0) {
			enumeratedPrimaryOutputs = enumeratedSecondaryOutputs;
			enumeratedSecondaryOutputs.clear();
		}

		//  Add the output variables for this tool to our list
		outputVarsAdditionsList.addAll(outputVariables);

		//  Create the build rule
		String buildRule = EMPTY_STRING;
		String outflag = tool.getOutputFlag();

		String primaryOutputs = EMPTY_STRING;
		String primaryOutputsQuoted = EMPTY_STRING;
		boolean first = true;
		for (int i = 0; i < enumeratedPrimaryOutputs.size(); i++) {
			String output = enumeratedPrimaryOutputs.get(i);
			if (!first) {
				primaryOutputs += WHITESPACE;
				primaryOutputsQuoted += WHITESPACE;
			}
			first = false;
			primaryOutputs += output;
			primaryOutputsQuoted += ensurePathIsGNUMakeTargetRuleCompatibleSyntax(output);
		}

		buildRule += (primaryOutputsQuoted + COLON + WHITESPACE);

		first = true;
		String calculatedDependencies = EMPTY_STRING;
		for (int i = 0; i < dependencies.size(); i++) {
			String input = dependencies.get(i);
			if (!first)
				calculatedDependencies += WHITESPACE;
			first = false;
			calculatedDependencies += input;
		}
		buildRule += calculatedDependencies;
		buildRule += WHITESPACE + MAKEFILE_NAME; // makefile itself
		buildRule += WHITESPACE + "$(OPTIONAL_TOOL_DEPS)"; //$NON-NLS-1$ // Optional dep to generated makefile extension files

		// Depend on additional object files for the tool, if any
		String[] additionalObjects = tool.getExtraFlags(IOption.OBJECTS);
		if (additionalObjects.length > 0) {
			buildRule += WHITESPACE + Stream.of(additionalObjects) //
					.map(this::ensurePathIsGNUMakeTargetRuleCompatibleSyntax) //
					.collect(Collectors.joining(WHITESPACE));
		}

		// We can't have duplicates in a makefile
		if (getRuleList().contains(buildRule)) {
		} else {
			getRuleList().add(buildRule);
			buffer.append(buildRule).append(NEWLINE);
			if (bTargetTool) {
				buffer.append(TAB).append(AT).append(escapedEcho(MESSAGE_START_BUILD + WHITESPACE + OUT_MACRO));
			}
			buffer.append(TAB).append(AT).append(escapedEcho(tool.getAnnouncement()));

			// Get the command line for this tool invocation
			String[] flags;
			try {
				flags = tool.getToolCommandFlags(null, null);
			} catch (BuildException ex) {
				// TODO  report error
				flags = EMPTY_STRING_ARRAY;
			}
			String command = tool.getToolCommand();
			try {
				//try to resolve the build macros in the tool command
				String resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
						command, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(null, null, null, tool));
				if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
					command = resolvedCommand;

			} catch (BuildMacroException e) {
			}
			String[] cmdInputs = inputs.toArray(new String[inputs.size()]);
			IManagedCommandLineGenerator gen = tool.getCommandLineGenerator();
			String commandLinePattern = tool.getCommandLinePattern();
			if (!commandLinePattern.contains("${EXTRA_FLAGS}")) { //$NON-NLS-1$
				String[] objs = tool.getExtraFlags(IOption.OBJECTS);
				String[] libs = tool.getExtraFlags(IOption.LIBRARIES);
				if (objs.length > 0 || libs.length > 0) {
					// Tool command line pattern would expect legacy "$(USER_OBJS)" or "$(LIBS)" make-symbols to be appended.
					commandLinePattern = commandLinePattern + " ${EXTRA_FLAGS}"; //$NON-NLS-1$
				}
			}
			IManagedCommandLineInfo cmdLInfo = gen.generateCommandLineInfo(tool, command, flags, outflag, outputPrefix,
					primaryOutputs, cmdInputs, commandLinePattern);

			// The command to build
			String buildCmd = null;
			if (cmdLInfo == null) {
				String toolFlags;
				try {
					toolFlags = tool.getToolCommandFlagsString(null, null);
				} catch (BuildException ex) {
					// TODO report error
					toolFlags = EMPTY_STRING;
				}
				buildCmd = command + WHITESPACE + toolFlags + WHITESPACE + outflag + WHITESPACE + outputPrefix
						+ primaryOutputs + WHITESPACE + IN_MACRO;
			} else
				buildCmd = cmdLInfo.getCommandLine();

			// resolve any remaining macros in the command after it has been
			// generated
			try {
				String resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
						buildCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(null, null, null, tool));
				if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
					buildCmd = resolvedCommand;

			} catch (BuildMacroException e) {
			}

			//buffer.append(TAB).append(AT).append(escapedEcho(buildCmd));
			//buffer.append(TAB).append(AT).append(buildCmd);
			buffer.append(TAB).append(buildCmd);

			// TODO
			// NOTE WELL:  Dependency file generation is not handled for this type of Tool

			// Echo finished message
			buffer.append(NEWLINE);
			buffer.append(TAB).append(AT).append(
					escapedEcho((bTargetTool ? MESSAGE_FINISH_BUILD : MESSAGE_FINISH_FILE) + WHITESPACE + OUT_MACRO));
			buffer.append(TAB).append(AT).append(ECHO_BLANK_LINE);

			// Just emit a blank line
			buffer.append(NEWLINE);
		}

		// If we have secondary outputs, output dependency rules without commands
		if (enumeratedSecondaryOutputs.size() > 0 || additionalTargets.size() > 0) {
			String primaryOutput = enumeratedPrimaryOutputs.get(0);
			Vector<String> addlOutputs = new Vector<>();
			addlOutputs.addAll(enumeratedSecondaryOutputs);
			addlOutputs.addAll(additionalTargets);
			for (int i = 0; i < addlOutputs.size(); i++) {
				String output = addlOutputs.get(i);
				String depLine = output + COLON + WHITESPACE + primaryOutput + WHITESPACE + calculatedDependencies
						+ NEWLINE;
				if (!getDepLineList().contains(depLine)) {
					getDepLineList().add(depLine);
					buffer.append(depLine);
				}
			}
			buffer.append(NEWLINE);
		}
		return true;
	}

	/**
	 * @param outputVarsAdditionsList  list to add needed build output variables to
	 * @param buffer  buffer to add rules to
	 */
	private void generateRulesForConsumers(ITool generatingTool, List<String> outputVarsAdditionsList,
			StringBuffer buffer) {
		//  Generate a build rule for any tool that consumes the output of this tool
		ToolInfoHolder h = (ToolInfoHolder) toolInfos.getValue();
		ITool[] buildTools = h.buildTools;
		boolean[] buildToolsUsed = h.buildToolsUsed;
		IOutputType[] outTypes = generatingTool.getOutputTypes();
		for (IOutputType outType : outTypes) {
			String[] outExts = outType.getOutputExtensions(generatingTool);
			String outVariable = outType.getBuildVariable();
			if (outExts != null) {
				for (String outExt : outExts) {
					for (int k = 0; k < buildTools.length; k++) {
						ITool tool = buildTools[k];
						if (!buildToolsUsed[k]) {
							// Also has to match build variables if specified
							IInputType inType = tool.getInputType(outExt);
							if (inType != null) {
								String inVariable = inType.getBuildVariable();
								if ((outVariable == null && inVariable == null) || (outVariable != null
										&& inVariable != null && outVariable.equals(inVariable))) {
									if (addRuleForTool(buildTools[k], buffer, false, null, null,
											outputVarsAdditionsList, null)) {
										buildToolsUsed[k] = true;
										// Look for tools that consume the output
										generateRulesForConsumers(buildTools[k], outputVarsAdditionsList, buffer);
									}
								}
							}
						}
					}
				}
			}
		}
	}

	protected boolean getToolInputsOutputs(ITool tool, Vector<String> inputs, Vector<String> dependencies,
			Vector<String> outputs, Vector<String> enumeratedPrimaryOutputs, Vector<String> enumeratedSecondaryOutputs,
			Vector<String> outputVariables, Vector<String> additionalTargets, boolean bTargetTool,
			Vector<String> managedProjectOutputs) {
		ToolInfoHolder h = (ToolInfoHolder) toolInfos.getValue();
		ITool[] buildTools = h.buildTools;
		ManagedBuildGnuToolInfo[] gnuToolInfos = h.gnuToolInfos;
		//  Get the information regarding the tool's inputs and outputs from the objects
		//  created by calculateToolInputsOutputs
		ManagedBuildGnuToolInfo toolInfo = null;
		for (int i = 0; i < buildTools.length; i++) {
			if (tool == buildTools[i]) {
				toolInfo = gnuToolInfos[i];
				break;
			}
		}
		if (toolInfo == null)
			return false;

		//  Populate the output Vectors
		inputs.addAll(toolInfo.getCommandInputs());
		outputs.addAll(toolInfo.getCommandOutputs());
		enumeratedPrimaryOutputs.addAll(toolInfo.getEnumeratedPrimaryOutputs());
		enumeratedSecondaryOutputs.addAll(toolInfo.getEnumeratedSecondaryOutputs());
		outputVariables.addAll(toolInfo.getOutputVariables());

		Vector<String> unprocessedDependencies = toolInfo.getCommandDependencies();
		for (String path : unprocessedDependencies) {
			dependencies.add(ensurePathIsGNUMakeTargetRuleCompatibleSyntax(path));
		}
		additionalTargets.addAll(toolInfo.getAdditionalTargets());

		if (bTargetTool && managedProjectOutputs != null) {
			for (String output : managedProjectOutputs) {
				dependencies.add(output);
			}
		}
		return true;
	}

	protected Vector<String> calculateSecondaryOutputs(IOutputType[] secondaryOutputs) {
		ToolInfoHolder h = (ToolInfoHolder) toolInfos.getValue();
		ITool[] buildTools = h.buildTools;
		Vector<String> buildVars = new Vector<>();
		for (int i = 0; i < buildTools.length; i++) {
			// Add the specified output build variables
			IOutputType[] outTypes = buildTools[i].getOutputTypes();
			if (outTypes != null && outTypes.length > 0) {
				for (int j = 0; j < outTypes.length; j++) {
					IOutputType outType = outTypes[j];
					//  Is this one of the secondary outputs?
					//  Look for an outputType with this ID, or one with a superclass with this id
					thisType: for (int k = 0; k < secondaryOutputs.length; k++) {
						IOutputType matchType = outType;
						do {
							if (matchType.getId().equals(secondaryOutputs[k].getId())) {
								buildVars.add(outType.getBuildVariable());
								break thisType;
							}
							matchType = matchType.getSuperClass();
						} while (matchType != null);
					}
				}
			}
		}
		return buildVars;
	}

	protected boolean isSecondaryOutputVar(ToolInfoHolder h, IOutputType[] secondaryOutputs, String varName) {
		ITool[] buildTools = h.buildTools;
		for (ITool buildTool : buildTools) {
			// Add the specified output build variables
			IOutputType[] outTypes = buildTool.getOutputTypes();
			if (outTypes != null && outTypes.length > 0) {
				for (IOutputType outType : outTypes) {
					//  Is this one of the secondary outputs?
					//  Look for an outputType with this ID, or one with a superclass with this id
					for (IOutputType secondaryOutput : secondaryOutputs) {
						IOutputType matchType = outType;
						do {
							if (matchType.getId().equals(secondaryOutput.getId())) {
								if (outType.getBuildVariable().equals(varName)) {
									return true;
								}
							}
							matchType = matchType.getSuperClass();
						} while (matchType != null);
					}
				}
			}
		}
		return false;
	}

	/*************************************************************************
	 *   S O U R C E S (sources.mk)   M A K E F I L E   M E T H O D S
	 ************************************************************************/

	private StringBuffer addSubdirectories() {
		StringBuffer buffer = new StringBuffer();
		// Add the comment
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(MOD_LIST))
				.append(NEWLINE);

		buffer.append("SUBDIRS := ").append(LINEBREAK); //$NON-NLS-1$

		// Get all the module names
		for (IResource container : getSubdirList()) {
			updateMonitor(ManagedMakeMessages.getFormattedString("MakefileGenerator.message.adding.source.folder", //$NON-NLS-1$
					container.getFullPath().toString()));
			// Check the special case where the module is the project root
			if (container.getFullPath() == project.getFullPath()) {
				buffer.append(DOT).append(WHITESPACE).append(LINEBREAK);
			} else {
				IPath path = container.getProjectRelativePath();
				buffer.append(escapeWhitespaces(path.toString())).append(WHITESPACE).append(LINEBREAK);
			}
		}

		buffer.append(NEWLINE);
		return buffer;
	}

	/*************************************************************************
	 *   F R A G M E N T (subdir.mk)   M A K E F I L E   M E T H O D S
	 ************************************************************************/

	/**
	 * Returns a <code>StringBuffer</code> containing the comment(s)
	 * for a fragment makefile (subdir.mk).
	 */
	protected StringBuffer addFragmentMakefileHeader() {
		return addGenericHeader();
	}

	/**
	 * Returns a <code>StringBuffer</code> containing makefile text for all of the sources
	 * contributed by a container (project directory/subdirectory) to the fragement makefile
	 *
	 * @param module  project resource directory/subdirectory
	 * @return StringBuffer  generated text for the fragement makefile
	 */
	protected StringBuffer addSources(IContainer module, String cleanTarget) throws CoreException {
		// Calculate the new directory relative to the build output
		IPath moduleRelativePath = module.getProjectRelativePath();
		String relativePath = moduleRelativePath.toString();
		relativePath += relativePath.length() == 0 ? "" : SEPARATOR; //$NON-NLS-1$

		// For build macros in the configuration, create a map which will map them
		// to a string which holds its list of sources.
		LinkedHashMap<String, String> buildVarToRuleStringMap = new LinkedHashMap<>();

		// Add statements that add the source files in this folder,
		// and generated source files, and generated dependency files
		// to the build macros
		for (Entry<String, List<IPath>> entry : buildSrcVars.entrySet()) {
			String macroName = entry.getKey();
			addMacroAdditionPrefix(buildVarToRuleStringMap, macroName, null, false);

		}
		for (Entry<String, List<IPath>> entry : buildOutVars.entrySet()) {
			String macroName = entry.getKey();
			addMacroAdditionPrefix(buildVarToRuleStringMap, macroName, "./" + relativePath, false); //$NON-NLS-1$
		}

		// String buffers
		StringBuffer buffer = new StringBuffer(); // Return buffer
		StringBuffer ruleBuffer = new StringBuffer(
				COMMENT_SYMBOL + WHITESPACE + ManagedMakeMessages.getResourceString(MOD_RULES) + NEWLINE);

		// Visit the resources in this folder and add each one to a sources macro, and generate a build rule, if appropriate
		IResource[] resources = module.members();

		IResourceInfo rcInfo;
		IFolder folder = project.getFolder(computeTopBuildDir(config.getName()));
		Set<IPath> filesToClean = new HashSet<>();

		for (IResource resource : resources) {
			if (resource.getType() == IResource.FILE) {
				// Check whether this resource is excluded from build
				IPath rcProjRelPath = resource.getProjectRelativePath();
				if (!isSource(rcProjRelPath))
					continue;
				rcInfo = config.getResourceInfo(rcProjRelPath, false);
				//				if( (rcInfo.isExcluded()) )
				//					continue;
				addFragmentMakefileEntriesForSource(buildVarToRuleStringMap, ruleBuffer, folder, relativePath, resource,
						getPathForResource(resource), rcInfo, null, false, filesToClean);
			}
		}

		// Write out the macro addition entries to the buffer
		buffer.append(writeAdditionMacros(buildVarToRuleStringMap));
		buffer.append(ruleBuffer).append(NEWLINE);

		if (cleanTarget != null && !filesToClean.isEmpty()) {
			buffer.append("clean: " + cleanTarget).append(NEWLINE).append(NEWLINE); //$NON-NLS-1$
			buffer.append(cleanTarget + COLON).append(NEWLINE);

			StringBuffer rmLineBuffer = new StringBuffer();
			rmLineBuffer.append(TAB).append("-$(RM)"); //$NON-NLS-1$

			// Convert the set to an ordered list. Without this "unneeded" sorting, the unit tests will fail
			List<IPath> filesToCleanOrdered = new ArrayList<>(filesToClean);
			filesToCleanOrdered.sort((p1, p2) -> p1.toString().compareTo(p2.toString()));

			for (IPath fileToClean : filesToCleanOrdered) {
				String path = escapeWhitespaces(
						(fileToClean.isAbsolute() || fileToClean.segment(0).equals(".") ? EMPTY_STRING : "./") //$NON-NLS-1$ //$NON-NLS-2$
								+ fileToClean.toString());

				// There is a max length for a command line, wrap to multiple invocations if needed.
				if (rmLineBuffer.length() + path.length() > MAX_CLEAN_LENGTH) {
					// Terminate this RM line
					buffer.append(rmLineBuffer).append(NEWLINE);

					// Start a new RM line
					rmLineBuffer = new StringBuffer();
					rmLineBuffer.append(TAB).append("-$(RM)"); //$NON-NLS-1$
				}
				rmLineBuffer.append(WHITESPACE).append(path);
			}

			buffer.append(rmLineBuffer).append(NEWLINE).append(NEWLINE);
			buffer.append(".PHONY: ").append(cleanTarget).append(NEWLINE).append(NEWLINE); //$NON-NLS-1$
		}

		return buffer;
	}

	/**
	 * Adds the entries for a particular source file to the fragment makefile
	 *
	 * @param buildVarToRuleStringMap  map of build variable names to the list of files assigned to the variable
	 * @param ruleBuffer  buffer to add generated nmakefile text to
	 * @param folder  the top level build output directory
	 * @param relativePath  build output directory relative path of the current output directory
	 * @param resource  the source file for this invocation of the tool - this may be null for a generated output
	 * @param sourceLocation  the full path of the source
	 * @param resConfig  the IResourceConfiguration associated with this file or null
	 * @param varName  the build variable to add this invocation's outputs to
	 *                   if <code>null</code>, use the file extension to find the name
	 * @param generatedSource  if <code>true</code>, this file was generated by another tool in the tool-chain
	 */
	protected void addFragmentMakefileEntriesForSource(LinkedHashMap<String, String> buildVarToRuleStringMap,
			StringBuffer ruleBuffer, IFolder folder, String relativePath, IResource resource, IPath sourceLocation,
			IResourceInfo rcInfo, String varName, boolean generatedSource, Set<IPath> filesToClean) {

		//  Determine which tool, if any, builds files with this extension
		String ext = sourceLocation.getFileExtension();
		ITool tool = null;

		//TODO: remove
		//		IResourceConfiguration resConfig = null;
		//		if(rcInfo instanceof IFileInfo){
		//			resConfig = (IFileInfo)rcInfo;
		//		}
		//end remove

		//  Use the tool from the resource configuration if there is one
		if (rcInfo instanceof IFileInfo) {
			IFileInfo fi = (IFileInfo) rcInfo;
			ITool[] tools = fi.getToolsToInvoke();
			if (tools != null && tools.length > 0) {
				tool = tools[0];
				//				if(!tool.getCustomBuildStep())
				addToBuildVar(buildVarToRuleStringMap, ext, varName, relativePath, sourceLocation, generatedSource);
			}
		}

		ToolInfoHolder h = getToolInfo(rcInfo.getPath());
		ITool buildTools[] = h.buildTools;

		//		if(tool == null){
		//			for (int j=0; j<buildTools.length; j++) {
		//				if (buildTools[j].buildsFileType(ext)) {
		//					if (tool == null) {
		//						tool = buildTools[j];
		//					}
		//					addToBuildVar(buildVarToRuleStringMap, ext, varName, relativePath, sourceLocation, generatedSource);
		//					break;
		//				}
		//			}
		//		}
		//
		//		if(tool == null && rcInfo.getPath().segmentCount() != 0){
		if (tool == null) {
			h = getToolInfo(Path.EMPTY);
			buildTools = h.buildTools;

			for (ITool buildTool : buildTools) {
				if (buildTool.buildsFileType(ext)) {
					tool = buildTool;
					addToBuildVar(buildVarToRuleStringMap, ext, varName, relativePath, sourceLocation, generatedSource);
					break;
				}
			}
		}

		if (tool != null) {
			//  Generate the rule to build this source file
			IInputType primaryInputType = tool.getPrimaryInputType();
			IInputType inputType = tool.getInputType(ext);
			if ((primaryInputType != null && !primaryInputType.getMultipleOfType())
					|| (inputType == null && tool != config.calculateTargetTool())) {

				// Try to add the rule for the file
				Vector<IPath> generatedOutputs = new Vector<>(); //  IPath's - build directory relative
				Vector<IPath> generatedDepFiles = new Vector<>(); //  IPath's - build directory relative or absolute
				addRuleForSource(relativePath, ruleBuffer, resource, sourceLocation, rcInfo, generatedSource,
						generatedDepFiles, generatedOutputs);

				// If the rule generates a dependency file(s), add the file(s) to the variable
				if (generatedDepFiles.size() > 0) {
					for (int k = 0; k < generatedDepFiles.size(); k++) {
						IPath generatedDepFile = generatedDepFiles.get(k);
						addMacroAdditionFile(buildVarToRuleStringMap, getDepMacroName(ext).toString(),
								(generatedDepFile.isAbsolute() ? "" : "./") + //$NON-NLS-1$ //$NON-NLS-2$
										generatedDepFile.toString());
					}
				}

				// If the generated outputs of this tool are input to another tool,
				// 1. add the output to the appropriate macro
				// 2. If the tool does not have multipleOfType input, generate the rule.

				IOutputType outType = tool.getPrimaryOutputType();
				String buildVariable = null;
				if (outType != null) {
					if (tool.getCustomBuildStep()) {
						// TODO: This is somewhat of a hack since a custom build step
						//       tool does not currently define a build variable
						if (generatedOutputs.size() > 0) {
							IPath firstOutput = generatedOutputs.get(0);
							String firstExt = firstOutput.getFileExtension();
							ToolInfoHolder tmpH = getFolderToolInfo(rcInfo.getPath());
							ITool[] tmpBuildTools = tmpH.buildTools;
							for (ITool tmpBuildTool : tmpBuildTools) {
								if (tmpBuildTool.buildsFileType(firstExt)) {
									String bV = tmpBuildTool.getPrimaryInputType().getBuildVariable();
									if (bV.length() > 0) {
										buildVariable = bV;
										break;
									}
								}
							}
						}
					} else {
						buildVariable = outType.getBuildVariable();
					}
				} else {
					// For support of pre-CDT 3.0 integrations.
					buildVariable = OBJS_MACRO;
				}

				for (int k = 0; k < generatedOutputs.size(); k++) {
					IPath generatedOutput;
					IResource generateOutputResource;
					if (generatedOutputs.get(k).isAbsolute()) {
						// TODO:  Should we use relative paths when possible (e.g., see MbsMacroSupplier.calculateRelPath)
						generatedOutput = generatedOutputs.get(k);
						//  If this file has an absolute path, then the generateOutputResource will not be correct
						//  because the file is not under the project.  We use this resource in the calls to the dependency generator
						generateOutputResource = project.getFile(generatedOutput);
					} else {
						generatedOutput = getPathForResource(project).append(getBuildWorkingDir())
								.append(generatedOutputs.get(k));
						generateOutputResource = project.getFile(getBuildWorkingDir().append(generatedOutputs.get(k)));
					}
					IResourceInfo nextRcInfo;
					if (rcInfo instanceof IFileInfo) {
						nextRcInfo = config.getResourceInfo(rcInfo.getPath().removeLastSegments(1), false);
					} else {
						nextRcInfo = rcInfo;
					}
					addFragmentMakefileEntriesForSource(buildVarToRuleStringMap, ruleBuffer, folder, relativePath,
							generateOutputResource, generatedOutput, nextRcInfo, buildVariable, true, filesToClean);
				}

				filesToClean.addAll(generatedDepFiles);
				filesToClean.addAll(generatedOutputs);
			}
		} else {
			//  If this is a secondary input, add it to build vars
			if (varName == null) {
				for (ITool buildTool : buildTools) {
					if (buildTool.isInputFileType(ext)) {
						addToBuildVar(buildVarToRuleStringMap, ext, varName, relativePath, sourceLocation,
								generatedSource);
						break;
					}
				}
			}
			//  If this generated output is identified as a secondary output, add the file to the build variable
			else {
				IOutputType[] secondaryOutputs = config.getToolChain().getSecondaryOutputs();
				if (secondaryOutputs.length > 0) {
					if (isSecondaryOutputVar(h, secondaryOutputs, varName)) {
						addMacroAdditionFile(buildVarToRuleStringMap, varName, relativePath, sourceLocation,
								generatedSource);
					}
				}
			}
		}
	}

	/**
	 * Gets a path for a resource by extracting the Path field from its
	 * location URI.
	 * @return IPath
	 * @since 6.0
	 */
	protected IPath getPathForResource(IResource resource) {
		return new Path(resource.getLocationURI().getPath());
	}

	/**
	 * Adds the source file to the appropriate build variable
	 *
	 * @param buildVarToRuleStringMap  map of build variable names to the list of files assigned to the variable
	 * @param ext  the file extension of the file
	 * @param varName  the build variable to add this invocation's outputs to
	 *                   if <code>null</code>, use the file extension to find the name
	 * @param relativePath  build output directory relative path of the current output directory
	 * @param sourceLocation  the full path of the source
	 * @param generatedSource  if <code>true</code>, this file was generated by another tool in the tool-chain
	 */
	protected void addToBuildVar(LinkedHashMap<String, String> buildVarToRuleStringMap, String ext, String varName,
			String relativePath, IPath sourceLocation, boolean generatedSource) {
		List<IPath> varList = null;
		if (varName == null) {
			// Get the proper source build variable based upon the extension
			varName = getSourceMacroName(ext).toString();
			varList = buildSrcVars.get(varName);
		} else {
			varList = buildOutVars.get(varName);
		}
		//  Add the resource to the list of all resources associated with a variable.
		//  Do not allow duplicates - there is no reason to and it can be 'bad' -
		//  e.g., having the same object in the OBJS list can cause duplicate symbol errors from the linker
		if ((varList != null) && !(varList.contains(sourceLocation))) {
			//  Since we don't know how these files will be used, we store them using a "location"
			//  path rather than a relative path
			varList.add(sourceLocation);
			if (!buildVarToRuleStringMap.containsKey(varName)) {
				//  TODO - is this an error?
			} else {
				//  Add the resource name to the makefile line that adds resources to the build variable
				addMacroAdditionFile(buildVarToRuleStringMap, varName, relativePath, sourceLocation, generatedSource);
			}
		}
	}

	private IManagedCommandLineInfo generateToolCommandLineInfo(ITool tool, String sourceExtension, String[] flags,
			String outputFlag, String outputPrefix, String outputName, String[] inputResources, IPath inputLocation,
			IPath outputLocation) {

		String cmd = tool.getToolCommand();
		//try to resolve the build macros in the tool command
		try {
			String resolvedCommand = null;

			if ((inputLocation != null && inputLocation.toString().indexOf(" ") != -1) || //$NON-NLS-1$
					(outputLocation != null && outputLocation.toString().indexOf(" ") != -1)) //$NON-NLS-1$
			{
				resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValue(cmd, "", //$NON-NLS-1$
						" ", //$NON-NLS-1$
						IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(inputLocation, outputLocation, null, tool));
			}

			else {
				resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(cmd, "", //$NON-NLS-1$
						" ", //$NON-NLS-1$
						IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(inputLocation, outputLocation, null, tool));
			}
			if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
				cmd = resolvedCommand;

		} catch (BuildMacroException e) {
		}

		IManagedCommandLineGenerator gen = tool.getCommandLineGenerator();
		return gen.generateCommandLineInfo(tool, cmd, flags, outputFlag, outputPrefix, outputName, inputResources,
				tool.getCommandLinePattern());

	}

	/**
	 * Create a rule for this source file.  We create a pattern rule if possible.
	 *
	 * This is an example of a pattern rule:
	 *
	 * <relative_path>/%.<outputExtension>: ../<relative_path>/%.<inputExtension>
	 * 		@echo Building file: $<
	 * 		@echo Invoking tool xxx
	 * 		@echo <tool> <flags> <output_flag><output_prefix>$@ $<
	 * 		@<tool> <flags> <output_flag><output_prefix>$@ $< && \
	 * 		echo -n $(@:%.o=%.d) ' <relative_path>/' >> $(@:%.o=%.d) && \
	 * 		<tool> -P -MM -MG <flags> $< >> $(@:%.o=%.d)
	 * 		@echo Finished building: $<
	 * 		@echo ' '
	 *
	 * Note that the macros all come from the build model and are
	 * resolved to a real command before writing to the module
	 * makefile, so a real command might look something like:
	 * source1/%.o: ../source1/%.cpp
	 * 		@echo Building file: $<
	 * 		@echo Invoking tool xxx
	 * 		@echo g++ -g -O2 -c -I/cygdrive/c/eclipse/workspace/Project/headers -o$@ $<
	 *		@g++ -g -O2 -c -I/cygdrive/c/eclipse/workspace/Project/headers -o$@ $< && \
	 * 		echo -n $(@:%.o=%.d) ' source1/' >> $(@:%.o=%.d) && \
	 * 		g++ -P -MM -MG -g -O2 -c -I/cygdrive/c/eclipse/workspace/Project/headers $< >> $(@:%.o=%.d)
	 * 		@echo Finished building: $<
	 * 		@echo ' '
	 *
	 * @param relativePath  top build output directory relative path of the current output directory
	 * @param buffer  buffer to populate with the build rule
	 * @param resource  the source file for this invocation of the tool
	 * @param sourceLocation  the full path of the source
	 * @param rcInfo  the IResourceInfo associated with this file or null
	 * @param generatedSource  <code>true</code> if the resource is a generated output
	 * @param enumeratedOutputs  vector of the filenames that are the output of this rule
	 */
	protected void addRuleForSource(String relativePath, StringBuffer buffer, IResource resource, IPath sourceLocation,
			IResourceInfo rcInfo, boolean generatedSource, Vector<IPath> generatedDepFiles,
			Vector<IPath> enumeratedOutputs) {

		String fileName = sourceLocation.removeFileExtension().lastSegment();
		String inputExtension = sourceLocation.getFileExtension();
		String outputExtension = null;

		ITool tool = null;
		if (rcInfo instanceof IFileInfo) {
			IFileInfo fi = (IFileInfo) rcInfo;
			ITool[] tools = fi.getToolsToInvoke();
			if (tools != null && tools.length > 0) {
				tool = tools[0];
			}
		} else {
			IFolderInfo foInfo = (IFolderInfo) rcInfo;
			tool = foInfo.getToolFromInputExtension(inputExtension);
		}

		ToolInfoHolder h = getToolInfo(rcInfo.getPath());

		if (tool != null)
			outputExtension = tool.getOutputExtension(inputExtension);
		if (outputExtension == null)
			outputExtension = EMPTY_STRING;

		//  Get the dependency generator information for this tool and file extension
		IManagedDependencyGenerator oldDepGen = null; //  This interface is deprecated but still supported
		IManagedDependencyGenerator2 depGen = null; //  This is the recommended interface
		IManagedDependencyInfo depInfo = null;
		IManagedDependencyCommands depCommands = null;
		IManagedDependencyPreBuild depPreBuild = null;
		IPath[] depFiles = null;
		boolean doDepGen = false;
		{
			IManagedDependencyGeneratorType t = null;
			if (tool != null)
				t = tool.getDependencyGeneratorForExtension(inputExtension);
			if (t != null) {
				int calcType = t.getCalculatorType();
				if (calcType <= IManagedDependencyGeneratorType.TYPE_OLD_TYPE_LIMIT) {
					oldDepGen = (IManagedDependencyGenerator) t;
					doDepGen = (calcType == IManagedDependencyGeneratorType.TYPE_COMMAND);
					if (doDepGen) {
						IPath depFile = Path.fromOSString(relativePath + fileName + DOT + DEP_EXT);
						getDependencyMakefiles(h).add(depFile);
						generatedDepFiles.add(depFile);
					}
				} else {
					depGen = (IManagedDependencyGenerator2) t;
					doDepGen = (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS);
					IBuildObject buildContext = rcInfo;//(resConfig != null) ? (IBuildObject)resConfig : (IBuildObject)config;

					depInfo = depGen.getDependencySourceInfo(resource.getProjectRelativePath(), resource, buildContext,
							tool, getBuildWorkingDir());

					if (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS) {
						depCommands = (IManagedDependencyCommands) depInfo;
						depFiles = depCommands.getDependencyFiles();
					} else if (calcType == IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS) {
						depPreBuild = (IManagedDependencyPreBuild) depInfo;
						depFiles = depPreBuild.getDependencyFiles();
					}
					if (depFiles != null) {
						for (IPath depFile : depFiles) {
							getDependencyMakefiles(h).add(depFile);
							generatedDepFiles.add(depFile);
						}
					}
				}
			}
		}

		// Figure out the output paths
		String optDotExt = EMPTY_STRING;
		if (outputExtension.length() > 0)
			optDotExt = DOT + outputExtension;

		Vector<IPath> ruleOutputs = new Vector<>();
		Vector<IPath> enumeratedPrimaryOutputs = new Vector<>(); // IPaths relative to the top build directory
		Vector<IPath> enumeratedSecondaryOutputs = new Vector<>(); // IPaths relative to the top build directory
		calculateOutputsForSource(tool, relativePath, resource, sourceLocation, ruleOutputs, enumeratedPrimaryOutputs,
				enumeratedSecondaryOutputs);
		enumeratedOutputs.addAll(enumeratedPrimaryOutputs);
		enumeratedOutputs.addAll(enumeratedSecondaryOutputs);
		String primaryOutputName = null;
		if (enumeratedPrimaryOutputs.size() > 0) {
			primaryOutputName = escapeWhitespaces(enumeratedPrimaryOutputs.get(0).toString());
		} else {
			primaryOutputName = escapeWhitespaces(relativePath + fileName + optDotExt);
		}
		String otherPrimaryOutputs = EMPTY_STRING;
		for (int i = 1; i < enumeratedPrimaryOutputs.size(); i++) { // Starting with 1 is intentional
			otherPrimaryOutputs += WHITESPACE + escapeWhitespaces(enumeratedPrimaryOutputs.get(i).toString());
		}

		// Output file location needed for the file-specific build macros
		IPath outputLocation = Path.fromOSString(primaryOutputName);
		if (!outputLocation.isAbsolute()) {
			outputLocation = getPathForResource(project).append(getBuildWorkingDir()).append(primaryOutputName);
		}

		// A separate rule is needed for the resource in the case where explicit file-specific macros
		// are referenced, or if the resource contains special characters in its path (e.g., whitespace)

		/* fix for 137674
		 *
		 * We only need an explicit rule if one of the following is true:
		 * - The resource is linked, and its full path to its real location contains special characters
		 * - The resource is not linked, but its project relative path contains special characters
		*/

		boolean resourceNameRequiresExplicitRule = (resource.isLinked()
				&& containsSpecialCharacters(sourceLocation.toString()))
				|| (!resource.isLinked() && containsSpecialCharacters(resource.getProjectRelativePath().toString()));

		boolean needExplicitRuleForFile = resourceNameRequiresExplicitRule
				|| BuildMacroProvider.getReferencedExplitFileMacros(tool).length > 0
				|| BuildMacroProvider.getReferencedExplitFileMacros(tool.getToolCommand(),
						IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(sourceLocation, outputLocation, null, tool)).length > 0;

		// Get and resolve the command
		String cmd = tool.getToolCommand();

		try {
			String resolvedCommand = null;
			if (!needExplicitRuleForFile) {
				resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(cmd,
						EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(sourceLocation, outputLocation, null, tool));
			} else {
				// if we need an explicit rule then don't use any builder
				// variables, resolve everything
				// to explicit strings
				resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValue(cmd, EMPTY_STRING,
						WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
						new FileContextData(sourceLocation, outputLocation, null, tool));
			}

			if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
				cmd = resolvedCommand;

		} catch (BuildMacroException e) {
		}

		String defaultOutputName = EMPTY_STRING;
		String primaryDependencyName = EMPTY_STRING;
		String patternPrimaryDependencyName = EMPTY_STRING;
		String home = (generatedSource) ? DOT : reachProjectRoot();
		String resourcePath = null;
		boolean patternRule = true;
		boolean isItLinked = false;
		if (resource.isLinked(IResource.CHECK_ANCESTORS)) {
			// it IS linked, so use the actual location
			isItLinked = true;
			resourcePath = sourceLocation.toString();
			// Need a hardcoded rule, not a pattern rule, as a linked file
			// can reside in any path
			defaultOutputName = escapeWhitespaces(relativePath + fileName + optDotExt);
			primaryDependencyName = escapeWhitespaces(resourcePath);
			patternRule = false;
		} else {
			// Use the relative path (not really needed to store per se but in the future someone may want this)
			resourcePath = relativePath;
			// The rule and command to add to the makefile
			if (rcInfo instanceof IFileInfo || needExplicitRuleForFile) {
				// Need a hardcoded rule, not a pattern rule
				defaultOutputName = escapeWhitespaces(resourcePath + fileName + optDotExt);
				patternRule = false;
			} else {
				defaultOutputName = relativePath + WILDCARD + optDotExt;
			}
			primaryDependencyName = escapeWhitespaces(
					home + SEPARATOR + resourcePath + fileName + DOT + inputExtension);
			patternPrimaryDependencyName = home + SEPARATOR + resourcePath + WILDCARD + DOT + inputExtension;
		} // end fix for PR 70491

		//  If the tool specifies a dependency calculator of TYPE_BUILD_COMMANDS, ask whether
		//  the dependency commands are "generic" (i.e., we can use a pattern rule)
		boolean needExplicitDependencyCommands = false;
		if (depCommands != null) {
			needExplicitDependencyCommands = !depCommands.areCommandsGeneric();
		}

		//  If we still think that we are using a pattern rule, check a few more things
		if (patternRule) {
			patternRule = false;
			//  Make sure that at least one of the rule outputs contains a %.
			for (int i = 0; i < ruleOutputs.size(); i++) {
				String ruleOutput = ruleOutputs.get(i).toString();
				if (ruleOutput.indexOf('%') >= 0) {
					patternRule = true;
					break;
				}
			}
			if (patternRule) {
				patternRule = !needExplicitDependencyCommands;
			}
		}

		// Begin building the rule for this source file
		String buildRule = EMPTY_STRING;

		if (patternRule) {
			if (ruleOutputs.size() == 0) {
				buildRule += defaultOutputName;
			} else {
				boolean first = true;
				for (int i = 0; i < ruleOutputs.size(); i++) {
					String ruleOutput = ruleOutputs.get(i).toString();
					if (ruleOutput.indexOf('%') >= 0) {
						if (first) {
							first = false;
						} else {
							buildRule += WHITESPACE;
						}
						buildRule += ruleOutput;
					}
				}
			}
		} else {
			buildRule += primaryOutputName;
		}

		String buildRuleDependencies = primaryDependencyName;
		String patternBuildRuleDependencies = patternPrimaryDependencyName;

		// Other additional inputs
		// Get any additional dependencies specified for the tool in other InputType elements and AdditionalInput elements
		IPath[] addlDepPaths = tool.getAdditionalDependencies();
		for (IPath addlDepPath : addlDepPaths) {
			// Translate the path from project relative to build directory relative
			IPath addlPath = addlDepPath;
			if (!(addlPath.toString().startsWith("$("))) { //$NON-NLS-1$
				if (!addlPath.isAbsolute()) {
					IPath tempPath = project.getLocation().append(new Path(ensureUnquoted(addlPath.toString())));
					if (tempPath != null) {
						addlPath = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), tempPath);
					}
				}
			}
			String suitablePath = ensurePathIsGNUMakeTargetRuleCompatibleSyntax(addlPath.toString());
			buildRuleDependencies += WHITESPACE + suitablePath;
			patternBuildRuleDependencies += WHITESPACE + suitablePath;
		}

		buildRule += COLON + WHITESPACE + (patternRule ? patternBuildRuleDependencies : buildRuleDependencies)
				+ WHITESPACE + escapeWhitespaces(relativePath + MODFILE_NAME);

		// No duplicates in a makefile.  If we already have this rule, don't add it or the commands to build the file
		if (getRuleList().contains(buildRule)) {
			//  TODO:  Should we assert that this is a pattern rule?
		} else {
			getRuleList().add(buildRule);

			// Echo starting message
			buffer.append(buildRule).append(NEWLINE);
			buffer.append(TAB).append(AT).append(escapedEcho(MESSAGE_START_FILE + WHITESPACE + IN_MACRO));
			buffer.append(TAB).append(AT).append(escapedEcho(tool.getAnnouncement()));

			// If the tool specifies a dependency calculator of TYPE_BUILD_COMMANDS, ask whether
			// there are any pre-tool commands.
			if (depCommands != null) {
				String[] preToolCommands = depCommands.getPreToolDependencyCommands();
				if (preToolCommands != null && preToolCommands.length > 0) {
					for (String preCmd : preToolCommands) {
						try {
							String resolvedCommand;
							IBuildMacroProvider provider = ManagedBuildManager.getBuildMacroProvider();
							if (!needExplicitRuleForFile) {
								resolvedCommand = provider.resolveValueToMakefileFormat(preCmd, EMPTY_STRING,
										WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
										new FileContextData(sourceLocation, outputLocation, null, tool));
							} else {
								// if we need an explicit rule then don't use any builder
								// variables, resolve everything to explicit strings
								resolvedCommand = provider.resolveValue(preCmd, EMPTY_STRING, WHITESPACE,
										IBuildMacroProvider.CONTEXT_FILE,
										new FileContextData(sourceLocation, outputLocation, null, tool));
							}
							if (resolvedCommand != null)
								buffer.append(resolvedCommand).append(NEWLINE);
						} catch (BuildMacroException e) {
						}
					}
				}
			}

			// Generate the command line

			Vector<String> inputs = new Vector<>();
			inputs.add(IN_MACRO);

			// Other additional inputs
			// Get any additional dependencies specified for the tool in other InputType elements and AdditionalInput elements
			IPath[] addlInputPaths = getAdditionalResourcesForSource(tool);
			for (IPath addlInputPath : addlInputPaths) {
				// Translate the path from project relative to build directory relative
				IPath addlPath = addlInputPath;
				if (!(addlPath.toString().startsWith("$("))) { //$NON-NLS-1$
					if (!addlPath.isAbsolute()) {
						IPath tempPath = getPathForResource(project).append(addlPath);
						if (tempPath != null) {
							addlPath = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), tempPath);
						}
					}
				}
				inputs.add(addlPath.toString());
			}
			String[] inputStrings = inputs.toArray(new String[inputs.size()]);

			String[] flags = null;
			// Get the tool command line options
			try {
				flags = tool.getToolCommandFlags(sourceLocation, outputLocation);
			} catch (BuildException ex) {
				// TODO add some routines to catch this
				flags = EMPTY_STRING_ARRAY;
			}

			// If we have a TYPE_BUILD_COMMANDS dependency generator, determine if there are any options that
			// it wants added to the command line
			if (depCommands != null) {
				flags = addDependencyOptions(depCommands, flags);
			}

			IManagedCommandLineInfo cmdLInfo = null;
			String outflag = null;
			String outputPrefix = null;

			if (rcInfo instanceof IFileInfo || needExplicitRuleForFile || needExplicitDependencyCommands) {
				outflag = tool.getOutputFlag();
				outputPrefix = tool.getOutputPrefix();

				// Call the command line generator
				IManagedCommandLineGenerator cmdLGen = tool.getCommandLineGenerator();
				cmdLInfo = cmdLGen.generateCommandLineInfo(tool, cmd, flags, outflag, outputPrefix,
						OUT_MACRO + otherPrimaryOutputs, inputStrings, tool.getCommandLinePattern());

			} else {
				outflag = tool.getOutputFlag();//config.getOutputFlag(outputExtension);
				outputPrefix = tool.getOutputPrefix();//config.getOutputPrefix(outputExtension);

				// Call the command line generator
				cmdLInfo = generateToolCommandLineInfo(tool, inputExtension, flags, outflag, outputPrefix,
						OUT_MACRO + otherPrimaryOutputs, inputStrings, sourceLocation, outputLocation);
			}

			// The command to build
			String buildCmd;
			if (cmdLInfo != null) {
				buildCmd = cmdLInfo.getCommandLine();
			} else {
				StringBuffer buildFlags = new StringBuffer();
				for (String flag : flags) {
					if (flag != null) {
						buildFlags.append(flag).append(WHITESPACE);
					}
				}
				buildCmd = cmd + WHITESPACE + buildFlags.toString().trim() + WHITESPACE + outflag + WHITESPACE
						+ outputPrefix + OUT_MACRO + otherPrimaryOutputs + WHITESPACE + IN_MACRO;
			}

			// resolve any remaining macros in the command after it has been
			// generated
			try {
				String resolvedCommand;
				IBuildMacroProvider provider = ManagedBuildManager.getBuildMacroProvider();
				if (!needExplicitRuleForFile) {
					resolvedCommand = provider.resolveValueToMakefileFormat(buildCmd, EMPTY_STRING, WHITESPACE,
							IBuildMacroProvider.CONTEXT_FILE,
							new FileContextData(sourceLocation, outputLocation, null, tool));
				} else {
					// if we need an explicit rule then don't use any builder
					// variables, resolve everything to explicit strings
					resolvedCommand = provider.resolveValue(buildCmd, EMPTY_STRING, WHITESPACE,
							IBuildMacroProvider.CONTEXT_FILE,
							new FileContextData(sourceLocation, outputLocation, null, tool));
				}

				if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
					buildCmd = resolvedCommand;

			} catch (BuildMacroException e) {
			}

			//buffer.append(TAB).append(AT).append(escapedEcho(buildCmd));
			//buffer.append(TAB).append(AT).append(buildCmd);
			buffer.append(TAB).append(buildCmd);

			// Determine if there are any dependencies to calculate
			if (doDepGen) {
				// Get the dependency rule out of the generator
				String[] depCmds = null;
				if (oldDepGen != null) {
					depCmds = new String[1];
					depCmds[0] = oldDepGen.getDependencyCommand(resource, ManagedBuildManager.getBuildInfo(project));
				} else {
					if (depCommands != null) {
						depCmds = depCommands.getPostToolDependencyCommands();
					}
				}

				if (depCmds != null) {
					for (String depCmd : depCmds) {
						// Resolve any macros in the dep command after it has been generated.
						// Note:  do not trim the result because it will strip out necessary tab characters.
						buffer.append(WHITESPACE).append(LOGICAL_AND).append(WHITESPACE).append(LINEBREAK);
						try {
							if (!needExplicitRuleForFile) {
								depCmd = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
										depCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
										new FileContextData(sourceLocation, outputLocation, null, tool));
							}

							else {
								depCmd = ManagedBuildManager.getBuildMacroProvider().resolveValue(depCmd, EMPTY_STRING,
										WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
										new FileContextData(sourceLocation, outputLocation, null, tool));
							}

						} catch (BuildMacroException e) {
						}

						buffer.append(depCmd);
					}
				}
			}

			// Echo finished message
			buffer.append(NEWLINE);
			buffer.append(TAB).append(AT).append(escapedEcho(MESSAGE_FINISH_FILE + WHITESPACE + IN_MACRO));
			buffer.append(TAB).append(AT).append(ECHO_BLANK_LINE).append(NEWLINE);
		}

		// Determine if there are calculated dependencies
		IPath[] addlDeps = null; // IPath's that are relative to the build directory
		IPath[] addlTargets = null; // IPath's that are relative to the build directory
		String calculatedDependencies = null;
		boolean addedDepLines = false;
		String depLine;
		if (oldDepGen != null && oldDepGen.getCalculatorType() != IManagedDependencyGeneratorType.TYPE_COMMAND) {
			addlDeps = oldCalculateDependenciesForSource(oldDepGen, tool, relativePath, resource);
		} else {
			if (depGen != null && depGen.getCalculatorType() == IManagedDependencyGeneratorType.TYPE_CUSTOM) {
				if (depInfo instanceof IManagedDependencyCalculator) {
					IManagedDependencyCalculator depCalculator = (IManagedDependencyCalculator) depInfo;
					addlDeps = calculateDependenciesForSource(depCalculator);
					addlTargets = depCalculator.getAdditionalTargets();
				}
			}
		}

		if (addlDeps != null && addlDeps.length > 0) {
			calculatedDependencies = ""; //$NON-NLS-1$
			for (IPath addlDep : addlDeps) {
				calculatedDependencies += WHITESPACE + escapeWhitespaces(addlDep.toString());
			}
		}

		if (calculatedDependencies != null) {
			depLine = primaryOutputName + COLON + calculatedDependencies + NEWLINE;
			if (!getDepLineList().contains(depLine)) {
				getDepLineList().add(depLine);
				addedDepLines = true;
				buffer.append(depLine);
			}
		}

		// Add any additional outputs here using dependency lines
		Vector<IPath> addlOutputs = new Vector<>();
		if (enumeratedPrimaryOutputs.size() > 1) {
			// Starting with 1 is intentional in order to skip the primary output
			for (int i = 1; i < enumeratedPrimaryOutputs.size(); i++)
				addlOutputs.add(enumeratedPrimaryOutputs.get(i));
		}
		addlOutputs.addAll(enumeratedSecondaryOutputs);
		if (addlTargets != null) {
			for (IPath addlTarget : addlTargets)
				addlOutputs.add(addlTarget);
		}
		for (int i = 0; i < addlOutputs.size(); i++) {
			depLine = escapeWhitespaces(addlOutputs.get(i).toString()) + COLON + WHITESPACE + primaryOutputName;
			if (calculatedDependencies != null)
				depLine += calculatedDependencies;
			depLine += NEWLINE;
			if (!getDepLineList().contains(depLine)) {
				getDepLineList().add(depLine);
				addedDepLines = true;
				buffer.append(depLine);
			}
		}
		if (addedDepLines) {
			buffer.append(NEWLINE);
		}

		//  If we are using a dependency calculator of type TYPE_PREBUILD_COMMANDS,
		//  get the rule to build the dependency file
		if (depPreBuild != null && depFiles != null) {
			addedDepLines = false;
			String[] preBuildCommands = depPreBuild.getDependencyCommands();
			if (preBuildCommands != null) {
				depLine = ""; //$NON-NLS-1$
				//  Can we use a pattern rule?
				patternRule = !isItLinked && !needExplicitRuleForFile && depPreBuild.areCommandsGeneric();
				//  Begin building the rule
				for (int i = 0; i < depFiles.length; i++) {
					if (i > 0)
						depLine += WHITESPACE;
					if (patternRule) {
						optDotExt = EMPTY_STRING;
						String depExt = depFiles[i].getFileExtension();
						if (depExt != null && depExt.length() > 0)
							optDotExt = DOT + depExt;
						depLine += escapeWhitespaces(relativePath + WILDCARD + optDotExt);
					} else {
						depLine += escapeWhitespaces((depFiles[i]).toString());
					}
				}
				depLine += COLON + WHITESPACE + (patternRule ? patternBuildRuleDependencies : buildRuleDependencies)
						+ WHITESPACE + escapeWhitespaces(relativePath + MODFILE_NAME);
				if (!getDepRuleList().contains(depLine)) {
					getDepRuleList().add(depLine);
					addedDepLines = true;
					buffer.append(depLine).append(NEWLINE);
					buffer.append(TAB).append(AT)
							.append(escapedEcho(MESSAGE_START_DEPENDENCY + WHITESPACE + OUT_MACRO));
					for (String preBuildCommand : preBuildCommands) {
						depLine = preBuildCommand;
						// Resolve macros
						try {
							if (!needExplicitRuleForFile) {
								depLine = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
										depLine, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
										new FileContextData(sourceLocation, outputLocation, null, tool));
							}

							else {
								depLine = ManagedBuildManager.getBuildMacroProvider().resolveValue(depLine,
										EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE,
										new FileContextData(sourceLocation, outputLocation, null, tool));
							}

						} catch (BuildMacroException e) {
						}
						//buffer.append(TAB).append(AT).append(escapedEcho(depLine));
						//buffer.append(TAB).append(AT).append(depLine).append(NEWLINE);
						buffer.append(TAB).append(depLine).append(NEWLINE);
					}
				}
				if (addedDepLines) {
					buffer.append(TAB).append(AT).append(ECHO_BLANK_LINE).append(NEWLINE);
				}
			}
		}
	}

	/*
	 * Add any dependency calculator options to the tool options
	 */
	private String[] addDependencyOptions(IManagedDependencyCommands depCommands, String[] flags) {
		String[] depOptions = depCommands.getDependencyCommandOptions();
		if (depOptions != null && depOptions.length > 0) {
			int flagsLen = flags.length;
			String[] flagsCopy = new String[flags.length + depOptions.length];
			for (int i = 0; i < flags.length; i++) {
				flagsCopy[i] = flags[i];
			}
			for (int i = 0; i < depOptions.length; i++) {
				flagsCopy[i + flagsLen] = depOptions[i];
			}
			flags = flagsCopy;
		}
		return flags;
	}

	/**
	 * Returns any additional resources specified for the tool in other InputType elements and AdditionalInput elements
	 */
	protected IPath[] getAdditionalResourcesForSource(ITool tool) {
		List<IPath> allRes = new ArrayList<>();
		IInputType[] types = tool.getInputTypes();
		for (IInputType type : types) {
			//  Additional resources come from 2 places.
			//  1.  From AdditionalInput childen
			IPath[] res = type.getAdditionalResources();
			for (IPath re : res) {
				allRes.add(re);
			}
			//  2.  From InputTypes that other than the primary input type
			if (!type.getPrimaryInput() && type != tool.getPrimaryInputType()) {
				String var = type.getBuildVariable();
				if (var != null && var.length() > 0) {
					allRes.add(Path.fromOSString("$(" + type.getBuildVariable() + ")")); //$NON-NLS-1$ //$NON-NLS-2$
				} else {
					//  Use file extensions
					String[] typeExts = type.getSourceExtensions(tool);
					for (IResource projectResource : projectResources) {
						if (projectResource.getType() == IResource.FILE) {
							String fileExt = projectResource.getFileExtension();
							if (fileExt == null) {
								fileExt = ""; //$NON-NLS-1$
							}
							for (String typeExt : typeExts) {
								if (fileExt.equals(typeExt)) {
									allRes.add(projectResource.getProjectRelativePath());
									break;
								}
							}
						}
					}
				}

				//  If an assignToOption has been specified, set the value of the option to the inputs
				IOption assignToOption = tool.getOptionBySuperClassId(type.getAssignToOptionId());
				IOption option = tool.getOptionBySuperClassId(type.getOptionId());
				if (assignToOption != null && option == null) {
					try {
						int optType = assignToOption.getValueType();
						IResourceInfo rcInfo = tool.getParentResourceInfo();
						if (rcInfo != null) {
							if (optType == IOption.STRING) {
								String optVal = ""; //$NON-NLS-1$
								for (int j = 0; j < allRes.size(); j++) {
									if (j != 0) {
										optVal += " "; //$NON-NLS-1$
									}
									String resPath = allRes.get(j).toString();
									if (!resPath.startsWith("$(")) { //$NON-NLS-1$
										IResource addlResource = project.getFile(resPath);
										if (addlResource != null) {
											IPath addlPath = addlResource.getLocation();
											if (addlPath != null) {
												resPath = ManagedBuildManager
														.calculateRelativePath(getTopBuildDir(), addlPath).toString();
											}
										}
									}
									optVal += ManagedBuildManager
											.calculateRelativePath(getTopBuildDir(), Path.fromOSString(resPath))
											.toString();
								}
								ManagedBuildManager.setOption(rcInfo, tool, assignToOption, optVal);
							} else if (optType == IOption.STRING_LIST || optType == IOption.LIBRARIES
									|| optType == IOption.OBJECTS || optType == IOption.INCLUDE_FILES
									|| optType == IOption.LIBRARY_PATHS || optType == IOption.LIBRARY_FILES
									|| optType == IOption.MACRO_FILES) {
								//TODO: do we need to do anything with undefs here?
								//  Note that the path(s) must be translated from project relative
								//  to top build directory relative
								String[] paths = new String[allRes.size()];
								for (int j = 0; j < allRes.size(); j++) {
									paths[j] = allRes.get(j).toString();
									if (!paths[j].startsWith("$(")) { //$NON-NLS-1$
										IResource addlResource = project.getFile(paths[j]);
										if (addlResource != null) {
											IPath addlPath = addlResource.getLocation();
											if (addlPath != null) {
												paths[j] = ManagedBuildManager
														.calculateRelativePath(getTopBuildDir(), addlPath).toString();
											}
										}
									}
								}
								ManagedBuildManager.setOption(rcInfo, tool, assignToOption, paths);
							} else if (optType == IOption.BOOLEAN) {
								boolean b = false;
								if (allRes.size() > 0)
									b = true;
								ManagedBuildManager.setOption(rcInfo, tool, assignToOption, b);
							} else if (optType == IOption.ENUMERATED || optType == IOption.TREE) {
								if (allRes.size() > 0) {
									String s = allRes.get(0).toString();
									ManagedBuildManager.setOption(rcInfo, tool, assignToOption, s);
								}
							}
							allRes.clear();
						}
					} catch (BuildException ex) {
					}
				}
			}
		}
		return allRes.toArray(new IPath[allRes.size()]);
	}

	/**
	 * Returns the output <code>IPath</code>s for this invocation of the tool with the specified source file
	 *
	 * The priorities for determining the names of the outputs of a tool are:
	 *  1.  If the tool is the build target and primary output, use artifact name & extension -
	 *      This case does not apply here...
	 *  2.  If an option is specified, use the value of the option
	 *  3.  If a nameProvider is specified, call it
	 *  4.  If outputNames is specified, use it
	 *  5.  Use the name pattern to generate a transformation macro
	 *      so that the source names can be transformed into the target names
	 *      using the built-in string substitution functions of <code>make</code>.
	 *
	 *  @param relativePath  build output directory relative path of the current output directory
	 *  @param ruleOutputs  Vector of rule IPaths that are relative to the build directory
	 *  @param enumeratedPrimaryOutputs  Vector of IPaths of primary outputs
	 *                            that are relative to the build directory
	 *  @param enumeratedSecondaryOutputs  Vector of IPaths of secondary outputs
	 *                            that are relative to the build directory
	 */
	protected void calculateOutputsForSource(ITool tool, String relativePath, IResource resource, IPath sourceLocation,
			Vector<IPath> ruleOutputs, Vector<IPath> enumeratedPrimaryOutputs,
			Vector<IPath> enumeratedSecondaryOutputs) {
		String inExt = sourceLocation.getFileExtension();
		String outExt = tool.getOutputExtension(inExt);
		IResourceInfo rcInfo = tool.getParentResourceInfo();

		IOutputType[] outTypes = tool.getOutputTypes();
		if (outTypes != null && outTypes.length > 0) {
			for (IOutputType type : outTypes) {
				boolean primaryOutput = (type == tool.getPrimaryOutputType());
				//if (primaryOutput && ignorePrimary) continue;
				String outputPrefix = type.getOutputPrefix();

				// Resolve any macros in the outputPrefix
				// Note that we cannot use file macros because if we do a clean
				// we need to know the actual name of the file to clean, and
				// cannot use any builder variables such as $@. Hence we use the
				// next best thing, i.e. configuration context.

				// figure out the configuration we're using
				//                IBuildObject toolParent = tool.getParent();
				//                IConfiguration config = null;
				// if the parent is a config then we're done
				//                if (toolParent instanceof IConfiguration)
				//                    config = (IConfiguration) toolParent;
				//                else if (toolParent instanceof IToolChain) {
				//                    // must be a toolchain
				//                    config = (IConfiguration) ((IToolChain) toolParent)
				//                            .getParent();
				//                }
				//
				//                else if (toolParent instanceof IResourceConfiguration) {
				//                    config = (IConfiguration) ((IResourceConfiguration) toolParent)
				//                            .getParent();
				//                }

				//                else {
				//                    // bad
				//                    throw new AssertionError(
				//                            "tool parent must be one of configuration, toolchain, or resource configuration");
				//                }

				//                if (config != null) {

				try {

					if (containsSpecialCharacters(sourceLocation.toString())) {
						outputPrefix = ManagedBuildManager.getBuildMacroProvider().resolveValue(outputPrefix, "", //$NON-NLS-1$
								" ", //$NON-NLS-1$
								IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
					} else {
						outputPrefix = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
								outputPrefix, "", //$NON-NLS-1$
								" ", //$NON-NLS-1$
								IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
					}
				}

				catch (BuildMacroException e) {
				}

				//                }

				boolean multOfType = type.getMultipleOfType();
				IOption option = tool.getOptionBySuperClassId(type.getOptionId());
				IManagedOutputNameProvider nameProvider = type.getNameProvider();
				String[] outputNames = type.getOutputNames();

				//  1.  If the tool is the build target and this is the primary output,
				//      use artifact name & extension
				//      Not appropriate here...
				//  2.  If an option is specified, use the value of the option
				if (option != null) {
					try {
						List<String> outputList = new ArrayList<>();
						int optType = option.getValueType();
						if (optType == IOption.STRING) {
							outputList.add(outputPrefix + option.getStringValue());
						} else if (optType == IOption.STRING_LIST || optType == IOption.LIBRARIES
								|| optType == IOption.OBJECTS || optType == IOption.INCLUDE_FILES
								|| optType == IOption.LIBRARY_PATHS || optType == IOption.LIBRARY_FILES
								|| optType == IOption.MACRO_FILES) {
							@SuppressWarnings("unchecked")
							List<String> value = (List<String>) option.getValue();
							outputList = value;
							((Tool) tool).filterValues(optType, outputList);
							// Add outputPrefix to each if necessary
							if (outputPrefix.length() > 0) {
								for (int j = 0; j < outputList.size(); j++) {
									outputList.set(j, outputPrefix + outputList.get(j));
								}
							}
						}
						for (int j = 0; j < outputList.size(); j++) {
							String outputName = outputList.get(j);

							// try to resolve the build macros in the output
							// names
							try {

								String resolved = null;

								if (containsSpecialCharacters(sourceLocation.toString())) {
									resolved = ManagedBuildManager.getBuildMacroProvider().resolveValue(outputName, "", //$NON-NLS-1$
											" ", //$NON-NLS-1$
											IBuildMacroProvider.CONTEXT_FILE,
											new FileContextData(sourceLocation, null, option, tool));
								}

								else {
									resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
											outputName, "", //$NON-NLS-1$
											" ", //$NON-NLS-1$
											IBuildMacroProvider.CONTEXT_FILE,
											new FileContextData(sourceLocation, null, option, tool));
								}

								if ((resolved = resolved.trim()).length() > 0)
									outputName = resolved;
							} catch (BuildMacroException e) {
							}

							IPath outPath = Path.fromOSString(outputName);
							//  If only a file name is specified, add the relative path of this output directory
							if (outPath.segmentCount() == 1) {
								outPath = Path.fromOSString(relativePath + outputList.get(j));
							}
							if (primaryOutput) {
								ruleOutputs.add(j, outPath);
								enumeratedPrimaryOutputs.add(j, resolvePercent(outPath, sourceLocation));
							} else {
								ruleOutputs.add(outPath);
								enumeratedSecondaryOutputs.add(resolvePercent(outPath, sourceLocation));
							}
						}
					} catch (BuildException ex) {
					}
				} else
				//  3.  If a nameProvider is specified, call it
				if (nameProvider != null) {
					IPath[] inPaths = new IPath[1];
					inPaths[0] = sourceLocation;
					IPath[] outPaths = nameProvider.getOutputNames(tool, inPaths);
					if (outPaths != null) {
						for (int j = 0; j < outPaths.length; j++) {
							IPath outPath = outPaths[j];
							String outputName = outPaths[j].toString();

							// try to resolve the build macros in the output names
							try {

								String resolved = null;

								if (containsSpecialCharacters(sourceLocation.toString())) {
									resolved = ManagedBuildManager.getBuildMacroProvider().resolveValue(outputName, "", //$NON-NLS-1$
											" ", //$NON-NLS-1$
											IBuildMacroProvider.CONTEXT_FILE,
											new FileContextData(sourceLocation, null, option, tool));
								}

								else {
									resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
											outputName, "", //$NON-NLS-1$
											" ", //$NON-NLS-1$
											IBuildMacroProvider.CONTEXT_FILE,
											new FileContextData(sourceLocation, null, option, tool));
								}

								if ((resolved = resolved.trim()).length() > 0)
									outputName = resolved;
							} catch (BuildMacroException e) {
							}

							//  If only a file name is specified, add the relative path of this output directory
							if (outPath.segmentCount() == 1) {
								outPath = Path.fromOSString(relativePath + outPath.toString());
							}
							if (primaryOutput) {
								ruleOutputs.add(j, outPath);
								enumeratedPrimaryOutputs.add(j, resolvePercent(outPath, sourceLocation));
							} else {
								ruleOutputs.add(outPath);
								enumeratedSecondaryOutputs.add(resolvePercent(outPath, sourceLocation));
							}
						}
					}
				} else
				//  4.  If outputNames is specified, use it
				if (outputNames != null) {
					for (int j = 0; j < outputNames.length; j++) {
						String outputName = outputNames[j];
						try {
							//try to resolve the build macros in the output names
							String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
									outputName, "", //$NON-NLS-1$
									" ", //$NON-NLS-1$
									IBuildMacroProvider.CONTEXT_FILE,
									new FileContextData(sourceLocation, null, option, tool));
							if ((resolved = resolved.trim()).length() > 0)
								outputName = resolved;
						} catch (BuildMacroException e) {
						}

						IPath outPath = Path.fromOSString(outputName);
						//  If only a file name is specified, add the relative path of this output directory
						if (outPath.segmentCount() == 1) {
							outPath = Path.fromOSString(relativePath + outPath.toString());
						}
						if (primaryOutput) {
							ruleOutputs.add(j, outPath);
							enumeratedPrimaryOutputs.add(j, resolvePercent(outPath, sourceLocation));
						} else {
							ruleOutputs.add(outPath);
							enumeratedSecondaryOutputs.add(resolvePercent(outPath, sourceLocation));
						}
					}
				} else {
					//  5.  Use the name pattern to generate a transformation macro
					//      so that the source names can be transformed into the target names
					//      using the built-in string substitution functions of <code>make</code>.
					if (multOfType) {
						// This case is not handled - a nameProvider or outputNames must be specified
						// TODO - report error
					} else {
						String namePattern = type.getNamePattern();
						IPath namePatternPath = null;
						if (namePattern == null || namePattern.length() == 0) {
							namePattern = relativePath + outputPrefix + IManagedBuilderMakefileGenerator.WILDCARD;
							if (outExt != null && outExt.length() > 0) {
								namePattern += DOT + outExt;
							}
							namePatternPath = Path.fromOSString(namePattern);
						} else {
							if (outputPrefix.length() > 0) {
								namePattern = outputPrefix + namePattern;
							}
							namePatternPath = Path.fromOSString(namePattern);
							//  If only a file name is specified, add the relative path of this output directory
							if (namePatternPath.segmentCount() == 1) {
								namePatternPath = Path.fromOSString(relativePath + namePatternPath.toString());
							}
						}

						if (primaryOutput) {
							ruleOutputs.add(0, namePatternPath);
							enumeratedPrimaryOutputs.add(0, resolvePercent(namePatternPath, sourceLocation));
						} else {
							ruleOutputs.add(namePatternPath);
							enumeratedSecondaryOutputs.add(resolvePercent(namePatternPath, sourceLocation));
						}
					}
				}
			}
		} else {
			// For support of pre-CDT 3.0 integrations.
			// NOTE WELL:  This only supports the case of a single "target tool"
			//     that consumes exactly all of the object files, $OBJS, produced
			//     by other tools in the build and produces a single output.
			//     In this case, the output file name is the input file name with
			//     the output extension.

			//if (!ignorePrimary) {
			String outPrefix = tool.getOutputPrefix();
			IPath outPath = Path.fromOSString(relativePath + outPrefix + WILDCARD);
			outPath = outPath.addFileExtension(outExt);
			ruleOutputs.add(0, outPath);
			enumeratedPrimaryOutputs.add(0, resolvePercent(outPath, sourceLocation));
			//}
		}
	}

	/**
	 * If the path contains a %, returns the path resolved using the resource name
	 *
	 */
	protected IPath resolvePercent(IPath outPath, IPath sourceLocation) {
		//  Get the input file name
		String fileName = sourceLocation.removeFileExtension().lastSegment();
		//  Replace the % with the file name
		String outName = outPath.toOSString().replaceAll("%", fileName); //$NON-NLS-1$
		IPath result = Path.fromOSString(outName);
		return DOT_SLASH_PATH.isPrefixOf(outPath) ? DOT_SLASH_PATH.append(result) : result;
	}

	/**
	 * Returns the dependency <code>IPath</code>s for this invocation of the tool with the specified source file
	 *
	 *  @param depGen  the dependency calculator
	 *  @param tool  tool used to build the source file
	 *  @param relativePath  build output directory relative path of the current output directory
	 *  @param resource  source file to scan for dependencies
	 *  @return Vector of IPaths that are relative to the build directory
	 */
	protected IPath[] oldCalculateDependenciesForSource(IManagedDependencyGenerator depGen, ITool tool,
			String relativePath, IResource resource) {
		Vector<IPath> deps = new Vector<>();
		int type = depGen.getCalculatorType();

		switch (type) {

		case IManagedDependencyGeneratorType.TYPE_INDEXER:
		case IManagedDependencyGeneratorType.TYPE_EXTERNAL:
			IResource[] res = depGen.findDependencies(resource, project);
			if (res != null) {
				for (IResource re : res) {
					IPath dep = null;
					if (re != null) {
						IPath addlPath = re.getLocation();
						if (addlPath != null) {
							dep = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), addlPath);
						}
					}
					if (dep != null) {
						deps.add(dep);
					}
				}
			}
			break;

		case IManagedDependencyGeneratorType.TYPE_NODEPS:
		default:
			break;
		}
		return deps.toArray(new IPath[deps.size()]);
	}

	/**
	 * Returns the dependency <code>IPath</code>s relative to the build directory
	 *
	 *  @param depCalculator  the dependency calculator
	 *  @return IPath[] that are relative to the build directory
	 */
	protected IPath[] calculateDependenciesForSource(IManagedDependencyCalculator depCalculator) {
		IPath[] addlDeps = depCalculator.getDependencies();
		if (addlDeps != null) {
			for (int i = 0; i < addlDeps.length; i++) {
				if (!addlDeps[i].isAbsolute()) {
					// Convert from project relative to build directory relative
					IPath absolutePath = project.getLocation().append(addlDeps[i]);
					addlDeps[i] = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), absolutePath);
				}
			}
		}
		return addlDeps;
	}

	/*************************************************************************
	 *   M A K E F I L E   G E N E R A T I O N   C O M M O N   M E T H O D S
	 ************************************************************************/

	/**
	 * Generates a source macro name from a file extension
	 */
	public StringBuffer getSourceMacroName(String extensionName) {
		StringBuffer macroName = new StringBuffer();

		// We need to handle case sensitivity in file extensions (e.g. .c vs .C), so if the
		// extension was already upper case, tack on an "UPPER_" to the macro name.
		// In theory this means there could be a conflict if you had for example,
		// extensions .c_upper, and .C, but realistically speaking the chances of this are
		// practically nil so it doesn't seem worth the hassle of generating a truly
		// unique name.
		if (extensionName.equals(extensionName.toUpperCase())) {
			macroName.append(extensionName.toUpperCase()).append("_UPPER"); //$NON-NLS-1$
		} else {
			// lower case... no need for "UPPER_"
			macroName.append(extensionName.toUpperCase());
		}
		macroName.append("_SRCS"); //$NON-NLS-1$
		return macroName;
	}

	/**
	 * Generates a generated dependency file macro name from a file extension
	 */
	public StringBuffer getDepMacroName(String extensionName) {
		StringBuffer macroName = new StringBuffer();

		// We need to handle case sensitivity in file extensions (e.g. .c vs .C), so if the
		// extension was already upper case, tack on an "UPPER_" to the macro name.
		// In theory this means there could be a conflict if you had for example,
		// extensions .c_upper, and .C, but realistically speaking the chances of this are
		// practically nil so it doesn't seem worth the hassle of generating a truly
		// unique name.
		if (extensionName.equals(extensionName.toUpperCase())) {
			macroName.append(extensionName.toUpperCase()).append("_UPPER"); //$NON-NLS-1$
		} else {
			// lower case... no need for "UPPER_"
			macroName.append(extensionName.toUpperCase());
		}
		macroName.append("_DEPS"); //$NON-NLS-1$
		return macroName;
	}

	/**
	 * Answers all of the output extensions that the target
	 * of the build has tools defined to work on.
	 *
	 * @return a <code>Set</code> containing all of the output extensions
	 */
	public Set<String> getOutputExtensions(ToolInfoHolder h) {
		if (h.outputExtensionsSet == null) {
			// The set of output extensions which will be produced by this tool.
			// It is presumed that this set is not very large (likely < 10) so
			// a HashSet should provide good performance.
			h.outputExtensionsSet = new HashSet<>();

			// For each tool for the target, lookup the kinds of sources it outputs
			// and add that to our list of output extensions.
			for (ITool tool : h.buildTools) {
				String[] outputs = tool.getAllOutputExtensions();
				if (outputs != null) {
					h.outputExtensionsSet.addAll(Arrays.asList(outputs));
				}
			}
		}
		return h.outputExtensionsSet;
	}

	/**
	 *  This method postprocesses a .d file created by a build.
	 *  It's main job is to add dummy targets for the header files dependencies.
	 *  This prevents make from aborting the build if the header file does not exist.
	 *
	 *  A secondary job is to work in tandem with the "echo" command that is used
	 *  by some tool-chains in order to get the "targets" part of the dependency rule
	 *  correct.
	 *
	 *  This method adds a comment to the beginning of the dependency file which it
	 *  checks for to determine if this dependency file has already been updated.
	 *
	 * @return a <code>true</code> if the dependency file is modified
	 * @since 9.3
	 */
	public boolean generateDummyTargets(IConfiguration cfg, IFile makefile, boolean force)
			throws CoreException, IOException {
		return generateDummyTargets(cfg.getRootFolderInfo(), makefile, force);
	}

	/**
	 * @since 9.3
	 */
	public boolean generateDummyTargets(IResourceInfo rcInfo, IFile makefile, boolean force)
			throws CoreException, IOException {

		if (makefile == null || !makefile.exists())
			return false;

		// Get the contents of the dependency file
		StringBuffer inBuffer;
		InputStream contentStream = makefile.getContents(false);
		try (Reader in = new InputStreamReader(contentStream)) {
			int chunkSize = contentStream.available();
			inBuffer = new StringBuffer(chunkSize);
			char[] readBuffer = new char[chunkSize];
			int n = in.read(readBuffer);
			while (n > 0) {
				inBuffer.append(readBuffer);
				n = in.read(readBuffer);
			}
		}

		// The rest of this operation is equally expensive, so
		// if we are doing an incremental build, only update the
		// files that do not have a comment
		String inBufferString = inBuffer.toString();
		if (!force && inBufferString.startsWith(COMMENT_SYMBOL)) {
			return false;
		}

		// Try to determine if this file already has dummy targets defined.
		// If so, we will only add the comment.
		String[] bufferLines = inBufferString.split("[\\r\\n]"); //$NON-NLS-1$
		for (String bufferLine : bufferLines) {
			if (bufferLine.endsWith(":")) { //$NON-NLS-1$
				StringBuffer outBuffer = addGenericHeader();
				outBuffer.append(inBuffer);
				save(outBuffer, makefile);
				return true;
			}
		}

		// Reconstruct the buffer tokens into useful chunks of dependency information
		Vector<String> bufferTokens = new Vector<>(Arrays.asList(inBufferString.split("\\s"))); //$NON-NLS-1$
		Vector<String> deps = new Vector<>(bufferTokens.size());
		Iterator<String> tokenIter = bufferTokens.iterator();
		while (tokenIter.hasNext()) {
			String token = tokenIter.next();
			if (token.lastIndexOf("\\") == token.length() - 1 && token.length() > 1) { //$NON-NLS-1$
				// This is escaped so keep adding to the token until we find the end
				while (tokenIter.hasNext()) {
					String nextToken = tokenIter.next();
					token += WHITESPACE + nextToken;
					if (!nextToken.endsWith("\\")) { //$NON-NLS-1$
						//$NON-NLS-1$
						break;
					}
				}
			}
			deps.add(token);
		}
		deps.trimToSize();

		// Now find the header file dependencies and make dummy targets for them
		boolean save = false;
		StringBuffer outBuffer = null;

		// If we are doing an incremental build, only update the files that do not have a comment
		String firstToken;
		try {
			firstToken = deps.get(0);
		} catch (ArrayIndexOutOfBoundsException e) {
			// This makes no sense so bail
			return false;
		}

		// Put the generated comments in the output buffer
		if (!firstToken.startsWith(COMMENT_SYMBOL)) {
			outBuffer = addGenericHeader();
		} else {
			outBuffer = new StringBuffer();
		}

		// Some echo implementations misbehave and put the -n and newline in the output
		if (firstToken.startsWith("-n")) { //$NON-NLS-1$

			// Now let's parse:
			// Win32 outputs -n '<path>/<file>.d <path>/'
			// POSIX outputs -n <path>/<file>.d <path>/
			// Get the dep file name
			String secondToken;
			try {
				secondToken = deps.get(1);
			} catch (ArrayIndexOutOfBoundsException e) {
				secondToken = ""; //$NON-NLS-1$
			}
			if (secondToken.startsWith("'")) { //$NON-NLS-1$
				// This is the Win32 implementation of echo (MinGW without MSYS)
				outBuffer.append(secondToken.substring(1)).append(WHITESPACE);
			} else {
				outBuffer.append(secondToken).append(WHITESPACE);
			}

			// The relative path to the build goal comes next
			String thirdToken;
			try {
				thirdToken = deps.get(2);
			} catch (ArrayIndexOutOfBoundsException e) {
				thirdToken = ""; //$NON-NLS-1$
			}
			int lastIndex = thirdToken.lastIndexOf("'"); //$NON-NLS-1$
			if (lastIndex != -1) {
				if (lastIndex == 0) {
					outBuffer.append(WHITESPACE);
				} else {
					outBuffer.append(thirdToken.substring(0, lastIndex - 1));
				}
			} else {
				outBuffer.append(thirdToken);
			}

			// Followed by the target output by the compiler plus ':'
			// If we see any empty tokens here, assume they are the result of
			// a line feed output by "echo" and skip them
			String fourthToken;
			int nToken = 3;
			try {
				do {
					fourthToken = deps.get(nToken++);
				} while (fourthToken.length() == 0);

			} catch (ArrayIndexOutOfBoundsException e) {
				fourthToken = ""; //$NON-NLS-1$
			}
			outBuffer.append(fourthToken).append(WHITESPACE);

			// Followed by the actual dependencies
			try {
				for (String nextElement : deps) {
					if (nextElement.endsWith("\\")) { //$NON-NLS-1$
						outBuffer.append(nextElement).append(NEWLINE).append(WHITESPACE);
					} else {
						outBuffer.append(nextElement).append(WHITESPACE);
					}
				}
			} catch (IndexOutOfBoundsException e) {
			}

		} else {
			outBuffer.append(inBuffer);
		}

		outBuffer.append(NEWLINE);
		save = true;

		IFolderInfo fo = null;
		if (rcInfo instanceof IFolderInfo) {
			fo = (IFolderInfo) rcInfo;
		} else {
			IConfiguration c = rcInfo.getParent();
			fo = (IFolderInfo) c.getResourceInfo(rcInfo.getPath().removeLastSegments(1), false);
		}
		// Dummy targets to add to the makefile
		for (String dummy : deps) {
			IPath dep = new Path(dummy);
			String extension = dep.getFileExtension();
			if (fo.isHeaderFile(extension)) {
				/*
				 * The formatting here is
				 * <dummy_target>:
				 */
				outBuffer.append(dummy).append(COLON).append(NEWLINE).append(NEWLINE);
			}
		}

		// Write them out to the makefile
		if (save) {
			save(outBuffer, makefile);
			return true;
		}

		return false;
	}

	/**
	 * prepend all instanced of '\' or '"' with a backslash
	 *
	 * @return resulting string
	 */
	static public String escapedEcho(String string) {
		String escapedString = string.replaceAll("'", "'\"'\"'"); //$NON-NLS-1$ //$NON-NLS-2$
		return ECHO + WHITESPACE + SINGLE_QUOTE + escapedString + SINGLE_QUOTE + NEWLINE;
	}

	static public String ECHO_BLANK_LINE = ECHO + WHITESPACE + SINGLE_QUOTE + WHITESPACE + SINGLE_QUOTE + NEWLINE;

	/**
	 * Outputs a comment formatted as follows:
	 * ##### ....... #####
	 * # <Comment message>
	 * ##### ....... #####
	 * @since 9.3
	 */
	protected StringBuffer addGenericHeader() {
		StringBuffer buffer = new StringBuffer();
		outputCommentLine(buffer);
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(HEADER))
				.append(NEWLINE);
		addCustomHeader(buffer);
		outputCommentLine(buffer);
		buffer.append(NEWLINE);
		return buffer;
	}

	/**
	 * @since 9.3
	 */
	protected void addCustomHeader(StringBuffer buffer) {
	}

	/**
	 * Put COLS_PER_LINE comment charaters in the argument.
	 */
	static protected void outputCommentLine(StringBuffer buffer) {
		for (int i = 0; i < COLS_PER_LINE; i++) {
			buffer.append(COMMENT_SYMBOL);
		}
		buffer.append(NEWLINE);
	}

	static public boolean containsSpecialCharacters(String path) {
		return path.matches(".*(\\s|[\\{\\}\\(\\)\\$\\@%=;]).*"); //$NON-NLS-1$
	}

	/**
	 * Answers the argument with all whitespaces replaced with an escape sequence.
	 */
	static public String escapeWhitespaces(String path) {
		// Escape the spaces in the path/filename if it has any
		String[] segments = path.split("\\s"); //$NON-NLS-1$
		if (segments.length > 1) {
			StringBuffer escapedPath = new StringBuffer();
			for (int index = 0; index < segments.length; ++index) {
				escapedPath.append(segments[index]);
				if (index + 1 < segments.length) {
					escapedPath.append("\\ "); //$NON-NLS-1$
				}
			}
			return escapedPath.toString().trim();
		} else {
			return path;
		}
	}

	/**
	 * Adds a macro addition prefix to a map of macro names to entries.
	 * Entry prefixes look like:
	 * 	C_SRCS += \
	 * 	${addprefix $(ROOT)/, \
	 */
	// TODO fix comment
	protected void addMacroAdditionPrefix(LinkedHashMap<String, String> map, String macroName, String relativePath,
			boolean addPrefix) {
		// there is no entry in the map, so create a buffer for this macro
		StringBuffer tempBuffer = new StringBuffer();
		tempBuffer.append(macroName).append(WHITESPACE).append(MACRO_ADDITION_PREFIX_SUFFIX);
		if (addPrefix) {
			tempBuffer.append(MACRO_ADDITION_ADDPREFIX_HEADER).append(relativePath)
					.append(MACRO_ADDITION_ADDPREFIX_SUFFIX);
		}

		// have to store the buffer in String form as StringBuffer is not a sublcass of Object
		map.put(macroName, tempBuffer.toString());
	}

	/**
	 * Adds a file to an entry in a map of macro names to entries.
	 * File additions look like:
	 * 	example.c, \
	 */
	protected void addMacroAdditionFile(HashMap<String, String> map, String macroName, String filename) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(map.get(macroName));

		// escape whitespace in the filename
		filename = escapeWhitespaces(filename);

		buffer.append(filename).append(WHITESPACE).append(LINEBREAK);
		// re-insert string in the map
		map.put(macroName, buffer.toString());
	}

	/**
	 * Adds a file to an entry in a map of macro names to entries.
	 * File additions look like:
	 * 	example.c, \
	 */
	protected void addMacroAdditionFile(HashMap<String, String> map, String macroName, String relativePath,
			IPath sourceLocation, boolean generatedSource) {
		//  Add the source file path to the makefile line that adds source files to the build variable
		String srcName;
		IPath projectLocation = getPathForResource(project);
		IPath dirLocation = projectLocation;
		if (generatedSource) {
			dirLocation = dirLocation.append(getBuildWorkingDir());
		}
		if (dirLocation.isPrefixOf(sourceLocation)) {
			IPath srcPath = sourceLocation.removeFirstSegments(dirLocation.segmentCount()).setDevice(null);
			if (generatedSource) {
				srcName = "./" + srcPath.toString(); //$NON-NLS-1$
			} else {
				srcName = reachProjectRoot() + SEPARATOR + srcPath.toString();
			}
		} else {
			if (generatedSource && !sourceLocation.isAbsolute()) {
				srcName = "./" + relativePath + sourceLocation.lastSegment().toString(); //$NON-NLS-1$
			} else {
				// TODO:  Should we use relative paths when possible (e.g., see MbsMacroSupplier.calculateRelPath)
				srcName = sourceLocation.toString();
			}
		}
		addMacroAdditionFile(map, macroName, srcName);
	}

	/**
	 * Adds file(s) to an entry in a map of macro names to entries.
	 */
	public void addMacroAdditionFiles(Map<String, Set<String>> map, String macroName, Vector<String> filenames) {
		Set<String> set = map.get(macroName);

		for (String filename : filenames) {
			if (!filename.isEmpty()) {
				set.add(filename);
			}
		}
	}

	/**
	 * Write all macro addition entries in a map to the buffer
	 */
	protected StringBuffer writeAdditionMacros(LinkedHashMap<String, String> map) {
		StringBuffer buffer = new StringBuffer();
		// Add the comment
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(MOD_VARS))
				.append(NEWLINE);

		for (String macroString : map.values()) {
			// Check if we added any files to the rule
			// Currently, we do this by comparing the end of the rule buffer to MACRO_ADDITION_PREFIX_SUFFIX
			if (!(macroString.endsWith(MACRO_ADDITION_PREFIX_SUFFIX))) {
				StringBuffer currentBuffer = new StringBuffer();

				// Remove the final "/"
				if (macroString.endsWith(LINEBREAK)) {
					macroString = macroString.substring(0, (macroString.length() - 2)) + NEWLINE;
				}
				currentBuffer.append(macroString);

				currentBuffer.append(NEWLINE);

				// append the contents of the buffer to the master buffer for
				// the whole file
				buffer.append(currentBuffer);
			}
		}
		return buffer.append(NEWLINE);
	}

	/**
	 * Write all macro addition entries in a map to the buffer
	 */
	protected StringBuffer writeTopAdditionMacros(List<String> varList, Map<String, Set<String>> varMap) {
		StringBuffer buffer = new StringBuffer();
		// Add the comment
		buffer.append(COMMENT_SYMBOL).append(WHITESPACE).append(ManagedMakeMessages.getResourceString(MOD_VARS))
				.append(NEWLINE);

		for (String macroName : varList) {
			Set<String> files = varMap.get(macroName);

			buffer.append(macroName).append(WHITESPACE).append(MACRO_ADDITION_PREFIX_SUFFIX);

			for (String filename : files) {
				// Bug 417228, ilg@livius.net & freidin.alex@gmail.com
				filename = ensurePathIsGNUMakeTargetRuleCompatibleSyntax(filename);

				buffer.append(filename).append(WHITESPACE).append(LINEBREAK);
			}

			buffer.append(NEWLINE);
		}
		return buffer.append(NEWLINE);
	}

	/**
	 * Calculates the inputs and outputs for tools that will be generated in the top makefile.
	 * This information is used by the top level makefile generation methods.
	 */
	protected void calculateToolInputsOutputs() {

		toolInfos.accept(new IPathSettingsContainerVisitor() {
			@Override
			public boolean visit(PathSettingsContainer container) {
				ToolInfoHolder h = (ToolInfoHolder) container.getValue();
				ITool[] buildTools = h.buildTools;
				ManagedBuildGnuToolInfo[] gnuToolInfos = h.gnuToolInfos;
				//  We are "done" when the information for all tools has been calculated,
				//  or we are not making any progress
				boolean done = false;
				boolean lastChance = false;
				int[] doneState = new int[buildTools.length];

				// Identify the target tool
				ITool targetTool = config.calculateTargetTool();
				//		if (targetTool == null) {
				//			targetTool = info.getToolFromOutputExtension(buildTargetExt);
				//		}

				//  Initialize the tool info array and the done state

				if (buildTools.length != 0 && buildTools[0].getCustomBuildStep())
					return true;

				for (int i = 0; i < buildTools.length; i++) {
					if ((buildTools[i] == targetTool)) {
						String ext = config.getArtifactExtension();
						//try to resolve the build macros in the artifact extension
						try {
							ext = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(ext, "", //$NON-NLS-1$
									" ", //$NON-NLS-1$
									IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
						} catch (BuildMacroException e) {
						}

						String name = config.getArtifactName();
						//try to resolve the build macros in the artifact name
						try {
							String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(
									name, "", //$NON-NLS-1$
									" ", //$NON-NLS-1$
									IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
							if ((resolved = resolved.trim()).length() > 0)
								name = resolved;
						} catch (BuildMacroException e) {
						}

						gnuToolInfos[i] = new ManagedBuildGnuToolInfo(project, buildTools[i], true, name, ext);
					} else {
						gnuToolInfos[i] = new ManagedBuildGnuToolInfo(project, buildTools[i], false, null, null);
					}
					doneState[i] = 0;
				}

				//  Initialize the build output variable to file additions map
				Map<String, Set<String>> map = getTopBuildOutputVars();
				Set<Entry<String, List<IPath>>> set = buildOutVars.entrySet();
				for (Entry<String, List<IPath>> entry : set) {
					String macroName = entry.getKey();

					// for projects with specific setting on folders/files do
					// not clear the macro value on subsequent passes
					// use TreeSet for deterministically sorted output
					map.putIfAbsent(macroName, new TreeSet<>());
				}

				// Set of input extensions for which macros have been created so far
				HashSet<String> handledDepsInputExtensions = new HashSet<>();
				HashSet<String> handledOutsInputExtensions = new HashSet<>();

				while (!done) {
					int[] testState = new int[doneState.length];
					for (int i = 0; i < testState.length; i++)
						testState[i] = 0;

					//  Calculate inputs
					for (int i = 0; i < gnuToolInfos.length; i++) {
						if (gnuToolInfos[i].areInputsCalculated()) {
							testState[i]++;
						} else {
							if (gnuToolInfos[i].calculateInputs(GnuMakefileGenerator.this, config, projectResources, h,
									lastChance)) {
								testState[i]++;
							}
						}
					}
					//  Calculate dependencies
					for (int i = 0; i < gnuToolInfos.length; i++) {
						if (gnuToolInfos[i].areDependenciesCalculated()) {
							testState[i]++;
						} else {
							if (gnuToolInfos[i].calculateDependencies(GnuMakefileGenerator.this, config,
									handledDepsInputExtensions, h, lastChance)) {
								testState[i]++;
							}
						}
					}
					//  Calculate outputs
					for (int i = 0; i < gnuToolInfos.length; i++) {
						if (gnuToolInfos[i].areOutputsCalculated()) {
							testState[i]++;
						} else {
							if (gnuToolInfos[i].calculateOutputs(GnuMakefileGenerator.this, config,
									handledOutsInputExtensions, lastChance)) {
								testState[i]++;
							}
						}
					}
					//  Are all calculated?  If so, done.
					done = true;
					for (int element : testState) {
						if (element != 3) {
							done = false;
							break;
						}
					}

					//  Test our "done" state vs. the previous "done" state.
					//  If we have made no progress, give it a "last chance" and then quit
					if (!done) {
						done = true;
						for (int i = 0; i < testState.length; i++) {
							if (testState[i] != doneState[i]) {
								done = false;
								break;
							}
						}
					}
					if (done) {
						if (!lastChance) {
							lastChance = true;
							done = false;
						}
					}
					if (!done) {
						doneState = testState;
					}
				}
				return true;
			}
		});
	}

	/**
	 * Returns the (String) list of files associated with the build variable
	 *
	 * @param variable  the variable name
	 * @param locationType  the format in which we want the filenames returned
	 * @param directory  project relative directory path used with locationType == DIRECTORY_RELATIVE
	 * @param getAll  only return the list if all tools that are going to contrubute to this
	 *                variable have done so.
	 * @return List
	 */
	public List<String> getBuildVariableList(ToolInfoHolder h, String variable, int locationType, IPath directory,
			boolean getAll) {
		ManagedBuildGnuToolInfo[] gnuToolInfos = h.gnuToolInfos;
		boolean done = true;
		for (int i = 0; i < gnuToolInfos.length; i++) {
			if (!gnuToolInfos[i].areOutputVariablesCalculated()) {
				done = false;
			}
		}
		if (!done && getAll)
			return null;
		List<IPath> list = buildSrcVars.get(variable);
		if (list == null) {
			list = buildOutVars.get(variable);
		}

		List<String> fileList = null;
		if (list != null) {
			//  Convert the items in the list to the location-type wanted by the caller,
			//  and to a string list
			IPath dirLocation = null;
			if (locationType != ABSOLUTE) {
				dirLocation = project.getLocation();
				if (locationType == PROJECT_SUBDIR_RELATIVE) {
					dirLocation = dirLocation.append(directory);
				}
			}
			for (int i = 0; i < list.size(); i++) {
				IPath path = list.get(i);
				if (locationType != ABSOLUTE) {
					if (dirLocation != null && dirLocation.isPrefixOf(path)) {
						path = path.removeFirstSegments(dirLocation.segmentCount()).setDevice(null);
					}
				}
				if (fileList == null) {
					fileList = new Vector<>();
				}
				fileList.add(path.toString());
			}
		}

		return fileList;
	}

	/**
	 * Returns the map of build variables to list of files
	 *
	 * @return HashMap
	 */
	public Map<String, List<IPath>> getBuildOutputVars() {
		return buildOutVars;
	}

	/**
	 * Returns the map of build variables used in the top makefile to list of files
	 */
	public Map<String, Set<String>> getTopBuildOutputVars() {
		return topBuildOutVars;
	}

	/**
	 * Returns the list of known build rules. This keeps me from generating duplicate
	 * rules for known file extensions.
	 *
	 * @return List
	 */
	protected Vector<String> getRuleList() {
		if (ruleList == null) {
			ruleList = new Vector<>();
		}
		return ruleList;
	}

	/**
	 * Returns the list of known dependency lines. This keeps me from generating duplicate
	 * lines.
	 *
	 * @return List
	 */
	protected Vector<String> getDepLineList() {
		if (depLineList == null) {
			depLineList = new Vector<>();
		}
		return depLineList;
	}

	/**
	 * Returns the list of known dependency file generation lines. This keeps me from
	 * generating duplicate lines.
	 *
	 * @return List
	 */
	protected Vector<String> getDepRuleList() {
		if (depRuleList == null) {
			depRuleList = new Vector<>();
		}
		return depRuleList;
	}

	/*************************************************************************
	 *   R E S O U R C E   V I S I T O R   M E T H O D S
	 ************************************************************************/

	/**
	 * Adds the container of the argument to the list of folders in the project that
	 * contribute source files to the build. The resource visitor has already established
	 * that the build model knows how to build the files. It has also checked that
	 * the resource is not generated as part of the build.
	 */
	protected void appendBuildSubdirectory(IResource resource) {
		IContainer container = resource.getParent();
		// Only add the container once
		if (!getSubdirList().contains(container))
			getSubdirList().add(container);
	}

	/**
	 * Adds the container of the argument to a list of subdirectories that are to be
	 * deleted. As a result, the directories that are generated for the output
	 * should be removed as well.
	 */
	protected void appendDeletedSubdirectory(IContainer container) {
		// No point in adding a folder if the parent is already there
		IContainer parent = container.getParent();
		if (!getDeletedDirList().contains(container) && !getDeletedDirList().contains(parent)) {
			getDeletedDirList().add(container);
		}
	}

	/**
	 * If a file is removed from a source folder (either because of a delete
	 * or move action on the part of the user), the makefilegenerator has to
	 * remove the dependency makefile along with the old build goal
	 */
	protected void appendDeletedFile(IResource resource) {
		// Cache this for now
		getDeletedFileList().add(resource);
	}

	/**
	 * Adds the container of the argument to a list of subdirectories that are part
	 * of an incremental rebuild of the project. The makefile fragments for these
	 * directories will be regenerated as a result of the build.
	 */
	protected void appendModifiedSubdirectory(IResource resource) {
		IContainer container = resource.getParent();

		if (!getModifiedList().contains(container)) {
			getModifiedList().add(container);
		}
	}

	/*************************************************************************
	 *   O T H E R   M E T H O D S
	 ************************************************************************/

	protected void cancel(String message) {
		if (monitor != null && !monitor.isCanceled()) {
			throw new OperationCanceledException(message);
		}
	}

	/**
	 * Check whether the build has been cancelled. Cancellation requests
	 * propagated to the caller by throwing <code>OperationCanceledException</code>.
	 *
	 * @see org.eclipse.core.runtime.OperationCanceledException#OperationCanceledException()
	 */
	protected void checkCancel() {
		if (monitor != null && monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
	}

	/**
	 * Return or create the folder needed for the build output. If we are
	 * creating the folder, set the derived bit to true so the CM system
	 * ignores the contents. If the resource exists, respect the existing
	 * derived setting.
	 */
	private IPath createDirectory(String dirName) throws CoreException {
		// Create or get the handle for the build directory
		IFolder folder = project.getFolder(dirName);
		if (!folder.exists()) {
			// Make sure that parent folders exist
			IPath parentPath = (new Path(dirName)).removeLastSegments(1);
			// Assume that the parent exists if the path is empty
			if (!parentPath.isEmpty()) {
				IFolder parent = project.getFolder(parentPath);
				if (!parent.exists()) {
					createDirectory(parentPath.toString());
				}
			}

			// Now make the requested folder
			try {
				folder.create(true, true, null);
			} catch (CoreException e) {
				if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
					folder.refreshLocal(IResource.DEPTH_ZERO, null);
				else
					throw e;
			}

			// Make sure the folder is marked as derived so it is not added to CM
			if (!folder.isDerived()) {
				folder.setDerived(true, null);
			}
		}

		return folder.getFullPath();
	}

	/**
	 * Return or create the makefile needed for the build. If we are creating
	 * the resource, set the derived bit to true so the CM system ignores
	 * the contents. If the resource exists, respect the existing derived
	 * setting.
	 */
	private IFile createFile(IPath makefilePath) throws CoreException {
		// Create or get the handle for the makefile
		IWorkspaceRoot root = CCorePlugin.getWorkspace().getRoot();
		IFile newFile = root.getFileForLocation(makefilePath);
		if (newFile == null) {
			newFile = root.getFile(makefilePath);
		}
		// Create the file if it does not exist
		ByteArrayInputStream contents = new ByteArrayInputStream(new byte[0]);
		try {
			newFile.create(contents, false, new SubProgressMonitor(monitor, 1));
			// Make sure the new file is marked as derived
			if (!newFile.isDerived()) {
				newFile.setDerived(true, null);
			}

		} catch (CoreException e) {
			// If the file already existed locally, just refresh to get contents
			if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
				newFile.refreshLocal(IResource.DEPTH_ZERO, null);
			else
				throw e;
		}

		return newFile;
	}

	private void deleteBuildTarget(IResource deletedFile) {
		// Get the project relative path of the file
		String fileName = getFileName(deletedFile);
		String srcExtension = deletedFile.getFileExtension();
		IPath folderPath = inFullPathFromOutFullPath(deletedFile.getFullPath().removeLastSegments(1));
		if (folderPath != null) {
			folderPath = folderPath.removeFirstSegments(1);
		} else {
			folderPath = new Path(""); //$NON-NLS-1$
		}
		IResourceInfo rcInfo = config.getResourceInfo(folderPath, false);
		if (rcInfo instanceof IFileInfo) {
			rcInfo = config.getResourceInfo(folderPath.removeLastSegments(1), false);
		}
		String targetExtension = ((IFolderInfo) rcInfo).getOutputExtension(srcExtension);
		if (!targetExtension.isEmpty())
			fileName += DOT + targetExtension;
		IPath projectRelativePath = deletedFile.getProjectRelativePath().removeLastSegments(1);
		IPath targetFilePath = getBuildWorkingDir().append(projectRelativePath).append(fileName);
		IResource depFile = project.findMember(targetFilePath);
		if (depFile != null && depFile.exists()) {
			try {
				depFile.delete(true, new SubProgressMonitor(monitor, 1));
			} catch (CoreException e) {
				// This had better be allowed during a build

			}
		}
	}

	private IPath inFullPathFromOutFullPath(IPath path) {
		IPath inPath = null;
		if (topBuildDir.isPrefixOf(path)) {
			inPath = path.removeFirstSegments(topBuildDir.segmentCount());
			inPath = project.getFullPath().append(path);
		}
		return inPath;
	}

	private void deleteDepFile(IResource deletedFile) {
		// Calculate the top build directory relative paths of the dependency files
		IPath[] depFilePaths = null;
		ITool tool = null;
		IManagedDependencyGeneratorType depType = null;
		String sourceExtension = deletedFile.getFileExtension();
		IPath folderPath = inFullPathFromOutFullPath(deletedFile.getFullPath().removeLastSegments(1));
		if (folderPath != null) {
			folderPath = folderPath.removeFirstSegments(1);
		} else {
			folderPath = new Path(""); //$NON-NLS-1$
		}
		ToolInfoHolder h = getToolInfo(folderPath);
		ITool[] tools = h.buildTools;
		for (int index = 0; index < tools.length; ++index) {
			if (tools[index].buildsFileType(sourceExtension)) {
				tool = tools[index];
				depType = tool.getDependencyGeneratorForExtension(sourceExtension);
				break;
			}
		}
		if (depType != null) {
			int calcType = depType.getCalculatorType();
			if (calcType == IManagedDependencyGeneratorType.TYPE_COMMAND) {
				depFilePaths = new IPath[1];
				IPath absolutePath = deletedFile.getLocation();
				depFilePaths[0] = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), absolutePath);
				depFilePaths[0] = depFilePaths[0].removeFileExtension().addFileExtension(DEP_EXT);
			} else if (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS
					|| calcType == IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS) {
				IManagedDependencyGenerator2 depGen = (IManagedDependencyGenerator2) depType;
				IManagedDependencyInfo depInfo = depGen.getDependencySourceInfo(deletedFile.getProjectRelativePath(),
						deletedFile, config, tool, getBuildWorkingDir());
				if (depInfo != null) {
					if (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS) {
						IManagedDependencyCommands depCommands = (IManagedDependencyCommands) depInfo;
						depFilePaths = depCommands.getDependencyFiles();
					} else if (calcType == IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS) {
						IManagedDependencyPreBuild depPreBuild = (IManagedDependencyPreBuild) depInfo;
						depFilePaths = depPreBuild.getDependencyFiles();
					}
				}
			}
		}

		// Delete the files if they exist
		if (depFilePaths != null) {
			for (IPath dfp : depFilePaths) {
				IPath depFilePath = getBuildWorkingDir().append(dfp);
				IResource depFile = project.findMember(depFilePath);
				if (depFile != null && depFile.exists()) {
					try {
						depFile.delete(true, new SubProgressMonitor(monitor, 1));
					} catch (CoreException e) {
						// This had better be allowed during a build
					}
				}
			}
		}
	}

	/**
	 * Returns the current build configuration.
	 *
	 * @return String
	 * @since 8.0
	 */
	protected IConfiguration getConfig() {
		return config;
	}

	/**
	 * Returns the build target extension.
	 *
	 * @return String
	 * @since 8.0
	 */
	protected String getBuildTargetExt() {
		return buildTargetExt;
	}

	/**
	 * Returns the build target name.
	 *
	 * @return String
	 * @since 8.0
	 */
	protected String getBuildTargetName() {
		return buildTargetName;
	}

	/**
	 * @return Returns the deletedDirList.
	 */
	private Vector<IResource> getDeletedDirList() {
		if (deletedDirList == null) {
			deletedDirList = new Vector<>();
		}
		return deletedDirList;
	}

	private Vector<IResource> getDeletedFileList() {
		if (deletedFileList == null) {
			deletedFileList = new Vector<>();
		}
		return deletedFileList;
	}

	private List<IPath> getDependencyMakefiles(ToolInfoHolder h) {
		if (h.dependencyMakefiles == null) {
			h.dependencyMakefiles = new ArrayList<>();
		}
		return h.dependencyMakefiles;
	}

	/**
	 * Strips off the file extension from the argument and returns
	 * the name component in a <code>String</code>
	 */
	private String getFileName(IResource file) {
		String answer = ""; //$NON-NLS-1$
		String lastSegment = file.getName();
		int extensionSeparator = lastSegment.lastIndexOf(DOT);
		if (extensionSeparator != -1) {
			answer = lastSegment.substring(0, extensionSeparator);
		}
		return answer;
	}

	/**
	 * Answers a Vector containing a list of directories that are invalid for the
	 * build for some reason. At the moment, the only reason a directory would
	 * not be considered for the build is if it contains a space in the relative
	 * path from the project root.
	 *
	 * @return a a list of directories that are invalid for the build
	 */
	private Vector<IResource> getInvalidDirList() {
		if (invalidDirList == null) {
			invalidDirList = new Vector<>();
		}
		return invalidDirList;
	}

	/**
	 * @return Collection of Containers which contain modified source files
	 */
	private Collection<IContainer> getModifiedList() {
		if (modifiedList == null)
			modifiedList = new LinkedHashSet<>();
		return modifiedList;
	}

	/**
	 * @return Collection of subdirectories (IContainers) contributing source code to the build
	 */
	private Collection<IContainer> getSubdirList() {
		if (subdirList == null)
			subdirList = new LinkedHashSet<>();
		return subdirList;
	}

	private void removeGeneratedDirectory(IContainer subDir) {
		try {
			// The source directory isn't empty
			if (subDir.exists() && subDir.members().length > 0)
				return;
		} catch (CoreException e) {
			// The resource doesn't exist so we should delete the output folder
		}

		// Figure out what the generated directory name is and delete it
		IPath moduleRelativePath = subDir.getProjectRelativePath();
		IPath buildRoot = getBuildWorkingDir();
		if (buildRoot == null) {
			return;
		}
		IPath moduleOutputPath = buildRoot.append(moduleRelativePath);
		IFolder folder = project.getFolder(moduleOutputPath);
		if (folder.exists()) {
			try {
				folder.delete(true, new SubProgressMonitor(monitor, 1));
			} catch (CoreException e) {
				// TODO Log this
			}
		}
	}

	protected void updateMonitor(String msg) {
		if (monitor != null && !monitor.isCanceled()) {
			monitor.subTask(msg);
			monitor.worked(1);
		}
	}

	/**
	 * Return the configuration's top build directory as an absolute path
	 */
	public IPath getTopBuildDir() {
		return getPathForResource(project).append(getBuildWorkingDir());
	}

	/**
	 * Process a String denoting a filepath in a way compatible for GNU Make rules, handling
	 * windows drive letters and whitespace appropriately.
	 * <p><p>
	 * The context these paths appear in is on the right hand side of a rule header. i.e.
	 * <p><p>
	 * target : dep1 dep2 dep3
	 * <p>
	 * @param path the String denoting the path to process
	 * @throws NullPointerException is path is null
	 * @return a suitable Make rule compatible path
	 */
	/* see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129782 */
	public String ensurePathIsGNUMakeTargetRuleCompatibleSyntax(String path) {
		boolean isQuotedOption = false;
		if (path.startsWith("-")) { //$NON-NLS-1$
			isQuotedOption = checkIfQuotedOption(path);
		}
		if (!isQuotedOption)
			return escapeWhitespaces(ensureUnquoted(path));
		return path;
	}

	private boolean checkIfQuotedOption(String path) {
		Matcher m1 = doubleQuotedOption.matcher(path);
		if (m1.matches())
			return true;
		Matcher m2 = singleQuotedOption.matcher(path);
		if (m2.matches())
			return true;
		return false;
	}

	/**
	 * Strips outermost quotes of Strings of the form "a" and 'a' or returns the original
	 * string if the input is not of this form.
	 *
	 * @throws NullPointerException if path is null
	 * @return a String without the outermost quotes (if the input has them)
	 */
	public static String ensureUnquoted(String path) {
		boolean doubleQuoted = path.startsWith("\"") && path.endsWith("\""); //$NON-NLS-1$ //$NON-NLS-2$
		boolean singleQuoted = path.startsWith("'") && path.endsWith("'"); //$NON-NLS-1$ //$NON-NLS-2$
		return doubleQuoted || singleQuoted ? path.substring(1, path.length() - 1) : path;
	}

	@Override
	public void initialize(int buildKind, IConfiguration cfg, IBuilder builder, IProgressMonitor monitor) {
		// Save the project so we can get path and member information
		this.project = cfg.getOwner().getProject();
		if (builder == null) {
			builder = cfg.getEditableBuilder();
		}
		try {
			projectResources = project.members();
		} catch (CoreException e) {
			projectResources = null;
		}
		// Save the monitor reference for reporting back to the user
		this.monitor = monitor;
		// Get the build info for the project
		//		this.info = info;
		// Get the name of the build target
		buildTargetName = cfg.getArtifactName();
		// Get its extension
		buildTargetExt = cfg.getArtifactExtension();

		try {
			//try to resolve the build macros in the target extension
			buildTargetExt = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(buildTargetExt,
					"", //$NON-NLS-1$
					" ", //$NON-NLS-1$
					IBuildMacroProvider.CONTEXT_CONFIGURATION, builder);
		} catch (BuildMacroException e) {
		}

		try {
			//try to resolve the build macros in the target name
			String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(buildTargetName,
					"", //$NON-NLS-1$
					" ", //$NON-NLS-1$
					IBuildMacroProvider.CONTEXT_CONFIGURATION, builder);
			if (resolved != null) {
				resolved = resolved.trim();
				if (resolved.length() > 0)
					buildTargetName = resolved;
			}
		} catch (BuildMacroException e) {
		}

		if (buildTargetExt == null) {
			buildTargetExt = ""; //$NON-NLS-1$
		}
		// Cache the build tools
		config = cfg;
		this.builder = builder;

		initToolInfos();
		//set the top build dir path
		initializeTopBuildDir(cfg.getName());

		srcEntries = config.getSourceEntries();
		if (srcEntries.length == 0) {
			srcEntries = new ICSourceEntry[] {
					new CSourceEntry(Path.EMPTY, null, ICSettingEntry.RESOLVED | ICSettingEntry.VALUE_WORKSPACE_PATH) };
		} else {
			ICConfigurationDescription cfgDes = ManagedBuildManager.getDescriptionForConfiguration(config);
			srcEntries = CDataUtil.resolveEntries(srcEntries, cfgDes);
		}
	}

	private void initToolInfos() {
		toolInfos = PathSettingsContainer.createRootContainer();

		IResourceInfo rcInfos[] = config.getResourceInfos();
		for (IResourceInfo rcInfo : rcInfos) {
			if (rcInfo.isExcluded() /*&& !((ResourceInfo)rcInfo).isRoot()*/)
				continue;

			ToolInfoHolder h = getToolInfo(rcInfo.getPath(), true);
			if (rcInfo instanceof IFolderInfo) {
				IFolderInfo fo = (IFolderInfo) rcInfo;
				h.buildTools = fo.getFilteredTools();
				h.buildToolsUsed = new boolean[h.buildTools.length];
				h.gnuToolInfos = new ManagedBuildGnuToolInfo[h.buildTools.length];
			} else {
				IFileInfo fi = (IFileInfo) rcInfo;
				h.buildTools = fi.getToolsToInvoke();
				h.buildToolsUsed = new boolean[h.buildTools.length];
				h.gnuToolInfos = new ManagedBuildGnuToolInfo[h.buildTools.length];
			}
		}
	}

	private ToolInfoHolder getToolInfo(IPath path) {
		return getToolInfo(path, false);
	}

	private ToolInfoHolder getFolderToolInfo(IPath path) {
		IResourceInfo rcInfo = config.getResourceInfo(path, false);
		while (rcInfo instanceof IFileInfo) {
			path = path.removeLastSegments(1);
			rcInfo = config.getResourceInfo(path, false);
		}
		return getToolInfo(path, false);
	}

	private ToolInfoHolder getToolInfo(IPath path, boolean create) {
		PathSettingsContainer child = toolInfos.getChildContainer(path, create, create);
		ToolInfoHolder h = null;
		if (child != null) {
			h = (ToolInfoHolder) child.getValue();
			if (h == null && create) {
				h = new ToolInfoHolder();
				child.setValue(h);
			}
		}
		return h;
	}

	private void ensureTopBuildDir() throws CoreException {
		IPath buildWorkingDir = getBuildWorkingDir();
		if (buildWorkingDir != null) {
			createDirectory(buildWorkingDir.toString());
		}
	}

	private void initializeTopBuildDir(String configName) {
		topBuildDir = project.getFolder(computeTopBuildDir(configName)).getFullPath();
	}

	/**
	 * Can be overwritten by a subclass to specify the top build directory to be
	 * used. Default implementation simply returns configuration name.
	 * <p>
	 * <strong>Note</strong>: be careful by overriding this method - all places in the custom code and related
	 * scripts using or referencing top build directory must also be changed to use same logic.
	 *
	 * @param configName name of the configuration
	 * @return project relative path for top build directory
	 * @since 8.7
	 */
	protected IPath computeTopBuildDir(String configName) {
		return new Path(configName);
	}

	/**
	 * @return As many ".." as required to get from getBuildWorkingDir() to the project root.
	 *
	 *         E.g. If getBuildWorkingDir() is "Debug", then the function returns "..". If
	 *         getBuildWorkingDir() returns "x86/Debug" then "../.." is returned.
	 *
	 * @since 8.7
	 */
	public String reachProjectRoot() {
		IPath buildWorkingDir = getBuildWorkingDir();
		if (buildWorkingDir == null) {
			return ROOT;
		}
		String root = ROOT;
		int segCnt = buildWorkingDir.segmentCount();
		for (int i = 1; i < segCnt; i++) {
			root += SEPARATOR + ROOT;
		}
		return root;
	}

	private String toCleanTarget(IPath path) {
		final BitSet allowedCodePoints = new BitSet(128);
		allowedCodePoints.set("A".codePointAt(0), "Z".codePointAt(0) + 1); //$NON-NLS-1$ //$NON-NLS-2$
		allowedCodePoints.set("a".codePointAt(0), "z".codePointAt(0) + 1); //$NON-NLS-1$ //$NON-NLS-2$
		allowedCodePoints.set("0".codePointAt(0), "9".codePointAt(0) + 1); //$NON-NLS-1$ //$NON-NLS-2$
		allowedCodePoints.set("_".codePointAt(0)); //$NON-NLS-1$

		StringBuilder sb = new StringBuilder("clean-"); //$NON-NLS-1$
		(path.isEmpty() ? DOT : path.toString()).codePoints().forEach(c -> {
			if (allowedCodePoints.get(c)) {
				sb.append(Character.toChars(c));
			} else {
				sb.append("-"); //$NON-NLS-1$
				sb.append(Long.toHexString(c));
				sb.append("-"); //$NON-NLS-1$
			}
		});

		return sb.toString();
	}
}

Back to the top