aboutsummaryrefslogtreecommitdiffstats
path: root/make.c
blob: b51f400f3fac96f6426830358642029cec897014 (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
/*	$NetBSD: make.c,v 1.86 2012/05/10 19:53:26 christos Exp $	*/

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

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

#ifndef MAKE_NATIVE
static char rcsid[] = "$NetBSD: make.c,v 1.86 2012/05/10 19:53:26 christos Exp $";
#else
#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)make.c	8.1 (Berkeley) 6/6/93";
#else
__RCSID("$NetBSD: make.c,v 1.86 2012/05/10 19:53:26 christos Exp $");
#endif
#endif /* not lint */
#endif

/*-
 * make.c --
 *	The functions which perform the examination of targets and
 *	their suitability for creation
 *
 * Interface:
 *	Make_Run 	    	Initialize things for the module and recreate
 *	    	  	    	whatever needs recreating. Returns TRUE if
 *	    	    	    	work was (or would have been) done and FALSE
 *	    	  	    	otherwise.
 *
 *	Make_Update	    	Update all parents of a given child. Performs
 *	    	  	    	various bookkeeping chores like the updating
 *	    	  	    	of the cmgn field of the parent, filling
 *	    	  	    	of the IMPSRC context variable, etc. It will
 *	    	  	    	place the parent on the toBeMade queue if it
 *	    	  	    	should be.
 *
 *	Make_TimeStamp	    	Function to set the parent's cmgn field
 *	    	  	    	based on a child's modification time.
 *
 *	Make_DoAllVar	    	Set up the various local variables for a
 *	    	  	    	target, including the .ALLSRC variable, making
 *	    	  	    	sure that any variable that needs to exist
 *	    	  	    	at the very least has the empty value.
 *
 *	Make_OODate 	    	Determine if a target is out-of-date.
 *
 *	Make_HandleUse	    	See if a child is a .USE node for a parent
 *				and perform the .USE actions if so.
 *
 *	Make_ExpandUse	    	Expand .USE nodes
 */

#include    "make.h"
#include    "hash.h"
#include    "dir.h"
#include    "job.h"

static unsigned int checked = 1;/* Sequence # to detect recursion */
static Lst     	toBeMade;	/* The current fringe of the graph. These
				 * are nodes which await examination by
				 * MakeOODate. It is added to by
				 * Make_Update and subtracted from by
				 * MakeStartJobs */

static int MakeAddChild(void *, void *);
static int MakeFindChild(void *, void *);
static int MakeUnmark(void *, void *);
static int MakeAddAllSrc(void *, void *);
static int MakeTimeStamp(void *, void *);
static int MakeHandleUse(void *, void *);
static Boolean MakeStartJobs(void);
static int MakePrintStatus(void *, void *);
static int MakeCheckOrder(void *, void *);
static int MakeBuildChild(void *, void *);
static int MakeBuildParent(void *, void *);

__dead static void
make_abort(GNode *gn, int line)
{
    static int two = 2;

    fprintf(debug_file, "make_abort from line %d\n", line);
    Targ_PrintNode(gn, &two);
    Lst_ForEach(toBeMade, Targ_PrintNode, &two);
    Targ_PrintGraph(3);
    abort();
}

/*-
 *-----------------------------------------------------------------------
 * Make_TimeStamp --
 *	Set the cmgn field of a parent node based on the mtime stamp in its
 *	child. Called from MakeOODate via Lst_ForEach.
 *
 * Input:
 *	pgn		the current parent
 *	cgn		the child we've just examined
 *
 * Results:
 *	Always returns 0.
 *
 * Side Effects:
 *	The cmgn of the parent node will be changed if the mtime
 *	field of the child is greater than it.
 *-----------------------------------------------------------------------
 */
int
Make_TimeStamp(GNode *pgn, GNode *cgn)
{
    if (pgn->cmgn == NULL || cgn->mtime > pgn->cmgn->mtime) {
	pgn->cmgn = cgn;
    }
    return (0);
}

/*
 * Input:
 *	pgn		the current parent
 *	cgn		the child we've just examined
 *
 */
static int
MakeTimeStamp(void *pgn, void *cgn)
{
    return Make_TimeStamp((GNode *)pgn, (GNode *)cgn);
}

/*-
 *-----------------------------------------------------------------------
 * Make_OODate --
 *	See if a given node is out of date with respect to its sources.
 *	Used by Make_Run when deciding which nodes to place on the
 *	toBeMade queue initially and by Make_Update to screen out USE and
 *	EXEC nodes. In the latter case, however, any other sort of node
 *	must be considered out-of-date since at least one of its children
 *	will have been recreated.
 *
 * Input:
 *	gn		the node to check
 *
 * Results:
 *	TRUE if the node is out of date. FALSE otherwise.
 *
 * Side Effects:
 *	The mtime field of the node and the cmgn field of its parents
 *	will/may be changed.
 *-----------------------------------------------------------------------
 */
Boolean
Make_OODate(GNode *gn)
{
    Boolean         oodate;

    /*
     * Certain types of targets needn't even be sought as their datedness
     * doesn't depend on their modification time...
     */
    if ((gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC)) == 0) {
	(void)Dir_MTime(gn, 1);
	if (DEBUG(MAKE)) {
	    if (gn->mtime != 0) {
		fprintf(debug_file, "modified %s...", Targ_FmtTime(gn->mtime));
	    } else {
		fprintf(debug_file, "non-existent...");
	    }
	}
    }

    /*
     * A target is remade in one of the following circumstances:
     *	its modification time is smaller than that of its youngest child
     *	    and it would actually be run (has commands or type OP_NOP)
     *	it's the object of a force operator
     *	it has no children, was on the lhs of an operator and doesn't exist
     *	    already.
     *
     * Libraries are only considered out-of-date if the archive module says
     * they are.
     *
     * These weird rules are brought to you by Backward-Compatibility and
     * the strange people who wrote 'Make'.
     */
    if (gn->type & (OP_USE|OP_USEBEFORE)) {
	/*
	 * If the node is a USE node it is *never* out of date
	 * no matter *what*.
	 */
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, ".USE node...");
	}
	oodate = FALSE;
    } else if ((gn->type & OP_LIB) &&
	       ((gn->mtime==0) || Arch_IsLib(gn))) {
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, "library...");
	}

	/*
	 * always out of date if no children and :: target
	 * or non-existent.
	 */
	oodate = (gn->mtime == 0 || Arch_LibOODate(gn) || 
		  (gn->cmgn == NULL && (gn->type & OP_DOUBLEDEP)));
    } else if (gn->type & OP_JOIN) {
	/*
	 * A target with the .JOIN attribute is only considered
	 * out-of-date if any of its children was out-of-date.
	 */
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, ".JOIN node...");
	}
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, "source %smade...", gn->flags & CHILDMADE ? "" : "not ");
	}
	oodate = (gn->flags & CHILDMADE) ? TRUE : FALSE;
    } else if (gn->type & (OP_FORCE|OP_EXEC|OP_PHONY)) {
	/*
	 * A node which is the object of the force (!) operator or which has
	 * the .EXEC attribute is always considered out-of-date.
	 */
	if (DEBUG(MAKE)) {
	    if (gn->type & OP_FORCE) {
		fprintf(debug_file, "! operator...");
	    } else if (gn->type & OP_PHONY) {
		fprintf(debug_file, ".PHONY node...");
	    } else {
		fprintf(debug_file, ".EXEC node...");
	    }
	}
	oodate = TRUE;
    } else if ((gn->cmgn != NULL && gn->mtime < gn->cmgn->mtime) ||
	       (gn->cmgn == NULL &&
		((gn->mtime == 0 && !(gn->type & OP_OPTIONAL))
		  || gn->type & OP_DOUBLEDEP)))
    {
	/*
	 * A node whose modification time is less than that of its
	 * youngest child or that has no children (cmgn == NULL) and
	 * either doesn't exist (mtime == 0) and it isn't optional
	 * or was the object of a * :: operator is out-of-date.
	 * Why? Because that's the way Make does it.
	 */
	if (DEBUG(MAKE)) {
	    if (gn->cmgn != NULL && gn->mtime < gn->cmgn->mtime) {
		fprintf(debug_file, "modified before source %s...",
		    gn->cmgn->path);
	    } else if (gn->mtime == 0) {
		fprintf(debug_file, "non-existent and no sources...");
	    } else {
		fprintf(debug_file, ":: operator and no sources...");
	    }
	}
	oodate = TRUE;
    } else {
	/* 
	 * When a non-existing child with no sources
	 * (such as a typically used FORCE source) has been made and
	 * the target of the child (usually a directory) has the same
	 * timestamp as the timestamp just given to the non-existing child
	 * after it was considered made.
	 */
	if (DEBUG(MAKE)) {
	    if (gn->flags & FORCE)
		fprintf(debug_file, "non existing child...");
	}
	oodate = (gn->flags & FORCE) ? TRUE : FALSE;
    }

