summaryrefslogtreecommitdiff
path: root/tests/utils/dotest.pp
blob: 6025aee6ca4e0a50261ad1d58e795cc1ec6304ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
{
    This file is part of the Free Pascal test suite.
    Copyright (c) 1999-2002 by the Free Pascal development team.

    This program makes the compilation and
    execution of individual test sources.

    See the file COPYING.FPC, included in this distribution,
    for details about the copyright.

    This program 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.

 **********************************************************************}
{$mode objfpc}
{$goto on}
{$H+}

program dotest;
uses
  sysutils,
  dos,
{$ifdef macos}
  macutils,
{$endif}
  teststr,
  testu,
  redir,
  bench,
  classes;

{$ifdef go32v2}
  {$define LIMIT83FS}
{$endif}
{$ifdef os2}
  {$define LIMIT83FS}
{$endif}
{$ifdef msdos}
  {$define LIMIT83FS}
{$endif}

type
  tcompinfo = (compver,comptarget,compcpu);
  tdelexecutable = (deBefore, deAfter);
  tdelexecutables = set of tdelexecutable;

const
  ObjExt='o';
  PPUExt='ppu';
{$ifdef UNIX}
  SrcExeExt='';
{$else UNIX}
{$ifdef MACOS}
  SrcExeExt='';
{$else MACOS}
  SrcExeExt='.exe';
{$endif MACOS}
{$endif UNIX}
  ExeExt : string = '';
  DllExt : string = '.so';
  DllPrefix: string = 'lib';
  DefaultTimeout=60;
  READ_ONLY = 0;

var
  Config : TConfig;
  CompilerLogFile,
  ExeLogFile,
  LongLogfile,
  FailLogfile,
  RTLUnitsDir,
  TestOutputDir,
  OutputDir : string;
  CompilerBin,
{ CompilerCPU and CompilerTarget are lowercased at start
  to avoid need to call lowercase again and again ... }
  CompilerCPU,
  CompilerTarget,
  CompilerVersion,
  DefaultCompilerCPU,
  DefaultCompilerTarget,
  DefaultCompilerVersion : string;
  PPFile : TStringList;
  PPFileInfo : TStringList;
  TestName : string;
  Current : longint;

