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
|
/* This file is part of mhmake.
*
* Copyright (C) 2001-2010 marha@sourceforge.net
*
* Mhmake is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mhmake is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Mhmake. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Rev$ */
#include "stdafx.h"
#include "mhmakefileparser.h"
#include "rule.h"
#include "util.h"
/*****************************************************************************/
int mhmakefileparser::SearchPath(const char *szCommand, const char *pExt, size_t Len, char *szFullCommand,char **pFilePart) const
{
static vector< fileinfo* > vSearchPath;
string Command(szCommand);
if (pExt)
Command+=pExt;
vector< fileinfo* >::iterator It;
vector< fileinfo* >::iterator ItEnd;
fileinfo* pCommandFile=GetFileInfo(Command,m_MakeDir);
if (pCommandFile->Exists())
{
goto found;
}
pCommandFile->InvalidateDate(); // It could be created in the makefile later
if (!vSearchPath.size())
{
char *pPath=getenv(PATH);
if (!pPath)
return 0;
char *Path=strdup(pPath); // To be able to use strtok
char *pTok=strtok(Path,OSPATHENVSEPSTR);
while (pTok)
{
vSearchPath.push_back(GetFileInfo(pTok,m_MakeDir));
pTok=strtok(NULL,OSPATHENVSEPSTR);
}
free(Path);
}
It=vSearchPath.begin();
ItEnd=vSearchPath.end();
while (It!=ItEnd)
{
pCommandFile=GetFileInfo(Command,*It);
if (pCommandFile->Exists())
goto found;
It++;
}
return 0;
found:
string FullCommand=pCommandFile->GetFullFileName();
size_t CommandLen=FullCommand.size();
if (CommandLen>Len-1)
{
throw string("Command to long: ") + FullCommand;
}
strcpy(szFullCommand,FullCommand.c_str());
return 1;
}
/*****************************************************************************/
string mhmakefileparser::SearchCommand(const string &Command, const string &Extension) const
{
char FullCommand[MAX_PATH]="";
unsigned long Size=sizeof(FullCommand);
const char *pExt;
if (Extension.empty())
pExt=NULL;
else
pExt=Extension.c_str();
if (SearchPath(UnquoteFileName(Command).c_str(),pExt,MAX_PATH,FullCommand,NULL))
return FullCommand;
#ifdef WIN32
/* See if we have a path for python.exe in the registry */
HKEY hKey;
string RegEntry=Command;
if (pExt)
{
RegEntry+=Extension;
}
string KeyName=string("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\")+RegEntry;
if (ERROR_SUCCESS!=RegOpenKey(HKEY_LOCAL_MACHINE,KeyName.c_str(),&hKey))
return FullCommand;
RegQueryValueEx(hKey,NULL,NULL,NULL,(LPBYTE)FullCommand,&Size);
RegCloseKey(hKey);
#endif
return FullCommand;
}
/*****************************************************************************/
/* Deletes a complete directory or files with wildcard. It can be assumed that the Directory passed does exist */
static bool DeleteDir(const string &Dir,const string WildSearch="*",bool bRemoveDir=true)
{
bool Error=false;
string Pattern=Dir+OSPATHSEP+WildSearch;
#ifdef WIN32
WIN32_FIND_DATA FindData;
mh_pid_t hFind=FindFirstFile(Pattern.c_str(),&FindData);
if (hFind==INVALID_HANDLE_VALUE)
{
return Error;
}
do
{
/* Only handle items which are not . and .. */
if (FindData.cFileName[0]!='.' || (FindData.cFileName[1] && (FindData.cFileName[1]!='.' || FindData.cFileName[2])) )
{
string FileName=Dir+OSPATHSEP+FindData.cFileName;
if (FindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{
Error = DeleteDir(FileName);
}
else
{
Error = (-1==remove(FileName.c_str()));
}
}
} while (FindNextFile(hFind,&FindData));
FindClose(hFind);
if (bRemoveDir)
Error = (0==RemoveDirectory(Dir.c_str()));
#else
glob_t Res;
if (glob (Pattern.c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
return Error;
for (int i=0; i<Res.gl_pathc; i++)
{
int Len=strlen(Res.gl_pathv[i])-1;
if (Res.gl_pathv[i][Len]=='/')
{
Res.gl_pathv[i][Len]=0;
Error = DeleteDir(Res.gl_pathv[i]);
}
else
{
Error = (-1==remove(Res.gl_pathv[i]));
}
}
globfree(&Res);
if (bRemoveDir)
Error = (-1==remove(Dir.c_str()));
#endif
return Error;
}
/*****************************************************************************/
mh_pid_t mhmakefileparser::DeleteFiles(const string &Params) const
{
bool IgnoreError=false;
vector<fileinfo*> Files;
// First check if the first parameter is -e meaning don't give an error when file does not exist
if (Params[1]=='-')
{
if (Params[2]=='e')
{
IgnoreError=true;
SplitToItems(Params.substr(4),Files);
}
else
{
cerr << "Invalid option "<<Params[1]<<" in del statement\n";
return (mh_pid_t)-1;
}
}
else
{
SplitToItems(Params,Files);
}
vector<fileinfo*>::const_iterator It=Files.begin();
while (It!=Files.end())
{
fileinfo* pFile=*It++;
string DirSearch="*";
bool bRemoveDir=true;
/* Now check if there is a wildcard */
if (pFile->GetFullFileName().find('*')!=string::npos)
{
DirSearch=pFile->GetName();
pFile=pFile->GetDir();
bRemoveDir=false;
}
pFile->InvalidateDate();
if (IgnoreError && !pFile->Exists() && !pFile->IsDir())
{
continue;
}
const string &FileName=pFile->GetFullFileName();
if (pFile->IsDir())
{
if (DeleteDir(FileName,DirSearch,bRemoveDir) && !IgnoreError)
{
cerr << "Error deleting "<<FileName<<endl;
return (mh_pid_t)-1;
}
}
else
{
if (-1==remove(FileName.c_str()) && !IgnoreError)
{
cerr << "Error deleting "<<FileName<<endl;
return (mh_pid_t)-1;
}
}
}
return (mh_pid_t)0;
}
/*****************************************************************************/
/* pDest can be a directory or a file */
static bool CopyFile(fileinfo* pSrc, fileinfo* pDest)
{
if (pDest->IsDir())
{
pDest=GetFileInfo(pSrc->GetName(),pDest);
}
string SrcFileName=pSrc->GetFullFileName();
string DestFileName=pDest->GetFullFileName();
/* Now copy the file */
FILE *pSrcFile=fopen(SrcFileName.c_str(),"rb");
if (!pSrcFile)
{
cerr << "copy: error opening file "<<SrcFileName<<endl;
return false;
}
FILE *pDestFile=fopen(DestFileName.c_str(),"wb");
if (!pDestFile)
{
cerr << "copy: error creating file "<<DestFileName<<endl;
return false;
}
char Buf[4096];
size_t Ret;
while ( (Ret=fread(Buf,1,sizeof(Buf),pSrcFile)) > 0)
{
fwrite(Buf,1,Ret,pDestFile);
}
fclose(pSrcFile);
fclose(pDestFile);
pDest->InvalidateDate();
return true;
}
/*****************************************************************************/
/* Copies a complete directory to a destination (currenlty not recursive */
static bool CopyDir(fileinfo* pDir, fileinfo* pDest,const string WildSearch="*")
{
bool Error=true;
string Pattern=pDir->GetFullFileName()+OSPATHSEP+WildSearch;
#ifdef WIN32
WIN32_FIND_DATA FindData;
mh_pid_t hFind=FindFirstFile(Pattern.c_str(),&FindData);
if (hFind==INVALID_HANDLE_VALUE)
{
return false;
}
do
{
/* Only handle items which are not . and .. */
if (FindData.cFileName[0]!='.' || (FindData.cFileName[1] && (FindData.cFileName[1]!='.' || FindData.cFileName[2])) )
{
if (FindData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN)
continue;
fileinfo* pSrc=GetFileInfo(FindData.cFileName,pDir);
if (pSrc->IsDir())
{
fileinfo* pNewDest=GetFileInfo(FindData.cFileName,pDest);
if (!pNewDest->IsDir())
{
if (pNewDest->Exists())
{
cerr << pNewDest->GetFullFileName() << " exists and is not a directory.\n";
Error = false;
goto exit;
}
if (!CreateDirectory(pNewDest->GetFullFileName().c_str(),NULL))
{
cerr << "Error creating directory " << pNewDest->GetFullFileName() << endl;
Error = false;
goto exit;
}
pNewDest->InvalidateDate();
}
Error = CopyDir(pSrc,pNewDest);
if (!Error) goto exit;
}
else
{
Error = CopyFile(pSrc,pDest);
if (!Error) goto exit;
}
}
} while (FindNextFile(hFind,&FindData));
exit:
FindClose(hFind);
#else
glob_t Res;
if (glob (Pattern.c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
return Error;
for (int i=0; i<Res.gl_pathc; i++)
{
fileinfo* pSrc=GetFileInfo(Res.gl_pathv[i],pDir);
if (pSrc->IsDir())
{
*(strrchr(Res.gl_pathv[i],'/'))='\0';
const char *SrcDirName=strrchr(Res.gl_pathv[i],'/')+1;
if (SrcDirName[0]=='.')
continue;
fileinfo* pNewDest=GetFileInfo(SrcDirName,pDest);
if (!pNewDest->IsDir())
{
if (pNewDest->Exists())
{
cerr << pNewDest->GetQuotedFullFileName() << " exists and is not a directory.\n";
Error = false;
goto exit;
}
if (-1==mkdir(pNewDest->GetFullFileName().c_str(),S_IRWXU))
{
cerr << "Error creating directory " << pNewDest->GetQuotedFullFileName() << endl;
Error = false;
goto exit;
}
pNewDest->InvalidateDate();
}
Error = CopyDir(pSrc,pNewDest);
if (!Error) goto exit;
}
else
{
Error = CopyFile(GetFileInfo(Res.gl_pathv[i],pDir),pDest);
if (!Error) goto exit;
}
}
exit:
globfree(&Res);
#endif
return Error;
}
/*****************************************************************************/
mh_pid_t mhmakefileparser::MakeDirsCommand(const string &Params) const
{
vector<fileinfo*> Dirs;
SplitToItems(Params,Dirs);
size_t NrDirs=Dirs.size();
for (size_t i=0; i<NrDirs; i++)
{
fileinfo* pDir=Dirs[i];
if (!MakeDirs(pDir))
return (mh_pid_t)-1;
}
return (mh_pid_t)0;
}
/*****************************************************************************/
static string RemoveQuotes(const string &StrIn)
{
char FirstChar=StrIn[0];
string Ret=StrIn;
if (FirstChar=='"')
{
int Len=Ret.length()-1;
if (Ret[Len]=='"')
Ret=Ret.substr(1,Len-1);
}
else if (FirstChar=='\'')
{
int Len=Ret.length()-1;
if (Ret[Len]=='\'')
Ret=Ret.substr(1,Len-1);
}
return Ret;
}
mh_pid_t mhmakefileparser::EchoCommand(const string &ParamsIn) const
{
string Params=f_strip(ParamsIn);
// Find the first > character
size_t Pos=Params.find_first_of('>');
if (Pos==string::npos)
{
// Just echo it
cout << RemoveQuotes(Params) << endl;
}
else
{
FILE *pfFile;
/* Extra the filename */
string Filename;
if (Params[Pos+1]=='>')
{
NextItem(Params.substr(Pos+2).c_str(),Filename);
fileinfo* pFile=GetFileInfo(Filename,m_MakeDir);
// Open file in append
pfFile=fopen(pFile->GetFullFileName().c_str(),"a");
}
else
{
NextItem(Params.substr(Pos+1).c_str(),Filename);
fileinfo* pFile=GetFileInfo(Filename,m_MakeDir);
pfFile=fopen(pFile->GetFullFileName().c_str(),"w");
}
if (!pfFile)
{
cerr << "Error opening file "<<Filename<<endl;
return (mh_pid_t)-1;
}
string EchoStr=RemoveQuotes(Params.substr(0,Pos-1))+"\n";
if (EchoStr.length()!=fwrite(EchoStr.c_str(),1,EchoStr.length(),pfFile))
{
cerr << "Error writing file "<<Filename<<endl;
return (mh_pid_t)-1;
}
fclose(pfFile);
}
return (mh_pid_t)0;
}
/*****************************************************************************/
mh_pid_t mhmakefileparser::CopyFiles(const string &Params) const
{
vector<fileinfo*> Files;
SplitToItems(Params,Files);
size_t NrSrcs=Files.size()-1;
if (NrSrcs<1)
{
cerr << "Wrong number of arguments in copy: "<<Params<<endl;
return (mh_pid_t)-1;
}
fileinfo* pDest=Files[NrSrcs];
if (NrSrcs>1 && !pDest->IsDir())
{
cerr << "copy: Destination must be a directory when more then one source : "<<Params<<endl;
return (mh_pid_t)-1;
}
for (size_t i=0; i<NrSrcs; i++)
{
fileinfo* pSrc=Files[i];
string SrcFileName=pSrc->GetFullFileName();
if (pSrc->IsDir())
{
SrcFileName+=OSPATHSEPSTR"*";
pSrc=GetFileInfo(SrcFileName,m_MakeDir);
}
//cerr << "copy "<<pSrc->GetFullFileName()<<" "<<pDest->GetFullFileName()<<endl;
/* Now check if there is a wildcard */
if (SrcFileName.find('*')!=string::npos)
{
if (!CopyDir(pSrc->GetDir(), pDest, pSrc->GetName()))
{
cerr << "copy: Error copying directory: " << Params << endl;
return (mh_pid_t)-1;
}
}
else
{
if (!CopyFile(pSrc,pDest))
{
cerr << "copy: Error copying file: " << Params << endl;
return (mh_pid_t)-1;
}
}
}
return (mh_pid_t)0;
}
/*****************************************************************************/
mh_pid_t mhmakefileparser::TouchFiles(const string &Params) const
{
vector<fileinfo*> Files;
SplitToItems(Params,Files);
vector<fileinfo*>::const_iterator It=Files.begin();
while (It!=Files.end())
{
fileinfo* pFile=*It++;
const string &FileName=pFile->GetFullFileName();
/* Since this can be part of a list of commands for a certain rule, and it is possible that the file
* was generated by one on the previous commands, we first need the invalidate the date so that the
* existance checking is done again */
pFile->InvalidateDate();
if (pFile->IsDir())
{
cerr << "touch: Cannot touch a directory: " << FileName << endl;
return (mh_pid_t)-1;
}
if (pFile->Exists())
{
int fd;
char c;
int status = 0;
struct stat st;
int Ret;
int saved_errno = 0;
fd = open (FileName.c_str(), O_RDWR);
if (fd<0)
{
st.st_size=0;
}
else
{
if (fstat (fd, &st) < 0)
{
cerr << "touch: Cannot stat file " << FileName << endl;
return (mh_pid_t)-1;
}
}
if (st.st_size == 0)
{
FILE *pFile;
if (fd>=0 && close(fd) < 0)
{
cerr << "touch: Error closing file " << FileName << endl;
return (mh_pid_t)-1;
}
/*Re-Create an empty file */
pFile=fopen(FileName.c_str(),"wb");
if (!pFile)
{
cerr << "touch: Cannot create file: " << FileName << endl;
return (mh_pid_t)-1;
}
fclose(pFile);
}
else
{
Ret=read (fd, &c, sizeof(c));
if (Ret!=sizeof(c) && Ret!=EOF)
{
cerr << "touch: Cannot read file " << FileName << ": "<<Ret<<endl;
return (mh_pid_t)-1;
}
if (lseek (fd, (off_t) 0, SEEK_SET) < 0)
{
cerr << "touch: Error changing file pointer " << FileName << endl;
return (mh_pid_t)-1;
}
if (write (fd, &c, sizeof c) != sizeof(c))
{
cerr << "touch: Error writing file " << FileName << endl;
return (mh_pid_t)-1;
}
if (close (fd) < 0)
{
cerr << "touch: Error closing file " << FileName << endl;
return (mh_pid_t)-1;
}
}
}
else
{
/* Create an empty file */
FILE *pFile=fopen(FileName.c_str(),"wb");
if (!pFile)
{
cerr << "touch: Cannot create file: " << FileName << endl;
return (mh_pid_t)-1;
}
fclose(pFile);
}
pFile->InvalidateDate();
}
return (mh_pid_t)0;
}
/*****************************************************************************/
const string &mhmakefileparser::GetPythonExe() const
{
static string PythonExe;
if (PythonExe.empty())
{
string FullCommand=SearchCommand(PYTHONEXE);
if (!FullCommand.empty())
{
PythonExe=QuoteFileName(FullCommand)+" ";
}
else
{
cerr<<"python executable not found in path and registry.\n";
exit(1);
}
}
return PythonExe;
}
/*****************************************************************************/
static const string &GetComspec()
{
static string Comspec;
if (Comspec.empty())
{
const char *pComspec=getenv(COMSPEC);
if (pComspec)
{
Comspec=pComspec;
#ifdef WIN32
Comspec+=" /c ";
#else
Comspec+=" -c \"";
#endif
}
else
{
#ifdef WIN32
Comspec="cmd.exe /c ";
#else
Comspec="sh -c \"";
#endif
}
}
return Comspec;
}
/*****************************************************************************/
static string GetExecutableFromCommand(const string &FullCommand)
{
string Ret;
FILE *pFile=fopen(FullCommand.c_str(),"r");
if (!pFile)
return Ret;
char Line[MAX_PATH];
if (fgets(Line,MAX_PATH,pFile) && Line[0]=='#' && Line[1]=='!')
{
Ret=Line+2;
Ret.resize(Ret.length()-1);
Ret=QuoteFileName(Ret)+" ";
}
fclose(pFile);
return Ret;
}
/*****************************************************************************/
string mhmakefileparser::GetFullCommand(const string &CommandIn)
{
map<string,string>::iterator pFound=m_CommandCache.find(CommandIn);
string Command=CommandIn;
if (pFound==m_CommandCache.end())
{
bool Found=false;
// Not found in the stack, search in the environment path
// Check if an extension is specified
const char *pBeg=Command.c_str();
const char *pEnd=pBeg+Command.length()-1;
bool HasExt=false;
while (pEnd>pBeg && *pEnd!='\\' && *pEnd!='/')
{
if (*pEnd=='.')
{
HasExt=true;
break;
}
pEnd--;
}
if (HasExt)
{
string FullCommand=SearchCommand(Command);
if (!FullCommand.empty())
{
Found=true;
Command=QuoteFileName(FullCommand);
}
}
else
{
/* First check for special internal commands */
if (CommandIn=="del")
{
m_CommandCache[CommandIn]="del";
return Command;
}
// Try with different extensions
string FullCommand=SearchCommand(Command,EXEEXT);
if (!FullCommand.empty())
{
Found=true;
Command=QuoteFileName(FullCommand);
}
else
{
FullCommand=SearchCommand(Command,".py");
if (!FullCommand.empty())
{
Found=true;
Command=GetPythonExe()+QuoteFileName(FullCommand);
}
else
{
// also search without extension, if found look inside the file if we find an executable to use
FullCommand=SearchCommand(Command);
if (!FullCommand.empty())
{
Found=true;
Command=GetExecutableFromCommand(FullCommand)+QuoteFileName(FullCommand);
}
}
}
}
if (!Found)
{
Command=GetComspec()+QuoteFileName(Command);
}
m_CommandCache[CommandIn]=Command;
return Command;
}
return pFound->second;
}
static void CommandSep(const string &Command, int &EndPos, int &NextBegin)
{
while (1)
{
EndPos=Command.find('&',NextBegin);
if (EndPos==string::npos || !EndPos)
{
// When there is only one command return that command, so we run %comspec% commands
// always via a temporary batch file. This is to avoid problems when quotes and pipe
// characters in parameters when using cmd /c
return;
}
EndPos--;
char C=Command[EndPos];
NextBegin=EndPos+2;
if (strchr("|<>",C))
{
continue;
}
if (NextBegin!=Command.length())
{
C=Command[NextBegin];
if (strchr("|<>",C))
{
continue;
}
}
while (strchr(" \t|<>",Command[NextBegin])) NextBegin++;
while (strchr(" \t|<>",Command[EndPos])) EndPos--;
break;
};
}
mh_pid_t mhmakefileparser::OsExeCommand(const string &Command, const string &Params, bool IgnoreError, string *pOutput) const
{
string FullCommandLine;
string ComSpec=GetComspec();
#ifdef WIN32
STARTUPINFO StartupInfo;
memset(&StartupInfo,0,sizeof(StartupInfo));
StartupInfo.cb=sizeof(STARTUPINFO);
PROCESS_INFORMATION ProcessInfo;
if (Command.substr(0,ComSpec.size())==ComSpec)
{
string tmpCommand=Command.substr(ComSpec.size(),Command.size());
FullCommandLine=ComSpec;
string ComspecCommandLine=tmpCommand+Params;
int NextBegin=0;
int EndPos=0;
CommandSep(ComspecCommandLine,EndPos,NextBegin);
// We have multiple commands so create an temporary batch file
FILE *pFile=(FILE*)1;
char Filename[MAX_PATH];
int Nr=1;
while (1)
{
sprintf(Filename,"%s\\tmp%d.bat",m_MakeDir->GetFullFileName().c_str(),Nr);
pFile=fopen(Filename,"r");
if (!pFile)
break;
fclose(pFile);
Nr++;
}
pFile=fopen(Filename,"w");
fprintf(pFile,"@echo off\n");
int PrevPos=0;
while (EndPos!=string::npos)
{
string SubCommand=ComspecCommandLine.substr(PrevPos,EndPos-PrevPos+1);
fprintf(pFile,"%s\n",SubCommand.c_str());
PrevPos=NextBegin;
CommandSep(ComspecCommandLine,EndPos,NextBegin);
}
string SubCommand=ComspecCommandLine.substr(PrevPos);
fprintf(pFile,"%s\n",SubCommand.c_str());
fclose(pFile);
FullCommandLine+=QuoteFileName(Filename);
((mhmakefileparser*)this)->m_FilesToRemoveAtEnd.push_back(string(Filename));
}
else
{
FullCommandLine=Command+Params;
}
char *pFullCommand=new char[FullCommandLine.length()+1];
strcpy(pFullCommand,FullCommandLine.c_str());
if (pOutput || g_Quiet)
{
mh_pid_t hChildStdinRd;
mh_pid_t hChildStdinWr;
mh_pid_t hChildStdoutRd;
mh_pid_t hChildStdoutWr;
mh_pid_t hChildStdinWrDup;
mh_pid_t hChildStdoutRdDup;
SECURITY_ATTRIBUTES saAttr;
BOOL fSuccess;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
return (mh_pid_t)-1;
/* Create new output read handle and the input write handle. Set
* the inheritance properties to FALSE. Otherwise, the child inherits
* the these handles; resulting in non-closeable handles to the pipes
* being created. */
fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
GetCurrentProcess(), &hChildStdinWrDup, 0,
FALSE, DUPLICATE_SAME_ACCESS);
if (!fSuccess) return (mh_pid_t)-1;
/* Close the inheritable version of ChildStdin that we're using. */
CloseHandle(hChildStdinWr);
if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
return (mh_pid_t)-1;
fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
GetCurrentProcess(), &hChildStdoutRdDup, 0,
FALSE, DUPLICATE_SAME_ACCESS);
if (!fSuccess) return (mh_pid_t)-1;
CloseHandle(hChildStdoutRd);
int hStdIn = _open_osfhandle((long)hChildStdinWrDup, _O_WRONLY|_O_TEXT);
FILE *pStdIn = _fdopen(hStdIn, "w");
int hStdOut = _open_osfhandle((long)hChildStdoutRdDup, _O_RDONLY|_O_TEXT);
FILE *pStdOut = _fdopen(hStdOut, "r");
StartupInfo.dwFlags = STARTF_USESTDHANDLES;
StartupInfo.hStdInput = hChildStdinRd;
StartupInfo.hStdOutput = hChildStdoutWr;
StartupInfo.hStdError = hChildStdoutWr;
if (!CreateProcess(NULL,pFullCommand,NULL,NULL,TRUE,CREATE_NO_WINDOW,m_pEnv,m_MakeDir->GetFullFileName().c_str(),&StartupInfo,&ProcessInfo))
{
delete[] pFullCommand;
string ErrorMessage=string("Error starting command: ") + FullCommandLine + " : " + stringify(GetLastError());
if (IgnoreError)
cerr << ErrorMessage << endl;
else
throw ErrorMessage;
}
delete[] pFullCommand;
if (!CloseHandle(hChildStdinRd)) return (mh_pid_t)-1;
if (!CloseHandle(hChildStdoutWr)) return (mh_pid_t)-1;
CloseHandle(ProcessInfo.hThread);
char Buf[256];
size_t Nbr;
while ( (Nbr=fread(Buf,1,sizeof(Buf)-1,pStdOut)) > 0)
{
if (pOutput)
{
Buf[Nbr]=0;
*pOutput+=Buf;
}
}
WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
fclose(pStdIn);
fclose(pStdOut);
DWORD ExitCode=0;
if (!GetExitCodeProcess(ProcessInfo.hProcess,&ExitCode) || ExitCode)
{
if (IgnoreError)
{
cerr << "Error running command: "<<Command<<", but ignoring error\n";
return (mh_pid_t)0; // Ignore error
}
else
return (mh_pid_t)-1;
}
CloseHandle(ProcessInfo.hProcess);
return (mh_pid_t)0;
}
else
{
if (!CreateProcess(NULL,pFullCommand,NULL,NULL,TRUE,0,m_pEnv,m_MakeDir->GetFullFileName().c_str(),&StartupInfo,&ProcessInfo))
{
delete[] pFullCommand;
string ErrorMessage=string("Error starting command: ") + Command + " : " + stringify(GetLastError());
if (IgnoreError)
cerr << ErrorMessage << endl;
else
throw ErrorMessage;
}
delete[] pFullCommand;
CloseHandle(ProcessInfo.hThread);
return ProcessInfo.hProcess;
}
#else
if (Command.substr(0,ComSpec.size())==ComSpec)
{
string tmpCommand=Command.substr(ComSpec.size(),Command.size());
FullCommandLine=ComSpec;
FullCommandLine+=QuoteFileName(tmpCommand)+Params;
}
else
{
FullCommandLine=Command+Params;
}
if (pOutput || g_Quiet)
{
int pipeto[2]; /* pipe to feed the exec'ed program input */
int pipefrom[2]; /* pipe to get the exec'ed program output */
if ( (-1==pipe(pipeto)) || (-1==pipe(pipefrom)) )
{
if (IgnoreError)
{
cerr << "Error creating pipe for : "<<Command<<", but ignoring error\n";
return (mh_pid_t)0; // Ignore error
}
else
return (mh_pid_t)-1;
}
pid_t ID=vfork();
if (ID==-1)
{
if (IgnoreError)
{
cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
return (mh_pid_t)0; // Ignore error
}
else
return (mh_pid_t)-1;
}
else if (ID==0)
{
int argc;
const char **pargv;
dup2( pipeto[0], STDIN_FILENO );
dup2( pipefrom[1], STDOUT_FILENO );
/* close unnecessary pipe descriptors for a clean environment */
close( pipeto[0] );
close( pipeto[1] );
close( pipefrom[0] );
close( pipefrom[1] );
poptParseArgvString(FullCommandLine.c_str(), &argc, &pargv);
if (-1==chdir(m_MakeDir->GetFullFileName().c_str()))
throw string("Error changing current directory to ")+m_MakeDir->GetFullFileName();
if (m_pEnv)
execve(pargv[0],(char *const*)pargv,m_pEnv);
else
execv(pargv[0],(char *const*)pargv);
free(pargv);
_exit (EXIT_FAILURE);
}
else
{
/* Close unused pipe ends. This is especially important for the
* pipefrom[1] write descriptor, otherwise readFromPipe will never
* get an EOF. */
close( pipeto[0] );
close( pipefrom[1] );
pid_t ID2=vfork();
if (ID2==-1)
{
if (IgnoreError)
{
cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
return (mh_pid_t)0; // Ignore error
}
else
return (mh_pid_t)-1;
}
else if (ID2==0)
{
/* Close pipe write descriptor, or we will never know when the
* writer process closes its end of the pipe and stops feeding the
* exec'ed program. */
close( pipeto[1] );
char Buf[256];
int Nbr;
while ( (Nbr=read(pipefrom[0],Buf,sizeof(Buf)-1)) > 0)
{
if (pOutput)
{
Buf[Nbr]=0;
*pOutput+=Buf;
}
}
close( pipefrom[0]);
_exit (EXIT_FAILURE);
}
else
{
/* close unused pipe end */
close( pipefrom[0] );
close( pipeto[1] );
int Status;
waitpid(ID2,&Status,0); // Wait until the reading of the output is finished
}
int Status;
int Ret=waitpid(ID,&Status,0);
if (Ret!=ID || Status)
{
if (IgnoreError)
{
cerr << "Error running command: "<<Command<<", but ignoring error\n";
return (mh_pid_t)0; // Ignore error
}
else
return (mh_pid_t)-1;
}
}
}
else
{ // No pOutput
pid_t ID=fork();
if (ID==-1)
{
if (IgnoreError)
{
cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
return (mh_pid_t)0; // Ignore error
}
else
return (mh_pid_t)-1;
}
else if (ID==0)
{
int argc;
const char **pargv;
poptParseArgvString(FullCommandLine.c_str(), &argc, &pargv);
if (-1==chdir(m_MakeDir->GetFullFileName().c_str()))
throw string("Error changing current directory to ")+m_MakeDir->GetFullFileName();
if (m_pEnv)
execve(pargv[0],(char *const*)pargv,m_pEnv);
else
execv(pargv[0],(char *const*)pargv);
free(pargv);
_exit (EXIT_FAILURE);
}
else
{
return (mh_pid_t)ID;
}
}
return (mh_pid_t)0;
#endif
}
///////////////////////////////////////////////////////////////////////////////
#ifndef WIN32
string EscapeQuotes(const string &Params)
{
int OldPos=0;
int Pos;
string Quote("\\\"");
string SemiColon(" ; ");
string Ret;
while (1)
{
int Pos=Params.find_first_of('"',OldPos);
int Pos2=Params.find(" & ",OldPos);
string ToReplace(Quote);
int Inc=1;
if (Pos==string::npos)
{
if (Pos2==string::npos)
break;
Pos=Pos2;
ToReplace=SemiColon;
Inc=3;
}
else
{
if (Pos2!=string::npos && Pos2<Pos)
{
Pos=Pos2;
ToReplace=SemiColon;
Inc=3;
}
}
Ret+=Params.substr(OldPos,Pos-OldPos);
Ret+=ToReplace;
OldPos=Pos+Inc;
}
Ret+=Params.substr(OldPos);
return Ret;
}
#endif
///////////////////////////////////////////////////////////////////////////////
mh_pid_t mhmakefileparser::ExecuteCommand(string Command, bool &IgnoreError, string *pOutput)
{
bool Echo=true;
IgnoreError=false;
while (Command.length())
{
if (Command[0]=='@')
{
Echo=false;
Command=Command.substr(1);
continue;
}
if (Command[0]=='-')
{
IgnoreError=true;
Command=Command.substr(1);
continue;
}
break;
}
if (!Command.length())
(mh_pid_t)0;
string InCommand=Command;
if (g_Quiet)
Echo=false;
const char *pCom=Command.c_str();
int StartCommandPos;
int EndCommandPos;
int BeginParamPos;
if (*pCom=='"')
{
StartCommandPos=1;
EndCommandPos=1;
while (pCom[EndCommandPos]!='"') EndCommandPos++;
}
else
{
StartCommandPos=0;
EndCommandPos=0;
}
while (!strchr(" \t",pCom[EndCommandPos])) EndCommandPos++;
BeginParamPos=EndCommandPos;
string Params=Command.substr(BeginParamPos);
Command=Command.substr(StartCommandPos,EndCommandPos-StartCommandPos);
// If we have special characters in the params we always call the command via the shell
unsigned i;
for (i=0; i<Params.size(); i++)
{
if (strchr("<>|&",Params[i]))
{
break;
}
}
if (i==Params.size())
{
if (Command!="del" && Command!="touch" && Command!="copy" && Command!="echo" && Command!="mkdir")
Command=GetFullCommand(Command);
#ifndef WIN32
if (Command.substr(0,GetComspec().size())==GetComspec())
{
Params=EscapeQuotes(Params);
Params+="\"";
}
#endif
}
else
{
if (Command!="echo" || strchr(Params.c_str(),'|')) // the EchoCommand(Params) does not implement piping, only redirecting (>)
{
string FullCommand=GetFullCommand(Command);
string ComSpec=GetComspec();
if (FullCommand.substr(0,ComSpec.size())!=ComSpec)
Command=FullCommand; // Only use FullCommand when it was found and not prepending by the comspec.
Command=ComSpec+Command;
#ifndef WIN32
Params=EscapeQuotes(Params);
Params+="\"";
#endif
}
}
if (Echo
#ifdef _DEBUG
|| g_DoNotExecute
#endif
)
{
#ifdef _DEBUG
if (g_PrintAdditionalInfo)
cout << Command << Params << endl;
else
cout << InCommand << endl;
#endif
}
/* first we check special internal commands */
#ifdef _DEBUG
if (pOutput || !g_DoNotExecute)
{
#endif
if (Command=="del")
{
return DeleteFiles(Params);
}
else if (Command=="touch")
{
return TouchFiles(Params);
}
else if (Command=="copy")
{
return CopyFiles(Params);
}
else if (Command=="echo")
{
return EchoCommand(Params);
}
else if (Command=="mkdir")
{
return MakeDirsCommand(Params);
}
return OsExeCommand(Command,Params,IgnoreError,pOutput);
#ifdef _DEBUG
}
#endif
return (mh_pid_t)0; /* No Error */
}
///////////////////////////////////////////////////////////////////////////////
void mhmakefileparser::BuildDependencies(const refptr<rule> &pRule, fileinfo* pTarget, mh_time_t TargetDate, mh_time_t &YoungestDate, bool &MakeTarget)
{
vector<fileinfo*> &Deps=pTarget->GetDeps();
vector<fileinfo*>::iterator pDepIt=Deps.begin();
while (pDepIt!=Deps.end())
{
StartBuildTarget(*pDepIt);
pDepIt++;
}
pDepIt=Deps.begin();
while (pDepIt!=Deps.end())
{
mh_time_t DepDate=WaitBuildTarget(*pDepIt);
#ifdef _DEBUG
if (!DepDate.DoesExist()&&!(*pDepIt)->IsPhony())
{
if (!(*pDepIt)->GetDir()->GetDate().DoesExist())
cout << "Building of "<<(*pDepIt)->GetFullFileName()<<" failed because directory does not exist (rule defined to create it?)\n";
else
cout << "Does not known how to create "<<(*pDepIt)->GetFullFileName()<<".\n";
}
#endif
if (DepDate.IsNewer(YoungestDate))
YoungestDate=DepDate;
if (DepDate.IsNewer(TargetDate))
{
#ifdef _DEBUG
if (pRule&&g_pPrintDependencyCheck && DepDate.IsExistingFile() && TargetDate.IsExistingFile())
cout<<"Going to build "<<pTarget->GetQuotedFullFileName()<<" because "<<(*pDepIt)->GetQuotedFullFileName()<<" is more recent\n";
#endif
MakeTarget=true;
}
pDepIt++;
}
}
///////////////////////////////////////////////////////////////////////////////
mh_time_t mhmakefileparser::StartBuildTarget(fileinfo* pTarget,bool bCheckTargetDir)
{
#ifdef _DEBUG
if (g_CheckCircularDeps)
{
deque<fileinfo*>::const_iterator pFind=find(m_TargetStack.begin(),m_TargetStack.end(),pTarget);
if (pFind!=m_TargetStack.end())
{
cout << "Circular dependency detected.\n"<<pTarget->GetQuotedFullFileName()<<" depending on itself.\n";
cout << "Dependency stack:\n";
deque<fileinfo*>::const_iterator pIt=m_TargetStack.begin();
while (pIt!=m_TargetStack.end())
{
cout << " " << (*pIt)->GetQuotedFullFileName() << endl;
pIt++;
}
}
if (!pTarget->IsBuildStarted()) m_TargetStack.push_back(pTarget);
}
#endif
#ifdef _DEBUG
static int Indent;
#endif
if (g_StopCompiling)
{
throw string("Compilation Interrupted by user.");
}
if (pTarget->IsBuild())
{
#ifdef _DEBUG
if (g_pPrintDependencyCheck)
{
for (int i=0; i<Indent; i++)
cout<<" ";
cout<<" Already build "<<pTarget->GetQuotedFullFileName()<<" : "<<pTarget->GetDate()<<endl;
}
#endif
return pTarget->GetDate();
}
if (pTarget->IsBuilding())
return mh_time_t(); // pTarget is still building, so we have to wait
#ifdef _DEBUG
if (g_GenProjectTree)
cout << pTarget->GetQuotedFullFileName() << endl;
Indent++;
if (g_pPrintDependencyCheck)
{
for (int i=0; i<Indent; i++)
cout<<" ";
cout<<"Building dependencies of "<<pTarget->GetQuotedFullFileName()<<endl;
}
#endif
pTarget->SetBuild();
/* Optimisation: do not build target when target dir does not exist,
but first build the target dir, in case there exists a rule for it*/
refptr<rule> pRule=pTarget->GetRule();
if (!pRule && bCheckTargetDir)
{
fileinfo *pTargetDir=pTarget->GetDir();
mh_time_t TargetDirDate=BuildTarget(pTargetDir,false);
if (!pTargetDir->Exists())
{
#ifdef _DEBUG
Indent--;
if (g_CheckCircularDeps)
{
m_TargetStack.pop_back();
}
#endif
return TargetDirDate;
}
}
mh_time_t TargetDate=pTarget->GetDate();
mh_time_t YoungestDate=TargetDate;
bool MakeTarget=!TargetDate.DoesExist(); // When the target does not exist, always build when a rule is found. This also makes sure the autodepscan will be done in case the target does not exist yet
if (!pRule || !pRule->GetCommands().size())
{
implicitruledep_t Result;
IMPLICITRULE::SearchImplicitRule(pTarget,Result);
implicitruledep_t::iterator ResultIt=Result.begin();
while (ResultIt!=Result.end())
{
if (ResultIt->first.empty())
{
pRule=ResultIt->second;
pTarget->SetRule(pRule);
#ifdef _DEBUG
if (g_PrintAdditionalInfo)
{
cout<<"Found implicit rule for "<<pTarget->GetQuotedFullFileName()<<endl;
pRule->PrintCommands(pTarget);
}
#endif
break;
}
else if (!IMPLICITRULE::PushRule(ResultIt->second))
{
/* We have to check all the implicitrule dependencies, only when they all can be build,
the implicit rule matches */
#ifdef _DEBUG
fileinfo *pYoungestTarget;
m_ImplicitSearch++;
#endif
mh_time_t ThisYoungestDate=YoungestDate;
vector<fileinfo*>::iterator ImplicitRuleDepsIt=ResultIt->first.begin();
while (ImplicitRuleDepsIt!=ResultIt->first.end())
{
fileinfo *pNewTarget=*ImplicitRuleDepsIt;
mh_time_t DepDate=BuildTarget(pNewTarget);
if (!DepDate.DoesExist())
{
pNewTarget=ResultIt->second->GetMakefile()->SearchvPath(pNewTarget);
if (pNewTarget!=NULL)
{
*ImplicitRuleDepsIt=pNewTarget; /* The file was elsewere so we have to update the dependencies */
DepDate=pNewTarget->GetDate();
}
}
if (!DepDate.DoesExist())
break;
if (DepDate.IsNewer(ThisYoungestDate))
{
ThisYoungestDate=DepDate;
#ifdef _DEBUG
pYoungestTarget=pNewTarget;
#endif
}
ImplicitRuleDepsIt++;
}
IMPLICITRULE::PopRule(ResultIt->second);
#ifdef _DEBUG
m_ImplicitSearch--;
#endif
if (ImplicitRuleDepsIt==ResultIt->first.end()) // All deps exists
{
ThisYoungestDate=YoungestDate;
pRule=ResultIt->second;
pTarget->InsertDeps(ResultIt->first);
pTarget->SetRule(pRule); /* This is an implicit rule so do not add the target */
#ifdef _DEBUG
if (g_PrintAdditionalInfo)
{
cout<<"Found implicit rule for "<<pTarget->GetQuotedFullFileName()<<". Dependents:\n";
vector<fileinfo*>::iterator ImplicitRuleDepsIt=ResultIt->first.begin();
while (ImplicitRuleDepsIt!=ResultIt->first.end())
{
cout<<" "<<(*ImplicitRuleDepsIt)->GetQuotedFullFileName()<<endl;
ImplicitRuleDepsIt++;
}
pRule->PrintCommands(pTarget);
}
#endif
if (ThisYoungestDate.IsNewer(TargetDate))
{
#ifdef _DEBUG
if (pRule,g_pPrintDependencyCheck && ThisYoungestDate.IsExistingFile() && TargetDate.IsExistingFile())
cout<<"Going to build "<<pTarget->GetQuotedFullFileName()<<" because "<<pYoungestTarget->GetQuotedFullFileName()<<" is more recent\n";
#endif
MakeTarget=true;
}
break;
}
}
#ifdef _DEBUG
else if (g_PrintAdditionalInfo)
{
cout << "Stopping implicit search of "<<pTarget->GetFullFileName()<<" because of implicit rule recursion detected.\n";
}
#endif
ResultIt++;
}
if (pRule)
{
#ifdef _DEBUG
pTarget->SetBuilding();
pTarget->SetRule(pRule);
pTarget->ClearBuilding();
#else
pTarget->SetRule(pRule);
#endif
}
}
mhmakefileparser *pMakefile=NULL;
if (pRule)
{
pMakefile=pRule->GetMakefile();
if (pMakefile->ForceAutoDepRescan()||MakeTarget==true)
pMakefile->UpdateAutomaticDependencies(pTarget);
}
else if (pTarget->GetAutoDepsMakefile())
pTarget->GetAutoDepsMakefile()->UpdateNoRuleAutomaticDependencies(pTarget);
BuildDependencies(pRule,pTarget,TargetDate,YoungestDate,MakeTarget);
if (pRule)
{
#ifdef _DEBUG
if (g_pPrintDependencyCheck)
{
for (int i=0; i<Indent; i++)
cout<<" ";
cout<<"Building "<<pTarget->GetQuotedFullFileName()<<endl;
}
#endif
if (!MakeTarget)
{
if (!TargetDate.DoesExist() || ( (g_RebuildAll || pMakefile->m_RebuildAll) && TargetDate.IsOlder(m_sBuildTime)))
{
#ifdef _DEBUG
if (g_pPrintDependencyCheck)
{
if (!TargetDate.DoesExist())
{
if (!m_ImplicitSearch && !pTarget->IsPhony())
cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" because it does not exist yet\n";
}
else if (TargetDate.IsOlder(m_sBuildTime))
{
cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" because need to rebuild all (-a)\n";
}
}
#endif
MakeTarget=true;
}
}
// Now execute the commands
vector<string> &Commands=pRule->GetCommands();
if (!MakeTarget)
{
vector<string>::iterator CommandIt=Commands.begin();
md5_context ctx;
md5_starts( &ctx );
while (CommandIt!=Commands.end())
{
pMakefile->SetRuleThatIsBuild(pTarget); // Make sure that the command expension is correct
string Command=pMakefile->ExpandExpression(*CommandIt);
pMakefile->ClearRuleThatIsBuild(); /* Make sure that further expansion is not taking this rule into account.*/
md5_update( &ctx, (uint8 *)Command.c_str(), (unsigned long)Command.size());
CommandIt++;
}
uint32 Md5_32=md5_finish32( &ctx);
if (!pTarget->CompareMd5_32(Md5_32))
{
if (TargetDate.IsNewerOrSame(m_sBuildTime) || TargetDate.IsDir())
{
// Only rebuild if it is not yet rebuild in this current run. This may happen for implicit rules that have multiple targets (implicit rules that build more then one target at the same time
pTarget->SetCommandsMd5_32(Md5_32);
pMakefile->AddTarget(pTarget);
pMakefile->SetAutoDepsDirty(); /* We need to update the autodeps file if the md5 has been changed */
}
else
{
#ifdef _DEBUG
if (!g_GenProjectTree)
cout << "Md5 is different for " << pTarget->GetQuotedFullFileName() << " Old:"<<hex<<pTarget->GetCommandsMd5_32()<<", New: "<<Md5_32<<". Commandline must have been changed so recompiling\n";
#endif
#ifdef _DEBUG
Indent--;
if (g_CheckCircularDeps)
{
m_TargetStack.pop_back();
}
#endif
MakeTarget=true;
}
}
}
if (MakeTarget)
{
// Queue for execution
if (sm_CommandQueue.QueueTarget(pTarget))
return mh_time_t();
mh_time_t NewDate=pTarget->GetDate();
if (NewDate.IsNewer(YoungestDate))
YoungestDate=NewDate;
}
}
#ifdef _DEBUG
if (g_pPrintDependencyCheck)
{
for (int i=0; i<Indent; i++)
cout<<" ";
cout<<"Building "<<pTarget->GetQuotedFullFileName()<<" finished : "<< YoungestDate << endl;
}
Indent--;
if (g_CheckCircularDeps)
{
m_TargetStack.pop_back();
}
if (!m_ImplicitSearch && !pTarget->Exists() && !pTarget->IsPhony() && !g_DoNotExecute && !g_GenProjectTree)
{
// This is only a warning for phony messages
cout<<"Warning: don't know how to make "<<pTarget->GetQuotedFullFileName()<<"\nMake the rule a phony rule to avoid this warning (but only do it when it is really phony).\n";;
}
#endif
pTarget->SetDate(YoungestDate); /* This is especially needed for phony targets in between real targets */
return YoungestDate;
}
///////////////////////////////////////////////////////////////////////////////
mh_time_t mhmakefileparser::WaitBuildTarget(fileinfo* pTarget)
{
return sm_CommandQueue.WaitForTarget(pTarget);
}
///////////////////////////////////////////////////////////////////////////////
void mhmakefileparser::BuildIncludedMakefiles()
{
vector<fileinfo*>::iterator MakefileIt=m_IncludedMakefiles.begin();
while (MakefileIt!=m_IncludedMakefiles.end())
{
#ifdef _DEBUG
if (g_PrintAdditionalInfo)
cout<<"Building include file "<<(*MakefileIt)->GetQuotedFullFileName()<<endl;
#endif
BuildTarget(*MakefileIt);
MakefileIt++;
}
}
|