#ifdef USE_META
    if (useMeta) {
	oodate = meta_oodate(gn, oodate);
    }
#endif

    /*
     * If the target isn't out-of-date, the parents need to know its
     * modification time. Note that targets that appear to be out-of-date
     * but aren't, because they have no commands and aren't of type OP_NOP,
     * have their mtime stay below their children's mtime to keep parents from
     * thinking they're out-of-date.
     */
    if (!oodate) {
	Lst_ForEach(gn->parents, MakeTimeStamp, gn);
    }

    return (oodate);
}

/*-
 *-----------------------------------------------------------------------
 * MakeAddChild  --
 *	Function used by Make_Run to add a child to the list l.
 *	It will only add the child if its make field is FALSE.
 *
 * Input:
 *	gnp		the node to add
 *	lp		the list to which to add it
 *
 * Results:
 *	Always returns 0
 *
 * Side Effects:
 *	The given list is extended
 *-----------------------------------------------------------------------
 */
static int
MakeAddChild(void *gnp, void *lp)
{
    GNode          *gn = (GNode *)gnp;
    Lst            l = (Lst) lp;

    if ((gn->flags & REMAKE) == 0 && !(gn->type & (OP_USE|OP_USEBEFORE))) {
	if (DEBUG(MAKE))
	    fprintf(debug_file, "MakeAddChild: need to examine %s%s\n",
		gn->name, gn->cohort_num);
	(void)Lst_EnQueue(l, gn);
    }
    return (0);
}

/*-
 *-----------------------------------------------------------------------
 * MakeFindChild  --
 *	Function used by Make_Run to find the pathname of a child
 *	that was already made.
 *
 * Input:
 *	gnp		the node to find
 *
 * Results:
 *	Always returns 0
 *
 * Side Effects:
 *	The path and mtime of the node and the cmgn of the parent are
 *	updated; the unmade children count of the parent is decremented.
 *-----------------------------------------------------------------------
 */
static int
MakeFindChild(void *gnp, void *pgnp)
{
    GNode          *gn = (GNode *)gnp;
    GNode          *pgn = (GNode *)pgnp;

    (void)Dir_MTime(gn, 0);
    Make_TimeStamp(pgn, gn);
    pgn->unmade--;

    return (0);
}

/*-
 *-----------------------------------------------------------------------
 * Make_HandleUse --
 *	Function called by Make_Run and SuffApplyTransform on the downward
 *	pass to handle .USE and transformation nodes. It implements the
 *	.USE and transformation functionality by copying the node's commands,
 *	type flags and children to the parent node.
 *
 *	A .USE node is much like an explicit transformation rule, except
 *	its commands are always added to the target node, even if the
 *	target already has commands.
 *
 * Input:
 *	cgn		The .USE node
 *	pgn		The target of the .USE node
 *
 * Results:
 *	none
 *
 * Side Effects:
 *	Children and commands may be added to the parent and the parent's
 *	type may be changed.
 *
 *-----------------------------------------------------------------------
 */