const
  DoGraph : boolean = false;
  UseOSOnly : boolean = false;
  DoInteractive : boolean = false;
  DoExecute : boolean = false;
  DoKnown : boolean = false;
  DoAll : boolean = false;
  DoUsual : boolean = true;
  { TargetDir : string = ''; unused }
  BenchmarkInfo : boolean = false;
  ExtraCompilerOpts : string = '';
  DelExecutable : TDelExecutables = [];
  RemoteAddr : string = '';
  RemotePathPrefix : string = '';
  RemotePath : string = '/tmp';
  RemotePara : string = '';
  RemoteRshParas : string = '';
  RemoteShell : string = '';
  RemoteShellBase : string = '';
  RemoteShellNeedsExport : boolean = false;
  rshprog : string = 'rsh';
  rcpprog : string = 'rcp';
  rquote : string = '''';
  UseTimeout : boolean = false;
  emulatorname : string = '';
  TargetCanCompileLibraries : boolean = true;
  UniqueSuffix: string = '';

{ Constants used in IsAbsolute function }
  TargetHasDosStyleDirectories : boolean = false;
  TargetAmigaLike : boolean = false;
  TargetIsMacOS : boolean = false;
  TargetIsUnix : boolean = false;

{ extracted from rtl/macos/macutils.inc }

function IsMacFullPath (const path: string): Boolean;
  begin
    if Pos(':', path) = 0 then    {its partial}
      IsMacFullPath := false
    else if path[1] = ':' then
      IsMacFullPath := false
    else
      IsMacFullPath := true
  end;


Function IsAbsolute (Const F : String) : boolean;
{
  Returns True if the name F is a absolute file name
}
begin
  IsAbsolute:=false;
  if TargetHasDosStyleDirectories then
    begin
      if (F[1]='/') or (F[1]='\') then
        IsAbsolute:=true;
      if (Length(F)>2) and (F[2]=':') and ((F[3]='\') or (F[3]='/')) then
        IsAbsolute:=true;
    end
  else if TargetAmigaLike then
    begin
      if (length(F)>0) and (Pos(':',F) <> 0) then
        IsAbsolute:=true;
    end
  else if TargetIsMacOS then
    begin
      IsAbsolute:=IsMacFullPath(F);
    end
  { generic case }
  else if (F[1]='/') then
    IsAbsolute:=true;
end;

Function FileExists (Const F : String) : Boolean;
{
  Returns True if the file exists, False if not.
}
Var
  info : searchrec;
begin
  FindFirst (F,anyfile,Info);
  FileExists:=DosError=0;
  FindClose (Info);
end;


Function PathExists (Const F : String) : Boolean;
{
  Returns True if the file exists, False if not.
}
Var
  info : searchrec;
begin
  FindFirst (F,anyfile,Info);
  PathExists:=(DosError=0) and (Info.Attr and Directory=Directory);
  FindClose (Info);
end;


function ToStr(l:longint):string;
var
  s : string;
begin
  Str(l,s);
  ToStr:=s;
end;


function ToStrZero(l:longint;nbzero : byte):string;
var
  s : string;
begin
  Str(l,s);
  while length(s)<nbzero do
    s:='0'+s;
  ToStrZero:=s;
end;


function trimspace(const s:string):string;
var
  i,j : longint;
begin
  i:=length(s);
  while (i>0) and (s[i] in [#9,' ']) do
   dec(i);
  j:=1;
  while (j<i) and (s[j] in [#9,' ']) do
   inc(j);
  trimspace:=Copy(s,j,i-j+1);
end;


function IsInList(const entry,list:string):boolean;
var
  i,istart : longint;
begin
  IsInList:=false;
  i:=0;
  while (i<length(list)) do
   begin
     { Find list item }
     istart:=i+1;
     while (i<length(list)) and
           (list[i+1]<>',') do
      inc(i);
     if Upcase(entry)=Upcase(TrimSpace(Copy(list,istart,i-istart+1))) then
      begin
        IsInList:=true;
        exit;
      end;
     { skip , }
     inc(i);
   end;
end;


procedure SetPPFileInfo;
Var
  info : searchrec;
  dt : DateTime;
begin
  FindFirst (PPFile[current],anyfile,Info);
  If DosError=0 then
    begin
      UnpackTime(info.time,dt);
      PPFileInfo.Insert(current,PPFile[current]+' '+ToStr(dt.year)+'/'+ToStrZero(dt.month,2)+'/'+
        ToStrZero(dt.day,2)+' '+ToStrZero(dt.Hour,2)+':'+ToStrZero(dt.min,2)+':'+ToStrZero(dt.sec,2));
    end
  else
    PPFileInfo.Insert(current,PPFile[current]);
  FindClose (Info);
end;


function SplitPath(const s:string):string;
var
  i : longint;
begin
  i:=Length(s);
  while (i>0) and not(s[i] in ['/','\'{$IFDEF MACOS},':'{$ENDIF}]) do
   dec(i);
  SplitPath:=Copy(s,1,i);
end;


function SplitBasePath(const s:string): string;
var
  i : longint;
begin
  i:=1;
  while (i<length(s)) and not(s[i] in ['/','\'{$IFDEF MACOS},':'{$ENDIF}]) do
   inc(i);
  if s[i] in  ['/','\'{$IFDEF MACOS},':'{$ENDIF}] then
    dec(i);
  SplitBasePath:=Copy(s,1,i);
end;

Function SplitFileName(const s:string):string;
var
  p : dirstr;
  n : namestr;
  e : extstr;
begin
  FSplit(s,p,n,e);
  SplitFileName:=n+e;
end;

Function SplitFileBase(const s:string):string;
var
  p : dirstr;
  n : namestr;
  e : extstr;
begin
  FSplit(s,p,n,e);
  SplitFileBase:=n;
end;

Function SplitFileExt(const s:string):string;
var
  p : dirstr;
  n : namestr;
  e : extstr;
begin
  FSplit(s,p,n,e);
  SplitFileExt:=e;
end;


function ForceExtension(Const HStr,ext:String):String;
{
  Return a filename which certainly has the extension ext
}
var
  j : longint;
begin
  j:=length(Hstr);
  while (j>0) and (Hstr[j]<>'.') do
   dec(j);
  if j=0 then
   j:=length(Hstr)+1;
  if Ext<>'' then
   begin
     if Ext[1]='.' then
       ForceExtension:=Copy(Hstr,1,j-1)+Ext
     else
       ForceExtension:=Copy(Hstr,1,j-1)+'.'+Ext
   end
  else
   ForceExtension:=Copy(Hstr,1,j-1);
end;

type
  TCharSet = set of char;

function GetToken(var s: string; Delims: TCharSet = [' ']):string;
var
  i : longint;
  p: PChar;
begin
  p:=PChar(s);
  i:=0;
  while (p^ <> #0) and not (p^ in Delims) do begin
    Inc(p);
    Inc(i);
  end;
  GetToken:=Copy(s,1,i);
  Delete(s,1,i+1);
end;

procedure mkdirtree(const s:string);
var
  SErr, hs : string;
  Err: longint;
begin
  if s='' then
    exit;
  if s[length(s)] in ['\','/'{$IFDEF MACOS},':'{$ENDIF}] then
    hs:=Copy(s,1,length(s)-1)
  else
    hs:=s;
  if not PathExists(hs) then
    begin
      { Try parent first }
      mkdirtree(SplitPath(hs));
      { make this dir }
      Verbose(V_Debug,'Making directory '+s);
      {$I-}
       MkDir (HS);
      {$I+}
      Err := IOResult;
      if Err <> 0 then
       begin
        { did another parallel instance create it in the mean time? }
        if not PathExists(hs) then
          begin
            { no -> error }
            Str (Err, SErr);
            Verbose (V_Error, 'Directory creation of "'+HS+'" failed ' + SErr);
          end;
       end;
    end;
end;


    Function RemoveFile(const f:string):boolean;
      var
        g : file;
      begin
        assign(g,f);
        {$I-}
         erase(g);
        {$I+}
        RemoveFile:=(ioresult=0);
      end;


function Copyfile(const fn1,fn2:string;append:boolean) : longint;
const
  bufsize = 16384;
var
  f,g : file;
  oldfilemode : byte;
  st : string;
  addsize,
  i   : longint;
  buf : pointer;
begin
  if Append then
   Verbose(V_Debug,'Appending '+fn1+' to '+fn2)
  else
   Verbose(V_Debug,'Copying '+fn1+' to '+fn2);
  assign(g,fn2);
  if append then
   begin
     {$I-}
      reset(g,1);
     {$I+}
     if ioresult<>0 then
      append:=false
     else
      seek(g,filesize(g));
   end;
  if not append then
   begin
     {$I-}
      rewrite(g,1);
     {$I+}
     if ioresult<>0 then
      Verbose(V_Error,'Can''t open '+fn2+' for output');
   end;
  assign(f,fn1);
  {$I-}
  { Try using read only file mode }
  oldfilemode:=filemode;
  filemode:=READ_ONLY;
  reset(f,1);
  {$I+}
  addsize:=0;
  getmem(buf,bufsize);
  if ioresult<>0 then
   begin
     sleep(1000);
     {$I-}
      reset(f,1);
     {$I+}
      if ioresult<>0 then
        begin
          Verbose(V_Warning,'Can''t open '+fn1);
          st:='Can''t open '+fn1;
          i:=length(st);
          // blocksize is larger than 255, so no check is needed
          move(st[1],buf^,i);
          blockwrite(g,buf^,i);
          freemem(buf,bufsize);
          close(g);
          filemode:=oldfilemode;
          exit;
        end;
   end;
  filemode:=oldfilemode;
  repeat
    blockread(f,buf^,bufsize,i);
    blockwrite(g,buf^,i);
    addsize:=addsize+i;
  until i<bufsize;
  freemem(buf,bufsize);
  close(f);
  close(g);
  CopyFile:=addsize;
end;


procedure AddLog(const logfile,s:string);
var
  t : text;
begin
  assign(t,logfile);
  {$I-}
   append(t);
  {$I+}
  if ioresult<>0 then
   begin
     {$I-}
      rewrite(t);
     {$I+}
     if ioresult<>0 then
       Verbose(V_Abort,'Can''t append to '+logfile);
   end;
  writeln(t,s);
  close(t);
end;


procedure ForceLog(const logfile:string);
var
  t : text;
begin
  assign(t,logfile);
  {$I-}
   append(t);
  {$I+}
  if ioresult<>0 then
   begin
     {$I-}
      rewrite(t);
     {$I+}
     if ioresult<>0 then
       Verbose(V_Abort,'Can''t Create '+logfile);
   end;
  close(t);
end;


function GetCompilerInfo(c:tcompinfo):boolean;
var
  t  : text;
  hs : string;
begin
  GetCompilerInfo:=false;
  { Try to get all information in one call, this is
    supported in 1.1. Older compilers 1.0.x will only
    return the first info }
  case c of
    compver :
      begin
        if DefaultCompilerVersion<>'' then
          begin
            GetCompilerInfo:=true;
            exit;
          end;
        hs:='-iVTPTO';
      end;
    compcpu :
      begin
        if DefaultCompilerCPU<>'' then
          begin
            GetCompilerInfo:=true;
            exit;
          end;
        hs:='-iTPTOV';
      end;
    comptarget :
      begin
        if DefaultCompilerTarget<>'' then
          begin
            GetCompilerInfo:=true;
            exit;
          end;
        hs:='-iTOTPV';
      end;
  end;
  ExecuteRedir(CompilerBin,hs,'','out.'+UniqueSuffix,'');
  assign(t,'out.'+UniqueSuffix);
  {$I-}
   reset(t);
  {$ifdef windows}
    { try to cope with Windows problems related to AntiVirus scanner
      that generate lag time during which access to a given if is forbidden }
   if (inoutres=5) then
     begin
       Sleep(5000);
       ioresult;
       Verbose(V_Warning,'Windows file not accessible out.'+UniqueSuffix);
       reset(t);
     end;
   {$endif windows}
   readln(t,hs);
   close(t);
   erase(t);
  {$I+}
  if ioresult<>0 then
   Verbose(V_Error,'Can''t get Compiler Info')
  else
   begin
     Verbose(V_Debug,'Retrieved Compiler Info: "'+hs+'"');
     case c of
       compver :
         begin
           DefaultCompilerVersion:=GetToken(hs);
           DefaultCompilerCPU:=GetToken(hs);
           DefaultCompilerTarget:=GetToken(hs);
         end;
       compcpu :
         begin
           DefaultCompilerCPU:=GetToken(hs);
           DefaultCompilerTarget:=GetToken(hs);
           DefaultCompilerVersion:=GetToken(hs);
         end;
       comptarget :
         begin
           DefaultCompilerTarget:=GetToken(hs);
           DefaultCompilerCPU:=GetToken(hs);
           DefaultCompilerVersion:=GetToken(hs);
         end;
     end;
     GetCompilerInfo:=true;
   end;
end;


function GetCompilerVersion:boolean;
const
  CompilerVersionDebugWritten : boolean = false;
begin
  if CompilerVersion='' then
    begin
      GetCompilerVersion:=GetCompilerInfo(compver);
      CompilerVersion:=DefaultCompilerVersion;
    end
  else
    GetCompilerVersion:=true;
  if GetCompilerVersion and not CompilerVersionDebugWritten then
    begin
      Verbose(V_Debug,'Compiler Version: "'+CompilerVersion+'"');
      CompilerVersionDebugWritten:=true;
    end;
end;


function GetCompilerCPU:boolean;
const
  CompilerCPUDebugWritten : boolean = false;
begin
  if CompilerCPU='' then
    begin
      GetCompilerCPU:=GetCompilerInfo(compcpu);
      CompilerCPU:=lowercase(DefaultCompilerCPU);
    end
  else
    GetCompilerCPU:=true;
  if GetCompilerCPU and not CompilerCPUDebugWritten then
    begin
      Verbose(V_Debug,'Compiler CPU: "'+CompilerCPU+'"');
      CompilerCPUDebugWritten:=true;
    end;
end;


function GetCompilerTarget:boolean;
const
  CompilerTargetDebugWritten : boolean = false;
begin
  if CompilerTarget='' then
    begin
      GetCompilerTarget:=GetCompilerInfo(comptarget);
      CompilerTarget:=lowercase(DefaultCompilerTarget);
    end
  else
    GetCompilerTarget:=true;
  if GetCompilerTarget and not CompilerTargetDebugWritten then
    begin
      Verbose(V_Debug,'Compiler Target: "'+CompilerTarget+'"');
      CompilerTargetDebugWritten:=true;
    end;
end;


function CompilerFullTarget:string;
begin
  if UseOSOnly then
    CompilerFullTarget:=CompilerTarget
  else
    CompilerFullTarget:=CompilerCPU+'-'+CompilerTarget;
end;

{ Set the three constants above according to
  the current target }

procedure SetTargetDirectoriesStyle;
var
  LTarget : string;
begin
  { Call this first to ensure that CompilerTarget is not empty }
  GetCompilerTarget;
  LTarget := CompilerTarget;
  TargetHasDosStyleDirectories :=
    (LTarget='emx') or
    (LTarget='go32v2') or
    (LTarget='msdos') or
    (LTarget='nativent') or
    (LTarget='os2') or
    (LTarget='symbian') or
    (LTarget='watcom') or
    (LTarget='wdosx') or
    (LTarget='win16') or
    (LTarget='win32') or
    (LTarget='win64');
  TargetAmigaLike:=
    (LTarget='amiga') or
    (LTarget='morphos');
  TargetIsMacOS:=
    (LTarget='macos');
  { Base on whether UNIX is defined as default macro
    in extradefines in systesms/i_XXX.pas units }
  TargetIsUnix:=
    (LTarget='linux') or
    (LTarget='linux6432') or
    (LTarget='freebsd') or
    (LTarget='openbsd') or
    (LTarget='netbsd') or
    (LTarget='beos') or
    (LTarget='haiku') or
    (LTarget='solaris') or
    (LTarget='iphonesim') or
    (LTarget='darwin') or
    (LTarget='aix') or
    (LTarget='android');

  { Set ExeExt for CompilerTarget.
    This list has been set up 2013-01 using the information in
    compiler/system/i_XXX.pas units.
    We should update this list when adding new targets PM }
  if (TargetHasDosStyleDirectories) or (LTarget='wince') then
    begin
      ExeExt:='.exe';
      DllExt:='.dll';
      DllPrefix:='';
    end
  else if LTarget='atari' then
    begin
      ExeExt:='.tpp';
      DllExt:='.dll';
      DllPrefix:='';
    end
  else if LTarget='gba' then
    ExeExt:='.gba'
  else if LTarget='nds' then
    ExeExt:='.bin'
  else if (LTarget='netware') or (LTarget='netwlibc') then
    begin
      ExeExt:='.nlm';
      DllExt:='.nlm';
      DllPrefix:='';
    end
  else if LTarget='wii' then
    ExeExt:='.dol';
end;

{$ifndef LIMIT83FS}
{ Set the UseOSOnly constant above according to
  the current target }

procedure SetUseOSOnly;
var
  LTarget : string;
begin
  { Call this first to ensure that CompilerTarget is not empty }
  GetCompilerTarget;
  LTarget := CompilerTarget;
  UseOSOnly:= (LTarget='emx') or
              (LTarget='go32v2') or
              (LTarget='msdos') or
              (LTarget='os2');
end;
{$endif not LIMIT83FS}

procedure SetTargetCanCompileLibraries;
var
  LTarget : string;
begin
  { Call this first to ensure that CompilerTarget is not empty }
  GetCompilerTarget;
  LTarget := CompilerTarget;
  { Feel free to add other targets here }
  if (LTarget='go32v2') then
    TargetCanCompileLibraries:=false;
end;


function OutputFileName(Const s,ext:String):String;
begin
{$ifndef macos}
  OutputFileName:=OutputDir+'/'+ForceExtension(s,ext);
{$else macos}
  OutputFileName:=ConcatMacPath(OutputDir,ForceExtension(s,ext));
{$endif macos}
end;


function TestOutputFileName(Const pref,base,ext:String):String;
begin
{$ifndef macos}
  TestOutputFileName:=TestOutputDir+'/'+ForceExtension(pref+SplitFileName(base),ext);
{$else macos}
  TestOutputFileName:=ConcatMacPath(TestOutputDir,ForceExtension(pref+SplitFileName(base),ext));
{$endif macos}
end;


function TestLogFileName(Const pref,base,ext:String):String;
var
  LogDir: String;
begin
  LogDir:=TestOutputDir;
{$ifndef macos}
  if UniqueSuffix<>'' then
    LogDir:=LogDir+'/..';
  TestLogFileName:=LogDir+'/'+ForceExtension(pref+SplitFileName(base),ext);
{$else macos}
  if UniqueSuffix<>'' then
    LogDir:=LogDir+'::';
  TestLogFileName:=ConcatMacPath(LogDir,ForceExtension(pref+SplitFileName(base),ext));
{$endif macos}
end;


function ExitWithInternalError(const OutName:string):boolean;
var
  t : text;
  s : string;
begin
  ExitWithInternalError:=false;
  { open logfile }
  assign(t,Outname);
  {$I-}
   reset(t);
  {$I+}
  if ioresult<>0 then
   exit;
  while not eof(t) do
   begin
     readln(t,s);
     if pos('Fatal: Internal error ',s)>0 then
      begin
        ExitWithInternalError:=true;
        break;
      end;
   end;
  close(t);
end;


{ Takes each option from AddOptions list
  considered as a space separated list
  and adds the option to args
  unless option contains a percent sign,
  in that case, the option after % will be added
  to args only if CompilerTarget is listed in
  the string part before %.
  NOTE: this function does not check for
  quoted options...
  The list before % must of course contain no spaces. }

procedure AppendOptions(AddOptions : string;var args : string);
var
  endopt,percentpos : longint;
  opttarget, currentopt : string;
begin
  Verbose(V_Debug,'AppendOptions called with AddOptions="'+AddOptions+'"');
  AddOptions:=trimspace(AddOptions);
  repeat
    endopt:=pos(' ',AddOptions);
    if endopt=0 then
      endopt:=length(AddOptions);
    currentopt:=trimspace(copy(AddOptions,1,endopt));
    AddOptions:=trimspace(copy(Addoptions,endopt+1,length(AddOptions)));
    if currentopt<>'' then
      begin
        percentpos:=pos('%',currentopt);
        if (percentpos=0) then
          begin
            Verbose(V_Debug,'Adding option="'+currentopt+'"');
            args:=args+' '+currentopt;
          end
        else
          begin
            opttarget:=lowercase(copy(currentopt,1,percentpos-1));
            if IsInList(CompilerTarget, opttarget) then
              begin
                Verbose(V_Debug,'Adding target specific option="'+currentopt+'" for '+opttarget);
                args:=args+' '+copy(currentopt,percentpos+1,length(currentopt))
              end
            else
              Verbose(V_Debug,'No matching target "'+currentopt+'"');
          end;
      end;
  until AddOptions='';
end;

{ This function removes some incompatible
  options from TEST_OPT before adding them to
  the list of options passed to the compiler.
  %DELOPT=XYZ  will remove XYZ exactly
  %DELOPT=XYZ* will remove all options starting with XYZ.
  NOTE: This fuinction does not handle quoted options. }
function DelOptions(Pattern, opts : string) : string;
var
  currentopt : string;
  optpos, endopt, startpos, endpos : longint;
  iswild : boolean;
begin
  opts:=trimspace(opts);
  pattern:=trimspace(pattern);
  repeat
    endpos:=pos(' ',pattern);
    if endpos=0 then
      endpos:=length(pattern);
    currentopt:=trimspace(copy(pattern,1,endpos));
    pattern:=trimspace(copy(pattern,endpos+1,length(pattern)));
    if currentopt<>'' then
      begin
        if currentopt[length(currentopt)]='*' then
          begin
            iswild:=true;
            system.delete(currentopt,length(currentopt),1);
          end
        else
          iswild:=false;
        startpos:=1;
        repeat
          optpos:=pos(currentopt,copy(opts,startpos,length(opts)));
          if optpos>0 then
            begin
              { move to index in full opts string }
              optpos:=optpos+startpos-1;
              { compute position of end of opt }
              endopt:=optpos+length(currentopt);
              { use that end as start position for next round }
              startpos:=endopt;
              if iswild then
                begin
                  while (opts[endopt]<>' ') and
                    (endopt<length(opts)) do
                    begin
                      inc(endopt);
                      inc(startpos);
                    end;
                  Verbose(V_Debug,'Pattern match found "'+currentopt+'*" in "'+opts+'"');
                  system.delete(opts,optpos,endopt-optpos+1);
                  Verbose(V_Debug,'After opts="'+opts+'"');
                end
              else
                begin
                  if (endopt>length(opts)) or (opts[endopt]=' ') then
                    begin
                      Verbose(V_Debug,'Exact match found "'+currentopt+'" in "'+opts+'"');
                      system.delete(opts,optpos,endopt-optpos+1);
                      Verbose(V_Debug,'After opts="'+opts+'"');
                    end
                  else
                    begin
                      Verbose(V_Debug,'No exact match "'+currentopt+'" in "'+opts+'"');
                    end;
                end;

            end;
        until optpos=0;
      end;
  until pattern='';
  DelOptions:=opts;
end;

function RunCompiler(const ExtraPara: string):boolean;
var
  args,LocalExtraArgs,
  wpoargs : string;
  passnr,
  passes  : longint;
  execres : boolean;
  EndTicks,
  StartTicks : int64;
begin
  RunCompiler:=false;
  args:='-n -T'+CompilerTarget+' -Fu'+RTLUnitsDir;
  if ExtraPara<>'' then
    args:=args+' '+ExtraPara;
  { the helper object files have been copied to the common directory }
  if UniqueSuffix<>'' then
    args:=args+' -Fo'+TestOutputDir+'/..';
  args:=args+' -FE'+TestOutputDir;
  if TargetIsMacOS then
    args:=args+' -WT ';  {tests should be compiled as MPWTool}
  if Config.DelOptions<>'' then
   LocalExtraArgs:=DelOptions(Config.DelOptions,ExtraCompilerOpts)
  else
    LocalExtraArgs:=ExtraCompilerOpts;

  if LocalExtraArgs<>'' then
   args:=args+' '+LocalExtraArgs;
  if TargetIsUnix then
    begin
      { Add runtime library path to current dir to find .so files }
      if Config.NeedLibrary then
        begin
          if (CompilerTarget='darwin') or
	     (CompilerTarget='aix') then
            args:=args+' -Fl'+TestOutputDir
	  else
          { do not use single quote for -k as they are mishandled on
            Windows Shells }
            args:=args+' -Fl'+TestOutputDir+' -k-rpath -k.'
        end;
    end;
  if Config.NeedOptions<>'' then
   AppendOptions(Config.NeedOptions,args);
  wpoargs:='';
  if (Config.WpoPasses=0) or
     (Config.WpoParas='') then
    passes:=1
  else
    passes:=config.wpopasses+1;
  args:=args+' '+PPFile[current];

  for passnr:=1 to passes do
    begin
      if (passes>1) then
        begin
          wpoargs:=' -OW'+config.wpoparas+' -FW'+TestOutputFileName('',PPFile[current],'wp'+tostr(passnr));
          if (passnr>1) then
            wpoargs:=wpoargs+' -Ow'+config.wpoparas+' -Fw'+TestOutputFileName('',PPFile[current],'wp'+tostr(passnr-1));
        end;
      Verbose(V_Debug,'Executing '+compilerbin+' '+args+wpoargs);
      { also get the output from as and ld that writes to stderr sometimes }
      StartTicks:=GetMicroSTicks;
    {$ifndef macos}
      execres:=ExecuteRedir(CompilerBin,args+wpoargs,'',CompilerLogFile,'stdout');
    {$else macos}
      {Due to that Toolserver is not reentrant, we have to asm and link via script.}
      execres:=ExecuteRedir(CompilerBin,'-s '+args+wpoargs,'',CompilerLogFile,'stdout');
      if execres then
        execres:=ExecuteRedir(TestOutputDir + ':ppas','','',CompilerLogFile,'stdout');
    {$endif macos}
      EndTicks:=GetMicroSTicks;
      Verbose(V_Debug,'Exitcode '+ToStr(ExecuteResult));
      if BenchmarkInfo then
        begin
          Verbose(V_Normal,'Compilation took '+ToStr(EndTicks-StartTicks)+' us');
        end;

      { Error during execution? }
      if (not execres) and (ExecuteResult=0) then
        begin
          AddLog(FailLogFile,TestName);
          AddLog(ResLogFile,failed_to_compile+PPFileInfo[current]);
          AddLog(LongLogFile,line_separation);
          AddLog(LongLogFile,failed_to_compile+PPFileInfo[current]);
          if CopyFile(CompilerLogFile,LongLogFile,true)=0 then
            AddLog(LongLogFile,'IOStatus'+ToStr(IOStatus));
          { avoid to try again }
          AddLog(ExeLogFile,failed_to_compile+PPFileInfo[current]);
          Verbose(V_Warning,'IOStatus: '+ToStr(IOStatus));
          exit;
        end;

      { Check for internal error }
      if ExitWithInternalError(CompilerLogFile) then
       begin
         AddLog(FailLogFile,TestName);
         if Config.Note<>'' then
          AddLog(FailLogFile,Config.Note);
         AddLog(ResLogFile,failed_to_compile+PPFileInfo[current]+' internalerror generated');
         AddLog(LongLogFile,line_separation);
         AddLog(LongLogFile,failed_to_compile+PPFileInfo[current]);
         if Config.Note<>'' then
          AddLog(LongLogFile,Config.Note);
         if CopyFile(CompilerLogFile,LongLogFile,true)=0 then
           AddLog(LongLogFile,'Internal error in compiler');
         { avoid to try again }
         AddLog(ExeLogFile,failed_to_compile+PPFileInfo[current]);
         Verbose(V_Warning,'Internal error in compiler');
         exit;
       end;
    end;

  { Should the compile fail ? }
  if Config.ShouldFail then
   begin
     if ExecuteResult<>0 then
      begin
        AddLog(ResLogFile,success_compilation_failed+PPFileInfo[current]);
        { avoid to try again }
        AddLog(ExeLogFile,success_compilation_failed+PPFileInfo[current]);
        RunCompiler:=true;
      end
     else
      begin
        AddLog(FailLogFile,TestName);
        if Config.Note<>'' then
          AddLog(FailLogFile,Config.Note);
        AddLog(ResLogFile,failed_compilation_successful+PPFileInfo[current]);
        AddLog(LongLogFile,line_separation);
        AddLog(LongLogFile,failed_compilation_successful+PPFileInfo[current]);
        { avoid to try again }
        AddLog(ExeLogFile,failed_compilation_successful+PPFileInfo[current]);
        if Config.Note<>'' then
          AddLog(LongLogFile,Config.Note);
        CopyFile(CompilerLogFile,LongLogFile,true);
      end;
   end
  else
   begin
     if (ExecuteResult<>0) and
        (((Config.KnownCompileNote<>'') and (Config.KnownCompileError=0)) or
         ((Config.KnownCompileError<>0) and (ExecuteResult=Config.KnownCompileError))) then
      begin
        AddLog(FailLogFile,TestName+known_problem+Config.KnownCompileNote);
        AddLog(ResLogFile,failed_to_compile+PPFileInfo[current]+known_problem+Config.KnownCompileNote);
        AddLog(LongLogFile,line_separation);
        AddLog(LongLogFile,known_problem+Config.KnownCompileNote);
        AddLog(LongLogFile,failed_to_compile+PPFileInfo[current]+' ('+ToStr(ExecuteResult)+')');
        if Copyfile(CompilerLogFile,LongLogFile,true)=0 then
          AddLog(LongLogFile,known_problem+'exitcode: '+ToStr(ExecuteResult));
        Verbose(V_Warning,known_problem+'exitcode: '+ToStr(ExecuteResult));
      end
     else if ExecuteResult<>0 then
      begin
        AddLog(FailLogFile,TestName);
        if Config.Note<>'' then
          AddLog(FailLogFile,Config.Note);
        AddLog(ResLogFile,failed_to_compile+PPFileInfo[current]);
        AddLog(LongLogFile,line_separation);
        AddLog(LongLogFile,failed_to_compile+PPFileInfo[current]);
        if Config.Note<>'' then
          AddLog(LongLogFile,Config.Note);
        if CopyFile(CompilerLogFile,LongLogFile,true)=0 then
          AddLog(LongLogFile,'Exitcode: '+ToStr(ExecuteResult)+' (expected 0)');
        { avoid to try again }
        AddLog(ExeLogFile,failed_to_compile+PPFileInfo[current]);
        Verbose(V_Warning,'Exitcode: '+ToStr(ExecuteResult)+' (expected 0)');
      end
     else
      begin
        AddLog(ResLogFile,successfully_compiled+PPFileInfo[current]);
        RunCompiler:=true;
      end;
   end;
end;


function CheckTestExitCode(const OutName:string):boolean;
var
  t : text;
  s : string;
  i,code : integer;
begin
  CheckTestExitCode:=false;
  { open logfile }
  assign(t,Outname);
  {$I-}
   reset(t);
  {$I+}
  if ioresult<>0 then
   exit;
  while not eof(t) do
   begin
     readln(t,s);
     i:=pos('TestExitCode: ',s);
     if i>0 then
      begin
        delete(s,1,i+14-1);
        val(s,ExecuteResult,code);
        if code=0 then
          CheckTestExitCode:=true;
        break;
      end;
   end;
  close(t);
end;

function LibraryExists(const PPFile : string; out FileName : string) : boolean;
begin
   { Check if a dynamic library XXX was created }
   { Windows XXX.dll style }
  FileName:=TestOutputFilename('',PPFile,'dll');
  if FileExists(FileName) then
    begin
      LibraryExists:=true;
      exit;
    end;
   { Linux libXXX.so style }
  FileName:=TestOutputFilename('lib',PPFile,'so');
  if FileExists(FileName) then
    begin
      LibraryExists:=true;
      exit;
    end;
   { Darwin libXXX.dylib style }
  FileName:=TestOutputFilename('lib',PPFile,'dylib');
  if FileExists(FileName) then
    begin
      LibraryExists:=true;
      exit;
    end;
   { MacOS LibXXX style }
  FileName:=TestOutputFilename('Lib',PPFile,'');
  if FileExists(FileName) then
    begin
      LibraryExists:=true;
      exit;
    end;
   { Netware wlic XXX.nlm style }
  FileName:=TestOutputFilename('',PPFile,'nlm');
  if FileExists(FileName) then
    begin
      LibraryExists:=true;
      exit;
    end;
   { Amiga  XXX.library style }
  FileName:=TestOutputFilename('',PPFile,'library');
  if FileExists(FileName) then
    begin
      LibraryExists:=true;
      exit;
    end;
  LibraryExists:=false;
end;

function ExecuteRemote(prog,args:string;out StartTicks,EndTicks : int64):boolean;
const
  MaxTrials = 5;
var
  Trials : longint;
  Res : boolean;
begin
  if SplitFileExt(prog)='' then
    prog:=prog+SrcExeExt;
  Verbose(V_Debug,'RemoteExecuting '+Prog+' '+args);
  StartTicks:=GetMicroSTicks;
  Res:=false;
  Trials:=0;
  While (Trials<MaxTrials) and not Res do
    begin
      inc(Trials);
      Res:=ExecuteRedir(prog,args,'',EXELogFile,'stdout');
      if not Res then
        Verbose(V_Debug,'Call to '+prog+' failed: '+
          'IOStatus='+ToStr(IOStatus)+
          ' RedirErrorOut='+ToStr(RedirErrorOut)+
          ' RedirErrorIn='+ToStr(RedirErrorIn)+
          ' RedirErrorError='+ToStr(RedirErrorError)+
          ' ExecuteResult='+ToStr(ExecuteResult));
    end;

  if Trials>1 then
    Verbose(V_Debug,'Done in '+tostr(trials)+' trials');
  EndTicks:=GetMicroSTicks;
  ExecuteRemote:=res;
end;

function ExecuteEmulated(const prog,args,FullExeLogFile:string;out StartTicks,EndTicks : int64):boolean;
begin
  Verbose(V_Debug,'EmulatorExecuting '+Prog+' '+args);
  StartTicks:=GetMicroSTicks;
  ExecuteEmulated:=ExecuteRedir(prog,args,'',FullExeLogFile,'stdout');
  EndTicks:=GetMicroSTicks;
end;


function MaybeCopyFiles(const FileToCopy : string) : boolean;
var
  TestRemoteExe,
  pref     : string;
  LocalFile, RemoteFile, s: string;
  LocalPath: string;
  i       : integer;
  execres : boolean;
  EndTicks,
  StartTicks : int64;
  FileList   : TStringList;

  function BuildFileList: TStringList;
    var
      s      : string;
      index  : longint;
    begin
      s:=Config.Files;
      if length(s) = 0 then
        begin
          Result:=nil;
          exit;
        end;
      Result:=TStringList.Create;
      repeat
        index:=pos(' ',s);
        if index=0 then
          LocalFile:=s
        else
          LocalFile:=copy(s,1,index-1);
        Result.Add(LocalFile);
        if index=0 then
          break;
        s:=copy(s,index+1,length(s)-index);
      until false;
    end;

begin
  if RemoteAddr='' then
    begin
      If UniqueSuffix<>'' then
        begin
          FileList:=BuildFileList;
          if assigned(FileList) then
            begin
              LocalPath:=SplitPath(PPFile[current]);
              if Length(LocalPath) > 0 then
                LocalPath:=LocalPath+'/';
              for i:=0 to FileList.count-1 do
                begin
                  LocalFile:=FileList[i];
                  CopyFile(LocalPath+LocalFile,TestOutputDir+'/'+LocalFile,false);
                end;
              FileList.Free;
            end;
        end;
      exit(true);
    end;
  execres:=true;
  { Check if library should be deleted. Do not copy to remote target in such case. }
  if (deAfter in DelExecutable) and (Config.DelFiles <> '') then
    if SplitFileName(FileToCopy) = DllPrefix + Trim(Config.DelFiles) + DllExt then
      exit;
  { We don't want to create subdirs, remove paths from the test }
  TestRemoteExe:=RemotePath+'/'+SplitFileName(FileToCopy);
  if deBefore in DelExecutable then
    begin
      s:=RemoteRshParas+' rm ';
      if rshprog <> 'adb' then
        s:=s+'-f ';
      ExecuteRemote(rshprog,s+TestRemoteExe,
                    StartTicks,EndTicks);
    end;
  execres:=ExecuteRemote(rcpprog,RemotePara+' '+FileToCopy+' '+
                         RemotePathPrefix+TestRemoteExe,StartTicks,EndTicks);
  if not execres then
  begin
    Verbose(V_normal, 'Could not copy executable '+FileToCopy);
    exit(execres);
  end;
  FileList:=BuildFileList;
  if assigned(FileList) then
  begin
    LocalPath:=SplitPath(PPFile[current]);
    if Length(LocalPath) > 0 then
      LocalPath:=LocalPath+'/';
    for i:=0 to FileList.count-1 do
      begin
        LocalFile:=FileList[i];
        RemoteFile:=RemotePath+'/'+SplitFileName(LocalFile);
        LocalFile:=LocalPath+LocalFile;
        if DoVerbose and (rcpprog='pscp') then
          pref:='-v '
        else
          pref:='';
        execres:=ExecuteRemote(rcpprog,pref+RemotePara+' '+LocalFile+' '+
                               RemotePathPrefix+RemoteFile,StartTicks,EndTicks);
        if not execres then
        begin
          Verbose(V_normal, 'Could not copy required file '+LocalFile);
          FileList.Free;
          exit(false);
        end;
      end;
  end;
  FileList.Free;
  MaybeCopyFiles:=execres;
end;

function RunExecutable:boolean;
const
{$ifdef unix}
  CurrDir = './';
{$else}
  CurrDir = '';
{$endif}
var
  OldDir, s, ss,
  execcmd,
  FullExeLogFile,
  TestRemoteExe,
  TestExe  : string;
  execres  : boolean;
  EndTicks,
  StartTicks : int64;
begin
  RunExecutable:=false;
  execres:=true;

  TestExe:=TestOutputFilename('',PPFile[current],ExeExt);

  execres:=MaybeCopyFiles(TestExe);
  if EmulatorName<>'' then
    begin
      { Get full name out log file, because we change the directory during
        execution }
      FullExeLogFile:=FExpand(EXELogFile);
      {$I-}
       GetDir(0,OldDir);
       ChDir(TestOutputDir);
      {$I+}
      ioresult;
      s:=CurrDir+SplitFileName(TestExe);
      execres:=ExecuteEmulated(EmulatorName,s,FullExeLogFile,StartTicks,EndTicks);
      {$I-}
       ChDir(OldDir);
      {$I+}
    end
  else if RemoteAddr<>'' then
    begin
      TestRemoteExe:=RemotePath+'/'+SplitFileName(TestExe);
      { rsh doesn't pass the exitcode, use a second command to print the exitcode
        on the remoteshell to stdout }
      if DoVerbose and (rshprog='plink') then
        execcmd:='-v '+RemoteRshParas
      else
        execcmd:=RemoteRshParas;
      execcmd:=execcmd+' '+rquote+
         'chmod 755 '+TestRemoteExe+
          ' && cd '+RemotePath+' && { ';
      { Using -rpath . at compile time does not seem
        to work for programs copied over to remote machine,
        at least not for FreeBSD.
        Does this work for all shells? }
      if Config.NeedLibrary then
        begin
          if RemoteShellNeedsExport then
            if CompilerTarget='darwin' then
              execcmd:=execcmd+' DYLD_LIBRARY_PATH=.; export DYLD_LIBRARY_PATH;'
            else
              execcmd:=execcmd+' LD_LIBRARY_PATH=.; export LD_LIBRARY_PATH;'
          else
            if CompilerTarget='darwin' then
              execcmd:=execcmd+' setenv DYLD_LIBRARY_PATH=.; '
            else
              execcmd:=execcmd+' setenv LD_LIBRARY_PATH=.; '
        end;


      if UseTimeout then
      begin
        if Config.Timeout=0 then
          Config.Timeout:=DefaultTimeout;
        str(Config.Timeout,s);
        if (RemoteShellBase='bash') then
          execcmd:=execcmd+'ulimit -t '+s+'; '
        else
          execcmd:=execcmd+'timeout -9 '+s;
      end;
      { as we moved to RemotePath, if path is not absolute
        we need to use ./execfilename only }
      if not isabsolute(TestRemoteExe) then
        execcmd:=execcmd+' ./'+SplitFileName(TestRemoteExe)
      else
        execcmd:=execcmd+' '+TestRemoteExe;
      execcmd:=execcmd+' ; echo TestExitCode: $?';
      if (deAfter in DelExecutable) and
         not Config.NeededAfter then
        begin
          execcmd:=execcmd+' ; rm ';
          if rshprog <> 'adb' then
            execcmd:=execcmd+'-f ';
          execcmd:=execcmd+SplitFileName(TestRemoteExe);
        end;
      execcmd:=execcmd+'; }'+rquote;
      execres:=ExecuteRemote(rshprog,execcmd,StartTicks,EndTicks);
      { Check for TestExitCode error in output, sets ExecuteResult }
      if not CheckTestExitCode(EXELogFile) then
        Verbose(V_Debug,'Failed to check exit code for '+execcmd);
      if (deAfter in DelExecutable) and ( (Config.DelFiles <> '') or (Config.Files <> '')) then
        begin
          ss:=Trim(Config.DelFiles + ' ' + Config.Files);
          execcmd:=RemoteRshParas+' ' + rquote + 'cd ' + RemotePath + ' && { ';
          while ss <> '' do
            begin
              s:=Trim(GetToken(ss, [' ',',',';']));
              if s = '' then
                break;
              if ExtractFileExt(s) = '' then
                // If file has no extension, treat it as exe or shared lib
                execcmd:=execcmd + 'rm ' + s + ExeExt + '; rm ' + DllPrefix + s + DllExt
              else
                execcmd:=execcmd + 'rm ' + s;
              execcmd:=execcmd + '; ';
            end;
          ExecuteRemote(rshprog,execcmd+'}'+rquote,StartTicks,EndTicks);
        end;
    end
  else
    begin
      { Get full name out log file, because we change the directory during
        execution }
      FullExeLogFile:=FExpand(EXELogFile);
      Verbose(V_Debug,'Executing '+TestExe);
      {$I-}
       GetDir(0,OldDir);
       ChDir(TestOutputDir);
      {$I+}
      ioresult;
      { don't redirect interactive and graph programs }
      StartTicks:=GetMicroSTicks;
      if Config.IsInteractive or Config.UsesGraph then
        execres:=ExecuteRedir(CurrDir+SplitFileName(TestExe),'','','','')
      else
        execres:=ExecuteRedir(CurrDir+SplitFileName(TestExe),'','',FullExeLogFile,'stdout');
      EndTicks:=GetMicroSTicks;
      {$I-}
       ChDir(OldDir);
      {$I+}
      ioresult;
    end;

  { Error during execution? }
  Verbose(V_Debug,'Exitcode '+ToStr(ExecuteResult));
  if BenchmarkInfo then
    begin
      Verbose(V_Normal,'Execution took '+ToStr(EndTicks-StartTicks)+' us');
    end;
  if (not execres) and (ExecuteResult=0) then
    begin
      AddLog(FailLogFile,TestName);
      AddLog(ResLogFile,failed_to_run+PPFileInfo[current]);
      AddLog(LongLogFile,line_separation);
      AddLog(LongLogFile,failed_to_run+PPFileInfo[current]);
      if CopyFile(EXELogFile,LongLogFile,true)=0 then
        AddLog(LongLogFile,'IOStatus: '+ToStr(IOStatus));
      { avoid to try again }
      AddLog(ExeLogFile,failed_to_run+PPFileInfo[current]);
      Verbose(V_Warning,'IOStatus: '+ToStr(IOStatus));
      exit;
    end;

  if ExecuteResult<>Config.ResultCode then
   begin
     if (ExecuteResult<>0) and
        (ExecuteResult=Config.KnownRunError) then
       begin
         AddLog(FailLogFile,TestName+known_problem+Config.KnownRunNote);
         AddLog(ResLogFile,failed_to_run+PPFileInfo[current]+known_problem+Config.KnownRunNote);
         AddLog(LongLogFile,line_separation);
         AddLog(LongLogFile,known_problem+Config.KnownRunNote);
         AddLog(LongLogFile,failed_to_run+PPFileInfo[current]+' ('+ToStr(ExecuteResult)+')');
         if Copyfile(EXELogFile,LongLogFile,true)=0 then
           begin
             AddLog(LongLogFile,known_problem+'exitcode: '+ToStr(ExecuteResult)+' (expected '+ToStr(Config.ResultCode)+')');
             AddLog(ExeLogFile,known_problem+'exitcode: '+ToStr(ExecuteResult)+' (expected '+ToStr(Config.ResultCode)+')');
           end;
         Verbose(V_Warning,known_problem+'exitcode: '+ToStr(ExecuteResult)+' (expected '+ToStr(Config.ResultCode)+')');
       end
     else
       begin
         AddLog(FailLogFile,TestName);
         AddLog(ResLogFile,failed_to_run+PPFileInfo[current]);
         AddLog(LongLogFile,line_separation);
         AddLog(LongLogFile,failed_to_run+PPFileInfo[current]+' ('+ToStr(ExecuteResult)+')');
         if Copyfile(EXELogFile,LongLogFile,true)=0 then
           begin
             AddLog(LongLogFile,'Exitcode: '+ToStr(ExecuteResult)+' (expected '+ToStr(Config.ResultCode)+')');
             AddLog(ExeLogFile,'Exitcode: '+ToStr(ExecuteResult)+' (expected '+ToStr(Config.ResultCode)+')');
           end;
         Verbose(V_Warning,'Exitcode: '+ToStr(ExecuteResult)+' (expected '+ToStr(Config.ResultCode)+')');
       end
   end
  else
   begin
     AddLog(ResLogFile,successfully_run+PPFileInfo[current]);
     RunExecutable:=true;
   end;

  if (deAfter in DelExecutable) and not Config.NeededAfter then
    begin
      Verbose(V_Debug,'Deleting executable '+TestExe);
      RemoveFile(TestExe);
      RemoveFile(ForceExtension(TestExe,ObjExt));
      RemoveFile(ForceExtension(TestExe,PPUExt));
    end;
end;


{ Try to collect information concerning the remote configuration
  Currently only records RemoteShell name and sets
  RemoteShellNeedsExport boolean variable }
procedure SetRemoteConfiguration;
var
  f : text;
  StartTicks,EndTicks : int64;
begin
  if RemoteAddr='' then
    exit;
  if rshprog = 'adb' then
    begin
      RemoteShellNeedsExport:=true;
      exit;
    end;
  ExeLogFile:='__remote.tmp';
  ExecuteRemote(rshprog,RemoteRshParas+
                ' "echo SHELL=${SHELL}"',StartTicks,EndTicks);
  Assign(f,ExeLogFile);
  Reset(f);
  While not eof(f) do
    begin
      Readln(f,RemoteShellBase);
      if pos('SHELL=',RemoteShellBase)>0 then
        begin
          RemoteShell:=TrimSpace(Copy(RemoteShellBase,pos('SHELL=',RemoteShellBase)+6,
                                      length(RemoteShellBase)));
          Verbose(V_Debug,'Remote shell is "'+RemoteShell+'"');
          RemoteShellBase:=SplitFileBase(RemoteShell);
          if (RemoteShellBase='bash') or (RemoteShellBase='sh') then
            RemoteShellNeedsExport:=true;
        end;
    end;
  Close(f);
end;

procedure getargs;

  procedure helpscreen;
  begin
    writeln('dotest [Options] <File>');
    writeln;
    writeln('Options can be:');
    writeln('  !ENV_NAME     parse environment variable ENV_NAME for options');
    writeln('  -A            include ALL tests');
    writeln('  -ADB          use ADB to run tests');
    writeln('  -B            delete executable before remote upload');
    writeln('  -C<compiler>  set compiler to use');
    writeln('  -D            display execution time');
    writeln('  -E            execute test also');
    writeln('  -G            include graph tests');
    writeln('  -I            include interactive tests');
    writeln('  -K            include known bug tests');
    writeln('  -L<ext>       set extension of temporary files (prevent conflicts with parallel invocations)');
    writeln('  -M<emulator>  run the tests using the given emulator');
    writeln('  -O            use timeout wrapper for (remote) execution');
    writeln('  -P<path>      path to the tests tree on the remote machine');
    writeln('  -R<remote>    run the tests remotely with the given rsh/ssh address');
    writeln('  -S            use ssh instead of rsh');
    writeln('  -T[cpu-]<os>  run tests for target cpu and os');
    writeln('  -U<remotepara>');
    writeln('                pass additional parameter to remote program. Multiple -U can be used');
    writeln('  -V            be verbose');
    writeln('  -W            use putty compatible file names when testing (plink and pscp)');
    writeln('  -X            don''t use COMSPEC');
    writeln('  -Y<opts>      extra options passed to the compiler. Several -Y<opt> can be given.');
    writeln('  -Z            remove temporary files (executable,ppu,o)');
    halt(1);
  end;

  procedure interpret_option (para : string);
  var
    ch : char;
    j : longint;
  begin
   Verbose(V_Debug,'Interpreting  option"'+para+'"');
    ch:=Upcase(para[2]);
    delete(para,1,2);
    case ch of
     'A' :
       if UpperCase(para) = 'DB' then
         begin
           rshprog:='adb';
           rcpprog:='adb';
           rquote:='"';
           if RemoteAddr = '' then
             RemoteAddr:='1'; // fake remote addr (default device will be used)
         end
       else
         begin
           DoGraph:=true;
           DoInteractive:=true;
           DoKnown:=true;
           DoAll:=true;
         end;

     'B' : Include(DelExecutable,deBefore);

     'C' : CompilerBin:=Para;

     'D' : BenchMarkInfo:=true;

     'E' : DoExecute:=true;

     'G' : begin
             DoGraph:=true;
             if para='-' then
               DoUsual:=false;
           end;

     'I' : begin
             DoInteractive:=true;
             if para='-' then
               DoUsual:=false;
           end;

     'K' : begin
             DoKnown:=true;
             if para='-' then
               DoUsual:=false;
           end;

     'L' : begin
             UniqueSuffix:=Para;
           end;

     'M' : EmulatorName:=Para;

     'O' : UseTimeout:=true;

     'P' : RemotePath:=Para;

     'R' : RemoteAddr:=Para;

     'S' :
       begin
         rshprog:='ssh';
         rcpprog:='scp';
       end;

     'T' :
       begin
         j:=Pos('-',Para);
         if j>0 then
           begin
             CompilerCPU:=Copy(Para,1,j-1);
             CompilerTarget:=Copy(Para,j+1,length(para));
           end
         else
           CompilerTarget:=Para
       end;

     'U' :
       RemotePara:=RemotePara+' '+Para;

     'V' : DoVerbose:=true;

     'W' :
       begin
         rshprog:='plink';
         rcpprog:='pscp';
         rquote:='"';
       end;

     'X' : UseComSpec:=false;

     'Y' : ExtraCompilerOpts:= ExtraCompilerOpts +' '+ Para;

     'Z' : Include(DelExecutable,deAfter);
    end;
 end;

 procedure interpret_env(arg : string);
 var
   para : string;
   pspace : longint;
 begin
   Verbose(V_Debug,'Interpreting environment option"'+arg+'"');
   { Get rid of leading '!' }
   delete(arg,1,1);
   arg:=getenv(arg);
   Verbose(V_Debug,'Environment value is "'+arg+'"');
   while (length(arg)>0) do
     begin
       while (length(arg)>0) and (arg[1]=' ') do
         delete(arg,1,1);
       pspace:=pos(' ',arg);
       if pspace=0 then
         pspace:=length(arg)+1;
       para:=copy(arg,1,pspace-1);
       if (length(para)>0) and (para[1]='-') then
         interpret_option (para)
       else
         begin
           PPFile.Insert(current,ForceExtension(Para,'pp'));
           inc(current);
         end;
       delete(arg,1,pspace);
     end;
 end;

var
  param : string;
  i  : longint;

begin
  CompilerBin:='ppc386'+srcexeext;
  for i:=1 to paramcount do
   begin
     param:=Paramstr(i);
     if (param[1]='-') then
      interpret_option(param)
     else if (param[1]='!') then
       interpret_env(param)
     else
       begin
         PPFile.Insert(current,ForceExtension(Param,'pp'));
         inc(current);
       end;
   end;
  if current=0 then
    HelpScreen;
  { disable graph,interactive when running remote }
  if RemoteAddr<>'' then
    begin
      DoGraph:=false;
      DoInteractive:=false;
    end;
  { If we use PuTTY plink program with -load option,
    the IP address or name should not be added to
    the command line }
  if (rshprog='plink') and (pos('-load',RemotePara)>0) then
    RemoteRshParas:=RemotePara
  else
    if rshprog='adb' then
      begin
        if RemoteAddr <> '1' then
          RemotePara:=Trim('-s ' + RemoteAddr + ' ' + RemotePara);
        RemoteRshParas:=Trim(RemotePara + ' shell');
      end
    else
      RemoteRshParas:=RemotePara+' '+RemoteAddr;
  if rcpprog = 'adb' then
    begin
      RemotePathPrefix:='';
      RemotePara:=Trim(RemotePara + ' push');
    end
  else
    RemotePathPrefix:=RemoteAddr + ':';
end;


procedure RunTest;
var
  PPDir,LibraryName,LogSuffix : string;
  Res : boolean;
begin
  Res:=GetConfig(PPFile[current],Config);

  if Res then
    begin
      Res:=GetCompilerCPU;
      Res:=GetCompilerTarget;
{$ifndef MACOS}
      RTLUnitsDir:='tstunits/'+CompilerFullTarget;
{$else MACOS}
      RTLUnitsDir:=':tstunits:'+CompilerFullTarget;
{$endif MACOS}
      if not PathExists(RTLUnitsDir) then
        Verbose(V_Abort,'Unit path "'+RTLUnitsDir+'" does not exists');
{$ifndef MACOS}
      OutputDir:='output/'+CompilerFullTarget;
{$else MACOS}
      OutputDir:=':output:'+CompilerFullTarget;
{$endif MACOS}
      if not PathExists(OutputDir) then
        Verbose(V_Abort,'Output path "'+OutputDir+'" does not exists');
      { Make subdir in output if needed }
      PPDir:=SplitPath(PPFile[current]);
      if PPDir[length(PPDir)] in ['/','\'{$ifdef MACOS},':'{$endif MACOS}] then
        Delete(PPDir,length(PPDir),1);
      if PPDir<>'' then
        begin
{$ifndef MACOS}
          TestOutputDir:=OutputDir+'/'+PPDir;
          if UniqueSuffix<>'' then
            TestOutputDir:=TestOutputDir+'/'+UniqueSuffix;
{$else MACOS}
          TestOutputDir:=OutputDir+PPDir;
          if UniqueSuffix<>'' then
            TestOutputDir:=TestOutputDir+':'+UniqueSuffix;
{$endif MACOS}
          mkdirtree(TestOutputDir);
        end
      else
        TestOutputDir:=OutputDir;
      if UniqueSuffix<>'' then
        LogSuffix:=UniqueSuffix
      else
        LogSuffix:=SplitBasePath(PPDir)+'log';
      ResLogFile:=OutputFileName('log',LogSuffix);
      LongLogFile:=OutputFileName('longlog',LogSuffix);
      FailLogFile:=OutputFileName('faillist',LogSuffix);
      ForceLog(ResLogFile);
      ForceLog(LongLogFile);
      ForceLog(FailLogFile);
      { Per test logfiles }
      CompilerLogFile:=TestLogFileName('',SplitFileName(PPFile[current]),'log');
      ExeLogFile:=TestLogFileName('',SplitFileName(PPFile[current]),'elg');
      Verbose(V_Debug,'Using Compiler logfile: '+CompilerLogFile);
      Verbose(V_Debug,'Using Execution logfile: '+ExeLogFile);
    end;

  if Res then
   begin
     if Config.UsesGraph and (not DoGraph) then
      begin
        AddLog(ResLogFile,skipping_graph_test+PPFileInfo[current]);
        { avoid a second attempt by writing to elg file }
        AddLog(EXELogFile,skipping_graph_test+PPFileInfo[current]);
        Verbose(V_Warning,skipping_graph_test);
        Res:=false;
      end;
   end;

  if Res then
   begin
     if Config.IsInteractive and (not DoInteractive) then
      begin
        { avoid a second attempt by writing to elg file }
        AddLog(EXELogFile,skipping_interactive_test+PPFileInfo[current]);
        AddLog(ResLogFile,skipping_interactive_test+PPFileInfo[current]);
        Verbose(V_Warning,skipping_interactive_test);
        Res:=false;
      end;
   end;

  if Res then
   begin
     if Config.IsKnownCompileError and (not DoKnown) then
      begin
        { avoid a second attempt by writing to elg file }
        AddLog(EXELogFile,skipping_known_bug+PPFileInfo[current]);
        AddLog(ResLogFile,skipping_known_bug+PPFileInfo[current]);
        Verbose(V_Warning,skipping_known_bug);
        Res:=false;
      end;
   end;

  if Res and not DoUsual then
    res:=(Config.IsInteractive and DoInteractive) or
         (Config.IsKnownRunError and DoKnown) or
         (Config.UsesGraph and DoGraph);

  if Res then
   begin
     if (Config.MinVersion<>'') and not DoAll then
      begin
        Verbose(V_Debug,'Required compiler version: '+Config.MinVersion);
        Res:=GetCompilerVersion;
        if CompilerVersion<Config.MinVersion then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_compiler_version_too_low+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_compiler_version_too_low+PPFileInfo[current]);
           Verbose(V_Warning,'Compiler version too low '+CompilerVersion+' < '+Config.MinVersion);
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     if (Config.MaxVersion<>'') and not DoAll then
      begin
        Verbose(V_Debug,'Highest compiler version: '+Config.MaxVersion);
        Res:=GetCompilerVersion;
        if CompilerVersion>Config.MaxVersion then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_compiler_version_too_high+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_compiler_version_too_high+PPFileInfo[current]);
           Verbose(V_Warning,'Compiler version too high '+CompilerVersion+' > '+Config.MaxVersion);
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     if Config.NeedCPU<>'' then
      begin
        Verbose(V_Debug,'Required compiler cpu: '+Config.NeedCPU);
        if not IsInList(CompilerCPU,Config.NeedCPU) then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_other_cpu+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_other_cpu+PPFileInfo[current]);
           Verbose(V_Warning,'Compiler cpu "'+CompilerCPU+'" is not in list "'+Config.NeedCPU+'"');
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     if Config.SkipCPU<>'' then
      begin
        Verbose(V_Debug,'Skip compiler cpu: '+Config.SkipCPU);
        if IsInList(CompilerCPU,Config.SkipCPU) then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_other_cpu+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_other_cpu+PPFileInfo[current]);
           Verbose(V_Warning,'Compiler cpu "'+CompilerCPU+'" is in list "'+Config.SkipCPU+'"');
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     if Config.SkipEmu<>'' then
      begin
        Verbose(V_Debug,'Skip emulator: '+emulatorname);
        if IsInList(emulatorname,Config.SkipEmu) then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_other_cpu+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_other_cpu+PPFileInfo[current]);
           Verbose(V_Warning,'Emulator "'+emulatorname+'" is in list "'+Config.SkipEmu+'"');
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     if Config.NeedTarget<>'' then
      begin
        Verbose(V_Debug,'Required compiler target: '+Config.NeedTarget);
        if not IsInList(CompilerTarget,Config.NeedTarget) then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_other_target+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_other_target+PPFileInfo[current]);
           Verbose(V_Warning,'Compiler target "'+CompilerTarget+'" is not in list "'+Config.NeedTarget+'"');
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     if Config.SkipTarget<>'' then
      begin
        Verbose(V_Debug,'Skip compiler target: '+Config.SkipTarget);
        if IsInList(CompilerTarget,Config.SkipTarget) then
         begin
           { avoid a second attempt by writing to elg file }
           AddLog(EXELogFile,skipping_other_target+PPFileInfo[current]);
           AddLog(ResLogFile,skipping_other_target+PPFileInfo[current]);
           Verbose(V_Warning,'Compiler target "'+CompilerTarget+'" is in list "'+Config.SkipTarget+'"');
           Res:=false;
         end;
      end;
   end;

  if Res then
   begin
     { Use known bug, to avoid adding a new entry for this PM 2011-06-24 }
     if Config.NeedLibrary and not TargetCanCompileLibraries then
      begin
        AddLog(EXELogFile,skipping_known_bug+PPFileInfo[current]);
        AddLog(ResLogFile,skipping_known_bug+PPFileInfo[current]);
        Verbose(V_Warning,'Compiler target "'+CompilerTarget+'" does not support library compilation');
        Res:=false;
      end;
   end;

  if Res then
   begin
     Res:=RunCompiler('');
     if Res and Config.NeedRecompile then
      Res:=RunCompiler(Config.RecompileOpt);
   end;

  if Res and (not Config.ShouldFail) then
   begin
     if (Config.NoRun) then
      begin
        { avoid a second attempt by writing to elg file }
        AddLog(EXELogFile,skipping_run_test+PPFileInfo[current]);
        AddLog(ResLogFile,skipping_run_test+PPFileInfo[current]);
        Verbose(V_Debug,skipping_run_test);
        if LibraryExists(PPFile[current],LibraryName) then
          MaybeCopyFiles(LibraryName);
      end
     else if Config.IsKnownRunError and (not DoKnown) then
      begin
        { avoid a second attempt by writing to elg file }
        AddLog(EXELogFile,skipping_known_bug+PPFileInfo[current]);
        AddLog(ResLogFile,skipping_known_bug+PPFileInfo[current]);
        Verbose(V_Warning,skipping_known_bug);
      end
     else
      begin
        if DoExecute then
         begin
           if FileExists(TestOutputFilename('',PPFile[current],'ppu')) or
              FileExists(TestOutputFilename('',PPFile[current],'ppo')) or
              FileExists(TestOutputFilename('',PPFile[current],'ppw')) then
             begin
               AddLog(ExeLogFile,skipping_run_unit+PPFileInfo[current]);
               AddLog(ResLogFile,skipping_run_unit+PPFileInfo[current]);
               Verbose(V_Debug,'Unit found, skipping run test')
             end
           else if LibraryExists(PPFile[current],LibraryName) then
             begin
               Verbose(V_Debug,'Library found, skipping run test');
               MaybeCopyFiles(LibraryName);
             end
           else
             Res:=RunExecutable;
         end;
      end;
   end;
end;


begin
  Current:=0;
  PPFile:=TStringList.Create;
  PPFile.Capacity:=10;
  PPFileInfo:=TStringList.Create;
  PPFileInfo.Capacity:=10;
  GetArgs;
  SetTargetDirectoriesStyle;
  SetTargetCanCompileLibraries;
  SetRemoteConfiguration;
{$ifdef LIMIT83fs}
  UseOSOnly:=true;
{$else not LIMIT83fs}
  SetUseOSOnly;
{$endif not LIMIT83fs}
  Verbose(V_Debug,'Found '+ToStr(PPFile.Count)+' tests to run');
  if current>0 then
    for current:=0 to PPFile.Count-1 do
      begin
        SetPPFileInfo;
        TestName:=Copy(PPFile[current],1,Pos('.pp',PPFile[current])-1);
        Verbose(V_Normal,'Running test '+TestName+', file '+PPFile[current]);
        RunTest;
      end;
  PPFile.Free;
  PPFileInfo.Free;
end.