void
Make_HandleUse(GNode *cgn, GNode *pgn)
{
    LstNode	ln; 	/* An element in the children list */

#ifdef DEBUG_SRC
    if ((cgn->type & (OP_USE|OP_USEBEFORE|OP_TRANSFORM)) == 0) {
	fprintf(debug_file, "Make_HandleUse: called for plain node %s\n", cgn->name);
	return;
    }
#endif

    if ((cgn->type & (OP_USE|OP_USEBEFORE)) || Lst_IsEmpty(pgn->commands)) {
	    if (cgn->type & OP_USEBEFORE) {
		/*
		 * .USEBEFORE --
		 *	prepend the child's commands to the parent.
		 */
		Lst cmds = pgn->commands;
		pgn->commands = Lst_Duplicate(cgn->commands, NULL);
		(void)Lst_Concat(pgn->commands, cmds, LST_CONCNEW);
		Lst_Destroy(cmds, NULL);
	    } else {
		/*
		 * .USE or target has no commands --
		 *	append the child's commands to the parent.
		 */
		(void)Lst_Concat(pgn->commands, cgn->commands, LST_CONCNEW);
	    }
    }

    if (Lst_Open(cgn->children) == SUCCESS) {
	while ((ln = Lst_Next(cgn->children)) != NULL) {
	    GNode *tgn, *gn = (GNode *)Lst_Datum(ln);

	    /*
	     * Expand variables in the .USE node's name
	     * and save the unexpanded form.
	     * We don't need to do this for commands.
	     * They get expanded properly when we execute.
	     */
	    if (gn->uname == NULL) {
		gn->uname = gn->name;
	    } else {
		if (gn->name)
		    free(gn->name);
	    }
	    gn->name = Var_Subst(NULL, gn->uname, pgn, FALSE);
	    if (gn->name && gn->uname && strcmp(gn->name, gn->uname) != 0) {
		/* See if we have a target for this node. */
		tgn = Targ_FindNode(gn->name, TARG_NOCREATE);
		if (tgn != NULL)
		    gn = tgn;
	    }

	    (void)Lst_AtEnd(pgn->children, gn);
	    (void)Lst_AtEnd(gn->parents, pgn);
	    pgn->unmade += 1;
	}
	Lst_Close(cgn->children);
    }

    pgn->type |= cgn->type & ~(OP_OPMASK|OP_USE|OP_USEBEFORE|OP_TRANSFORM);
}

/*-
 *-----------------------------------------------------------------------
 * MakeHandleUse --
 *	Callback function for Lst_ForEach, used by Make_Run on the downward
 *	pass to handle .USE nodes. Should be called before the children
 *	are enqueued to be looked at by MakeAddChild.
 *	This function calls Make_HandleUse to copy the .USE node's commands,
 *	type flags and children to the parent node.
 *
 * Input:
 *	cgnp		the child we've just examined
 *	pgnp		the current parent
 *
 * Results:
 *	returns 0.
 *
 * Side Effects:
 *	After expansion, .USE child nodes are removed from the parent
 *
 *-----------------------------------------------------------------------
 */
static int
MakeHandleUse(void *cgnp, void *pgnp)
{
    GNode	*cgn = (GNode *)cgnp;
    GNode	*pgn = (GNode *)pgnp;
    LstNode	ln; 	/* An element in the children list */
    int		unmarked;

    unmarked = ((cgn->type & OP_MARK) == 0);
    cgn->type |= OP_MARK;

    if ((cgn->type & (OP_USE|OP_USEBEFORE)) == 0)
	return (0);

    if (unmarked)
	Make_HandleUse(cgn, pgn);

    /*
     * This child node is now "made", so we decrement the count of
     * unmade children in the parent... We also remove the child
     * from the parent's list to accurately reflect the number of decent
     * children the parent has. This is used by Make_Run to decide
     * whether to queue the parent or examine its children...
     */
    if ((ln = Lst_Member(pgn->children, cgn)) != NULL) {
	Lst_Remove(pgn->children, ln);
	pgn->unmade--;
    }
    return (0);
}


/*-
 *-----------------------------------------------------------------------
 * Make_Recheck --
 *	Check the modification time of a gnode, and update it as described
 *	in the comments below.
 *
 * Results:
 *	returns 0 if the gnode does not exist, or it's filesystem
 *	time if it does.
 *
 * Side Effects:
 *	the gnode's modification time and path name are affected.
 *
 *-----------------------------------------------------------------------
 */
time_t
Make_Recheck(GNode *gn)
{
    time_t mtime = Dir_MTime(gn, 1);

#ifndef RECHECK
    /*
     * We can't re-stat the thing, but we can at least take care of rules
     * where a target depends on a source that actually creates the
     * target, but only if it has changed, e.g.
     *
     * parse.h : parse.o
     *
     * parse.o : parse.y
     *  	yacc -d parse.y
     *  	cc -c y.tab.c
     *  	mv y.tab.o parse.o
     *  	cmp -s y.tab.h parse.h || mv y.tab.h parse.h
     *
     * In this case, if the definitions produced by yacc haven't changed
     * from before, parse.h won't have been updated and gn->mtime will
     * reflect the current modification time for parse.h. This is
     * something of a kludge, I admit, but it's a useful one..
     * XXX: People like to use a rule like
     *
     * FRC:
     *
     * To force things that depend on FRC to be made, so we have to
     * check for gn->children being empty as well...
     */
    if (!Lst_IsEmpty(gn->commands) || Lst_IsEmpty(gn->children)) {
	gn->mtime = now;
    }
#else
    /*
     * This is what Make does and it's actually a good thing, as it
     * allows rules like
     *
     *	cmp -s y.tab.h parse.h || cp y.tab.h parse.h
     *
     * to function as intended. Unfortunately, thanks to the stateless
     * nature of NFS (by which I mean the loose coupling of two clients
     * using the same file from a common server), there are times
     * when the modification time of a file created on a remote
     * machine will not be modified before the local stat() implied by
     * the Dir_MTime occurs, thus leading us to believe that the file
     * is unchanged, wreaking havoc with files that depend on this one.
     *
     * I have decided it is better to make too much than to make too
     * little, so this stuff is commented out unless you're sure it's ok.
     * -- ardeb 1/12/88
     */
    /*
     * Christos, 4/9/92: If we are  saving commands pretend that
     * the target is made now. Otherwise archives with ... rules
     * don't work!
     */
    if (NoExecute(gn) || (gn->type & OP_SAVE_CMDS) ||
	    (mtime == 0 && !(gn->type & OP_WAIT))) {
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, " recheck(%s): update time from %s to now\n",
		   gn->name, Targ_FmtTime(gn->mtime));
	}
	gn->mtime = now;
    }
    else {
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, " recheck(%s): current update time: %s\n",
		   gn->name, Targ_FmtTime(gn->mtime));
	}
    }
#endif
    return mtime;
}

/*-
 *-----------------------------------------------------------------------
 * Make_Update  --
 *	Perform update on the parents of a node. Used by JobFinish once
 *	a node has been dealt with and by MakeStartJobs if it finds an
 *	up-to-date node.
 *
 * Input:
 *	cgn		the child node
 *
 * Results:
 *	Always returns 0
 *
 * Side Effects:
 *	The unmade field of pgn is decremented and pgn may be placed on
 *	the toBeMade queue if this field becomes 0.
 *
 * 	If the child was made, the parent's flag CHILDMADE field will be
 *	set true.
 *
 *	If the child is not up-to-date and still does not exist,
 *	set the FORCE flag on the parents.
 *
 *	If the child wasn't made, the cmgn field of the parent will be
 *	altered if the child's mtime is big enough.
 *
 *	Finally, if the child is the implied source for the parent, the
 *	parent's IMPSRC variable is set appropriately.
 *
 *-----------------------------------------------------------------------
 */
void
Make_Update(GNode *cgn)
{
    GNode 	*pgn;	/* the parent node */
    char  	*cname;	/* the child's name */
    LstNode	ln; 	/* Element in parents and iParents lists */
    time_t	mtime = -1;
    char	*p1;
    Lst		parents;
    GNode	*centurion;

    /* It is save to re-examine any nodes again */
    checked++;

    cname = Var_Value(TARGET, cgn, &p1);
    if (p1)
	free(p1);

    if (DEBUG(MAKE))
	fprintf(debug_file, "Make_Update: %s%s\n", cgn->name, cgn->cohort_num);

    /*
     * If the child was actually made, see what its modification time is
     * now -- some rules won't actually update the file. If the file still
     * doesn't exist, make its mtime now.
     */
    if (cgn->made != UPTODATE) {
	mtime = Make_Recheck(cgn);
    }

    /*
     * If this is a `::' node, we must consult its first instance
     * which is where all parents are linked.
     */
    if ((centurion = cgn->centurion) != NULL) {
	if (!Lst_IsEmpty(cgn->parents))
		Punt("%s%s: cohort has parents", cgn->name, cgn->cohort_num);
	centurion->unmade_cohorts -= 1;
	if (centurion->unmade_cohorts < 0)
	    Error("Graph cycles through centurion %s", centurion->name);
    } else {
	centurion = cgn;
    }
    parents = centurion->parents;

    /* If this was a .ORDER node, schedule the RHS */
    Lst_ForEach(centurion->order_succ, MakeBuildParent, Lst_First(toBeMade));

    /* Now mark all the parents as having one less unmade child */
    if (Lst_Open(parents) == SUCCESS) {
	while ((ln = Lst_Next(parents)) != NULL) {
	    pgn = (GNode *)Lst_Datum(ln);
	    if (DEBUG(MAKE))
		fprintf(debug_file, "inspect parent %s%s: flags %x, "
			    "type %x, made %d, unmade %d ",
			pgn->name, pgn->cohort_num, pgn->flags,
			pgn->type, pgn->made, pgn->unmade-1);

	    if (!(pgn->flags & REMAKE)) {
		/* This parent isn't needed */
		if (DEBUG(MAKE))
		    fprintf(debug_file, "- not needed\n");
		continue;
	    }
	    if (mtime == 0 && !(cgn->type & OP_WAIT))
		pgn->flags |= FORCE;

	    /*
	     * If the parent has the .MADE attribute, its timestamp got
	     * updated to that of its newest child, and its unmake
	     * child count got set to zero in Make_ExpandUse().
	     * However other things might cause us to build one of its
	     * children - and so we mustn't do any processing here when
	     * the child build finishes.
	     */
	    if (pgn->type & OP_MADE) {
		if (DEBUG(MAKE))
		    fprintf(debug_file, "- .MADE\n");
		continue;
	    }

	    if ( ! (cgn->type & (OP_EXEC|OP_USE|OP_USEBEFORE))) {
		if (cgn->made == MADE)
		    pgn->flags |= CHILDMADE;
		(void)Make_TimeStamp(pgn, cgn);
	    }

	    /*
	     * A parent must wait for the completion of all instances
	     * of a `::' dependency.
	     */
	    if (centurion->unmade_cohorts != 0 || centurion->made < MADE) {
		if (DEBUG(MAKE))
		    fprintf(debug_file,
			    "- centurion made %d, %d unmade cohorts\n",
			    centurion->made, centurion->unmade_cohorts);
		continue;
	    }

	    /* One more child of this parent is now made */
	    pgn->unmade -= 1;
	    if (pgn->unmade < 0) {
		if (DEBUG(MAKE)) {
		    fprintf(debug_file, "Graph cycles through %s%s\n",
			pgn->name, pgn->cohort_num);
		    Targ_PrintGraph(2);
		}
		Error("Graph cycles through %s%s", pgn->name, pgn->cohort_num);
	    }

	    /* We must always rescan the parents of .WAIT and .ORDER nodes. */
	    if (pgn->unmade != 0 && !(centurion->type & OP_WAIT)
		    && !(centurion->flags & DONE_ORDER)) {
		if (DEBUG(MAKE))
		    fprintf(debug_file, "- unmade children\n");
		continue;
	    }
	    if (pgn->made != DEFERRED) {
		/*
		 * Either this parent is on a different branch of the tree,
		 * or it on the RHS of a .WAIT directive
		 * or it is already on the toBeMade list.
		 */
		if (DEBUG(MAKE))
		    fprintf(debug_file, "- not deferred\n");
		continue;
	    }
	    if (pgn->order_pred
		    && Lst_ForEach(pgn->order_pred, MakeCheckOrder, 0)) {
		/* A .ORDER rule stops us building this */
		continue;
	    }
	    if (DEBUG(MAKE)) {
		static int two = 2;
		fprintf(debug_file, "- %s%s made, schedule %s%s (made %d)\n",
			cgn->name, cgn->cohort_num,
			pgn->name, pgn->cohort_num, pgn->made);
		Targ_PrintNode(pgn, &two);
	    }
	    /* Ok, we can schedule the parent again */
	    pgn->made = REQUESTED;
	    (void)Lst_EnQueue(toBeMade, pgn);
	}
	Lst_Close(parents);
    }

    /*
     * Set the .PREFIX and .IMPSRC variables for all the implied parents
     * of this node.
     */
    if (Lst_Open(cgn->iParents) == SUCCESS) {
	char	*cpref = Var_Value(PREFIX, cgn, &p1);

	while ((ln = Lst_Next(cgn->iParents)) != NULL) {
	    pgn = (GNode *)Lst_Datum(ln);
	    if (pgn->flags & REMAKE) {
		Var_Set(IMPSRC, cname, pgn, 0);
		if (cpref != NULL)
		    Var_Set(PREFIX, cpref, pgn, 0);
	    }
	}
	if (p1)
	    free(p1);
	Lst_Close(cgn->iParents);
    }
}

/*-
 *-----------------------------------------------------------------------
 * MakeAddAllSrc --
 *	Add a child's name to the ALLSRC and OODATE variables of the given
 *	node. Called from Make_DoAllVar via Lst_ForEach. A child is added only
 *	if it has not been given the .EXEC, .USE or .INVISIBLE attributes.
 *	.EXEC and .USE children are very rarely going to be files, so...
 *	If the child is a .JOIN node, its ALLSRC is propagated to the parent.
 *
 *	A child is added to the OODATE variable if its modification time is
 *	later than that of its parent, as defined by Make, except if the
 *	parent is a .JOIN node. In that case, it is only added to the OODATE
 *	variable if it was actually made (since .JOIN nodes don't have
 *	modification times, the comparison is rather unfair...)..
 *
 * Results:
 *	Always returns 0
 *
 * Side Effects:
 *	The ALLSRC variable for the given node is extended.
 *-----------------------------------------------------------------------
 */
static int
MakeUnmark(void *cgnp, void *pgnp __unused)
{
    GNode	*cgn = (GNode *)cgnp;

    cgn->type &= ~OP_MARK;
    return (0);
}

/*
 * Input:
 *	cgnp		The child to add
 *	pgnp		The parent to whose ALLSRC variable it should
 *			be added
 *
 */
static int
MakeAddAllSrc(void *cgnp, void *pgnp)
{
    GNode	*cgn = (GNode *)cgnp;
    GNode	*pgn = (GNode *)pgnp;

    if (cgn->type & OP_MARK)
	return (0);
    cgn->type |= OP_MARK;

    if ((cgn->type & (OP_EXEC|OP_USE|OP_USEBEFORE|OP_INVISIBLE)) == 0) {
	char *child, *allsrc;
	char *p1 = NULL, *p2 = NULL;

	if (cgn->type & OP_ARCHV)
	    child = Var_Value(MEMBER, cgn, &p1);
	else
	    child = cgn->path ? cgn->path : cgn->name;
	if (cgn->type & OP_JOIN) {
	    allsrc = Var_Value(ALLSRC, cgn, &p2);
	} else {
	    allsrc = child;
	}
	if (allsrc != NULL)
		Var_Append(ALLSRC, allsrc, pgn);
	if (p2)
	    free(p2);
	if (pgn->type & OP_JOIN) {
	    if (cgn->made == MADE) {
		Var_Append(OODATE, child, pgn);
	    }
	} else if ((pgn->mtime < cgn->mtime) ||
		   (cgn->mtime >= now && cgn->made == MADE))
	{
	    /*
	     * It goes in the OODATE variable if the parent is younger than the
	     * child or if the child has been modified more recently than
	     * the start of the make. This is to keep pmake from getting
	     * confused if something else updates the parent after the
	     * make starts (shouldn't happen, I know, but sometimes it
	     * does). In such a case, if we've updated the kid, the parent
	     * is likely to have a modification time later than that of
	     * the kid and anything that relies on the OODATE variable will
	     * be hosed.
	     *
	     * XXX: This will cause all made children to go in the OODATE
	     * variable, even if they're not touched, if RECHECK isn't defined,
	     * since cgn->mtime is set to now in Make_Update. According to
	     * some people, this is good...
	     */
	    Var_Append(OODATE, child, pgn);
	}
	if (p1)
	    free(p1);
    }
    return (0);
}

/*-
 *-----------------------------------------------------------------------
 * Make_DoAllVar --
 *	Set up the ALLSRC and OODATE variables. Sad to say, it must be
 *	done separately, rather than while traversing the graph. This is
 *	because Make defined OODATE to contain all sources whose modification
 *	times were later than that of the target, *not* those sources that
 *	were out-of-date. Since in both compatibility and native modes,
 *	the modification time of the parent isn't found until the child
 *	has been dealt with, we have to wait until now to fill in the
 *	variable. As for ALLSRC, the ordering is important and not
 *	guaranteed when in native mode, so it must be set here, too.
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	The ALLSRC and OODATE variables of the given node is filled in.
 *	If the node is a .JOIN node, its TARGET variable will be set to
 * 	match its ALLSRC variable.
 *-----------------------------------------------------------------------
 */
void
Make_DoAllVar(GNode *gn)
{
    if (gn->flags & DONE_ALLSRC)
	return;
    
    Lst_ForEach(gn->children, MakeUnmark, gn);
    Lst_ForEach(gn->children, MakeAddAllSrc, gn);

    if (!Var_Exists (OODATE, gn)) {
	Var_Set(OODATE, "", gn, 0);
    }
    if (!Var_Exists (ALLSRC, gn)) {
	Var_Set(ALLSRC, "", gn, 0);
    }

    if (gn->type & OP_JOIN) {
	char *p1;
	Var_Set(TARGET, Var_Value(ALLSRC, gn, &p1), gn, 0);
	if (p1)
	    free(p1);
    }
    gn->flags |= DONE_ALLSRC;
}

/*-
 *-----------------------------------------------------------------------
 * MakeStartJobs --
 *	Start as many jobs as possible.
 *
 * Results:
 *	If the query flag was given to pmake, no job will be started,
 *	but as soon as an out-of-date target is found, this function
 *	returns TRUE. At all other times, this function returns FALSE.
 *
 * Side Effects:
 *	Nodes are removed from the toBeMade queue and job table slots
 *	are filled.
 *
 *-----------------------------------------------------------------------
 */

static int
MakeCheckOrder(void *v_bn, void *ignore __unused)
{
    GNode *bn = v_bn;

    if (bn->made >= MADE || !(bn->flags & REMAKE))
	return 0;
    if (DEBUG(MAKE))
	fprintf(debug_file, "MakeCheckOrder: Waiting for .ORDER node %s%s\n",
		bn->name, bn->cohort_num);
    return 1;
}

static int
MakeBuildChild(void *v_cn, void *toBeMade_next)
{
    GNode *cn = v_cn;

    if (DEBUG(MAKE))
	fprintf(debug_file, "MakeBuildChild: inspect %s%s, made %d, type %x\n",
	    cn->name, cn->cohort_num, cn->made, cn->type);
    if (cn->made > DEFERRED)
	return 0;

    /* If this node is on the RHS of a .ORDER, check LHSs. */
    if (cn->order_pred && Lst_ForEach(cn->order_pred, MakeCheckOrder, 0)) {
	/* Can't build this (or anything else in this child list) yet */
	cn->made = DEFERRED;
	return 1;
    }

    if (DEBUG(MAKE))
	fprintf(debug_file, "MakeBuildChild: schedule %s%s\n",
		cn->name, cn->cohort_num);

    cn->made = REQUESTED;
    if (toBeMade_next == NULL)
	Lst_AtEnd(toBeMade, cn);
    else
	Lst_InsertBefore(toBeMade, toBeMade_next, cn);

    if (cn->unmade_cohorts != 0)
	Lst_ForEach(cn->cohorts, MakeBuildChild, toBeMade_next);

    /*
     * If this node is a .WAIT node with unmade chlidren
     * then don't add the next sibling.
     */
    return cn->type & OP_WAIT && cn->unmade > 0;
}

/* When a .ORDER RHS node completes we do this on each LHS */
static int
MakeBuildParent(void *v_pn, void *toBeMade_next)
{
    GNode *pn = v_pn;

    if (pn->made != DEFERRED)
	return 0;

    if (MakeBuildChild(pn, toBeMade_next) == 0) {
	/* Mark so that when this node is built we reschedule its parents */
	pn->flags |= DONE_ORDER;
    }

    return 0;
}

static Boolean
MakeStartJobs(void)
{
    GNode	*gn;
    int		have_token = 0;

    while (!Lst_IsEmpty (toBeMade)) {
	/* Get token now to avoid cycling job-list when we only have 1 token */
	if (!have_token && !Job_TokenWithdraw())
	    break;
	have_token = 1;

	gn = (GNode *)Lst_DeQueue(toBeMade);
	if (DEBUG(MAKE))
	    fprintf(debug_file, "Examining %s%s...\n",
		    gn->name, gn->cohort_num);

	if (gn->made != REQUESTED) {
	    if (DEBUG(MAKE))
		fprintf(debug_file, "state %d\n", gn->made);

	    make_abort(gn, __LINE__);
	}

	if (gn->checked == checked) {
	    /* We've already looked at this node since a job finished... */
	    if (DEBUG(MAKE))
		fprintf(debug_file, "already checked %s%s\n",
			gn->name, gn->cohort_num);
	    gn->made = DEFERRED;
	    continue;
	}
	gn->checked = checked;

	if (gn->unmade != 0) {
	    /*
	     * We can't build this yet, add all unmade children to toBeMade,
	     * just before the current first element.
	     */
	    gn->made = DEFERRED;
	    Lst_ForEach(gn->children, MakeBuildChild, Lst_First(toBeMade));
	    /* and drop this node on the floor */
	    if (DEBUG(MAKE))
		fprintf(debug_file, "dropped %s%s\n", gn->name, gn->cohort_num);
	    continue;
	}

	gn->made = BEINGMADE;
	if (Make_OODate(gn)) {
	    if (DEBUG(MAKE)) {
		fprintf(debug_file, "out-of-date\n");
	    }
	    if (queryFlag) {
		return (TRUE);
	    }
	    Make_DoAllVar(gn);
	    Job_Make(gn);
	    have_token = 0;
	} else {
	    if (DEBUG(MAKE)) {
		fprintf(debug_file, "up-to-date\n");
	    }
	    gn->made = UPTODATE;
	    if (gn->type & OP_JOIN) {
		/*
		 * Even for an up-to-date .JOIN node, we need it to have its
		 * context variables so references to it get the correct
		 * value for .TARGET when building up the context variables
		 * of its parent(s)...
		 */
		Make_DoAllVar(gn);
	    }
	    Make_Update(gn);
	}
    }

    if (have_token)
	Job_TokenReturn();

    return (FALSE);
}

/*-
 *-----------------------------------------------------------------------
 * MakePrintStatus --
 *	Print the status of a top-level node, viz. it being up-to-date
 *	already or not created due to an error in a lower level.
 *	Callback function for Make_Run via Lst_ForEach.
 *
 * Input:
 *	gnp		Node to examine
 *	cyclep		True if gn->unmade being non-zero implies a
 *			cycle in the graph, not an error in an
 *			inferior.
 *
 * Results:
 *	Always returns 0.
 *
 * Side Effects:
 *	A message may be printed.
 *
 *-----------------------------------------------------------------------
 */
static int
MakePrintStatusOrder(void *ognp, void *gnp)
{
    GNode *ogn = ognp;
    GNode *gn = gnp;

    if (!(ogn->flags & REMAKE) || ogn->made > REQUESTED)
	/* not waiting for this one */
	return 0;

    printf("    `%s%s' has .ORDER dependency against %s%s "
		"(made %d, flags %x, type %x)\n",
	    gn->name, gn->cohort_num,
	    ogn->name, ogn->cohort_num, ogn->made, ogn->flags, ogn->type);
    if (DEBUG(MAKE) && debug_file != stdout)
	fprintf(debug_file, "    `%s%s' has .ORDER dependency against %s%s "
		    "(made %d, flags %x, type %x)\n",
		gn->name, gn->cohort_num,
		ogn->name, ogn->cohort_num, ogn->made, ogn->flags, ogn->type);
    return 0;
}

static int
MakePrintStatus(void *gnp, void *v_errors)
{
    GNode   	*gn = (GNode *)gnp;
    int 	*errors = v_errors;

    if (gn->flags & DONECYCLE)
	/* We've completely processed this node before, don't do it again. */
	return 0;

    if (gn->unmade == 0) {
	gn->flags |= DONECYCLE;
	switch (gn->made) {
	case UPTODATE:
	    printf("`%s%s' is up to date.\n", gn->name, gn->cohort_num);
	    break;
	case MADE:
	    break;
	case UNMADE:
	case DEFERRED:
	case REQUESTED:
	case BEINGMADE:
	    (*errors)++;
	    printf("`%s%s' was not built (made %d, flags %x, type %x)!\n",
		    gn->name, gn->cohort_num, gn->made, gn->flags, gn->type);
	    if (DEBUG(MAKE) && debug_file != stdout)
		fprintf(debug_file,
			"`%s%s' was not built (made %d, flags %x, type %x)!\n",
			gn->name, gn->cohort_num, gn->made, gn->flags, gn->type);
	    /* Most likely problem is actually caused by .ORDER */
	    Lst_ForEach(gn->order_pred, MakePrintStatusOrder, gn);
	    break;
	default:
	    /* Errors - already counted */
	    printf("`%s%s' not remade because of errors.\n",
		    gn->name, gn->cohort_num);
	    if (DEBUG(MAKE) && debug_file != stdout)
		fprintf(debug_file, "`%s%s' not remade because of errors.\n",
			gn->name, gn->cohort_num);
	    break;
	}
	return 0;
    }

    if (DEBUG(MAKE))
	fprintf(debug_file, "MakePrintStatus: %s%s has %d unmade children\n",
		gn->name, gn->cohort_num, gn->unmade);
    /*
     * If printing cycles and came to one that has unmade children,
     * print out the cycle by recursing on its children.
     */
    if (!(gn->flags & CYCLE)) {
	/* Fist time we've seen this node, check all children */
	gn->flags |= CYCLE;
	Lst_ForEach(gn->children, MakePrintStatus, errors);
	/* Mark that this node needn't be processed again */
	gn->flags |= DONECYCLE;
	return 0;
    }

    /* Only output the error once per node */
    gn->flags |= DONECYCLE;
    Error("Graph cycles through `%s%s'", gn->name, gn->cohort_num);
    if ((*errors)++ > 100)
	/* Abandon the whole error report */
	return 1;

    /* Reporting for our children will give the rest of the loop */
    Lst_ForEach(gn->children, MakePrintStatus, errors);
    return 0;
}


/*-
 *-----------------------------------------------------------------------
 * Make_ExpandUse --
 *	Expand .USE nodes and create a new targets list
 *
 * Input:
 *	targs		the initial list of targets
 *
 * Side Effects:
 *-----------------------------------------------------------------------
 */
void
Make_ExpandUse(Lst targs)
{
    GNode  *gn;		/* a temporary pointer */
    Lst    examine; 	/* List of targets to examine */

    examine = Lst_Duplicate(targs, NULL);

    /*
     * Make an initial downward pass over the graph, marking nodes to be made
     * as we go down. We call Suff_FindDeps to find where a node is and
     * to get some children for it if it has none and also has no commands.
     * If the node is a leaf, we stick it on the toBeMade queue to
     * be looked at in a minute, otherwise we add its children to our queue
     * and go on about our business.
     */
    while (!Lst_IsEmpty (examine)) {
	gn = (GNode *)Lst_DeQueue(examine);
    
	if (gn->flags & REMAKE)
	    /* We've looked at this one already */
	    continue;
	gn->flags |= REMAKE;
	if (DEBUG(MAKE))
	    fprintf(debug_file, "Make_ExpandUse: examine %s%s\n",
		    gn->name, gn->cohort_num);

	if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts)) {
	    /* Append all the 'cohorts' to the list of things to examine */
	    Lst new;
	    new = Lst_Duplicate(gn->cohorts, NULL);
	    Lst_Concat(new, examine, LST_CONCLINK);
	    examine = new;
	}

	/*
	 * Apply any .USE rules before looking for implicit dependencies
	 * to make sure everything has commands that should...
	 * Make sure that the TARGET is set, so that we can make
	 * expansions.
	 */
	if (gn->type & OP_ARCHV) {
	    char *eoa, *eon;
	    eoa = strchr(gn->name, '(');
	    eon = strchr(gn->name, ')');
	    if (eoa == NULL || eon == NULL)
		continue;
	    *eoa = '\0';
	    *eon = '\0';
	    Var_Set(MEMBER, eoa + 1, gn, 0);
	    Var_Set(ARCHIVE, gn->name, gn, 0);
	    *eoa = '(';
	    *eon = ')';
	}

	(void)Dir_MTime(gn, 0);
	Var_Set(TARGET, gn->path ? gn->path : gn->name, gn, 0);
	Lst_ForEach(gn->children, MakeUnmark, gn);
	Lst_ForEach(gn->children, MakeHandleUse, gn);

	if ((gn->type & OP_MADE) == 0)
	    Suff_FindDeps(gn);
	else {
	    /* Pretend we made all this node's children */
	    Lst_ForEach(gn->children, MakeFindChild, gn);
	    if (gn->unmade != 0)
		    printf("Warning: %s%s still has %d unmade children\n",
			    gn->name, gn->cohort_num, gn->unmade);
	}

	if (gn->unmade != 0)
	    Lst_ForEach(gn->children, MakeAddChild, examine);
    }

    Lst_Destroy(examine, NULL);
}

/*-
 *-----------------------------------------------------------------------
 * Make_ProcessWait --
 *	Convert .WAIT nodes into dependencies
 *
 * Input:
 *	targs		the initial list of targets
 *
 *-----------------------------------------------------------------------
 */

static int
link_parent(void *cnp, void *pnp)
{
    GNode *cn = cnp;
    GNode *pn = pnp;

    Lst_AtEnd(pn->children, cn);
    Lst_AtEnd(cn->parents, pn);
    pn->unmade++;
    return 0;
}

static int
add_wait_dep(void *v_cn, void *v_wn)
{
    GNode *cn = v_cn;
    GNode *wn = v_wn;

    if (cn == wn)
	return 1;

    if (cn == NULL || wn == NULL) {
	printf("bad wait dep %p %p\n", cn, wn);
	exit(4);
    }
    if (DEBUG(MAKE))
	 fprintf(debug_file, ".WAIT: add dependency %s%s -> %s\n",
		cn->name, cn->cohort_num, wn->name);

    Lst_AtEnd(wn->children, cn);
    wn->unmade++;
    Lst_AtEnd(cn->parents, wn);
    return 0;
}

static void
Make_ProcessWait(Lst targs)
{
    GNode  *pgn;	/* 'parent' node we are examining */
    GNode  *cgn;	/* Each child in turn */
    LstNode owln;	/* Previous .WAIT node */
    Lst    examine; 	/* List of targets to examine */
    LstNode ln;

    /*
     * We need all the nodes to have a common parent in order for the
     * .WAIT and .ORDER scheduling to work.
     * Perhaps this should be done earlier...
     */

    pgn = Targ_NewGN(".MAIN");
    pgn->flags = REMAKE;
    pgn->type = OP_PHONY | OP_DEPENDS;
    /* Get it displayed in the diag dumps */
    Lst_AtFront(Targ_List(), pgn);

    Lst_ForEach(targs, link_parent, pgn);

    /* Start building with the 'dummy' .MAIN' node */
    MakeBuildChild(pgn, NULL);

    examine = Lst_Init(FALSE);
    Lst_AtEnd(examine, pgn);

    while (!Lst_IsEmpty (examine)) {
	pgn = Lst_DeQueue(examine);
   
	/* We only want to process each child-list once */
	if (pgn->flags & DONE_WAIT)
	    continue;
	pgn->flags |= DONE_WAIT;
	if (DEBUG(MAKE))
	    fprintf(debug_file, "Make_ProcessWait: examine %s\n", pgn->name);

	if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts)) {
	    /* Append all the 'cohorts' to the list of things to examine */
	    Lst new;
	    new = Lst_Duplicate(pgn->cohorts, NULL);
	    Lst_Concat(new, examine, LST_CONCLINK);
	    examine = new;
	}

	owln = Lst_First(pgn->children);
	Lst_Open(pgn->children);
	for (; (ln = Lst_Next(pgn->children)) != NULL; ) {
	    cgn = Lst_Datum(ln);
	    if (cgn->type & OP_WAIT) {
		/* Make the .WAIT node depend on the previous children */
		Lst_ForEachFrom(pgn->children, owln, add_wait_dep, cgn);
		owln = ln;
	    } else {
		Lst_AtEnd(examine, cgn);
	    }
	}
	Lst_Close(pgn->children);
    }

    Lst_Destroy(examine, NULL);
}

/*-
 *-----------------------------------------------------------------------
 * Make_Run --
 *	Initialize the nodes to remake and the list of nodes which are
 *	ready to be made by doing a breadth-first traversal of the graph
 *	starting from the nodes in the given list. Once this traversal
 *	is finished, all the 'leaves' of the graph are in the toBeMade
 *	queue.
 *	Using this queue and the Job module, work back up the graph,
 *	calling on MakeStartJobs to keep the job table as full as
 *	possible.
 *
 * Input:
 *	targs		the initial list of targets
 *
 * Results:
 *	TRUE if work was done. FALSE otherwise.
 *
 * Side Effects:
 *	The make field of all nodes involved in the creation of the given
 *	targets is set to 1. The toBeMade list is set to contain all the
 *	'leaves' of these subgraphs.
 *-----------------------------------------------------------------------
 */
Boolean
Make_Run(Lst targs)
{
    int	    	    errors; 	/* Number of errors the Job module reports */

    /* Start trying to make the current targets... */
    toBeMade = Lst_Init(FALSE);

    Make_ExpandUse(targs);
    Make_ProcessWait(targs);

    if (DEBUG(MAKE)) {
	 fprintf(debug_file, "#***# full graph\n");
	 Targ_PrintGraph(1);
    }

    if (queryFlag) {
	/*
	 * We wouldn't do any work unless we could start some jobs in the
	 * next loop... (we won't actually start any, of course, this is just
	 * to see if any of the targets was out of date)
	 */
	return (MakeStartJobs());
    }
    /*
     * Initialization. At the moment, no jobs are running and until some
     * get started, nothing will happen since the remaining upward
     * traversal of the graph is performed by the routines in job.c upon
     * the finishing of a job. So we fill the Job table as much as we can
     * before going into our loop.
     */
    (void)MakeStartJobs();

    /*
     * Main Loop: The idea here is that the ending of jobs will take
     * care of the maintenance of data structures and the waiting for output
     * will cause us to be idle most of the time while our children run as
     * much as possible. Because the job table is kept as full as possible,
     * the only time when it will be empty is when all the jobs which need
     * running have been run, so that is the end condition of this loop.
     * Note that the Job module will exit if there were any errors unless the
     * keepgoing flag was given.
     */
    while (!Lst_IsEmpty(toBeMade) || jobTokensRunning > 0) {
	Job_CatchOutput();
	(void)MakeStartJobs();
    }

    errors = Job_Finish();

    /*
     * Print the final status of each target. E.g. if it wasn't made
     * because some inferior reported an error.
     */
    if (DEBUG(MAKE))
	 fprintf(debug_file, "done: errors %d\n", errors);
    if (errors == 0) {
	Lst_ForEach(targs, MakePrintStatus, &errors);
	if (DEBUG(MAKE)) {
	    fprintf(debug_file, "done: errors %d\n", errors);
	    if (errors)
		Targ_PrintGraph(4);
	}
    }
    return errors != 0;
}