PiDP-8/I SoftwareCheck-in [05bd569e5e]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:First steps to getting os8-run working with Python 3: this is all of the print() calls. (print() is a function in Python 3, not a keyword as in prior versions, so it requires parens around its arguments, always.) This is the start of a new branch because this won't be the only thing needed to get these programs working under Python 3. This is needed on my macOS box because Anaconda Distribution installs Python 3 as "python", which is arguably wrong, but hopefully we can get os8-run and its helper libraries into a state where they run on both versions so this won't matter any more. This checkin *also* accidentally includes a SIMH update, because I was in the middle of the SIMH update and got distracted by fixing the Python 2-isms and accidentally checked the SIMH changes in as well. The SIMH update should have been on trunk only. I'll fix that on this branch a bit down the line.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both |  os8-run-python3
Files: files | file ages | folders
SHA3-256:  05bd569e5ef5b2d1defc8e7cfb343faa6bbc7f7ab96095d001e57b2616bab43f
User & Date: tangent 2019-04-15 06:27:50
Original Comment: First steps to getting os8-run working with Python 3: this is all of the print() calls. (print() is a function in Python 3, not a keyword as in prior versions, so it requires parens around its arguments, always.) This is the start of a new branch because this won't be the only thing needed to get these programs working under Python 3. This is needed on my macOS box because Anaconda Distribution installs Python 3 as "python", which is arguably wrong, but hopefully we can get os8-run and its helper libraries into a state where they run on both versions so this won't matter any more.
Context
2019-04-15
06:33
Replaced use of dict.iteritems() with items() check-in: 394ecc357c user: tangent tags: os8-run-python3
06:27
First steps to getting os8-run working with Python 3: this is all of the print() calls. (print() is a function in Python 3, not a keyword as in prior versions, so it requires parens around its arguments, always.) This is the start of a new branch because this won't be the only thing needed to get these programs working under Python 3. This is needed on my macOS box because Anaconda Distribution installs Python 3 as "python", which is arguably wrong, but hopefully we can get os8-run and its helper libraries into a state where they run on both versions so this won't matter any more. This checkin *also* accidentally includes a SIMH update, because I was in the middle of the SIMH update and got distracted by fixing the Python 2-isms and accidentally checked the SIMH changes in as well. The SIMH update should have been on trunk only. I'll fix that on this branch a bit down the line. check-in: 05bd569e5e user: tangent tags: os8-run-python3
05:40
Updated bosi script to point at the Fossil 2.8 binary for RPi check-in: 5e51328bc2 user: tangent tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to Makefile.in.

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization from those authors.
########################################################################

# Git commit ID and time of the latest version of the SIMH 4 project on
# GitHub that has been merged into this source base.
SGCID=2f8fca49c6bfa4999d40a4adc50d6a2ad55464a3
SGCTM=2019-01-23T15:17:19-08:00

# C build flags for the PDP-8 simulator and its PiDP-8/I extensions.
SIM_CFLAGS := @CFLAGS@ @BUILDMODE@ \
	-Wno-unused-result -Wno-parentheses \
	-DUSE_READER_THREAD -DHAVE_DLOPEN=$(subst .,,@SH_SOEXT@) -DPIDP8I \
	-DSIM_ASYNCH_IO -DHAVE_REGEX_H -DHAVE_GLOB \
	-DSIM_GIT_COMMIT_ID=$(SGCID) -DSIM_GIT_COMMIT_TIME=$(SGCTM) \







|
|







32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization from those authors.
########################################################################

# Git commit ID and time of the latest version of the SIMH 4 project on
# GitHub that has been merged into this source base.
SGCID=2f0db74483bead32a9a6ef9c1606ba3162f63fc5
SGCTM=2019-04-13T12:49:43-07:00

# C build flags for the PDP-8 simulator and its PiDP-8/I extensions.
SIM_CFLAGS := @CFLAGS@ @BUILDMODE@ \
	-Wno-unused-result -Wno-parentheses \
	-DUSE_READER_THREAD -DHAVE_DLOPEN=$(subst .,,@SH_SOEXT@) -DPIDP8I \
	-DSIM_ASYNCH_IO -DHAVE_REGEX_H -DHAVE_GLOB \
	-DSIM_GIT_COMMIT_ID=$(SGCID) -DSIM_GIT_COMMIT_TIME=$(SGCTM) \

Changes to bin/os8-run.

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
...
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
...
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
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
...
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
# -*- coding: utf-8 -*-
########################################################################
# Script runner for OS/8 under SIMH.
# The library module os8script.py does the heavy lifting.
#
# See USAGE message below for details.
#
# Copyright © 2018 by Bill Cattey and Warren Young
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
................................................................................
       "\n \tscript [script] ... "

_en_dis_arg_re = re.compile("^(enable|disable)_(\S+)$")


def opt_set(en_dis, option, options_enabled, options_disabled):
  if option == None or en_dis == None: return
  # print en_dis + " " + option
  if en_dis == "enable":
    if option not in options_enabled:
      options_enabled.append(option)
    if option in options_disabled:
        options_disabled.remove(option)
  elif en_dis == "disable":
    if option not in options_disabled:
................................................................................
  enable_usage = ""
  disable_usage = ""

  idx = 1
  numargs = len(sys.argv)

  if numargs < 2:
    print USAGE
    sys.exit(-1)

  # Add arguments corresponding to --*-os8-* configure script options
  max_obn_len = 0
  for obn, vals in os8opts.opts.iteritems():
    max_obn_len = max(max_obn_len, len(obn))
  for obn, vals in os8opts.opts.iteritems():
................................................................................

  if disable_usage != "":
    USAGE += "\n  Known disable options: \n"
    USAGE += disable_usage
    
  while idx < numargs:
    arg = sys.argv[idx]
    # print "idx: " + str(idx) + ", arg: " + arg
    # print "Files: " + str(script_files)
    # print "Options: " + str(options_enabled)
    if arg == "-d" or arg == "--debug":
      DEBUG = True
    elif arg == "-h" or arg == "--help":
      print USAGE
      sys.exit(0)
    elif arg == "-v" or arg == "--verbose":
      VERBOSE = 1
    elif arg == "-vv" or arg == "--very-verbose":
      VERY_VERBOSE = 1
    elif arg == "--enable":
      idx +=1
      if idx == numargs:
        print "expecting an option but got none."
      else:
        option = sys.argv[idx]
        # Only add the option once
        if option not in options_enabled: options_enabled.append(option)
    elif arg == "--disable":
      idx +=1
      if idx == numargs:
        print "expecting an option but got none."
      else:
        option = sys.argv[idx]
        # Only add the option once
        if option not in options_disabled: options_disabled.append(option)
    else:
      script_files.append(arg)
    idx += 1
................................................................................
def main ():
  script_files = []
  options_enabled = []
  options_disabled = []

  parse_args (script_files, options_enabled, options_disabled)
  if len(script_files) == 0:
    print "Need a script file to run."
    sys.exit(-1)

  if VERBOSE:
    print "script_files: " + str(script_files)
  if DEBUG:
    print "options_enabled" + str(options_enabled)
    print "options_disabled" + str(options_disabled)
  
  # Append SIMH and OS/8 output to a file by default.
  #
  # We append because we're run twice in each test directory via the
  # os8-sys Makefile target called by test-os8-run, once for the "dist"
  # media and once for the actual RK05 bootable media.  So, the second
  # run must append its logs to the first run's log file.
................................................................................
  s.set_logfile (open (dirs.log + 'os8-run' + '.log', 'a') \
      if not VERY_VERBOSE else os.fdopen (sys.stdout.fileno (), 'w', 0))

  os8 = os8script (s, options_enabled, options_disabled, verbose=VERBOSE, debug=DEBUG)

  for script_file in script_files:
    if VERBOSE:
      print os.path.basename (__file__) + " -- Language Version: " + os8.lang_version

    print "Running script file: " + script_file
    os8.run_script_file (script_file)

  # After all scripts are done, we remove any scratch files,
  # detach any mounted devices, and shut down simh gracefully.

  for filename in os8.scratch_list:
    if os8.verbose: print "Deleting scratch_copy: " + filename
    os.remove(filename)
    
  s.send_cmd ("detach all")

  s.quit ()
  if VERBOSE: print "Done!"

  
if __name__ == "__main__":
    main()







|







 







|







 







|







 







|
|
|



|








|







|







 







|



|

|
|







 







|

|






|





|




2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
...
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
...
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
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
...
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
# -*- coding: utf-8 -*-
########################################################################
# Script runner for OS/8 under SIMH.
# The library module os8script.py does the heavy lifting.
#
# See USAGE message below for details.
#
# Copyright © 2018-2019 by Bill Cattey and Warren Young
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
................................................................................
       "\n \tscript [script] ... "

_en_dis_arg_re = re.compile("^(enable|disable)_(\S+)$")


def opt_set(en_dis, option, options_enabled, options_disabled):
  if option == None or en_dis == None: return
  # print(en_dis + " " + option)
  if en_dis == "enable":
    if option not in options_enabled:
      options_enabled.append(option)
    if option in options_disabled:
        options_disabled.remove(option)
  elif en_dis == "disable":
    if option not in options_disabled:
................................................................................
  enable_usage = ""
  disable_usage = ""

  idx = 1
  numargs = len(sys.argv)

  if numargs < 2:
    print(USAGE)
    sys.exit(-1)

  # Add arguments corresponding to --*-os8-* configure script options
  max_obn_len = 0
  for obn, vals in os8opts.opts.iteritems():
    max_obn_len = max(max_obn_len, len(obn))
  for obn, vals in os8opts.opts.iteritems():
................................................................................

  if disable_usage != "":
    USAGE += "\n  Known disable options: \n"
    USAGE += disable_usage
    
  while idx < numargs:
    arg = sys.argv[idx]
    # print("idx: " + str(idx) + ", arg: " + arg)
    # print("Files: " + str(script_files))
    # print("Options: " + str(options_enabled))
    if arg == "-d" or arg == "--debug":
      DEBUG = True
    elif arg == "-h" or arg == "--help":
      print(USAGE)
      sys.exit(0)
    elif arg == "-v" or arg == "--verbose":
      VERBOSE = 1
    elif arg == "-vv" or arg == "--very-verbose":
      VERY_VERBOSE = 1
    elif arg == "--enable":
      idx +=1
      if idx == numargs:
        print("expecting an option but got none.")
      else:
        option = sys.argv[idx]
        # Only add the option once
        if option not in options_enabled: options_enabled.append(option)
    elif arg == "--disable":
      idx +=1
      if idx == numargs:
        print("expecting an option but got none.")
      else:
        option = sys.argv[idx]
        # Only add the option once
        if option not in options_disabled: options_disabled.append(option)
    else:
      script_files.append(arg)
    idx += 1
................................................................................
def main ():
  script_files = []
  options_enabled = []
  options_disabled = []

  parse_args (script_files, options_enabled, options_disabled)
  if len(script_files) == 0:
    print("Need a script file to run.")
    sys.exit(-1)

  if VERBOSE:
    print("script_files: " + str(script_files))
  if DEBUG:
    print("options_enabled" + str(options_enabled))
    print("options_disabled" + str(options_disabled))
  
  # Append SIMH and OS/8 output to a file by default.
  #
  # We append because we're run twice in each test directory via the
  # os8-sys Makefile target called by test-os8-run, once for the "dist"
  # media and once for the actual RK05 bootable media.  So, the second
  # run must append its logs to the first run's log file.
................................................................................
  s.set_logfile (open (dirs.log + 'os8-run' + '.log', 'a') \
      if not VERY_VERBOSE else os.fdopen (sys.stdout.fileno (), 'w', 0))

  os8 = os8script (s, options_enabled, options_disabled, verbose=VERBOSE, debug=DEBUG)

  for script_file in script_files:
    if VERBOSE:
      print(os.path.basename (__file__) + " -- Language Version: " + os8.lang_version)

    print("Running script file: " + script_file)
    os8.run_script_file (script_file)

  # After all scripts are done, we remove any scratch files,
  # detach any mounted devices, and shut down simh gracefully.

  for filename in os8.scratch_list:
    if os8.verbose: print("Deleting scratch_copy: " + filename)
    os.remove(filename)
    
  s.send_cmd ("detach all")

  s.quit ()
  if VERBOSE: print("Done!")

  
if __name__ == "__main__":
    main()

Changes to lib/os8script.py.

1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
...
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
...
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
....
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
....
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
....
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
....
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
....
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
....
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
....
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
....
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
....
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
....
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
....
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
....
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
....
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########################################################################
# simh-os8-script.py Library for scripting OS/8 under SIMH
# Contains validators and callers for os8 and simh commands to make
# it easier to create scripts.
#
# Copyright © 2017 by Jonathan Trites, William Cattey, and Warren Young.

#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
................................................................................

# Local routine to perform a save of a pre-existing file
# because we do this in a couple places

def save_if_needed(path):
  if os.path.isfile(path):
    save_path = path + ".save"
    print "Pre-existing " + path + " found.  Saving as " + path + ".save"
    if os.path.isfile(save_path):
      print "Overwriting old " + path + ".save"
      os.remove(save_path)
    os.rename(path, save_path)
  
def version_to_array (version):
  vers_array = []
  this_str = ""

................................................................................
    if m == None: return path
    var = m.group(1)

    val = getattr (dirs, var, None)
    if val != None:
      return os.path.join(val,m.group(2))
    else:
      print "At line " + str(self.line_ct_stack[0]) + \
        ": {$" + var + "} is not a valid path expansion in " + path
      return None
    

  #### print_expand ######################################################
  # Close kin to path_expand.  Takes a string that may name a path
  # substitution or the magic $version value and performs the appropriate
  # value substitution.
................................................................................
    while idx < endpoint:
      # If version has more digits than test, the greater than test succeeds.
      if idx >= len(version_array):
           vers_item = "0"
      else:
         vers_item = version_array[idx]
      test_item = test_array[idx]

      if self.debug: print  "version_test: vers_item: " + vers_item + \
         ", test_item: " + test_item

      vers_num = int(vers_item)
      test_num = int(test_item)

      # First time version componet greater than test -> success.
      if vers_num > test_num:

        if self.debug: print "version_test: Success: version greater than test."
        return True
      # First time version component less than test -> failure.
      elif test_num > vers_num:
        if self.debug: print "version_test: Fails on sub compare."
        return False
      #Otherwise is equal. Keep going.

      idx += 1
    # Made it all the way through. Test succeeds.

    if self.debug: print "version_test: Success. Made it thru test string."
    return True

          
  #### basic_line_parse ################################################
  # Returns stripped line and any other cleanup we want.
  # Returns None if we should just 'continue' on to the next line.
  # Filters out comments.
................................................................................
    if retval == "": return None
    elif retval[0] == "#": return None
    # First test if we are in a begin option block
    m = re.match (_begin_en_dis_comm_re, retval)
    if m != None:
      en_dis = m.group(1)
      rest = m.group(2)
      if self.verbose: print "Line " + str(self.line_ct_stack[0]) + \
         ": doing_begin_option: " + en_dis + " " + rest

      if self.debug: print "options_enabled: " + str (self.options_enabled)
      if self.debug: print "options_disabled: " + str (self.options_disabled)
      if self.debug: print "options_stack: " + str(self.options_stack)

      vers_match = False
      if en_dis == "version":
        # Check for mal-formed version match first
        if re.match (_version_parse_re, rest) == None:
          print "Mal-formed version match string {" + rest + "} at line " + \
            str(self.line_ct_stack[0]) + ". Ignoring this block."
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)
          return None
        vers_match = self.version_test (rest)
        if vers_match:
          # Block is active. We push it onto the stack

          if self.debug: print "Pushing version enabled block " + rest + " onto options_stack"

          self.options_stack.insert(0, rest)

          if self.debug: print " new options_stack: " + str(self.options_stack)
        else:
          # Option is inactive.  Ignore all subseqent lines
          # until we get to an end command that matches our option.
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)
        return None
        
      elif en_dis == "enabled":
        if rest in self.options_enabled:
          # Block is active. We push it onto the stack

          if self.debug: print "Pushing enabled block " + rest + " onto options_stack"
          self.options_stack.insert(0, rest)

          if self.debug: print "new options_stack: " + str(self.options_stack)
        else:
          # Option is inactive.  Ignore all subseqent lines
          # until we get to an end command that matches our option.
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)

        return None
      # only other choice is disabled because of our regex.
      else:
        if rest not in self.options_disabled:
          # Block defaults to active. We push it onto the stack

          if self.debug: print "Pushing not_disabled block " + rest + " onto options_stack"

          self.options_stack.insert(0, rest)

          if self.debug: print "new options_stack: " + str(self.options_stack)
        else:
          # Block is inactive.  Ignore all subseqent lines
          # until we get to an end command that matches our option.
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)
        return None
  
    m = re.match(_end_en_dis_comm_re, retval)
    if m != None:
      rest = m.group(2)

      if self.verbose: print "Line " + str(self.line_ct_stack[0]) + ": end rest = " + rest
      if (rest == None or rest == ""):
        print "Warning! option end statement at line " + str(self.line_ct_stack[0]) + \
          " encountered with no argument."
        return None
      if len(self.options_stack) == 0:
        print "Warning! option end statement at line " + str(self.line_ct_stack[0]) + \

          " found with no matching begin for option: " + rest
        return None
      if rest != self.options_stack[0]:
        print "Warning! Mismatched option begin/end group at line " + \
          str(self.line_ct_stack[0]) + ". Currently inside option: " + \
          self.options_stack[0] + " not " + rest
        return None
      else:
        if self.debug: print "Popping " + self.options_stack[0]
        self.options_stack.pop(0)

        if self.debug: print "new options_stack: " + str(self.options_stack)
        return None
  
    return retval
  
  
  #### ignore_to_subcomm_end ###########################################
  
  def ignore_to_subcomm_end (self, old_line, script_file, end_str):
    if self.debug: print "ignore to: " + end_str
    for line in script_file:
      self.line_ct_stack[0] += 1
      line = line.strip()

      if self.verbose: print "Ignore line " + str(self.line_ct_stack[0]) + ": " + line
      
      m = re.match(_end_comm_re, line)
      if m == None: continue
  
      rest = m.group(1)
      if rest == None: rest = ""
      
................................................................................
  
  #### include_command #################################################
  # Call run_system_script recursively on the file path provided.
  
  def include_command (self, line, script_file):
    path = self.path_expand(line)
    if path == None:
      print "Ignoring: \n\tinclude " + line
      return "fail"

    if not os.path.isfile(path):
      print "Line " + str(self.line_ct_stack[0]) + \
        ": Could not find include file: " + path
      return "fail"
    if self.verbose: print "line: " + str(self.line_ct_stack[0]) + \
       ": include " + line
    return self.run_script_file (path)
      
  
  #### enable_option_command ###########################################
  # Deletes an option from the list of active options.
  # Parses the first argument after "enable" as the key to enable.
  # The end of the key is the end of the line or the first whitespace
  # character.
  
  def enable_option_command (self, line, script_file):
    if line == "":
      print "Empty option to enable at line: " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"
    m = re.match(_comm_re, line)
    if m == None:
      print "Could not parse enable command at line " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"
    option = m.group(1)
    if option == None:
      print "Empty option to enable command at line: " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"

    if self.verbose: print "Line " + str(self.line_ct_stack[0]) + \
       ": enable option: " + option
    # Remove it from other set if present
    if option in self.options_disabled:
      self.options_disabled.remove(option)
    # Add it if not already present.
    if option not in self.options_enabled:
      self.options_enabled.append(option)
    return "success"
................................................................................
  # Deletes an option from the list of active options.
  # Parses the first argument after "disable" as the key to enable.
  # The end of the key is the end of the line or the first whitespace
  # character.
 
  def disable_option_command (self, line, script_file):
    if line == "":
      print "Empty option to disable at line: " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"
    m = re.match(_comm_re, line)
    if m == None:
      print "Could not parse disable option command at line " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"
    option = m.group(1)
    if option == None:
      print "Empty option to disable command at line " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"
    if self.verbose: print "line: " + \

       str(self.line_ct_stack[0]) + ": disable option: " + option
    # Remove it from other set if present
    if option in self.options_enabled:
      self.options_enabled.remove(option)
    # Add it if not already present.
    if option not in self.options_disabled:
      self.options_disabled.append(option)
    return "success"
................................................................................
  # First arg is the item to configure.
  # Second arg is the setting.
  # This enables adding option setting inside a script file.
  
  def configure_command (self, line, script_file):
    m = re.match(_two_args_re, line)
    if m == None or m.group(1) == None or m.group(2) == None: 
      print "Could not parse configure command arguments at line " + \
        str(self.line_ct_stack[0]) + ": {" + line + "}"
      return "fail"
    item = m.group(1)
    setting = m.group(2)
    if item not in _configurables:
      print "Ignoring invalid configuration item at line " + \
        str(self.line_ct_stack[0]) + ": " + item
      return "fail"
    if setting not in _configurables[item]:
      print "At line " + str(self.line_ct_stack[0]) + \
        ": Cannot set " + item + " to " + setting + "."
      return "fail"
    if item == "tape":
      self.simh.set_tape_config(setting)
    elif item == "rx":
      self.simh.set_rx_config (setting)
    elif item == "tti":
      self.simh.set_tti_config (setting)
................................................................................


  #### cpto_command ###########################################
  # Calls os8_pip_to with the command line arguments.
  
  def cpto_command (self, line, script_file):
    if not self.booted:
      print "Cannot run cpto command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted."
      return "die"

    # Is 2nd and final arg the option?
    m = re.match(_from_to_re_1, line)
    if m != None:
      # Yes.  Expand Source first.
      path = self.path_expand(m.group(1))
      if path == None:
        print "Ignoring: \n\tcpto " + line
        return "fail"
      self.simh.os8_pip_to (path, "DSK:", m.group(2))
    else:
      # Is this normal case of source, dest, with possibly empty option?
      m = re.match(_from_to_re_2, line)
      if m == None:
        print "Could not parse cpto command at line " + \
          str(self.line_ct_stack[0]) + "."
        return "fail"
      path = self.path_expand(m.group(1))
      if path == None:
        print "Ignoring: \n\tcpto " + line
        return "fail"
      self.simh.os8_pip_to (path, m.group(2), m.group(4))
    return "success"


  #### cpto_command ###########################################
  # Calls os8_pip_from with the command line arguments.
  
  def cpfrom_command (self, line, script_file):
    if not self.booted:
      print "Cannot run cpfrom command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted."
      return "die"
    m = re.match(_from_to_re_2, line)
    if m == None:
      print "Could not parse cpfrom command at line " + \
        str(self.line_ct_stack[0]) + "."
      return "fail"
  
    path = self.path_expand(m.group(2))
    if path == None:
      print "Ignoring: \n\tcpfrom " + line
      return "fail"
    self.simh.os8_pip_from (m.group(1), path, m.group(4))
    return "success"


  #### copy_command ###############################################
  # Simple script interface to create a copy of a file.

  def copy_command (self, line, script_file):
    m = re.match(_two_args_re, line)
    if m == None or m.group(1) == None or m.group(2) == None: 
      print "Could not copy command: " + line
      return "fail"
    from_path = self.path_expand(m.group(1))      
    to_path = self.path_expand(m.group(2))

    if from_path == None or to_path == None:
      print "Ignoring: \n\t copy " + line
      return "fail"

    print "copy command: \n\tfrom: " + from_path + ", \n\tto: " + to_path
    
    if (not os.path.isfile(from_path)):
        print "At line " + str(self.line_ct_stack[0]) + \
          ": Required copy input file: " + from_path + " not found."
        return "fail"

    save_if_needed(to_path)
    
    try:
      shutil.copyfile(from_path, to_path)
    except shutil.Error as e:
      print "copy command failed with error: " + str(e)
      return "fail"
    except IOError as e:
      print "copy command failed with IOError: " + str(e)
      return "fail"
    return "success"


  #### resume_command #############################################
  # Call the os8_resume in simh to resume OS/8.

  def resume_command (self, line, script_file):
    if self.verbose: print "Resuming OS/8 at line " + \
       str(self.line_ct_stack[0]) + "."

    self.simh.os8_restart()
    return "success"


  #### restart_command #############################################
  # Call the os8_restart in simh to resume OS/8.

  def restart_command (self, line, script_file):
    if self.verbose: print "Restarting OS/8 at line " + \
       str(self.line_ct_stack[0]) + "."

    self.simh.os8_restart()
    return "success"


  #### patch_command ##############################################
  # Read the named patch file and perform its actions.

  def patch_command (self, line, script_file):
    if not self.booted:
      print "Cannot run patch command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted."
      return "die"
    path = self.path_expand(line)
    if path == None:
      print "Ignoring: \n\t" + "patch " + line
      return "fail"
    if not os.path.isfile(path):
      print "At line " + str(self.line_ct_stack[0]) + \
        ": Patch file: " + path + " not found."
      return "fail"

    self.run_patch_file (path)
    return "success"


  #### exit_command ###############################################
................................................................................
        intfound = True
        status = int(m.group(2))
      else:
        intfound = False
    if self.verbose:
      if intfound: stat_str = str(status)
      else: stat_str = line
      print "Calling sys.exit (" +  stat_str + ") at line: " + \
        str(self.line_ct_stack[0]) + "."
    if intfound: sys.exit (status)
    else: sys.exit(line)


  #### print_command ###############################################
  # Print text from the running script
  # If verbose is set, say what line in the script containing
  # the print command.

  def print_command (self, line, script_file):
    if self.verbose:
      print "Line: " + str(self.line_ct_stack[0]) + ": " + line
    else:
      print self.print_expand(line)
    return "success"


  #### _command ###########################################
  # 

  def _command (self, line, script_file):
................................................................................
                "resume": self.resume_command,
                "restart": self.restart_command,
                "patch": self.patch_command}
  
    try:
      script_file = open(script_path, "r")
    except IOError:
      print script_path + " not found."
      return "fail"

    # Every time we start a new script
    # We append a new line number count of 0
    # onto our line_ct_stack
    self.line_ct_stack.insert(0, 0)

    if self.debug: print "New line_ct_stack: " + str(self.line_ct_stack)
  
    for line in script_file:
      line = self.basic_line_parse (line, script_file)
      if line == None: continue
      
      m = re.match(_comm_re, line)
      if m == None:
        print "Ignoring command line at line " + \
          str(self.line_ct_stack[0]) + ": " + line
        continue
  
      if m.group(1) not in commands:
        print "Unrecognized script command at line " + \
          str(self.line_ct_stack[0]) + ": " + m.group(1)
        continue
  
      # print "arg: " + m.group(3)
      if m.group(3) == None: rest = ""
      else: rest = m.group(3)
      retval = commands[m.group(1)](rest, script_file)
      if retval == "die":
        print "\nFatal error encountered in " + script_path + \
          " at line " +  str(self.line_ct_stack[0]) + ":"
        print "\t" + line
        sys.exit(-1)

    # Done.  Pop the line count off our line_ct_stack
    self.line_ct_stack.pop(0)

    if self.debug: print "popped line_ct_stack: " + str(self.line_ct_stack)
    
    return "success"


  #### end_command #####################################################
  
  def end_command (self, line, script_file):
    print "Unexpectedly encountered end command at line " + \
      str(self.line_ct_stack[0]) + ": " + line
    return "fail"

  
  #### parse_odt #######################################################
  
  def parse_odt (self, com, line):
    if self.debug: print line
    
    if line == "\\c": return "break"
    match = _odt_parse.match(line)
    if match == None:
      print "Aborting because of bad ODT line: " + line
      self.simh.os8_send_ctrl('C')
      return "err"
    loc = match.group(1)
    old_val = match.group(2)
    new_val = match.group(3)
    expect_val_str = "\s*[0-7]{4} "
    

    if self.debug: print "Loc: " + loc + ", old_val: " + old_val + ", new_val: " + new_val

    self.simh.os8_send_str (loc + "/")
    self.simh._child.expect(expect_val_str)
  
    if old_val.isdigit():          # We need to check old value
      found_val = self.simh._child.after.strip()
      if found_val != old_val:
        print "\tOld value: " + found_val + " does not match " + old_val + ". Aborting patch."

        # Abort out of ODT back to the OS/8 Monitor
        self.simh.os8_send_ctrl('C')
        return "err"
  
    self.simh.os8_send_line (new_val)
    return "cont"

................................................................................

  #### futil_file ########################################################
  
  def futil_file (self, com, line):
    # Redundant re-parse of line but nobody else wants args right now.
    match = _com_split_parse.match(line)
    if match == None:
      print "Aborting because of mal-formed FUTIL FILE command: " + line
      self.simh.os8_send_ctrl('C')
      return "err"
    fname = match.group(2)
    expect_futil_file_str = "\n" + fname + "\s+(.*)$"
    self.simh.os8_send_line (line)
    self.simh._child.expect(expect_futil_file_str)
    result = self.simh._child.after.strip()
    match = _com_split_parse.match(result)
    if match == None:
      print "Aborting because unexpected return status: " + result + " from: " + line

      self.simh.os8_send_ctrl('C')
      return "err"
    if match.group(2).strip() == "LOOKUP FAILED":
      print "Aborting because of FUTIL lookup failure on: " + fname
      self.simh.os8_send_ctrl('C')
      return "err"
    else:
      return "cont"
  
  
  #### parse_futil #####################################################
................................................................................
  
    if line[0].isdigit():
      # Treat the line as ODT
      return self.parse_odt(com, line)
    else:
      match = _com_split_parse.match(line)
      if match == None:
        print "Ignoring failed FUTIL command parse of: " + line
        return "cont"
      fcom = match.group(1)
      rest = match.group(2)
  
      if fcom not in futil_specials:
        # Blind faith and no error checking.
        self.simh.os8_send_line(line)
................................................................................
  def run_patch_file (self, pathname):
    sys.stdout.write ("Applying patch " + os.path.basename (pathname) + "...")
    sys.stdout.flush ()

    try:
      patch_file = open(pathname, "r")
    except IOError:
      print pathname + " not found. Skipping."
      return "fail"
  
    special_commands = {
      "ODT": self.parse_odt,
      "R": None,               # Get next parser.
      "FUTIL": self.parse_futil
    }
................................................................................
          self.simh.os8_send_ctrl('C')
        elif retval == "err":
          patch_file.close()
          return "fail"
      elif line[0] == '.':        # New OS/8 Command
        match = _com_os8_parse.match(line)
        if match == None:
          print "Aborting patch on failed OS/8 command parse of: " + line
          return "fail"
        com = match.group(1)
        rest = match.group(2)
  
        if com in special_commands:
          if com == "R":
            # Run command is special.  Take arg as the command and run it.
................................................................................
            com = rest
          inside_a_command = True
          the_command = com
          the_command_parser = special_commands[com]
  
        # We carefully separate com and args
        # But don't make much use of that yet.
        if self.verbose and self.debug: print line
        self.simh.os8_send_cmd ("\\.", line[1:])  # Skip Prompt.
  
    patch_file.close()
  
    print "Success."
    return "success"


  #### skip_patch ######################################################
  # Returns true if the given filename matches one of the regex string
  # keys of the given skips dict and the flag value for that key is set.
  # See skips definition in make_patch, which calls this.
................................................................................
  # binary and optional listing files.
  
  def call_pal8 (self, source, binary):
    pal8_replies = ["ERRORS DETECTED: ", "BE\s+\S+", "CF\s+\S+", "DE\s+\S+", "DF", "IC\s+\S+", "ID\s+\S+",
                    "IE\s+\S+", "II\s+\S+", "IP\s+\S+", "IZ\s+\S+", "LD\s+\S+", "LG\s+\S+", "PE\s+\S+",
                    "PH\s+\S+", "RD\s+\S+", "SE\s+\S+", "UO\s+\S+", "US\s+\S+", "ZE\s+\S+", "\S+ NOT FOUND"]
  
    if self.verbose: print "Assembling " + source
    com_line = binary + "<" + source
    self.simh.os8_send_cmd ("\\.", "R PAL8")
    # Did the command successfully run and enter the command decoder?
    reply = self.simh._child.expect (self.simh._cd_replies)
    if reply != 0:
      print "PAL8 failed to start at line " + \
        str(self.line_ct_stack[0])
      return "fail"

    self.simh.os8_send_line (com_line)
    err_count = 0
    reply = self.simh._child.expect (pal8_replies)
    executed_line = self.simh._child.before.strip()
    reply_str = self.simh._child.after.strip()
    if reply == 0:
      self.simh._child.expect("\d+")
      err_count = int(self.simh._child.after.strip())
      reply_str += " " + self.simh._child.after.strip()
    if reply > 0 or err_count > 0:
      print "PAL8 Error: "
      print "\t*" + executed_line
      print "\t" + reply_str
      self.simh.os8_send_ctrl ('c')      # exit PAL8 Just in case.
      # We could do something better than just dying, I expect.
      return "fail"
    # self.simh.os8_send_ctrl ('[')      # exit PAL8
    return "success"


................................................................................
  # I tried to avoid including this command but sometimes you just
  # have to reconfigure subtle bits of device drivers.
  # We assume we can call a simh command at any time, but
  # doing so puts us in the simh context that persists until we
  # issue a boot or go command.
  
  def simh_command (self, line, script_file):
    print "simh command is disabled. Line " + \
      str(self.line_ct_stack[0]) + " ignored."
    return "fail"
    if self.verbose: print line
    self.simh.send_cmd(line)
    return "success"


  #### umount_command ##################################################
  def umount_command (self, line, script_file):
    detach_comm = "det " + line
    if self.verbose: print "line: " + \
        str(self.line_ct_stack[0]) + ": " + detach_comm
    self.simh.send_cmd(detach_comm)
    return "success"


  #### make_scratch ####################################################
  # Create a copy of the contents of image file using the python
  # method to create a secure, named temp filename.
................................................................................
  # and an extension which we use.
  # After copying the source image, the file is closed and the name
  # of the scratch file is returned.
  def make_scratch (self, base_imagename, extension):
    try:
      src_image = open(base_imagename+extension, "rb")
    except IOError:
      print "Open of imagefile " + base_imagename + extension + " failed."
      return None
      
    dest_image = tempfile.NamedTemporaryFile(mode='w+b', \
                                             prefix=base_imagename+'-temp-', \
                                             suffix=extension, \
                                             delete=False)
    destname = dest_image.name
    if self.debug: print "Temp file name is: " + destname

    try:
      shutil.copyfileobj(src_image, dest_image)
    except shutil.Error as e:
      print "Copy of imagefile " + base_imagename + extension + \
        " to scratch failed with error: " + str(e)
      return None
    except IOError as e:
      print "Copy of imagefile " + base_imagename + extension + \
        ", failed with IOError: " + \
        str(e)
      return None
    src_image.close()
    dest_image.close()
    self.scratch_list.append(destname)
    return destname
    

................................................................................
  #
  # If the mount command fails for any reason, we presume
  # it is a fatal error and abort the script.
  
  def mount_command (self, line, script_file):
    m = re.match(_mount_re, line)
    if m == None:
      print "At line " + str(self.line_ct_stack[0]) + \
        ", could not parse mount.  Ignoring: {" + line + "}."
      return "die"
    simh_dev = m.group(1)
    unit = m.group(2)
    rest = m.group(3)
    parts = rest.split()
    if len(parts) == 0:
      print "At line " + str(self.line_ct_stack[0]) + \
        ": No image name specified in: {" + line + "}"
      return "die"
    ro_arg = ""
    imagename = self.path_expand(parts[0])
    if imagename == None: return "die"
    
    dot = imagename.rindex(".")
    base_imagename = imagename[:dot]
................................................................................
    # Case of additional arguments.
    if len (parts) > 1:
      # Perform must_exist before scratch
      if "new" in parts[1:]:
        save_if_needed(imagename)
      if "must_exist" in parts[1:] or "required" in parts[1:]:
          if not os.path.exists(imagename):
            print "At line " + str(self.line_ct_stack[0]) + \
              ", " + imagename + " must exist but was not found. Not mounting."
            return "die"
      if "scratch" in parts[1:]:
        copy_imagename = self.make_scratch(base_imagename, extension)
        if copy_imagename == None: return "die"
        imagename = copy_imagename
        
      if "readonly" in parts[1:] or "ro" in parts[1:]:
        if copy_imagename != "":
          print "At line " + str(self.line_ct_stack[0]) + \
            ": You don't really need to set readonly on a scratch copy."
        ro_arg = "-r "
      if "no_overwrite" in parts[1:] or "preserve" in parts[1:]:
        if copy_imagename != "":
          print "Ignoring preserve option at line " + \

            str(self.line_ct_stack[0]) + " because scratch option is present."
        else:
          next_tape = 0
          while os.path.isfile(imagename):
            print "Found: " + imagename
            next_tape += 1
            imagename =  base_imagename + "-" + str(next_tape) + extension
    if unit == None or unit == "":
      print "Need unit number for: " + line
      return "die"
  
    if simh_dev not in _os8_from_simh_dev:
      print "At line " + str(self.line_ct_stack[0]) + \
        ": Unrecognized simh dev: " + simh_dev
      return "die"
    os8dev = _os8_from_simh_dev[simh_dev]
  
    attach_comm = "att " + ro_arg + simh_dev + unit + " " + imagename
  

    if self.verbose: print "Line " + str(self.line_ct_stack[0]) + \
       ": mount: " + attach_comm
    self.simh.send_cmd(attach_comm)
    return "success"


  #### boot_command ####################################################
  #
  # Check to see if the device to be booted has something attached.
................................................................................
  def boot_command (self, line, script_file):
    # First confirm something is attached to boot from.
    ucname = line.upper()
    boot_replies = [ucname + "\s+(.+)\r", "Non-existent device"]
    self.simh.send_cmd("show " + line)
    retval = self.simh._child.expect(boot_replies)
    if retval == 1:
      print "Attempt to boot non-existent device: " + line
      return "die"
    m = re.match("^(\S+)\s(\S+),\s+(attached to |not attached)(\S+)?,\s+(.+)\r",
                 self.simh._child.after)
    if m == None:
      print "Could not determine if device " + line + " is attached."
      return "die"

    # Caution match group we want ends with a space.
    if m.group(3) != "attached to ":
      print "Attempt to boot on non-attached device: " + line
      return "die"
    
    boot_comm = "boot " + line
    if self.verbose: print "Line " + str(self.line_ct_stack[0]) + ": " + \
       boot_comm
    self.simh.send_cmd(boot_comm)
    self.booted = True
    return "success"


  #### os8_command #####################################################
  
  def os8_command (self, line, script_file):
    if not self.booted:
      print "Cannot run os8 command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted."
      return "die"

    os8_comm = line
    if self.verbose: print "Line: " + \
       str(self.line_ct_stack[0]) + ": os8_command: " + os8_comm

    # Resume OS/8 if necessary.
    if self.simh._context == "simh":
      self.resume_command(line, script_file)

    self.simh.os8_send_cmd ("\\.", os8_comm, self.debug)
    return "success"
................................................................................
  # The "pal8" script command comes in two forms:
  # The two argument form where the PAL8 status is printed on the fly
  # and the 3 argument form where all status goes into the listing file.
  # We do the 3 argument form with a simple "os8" script command.
  
  def pal8_command (self, line, script_file):
    if not self.booted:
      print "Cannot run pal8 command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted."
      return "die"

    m_2form = re.match (_two_arg_pal_re, line)
    if m_2form != None:

      # Resume OS/8 if necessary.
      if self.simh._context == "simh":
................................................................................
      # Call the 2arg pal8 code that works hard at error analysis.
      return self.call_pal8 (m_2form.group(4), m_2form.group(1))
    else:
      m_3form = re.match (_three_arg_pal_re, line)
      if m_3form != None:
        # Just run the OS/8 command.
        os8_comm = "pal8 " + line
        if self.verbose: print "Line: " + \

           str(self.line_ct_stack[0]) + ": Calling 3-arg pal8 command: " + os8_comm
        self.simh.os8_send_cmd ("\\.", os8_comm)
      else:
        print "At line " + str(self.line_ct_stack[0]) + \
          ": Unrecognized pal8 form: {" + line + "}."
        return "fail"
    return "success"


  #### begin_command ###################################################
  
  def begin_command (self, line, script_file):
    if not self.booted:
      print "Cannot execute begin subcommand block at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted."
      return "die"

    sub_commands = {"fotp": self.fotp_subcomm, "build": self.build_subcomm,
                    "absldr": self.absldr_subcomm,
                    "cdprog": self.cdprog_subcomm}
  
    m = re.match(_comm_re, line)
    if m == None:
      print "Could not parse sub-command at line " + \
        str(self.line_ct_stack[0]) + ": " + line
    if m.group(1) not in sub_commands:
      print "Ignoring unrecognized sub-command at line " + \
        str(self.line_ct_stack[0]) + ": " + m.group(1)
      print "Ignoring everything to next end."
      self.ignore_to_subcomm_end(line, script_file, "")
      return "fail"
    else:
      # Resume OS/8 if necessary.
      if self.simh._context == "simh":
        self.resume_command(line, script_file)

................................................................................
  
  def build_subcomm (self, old_line, script_file):
    # A race condition results if we send ^C when we are already at
    # Monitor level.  So need_exit gets set to False, when we know
    # we have already exited build, and are at the monitor prompt.
    need_exit = True
    os8_comm = "RU " + old_line

    if self.verbose: print "Line " + str(self.line_ct_stack[0]) + ": " + \
       os8_comm
    prompt_str = "\n\\$$"
    if self.debug:
      print "sending to simh: " + os8_comm
      print " and expecting prompt: '\\n\\\\$$'"
    self.simh.os8_send_cmd ("\\.", os8_comm)
    self.simh._child.expect(prompt_str)
    
    for line in script_file:
      # if self.debug:
      #  print "line: " + line
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      m = re.match(_comm_re, line)
      if m == None:
        print "Ignoring mal-formed build sub-command at line " + \
          str(self.line_ct_stack[0]) + ": " + line
        continue
  
      build_sub = m.group(1)
      rest = m.group(3)
      if rest == None: rest = ""
      
      if build_sub not in _build_comm_regs:
        print "Unrecognized BUILD command at line " + \
          str(self.line_ct_stack[0]) + ": " + build_sub
        continue
  
      if build_sub == "end":
        if rest == "":
          print "Warning! end statement encountered inside build with no argument at line " + \
            str(self.line_ct_stack[0]) + ".\nExiting build."
          return "fail"
        elif rest != "build": 
          print "Warning! Mismatched begin/end blocks in BUILD at line " + \
            str(self.line_ct_stack[0]) + ".\nEncountered end: {" + rest + "}. Exiting BUILD."

          return "fail"
        
        if self.verbose:
          print "Line " + str(self.line_ct_stack[0]) + ": end BUILD"
        if self.debug:
          print "before: " + self.simh._child.before.strip()
          print "after: " + self.simh._child.after.strip()
        # Return to monitor level unless need_exit == False.
        if need_exit:
          self.simh.os8_send_ctrl ('c')

        return "success"
        
      build_re = _build_comm_regs[build_sub]
  
      if build_re != None:
        m2 = re.match(build_re, rest)
        if m2 == None:
          print "Ignoring mal-formed BUILD at line " + \
            str(self.line_ct_stack[0]) + ": " + build_sub + " command: " + rest

          continue
      
        if build_sub == "BUILD":
          if m2.group(1) == None or m2.group(1) == "":
            print "Missing source of OS8.BN. Ignoring BUILD command at line " + \
              str(self.line_ct_stack[0]) + "."
            continue
          else: kbm_arg = m2.group(1)

          if m2.group(3) == None or m2.group(3) == "":
            print "Missing sorce of CD.BN. Ignoring BUILD command at line " + \
              str(self.line_ct_stack[0]) + "."
            continue
          else: cd_arg = m2.group(3)
          

          if self.verbose: print "Line " + str(self.line_ct_stack[0]) + \
             ": BUILD KBM: " + kbm_arg + ", CD: " + cd_arg
          if self.debug:
            print "sending to simh: BUILD"
          self.simh.os8_send_line ("BUILD")

          build_build_replies = ["LOAD OS/8: "]
          build_build_replies.extend(_build_replies)
          
          if self.debug:
            print "expecting: " + str(build_build_replies)
          reply = self.simh._child.expect(build_build_replies)
          if self.debug:
            print "reply: " + str(reply)
            print "before: " + self.simh._child.before.strip()
            print "after: " + self.simh._child.after.strip()
          if reply != 0:
            print "No prompt for LOAD OS/8 in BUILD command within BUILD at line " + \
              str(self.line_ct_stack[0]) + "."
            print "Instead got: {" + self.simh._child.after + "}."
            print "Exiting BUILD."
            return "die"
          if self.debug:
            print "sending to simh: " + kbm_arg
          self.simh.os8_send_line (kbm_arg)

          build_build_replies = ["LOAD CD: "]
          build_build_replies.extend(_build_replies)
          
          if self.debug:
            print "expecting: " + str(build_build_replies)
          reply = self.simh._child.expect(build_build_replies)
          if self.debug:
            print "reply: " + str(reply)
            print "before: " + self.simh._child.before.strip()
            print "after: " + self.simh._child.after.strip()
          if reply != 0:
            print "No prompt for LOAD CD in BUILD command within BUILD at line " + \
              str(self.line_ct_stack[0]) + "."
            print "Instead got: {" + self.simh._child.after + "}."
            print "Exiting BUILD."
            return "die"
          if self.debug:
            print "sending to simh: " + cd_arg
          self.simh.os8_send_line (cd_arg)

          # Done with BUILD command dialog within BUILD.SV
          # Get that BUILD.SV prompt.
          if self.debug:
            print "Expecting prompt: '\\n\\\\$$'"
          self.simh._child.expect(prompt_str)
          if self.debug:
            print "Resume BUILD.SV command loop."
          continue

      comm = build_sub + " " + rest
      if self.verbose: print "Line " + str(self.line_ct_stack[0]) + \
         ": BUILD-> " + comm

      if self.debug:
        print "sending to simh: " + comm
      self.simh.os8_send_line (comm)
      if self.debug:
        print "expecting: " + str(_build_replies)
      reply = self.simh._child.expect(_build_replies)
      if self.debug:
        print "reply: " + str(reply)
        print "before: " + self.simh._child.before.strip()
        print "after: " + self.simh._child.after.strip()
      if reply > 3:
        print "BUILD error at line " + str(self.line_ct_stack[0]) + \
          " with command " + self.simh._child.before.strip()
        print "\t" + self.simh._child.after.strip()
        self.simh.os8_send_ctrl ('c')
      # Special case "BOOT" sub-command: May ask, "WRITE ZERO DIRECT?"
      if build_sub == "BOOT":
        if reply == 2:
          if self.debug:
            print "Boot received \"WRITE ZERO DIRECT?\""
            print "sending to simh: Y"
          self.simh.os8_send_line("Y")
          if self.debug:
            print "Expecting \"SYS BUILT\""
          reply = self.simh._child.expect("SYS BUILT")
          if self.debug:
            print "ZeroDir: reply: " + str(reply)
            print "before: " + self.simh._child.before.strip()
            print "after: " + self.simh._child.after.strip()
          need_exit = False
        elif reply == 0:
          reply = self.simh._child.expect("SYS BUILT")
          if self.debug:
            print "$: reply: " + str(reply)
            print "before: " + self.simh._child.before.strip()
            print "after: " + self.simh._child.after.strip()
          need_exit = False
        elif reply == 1:
          reply = self.simh._child.expect("\\.")
          if self.debug:
            print "SysBuilt: reply: " + str(reply)
            print "before: " + self.simh._child.before.strip()
            print "after: " + self.simh._child.after.strip()
    print "Warning end of file encountered with no end of BUILD command block at line " + \
      str(self.line_ct_stack[0]) + "."
    return "fail"
  
  #### cdprog_subcomm ##################################################
  # Cycle through OS/8 command decoder with the command specified
  # in the argument.
  
  def cdprog_subcomm (self, old_line, script_file):
    os8_comm = "RU " + old_line
    end_str = "cdprog " + old_line
    if self.verbose: print "Line: " + \
       str(self.line_ct_stack[0]) + ": " + os8_comm
    self.simh.os8_send_cmd ("\\.", os8_comm)
    
    for line in script_file:
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      # Test for special case, "end" and act on it if present.
      m = re.match(_comm_re, line)
      if m != None and m.group(1) != None and m.group(1) != "" and m.group(1)  == "end":
        rest = m.group(3)
        retval = "fail"  # Return fail unless proven successful.
        if rest == None or rest == "":
          print "Warning! end statement encountered inside cdprog with no argument at line " + \

            str(self.line_ct_stack[0]) + "."
          print "Expecting: {" + end_str + "}."
        elif rest != end_str:
          print "Warning! Mismatched begin/end blocks in cdprog at line " + \
            str(self.line_ct_stack[0]) + ".\n"
          print "Expecting: {" + end_str + "}. Got: {" + rest + "}.\n"
        else:
          retval = "success"

          if self.verbose: print "Line " + str(self.line_ct_stack[0]) + ": end " + end_str
        if retval == "fail":
          print "Exiting cdprog, possibly earlier than expected at line " + \
            str(self.line_ct_stack[0]) + "."
        self.simh.os8_send_ctrl ('[')
        return retval
  
      # We could do some basic OS/8 command decoder synax checking here.
      comm = line
      if self.verbose: print "Line: " + \
         str(self.line_ct_stack[0]) + ": * " + line
      self.simh.os8_send_cmd ("\\*", line)
    print "Warning end of file encountered at line " + \

      str(self.line_ct_stack[0]) + " with no end of cdprog command block."
    self.simh.os8_send_ctrl ('[')
    return "fail"

  
  #### fotp_subcomm ####################################################
  
  def fotp_subcomm (self, old_line, script_file):
    os8_comm = "RU " + old_line
    if self.verbose: print "Line: " + \
       str(self.line_ct_stack[0]) + ": " + os8_comm
    self.simh.os8_send_cmd ("\\.", os8_comm)
    
    for line in script_file:
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      # Test for special case, "end" and act on it if present.
      m = re.match(_comm_re, line)
      if m != None and m.group(1) != None and m.group(1) != "" and m.group(1)  == "end":
        rest = m.group(3)
        if rest == None or rest == "":
          print "Warning! end statement encountered inside fotp with no argument at line " + \

            str(self.line_ct_stack[0]) + "."
          return "fail"
        elif rest != "fotp":
          print "Warning! Mismatched begin/end blocks in FOTP at line " + \
            str(self.line_ct_stack[0]) + ".\nEncountered end: {" + rest + "}. Exiting FOTP."

          return "fail"


        if self.verbose: print "Line " + str(self.line_ct_stack[0]) + ": end FOTP"
        self.simh.os8_send_ctrl ('[')
        return "success"
  
      m = re.match(_fotp_re, line)
      if m == None:
        print "At line " + str(self.line_ct_stack[0]) + \
          ": ignoring mal-formed fotp file spec: {" + line + "}."
        continue
  
      comm = line
      if self.verbose: print "Line: " + \
         str(self.line_ct_stack[0]) + ": * " + line
      self.simh.os8_send_cmd ("\\*", line)
    print "Warning end of file encountered at line " + \

      str(self.line_ct_stack[0]) + " with no end of FOTP command block."
    return "fail"

  
  #### absldr_subcomm ##################################################
  # A clone of fotp_subcom.  Can we find a way to merge the common code?
  
  def absldr_subcomm (self, old_line, script_file):
    os8_comm = "RU " + old_line
    if self.verbose: print " line: " + \
       str(self.line_ct_stack[0]) + ": " + os8_comm
    self.simh.os8_send_cmd ("\\.", os8_comm)
    
    for line in script_file:
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      # Test for special case, "end" and act on it if present.
      m = re.match(_comm_re, line)
      if m != None and m.group(1) != None and m.group(1) != "" and m.group(1)  == "end":
        rest = m.group(3)
        if rest == None or rest == "":
          print "Warning! end statement encountered inside ABSLDR with no argument at line " + \

            str(self.line_ct_stack[0]) + "."
          return "fail"
        elif rest != "absldr":
          print "Warning! Mismatched begin/end blocks in ABSLDR at line " + \

            str(self.line_ct_stack[0]) + ".\nEncountered end: {" + rest + "}. Exiting ABSLDR."
          return "fail"
          

        if self.verbose: print "End ABSLDR at line " + str(self.line_ct_stack[0]) + "."
        self.simh.os8_send_ctrl ('[')
        return "success"
  
      m = re.match(_absldr_re, line)
      if m == None:
        print "Ignoring mal-formed absldr file spec at line " + str(self.line_ct_stack[0]) + \
          ": {" + line + "}."
        continue
  
      comm = line

      if self.verbose: print "Line : " + str(self.line_ct_stack[0]) + "* " + line
      self.simh.os8_send_cmd ("\\*", line)
    print "Warning end of file encountered at line " + \
      str(self.line_ct_stack[0]) + "with no end of ABSLDR command block."
    return "fail"


  #### check_exists ####################################################
  # Check existence of all files needed
  
  def check_exists (s, image_copyins):
    for copyin in image_copyins:
      image = copyin[1]
      image_path = dirs.os8mi + image
      if (not os.path.isfile(image_path)):
          print "Required file: " + image_path + " not found."
          mkos8_abort(s)
      # else: print "Found " + image_path
  
     
  #### Data Structures ################################################
  #
  # The make procedures use helper procedures
  # to confirm that the relevant input image file exists and
  # to perform the file copies.
................................................................................
  # Detaches dt0 and dt1 after using them.
  # copyin0 mounts on dt0.  copyin1 mounts on dt1.
  # Either copyin or both can be None
  
  def copyin_pair (s, copyin0, copyin1, debug):
    if debug:
      if copyin0:
        print "Copying: " + copyin0[1] + " to: " + copyin0[0] + "from dt0"

      else: print "copyin0 is empty."

      if copyin1:
        print "Copying: " + copyin1[1] + " to: " + copyin1[0] + "from dt1"

      else: print "copyin1 is empty."
      
    if not copyin0 and not copyin1: return   # Nothing to do.
  
    # The order of events here is a bit funky because we want
    # to use both DECtape drives but also
    # switch between SIMH and OS/8 as infrequently as possible.
  
    if copyin0: self.simh.send_cmd ("attach -r dt0 " + dirs.os8mi + copyin0[1])
    if copyin1: self.simh.send_cmd ("attach -r dt1 " + dirs.os8mi + copyin1[1])
  
    self.simh.os8_restart()
  
    if copyin0:
      if self.verbose: print copyin0[2]
      if copyin0[3]:                    # We have specific files to do.
        for file_copyin in copyin0[3]:
          self.simh.os8_send_cmd ("\\.", "COPY " + file_copyin[0] + "<DTA0:" + file_copyin[1])
      else:
        self.simh.os8_send_cmd ("\\.", "COPY " + copyin0[0] + "<DTA0:*.*")
  
    if copyin1:
      if self.verbose: print copyin1[2]
      if copyin1[3]:                    # We have specific files to do.
        for file_copyin in copyin1[3]:
          self.simh.os8_send_cmd ("\\.", "COPY " + file_copyin[0] + "<DTA1:" + file_copyin[1])
      else:
        self.simh.os8_send_cmd ("\\.", "COPY " + copyin1[0] + "<DTA1:*.*")
  
    self.simh.back_to_cmd("\\.")







|
>







 







|

|







 







|
|







 







>
|
|






>
|



|





>
|







 







|
|
>
|
|
|





|
|





>
|
>

>
|









>
|

>
|










>
|
>

>
|









>
|

|
|


|
>
|


|

|


|

>
|








|



>
|







 







|



|
|

|
|











|
|



|
|



|
|

>
|
|







 







|
|



|
|



|
|

|
>
|







 







|
|




|
|


|
|







 







|
|








|






|
|



|










|
|



|
|




|











|





|


|


|
|







|


|








|
|









|
|










|
|



|


|
|







 







|
|











|

|







 







|






>
|







|
|



|
|


|




|
|
|




>
|







|
|






|




|







>
|
>






|
>







 







|









|
>



|







 







|







 







|







 







|







 







|




|







 







|





|
<












|
|
|







 







|
|

|







|
|







 







|







|




|
|


|
|
<







 







|
|






|
|







 







|
|








|
|



|
>
|



|



|



|
|





>
|
|







 







|




|




|



|
|









|
|



|
|







 







|
|







 







|
>
|


|
|








|
|








|
|

|
|
|







 







>
|
<


|
|





|





|
|







|
|




|
|


|
|
>



|

|
|











|
|
>




|
|




|
|



>
|
|

|






|


|
|
|

|
|
|
|


|






|


|
|
|

|
|
|
|


|





|


|



|
|


|


|


|
|
|

|
|
|





|
|


|


|
|
|




|
|
|




|
|
|
|
|









|
|












|
>
|
|

|
|
|


>
|

|
|





|
|

|
>
|








|
|











|
>
|


|
|
>


>
|





|
|



|
|

|
>
|








|
|











|
>
|


|
>
|


>
|





|
|



>
|

|
|











|

|







 







|
>
|
>

|
>
|













|







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
...
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
....
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
....
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
....
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
....
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
....
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
....
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
....
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
....
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
....
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
....
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
....
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
....
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
....
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
....
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########################################################################
# simh-os8-script.py Library for scripting OS/8 under SIMH
# Contains validators and callers for os8 and simh commands to make
# it easier to create scripts.
#
# Copyright © 2017-2019 by Jonathan Trites, William Cattey, and
# Warren Young.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
................................................................................

# Local routine to perform a save of a pre-existing file
# because we do this in a couple places

def save_if_needed(path):
  if os.path.isfile(path):
    save_path = path + ".save"
    print("Pre-existing " + path + " found.  Saving as " + path + ".save")
    if os.path.isfile(save_path):
      print("Overwriting old " + path + ".save")
      os.remove(save_path)
    os.rename(path, save_path)
  
def version_to_array (version):
  vers_array = []
  this_str = ""

................................................................................
    if m == None: return path
    var = m.group(1)

    val = getattr (dirs, var, None)
    if val != None:
      return os.path.join(val,m.group(2))
    else:
      print("At line " + str(self.line_ct_stack[0]) + \
        ": {$" + var + "} is not a valid path expansion in " + path)
      return None
    

  #### print_expand ######################################################
  # Close kin to path_expand.  Takes a string that may name a path
  # substitution or the magic $version value and performs the appropriate
  # value substitution.
................................................................................
    while idx < endpoint:
      # If version has more digits than test, the greater than test succeeds.
      if idx >= len(version_array):
           vers_item = "0"
      else:
         vers_item = version_array[idx]
      test_item = test_array[idx]
      if self.debug:
        print("version_test: vers_item: " + vers_item + \
           ", test_item: " + test_item)

      vers_num = int(vers_item)
      test_num = int(test_item)

      # First time version componet greater than test -> success.
      if vers_num > test_num:
        if self.debug:
          print("version_test: Success: version greater than test.")
        return True
      # First time version component less than test -> failure.
      elif test_num > vers_num:
        if self.debug: print("version_test: Fails on sub compare.")
        return False
      #Otherwise is equal. Keep going.

      idx += 1
    # Made it all the way through. Test succeeds.
    if self.debug:
      print("version_test: Success. Made it thru test string.")
    return True

          
  #### basic_line_parse ################################################
  # Returns stripped line and any other cleanup we want.
  # Returns None if we should just 'continue' on to the next line.
  # Filters out comments.
................................................................................
    if retval == "": return None
    elif retval[0] == "#": return None
    # First test if we are in a begin option block
    m = re.match (_begin_en_dis_comm_re, retval)
    if m != None:
      en_dis = m.group(1)
      rest = m.group(2)
      if self.verbose: print("Line " + str(self.line_ct_stack[0]) + \
         ": doing_begin_option: " + en_dis + " " + rest)
      if self.debug:
        print("options_enabled: " + str (self.options_enabled))
        print("options_disabled: " + str (self.options_disabled))
        print("options_stack: " + str(self.options_stack))

      vers_match = False
      if en_dis == "version":
        # Check for mal-formed version match first
        if re.match (_version_parse_re, rest) == None:
          print("Mal-formed version match string {" + rest + "} at line " + \
            str(self.line_ct_stack[0]) + ". Ignoring this block.")
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)
          return None
        vers_match = self.version_test (rest)
        if vers_match:
          # Block is active. We push it onto the stack
          if self.debug:
            print("Pushing version enabled block " + rest + \
                " onto options_stack")
          self.options_stack.insert(0, rest)
          if self.debug: print(" new options_stack: " + \
              str(self.options_stack))
        else:
          # Option is inactive.  Ignore all subseqent lines
          # until we get to an end command that matches our option.
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)
        return None
        
      elif en_dis == "enabled":
        if rest in self.options_enabled:
          # Block is active. We push it onto the stack
          if self.debug:
              print("Pushing enabled block " + rest + " onto options_stack")
          self.options_stack.insert(0, rest)
          if self.debug:
            print("new options_stack: " + str(self.options_stack))
        else:
          # Option is inactive.  Ignore all subseqent lines
          # until we get to an end command that matches our option.
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)

        return None
      # only other choice is disabled because of our regex.
      else:
        if rest not in self.options_disabled:
          # Block defaults to active. We push it onto the stack
          if self.debug:
            print("Pushing not_disabled block " + rest + \
                " onto options_stack")
          self.options_stack.insert(0, rest)
          if self.debug:
            print("new options_stack: " + str(self.options_stack))
        else:
          # Block is inactive.  Ignore all subseqent lines
          # until we get to an end command that matches our option.
          self.ignore_to_subcomm_end (retval, script_file, en_dis + " " + rest)
        return None
  
    m = re.match(_end_en_dis_comm_re, retval)
    if m != None:
      rest = m.group(2)
      if self.verbose:
        print("Line " + str(self.line_ct_stack[0]) + ": end rest = " + rest)
      if (rest == None or rest == ""):
        print("Warning! option end statement at line " + \
          str(self.line_ct_stack[0]) + " encountered with no argument.")
        return None
      if len(self.options_stack) == 0:
        print("Warning! option end statement at line " + \
          str(self.line_ct_stack[0]) + \
          " found with no matching begin for option: " + rest)
        return None
      if rest != self.options_stack[0]:
        print("Warning! Mismatched option begin/end group at line " + \
          str(self.line_ct_stack[0]) + ". Currently inside option: " + \
          self.options_stack[0] + " not " + rest)
        return None
      else:
        if self.debug: print("Popping " + self.options_stack[0])
        self.options_stack.pop(0)
        if self.debug:
          print("new options_stack: " + str(self.options_stack))
        return None
  
    return retval
  
  
  #### ignore_to_subcomm_end ###########################################
  
  def ignore_to_subcomm_end (self, old_line, script_file, end_str):
    if self.debug: print("ignore to: " + end_str)
    for line in script_file:
      self.line_ct_stack[0] += 1
      line = line.strip()
      if self.verbose:
        print("Ignore line " + str(self.line_ct_stack[0]) + ": " + line)
      
      m = re.match(_end_comm_re, line)
      if m == None: continue
  
      rest = m.group(1)
      if rest == None: rest = ""
      
................................................................................
  
  #### include_command #################################################
  # Call run_system_script recursively on the file path provided.
  
  def include_command (self, line, script_file):
    path = self.path_expand(line)
    if path == None:
      print("Ignoring: \n\tinclude " + line)
      return "fail"

    if not os.path.isfile(path):
      print("Line " + str(self.line_ct_stack[0]) + \
        ": Could not find include file: " + path)
      return "fail"
    if self.verbose:
      print("line: " + str(self.line_ct_stack[0]) + ": include " + line)
    return self.run_script_file (path)
      
  
  #### enable_option_command ###########################################
  # Deletes an option from the list of active options.
  # Parses the first argument after "enable" as the key to enable.
  # The end of the key is the end of the line or the first whitespace
  # character.
  
  def enable_option_command (self, line, script_file):
    if line == "":
      print("Empty option to enable at line: " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
    m = re.match(_comm_re, line)
    if m == None:
      print("Could not parse enable command at line " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
    option = m.group(1)
    if option == None:
      print("Empty option to enable command at line: " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
    if self.verbose:
      print("Line " + str(self.line_ct_stack[0]) + \
         ": enable option: " + option)
    # Remove it from other set if present
    if option in self.options_disabled:
      self.options_disabled.remove(option)
    # Add it if not already present.
    if option not in self.options_enabled:
      self.options_enabled.append(option)
    return "success"
................................................................................
  # Deletes an option from the list of active options.
  # Parses the first argument after "disable" as the key to enable.
  # The end of the key is the end of the line or the first whitespace
  # character.
 
  def disable_option_command (self, line, script_file):
    if line == "":
      print("Empty option to disable at line: " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
    m = re.match(_comm_re, line)
    if m == None:
      print("Could not parse disable option command at line " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
    option = m.group(1)
    if option == None:
      print("Empty option to disable command at line " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
    if self.verbose:
      print("line: " + str(self.line_ct_stack[0]) + \
          ": disable option: " + option)
    # Remove it from other set if present
    if option in self.options_enabled:
      self.options_enabled.remove(option)
    # Add it if not already present.
    if option not in self.options_disabled:
      self.options_disabled.append(option)
    return "success"
................................................................................
  # First arg is the item to configure.
  # Second arg is the setting.
  # This enables adding option setting inside a script file.
  
  def configure_command (self, line, script_file):
    m = re.match(_two_args_re, line)
    if m == None or m.group(1) == None or m.group(2) == None: 
      print("Could not parse configure command arguments at line " + \
        str(self.line_ct_stack[0]) + ": {" + line + "}")
      return "fail"
    item = m.group(1)
    setting = m.group(2)
    if item not in _configurables:
      print("Ignoring invalid configuration item at line " + \
        str(self.line_ct_stack[0]) + ": " + item)
      return "fail"
    if setting not in _configurables[item]:
      print("At line " + str(self.line_ct_stack[0]) + \
        ": Cannot set " + item + " to " + setting + ".")
      return "fail"
    if item == "tape":
      self.simh.set_tape_config(setting)
    elif item == "rx":
      self.simh.set_rx_config (setting)
    elif item == "tti":
      self.simh.set_tti_config (setting)
................................................................................


  #### cpto_command ###########################################
  # Calls os8_pip_to with the command line arguments.
  
  def cpto_command (self, line, script_file):
    if not self.booted:
      print("Cannot run cpto command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted.")
      return "die"

    # Is 2nd and final arg the option?
    m = re.match(_from_to_re_1, line)
    if m != None:
      # Yes.  Expand Source first.
      path = self.path_expand(m.group(1))
      if path == None:
        print("Ignoring: \n\tcpto " + line)
        return "fail"
      self.simh.os8_pip_to (path, "DSK:", m.group(2))
    else:
      # Is this normal case of source, dest, with possibly empty option?
      m = re.match(_from_to_re_2, line)
      if m == None:
        print("Could not parse cpto command at line " + \
          str(self.line_ct_stack[0]) + ".")
        return "fail"
      path = self.path_expand(m.group(1))
      if path == None:
        print("Ignoring: \n\tcpto " + line)
        return "fail"
      self.simh.os8_pip_to (path, m.group(2), m.group(4))
    return "success"


  #### cpto_command ###########################################
  # Calls os8_pip_from with the command line arguments.
  
  def cpfrom_command (self, line, script_file):
    if not self.booted:
      print("Cannot run cpfrom command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted.")
      return "die"
    m = re.match(_from_to_re_2, line)
    if m == None:
      print("Could not parse cpfrom command at line " + \
        str(self.line_ct_stack[0]) + ".")
      return "fail"
  
    path = self.path_expand(m.group(2))
    if path == None:
      print("Ignoring: \n\tcpfrom " + line)
      return "fail"
    self.simh.os8_pip_from (m.group(1), path, m.group(4))
    return "success"


  #### copy_command ###############################################
  # Simple script interface to create a copy of a file.

  def copy_command (self, line, script_file):
    m = re.match(_two_args_re, line)
    if m == None or m.group(1) == None or m.group(2) == None: 
      print("Could not copy command: " + line)
      return "fail"
    from_path = self.path_expand(m.group(1))      
    to_path = self.path_expand(m.group(2))

    if from_path == None or to_path == None:
      print("Ignoring: \n\t copy " + line)
      return "fail"

    print("copy command: \n\tfrom: " + from_path + ", \n\tto: " + to_path)
    
    if (not os.path.isfile(from_path)):
        print("At line " + str(self.line_ct_stack[0]) + \
          ": Required copy input file: " + from_path + " not found.")
        return "fail"

    save_if_needed(to_path)
    
    try:
      shutil.copyfile(from_path, to_path)
    except shutil.Error as e:
      print("copy command failed with error: " + str(e))
      return "fail"
    except IOError as e:
      print("copy command failed with IOError: " + str(e))
      return "fail"
    return "success"


  #### resume_command #############################################
  # Call the os8_resume in simh to resume OS/8.

  def resume_command (self, line, script_file):
    if self.verbose:
      print("Resuming OS/8 at line " + str(self.line_ct_stack[0]) + ".")

    self.simh.os8_restart()
    return "success"


  #### restart_command #############################################
  # Call the os8_restart in simh to resume OS/8.

  def restart_command (self, line, script_file):
    if self.verbose:
      print("Restarting OS/8 at line " + str(self.line_ct_stack[0]) + ".")

    self.simh.os8_restart()
    return "success"


  #### patch_command ##############################################
  # Read the named patch file and perform its actions.

  def patch_command (self, line, script_file):
    if not self.booted:
      print("Cannot run patch command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted.")
      return "die"
    path = self.path_expand(line)
    if path == None:
      print("Ignoring: \n\t" + "patch " + line)
      return "fail"
    if not os.path.isfile(path):
      print("At line " + str(self.line_ct_stack[0]) + \
        ": Patch file: " + path + " not found.")
      return "fail"

    self.run_patch_file (path)
    return "success"


  #### exit_command ###############################################
................................................................................
        intfound = True
        status = int(m.group(2))
      else:
        intfound = False
    if self.verbose:
      if intfound: stat_str = str(status)
      else: stat_str = line
      print("Calling sys.exit (" +  stat_str + ") at line: " + \
        str(self.line_ct_stack[0]) + ".")
    if intfound: sys.exit (status)
    else: sys.exit(line)


  #### print_command ###############################################
  # Print text from the running script
  # If verbose is set, say what line in the script containing
  # the print command.

  def print_command (self, line, script_file):
    if self.verbose:
      print("Line: " + str(self.line_ct_stack[0]) + ": " + line)
    else:
      print(self.print_expand(line))
    return "success"


  #### _command ###########################################
  # 

  def _command (self, line, script_file):
................................................................................
                "resume": self.resume_command,
                "restart": self.restart_command,
                "patch": self.patch_command}
  
    try:
      script_file = open(script_path, "r")
    except IOError:
      print(script_path + " not found.")
      return "fail"

    # Every time we start a new script
    # We append a new line number count of 0
    # onto our line_ct_stack
    self.line_ct_stack.insert(0, 0)
    if self.debug:
      print("New line_ct_stack: " + str(self.line_ct_stack))
  
    for line in script_file:
      line = self.basic_line_parse (line, script_file)
      if line == None: continue
      
      m = re.match(_comm_re, line)
      if m == None:
        print("Ignoring command line at line " + \
          str(self.line_ct_stack[0]) + ": " + line)
        continue
  
      if m.group(1) not in commands:
        print("Unrecognized script command at line " + \
          str(self.line_ct_stack[0]) + ": " + m.group(1))
        continue
  
      # print("arg: " + m.group(3))
      if m.group(3) == None: rest = ""
      else: rest = m.group(3)
      retval = commands[m.group(1)](rest, script_file)
      if retval == "die":
        print("\nFatal error encountered in " + script_path + \
          " at line " +  str(self.line_ct_stack[0]) + ":")
        print("\t" + line)
        sys.exit(-1)

    # Done.  Pop the line count off our line_ct_stack
    self.line_ct_stack.pop(0)
    if self.debug:
      print("popped line_ct_stack: " + str(self.line_ct_stack))
    
    return "success"


  #### end_command #####################################################
  
  def end_command (self, line, script_file):
    print("Unexpectedly encountered end command at line " + \
      str(self.line_ct_stack[0]) + ": " + line)
    return "fail"

  
  #### parse_odt #######################################################
  
  def parse_odt (self, com, line):
    if self.debug: print(line)
    
    if line == "\\c": return "break"
    match = _odt_parse.match(line)
    if match == None:
      print("Aborting because of bad ODT line: " + line)
      self.simh.os8_send_ctrl('C')
      return "err"
    loc = match.group(1)
    old_val = match.group(2)
    new_val = match.group(3)
    expect_val_str = "\s*[0-7]{4} "
    
    if self.debug:
      print("Loc: " + loc + ", old_val: " + old_val + ", new_val: " + \
          new_val)
    self.simh.os8_send_str (loc + "/")
    self.simh._child.expect(expect_val_str)
  
    if old_val.isdigit():          # We need to check old value
      found_val = self.simh._child.after.strip()
      if found_val != old_val:
        print("\tOld value: " + found_val + " does not match " +
            old_val + ". Aborting patch.")
        # Abort out of ODT back to the OS/8 Monitor
        self.simh.os8_send_ctrl('C')
        return "err"
  
    self.simh.os8_send_line (new_val)
    return "cont"

................................................................................

  #### futil_file ########################################################
  
  def futil_file (self, com, line):
    # Redundant re-parse of line but nobody else wants args right now.
    match = _com_split_parse.match(line)
    if match == None:
      print("Aborting because of mal-formed FUTIL FILE command: " + line)
      self.simh.os8_send_ctrl('C')
      return "err"
    fname = match.group(2)
    expect_futil_file_str = "\n" + fname + "\s+(.*)$"
    self.simh.os8_send_line (line)
    self.simh._child.expect(expect_futil_file_str)
    result = self.simh._child.after.strip()
    match = _com_split_parse.match(result)
    if match == None:
      print("Aborting because unexpected return status: " + result + \
          " from: " + line)
      self.simh.os8_send_ctrl('C')
      return "err"
    if match.group(2).strip() == "LOOKUP FAILED":
      print("Aborting because of FUTIL lookup failure on: " + fname)
      self.simh.os8_send_ctrl('C')
      return "err"
    else:
      return "cont"
  
  
  #### parse_futil #####################################################
................................................................................
  
    if line[0].isdigit():
      # Treat the line as ODT
      return self.parse_odt(com, line)
    else:
      match = _com_split_parse.match(line)
      if match == None:
        print("Ignoring failed FUTIL command parse of: " + line)
        return "cont"
      fcom = match.group(1)
      rest = match.group(2)
  
      if fcom not in futil_specials:
        # Blind faith and no error checking.
        self.simh.os8_send_line(line)
................................................................................
  def run_patch_file (self, pathname):
    sys.stdout.write ("Applying patch " + os.path.basename (pathname) + "...")
    sys.stdout.flush ()

    try:
      patch_file = open(pathname, "r")
    except IOError:
      print(pathname + " not found. Skipping.")
      return "fail"
  
    special_commands = {
      "ODT": self.parse_odt,
      "R": None,               # Get next parser.
      "FUTIL": self.parse_futil
    }
................................................................................
          self.simh.os8_send_ctrl('C')
        elif retval == "err":
          patch_file.close()
          return "fail"
      elif line[0] == '.':        # New OS/8 Command
        match = _com_os8_parse.match(line)
        if match == None:
          print("Aborting patch on failed OS/8 command parse of: " + line)
          return "fail"
        com = match.group(1)
        rest = match.group(2)
  
        if com in special_commands:
          if com == "R":
            # Run command is special.  Take arg as the command and run it.
................................................................................
            com = rest
          inside_a_command = True
          the_command = com
          the_command_parser = special_commands[com]
  
        # We carefully separate com and args
        # But don't make much use of that yet.
        if self.verbose and self.debug: print(line)
        self.simh.os8_send_cmd ("\\.", line[1:])  # Skip Prompt.
  
    patch_file.close()
  
    print("Success.")
    return "success"


  #### skip_patch ######################################################
  # Returns true if the given filename matches one of the regex string
  # keys of the given skips dict and the flag value for that key is set.
  # See skips definition in make_patch, which calls this.
................................................................................
  # binary and optional listing files.
  
  def call_pal8 (self, source, binary):
    pal8_replies = ["ERRORS DETECTED: ", "BE\s+\S+", "CF\s+\S+", "DE\s+\S+", "DF", "IC\s+\S+", "ID\s+\S+",
                    "IE\s+\S+", "II\s+\S+", "IP\s+\S+", "IZ\s+\S+", "LD\s+\S+", "LG\s+\S+", "PE\s+\S+",
                    "PH\s+\S+", "RD\s+\S+", "SE\s+\S+", "UO\s+\S+", "US\s+\S+", "ZE\s+\S+", "\S+ NOT FOUND"]
  
    if self.verbose: print("Assembling " + source)
    com_line = binary + "<" + source
    self.simh.os8_send_cmd ("\\.", "R PAL8")
    # Did the command successfully run and enter the command decoder?
    reply = self.simh._child.expect (self.simh._cd_replies)
    if reply != 0:
      print("PAL8 failed to start at line " + str(self.line_ct_stack[0]))

      return "fail"

    self.simh.os8_send_line (com_line)
    err_count = 0
    reply = self.simh._child.expect (pal8_replies)
    executed_line = self.simh._child.before.strip()
    reply_str = self.simh._child.after.strip()
    if reply == 0:
      self.simh._child.expect("\d+")
      err_count = int(self.simh._child.after.strip())
      reply_str += " " + self.simh._child.after.strip()
    if reply > 0 or err_count > 0:
      print("PAL8 Error: ")
      print("\t*" + executed_line)
      print("\t" + reply_str)
      self.simh.os8_send_ctrl ('c')      # exit PAL8 Just in case.
      # We could do something better than just dying, I expect.
      return "fail"
    # self.simh.os8_send_ctrl ('[')      # exit PAL8
    return "success"


................................................................................
  # I tried to avoid including this command but sometimes you just
  # have to reconfigure subtle bits of device drivers.
  # We assume we can call a simh command at any time, but
  # doing so puts us in the simh context that persists until we
  # issue a boot or go command.
  
  def simh_command (self, line, script_file):
    print("simh command is disabled. Line " + \
      str(self.line_ct_stack[0]) + " ignored.")
    return "fail"
    if self.verbose: print(line)
    self.simh.send_cmd(line)
    return "success"


  #### umount_command ##################################################
  def umount_command (self, line, script_file):
    detach_comm = "det " + line
    if self.verbose: print("line: " + \
        str(self.line_ct_stack[0]) + ": " + detach_comm)
    self.simh.send_cmd(detach_comm)
    return "success"


  #### make_scratch ####################################################
  # Create a copy of the contents of image file using the python
  # method to create a secure, named temp filename.
................................................................................
  # and an extension which we use.
  # After copying the source image, the file is closed and the name
  # of the scratch file is returned.
  def make_scratch (self, base_imagename, extension):
    try:
      src_image = open(base_imagename+extension, "rb")
    except IOError:
      print("Open of imagefile " + base_imagename + extension + " failed.")
      return None
      
    dest_image = tempfile.NamedTemporaryFile(mode='w+b', \
                                             prefix=base_imagename+'-temp-', \
                                             suffix=extension, \
                                             delete=False)
    destname = dest_image.name
    if self.debug: print("Temp file name is: " + destname)

    try:
      shutil.copyfileobj(src_image, dest_image)
    except shutil.Error as e:
      print("Copy of imagefile " + base_imagename + extension + \
        " to scratch failed with error: " + str(e))
      return None
    except IOError as e:
      print("Copy of imagefile " + base_imagename + extension + \
          ", failed with IOError: " + str(e))

      return None
    src_image.close()
    dest_image.close()
    self.scratch_list.append(destname)
    return destname
    

................................................................................
  #
  # If the mount command fails for any reason, we presume
  # it is a fatal error and abort the script.
  
  def mount_command (self, line, script_file):
    m = re.match(_mount_re, line)
    if m == None:
      print("At line " + str(self.line_ct_stack[0]) + \
        ", could not parse mount.  Ignoring: {" + line + "}.")
      return "die"
    simh_dev = m.group(1)
    unit = m.group(2)
    rest = m.group(3)
    parts = rest.split()
    if len(parts) == 0:
      print("At line " + str(self.line_ct_stack[0]) + \
        ": No image name specified in: {" + line + "}")
      return "die"
    ro_arg = ""
    imagename = self.path_expand(parts[0])
    if imagename == None: return "die"
    
    dot = imagename.rindex(".")
    base_imagename = imagename[:dot]
................................................................................
    # Case of additional arguments.
    if len (parts) > 1:
      # Perform must_exist before scratch
      if "new" in parts[1:]:
        save_if_needed(imagename)
      if "must_exist" in parts[1:] or "required" in parts[1:]:
          if not os.path.exists(imagename):
            print("At line " + str(self.line_ct_stack[0]) + ", " + \
                imagename + " must exist but was not found. Not mounting.")
            return "die"
      if "scratch" in parts[1:]:
        copy_imagename = self.make_scratch(base_imagename, extension)
        if copy_imagename == None: return "die"
        imagename = copy_imagename
        
      if "readonly" in parts[1:] or "ro" in parts[1:]:
        if copy_imagename != "":
          print("At line " + str(self.line_ct_stack[0]) + \
            ": You don't really need to set readonly on a scratch copy.")
        ro_arg = "-r "
      if "no_overwrite" in parts[1:] or "preserve" in parts[1:]:
        if copy_imagename != "":
          print("Ignoring preserve option at line " + \
              str(self.line_ct_stack[0]) + \
              " because scratch option is present.")
        else:
          next_tape = 0
          while os.path.isfile(imagename):
            print("Found: " + imagename)
            next_tape += 1
            imagename =  base_imagename + "-" + str(next_tape) + extension
    if unit == None or unit == "":
      print("Need unit number for: " + line)
      return "die"
  
    if simh_dev not in _os8_from_simh_dev:
      print("At line " + str(self.line_ct_stack[0]) + \
          ": Unrecognized simh dev: " + simh_dev)
      return "die"
    os8dev = _os8_from_simh_dev[simh_dev]
  
    attach_comm = "att " + ro_arg + simh_dev + unit + " " + imagename
  
    if self.verbose:
      print("Line " + str(self.line_ct_stack[0]) + ": mount: " + \
          attach_comm)
    self.simh.send_cmd(attach_comm)
    return "success"


  #### boot_command ####################################################
  #
  # Check to see if the device to be booted has something attached.
................................................................................
  def boot_command (self, line, script_file):
    # First confirm something is attached to boot from.
    ucname = line.upper()
    boot_replies = [ucname + "\s+(.+)\r", "Non-existent device"]
    self.simh.send_cmd("show " + line)
    retval = self.simh._child.expect(boot_replies)
    if retval == 1:
      print("Attempt to boot non-existent device: " + line)
      return "die"
    m = re.match("^(\S+)\s(\S+),\s+(attached to |not attached)(\S+)?,\s+(.+)\r",
                 self.simh._child.after)
    if m == None:
      print("Could not determine if device " + line + " is attached.")
      return "die"

    # Caution match group we want ends with a space.
    if m.group(3) != "attached to ":
      print("Attempt to boot on non-attached device: " + line)
      return "die"
    
    boot_comm = "boot " + line
    if self.verbose:
      print("Line " + str(self.line_ct_stack[0]) + ": " + boot_comm)
    self.simh.send_cmd(boot_comm)
    self.booted = True
    return "success"


  #### os8_command #####################################################
  
  def os8_command (self, line, script_file):
    if not self.booted:
      print("Cannot run os8 command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted.")
      return "die"

    os8_comm = line
    if self.verbose: print("Line: " + \
       str(self.line_ct_stack[0]) + ": os8_command: " + os8_comm)

    # Resume OS/8 if necessary.
    if self.simh._context == "simh":
      self.resume_command(line, script_file)

    self.simh.os8_send_cmd ("\\.", os8_comm, self.debug)
    return "success"
................................................................................
  # The "pal8" script command comes in two forms:
  # The two argument form where the PAL8 status is printed on the fly
  # and the 3 argument form where all status goes into the listing file.
  # We do the 3 argument form with a simple "os8" script command.
  
  def pal8_command (self, line, script_file):
    if not self.booted:
      print("Cannot run pal8 command at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted.")
      return "die"

    m_2form = re.match (_two_arg_pal_re, line)
    if m_2form != None:

      # Resume OS/8 if necessary.
      if self.simh._context == "simh":
................................................................................
      # Call the 2arg pal8 code that works hard at error analysis.
      return self.call_pal8 (m_2form.group(4), m_2form.group(1))
    else:
      m_3form = re.match (_three_arg_pal_re, line)
      if m_3form != None:
        # Just run the OS/8 command.
        os8_comm = "pal8 " + line
        if self.verbose:
          print("Line: " + str(self.line_ct_stack[0]) + \
              ": Calling 3-arg pal8 command: " + os8_comm)
        self.simh.os8_send_cmd ("\\.", os8_comm)
      else:
        print("At line " + str(self.line_ct_stack[0]) + \
          ": Unrecognized pal8 form: {" + line + "}.")
        return "fail"
    return "success"


  #### begin_command ###################################################
  
  def begin_command (self, line, script_file):
    if not self.booted:
      print("Cannot execute begin subcommand block at line " + \
        str(self.line_ct_stack[0]) + ". OS/8 has not been booted.")
      return "die"

    sub_commands = {"fotp": self.fotp_subcomm, "build": self.build_subcomm,
                    "absldr": self.absldr_subcomm,
                    "cdprog": self.cdprog_subcomm}
  
    m = re.match(_comm_re, line)
    if m == None:
      print("Could not parse sub-command at line " + \
        str(self.line_ct_stack[0]) + ": " + line)
    if m.group(1) not in sub_commands:
      print("Ignoring unrecognized sub-command at line " + \
        str(self.line_ct_stack[0]) + ": " + m.group(1))
      print("Ignoring everything to next end.")
      self.ignore_to_subcomm_end(line, script_file, "")
      return "fail"
    else:
      # Resume OS/8 if necessary.
      if self.simh._context == "simh":
        self.resume_command(line, script_file)

................................................................................
  
  def build_subcomm (self, old_line, script_file):
    # A race condition results if we send ^C when we are already at
    # Monitor level.  So need_exit gets set to False, when we know
    # we have already exited build, and are at the monitor prompt.
    need_exit = True
    os8_comm = "RU " + old_line
    if self.verbose:
      print("Line " + str(self.line_ct_stack[0]) + ": " + os8_comm)

    prompt_str = "\n\\$$"
    if self.debug:
      print("sending to simh: " + os8_comm)
      print(" and expecting prompt: '\\n\\\\$$'")
    self.simh.os8_send_cmd ("\\.", os8_comm)
    self.simh._child.expect(prompt_str)
    
    for line in script_file:
      # if self.debug:
      #  print("line: " + line)
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      m = re.match(_comm_re, line)
      if m == None:
        print("Ignoring mal-formed build sub-command at line " + \
          str(self.line_ct_stack[0]) + ": " + line)
        continue
  
      build_sub = m.group(1)
      rest = m.group(3)
      if rest == None: rest = ""
      
      if build_sub not in _build_comm_regs:
        print("Unrecognized BUILD command at line " + \
            str(self.line_ct_stack[0]) + ": " + build_sub)
        continue
  
      if build_sub == "end":
        if rest == "":
          print("Warning! end statement encountered inside build with no argument at line " + \
              str(self.line_ct_stack[0]) + ".\nExiting build.")
          return "fail"
        elif rest != "build": 
          print("Warning! Mismatched begin/end blocks in BUILD at line " + \
              str(self.line_ct_stack[0]) + ".\nEncountered end: {" + \
              rest + "}. Exiting BUILD.")
          return "fail"
        
        if self.verbose:
          print("Line " + str(self.line_ct_stack[0]) + ": end BUILD")
        if self.debug:
          print("before: " + self.simh._child.before.strip())
          print("after: " + self.simh._child.after.strip())
        # Return to monitor level unless need_exit == False.
        if need_exit:
          self.simh.os8_send_ctrl ('c')

        return "success"
        
      build_re = _build_comm_regs[build_sub]
  
      if build_re != None:
        m2 = re.match(build_re, rest)
        if m2 == None:
          print("Ignoring mal-formed BUILD at line " + \
              str(self.line_ct_stack[0]) + ": " + build_sub + \
              " command: " + rest)
          continue
      
        if build_sub == "BUILD":
          if m2.group(1) == None or m2.group(1) == "":
            print("Missing source of OS8.BN. Ignoring BUILD command at line " + \
                str(self.line_ct_stack[0]) + ".")
            continue
          else: kbm_arg = m2.group(1)

          if m2.group(3) == None or m2.group(3) == "":
            print("Missing sorce of CD.BN. Ignoring BUILD command at line " + \
                str(self.line_ct_stack[0]) + ".")
            continue
          else: cd_arg = m2.group(3)
          
          if self.verbose:
            print("Line " + str(self.line_ct_stack[0]) + \
                 ": BUILD KBM: " + kbm_arg + ", CD: " + cd_arg)
          if self.debug:
            print("sending to simh: BUILD")
          self.simh.os8_send_line ("BUILD")

          build_build_replies = ["LOAD OS/8: "]
          build_build_replies.extend(_build_replies)
          
          if self.debug:
            print("expecting: " + str(build_build_replies))
          reply = self.simh._child.expect(build_build_replies)
          if self.debug:
            print("reply: " + str(reply))
            print("before: " + self.simh._child.before.strip())
            print("after: " + self.simh._child.after.strip())
          if reply != 0:
            print("No prompt for LOAD OS/8 in BUILD command within BUILD at line " + \
              str(self.line_ct_stack[0]) + ".")
            print("Instead got: {" + self.simh._child.after + "}.")
            print("Exiting BUILD.")
            return "die"
          if self.debug:
            print("sending to simh: " + kbm_arg)
          self.simh.os8_send_line (kbm_arg)

          build_build_replies = ["LOAD CD: "]
          build_build_replies.extend(_build_replies)
          
          if self.debug:
            print("expecting: " + str(build_build_replies))
          reply = self.simh._child.expect(build_build_replies)
          if self.debug:
            print("reply: " + str(reply))
            print("before: " + self.simh._child.before.strip())
            print("after: " + self.simh._child.after.strip())
          if reply != 0:
            print("No prompt for LOAD CD in BUILD command within BUILD at line " + \
              str(self.line_ct_stack[0]) + ".")
            print("Instead got: {" + self.simh._child.after + "}.")
            print("Exiting BUILD.")
            return "die"
          if self.debug:
            print("sending to simh: " + cd_arg)
          self.simh.os8_send_line (cd_arg)

          # Done with BUILD command dialog within BUILD.SV
          # Get that BUILD.SV prompt.
          if self.debug:
            print("Expecting prompt: '\\n\\\\$$'")
          self.simh._child.expect(prompt_str)
          if self.debug:
            print("Resume BUILD.SV command loop.")
          continue

      comm = build_sub + " " + rest
      if self.verbose:
        print("Line " + str(self.line_ct_stack[0]) + ": BUILD-> " + comm)

      if self.debug:
        print("sending to simh: " + comm)
      self.simh.os8_send_line (comm)
      if self.debug:
        print("expecting: " + str(_build_replies))
      reply = self.simh._child.expect(_build_replies)
      if self.debug:
        print("reply: " + str(reply))
        print("before: " + self.simh._child.before.strip())
        print("after: " + self.simh._child.after.strip())
      if reply > 3:
        print("BUILD error at line " + str(self.line_ct_stack[0]) + \
          " with command " + self.simh._child.before.strip())
        print("\t" + self.simh._child.after.strip())
        self.simh.os8_send_ctrl ('c')
      # Special case "BOOT" sub-command: May ask, "WRITE ZERO DIRECT?"
      if build_sub == "BOOT":
        if reply == 2:
          if self.debug:
            print("Boot received \"WRITE ZERO DIRECT?\"")
            print("sending to simh: Y")
          self.simh.os8_send_line("Y")
          if self.debug:
            print("Expecting \"SYS BUILT\"")
          reply = self.simh._child.expect("SYS BUILT")
          if self.debug:
            print("ZeroDir: reply: " + str(reply))
            print("before: " + self.simh._child.before.strip())
            print("after: " + self.simh._child.after.strip())
          need_exit = False
        elif reply == 0:
          reply = self.simh._child.expect("SYS BUILT")
          if self.debug:
            print("$: reply: " + str(reply))
            print("before: " + self.simh._child.before.strip())
            print("after: " + self.simh._child.after.strip())
          need_exit = False
        elif reply == 1:
          reply = self.simh._child.expect("\\.")
          if self.debug:
            print("SysBuilt: reply: " + str(reply))
            print("before: " + self.simh._child.before.strip())
            print("after: " + self.simh._child.after.strip())
    print("Warning end of file encountered with no end of BUILD command block at line " + \
      str(self.line_ct_stack[0]) + ".")
    return "fail"
  
  #### cdprog_subcomm ##################################################
  # Cycle through OS/8 command decoder with the command specified
  # in the argument.
  
  def cdprog_subcomm (self, old_line, script_file):
    os8_comm = "RU " + old_line
    end_str = "cdprog " + old_line
    if self.verbose:
      print("Line: " + str(self.line_ct_stack[0]) + ": " + os8_comm)
    self.simh.os8_send_cmd ("\\.", os8_comm)
    
    for line in script_file:
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      # Test for special case, "end" and act on it if present.
      m = re.match(_comm_re, line)
      if m != None and m.group(1) != None and m.group(1) != "" and m.group(1)  == "end":
        rest = m.group(3)
        retval = "fail"  # Return fail unless proven successful.
        if rest == None or rest == "":
          print("Warning! end statement encountered inside cdprog " + \
              "with no argument at line " + \
              str(self.line_ct_stack[0]) + ".")
          print("Expecting: {" + end_str + "}.")
        elif rest != end_str:
          print("Warning! Mismatched begin/end blocks in cdprog at line " + \
            str(self.line_ct_stack[0]) + ".\n")
          print("Expecting: {" + end_str + "}. Got: {" + rest + "}.\n")
        else:
          retval = "success"
          if self.verbose:
            print("Line " + str(self.line_ct_stack[0]) + ": end " + end_str)
        if retval == "fail":
          print("Exiting cdprog, possibly earlier than expected at line " + \
            str(self.line_ct_stack[0]) + ".")
        self.simh.os8_send_ctrl ('[')
        return retval
  
      # We could do some basic OS/8 command decoder synax checking here.
      comm = line
      if self.verbose:
        print("Line: " + str(self.line_ct_stack[0]) + ": * " + line)
      self.simh.os8_send_cmd ("\\*", line)
    print("Warning end of file encountered at line " + \
        str(self.line_ct_stack[0]) + \
        " with no end of cdprog command block.")
    self.simh.os8_send_ctrl ('[')
    return "fail"

  
  #### fotp_subcomm ####################################################
  
  def fotp_subcomm (self, old_line, script_file):
    os8_comm = "RU " + old_line
    if self.verbose:
      print("Line: " + str(self.line_ct_stack[0]) + ": " + os8_comm)
    self.simh.os8_send_cmd ("\\.", os8_comm)
    
    for line in script_file:
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      # Test for special case, "end" and act on it if present.
      m = re.match(_comm_re, line)
      if m != None and m.group(1) != None and m.group(1) != "" and m.group(1)  == "end":
        rest = m.group(3)
        if rest == None or rest == "":
          print("Warning! end statement encountered inside fotp " + \
              "with no argument at line " + \
              str(self.line_ct_stack[0]) + ".")
          return "fail"
        elif rest != "fotp":
          print("Warning! Mismatched begin/end blocks in FOTP at line " + \
              str(self.line_ct_stack[0]) + ".\nEncountered end: {" + \
              rest + "}. Exiting FOTP.")
          return "fail"

        if self.verbose:
          print("Line " + str(self.line_ct_stack[0]) + ": end FOTP")
        self.simh.os8_send_ctrl ('[')
        return "success"
  
      m = re.match(_fotp_re, line)
      if m == None:
        print("At line " + str(self.line_ct_stack[0]) + \
            ": ignoring mal-formed fotp file spec: {" + line + "}.")
        continue
  
      comm = line
      if self.verbose:
        print("Line: " + str(self.line_ct_stack[0]) + ": * " + line)
      self.simh.os8_send_cmd ("\\*", line)
    print("Warning end of file encountered at line " + \
        str(self.line_ct_stack[0]) +
        " with no end of FOTP command block.")
    return "fail"

  
  #### absldr_subcomm ##################################################
  # A clone of fotp_subcom.  Can we find a way to merge the common code?
  
  def absldr_subcomm (self, old_line, script_file):
    os8_comm = "RU " + old_line
    if self.verbose:
      print(" line: " + str(self.line_ct_stack[0]) + ": " + os8_comm)
    self.simh.os8_send_cmd ("\\.", os8_comm)
    
    for line in script_file:
      line = self.basic_line_parse(line, script_file)
      if line == None: continue
  
      # Test for special case, "end" and act on it if present.
      m = re.match(_comm_re, line)
      if m != None and m.group(1) != None and m.group(1) != "" and m.group(1)  == "end":
        rest = m.group(3)
        if rest == None or rest == "":
          print("Warning! end statement encountered inside ABSLDR " + \
              "with no argument at line " +
              str(self.line_ct_stack[0]) + ".")
          return "fail"
        elif rest != "absldr":
          print("Warning! Mismatched begin/end blocks in ABSLDR at " + \
              "line " + str(self.line_ct_stack[0]) + \
              ".\nEncountered end: {" + rest + "}. Exiting ABSLDR.")
          return "fail"
          
        if self.verbose:
          print("End ABSLDR at line " + str(self.line_ct_stack[0]) + ".")
        self.simh.os8_send_ctrl ('[')
        return "success"
  
      m = re.match(_absldr_re, line)
      if m == None:
        print("Ignoring mal-formed absldr file spec at line " + \
            str(self.line_ct_stack[0]) + ": {" + line + "}.")
        continue
  
      comm = line
      if self.verbose:
        print("Line : " + str(self.line_ct_stack[0]) + "* " + line)
      self.simh.os8_send_cmd ("\\*", line)
    print("Warning end of file encountered at line " + \
      str(self.line_ct_stack[0]) + "with no end of ABSLDR command block.")
    return "fail"


  #### check_exists ####################################################
  # Check existence of all files needed
  
  def check_exists (s, image_copyins):
    for copyin in image_copyins:
      image = copyin[1]
      image_path = dirs.os8mi + image
      if (not os.path.isfile(image_path)):
          print("Required file: " + image_path + " not found.")
          mkos8_abort(s)
      # else: print("Found " + image_path)
  
     
  #### Data Structures ################################################
  #
  # The make procedures use helper procedures
  # to confirm that the relevant input image file exists and
  # to perform the file copies.
................................................................................
  # Detaches dt0 and dt1 after using them.
  # copyin0 mounts on dt0.  copyin1 mounts on dt1.
  # Either copyin or both can be None
  
  def copyin_pair (s, copyin0, copyin1, debug):
    if debug:
      if copyin0:
        print("Copying: " + copyin0[1] + " to: " + copyin0[0] + "from dt0")
      else:
        print("copyin0 is empty.")

      if copyin1:
        print("Copying: " + copyin1[1] + " to: " + copyin1[0] + "from dt1")
      else:
        print("copyin1 is empty.")
      
    if not copyin0 and not copyin1: return   # Nothing to do.
  
    # The order of events here is a bit funky because we want
    # to use both DECtape drives but also
    # switch between SIMH and OS/8 as infrequently as possible.
  
    if copyin0: self.simh.send_cmd ("attach -r dt0 " + dirs.os8mi + copyin0[1])
    if copyin1: self.simh.send_cmd ("attach -r dt1 " + dirs.os8mi + copyin1[1])
  
    self.simh.os8_restart()
  
    if copyin0:
      if self.verbose: print(copyin0[2])
      if copyin0[3]:                    # We have specific files to do.
        for file_copyin in copyin0[3]:
          self.simh.os8_send_cmd ("\\.", "COPY " + file_copyin[0] + "<DTA0:" + file_copyin[1])
      else:
        self.simh.os8_send_cmd ("\\.", "COPY " + copyin0[0] + "<DTA0:*.*")
  
    if copyin1:
      if self.verbose: print(copyin1[2])
      if copyin1[3]:                    # We have specific files to do.
        for file_copyin in copyin1[3]:
          self.simh.os8_send_cmd ("\\.", "COPY " + file_copyin[0] + "<DTA1:" + file_copyin[1])
      else:
        self.simh.os8_send_cmd ("\\.", "COPY " + copyin1[0] + "<DTA1:*.*")
  
    self.simh.back_to_cmd("\\.")

Changes to lib/simh.py.

311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
...
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
...
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
...
515
516
517
518
519
520
521

522
523
524
525
526
527
528
529
...
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
...
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
...
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
...
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
....
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
  # system to OS/8 Keyboard Monitor context without either changing the
  # context in some way that might break the caller's needed state (e.g.
  # Ctrl-E, go 7600) or lose data (e.g. Ctrl-C) or fail entirely (e.g.
  # Enter.)  It's up to the caller to arrange this.

  def os8_send_cmd (self, prompt, line, debug=False, timeout=60):
    if self._context != 'os8': 
      print "OS/8 is not running. Cannot execute: " + line 
      return
    if debug:
      print "os8_send_cmd: expecting: " + prompt
      print "\tLast match before: {" + self._child.before + "}"
      print "\tLast match after: {" + self._child.after + "}"
    self._child.expect ("\n%s$" % prompt, timeout = timeout)
    self.os8_send_line (line)


  #### os8_send_ctrl ###################################################
  # Send a control character to OS/8 corresponding to the ASCII letter
  # given.  We precede it with the OS/8 keyboard delay, since we're
................................................................................
    self.os8_send_ctrl ('[')      # exit PIP


  #### pip_error_handler ###############################################
  # Common error handler for os8_pip_to and os8_pip_from

  def pip_error_handler(self, caller, reply):
    print "PIP error from inside " + caller + ": "
    print "\t" + self._child.before.strip()
    print "\t" + self._child.after.strip()
    
    # Was this error fatal or do we need to clean up?
    # Remember we subtract 1 from reply to get index into error tables.
    if not self._os8_fatal_check[reply - 1]:
      # Non fatal error.  Exit pip to the monitor
      self.os8_send_ctrl ('[')      # exit PIP

................................................................................
  # Entry context should be inside OS/8.  Exit context is inside OS/8.

  def os8_pip_to (self, path, os8name, option = None):
    if option == None: option = ""
    # If os8name is just a device, synthesize an upcased name from
    # the POSIX file basename.
    if not os.path.exists(path):
      print path + " not found. Skipping."
      return
    m = re.match(self._os8_file_re, os8name)
    if m != None and (m.group(2) == None or m.group(2) == ""):
        dest = self.mk_os8_name(os8name, path)
    else:
        dest = os8name

    did_conversion = False
    if option == "" or option == "/A":
      # Convert text file to SIMH paper tape format in current dir of path.
      if self.verbose: print "Format converting " + path
      bdir = pidp8i.dirs.build
      # Create uniquified temp path name.
      pt   = path + "-" + str(os.getpid()) + ".pt_temp"
      tool = os.path.join (bdir, 'bin', 'txt2ptp')
      subprocess.call (tool + ' < ' + path + ' > ' + pt, shell = True)
      did_conversion = True
    elif option not in self._valid_pip_options:
      print "Invalid PIP option: " + option + ". Ignoring: " + path + " to OS/8."

      return
    else:
      pt = path

    # TODO: Sacrificial extra character code goes here.

    # Paper tape created, so attach it read-only and copy it in.  We're
................................................................................
      colon = os8name.find(':')
      if colon == -1:                # No dev, just a name.
        path = path + "/" + os8name
      else:
        path = path + "/" + os8name[colon+1:]

    if option != "" and option not in self._valid_pip_options:

      print "Invalid PIP option: " + option + ". Ignoring os8_pip_from on: " + path
      return

    self.back_to_cmd ('\\.')
    self.send_cmd ('attach ptp ' + path)
    self.os8_restart ()
    
    self.os8_send_cmd ('\\.', 'R PIP')
................................................................................

    self.os8_send_ctrl ('[')      # exit PIP
    self.back_to_cmd ('\\.')
    self.send_cmd ('detach ptp')  # Clean flush of buffers.
    self.os8_restart ()

    if option == "" or option == "/A":
      if self.verbose: print "Format converting " + path
      # Convert text file to SIMH paper tape format
      bdir = pidp8i.dirs.build
      # Create uniquified temp path name.
      pf = path + "-" + str(os.getpid()) + ".pf_temp"
      os.rename(path, pf)
      tool = os.path.join (bdir, 'bin', 'ptp2txt')
      subprocess.call (tool + ' < ' + pf + ' > ' + path, shell = True)
................................................................................
      attached[m.group(4)] = filename
    return attached

  #### do_print_lines ###################################################
  # Debugging aid. Prints what we parsed out of _child.after.
  def do_print_lines (self, lines):
    for line in lines:
      print line

  #### simh_configure routines #########################################
  # These routines affect the state of device configuration in SIMH.
  # They are intended as robust ways to toggle between incompatible
  # configurations of SIMH:
  # Choice of TD8E or TC08 DECtape (SIMH td and dt devices).
  # Choice of RX01 or RX02 Floppy emulation.
................................................................................
  # For now, return True if the change was successful and False if not.


  def set_tape_config (self, to_tape):
    if to_tape == "dt": from_tape = "td"
    elif to_tape == "td": from_tape = "dt"
    else:
      print "Cannot set_tape_config for " + to_tape
      return False


    if self.verbose: print "Disable: " + from_tape + ", and enable: " + to_tape
    
    lines = self.do_simh_show(from_tape)
    from_status = self.parse_show_tape_dev(lines)

    if from_status == None:
      print "do_tape_change: Trouble parsing \'show " + from_tape + "\' output from simh. Giving up on:"

      self.do_print_lines (lines)
      return False


    if from_status == "disabled": print from_tape + " already is disabled."
    else:
      attached_from = self.parse_show_tape_attached(lines)
      if attached_from == None:
        print "do_tape_change: Trouble parsing \'show " + from_tape + "\' output from simh. Giving up on:"

        self.do_print_lines (lines)
        return False
      else:
        for unit in attached_from.keys():
          if attached_from[unit] != "":
            det_comm = "det " + from_tape + unit

            if self.verbose: print det_comm + "(Had: " + attached_from[unit] + ")"
            self.send_cmd(det_comm)
        self.send_cmd("set " + from_tape + " disabled")

    lines = self.do_simh_show(to_tape)
    to_status = self.parse_show_tape_dev(lines)

    if to_status == None:
      print "do_tape_change: Trouble parsing \'show " + to_tape + "\' output from simh. Giving up on:"

      self.do_print_lines (lines)
      return False
    elif to_status != "disabled": print to_tape + " already is enabled."

    else:
      self.send_cmd("set " + to_tape + " enabled")    

    # Test to confirm to_tape is now enabled.

    lines = self.do_simh_show(to_tape)
    to_status = self.parse_show_tape_dev(lines)

    if to_status == None:

      print "Failed enable of " + to_tape + ". Parse fail on \'show " + to_tape + "\'. Got:"
      self.do_print_lines (lines)
      return False
    elif to_status == "disabled":
      print "Failed enable of " + to_tape + ". Device still disabled."
      return False
    else: 
      return True


  #### parse_show_rx_dev ###############################################
  # Show the rx device configuration.
................................................................................
      to_rx = "rx8e"
      from_rx = "rx28"
    elif to_rx == "rx28": from_rx = "rx8e"
    elif to_rx == "rx02":
      to_rx = "rx28"
      from_rx = "rx8e"
    else:
      print "Cannot set_rx_config for " + to_rx
      return False
      

    if self.verbose: print "Switch rx driver: " + from_rx + ", to: " + to_rx
    lines = self.do_simh_show("rx")

    rx_type = self.parse_show_rx_dev (lines)
    if rx_type == None:
      print "do_rx_change: Trouble parsing \'show rx\' output from simh. Giving up on:"
      self.do_print_lines(lines)
      return False
    elif rx_type == "disabled":
      if self.verbose: print "rx is disabled. Enabling..."
      self.send_cmd("set rx enabled")
      # Retry getting rx info
      lines = self.do_simh_show("rx")
      rx_type = self.parse_show_rx_dev (lines)
      if rx_type == None:
        print "do_rx_change after re-enable: Trouble parsing \`show rx\` output from simh. Giving up on:"
        self.do_print_lines(lines)
        return False
      elif rx_type == "disabled":
        print "do_rx_change re-enable of rx failed. Giving up."
        return False

    if rx_type.lower() == to_rx:
      print "rx device is already set to " + to_rx
      return None
      
    attached_rx= self.parse_show_rx_attached(lines)
    if attached_rx == None:
      print "do_rx_change: Trouble parsing /'show rx\' from simh to find rx attachments. Got:"
      self.do_print_lines(lines)
    else:
      for unit in attached_rx.keys():
        if attached_rx[unit] != "":
          det_comm = "det rx" + unit

          if self.verbose: print det_comm + "(Had: " + attached_rx[unit] + ")"
          self.send_cmd(det_comm)

    self.send_cmd("set rx " + to_rx)

    # Test to confirm new setting of RX
    lines = self.do_simh_show("rx")
    rx_type = self.parse_show_rx_dev (lines)

    if rx_type == None:
      print "Failed change of rx to " + to_rx + ". Parse fail on \'show rx\'."

      return False
    elif rx_type.lower() != to_rx: 
      print "Failed change of rx to " + to_rx + ". Instead got: " + rx_type

      return False
    return True


  #### get_tti ##################################################
  # Returns an ordered list of files attached or None if disabled.
  def parse_show_tti (self, lines):
................................................................................

  #### do_tti_change ###################################################

  def set_tti_config (self, to_tti):
    if to_tti == "KSR": from_tti = "7b"
    elif to_tti == "7b": from_tti = "KSR"
    else:
      print "Cannot set_tti_config to " + to_tti
      return
    

    if self.verbose: print "Switch tti driver from: " + from_tti + ", to: " + to_tti

    lines = self.do_simh_show("tti")
    tti_type = self.parse_show_tti (lines)
    if tti_type == None:
      print "do_tti_change: Trouble parsing \'show tti\' output from simh. Giving up on:"
      self.do_print_lines(lines)
      return False
    elif tti_type == to_tti:
      print "tti device is already set to " + to_tti
      return None

    self.send_cmd("set tti " + to_tti)

    # Test to confirm new setting of tti
    lines = self.do_simh_show("tti")
    tti_type = self.parse_show_tti (lines)
    
    if tti_type == None:
      print "Failed change of tti to " + to_tti + ". Parse fail on \'show tti\'."

      return False
    elif tti_type != to_tti: 
      print "Failed change of tti to " + to_tti + ". Instead got: " + tti_type

      return False
    else:
      return True









|


|
|
|







 







|
|
|







 







|










|







|
>







 







>
|







 







|







 







|







 







|


>
|





|
>



>
|



|
>






>
|







|
>


|
>









>
|



|







 







|


>
|




|



|





|



|



|




|





>
|









|
>


|
>







 







|


>
|




|



|









|
>


|
>





311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
...
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
...
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
...
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
...
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
...
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
...
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
...
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
....
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
  # system to OS/8 Keyboard Monitor context without either changing the
  # context in some way that might break the caller's needed state (e.g.
  # Ctrl-E, go 7600) or lose data (e.g. Ctrl-C) or fail entirely (e.g.
  # Enter.)  It's up to the caller to arrange this.

  def os8_send_cmd (self, prompt, line, debug=False, timeout=60):
    if self._context != 'os8': 
      print("OS/8 is not running. Cannot execute: " + lin)
      return
    if debug:
      print("os8_send_cmd: expecting: " + prompt)
      print("\tLast match before: {" + self._child.before + "}")
      print("\tLast match after: {" + self._child.after + "}")
    self._child.expect ("\n%s$" % prompt, timeout = timeout)
    self.os8_send_line (line)


  #### os8_send_ctrl ###################################################
  # Send a control character to OS/8 corresponding to the ASCII letter
  # given.  We precede it with the OS/8 keyboard delay, since we're
................................................................................
    self.os8_send_ctrl ('[')      # exit PIP


  #### pip_error_handler ###############################################
  # Common error handler for os8_pip_to and os8_pip_from

  def pip_error_handler(self, caller, reply):
    print("PIP error from inside " + caller + ": ")
    print("\t" + self._child.before.strip())
    print("\t" + self._child.after.strip())
    
    # Was this error fatal or do we need to clean up?
    # Remember we subtract 1 from reply to get index into error tables.
    if not self._os8_fatal_check[reply - 1]:
      # Non fatal error.  Exit pip to the monitor
      self.os8_send_ctrl ('[')      # exit PIP

................................................................................
  # Entry context should be inside OS/8.  Exit context is inside OS/8.

  def os8_pip_to (self, path, os8name, option = None):
    if option == None: option = ""
    # If os8name is just a device, synthesize an upcased name from
    # the POSIX file basename.
    if not os.path.exists(path):
      print(path + " not found. Skipping.")
      return
    m = re.match(self._os8_file_re, os8name)
    if m != None and (m.group(2) == None or m.group(2) == ""):
        dest = self.mk_os8_name(os8name, path)
    else:
        dest = os8name

    did_conversion = False
    if option == "" or option == "/A":
      # Convert text file to SIMH paper tape format in current dir of path.
      if self.verbose: print("Format converting " + path)
      bdir = pidp8i.dirs.build
      # Create uniquified temp path name.
      pt   = path + "-" + str(os.getpid()) + ".pt_temp"
      tool = os.path.join (bdir, 'bin', 'txt2ptp')
      subprocess.call (tool + ' < ' + path + ' > ' + pt, shell = True)
      did_conversion = True
    elif option not in self._valid_pip_options:
      print("Invalid PIP option: " + option + ". Ignoring: " + path + \
          " to OS/8.")
      return
    else:
      pt = path

    # TODO: Sacrificial extra character code goes here.

    # Paper tape created, so attach it read-only and copy it in.  We're
................................................................................
      colon = os8name.find(':')
      if colon == -1:                # No dev, just a name.
        path = path + "/" + os8name
      else:
        path = path + "/" + os8name[colon+1:]

    if option != "" and option not in self._valid_pip_options:
      print("Invalid PIP option: " + option + \
          ". Ignoring os8_pip_from on: " + path)
      return

    self.back_to_cmd ('\\.')
    self.send_cmd ('attach ptp ' + path)
    self.os8_restart ()
    
    self.os8_send_cmd ('\\.', 'R PIP')
................................................................................

    self.os8_send_ctrl ('[')      # exit PIP
    self.back_to_cmd ('\\.')
    self.send_cmd ('detach ptp')  # Clean flush of buffers.
    self.os8_restart ()

    if option == "" or option == "/A":
      if self.verbose: print("Format converting " + path)
      # Convert text file to SIMH paper tape format
      bdir = pidp8i.dirs.build
      # Create uniquified temp path name.
      pf = path + "-" + str(os.getpid()) + ".pf_temp"
      os.rename(path, pf)
      tool = os.path.join (bdir, 'bin', 'ptp2txt')
      subprocess.call (tool + ' < ' + pf + ' > ' + path, shell = True)
................................................................................
      attached[m.group(4)] = filename
    return attached

  #### do_print_lines ###################################################
  # Debugging aid. Prints what we parsed out of _child.after.
  def do_print_lines (self, lines):
    for line in lines:
      print(line)

  #### simh_configure routines #########################################
  # These routines affect the state of device configuration in SIMH.
  # They are intended as robust ways to toggle between incompatible
  # configurations of SIMH:
  # Choice of TD8E or TC08 DECtape (SIMH td and dt devices).
  # Choice of RX01 or RX02 Floppy emulation.
................................................................................
  # For now, return True if the change was successful and False if not.


  def set_tape_config (self, to_tape):
    if to_tape == "dt": from_tape = "td"
    elif to_tape == "td": from_tape = "dt"
    else:
      print("Cannot set_tape_config for " + to_tape)
      return False

    if self.verbose:
      print("Disable: " + from_tape + ", and enable: " + to_tape)
    
    lines = self.do_simh_show(from_tape)
    from_status = self.parse_show_tape_dev(lines)

    if from_status == None:
      print("do_tape_change: Trouble parsing \'show " + from_tape + \
          "\' output from simh. Giving up on:")
      self.do_print_lines (lines)
      return False

    if from_status == "disabled":
      print(from_tape + " already is disabled.")
    else:
      attached_from = self.parse_show_tape_attached(lines)
      if attached_from == None:
        print("do_tape_change: Trouble parsing \'show " + from_tape + \
            "\' output from simh. Giving up on:")
        self.do_print_lines (lines)
        return False
      else:
        for unit in attached_from.keys():
          if attached_from[unit] != "":
            det_comm = "det " + from_tape + unit
            if self.verbose:
              print(det_comm + "(Had: " + attached_from[unit] + ")")
            self.send_cmd(det_comm)
        self.send_cmd("set " + from_tape + " disabled")

    lines = self.do_simh_show(to_tape)
    to_status = self.parse_show_tape_dev(lines)

    if to_status == None:
      print("do_tape_change: Trouble parsing \'show " + to_tape + \
          "\' output from simh. Giving up on:")
      self.do_print_lines (lines)
      return False
    elif to_status != "disabled":
      print(to_tape + " already is enabled.")
    else:
      self.send_cmd("set " + to_tape + " enabled")    

    # Test to confirm to_tape is now enabled.

    lines = self.do_simh_show(to_tape)
    to_status = self.parse_show_tape_dev(lines)

    if to_status == None:
      print("Failed enable of " + to_tape + \
          ". Parse fail on \'show " + to_tape + "\'. Got:")
      self.do_print_lines (lines)
      return False
    elif to_status == "disabled":
      print("Failed enable of " + to_tape + ". Device still disabled.")
      return False
    else: 
      return True


  #### parse_show_rx_dev ###############################################
  # Show the rx device configuration.
................................................................................
      to_rx = "rx8e"
      from_rx = "rx28"
    elif to_rx == "rx28": from_rx = "rx8e"
    elif to_rx == "rx02":
      to_rx = "rx28"
      from_rx = "rx8e"
    else:
      print("Cannot set_rx_config for " + to_rx)
      return False
      
    if self.verbose:
      print("Switch rx driver: " + from_rx + ", to: " + to_rx)
    lines = self.do_simh_show("rx")

    rx_type = self.parse_show_rx_dev (lines)
    if rx_type == None:
      print("do_rx_change: Trouble parsing \'show rx\' output from simh.  Giving up on:")
      self.do_print_lines(lines)
      return False
    elif rx_type == "disabled":
      if self.verbose: print("rx is disabled. Enabling...")
      self.send_cmd("set rx enabled")
      # Retry getting rx info
      lines = self.do_simh_show("rx")
      rx_type = self.parse_show_rx_dev (lines)
      if rx_type == None:
        print("do_rx_change after re-enable: Trouble parsing \`show rx\` output from simh. Giving up on:")
        self.do_print_lines(lines)
        return False
      elif rx_type == "disabled":
        print("do_rx_change re-enable of rx failed. Giving up.")
        return False

    if rx_type.lower() == to_rx:
      print("rx device is already set to " + to_rx)
      return None
      
    attached_rx= self.parse_show_rx_attached(lines)
    if attached_rx == None:
      print("do_rx_change: Trouble parsing /'show rx\' from simh to find rx attachments. Got:")
      self.do_print_lines(lines)
    else:
      for unit in attached_rx.keys():
        if attached_rx[unit] != "":
          det_comm = "det rx" + unit
          if self.verbose:
            print(det_comm + "(Had: " + attached_rx[unit] + ")")
          self.send_cmd(det_comm)

    self.send_cmd("set rx " + to_rx)

    # Test to confirm new setting of RX
    lines = self.do_simh_show("rx")
    rx_type = self.parse_show_rx_dev (lines)

    if rx_type == None:
      print("Failed change of rx to " + to_rx + \
          ". Parse fail on \'show rx\'.")
      return False
    elif rx_type.lower() != to_rx: 
      print("Failed change of rx to " + to_rx + ". Instead got: " + \
          rx_type)
      return False
    return True


  #### get_tti ##################################################
  # Returns an ordered list of files attached or None if disabled.
  def parse_show_tti (self, lines):
................................................................................

  #### do_tti_change ###################################################

  def set_tti_config (self, to_tti):
    if to_tti == "KSR": from_tti = "7b"
    elif to_tti == "7b": from_tti = "KSR"
    else:
      print("Cannot set_tti_config to " + to_tti)
      return
    
    if self.verbose:
      print("Switch tti driver from: " + from_tti + ", to: " + to_tti)

    lines = self.do_simh_show("tti")
    tti_type = self.parse_show_tti (lines)
    if tti_type == None:
      print("do_tti_change: Trouble parsing \'show tti\' output from simh. Giving up on:")
      self.do_print_lines(lines)
      return False
    elif tti_type == to_tti:
      print("tti device is already set to " + to_tti)
      return None

    self.send_cmd("set tti " + to_tti)

    # Test to confirm new setting of tti
    lines = self.do_simh_show("tti")
    tti_type = self.parse_show_tti (lines)
    
    if tti_type == None:
      print("Failed change of tti to " + to_tti + \
          ". Parse fail on \'show tti\'.")
      return False
    elif tti_type != to_tti: 
      print("Failed change of tti to " + to_tti + ". Instead got: " + \
          tti_type)
      return False
    else:
      return True


Changes to src/SIMH/PDP8/pdp8_dt.c.

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
   (floating point) time, to allow save and restore of the start times.
*/

t_bool dt_setpos (UNIT *uptr)
{
uint32 new_time, ut, ulin, udelt;
int32 mot = DTS_GETMOT (uptr->STATE);
int32 unum, delta;

new_time = sim_grtime ();                               /* current time */
ut = new_time - uptr->LASTT;                            /* elapsed time */
if (ut == 0)                                            /* no time gone? exit */
    return FALSE;
uptr->LASTT = new_time;                                 /* update last time */
switch (mot & ~DTS_DIR) {                               /* case on motion */







|







645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
   (floating point) time, to allow save and restore of the start times.
*/

t_bool dt_setpos (UNIT *uptr)
{
uint32 new_time, ut, ulin, udelt;
int32 mot = DTS_GETMOT (uptr->STATE);
int32 unum, delta = 0;

new_time = sim_grtime ();                               /* current time */
ut = new_time - uptr->LASTT;                            /* elapsed time */
if (ut == 0)                                            /* no time gone? exit */
    return FALSE;
uptr->LASTT = new_time;                                 /* update last time */
switch (mot & ~DTS_DIR) {                               /* case on motion */

Changes to src/SIMH/scp.c.

573
574
575
576
577
578
579

580
581
582
583
584
585
586
...
691
692
693
694
695
696
697

698
699
700
701
702
703
704
705














706
707
708
709
710
711
712
...
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
....
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
....
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
....
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
....
2562
2563
2564
2565
2566
2567
2568

2569
2570
2571
2572
2573
2574
2575
....
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
....
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
....
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
....
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
....
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
....
3333
3334
3335
3336
3337
3338
3339





3340
3341
3342
3343
3344
3345
3346
3347
....
3352
3353
3354
3355
3356
3357
3358

3359
3360

3361

3362
3363
3364
3365
3366

3367
3368
3369
3370
3371
3372
3373
....
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
....
4226
4227
4228
4229
4230
4231
4232




4233
4234
4235
4236
4237

4238
4239
4240
4241
4242
4243
4244
....
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
....
5132
5133
5134
5135
5136
5137
5138


5139
5140
5141
5142


5143
5144
5145
5146
5147
5148
5149
....
5992
5993
5994
5995
5996
5997
5998
5999

6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
....
6011
6012
6013
6014
6015
6016
6017

6018
6019
6020
6021
6022
6023
6024
6025
....
6700
6701
6702
6703
6704
6705
6706
6707
6708


6709
6710
6711
6712
6713
6714
6715
....
6899
6900
6901
6902
6903
6904
6905

6906
6907
6908
6909
6910
6911
6912
....
6952
6953
6954
6955
6956
6957
6958


6959
6960
6961
6962
6963
6964
6965
....
6967
6968
6969
6970
6971
6972
6973






6974
6975
6976
6977
6978
6979
6980
....
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
....
7288
7289
7290
7291
7292
7293
7294

7295
7296
7297
7298
7299
7300
7301
....
7538
7539
7540
7541
7542
7543
7544

7545
7546
7547
7548
7549
7550
7551
....
7716
7717
7718
7719
7720
7721
7722








































7723
7724
7725
7726
7727
7728
7729
....
7907
7908
7909
7910
7911
7912
7913

7914
7915
7916
7917
7918
7919
7920
....
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
....
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
.....
10691
10692
10693
10694
10695
10696
10697

10698
10699
10700
10701

10702
10703
10704
10705
10706
10707
10708
10709
10710
.....
12889
12890
12891
12892
12893
12894
12895





12896
12897
12898
12899
12900
12901
12902
.....
13650
13651
13652
13653
13654
13655
13656
13657



13658

13659
13660
13661
13662
13663
13664
13665
.....
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
.....
14505
14506
14507
14508
14509
14510
14511






























14512
14513
14514
14515
14516
14517
14518
14519
14520
14521

14522
14523





14524



14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542


14543
14544
14545
    t_addr low, t_addr high, DEVICE *dptr, UNIT *uptr);
t_stat ex_addr (FILE *ofile, int32 flag, t_addr addr, DEVICE *dptr, UNIT *uptr);
t_stat dep_addr (int32 flag, const char *cptr, t_addr addr, DEVICE *dptr,
    UNIT *uptr, int32 dfltinc);
void fprint_fields (FILE *stream, t_value before, t_value after, BITFIELD* bitdefs);
t_stat step_svc (UNIT *ptr);
t_stat expect_svc (UNIT *ptr);

t_stat shift_args (char *do_arg[], size_t arg_count);
t_stat set_on (int32 flag, CONST char *cptr);
t_stat set_verify (int32 flag, CONST char *cptr);
t_stat set_message (int32 flag, CONST char *cptr);
t_stat set_quiet (int32 flag, CONST char *cptr);
t_stat set_asynch (int32 flag, CONST char *cptr);
t_stat sim_show_asynch (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
................................................................................
    sim_int_step_description};

static const char *sim_int_expect_description (DEVICE *dptr)
{
return "Expect facility";
}


static UNIT sim_expect_unit = { UDATA (&expect_svc, 0, 0) };
DEVICE sim_expect_dev = {
    "INT-EXPECT", &sim_expect_unit, NULL, NULL, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL, 
    NULL, DEV_NOSAVE, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL,
    sim_int_expect_description};















#if defined USE_INT64
static const char *sim_si64 = "64b data";
#else
static const char *sim_si64 = "32b data";
#endif
#if defined USE_ADDR64
................................................................................
         {"IERR",    "Internal error"},
         {"MTRLNT",  "Invalid magtape record length"},
         {"LOST",    "Console Telnet connection lost"},
         {"TTMO",    "Console Telnet connection timed out"},
         {"STALL",   "Console Telnet output stall"},
         {"AFAIL",   "Assertion failed"},
         {"INVREM",  "Invalid remote console command"},
         {"NOTATT",  "Not attached"},
         {"EXPECT",  "Expect matched"},
         {"AMBREG",  "Ambiguous register name"},
         {"REMOTE",  "remote console command"},
         {"INVEXPR", "invalid expression"},
    };

const size_t size_map[] = { sizeof (int8),
................................................................................
      " Console Telnet connection timed out\n"
      "5 STALL\n"
      " Console Telnet output stall\n"
      "5 AFAIL\n"
      " Assertion failed\n"
      "5 INVREM\n"
      " Invalid remote console command\n"
      "5 NOTATT\n"
      " Not attached \n"
      "5 AMBREG\n"
      " Ambiguous register\n"
#define HLP_SHIFT       "*Commands Executing_Command_Files SHIFT"
      "3SHIFT\n"
      "++shift                    shift the command file's positional parameters\n"
#define HLP_CALL        "*Commands Executing_Command_Files CALL"
      "3CALL\n"
................................................................................
      " than SCPE_STEP, SCPE_OK, and SCPE_EXIT.\n\n"
      " ON Traps can specify any of these status values:\n\n"
      "++NXM, UNATT, IOERR, CSUM, FMT, NOATT, OPENERR, MEM, ARG,\n"
      "++STEP, UNK, RO, INCOMP, STOP, TTIERR, TTOERR, EOF, REL,\n"
      "++NOPARAM, ALATT, TIMER, SIGERR, TTYERR, SUB, NOFNC, UDIS,\n"
      "++NORO, INVSW, MISVAL, 2FARG, 2MARG, NXDEV, NXUN, NXREG,\n"
      "++NXPAR, NEST, IERR, MTRLNT, LOST, TTMO, STALL, AFAIL,\n"
      "++NOTATT, AMBREG\n\n"
      " These values can be indicated by name or by their internal\n"
      " numeric value (not recommended).\n"
      /***************** 80 character line width template *************************/
      "3CONTROL-C Trapping\n"
      " A special ON trap is available to describe action(s) to be taken\n"
      " when CONTROL_C (aka SIGINT) occurs during the execution of\n"
      " simh commands and/or command procedures.\n\n"
................................................................................
      "5File Existence Expressions\n"
      " File existence can be determined with:\n\n"
      "++{NOT} EXIST \"<filespec>\"\n\n"
      "++{NOT} EXIST <filespec>\n\n"
      " Specifies a true (false {NOT}) condition if the file exists.\n"
      "5File Comparison Expressions\n"
      " Files can have their contents compared with:\n\n"
      "++-D {NOT} \"<filespec1>\" == \"<filespec2>\" \n\n"
      " Specifies a true (false {NOT}) condition if the indicated files\n"
      " have the same contents.\n\n"
       /***************** 80 character line width template *************************/
#define HLP_EXIT        "*Commands Exiting_The_Simulator"
      "2Exiting The Simulator\n"
      " EXIT (synonyms QUIT and BYE) returns control to the operating system.\n"
      "3 Exit Status\n"
................................................................................
    fprintf (stderr, "Fatal timer initialization error\n");
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
sim_register_internal_device (&sim_scp_dev);
sim_register_internal_device (&sim_expect_dev);
sim_register_internal_device (&sim_step_dev);


if ((stat = sim_ttinit ()) != SCPE_OK) {
    fprintf (stderr, "Fatal terminal initialization error\n%s\n",
        sim_error_text (stat));
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
................................................................................
setenv ("SIM_REGEX_TYPE", "PCREPOSIX", 1);              /* Publish regex type */
#elif defined (HAVE_REGEX_H)
setenv ("SIM_REGEX_TYPE", "REGEX", 1);                  /* Publish regex type */
#endif
if (*argv[0]) {                                         /* sim name arg? */
    char *np;                                           /* "path.ini" */

    strncpy (nbuf, argv[0], PATH_MAX + 1);              /* copy sim name */
    if ((np = (char *)match_ext (nbuf, "EXE")))         /* remove .exe */
        *np = 0;
    np = strrchr (nbuf, '/');                           /* stript path and try again in cwd */
    if (np == NULL)
        np = strrchr (nbuf, '\\');                      /* windows path separator */
    if (np == NULL)
        np = strrchr (nbuf, ']');                       /* VMS path separator */
................................................................................
if (SCPE_BARE_STATUS(stat) == SCPE_OPENERR)
    stat = do_cmd (-1, "simh.ini");                     /* simh.ini proc cmd file */
if (*cbuf)                                              /* cmd file arg? */
    stat = do_cmd (0, cbuf);                            /* proc cmd file */
else if (*argv[0]) {                                    /* sim name arg? */
    char *np;                                           /* "path.ini" */
    nbuf[0] = '"';                                      /* starting " */
    strncpy (nbuf + 1, argv[0], PATH_MAX + 1);          /* copy sim name */
    if ((np = (char *)match_ext (nbuf, "EXE")))         /* remove .exe */
        *np = 0;
    strlcat (nbuf, ".ini\"", sizeof (nbuf));            /* add .ini" */
    stat = do_cmd (-1, nbuf) & ~SCPE_NOMESSAGE;         /* proc default cmd file */
    if (stat == SCPE_OPENERR) {                         /* didn't exist/can't open? */
        np = strrchr (nbuf, '/');                       /* stript path and try again in cwd */
        if (np == NULL)
................................................................................
            stat = do_cmd (-1, np) & ~SCPE_NOMESSAGE;   /* proc default cmd file */
            }
        }
    }
if (SCPE_BARE_STATUS(stat) == SCPE_OPENERR)             /* didn't exist/can't open? */
    stat = SCPE_OK;

if (sim_switches & SWMASK ('T'))                        /* Command Line -T switch */
    stat = sim_library_unit_tests ();                   /* run library unit tests */

if (SCPE_BARE_STATUS(stat) != SCPE_EXIT)
    process_stdin_commands (SCPE_BARE_STATUS(stat), argv);

detach_all (0, TRUE);                                   /* close files */
sim_set_deboff (0, NULL);                               /* close debug */
................................................................................
        break;
    }
return SCPE_OK;
}

t_stat help_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CTAB *cmdp;

GET_SWITCHES (cptr);                                    /* get switches */
if (sim_switches & SWMASK ('F'))
    flag = flag | SCP_HELP_FLAT;
if (*cptr) {
    cptr = get_glyph (cptr, gbuf, 0);
................................................................................

                    if ((shptr == NULL) || (shptr->help == NULL) || (*shptr->help == '\0'))
                        return SCPE_ARG;
                    return help_cmd_output (flag, shptr->help, NULL);
                    }
                return SCPE_ARG;
                }
            else
                return SCPE_2MARG;
            }
        if (cmdp->help) {
            if (strcmp (cmdp->name, "HELP") == 0) {
                DEVICE *dptr;
                int i;

                for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
................................................................................
                if (((cmdp->action == &exdep_cmd) || (0 == strcmp(cmdp->name, "BOOT"))) &&
                    sim_dflt_dev->help) {
                        sim_dflt_dev->help (stdout, sim_dflt_dev, sim_dflt_dev->units, 0, cmdp->name);
                        if (sim_log)
                            sim_dflt_dev->help (sim_log, sim_dflt_dev, sim_dflt_dev->units, 0, cmdp->name);
                    }
                }





            help_cmd_output (flag, cmdp->help, cmdp->help_base);
            }
        else { /* no help so it is likely a command alias */
            CTAB *cmdpa;

            for (cmdpa=cmd_table; cmdpa->name != NULL; cmdpa++)
                if ((cmdpa->action == cmdp->action) && (cmdpa->help)) {
                    sim_printf ("%s is an alias for the %s command:\n%s", 
................................................................................
                sim_printf ("No help available for the %s command\n", cmdp->name);
            }
        }
    else { 
        DEVICE *dptr;
        UNIT *uptr;
        t_stat r;


        if (0 == strcmp (gbuf, "DEVICE"))

            cptr = get_glyph (cptr, gbuf, 0);

        dptr = find_unit (gbuf, &uptr);
        if (dptr == NULL) {
            dptr = find_dev (gbuf);
            if (dptr == NULL)
                return SCPE_ARG;

            if (dptr->flags & DEV_DISABLE)
                sim_printf ("Device %s is currently disabled\n", dptr->name);
            }
        r = help_dev_help (stdout, dptr, uptr, flag, cptr);
        if (sim_log)
            help_dev_help (sim_log, dptr, uptr, flag | SCP_HELP_FLAT, cptr);
        return r;
................................................................................
   instr        =       input string
   tmpbuf       =       temp buffer
   maxstr       =       min (len (instr), len (tmpbuf))
   do_arg[10]   =       arguments

   Token "%0" represents the command file name.

   The input sequence "\%" represents a literal "%", and "\\" represents a
   literal "\".  All other character combinations are rendered literally.

   Omitted parameters result in null-string substitutions.
*/

void sim_sub_args (char *instr, size_t instr_size, char *do_arg[])
{
................................................................................
                                }
                            else
                                break;
                        }
                    ++ip;
                    }
                else {




                    get_glyph_nc (ip, gbuf, '%');           /* get the literal name */
                    ap = _sim_get_env_special (gbuf, rbuf, sizeof (rbuf));
                    ip += strlen (gbuf);
                    if (*ip == '%') 
                        ++ip;

                    }
                }
            if (ap) {                                   /* non-null arg? */
                char *expanded = NULL;

                if (expand_it) {
                    expanded = sim_filepath_parts (ap, parts);
................................................................................
size_t i;

for (i=1; i<arg_count-1; ++i)
    do_arg[i] = do_arg[i+1];
return SCPE_OK;
}

static
int sim_cmp_string (const char *s1, const char *s2)
{
long int v1, v2;
char *ep1, *ep2;

if (sim_switches & SWMASK ('F')) {      /* File Compare? */
    FILE *f1, *f2;
................................................................................
if (sim_switches & SWMASK ('P')) {
    CONST char *deflt = NULL;

    cptr = get_glyph_quoted (cptr, prompt, 0);          /* get prompt */
    if (prompt[0] == '\0')
        return sim_messagef (SCPE_2FARG, "Missing Prompt and Environment Variable Name\n");
    if ((prompt[0] == '"') || (prompt[0] == '\'')) {


        prompt[strlen (prompt) - 1] = '\0';
        memmove (prompt, prompt + 1, strlen (prompt));
        }
    deflt = get_glyph (cptr, varname, '=');             /* get environment variable name */


    if (deflt == NULL)
        deflt = "";
    if (*deflt) {
        strlcat (prompt, " [", sizeof (prompt));
        strlcat (prompt, deflt, sizeof (prompt));
        strlcat (prompt, "] ", sizeof (prompt));
        }
................................................................................
memset (&buf, 0, sizeof (buf));
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_clock_queue == QUEUE_LIST_END)
    fprintf (st, "%s event queue empty, time = %.0f, executing %s instructios/sec\n",
             sim_name, sim_time, sim_fmt_numeric (sim_timer_inst_per_sec ()));
else {
    const char *tim;


    fprintf (st, "%s event queue status, time = %.0f, executing %s instructions/sec\n",
             sim_name, sim_time, sim_fmt_numeric (sim_timer_inst_per_sec ()));
    accum = 0;
    for (uptr = sim_clock_queue; uptr != QUEUE_LIST_END; uptr = uptr->next) {
        if (uptr == &sim_step_unit)
            fprintf (st, "  Step timer");
        else
            if (uptr == &sim_expect_unit)
                fprintf (st, "  Expect fired");
................................................................................
                if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                    fprintf (st, "  %s", sim_dname (dptr));
                    if (dptr->numunits > 1)
                        fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                    }
                else
                    fprintf (st, "  Unknown");

        tim = sim_fmt_secs(((accum + uptr->time) / sim_timer_inst_per_sec ()) + (uptr->usecs_remaining / 1000000.0));
        if (uptr->usecs_remaining)
            fprintf (st, " at %d plus %.0f usecs%s%s%s%s\n", accum + uptr->time, uptr->usecs_remaining,
                                            (*tim) ? " (" : "", tim, (*tim) ? " total)" : "",
                                            (uptr->flags & UNIT_IDLE) ? " (Idle capable)" : "");
        else
            fprintf (st, " at %d%s%s%s%s\n", accum + uptr->time, 
                                            (*tim) ? " (" : "", tim, (*tim) ? ")" : "",
................................................................................
t_stat reason;

for (i = 0; i < start; i++) {
    if (sim_devices[i] == NULL)
        return SCPE_IERR;
    }
for (i = start; (dptr = sim_devices[i]) != NULL; i++) {
    if (sim_switches & SWMASK('P'))
        tmxr_add_debug (dptr);          /* Add TMXR debug to MUX devices */


    if (dptr->reset != NULL) {
        reason = dptr->reset (dptr);
        if (reason != SCPE_OK)
            return reason;
        }
    }
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i) {
................................................................................
}

/* Attach unit to file */

t_stat attach_unit (UNIT *uptr, CONST char *cptr)
{
DEVICE *dptr;


if (!(uptr->flags & UNIT_ATTABLE))                      /* not attachable? */
    return SCPE_NOATT;
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char)); /* alloc name buf */
if (uptr->filename == NULL)
................................................................................
                    return attach_err (uptr, SCPE_OPENERR); /* yes, error */
                uptr->fileref = sim_fopen (cptr, "wb+");/* open new file */
                if (uptr->fileref == NULL)              /* open fail? */
                    return attach_err (uptr, SCPE_OPENERR); /* yes, error */
                sim_messagef (SCPE_OK, "%s: creating new file\n", sim_dname (dptr));
                }
            }                                           /* end if null */


        }                                               /* end else */
    }
if (uptr->flags & UNIT_BUFABLE) {                       /* buffer? */
    uint32 cap = ((uint32) uptr->capac) / dptr->aincr;  /* effective size */
    if (uptr->flags & UNIT_MUSTBUF)                     /* dyn alloc? */
        uptr->filebuf = calloc (cap, SZ_D (dptr));      /* allocate */
    if (uptr->filebuf == NULL)                          /* no buffer? */
................................................................................
    sim_messagef (SCPE_OK, "%s: buffering file in memory\n", sim_dname (dptr));
    uptr->hwmark = (uint32)sim_fread (uptr->filebuf,    /* read file */
        SZ_D (dptr), cap, uptr->fileref);
    uptr->flags = uptr->flags | UNIT_BUF;               /* set buffered */
    }
uptr->flags = uptr->flags | UNIT_ATT;
uptr->pos = 0;






return SCPE_OK;
}

t_stat attach_err (UNIT *uptr, t_stat stat)
{
free (uptr->filename);
uptr->filename = NULL;
................................................................................
    return SCPE_IERR;
if (!(uptr->flags & UNIT_ATTABLE))                      /* attachable? */
    return SCPE_NOATT;
if (!(uptr->flags & UNIT_ATT)) {                        /* not attached? */
    if (sim_switches & SIM_SW_REST)                     /* restoring? */
        return SCPE_OK;                                 /* allow detach */
    else
        return SCPE_NOTATT;                             /* complain */
    }
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_OK;
if ((uptr->flags & UNIT_BUF) && (uptr->filebuf)) {
    uint32 cap = (uptr->hwmark + dptr->aincr - 1) / dptr->aincr;
    if (uptr->hwmark && ((uptr->flags & UNIT_RO) == 0)) {
        sim_messagef (SCPE_OK, "%s: writing buffer to file\n", sim_dname (dptr));
................................................................................
        WRITE_I (uptr->u4);
        WRITE_I (uptr->u5);                             /* [V3.0] more unit */
        WRITE_I (uptr->u6);
        WRITE_I (uptr->flags);                          /* [V2.10] flags */
        WRITE_I (uptr->dynflags);
        WRITE_I (uptr->wait);
        WRITE_I (uptr->buf);

        WRITE_I (uptr->capac);                          /* [V3.5] capacity */
        fprintf (sfile, "%.0f\n", uptr->usecs_remaining);/* [V4.0] remaining wait */
        WRITE_I (uptr->pos);
        if (uptr->flags & UNIT_ATT) {
            fputs (uptr->filename, sfile);
            if ((uptr->flags & UNIT_BUF) &&             /* writable buffered */
                uptr->hwmark &&                         /* files need to be */
................................................................................
        READ_I (uptr->u5);                              /* [V3.0+] more dev spec */
        READ_I (uptr->u6);
        READ_I (flg);                                   /* [V2.10+] unit flags */
        if (v40) {                                      /* [V4.0+] dynflags */
            READ_I (uptr->dynflags);
            READ_I (uptr->wait);
            READ_I (uptr->buf);

            }
        old_capac = uptr->capac;                        /* save current capacity */
        if (v35) {                                      /* [V3.5+] capacity */
            READ_I (uptr->capac);
            }
        if (v40) {
            READ_S (buf);
................................................................................
free (attnames);
free (attunits);
free (attswitches);
if (warned)
    sim_printf ("restore with the -Q switch to suppress warning messages\n");
return r;
}









































/* Run, go, boot, cont, step, next commands

   ru[n] [new PC]       reset and start simulation
   go [new PC]          start simulation
   co[nt]               start simulation
   s[tep] [step limit]  start simulation for 'limit' instructions
................................................................................
    }
if (sim_step) {                                         /* set step timer */
    if (sim_switches & SWMASK ('T'))                    /* stepping for elapsed time? */
        sim_activate_after (&sim_step_unit, (uint32)sim_step);/* wall clock based step */
    else
        sim_activate (&sim_step_unit, sim_step);        /* instruction based step */
    }

stop_cpu = FALSE;
sim_is_running = TRUE;                                  /* flag running */
fflush(stdout);                                         /* flush stdout */
if (sim_log)                                            /* flush log if enabled */
    fflush (sim_log);
sim_throt_sched ();                                     /* set throttle */
sim_start_timer_services ();                            /* enable wall clock timing */
................................................................................
sim_stop_timer_services ();                             /* disable wall clock timing */
sim_ttcmd ();                                           /* restore console */
sim_brk_clrall (BRK_TYP_DYN_STEPOVER);                  /* cancel any step/over subroutine breakpoints */
#ifdef SIGHUP
signal (SIGHUP, SIG_DFL);                               /* cancel WRU */
#endif
signal (SIGTERM, SIG_DFL);                              /* cancel WRU */
if (sim_log)                                            /* flush console log */
    fflush (sim_log);
if (sim_deb)                                            /* flush debug log */
    _sim_debug_flush ();
for (i = 1; (dptr = sim_devices[i]) != NULL; i++) {     /* flush attached files */
    for (j = 0; j < dptr->numunits; j++) {              /* if not buffered in mem */
        uptr = dptr->units + j;
        if (uptr->flags & UNIT_ATT) {                   /* attached, */
            if (uptr->io_flush)                         /* unit specific flush routine */
                uptr->io_flush (uptr);                  /* call it */
            else {
                if (!(uptr->flags & UNIT_BUF) &&        /* not buffered, */
                    (uptr->fileref) &&                  /* real file, */
                    !(uptr->dynflags & UNIT_NO_FIO) &&  /* is FILE *, */
                    !(uptr->flags & UNIT_RO))           /* not read only? */
                    fflush (uptr->fileref);
                }
            }
        }
    }
sim_cancel (&sim_step_unit);                            /* cancel step timer */
sim_throt_cancel ();                                    /* cancel throttle */
AIO_UPDATE_QUEUE;
UPDATE_SIM_TIME;                                        /* update sim time */
return r | ((sim_switches & SWMASK ('Q')) ? SCPE_NOMESSAGE : 0);
}

................................................................................
            }
        else {
            if (sim_fseek (uptr->fileref, (t_addr)(sz * loc), SEEK_SET)) {
                clearerr (uptr->fileref);
                reason = SCPE_IOERR;
                break;
                }
            sim_fread (&sim_eval[i], sz, 1, uptr->fileref);
            if ((feof (uptr->fileref)) &&
               !(uptr->flags & UNIT_FIX)) {
                reason = SCPE_EOF;
                break;
                }
            else if (ferror (uptr->fileref)) {
                clearerr (uptr->fileref);
................................................................................
            reason = uptr->action (uptr);
        else
            reason = SCPE_OK;
        }
    AIO_EVENT_COMPLETE(uptr, reason);
    bare_reason = SCPE_BARE_STATUS (reason);
    if ((bare_reason != SCPE_OK)     &&  /* Provide context for unexpected errors */

        (bare_reason != SCPE_STOP)   && 
        (bare_reason != SCPE_STEP)   && 
        (bare_reason != SCPE_EXPECT) &&
        (bare_reason != SCPE_EXIT)   && 

        (bare_reason != SCPE_REMOTE))
        reason = sim_messagef (SCPE_IERR, "\nUnexpected internal error while processing event for %s which returned %d - %s\n", sim_uname (uptr), reason, sim_error_text (reason));
    } while ((reason == SCPE_OK) && 
             (sim_interval <= 0) && 
             (sim_clock_queue != QUEUE_LIST_END) &&
             (!stop_cpu));

if (sim_clock_queue == QUEUE_LIST_END) {                /* queue empty? */
    sim_interval = noqueue_time = NOQUEUE_WAIT;         /* flag queue empty */
................................................................................
                if (eidx) {
                    if (sim_isprint (ebcdic2ascii[data[i+sidx]]))
                        ebcdicbuf[eidx++] = ebcdic2ascii[data[i+sidx]];
                    else
                        ebcdicbuf[eidx++] = '.';
                    }
                }





            outbuf[oidx] = '\0';
            strbuf[soff+sidx] = '\0';
            ebcdicbuf[eidx] = '\0';
            rad50buf[ridx] = '\0';
            _sim_debug_unit (reason, uptr, "%04X%-48s %s%s%s\n", i, outbuf, strbuf, ebcdicbuf, rad50buf);
            }
        if (same > 0) {
................................................................................
    if (!cptr || !*cptr) {
        pstring = helpPrompt (topic, prompt[topic->kids != 0], FALSE);

        cptr = read_line_p (pstring, cbuf, sizeof (cbuf), stdin);
        free (pstring);
        }

    if (!cptr)                              /* EOF, exit help */



        break;


    cptr = get_glyph (cptr, gbuf, 0);
    if (!strcmp (gbuf, "*")) {              /* Wildcard */
        displayFlatHelp (st, dptr, uptr, flag, topic, ap);
        gbuf[0] = '\0';                     /* Displayed all subtopics, go up */
        }
    if (!gbuf[0]) {                         /* Blank, up a level */
................................................................................
{
if (this_Stack == NULL)
    return FALSE;

if (this_Stack->pointer == this_Stack->size) {  /* If necessary, grow stack */
    this_Stack->size += STACK_GROW_AMOUNT;
    this_Stack->elements = (Stack_Element *)realloc (this_Stack->elements, this_Stack->size * sizeof(*this_Stack->elements));
    memset (&this_Stack->elements[this_Stack->size - STACK_GROW_AMOUNT], 0, STACK_GROW_AMOUNT * sizeof(*this_Stack->elements));
    }

this_Stack->elements[this_Stack->pointer].op = op;
strlcpy (this_Stack->elements[this_Stack->pointer].data, data, sizeof (this_Stack->elements[this_Stack->pointer].data));
++this_Stack->pointer;

if (op)
................................................................................
    return cptr;
    }

*value = sim_eval_postfix (postfix, stat);
delete_Stack (postfix);
return cptr;
}































/*
 * Compiled in unit tests for the various device oriented library 
 * modules: sim_card, sim_disk, sim_tape, sim_ether, sim_tmxr, etc.
 */

static t_stat sim_library_unit_tests (void)
{
int i;
DEVICE *dptr;

t_stat stat = SCPE_OK;






for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {



    switch (DEV_TYPE(dptr)) {
#if defined(USE_SIM_CARD)
        case DEV_CARD:
            stat = sim_card_test (dptr);
            break;
#endif
        case DEV_DISK:
            stat = sim_disk_test (dptr);
            break;
        case DEV_ETHER:
            stat = sim_ether_test (dptr);
            break;
        case DEV_TAPE:
            stat = sim_tape_test (dptr);
            break;
        default:
            break;
        }


    }
return stat;
}







>







 







>








>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<







 







<
<







 







|







 







|







 







>







 







|







 







|







 







|







 







|







 







<
<







 







>
>
>
>
>
|







 







>

|
>

>




|
>







 







|







 







>
>
>
>
|
|
|
|
|
>







 







<







 







>
>




>
>







 







|
>


|







 







>
|







 







|

>
>







 







>







 







>
>







 







>
>
>
>
>
>







 







|







 







>







 







>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>







 







|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|







 







>
|
|
|
|
>
|
|







 







>
>
>
>
>







 







|
>
>
>

>







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










>


>
>
>
>
>

>
>
>



|



|


|


|




>
>



573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
...
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
...
783
784
785
786
787
788
789

790
791
792
793
794
795
796
....
1799
1800
1801
1802
1803
1804
1805


1806
1807
1808
1809
1810
1811
1812
....
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
....
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
....
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
....
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
....
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
....
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
....
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
....
3306
3307
3308
3309
3310
3311
3312


3313
3314
3315
3316
3317
3318
3319
....
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
....
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
....
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
....
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
....
4310
4311
4312
4313
4314
4315
4316

4317
4318
4319
4320
4321
4322
4323
....
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
....
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
....
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
....
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
....
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
....
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
....
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
....
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
....
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
....
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
....
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
....
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
....
8055
8056
8057
8058
8059
8060
8061
8062
8063


















8064
8065
8066
8067
8068
8069
8070
....
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
.....
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
.....
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
.....
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
.....
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
.....
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
    t_addr low, t_addr high, DEVICE *dptr, UNIT *uptr);
t_stat ex_addr (FILE *ofile, int32 flag, t_addr addr, DEVICE *dptr, UNIT *uptr);
t_stat dep_addr (int32 flag, const char *cptr, t_addr addr, DEVICE *dptr,
    UNIT *uptr, int32 dfltinc);
void fprint_fields (FILE *stream, t_value before, t_value after, BITFIELD* bitdefs);
t_stat step_svc (UNIT *ptr);
t_stat expect_svc (UNIT *ptr);
t_stat flush_svc (UNIT *ptr);
t_stat shift_args (char *do_arg[], size_t arg_count);
t_stat set_on (int32 flag, CONST char *cptr);
t_stat set_verify (int32 flag, CONST char *cptr);
t_stat set_message (int32 flag, CONST char *cptr);
t_stat set_quiet (int32 flag, CONST char *cptr);
t_stat set_asynch (int32 flag, CONST char *cptr);
t_stat sim_show_asynch (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
................................................................................
    sim_int_step_description};

static const char *sim_int_expect_description (DEVICE *dptr)
{
return "Expect facility";
}

#define FLUSH_INTERVAL 30*1000000           /* Flush I/O buffers every 30 seconds */
static UNIT sim_expect_unit = { UDATA (&expect_svc, 0, 0) };
DEVICE sim_expect_dev = {
    "INT-EXPECT", &sim_expect_unit, NULL, NULL, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL, 
    NULL, DEV_NOSAVE, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL,
    sim_int_expect_description};

static const char *sim_int_flush_description (DEVICE *dptr)
{
return "Flush facility";
}

static UNIT sim_flush_unit = { UDATA (&flush_svc, UNIT_IDLE, 0) };
DEVICE sim_flush_dev = {
    "INT-FLUSH", &sim_flush_unit, NULL, NULL, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL, 
    NULL, DEV_NOSAVE, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL,
    sim_int_flush_description};

#if defined USE_INT64
static const char *sim_si64 = "64b data";
#else
static const char *sim_si64 = "32b data";
#endif
#if defined USE_ADDR64
................................................................................
         {"IERR",    "Internal error"},
         {"MTRLNT",  "Invalid magtape record length"},
         {"LOST",    "Console Telnet connection lost"},
         {"TTMO",    "Console Telnet connection timed out"},
         {"STALL",   "Console Telnet output stall"},
         {"AFAIL",   "Assertion failed"},
         {"INVREM",  "Invalid remote console command"},

         {"EXPECT",  "Expect matched"},
         {"AMBREG",  "Ambiguous register name"},
         {"REMOTE",  "remote console command"},
         {"INVEXPR", "invalid expression"},
    };

const size_t size_map[] = { sizeof (int8),
................................................................................
      " Console Telnet connection timed out\n"
      "5 STALL\n"
      " Console Telnet output stall\n"
      "5 AFAIL\n"
      " Assertion failed\n"
      "5 INVREM\n"
      " Invalid remote console command\n"


      "5 AMBREG\n"
      " Ambiguous register\n"
#define HLP_SHIFT       "*Commands Executing_Command_Files SHIFT"
      "3SHIFT\n"
      "++shift                    shift the command file's positional parameters\n"
#define HLP_CALL        "*Commands Executing_Command_Files CALL"
      "3CALL\n"
................................................................................
      " than SCPE_STEP, SCPE_OK, and SCPE_EXIT.\n\n"
      " ON Traps can specify any of these status values:\n\n"
      "++NXM, UNATT, IOERR, CSUM, FMT, NOATT, OPENERR, MEM, ARG,\n"
      "++STEP, UNK, RO, INCOMP, STOP, TTIERR, TTOERR, EOF, REL,\n"
      "++NOPARAM, ALATT, TIMER, SIGERR, TTYERR, SUB, NOFNC, UDIS,\n"
      "++NORO, INVSW, MISVAL, 2FARG, 2MARG, NXDEV, NXUN, NXREG,\n"
      "++NXPAR, NEST, IERR, MTRLNT, LOST, TTMO, STALL, AFAIL,\n"
      "++AMBREG\n\n"
      " These values can be indicated by name or by their internal\n"
      " numeric value (not recommended).\n"
      /***************** 80 character line width template *************************/
      "3CONTROL-C Trapping\n"
      " A special ON trap is available to describe action(s) to be taken\n"
      " when CONTROL_C (aka SIGINT) occurs during the execution of\n"
      " simh commands and/or command procedures.\n\n"
................................................................................
      "5File Existence Expressions\n"
      " File existence can be determined with:\n\n"
      "++{NOT} EXIST \"<filespec>\"\n\n"
      "++{NOT} EXIST <filespec>\n\n"
      " Specifies a true (false {NOT}) condition if the file exists.\n"
      "5File Comparison Expressions\n"
      " Files can have their contents compared with:\n\n"
      "++-F {NOT} \"<filespec1>\" == \"<filespec2>\" \n\n"
      " Specifies a true (false {NOT}) condition if the indicated files\n"
      " have the same contents.\n\n"
       /***************** 80 character line width template *************************/
#define HLP_EXIT        "*Commands Exiting_The_Simulator"
      "2Exiting The Simulator\n"
      " EXIT (synonyms QUIT and BYE) returns control to the operating system.\n"
      "3 Exit Status\n"
................................................................................
    fprintf (stderr, "Fatal timer initialization error\n");
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
sim_register_internal_device (&sim_scp_dev);
sim_register_internal_device (&sim_expect_dev);
sim_register_internal_device (&sim_step_dev);
sim_register_internal_device (&sim_flush_dev);

if ((stat = sim_ttinit ()) != SCPE_OK) {
    fprintf (stderr, "Fatal terminal initialization error\n%s\n",
        sim_error_text (stat));
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
................................................................................
setenv ("SIM_REGEX_TYPE", "PCREPOSIX", 1);              /* Publish regex type */
#elif defined (HAVE_REGEX_H)
setenv ("SIM_REGEX_TYPE", "REGEX", 1);                  /* Publish regex type */
#endif
if (*argv[0]) {                                         /* sim name arg? */
    char *np;                                           /* "path.ini" */

    strlcpy (nbuf, argv[0], PATH_MAX + 2);              /* copy sim name */
    if ((np = (char *)match_ext (nbuf, "EXE")))         /* remove .exe */
        *np = 0;
    np = strrchr (nbuf, '/');                           /* stript path and try again in cwd */
    if (np == NULL)
        np = strrchr (nbuf, '\\');                      /* windows path separator */
    if (np == NULL)
        np = strrchr (nbuf, ']');                       /* VMS path separator */
................................................................................
if (SCPE_BARE_STATUS(stat) == SCPE_OPENERR)
    stat = do_cmd (-1, "simh.ini");                     /* simh.ini proc cmd file */
if (*cbuf)                                              /* cmd file arg? */
    stat = do_cmd (0, cbuf);                            /* proc cmd file */
else if (*argv[0]) {                                    /* sim name arg? */
    char *np;                                           /* "path.ini" */
    nbuf[0] = '"';                                      /* starting " */
    strlcpy (nbuf + 1, argv[0], PATH_MAX + 2);          /* copy sim name */
    if ((np = (char *)match_ext (nbuf, "EXE")))         /* remove .exe */
        *np = 0;
    strlcat (nbuf, ".ini\"", sizeof (nbuf));            /* add .ini" */
    stat = do_cmd (-1, nbuf) & ~SCPE_NOMESSAGE;         /* proc default cmd file */
    if (stat == SCPE_OPENERR) {                         /* didn't exist/can't open? */
        np = strrchr (nbuf, '/');                       /* stript path and try again in cwd */
        if (np == NULL)
................................................................................
            stat = do_cmd (-1, np) & ~SCPE_NOMESSAGE;   /* proc default cmd file */
            }
        }
    }
if (SCPE_BARE_STATUS(stat) == SCPE_OPENERR)             /* didn't exist/can't open? */
    stat = SCPE_OK;

if (sim_switches & SWMASK ('T'))                       /* Command Line -T switch */
    stat = sim_library_unit_tests ();                   /* run library unit tests */

if (SCPE_BARE_STATUS(stat) != SCPE_EXIT)
    process_stdin_commands (SCPE_BARE_STATUS(stat), argv);

detach_all (0, TRUE);                                   /* close files */
sim_set_deboff (0, NULL);                               /* close debug */
................................................................................
        break;
    }
return SCPE_OK;
}

t_stat help_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE], gbuf2[CBUFSIZE];
CTAB *cmdp;

GET_SWITCHES (cptr);                                    /* get switches */
if (sim_switches & SWMASK ('F'))
    flag = flag | SCP_HELP_FLAT;
if (*cptr) {
    cptr = get_glyph (cptr, gbuf, 0);
................................................................................

                    if ((shptr == NULL) || (shptr->help == NULL) || (*shptr->help == '\0'))
                        return SCPE_ARG;
                    return help_cmd_output (flag, shptr->help, NULL);
                    }
                return SCPE_ARG;
                }


            }
        if (cmdp->help) {
            if (strcmp (cmdp->name, "HELP") == 0) {
                DEVICE *dptr;
                int i;

                for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
................................................................................
                if (((cmdp->action == &exdep_cmd) || (0 == strcmp(cmdp->name, "BOOT"))) &&
                    sim_dflt_dev->help) {
                        sim_dflt_dev->help (stdout, sim_dflt_dev, sim_dflt_dev->units, 0, cmdp->name);
                        if (sim_log)
                            sim_dflt_dev->help (sim_log, sim_dflt_dev, sim_dflt_dev->units, 0, cmdp->name);
                    }
                }
            strlcpy (gbuf2, cmdp->help, sizeof (gbuf2));
            if (*cptr) {
                strlcat (gbuf2, " ", sizeof (gbuf2));
                strlcat (gbuf2, cptr, sizeof (gbuf2));
                }
            help_cmd_output (flag, gbuf2, cmdp->help_base);
            }
        else { /* no help so it is likely a command alias */
            CTAB *cmdpa;

            for (cmdpa=cmd_table; cmdpa->name != NULL; cmdpa++)
                if ((cmdpa->action == cmdp->action) && (cmdpa->help)) {
                    sim_printf ("%s is an alias for the %s command:\n%s", 
................................................................................
                sim_printf ("No help available for the %s command\n", cmdp->name);
            }
        }
    else { 
        DEVICE *dptr;
        UNIT *uptr;
        t_stat r;
        t_bool explicit_device = FALSE;

        if (0 == strcmp (gbuf, "DEVICE")) {
            explicit_device = TRUE;
            cptr = get_glyph (cptr, gbuf, 0);
            }
        dptr = find_unit (gbuf, &uptr);
        if (dptr == NULL) {
            dptr = find_dev (gbuf);
            if (dptr == NULL)
                return sim_messagef (SCPE_ARG, "No HELP available for %s%s %s\n", 
                                               explicit_device ? "DEVICE " : "", gbuf, cptr);
            if (dptr->flags & DEV_DISABLE)
                sim_printf ("Device %s is currently disabled\n", dptr->name);
            }
        r = help_dev_help (stdout, dptr, uptr, flag, cptr);
        if (sim_log)
            help_dev_help (sim_log, dptr, uptr, flag | SCP_HELP_FLAT, cptr);
        return r;
................................................................................
   instr        =       input string
   tmpbuf       =       temp buffer
   maxstr       =       min (len (instr), len (tmpbuf))
   do_arg[10]   =       arguments

   Token "%0" represents the command file name.

   The input sequence "%%" represents a literal "%", and "\\" represents a
   literal "\".  All other character combinations are rendered literally.

   Omitted parameters result in null-string substitutions.
*/

void sim_sub_args (char *instr, size_t instr_size, char *do_arg[])
{
................................................................................
                                }
                            else
                                break;
                        }
                    ++ip;
                    }
                else {
                    if (*ip == '\0') {                  /* is this a bare % at end of line? */
                        *op++ = '%';                    /* leave it there as a literal percent sign */
                        }
                    else {
                        get_glyph_nc (ip, gbuf, '%');   /* get the literal name */
                        ap = _sim_get_env_special (gbuf, rbuf, sizeof (rbuf));
                        ip += strlen (gbuf);
                        if (*ip == '%') 
                            ++ip;
                        }
                    }
                }
            if (ap) {                                   /* non-null arg? */
                char *expanded = NULL;

                if (expand_it) {
                    expanded = sim_filepath_parts (ap, parts);
................................................................................
size_t i;

for (i=1; i<arg_count-1; ++i)
    do_arg[i] = do_arg[i+1];
return SCPE_OK;
}


int sim_cmp_string (const char *s1, const char *s2)
{
long int v1, v2;
char *ep1, *ep2;

if (sim_switches & SWMASK ('F')) {      /* File Compare? */
    FILE *f1, *f2;
................................................................................
if (sim_switches & SWMASK ('P')) {
    CONST char *deflt = NULL;

    cptr = get_glyph_quoted (cptr, prompt, 0);          /* get prompt */
    if (prompt[0] == '\0')
        return sim_messagef (SCPE_2FARG, "Missing Prompt and Environment Variable Name\n");
    if ((prompt[0] == '"') || (prompt[0] == '\'')) {
        if (strlen (prompt) < 3)
            return sim_messagef (SCPE_ARG, "Invalid Prompt\n");
        prompt[strlen (prompt) - 1] = '\0';
        memmove (prompt, prompt + 1, strlen (prompt));
        }
    deflt = get_glyph (cptr, varname, '=');             /* get environment variable name */
    if (varname[0] == '\0')
        return sim_messagef (SCPE_2FARG, "Missing Environment Variable Name\n");
    if (deflt == NULL)
        deflt = "";
    if (*deflt) {
        strlcat (prompt, " [", sizeof (prompt));
        strlcat (prompt, deflt, sizeof (prompt));
        strlcat (prompt, "] ", sizeof (prompt));
        }
................................................................................
memset (&buf, 0, sizeof (buf));
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_clock_queue == QUEUE_LIST_END)
    fprintf (st, "%s event queue empty, time = %.0f, executing %s instructios/sec\n",
             sim_name, sim_time, sim_fmt_numeric (sim_timer_inst_per_sec ()));
else {
    const char *tim = "";
    double inst_per_sec = sim_timer_inst_per_sec ();

    fprintf (st, "%s event queue status, time = %.0f, executing %s instructions/sec\n",
             sim_name, sim_time, sim_fmt_numeric (inst_per_sec));
    accum = 0;
    for (uptr = sim_clock_queue; uptr != QUEUE_LIST_END; uptr = uptr->next) {
        if (uptr == &sim_step_unit)
            fprintf (st, "  Step timer");
        else
            if (uptr == &sim_expect_unit)
                fprintf (st, "  Expect fired");
................................................................................
                if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                    fprintf (st, "  %s", sim_dname (dptr));
                    if (dptr->numunits > 1)
                        fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                    }
                else
                    fprintf (st, "  Unknown");
        if (inst_per_sec != 0.0)
            tim = sim_fmt_secs(((accum + uptr->time) / sim_timer_inst_per_sec ()) + (uptr->usecs_remaining / 1000000.0));
        if (uptr->usecs_remaining)
            fprintf (st, " at %d plus %.0f usecs%s%s%s%s\n", accum + uptr->time, uptr->usecs_remaining,
                                            (*tim) ? " (" : "", tim, (*tim) ? " total)" : "",
                                            (uptr->flags & UNIT_IDLE) ? " (Idle capable)" : "");
        else
            fprintf (st, " at %d%s%s%s%s\n", accum + uptr->time, 
                                            (*tim) ? " (" : "", tim, (*tim) ? ")" : "",
................................................................................
t_stat reason;

for (i = 0; i < start; i++) {
    if (sim_devices[i] == NULL)
        return SCPE_IERR;
    }
for (i = start; (dptr = sim_devices[i]) != NULL; i++) {
    if (sim_switches & SWMASK('P')) {
        tmxr_add_debug (dptr);          /* Add TMXR debug to MUX devices */
        sim_tape_add_debug (dptr);      /* Add TAPE debug to TAPE devices */
        }
    if (dptr->reset != NULL) {
        reason = dptr->reset (dptr);
        if (reason != SCPE_OK)
            return reason;
        }
    }
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i) {
................................................................................
}

/* Attach unit to file */

t_stat attach_unit (UNIT *uptr, CONST char *cptr)
{
DEVICE *dptr;
t_bool open_rw = FALSE;

if (!(uptr->flags & UNIT_ATTABLE))                      /* not attachable? */
    return SCPE_NOATT;
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char)); /* alloc name buf */
if (uptr->filename == NULL)
................................................................................
                    return attach_err (uptr, SCPE_OPENERR); /* yes, error */
                uptr->fileref = sim_fopen (cptr, "wb+");/* open new file */
                if (uptr->fileref == NULL)              /* open fail? */
                    return attach_err (uptr, SCPE_OPENERR); /* yes, error */
                sim_messagef (SCPE_OK, "%s: creating new file\n", sim_dname (dptr));
                }
            }                                           /* end if null */
        else
            open_rw = TRUE;
        }                                               /* end else */
    }
if (uptr->flags & UNIT_BUFABLE) {                       /* buffer? */
    uint32 cap = ((uint32) uptr->capac) / dptr->aincr;  /* effective size */
    if (uptr->flags & UNIT_MUSTBUF)                     /* dyn alloc? */
        uptr->filebuf = calloc (cap, SZ_D (dptr));      /* allocate */
    if (uptr->filebuf == NULL)                          /* no buffer? */
................................................................................
    sim_messagef (SCPE_OK, "%s: buffering file in memory\n", sim_dname (dptr));
    uptr->hwmark = (uint32)sim_fread (uptr->filebuf,    /* read file */
        SZ_D (dptr), cap, uptr->fileref);
    uptr->flags = uptr->flags | UNIT_BUF;               /* set buffered */
    }
uptr->flags = uptr->flags | UNIT_ATT;
uptr->pos = 0;
if (open_rw &&                                      /* open for write in append mode? */
    (sim_switches & SWMASK ('A')) &&
    (uptr->flags & UNIT_SEQ) &&
    (!(uptr->flags & UNIT_MUSTBUF)) &&
    (0 == sim_fseek (uptr->fileref, 0, SEEK_END)))
    uptr->pos = (t_addr)sim_ftell (uptr->fileref);  /* Position at end of file */
return SCPE_OK;
}

t_stat attach_err (UNIT *uptr, t_stat stat)
{
free (uptr->filename);
uptr->filename = NULL;
................................................................................
    return SCPE_IERR;
if (!(uptr->flags & UNIT_ATTABLE))                      /* attachable? */
    return SCPE_NOATT;
if (!(uptr->flags & UNIT_ATT)) {                        /* not attached? */
    if (sim_switches & SIM_SW_REST)                     /* restoring? */
        return SCPE_OK;                                 /* allow detach */
    else
        return SCPE_UNATT;                              /* complain */
    }
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_OK;
if ((uptr->flags & UNIT_BUF) && (uptr->filebuf)) {
    uint32 cap = (uptr->hwmark + dptr->aincr - 1) / dptr->aincr;
    if (uptr->hwmark && ((uptr->flags & UNIT_RO) == 0)) {
        sim_messagef (SCPE_OK, "%s: writing buffer to file\n", sim_dname (dptr));
................................................................................
        WRITE_I (uptr->u4);
        WRITE_I (uptr->u5);                             /* [V3.0] more unit */
        WRITE_I (uptr->u6);
        WRITE_I (uptr->flags);                          /* [V2.10] flags */
        WRITE_I (uptr->dynflags);
        WRITE_I (uptr->wait);
        WRITE_I (uptr->buf);
        WRITE_I (uptr->recsize);
        WRITE_I (uptr->capac);                          /* [V3.5] capacity */
        fprintf (sfile, "%.0f\n", uptr->usecs_remaining);/* [V4.0] remaining wait */
        WRITE_I (uptr->pos);
        if (uptr->flags & UNIT_ATT) {
            fputs (uptr->filename, sfile);
            if ((uptr->flags & UNIT_BUF) &&             /* writable buffered */
                uptr->hwmark &&                         /* files need to be */
................................................................................
        READ_I (uptr->u5);                              /* [V3.0+] more dev spec */
        READ_I (uptr->u6);
        READ_I (flg);                                   /* [V2.10+] unit flags */
        if (v40) {                                      /* [V4.0+] dynflags */
            READ_I (uptr->dynflags);
            READ_I (uptr->wait);
            READ_I (uptr->buf);
            READ_I (uptr->recsize);
            }
        old_capac = uptr->capac;                        /* save current capacity */
        if (v35) {                                      /* [V3.5+] capacity */
            READ_I (uptr->capac);
            }
        if (v40) {
            READ_S (buf);
................................................................................
free (attnames);
free (attunits);
free (attswitches);
if (warned)
    sim_printf ("restore with the -Q switch to suppress warning messages\n");
return r;
}

void sim_flush_buffered_files (void)
{
uint32 i, j;
DEVICE *dptr;
UNIT *uptr;

if (sim_log)                                            /* flush console log */
    fflush (sim_log);
if (sim_deb)                                            /* flush debug log */
    _sim_debug_flush ();
for (i = 1; (dptr = sim_devices[i]) != NULL; i++) {     /* flush attached files */
    for (j = 0; j < dptr->numunits; j++) {              /* if not buffered in mem */
        uptr = dptr->units + j;
        if (uptr->flags & UNIT_ATT) {                   /* attached, */
            if (uptr->io_flush) {                       /* unit specific flush routine? */
                if (!sim_asynch_enabled ||              /* and asynch I/O not possible? */
                    !sim_is_running)
                    uptr->io_flush (uptr);              /* call it */
                }
            else {
                if (!(uptr->flags & UNIT_BUF) &&        /* not buffered, */
                    (uptr->fileref) &&                  /* real file, */
                    !(uptr->dynflags & UNIT_NO_FIO) &&  /* is FILE *, */
                    !(uptr->flags & UNIT_RO))           /* not read only? */
                    fflush (uptr->fileref);
                }
            }
        }
    }
}

t_stat
flush_svc (UNIT *uptr)
{
sim_activate_after (uptr, FLUSH_INTERVAL);
sim_flush_buffered_files ();
return SCPE_OK;
}


/* Run, go, boot, cont, step, next commands

   ru[n] [new PC]       reset and start simulation
   go [new PC]          start simulation
   co[nt]               start simulation
   s[tep] [step limit]  start simulation for 'limit' instructions
................................................................................
    }
if (sim_step) {                                         /* set step timer */
    if (sim_switches & SWMASK ('T'))                    /* stepping for elapsed time? */
        sim_activate_after (&sim_step_unit, (uint32)sim_step);/* wall clock based step */
    else
        sim_activate (&sim_step_unit, sim_step);        /* instruction based step */
    }
sim_activate_after (&sim_flush_unit, FLUSH_INTERVAL);   /* Enable periodic buffer flushing */
stop_cpu = FALSE;
sim_is_running = TRUE;                                  /* flag running */
fflush(stdout);                                         /* flush stdout */
if (sim_log)                                            /* flush log if enabled */
    fflush (sim_log);
sim_throt_sched ();                                     /* set throttle */
sim_start_timer_services ();                            /* enable wall clock timing */
................................................................................
sim_stop_timer_services ();                             /* disable wall clock timing */
sim_ttcmd ();                                           /* restore console */
sim_brk_clrall (BRK_TYP_DYN_STEPOVER);                  /* cancel any step/over subroutine breakpoints */
#ifdef SIGHUP
signal (SIGHUP, SIG_DFL);                               /* cancel WRU */
#endif
signal (SIGTERM, SIG_DFL);                              /* cancel WRU */
sim_flush_buffered_files();
sim_cancel (&sim_flush_unit);                           /* cancel flush timer */


















sim_cancel (&sim_step_unit);                            /* cancel step timer */
sim_throt_cancel ();                                    /* cancel throttle */
AIO_UPDATE_QUEUE;
UPDATE_SIM_TIME;                                        /* update sim time */
return r | ((sim_switches & SWMASK ('Q')) ? SCPE_NOMESSAGE : 0);
}

................................................................................
            }
        else {
            if (sim_fseek (uptr->fileref, (t_addr)(sz * loc), SEEK_SET)) {
                clearerr (uptr->fileref);
                reason = SCPE_IOERR;
                break;
                }
            (void)sim_fread (&sim_eval[i], sz, 1, uptr->fileref);
            if ((feof (uptr->fileref)) &&
               !(uptr->flags & UNIT_FIX)) {
                reason = SCPE_EOF;
                break;
                }
            else if (ferror (uptr->fileref)) {
                clearerr (uptr->fileref);
................................................................................
            reason = uptr->action (uptr);
        else
            reason = SCPE_OK;
        }
    AIO_EVENT_COMPLETE(uptr, reason);
    bare_reason = SCPE_BARE_STATUS (reason);
    if ((bare_reason != SCPE_OK)     &&  /* Provide context for unexpected errors */
        (bare_reason >= SCPE_BASE)   &&
        (bare_reason != SCPE_EXPECT) &&
        (bare_reason != SCPE_REMOTE) &&
        (bare_reason != SCPE_MTRLNT) && 
        (bare_reason != SCPE_STOP)   && 
        (bare_reason != SCPE_STEP)   && 
        (bare_reason != SCPE_EXIT))
        sim_messagef (reason, "\nUnexpected internal error while processing event for %s which returned %d - %s\n", sim_uname (uptr), reason, sim_error_text (reason));
    } while ((reason == SCPE_OK) && 
             (sim_interval <= 0) && 
             (sim_clock_queue != QUEUE_LIST_END) &&
             (!stop_cpu));

if (sim_clock_queue == QUEUE_LIST_END) {                /* queue empty? */
    sim_interval = noqueue_time = NOQUEUE_WAIT;         /* flag queue empty */
................................................................................
                if (eidx) {
                    if (sim_isprint (ebcdic2ascii[data[i+sidx]]))
                        ebcdicbuf[eidx++] = ebcdic2ascii[data[i+sidx]];
                    else
                        ebcdicbuf[eidx++] = '.';
                    }
                }
            for (; sidx<16; ++sidx) {
                strbuf[soff+sidx] = ' ';
                if (eidx)
                    ebcdicbuf[eidx++] = ' ';
                }
            outbuf[oidx] = '\0';
            strbuf[soff+sidx] = '\0';
            ebcdicbuf[eidx] = '\0';
            rad50buf[ridx] = '\0';
            _sim_debug_unit (reason, uptr, "%04X%-48s %s%s%s\n", i, outbuf, strbuf, ebcdicbuf, rad50buf);
            }
        if (same > 0) {
................................................................................
    if (!cptr || !*cptr) {
        pstring = helpPrompt (topic, prompt[topic->kids != 0], FALSE);

        cptr = read_line_p (pstring, cbuf, sizeof (cbuf), stdin);
        free (pstring);
        }

    if (!cptr) {                            /* EOF, exit help */
#if !defined(_WIN32)
        printf ("\n");
#endif
        break;
        }

    cptr = get_glyph (cptr, gbuf, 0);
    if (!strcmp (gbuf, "*")) {              /* Wildcard */
        displayFlatHelp (st, dptr, uptr, flag, topic, ap);
        gbuf[0] = '\0';                     /* Displayed all subtopics, go up */
        }
    if (!gbuf[0]) {                         /* Blank, up a level */
................................................................................
{
if (this_Stack == NULL)
    return FALSE;

if (this_Stack->pointer == this_Stack->size) {  /* If necessary, grow stack */
    this_Stack->size += STACK_GROW_AMOUNT;
    this_Stack->elements = (Stack_Element *)realloc (this_Stack->elements, this_Stack->size * sizeof(*this_Stack->elements));
    memset (this_Stack->elements + this_Stack->size - STACK_GROW_AMOUNT, 0, STACK_GROW_AMOUNT * sizeof(*this_Stack->elements));
    }

this_Stack->elements[this_Stack->pointer].op = op;
strlcpy (this_Stack->elements[this_Stack->pointer].data, data, sizeof (this_Stack->elements[this_Stack->pointer].data));
++this_Stack->pointer;

if (op)
................................................................................
    return cptr;
    }

*value = sim_eval_postfix (postfix, stat);
delete_Stack (postfix);
return cptr;
}

/*
 * To avoid Coverity complaints about the use of rand() we define the function locally
 * This implementation of Lehmer's minimal standard algorithm is derived 
 * from the integer solution provided in:
 " "Communications of the ACM, October 1988, Volume 31, Number 10, page 1195"
 */

static int32 sim_rand_seed = 2;

void sim_srand (unsigned int seed)
{
/* Keep the seed within 1..RAND_MAX */
sim_rand_seed = (int32)(seed % RAND_MAX) + 1;
}

int sim_rand ()
{
const int32 a = 16807;
const int32 q = 127773;         /* (RAND_MAX + 1) / a */
const int32 r = 2836;           /* (RAND_MAX + 1) % a */
int32 lo, hi;

hi = sim_rand_seed / q;
lo = sim_rand_seed % q;
sim_rand_seed = a * lo - r * hi;
if (sim_rand_seed < 0)
    sim_rand_seed += RAND_MAX + 1;
return (sim_rand_seed - 1);
}

/*
 * Compiled in unit tests for the various device oriented library 
 * modules: sim_card, sim_disk, sim_tape, sim_ether, sim_tmxr, etc.
 */

static t_stat sim_library_unit_tests (void)
{
int i;
DEVICE *dptr;
int32 saved_switches = sim_switches & ~SWMASK ('T');
t_stat stat = SCPE_OK;

if (sim_switches & SWMASK ('D')) {
    sim_switches &= ~(SWMASK ('D') | SWMASK ('R') | SWMASK ('F') | SWMASK ('T'));
    sim_set_debon (0, "STDOUT");
    sim_switches = saved_switches;
    }
for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
    t_stat tstat = SCPE_OK;

    sim_switches = saved_switches;
    switch (DEV_TYPE(dptr)) {
#if defined(USE_SIM_CARD)
        case DEV_CARD:
            tstat = sim_card_test (dptr);
            break;
#endif
        case DEV_DISK:
            tstat = sim_disk_test (dptr);
            break;
        case DEV_ETHER:
            tstat = sim_ether_test (dptr);
            break;
        case DEV_TAPE:
            tstat = sim_tape_test (dptr);
            break;
        default:
            break;
        }
    if (tstat != SCPE_OK)
        stat = tstat;
    }
return stat;
}

Changes to src/SIMH/scp.h.

227
228
229
230
231
232
233








234
235
236
237
238
239
240
...
293
294
295
296
297
298
299

300
301
302
303
304
305
306
...
322
323
324
325
326
327
328

329
330
331
332
333
334
335
#endif
#ifndef strncasecmp
#define strncasecmp(str1, str2, len) sim_strncasecmp((str1), (str2), (len))
#endif
#ifndef strcasecmp
#define strcasecmp(str1, str2) sim_strcasecmp ((str1), (str2))
#endif








CONST char *get_sim_opt (int32 opt, CONST char *cptr, t_stat *st);
CONST char *get_sim_sw (CONST char *cptr);
const char *put_switches (char *buf, size_t bufsize, uint32 sw);
CONST char *get_glyph (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_nc (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_quoted (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_cmd (const char *iptr, char *optr);
................................................................................
t_stat sim_exp_set (EXPECT *exp, const char *match, int32 cnt, uint32 after, int32 switches, const char *act);
t_stat sim_exp_clr (EXPECT *exp, const char *match);
t_stat sim_exp_clrall (EXPECT *exp);
t_stat sim_exp_show (FILE *st, CONST EXPECT *exp, const char *match);
t_stat sim_exp_showall (FILE *st, const EXPECT *exp);
t_stat sim_exp_check (EXPECT *exp, uint8 data);
CONST char *match_ext (CONST char *fnam, const char *ext);

t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_add_debug_flags (DEVICE *dptr, DEBTAB *debflags);
const char *sim_error_text (t_stat stat);
t_stat sim_string_to_stat (const char *cptr, t_stat *cond);
t_stat sim_cancel_step (void);
................................................................................
void sim_debug_unit (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#else
void _sim_debug_unit (uint32 dbits, UNIT *uptr, const char* fmt, ...) GCC_FMT_ATTR(3, 4);
void _sim_debug_device (uint32 dbits, DEVICE* dptr, const char* fmt, ...) GCC_FMT_ATTR(3, 4);
#define sim_debug(dbits, dptr, ...) do { if (sim_deb && dptr && ((dptr)->dctrl & (dbits))) _sim_debug_device (dbits, dptr, __VA_ARGS__);} while (0)
#define sim_debug_unit(dbits, uptr, ...) do { if (sim_deb && uptr && (((uptr)->dctrl | (uptr)->dptr->dctrl) & (dbits))) _sim_debug_unit (dbits, uptr, __VA_ARGS__);} while (0)
#endif


void fprint_stopped_gen (FILE *st, t_stat v, REG *pc, DEVICE *dptr);
#define SCP_HELP_FLAT   (1u << 31)       /* Force flat help when prompting is not possible */
#define SCP_HELP_ONECMD (1u << 30)       /* Display one topic, do not prompt */
#define SCP_HELP_ATTACH (1u << 29)       /* Top level topic is ATTACH help */
t_stat scp_help (FILE *st, DEVICE *dptr,
                 UNIT *uptr, int32 flag, const char *help, const char *cptr, ...);







>
>
>
>
>
>
>
>







 







>







 







>







227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
...
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
...
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#endif
#ifndef strncasecmp
#define strncasecmp(str1, str2, len) sim_strncasecmp((str1), (str2), (len))
#endif
#ifndef strcasecmp
#define strcasecmp(str1, str2) sim_strcasecmp ((str1), (str2))
#endif
void sim_srand (unsigned int seed);
int sim_rand (void);
#ifdef RAND_MAX
#undef RAND_MAX
#endif
#define RAND_MAX 2147483646
#define rand sim_rand
#define srand(seed) sim_srand(seed)
CONST char *get_sim_opt (int32 opt, CONST char *cptr, t_stat *st);
CONST char *get_sim_sw (CONST char *cptr);
const char *put_switches (char *buf, size_t bufsize, uint32 sw);
CONST char *get_glyph (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_nc (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_quoted (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_cmd (const char *iptr, char *optr);
................................................................................
t_stat sim_exp_set (EXPECT *exp, const char *match, int32 cnt, uint32 after, int32 switches, const char *act);
t_stat sim_exp_clr (EXPECT *exp, const char *match);
t_stat sim_exp_clrall (EXPECT *exp);
t_stat sim_exp_show (FILE *st, CONST EXPECT *exp, const char *match);
t_stat sim_exp_showall (FILE *st, const EXPECT *exp);
t_stat sim_exp_check (EXPECT *exp, uint8 data);
CONST char *match_ext (CONST char *fnam, const char *ext);
int sim_cmp_string (const char *s1, const char *s2);
t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_add_debug_flags (DEVICE *dptr, DEBTAB *debflags);
const char *sim_error_text (t_stat stat);
t_stat sim_string_to_stat (const char *cptr, t_stat *cond);
t_stat sim_cancel_step (void);
................................................................................
void sim_debug_unit (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#else
void _sim_debug_unit (uint32 dbits, UNIT *uptr, const char* fmt, ...) GCC_FMT_ATTR(3, 4);
void _sim_debug_device (uint32 dbits, DEVICE* dptr, const char* fmt, ...) GCC_FMT_ATTR(3, 4);
#define sim_debug(dbits, dptr, ...) do { if (sim_deb && dptr && ((dptr)->dctrl & (dbits))) _sim_debug_device (dbits, dptr, __VA_ARGS__);} while (0)
#define sim_debug_unit(dbits, uptr, ...) do { if (sim_deb && uptr && (((uptr)->dctrl | (uptr)->dptr->dctrl) & (dbits))) _sim_debug_unit (dbits, uptr, __VA_ARGS__);} while (0)
#endif
void sim_flush_buffered_files (void);

void fprint_stopped_gen (FILE *st, t_stat v, REG *pc, DEVICE *dptr);
#define SCP_HELP_FLAT   (1u << 31)       /* Force flat help when prompting is not possible */
#define SCP_HELP_ONECMD (1u << 30)       /* Display one topic, do not prompt */
#define SCP_HELP_ATTACH (1u << 29)       /* Top level topic is ATTACH help */
t_stat scp_help (FILE *st, DEVICE *dptr,
                 UNIT *uptr, int32 flag, const char *help, const char *cptr, ...);

Changes to src/SIMH/sim_console.c.

663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
...
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
....
1408
1409
1410
1411
1412
1413
1414

1415
1416
1417
1418
1419
1420
1421
....
1433
1434
1435
1436
1437
1438
1439

1440
1441
1442
1443
1444
1445
1446
....
2235
2236
2237
2238
2239
2240
2241















2242
2243
2244
2245
2246
2247
2248
....
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272

2273
2274
2275
2276
2277
2278
2279

c = tmxr_poll_conn (&sim_rem_con_tmxr);
if (c >= 0) {                                           /* poll connect */
    REMOTE *rem = &sim_rem_consoles[c];
    TMLN *lp = rem->lp;
    char wru_name[8];

    sim_activate_after(uptr+1, 1000000);                /* start data poll after 1 second */
    lp->rcve = 1;                                       /* rcv enabled */
    rem->buf_ptr = 0;                                   /* start with empty command buffer */
    rem->single_mode = TRUE;                            /* start in single command mode */
    rem->read_timeout = sim_rem_read_timeout;           /* Start with default timeout */
    if (isprint(sim_int_char&0xFF))
        sprintf(wru_name, "'%c'", sim_int_char&0xFF);
    else
................................................................................
{
char cbuf[4*CBUFSIZE];
REMOTE *rem = &sim_rem_consoles[(int)(lp - sim_rem_con_tmxr.ldsc)];
int line = rem->line;

if ((!sim_oline) && (sim_log)) {
    fflush (sim_log);
    sim_fseeko (sim_log, sim_rem_cmd_log_start, SEEK_SET);
    cbuf[sizeof(cbuf)-1] = '\0';
    while (fgets (cbuf, sizeof(cbuf)-1, sim_log))
        tmxr_linemsgf (lp, "%s", cbuf);
    }
sim_oline = NULL;
if ((rem->act == NULL) && 
    (!tmxr_input_pending_ln (lp))) {
................................................................................
            i = -1;
            continue;
            }
        else {
            sim_is_running = FALSE;
            sim_rem_collect_all_registers ();
            sim_stop_timer_services ();

            if (rem->act == NULL) {
                for (j=0; j < sim_rem_con_tmxr.lines; j++) {
                    TMLN *lpj = &sim_rem_con_tmxr.ldsc[j];
                    if ((i == j) || (!lpj->conn))
                        continue;
                    tmxr_linemsgf (lpj, "\nRemote Master Console(%s) Entering Commands\n", lp->ipad);
                    tmxr_send_buffered_data (lpj);     /* flush any buffered data */
................................................................................
            c = c & ~TMXR_VALID;
            if (rem->single_mode) {
                if (c == sim_int_char) {            /* ^E (the interrupt character) must start continue mode console interaction */
                    rem->single_mode = FALSE;       /* enter multi command mode */
                    sim_is_running = FALSE;
                    sim_rem_collect_all_registers ();
                    sim_stop_timer_services ();

                    stat = SCPE_STOP;
                    _sim_rem_message ("RUN", stat);
                    _sim_rem_log_out (lp);
                    for (j=0; j < sim_rem_con_tmxr.lines; j++) {
                        TMLN *lpj = &sim_rem_con_tmxr.ldsc[j];
                        if ((i == j) || (!lpj->conn))
                            continue;
................................................................................
if (sim_log)
    fprintf (st, "Logging enabled to \"%s\"\n", 
                 sim_logfile_name (sim_log, sim_log_ref));
else
    fprintf (st, "Logging disabled\n");
return SCPE_OK;
}
















/* Set debug routine */

t_stat sim_set_debon (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
t_stat r;
................................................................................
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
r = sim_open_logfile (gbuf, FALSE, &sim_deb, &sim_deb_ref);

if (r != SCPE_OK)
    return r;

sim_deb_switches = sim_switches & 
                   (SWMASK ('R') | SWMASK ('P') | 
                    SWMASK ('T') | SWMASK ('A') | 
                    SWMASK ('F') | SWMASK ('N') |
                    SWMASK ('B'));                  /* save debug switches */

if (sim_deb_switches & SWMASK ('R')) {
    struct tm loc_tm, gmt_tm;
    time_t time_t_now;

    clock_gettime(CLOCK_REALTIME, &sim_deb_basetime);
    time_t_now = (time_t)sim_deb_basetime.tv_sec;
    /* Adjust the relative timebase to reflect the localtime GMT offset */







|







 







|







 







>







 







>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
<
<
<
<
>







663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
...
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
....
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
....
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
....
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
....
2278
2279
2280
2281
2282
2283
2284
2285




2286
2287
2288
2289
2290
2291
2292
2293

c = tmxr_poll_conn (&sim_rem_con_tmxr);
if (c >= 0) {                                           /* poll connect */
    REMOTE *rem = &sim_rem_consoles[c];
    TMLN *lp = rem->lp;
    char wru_name[8];

    sim_activate_after(rem_con_data_unit, 1000000);     /* start data poll after 1 second */
    lp->rcve = 1;                                       /* rcv enabled */
    rem->buf_ptr = 0;                                   /* start with empty command buffer */
    rem->single_mode = TRUE;                            /* start in single command mode */
    rem->read_timeout = sim_rem_read_timeout;           /* Start with default timeout */
    if (isprint(sim_int_char&0xFF))
        sprintf(wru_name, "'%c'", sim_int_char&0xFF);
    else
................................................................................
{
char cbuf[4*CBUFSIZE];
REMOTE *rem = &sim_rem_consoles[(int)(lp - sim_rem_con_tmxr.ldsc)];
int line = rem->line;

if ((!sim_oline) && (sim_log)) {
    fflush (sim_log);
    (void)sim_fseeko (sim_log, sim_rem_cmd_log_start, SEEK_SET);
    cbuf[sizeof(cbuf)-1] = '\0';
    while (fgets (cbuf, sizeof(cbuf)-1, sim_log))
        tmxr_linemsgf (lp, "%s", cbuf);
    }
sim_oline = NULL;
if ((rem->act == NULL) && 
    (!tmxr_input_pending_ln (lp))) {
................................................................................
            i = -1;
            continue;
            }
        else {
            sim_is_running = FALSE;
            sim_rem_collect_all_registers ();
            sim_stop_timer_services ();
            sim_flush_buffered_files ();
            if (rem->act == NULL) {
                for (j=0; j < sim_rem_con_tmxr.lines; j++) {
                    TMLN *lpj = &sim_rem_con_tmxr.ldsc[j];
                    if ((i == j) || (!lpj->conn))
                        continue;
                    tmxr_linemsgf (lpj, "\nRemote Master Console(%s) Entering Commands\n", lp->ipad);
                    tmxr_send_buffered_data (lpj);     /* flush any buffered data */
................................................................................
            c = c & ~TMXR_VALID;
            if (rem->single_mode) {
                if (c == sim_int_char) {            /* ^E (the interrupt character) must start continue mode console interaction */
                    rem->single_mode = FALSE;       /* enter multi command mode */
                    sim_is_running = FALSE;
                    sim_rem_collect_all_registers ();
                    sim_stop_timer_services ();
                    sim_flush_buffered_files ();
                    stat = SCPE_STOP;
                    _sim_rem_message ("RUN", stat);
                    _sim_rem_log_out (lp);
                    for (j=0; j < sim_rem_con_tmxr.lines; j++) {
                        TMLN *lpj = &sim_rem_con_tmxr.ldsc[j];
                        if ((i == j) || (!lpj->conn))
                            continue;
................................................................................
if (sim_log)
    fprintf (st, "Logging enabled to \"%s\"\n", 
                 sim_logfile_name (sim_log, sim_log_ref));
else
    fprintf (st, "Logging disabled\n");
return SCPE_OK;
}

/* Set debug switches */

int32 sim_set_deb_switches (int32 switches)
{
int32 old_deb_switches = sim_deb_switches;

sim_deb_switches = switches & 
                   (SWMASK ('R') | SWMASK ('P') | 
                    SWMASK ('T') | SWMASK ('A') | 
                    SWMASK ('F') | SWMASK ('N') |
                    SWMASK ('B') | SWMASK ('E') |
                    SWMASK ('D') );                 /* save debug switches */
return old_deb_switches;
}

/* Set debug routine */

t_stat sim_set_debon (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
t_stat r;
................................................................................
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
r = sim_open_logfile (gbuf, FALSE, &sim_deb, &sim_deb_ref);

if (r != SCPE_OK)
    return r;

sim_set_deb_switches (sim_switches);





if (sim_deb_switches & SWMASK ('R')) {
    struct tm loc_tm, gmt_tm;
    time_t time_t_now;

    clock_gettime(CLOCK_REALTIME, &sim_deb_basetime);
    time_t_now = (time_t)sim_deb_basetime.tv_sec;
    /* Adjust the relative timebase to reflect the localtime GMT offset */

Changes to src/SIMH/sim_console.h.

77
78
79
80
81
82
83

84
85
86
87
88
89
90
t_stat sim_set_kmap (int32 flag, CONST char *cptr);
t_stat sim_set_telnet (int32 flag, CONST char *cptr);
t_stat sim_set_notelnet (int32 flag, CONST char *cptr);
t_stat sim_set_serial (int32 flag, CONST char *cptr);
t_stat sim_set_noserial (int32 flag, CONST char *cptr);
t_stat sim_set_logon (int32 flag, CONST char *cptr);
t_stat sim_set_logoff (int32 flag, CONST char *cptr);

t_stat sim_set_debon (int32 flag, CONST char *cptr);
t_stat sim_set_cons_debug (int32 flg, CONST char *cptr);
t_stat sim_set_cons_buff (int32 flg, CONST char *cptr);
t_stat sim_set_cons_unbuff (int32 flg, CONST char *cptr);
t_stat sim_set_cons_log (int32 flg, CONST char *cptr);
t_stat sim_set_cons_nolog (int32 flg, CONST char *cptr);
t_stat sim_set_deboff (int32 flag, CONST char *cptr);







>







77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
t_stat sim_set_kmap (int32 flag, CONST char *cptr);
t_stat sim_set_telnet (int32 flag, CONST char *cptr);
t_stat sim_set_notelnet (int32 flag, CONST char *cptr);
t_stat sim_set_serial (int32 flag, CONST char *cptr);
t_stat sim_set_noserial (int32 flag, CONST char *cptr);
t_stat sim_set_logon (int32 flag, CONST char *cptr);
t_stat sim_set_logoff (int32 flag, CONST char *cptr);
int32 sim_set_deb_switches (int32 switches);
t_stat sim_set_debon (int32 flag, CONST char *cptr);
t_stat sim_set_cons_debug (int32 flg, CONST char *cptr);
t_stat sim_set_cons_buff (int32 flg, CONST char *cptr);
t_stat sim_set_cons_unbuff (int32 flg, CONST char *cptr);
t_stat sim_set_cons_log (int32 flg, CONST char *cptr);
t_stat sim_set_cons_nolog (int32 flg, CONST char *cptr);
t_stat sim_set_deboff (int32 flag, CONST char *cptr);

Changes to src/SIMH/sim_defs.h.

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
...
588
589
590
591
592
593
594

595
596
597
598
599
600
601
...
647
648
649
650
651
652
653

654
655
656
657
658
659
660
661
#define SCPE_IERR       (SCPE_BASE + 37)                /* internal error */
#define SCPE_MTRLNT     (SCPE_BASE + 38)                /* tape rec lnt error */
#define SCPE_LOST       (SCPE_BASE + 39)                /* Telnet conn lost */
#define SCPE_TTMO       (SCPE_BASE + 40)                /* Telnet conn timeout */
#define SCPE_STALL      (SCPE_BASE + 41)                /* Telnet conn stall */
#define SCPE_AFAIL      (SCPE_BASE + 42)                /* assert failed */
#define SCPE_INVREM     (SCPE_BASE + 43)                /* invalid remote console command */
#define SCPE_NOTATT     (SCPE_BASE + 44)                /* not attached */
#define SCPE_EXPECT     (SCPE_BASE + 45)                /* expect matched */
#define SCPE_AMBREG     (SCPE_BASE + 46)                /* ambiguous register */
#define SCPE_REMOTE     (SCPE_BASE + 47)                /* remote console command */
#define SCPE_INVEXPR    (SCPE_BASE + 48)                /* invalid expression */

#define SCPE_MAX_ERR    (SCPE_BASE + 48)                /* Maximum SCPE Error Value */
#define SCPE_KFLAG      0x10000000                      /* tti data flag */
#define SCPE_BREAK      0x20000000                      /* tti break flag */
#define SCPE_NOMESSAGE  0x40000000                      /* message display supression flag */
#define SCPE_BARE_STATUS(stat) ((stat) & ~(SCPE_NOMESSAGE|SCPE_KFLAG|SCPE_BREAK))

/* Print value format codes */

................................................................................
    int32               u5;                             /* device specific */
    int32               u6;                             /* device specific */
    void                *up7;                           /* device specific */
    void                *up8;                           /* device specific */
    uint16              us9;                            /* device specific */
    uint16              us10;                           /* device specific */
    void                *tmxr;                          /* TMXR linkage */

    t_bool              (*cancel)(UNIT *);
    double              usecs_remaining;                /* time balance for long delays */
    char                *uname;                         /* Unit name */
    DEVICE              *dptr;                          /* DEVICE linkage (backpointer) */
    uint32              dctrl;                          /* debug control */
#ifdef SIM_ASYNCH_IO
    void                (*a_check_completion)(UNIT *);
................................................................................
/* These flags are only set dynamically */

#define UNIT_ATTMULT    0000001         /* Allow multiple attach commands */
#define UNIT_TM_POLL    0000002         /* TMXR Polling unit */
#define UNIT_NO_FIO     0000004         /* fileref is NOT a FILE * */
#define UNIT_DISK_CHK   0000010         /* disk data debug checking (sim_disk) */
#define UNIT_TMR_UNIT   0000020         /* Unit registered as a calibrated timer */

#define UNIT_V_DF_TAPE  6               /* Bit offset for Tape Density reservation */
#define UNIT_S_DF_TAPE  3               /* Bits Reserved for Tape Density */

struct BITFIELD {
    const char      *name;                              /* field name */
    uint32          offset;                             /* starting bit */
    uint32          width;                              /* width */
    const char      **valuenames;                       /* map of values to strings */







|
<
|
|
|

|







 







>







 







>
|







407
408
409
410
411
412
413
414

415
416
417
418
419
420
421
422
423
424
425
426
...
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
...
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
#define SCPE_IERR       (SCPE_BASE + 37)                /* internal error */
#define SCPE_MTRLNT     (SCPE_BASE + 38)                /* tape rec lnt error */
#define SCPE_LOST       (SCPE_BASE + 39)                /* Telnet conn lost */
#define SCPE_TTMO       (SCPE_BASE + 40)                /* Telnet conn timeout */
#define SCPE_STALL      (SCPE_BASE + 41)                /* Telnet conn stall */
#define SCPE_AFAIL      (SCPE_BASE + 42)                /* assert failed */
#define SCPE_INVREM     (SCPE_BASE + 43)                /* invalid remote console command */
#define SCPE_EXPECT     (SCPE_BASE + 44)                /* expect matched */

#define SCPE_AMBREG     (SCPE_BASE + 45)                /* ambiguous register */
#define SCPE_REMOTE     (SCPE_BASE + 46)                /* remote console command */
#define SCPE_INVEXPR    (SCPE_BASE + 47)                /* invalid expression */

#define SCPE_MAX_ERR    (SCPE_BASE + 47)                /* Maximum SCPE Error Value */
#define SCPE_KFLAG      0x10000000                      /* tti data flag */
#define SCPE_BREAK      0x20000000                      /* tti break flag */
#define SCPE_NOMESSAGE  0x40000000                      /* message display supression flag */
#define SCPE_BARE_STATUS(stat) ((stat) & ~(SCPE_NOMESSAGE|SCPE_KFLAG|SCPE_BREAK))

/* Print value format codes */

................................................................................
    int32               u5;                             /* device specific */
    int32               u6;                             /* device specific */
    void                *up7;                           /* device specific */
    void                *up8;                           /* device specific */
    uint16              us9;                            /* device specific */
    uint16              us10;                           /* device specific */
    void                *tmxr;                          /* TMXR linkage */
    uint32              recsize;                        /* Tape info */
    t_bool              (*cancel)(UNIT *);
    double              usecs_remaining;                /* time balance for long delays */
    char                *uname;                         /* Unit name */
    DEVICE              *dptr;                          /* DEVICE linkage (backpointer) */
    uint32              dctrl;                          /* debug control */
#ifdef SIM_ASYNCH_IO
    void                (*a_check_completion)(UNIT *);
................................................................................
/* These flags are only set dynamically */

#define UNIT_ATTMULT    0000001         /* Allow multiple attach commands */
#define UNIT_TM_POLL    0000002         /* TMXR Polling unit */
#define UNIT_NO_FIO     0000004         /* fileref is NOT a FILE * */
#define UNIT_DISK_CHK   0000010         /* disk data debug checking (sim_disk) */
#define UNIT_TMR_UNIT   0000020         /* Unit registered as a calibrated timer */
#define UNIT_TAPE_MRK   0000040         /* Tape Unit AWS Tapemark */
#define UNIT_V_DF_TAPE  7               /* Bit offset for Tape Density reservation */
#define UNIT_S_DF_TAPE  3               /* Bits Reserved for Tape Density */

struct BITFIELD {
    const char      *name;                              /* field name */
    uint32          offset;                             /* starting bit */
    uint32          width;                              /* width */
    const char      **valuenames;                       /* map of values to strings */

Changes to src/SIMH/sim_disk.c.

1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
....
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
....
1805
1806
1807
1808
1809
1810
1811


1812
1813
1814
1815
1816
1817
1818
1819
1820
....
3483
3484
3485
3486
3487
3488
3489
3490

3491

3492
3493
3494
3495
3496
3497
3498
....
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106

4107
4108
4109
4110
4111
4112
4113
4114
            }
        free (copy_buf);
        sim_vhd_disk_close (vhd);
        sim_disk_detach (uptr);
        if (r == SCPE_OK) {
            created = TRUE;
            copied = TRUE;
            tbuf[sizeof(tbuf)-1] = '\0';
            strncpy (tbuf, gbuf, sizeof(tbuf)-1);
            cptr = tbuf;
            sim_disk_set_fmt (uptr, 0, "VHD", NULL);
            sim_switches = saved_sim_switches;
            }
        else
            return r;
        /* fall through and open/return the newly created & copied vhd */
................................................................................
    default:
        return SCPE_IERR;
    }
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char));/* alloc name buf */
uptr->disk_ctx = ctx = (struct disk_context *)calloc(1, sizeof(struct disk_context));
if ((uptr->filename == NULL) || (uptr->disk_ctx == NULL))
    return _err_return (uptr, SCPE_MEM);
strncpy (uptr->filename, cptr, CBUFSIZE);               /* save name */
ctx->sector_size = (uint32)sector_size;                 /* save sector_size */
ctx->capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* save capacity units (word: 2, byte: 1) */
ctx->xfer_element_size = (uint32)xfer_element_size;     /* save xfer_element_size */
ctx->dptr = dptr;                                       /* save DEVICE pointer */
ctx->dbit = dbit;                                       /* save debug bit */
ctx->media_removed = 0;                                 /* default present */
sim_debug_unit (ctx->dbit, uptr, "sim_disk_attach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);
................................................................................
t_stat sim_disk_detach (UNIT *uptr)
{
struct disk_context *ctx;
int (*close_function)(FILE *f);
FILE *fileref;
t_bool auto_format;



if ((uptr == NULL) || !(uptr->flags & UNIT_ATT))
    return SCPE_NOTATT;

ctx = (struct disk_context *)uptr->disk_ctx;
fileref = uptr->fileref;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_detach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);

switch (DK_GET_FMT (uptr)) {                            /* case on format */
................................................................................
                                      NULL,
                                      &ParentModificationTime,
                                      NULL,
                                      0)) {
                    if ((0 == memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID))) &&
                        ((sDynamic->ParentTimeStamp == ParentModificationTime) ||
                         ((NtoHl(sDynamic->ParentTimeStamp)-NtoHl(ParentModificationTime)) == 3600) ||
                         (sim_switches & SWMASK ('O'))))

                         strncpy (szParentVHDPath, CheckPath, ParentVHDPathSize);

                    else {
                        if (0 != memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID)))
                            sim_printf ("Error Invalid Parent VHD '%s' for Differencing VHD: %s\n", CheckPath, szVHDPath);
                        else
                            sim_printf ("Error Parent VHD '%s' has been modified since Differencing VHD: %s was created\n", CheckPath, szVHDPath);
                        Return = EINVAL;                /* File Corrupt/Invalid */
                        }
................................................................................
#else
char buffer[PATH_MAX];
char *wd = getcwd(buffer, PATH_MAX);

if ((szFileSpec[0] != '/') || (strchr (szFileSpec, ':')))
    snprintf (szFullFileSpecBuffer, BufferSize, "%s/%s", wd, szFileSpec);
else
    strncpy (szFullFileSpecBuffer, szFileSpec, BufferSize);
if ((c = strstr (szFullFileSpecBuffer, "]/")))
    memmove (c+1, c+2, strlen(c+2)+1);
memset (szFullFileSpecBuffer + strlen (szFullFileSpecBuffer), 0, BufferSize - strlen (szFullFileSpecBuffer));
#endif
}

static char *
HostPathToVhdPath (const char *szHostPath,
                   char *szVhdPath,
                   size_t VhdPathSize)
{
char *c, *d;


strncpy (szVhdPath, szHostPath, VhdPathSize-1);
if ((szVhdPath[1] == ':') && islower(szVhdPath[0]))
    szVhdPath[0] = toupper(szVhdPath[0]);
szVhdPath[VhdPathSize-1] = '\0';
if ((c = strrchr (szVhdPath, ']'))) {
    *c = '\0';
    if (!(d = strchr (szVhdPath, '[')))
        return d;







<
|







 







|







 







>
>
|
|







 







|
>
|
>







 







|













>
|







1485
1486
1487
1488
1489
1490
1491

1492
1493
1494
1495
1496
1497
1498
1499
....
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
....
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
....
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
....
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
            }
        free (copy_buf);
        sim_vhd_disk_close (vhd);
        sim_disk_detach (uptr);
        if (r == SCPE_OK) {
            created = TRUE;
            copied = TRUE;

            strlcpy (tbuf, gbuf, sizeof(tbuf)-1);
            cptr = tbuf;
            sim_disk_set_fmt (uptr, 0, "VHD", NULL);
            sim_switches = saved_sim_switches;
            }
        else
            return r;
        /* fall through and open/return the newly created & copied vhd */
................................................................................
    default:
        return SCPE_IERR;
    }
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char));/* alloc name buf */
uptr->disk_ctx = ctx = (struct disk_context *)calloc(1, sizeof(struct disk_context));
if ((uptr->filename == NULL) || (uptr->disk_ctx == NULL))
    return _err_return (uptr, SCPE_MEM);
strlcpy (uptr->filename, cptr, CBUFSIZE);               /* save name */
ctx->sector_size = (uint32)sector_size;                 /* save sector_size */
ctx->capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* save capacity units (word: 2, byte: 1) */
ctx->xfer_element_size = (uint32)xfer_element_size;     /* save xfer_element_size */
ctx->dptr = dptr;                                       /* save DEVICE pointer */
ctx->dbit = dbit;                                       /* save debug bit */
ctx->media_removed = 0;                                 /* default present */
sim_debug_unit (ctx->dbit, uptr, "sim_disk_attach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);
................................................................................
t_stat sim_disk_detach (UNIT *uptr)
{
struct disk_context *ctx;
int (*close_function)(FILE *f);
FILE *fileref;
t_bool auto_format;

if (uptr == NULL)
    return SCPE_IERR;
if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;

ctx = (struct disk_context *)uptr->disk_ctx;
fileref = uptr->fileref;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_detach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);

switch (DK_GET_FMT (uptr)) {                            /* case on format */
................................................................................
                                      NULL,
                                      &ParentModificationTime,
                                      NULL,
                                      0)) {
                    if ((0 == memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID))) &&
                        ((sDynamic->ParentTimeStamp == ParentModificationTime) ||
                         ((NtoHl(sDynamic->ParentTimeStamp)-NtoHl(ParentModificationTime)) == 3600) ||
                         (sim_switches & SWMASK ('O')))) {
                         memset (szParentVHDPath, 0, ParentVHDPathSize);
                         strlcpy (szParentVHDPath, CheckPath, ParentVHDPathSize);
                        }
                    else {
                        if (0 != memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID)))
                            sim_printf ("Error Invalid Parent VHD '%s' for Differencing VHD: %s\n", CheckPath, szVHDPath);
                        else
                            sim_printf ("Error Parent VHD '%s' has been modified since Differencing VHD: %s was created\n", CheckPath, szVHDPath);
                        Return = EINVAL;                /* File Corrupt/Invalid */
                        }
................................................................................
#else
char buffer[PATH_MAX];
char *wd = getcwd(buffer, PATH_MAX);

if ((szFileSpec[0] != '/') || (strchr (szFileSpec, ':')))
    snprintf (szFullFileSpecBuffer, BufferSize, "%s/%s", wd, szFileSpec);
else
    strlcpy (szFullFileSpecBuffer, szFileSpec, BufferSize);
if ((c = strstr (szFullFileSpecBuffer, "]/")))
    memmove (c+1, c+2, strlen(c+2)+1);
memset (szFullFileSpecBuffer + strlen (szFullFileSpecBuffer), 0, BufferSize - strlen (szFullFileSpecBuffer));
#endif
}

static char *
HostPathToVhdPath (const char *szHostPath,
                   char *szVhdPath,
                   size_t VhdPathSize)
{
char *c, *d;

memset (szVhdPath, 0, VhdPathSize);
strlcpy (szVhdPath, szHostPath, VhdPathSize-1);
if ((szVhdPath[1] == ':') && islower(szVhdPath[0]))
    szVhdPath[0] = toupper(szVhdPath[0]);
szVhdPath[VhdPathSize-1] = '\0';
if ((c = strrchr (szVhdPath, ']'))) {
    *c = '\0';
    if (!(d = strchr (szVhdPath, '[')))
        return d;

Changes to src/SIMH/sim_ether.c.

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
....
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
....
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
....
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
....
3641
3642
3643
3644
3645
3646
3647




























































































3648
3649
3650
3651
3652
3653
3654
....
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
....
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776

3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799






3800
3801
3802
3803
3804
3805
3806
....
3811
3812
3813
3814
3815
3816
3817




















3818
3819
3820
3821
3822
3823

3824
3825
3826
3827
3828
3829
3830
....
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
....
4058
4059
4060
4061
4062
4063
4064









































































































































































4065
4066







4067
4068
4069

  /* Allow generated MAC address */
  /* XX:XX:XX:XX:XX:XX{/bits{>file}} */
  /* bits (if specified) must be from 16 thru 48 */

  memset (&state, 0, sizeof(state));
  _eth_get_system_id (state.system_id, sizeof(state.system_id));
  strncpy (state.sim, sim_name, sizeof(state.sim));
  getcwd (state.cwd, sizeof(state.cwd));
  if (uptr)
    strncpy (state.uname, sim_uname (uptr), sizeof(state.uname)-1);
  cptr = strchr (strmac, '>');
  if (cptr) {
    state.file[sizeof(state.file)-1] = '\0';
    strncpy (state.file, cptr + 1, sizeof(state.file)-1);
    if ((f = fopen (state.file, "r"))) {
      filebuf[sizeof(filebuf)-1] = '\0';
      fgets (filebuf, sizeof(filebuf)-1, f);
      strmac = filebuf;
      fclose (f);
      strcpy (state.file, "");  /* avoid saving */
      }
................................................................................
    /* Set up interface flags */
    strcpy(ifr.ifr_name, devname);
    ifr.ifr_flags = IFF_TAP|IFF_NO_PI;

    /* Send interface requests to TUN/TAP driver. */
    if (ioctl(tun, TUNSETIFF, &ifr) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
        close(tun);
        }
      else {
        *fd_handle = tun;
        strcpy(savname, ifr.ifr_name);
        }
      }
    else
      strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
    }
  else
    strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
#elif defined(HAVE_BSDTUNTAP) && defined(HAVE_TAP_NETWORK)
  if (1) {
    char dev_name[64] = "";

    snprintf(dev_name, sizeof(dev_name)-1, "/dev/%s", devname);
    dev_name[sizeof(dev_name)-1] = '\0';

    if ((tun = open(dev_name, O_RDWR)) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
        close(tun);
        }
      else {
        *fd_handle = tun;
        strcpy(savname, devname);
        }
#if defined (__APPLE__)
      if (1) {
        struct ifreq ifr;
        int s;

        memset (&ifr, 0, sizeof(ifr));
        ifr.ifr_addr.sa_family = AF_INET;
        strncpy(ifr.ifr_name, savname, sizeof(ifr.ifr_name));
        if ((s = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
          if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) >= 0) {
            ifr.ifr_flags |= IFF_UP;
            if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&ifr)) {
              strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
              close(tun);
              }
            }
          close(s);
          }
        }
#endif
      }
    else
      strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
  }
#else
  strncpy(errbuf, "No support for tap: devices", PCAP_ERRBUF_SIZE-1);
#endif /* !defined(__linux) && !defined(HAVE_BSDTUNTAP) */
  if (0 == errbuf[0]) {
    *eth_api = ETH_API_TAP;
    *handle = (void *)1;  /* Flag used to indicated open */
    }
  }
else { /* !tap: */
................................................................................

      voa.port = (int)get_uint (vdeport_s, 10, 255, &r);
      if (r != SCPE_OK)
          return sim_messagef (SCPE_OPENERR, "Eth: Invalid vde port number: %s in %s\n", vdeport_s, savname);
      }

    if (!(*handle = (void*) vde_open((char *)vdeswitch_s, (char *)"simh", &voa)))
      strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
    else {
      *eth_api = ETH_API_VDE;
      *fd_handle = vde_datafd((VDECONN*)(*handle));
      }
#else
    strncpy(errbuf, "No support for vde: network devices", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_VDE_NETWORK) */
    }
  else { /* !vde: */
    if (0 == strncmp("nat:", savname, 4)) {
#if defined(HAVE_SLIRP_NETWORK)
      const char *devname = savname + 4;

      while (isspace(*devname))
        ++devname;
      if (!(*handle = (void*) sim_slirp_open(devname, opaque, &_slirp_callback, dptr, dbit)))
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
      else {
        *eth_api = ETH_API_NAT;
        *fd_handle = 0;
        }
#else
      strncpy(errbuf, "No support for nat: network devices", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_SLIRP_NETWORK) */
      }
    else { /* not nat: */
      if (0 == strncmp("udp:", savname, 4)) {
        char localport[CBUFSIZE], host[CBUFSIZE], port[CBUFSIZE];
        char hostport[2*CBUFSIZE];
        const char *devname = savname + 4;
................................................................................
           */
          int v = 1;
          ioctl(pcap_fileno(*handle), BIOCIMMEDIATE, &v);
          }
#endif /* defined (__APPLE__) */
#endif /* !defined (USE_READER_THREAD) */
#else
        strncpy (errbuf, "Unknown or unsupported network device", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_PCAP_NETWORK) */
        } /* not udp:, so attempt to open the parameter as if it were an explicit device name */
      } /* !nat: */
    } /* !vde: */
  } /* !tap: */
if (errbuf[0])
  return SCPE_OPENERR;
................................................................................
  pthread_mutex_unlock (&dev->lock);  
  if ((status) && (routine))
    routine(0);
#endif

return status;
}





























































































t_stat eth_filter(ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                  ETH_BOOL all_multicast, ETH_BOOL promiscuous)
{
return eth_filter_hash(dev, addr_count, addresses, 
                       all_multicast, promiscuous, 
                       NULL);
................................................................................
t_stat eth_filter_hash(ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                       ETH_BOOL all_multicast, ETH_BOOL promiscuous, 
                       ETH_MULTIHASH* const hash)
{
int i;
char buf[116+66*ETH_FILTER_MAX];
char mac[20];
char* buf2;
t_stat status;
#ifdef USE_BPF
struct bpf_program bpf;
#endif

/* make sure device exists */
if (!dev) return SCPE_UNATT;
................................................................................
  if (dev->all_multicast) {
    sim_debug(dev->dbit, dev->dptr, "All Multicast\n");
    }
  if (dev->promiscuous) {
    sim_debug(dev->dbit, dev->dptr, "Promiscuous\n");
    }
  }

/* setup BPF filters and other fields to minimize packet delivery */
strcpy(buf, "");

/* construct destination filters - since the real ethernet interface was set
   into promiscuous mode by eth_open(), we need to filter out the packets that
   our simulated interface doesn't want. */
if (!dev->promiscuous) {
  for (i = 0; i < addr_count; i++) {
    eth_mac_fmt(&dev->filter_address[i], mac);
    if (!strstr(buf, mac))    /* eliminate duplicates */
      sprintf(&buf[strlen(buf)], "%s(ether dst %s)", (*buf) ? " or " : "((", mac);
    }
  if (dev->all_multicast || dev->hash_filter)
    sprintf(&buf[strlen(buf)], "%s(ether multicast)", (*buf) ? " or " : "((");
  if (strlen(buf) > 0)
    sprintf(&buf[strlen(buf)], ")");
  }

/* construct source filters - this prevents packets from being reflected back 
   by systems where WinPcap and libpcap cause packet reflections. Note that
   some systems do not reflect packets at all. This *assumes* that the 
   simulated NIC will not send out packets with multicast source fields. */
if ((addr_count > 0) && (dev->reflections > 0)) {
  if (strlen(buf) > 0)
    sprintf(&buf[strlen(buf)], " and ");
  sprintf (&buf[strlen(buf)], "not (");
  buf2 = &buf[strlen(buf)];
  for (i = 0; i < addr_count; i++) {
    if (dev->filter_address[i][0] & 0x01) continue; /* skip multicast addresses */
    eth_mac_fmt(&dev->filter_address[i], mac);
    if (!strstr(buf2, mac))   /* eliminate duplicates */
      sprintf(&buf2[strlen(buf2)], "%s(ether src %s)", (*buf2) ? " or " : "", mac);
    }
  sprintf (&buf[strlen(buf)], ")");
  if (1 == strlen(buf2)) {          /* all addresses were multicast? */
    buf[strlen(buf)-6] = '\0';      /* Remove "not ()" */
    if (strlen(buf) > 0)
        buf[strlen(buf)-5] = '\0';  /* remove " and " */
    }
  }
if (strlen(buf) > 0)
  sprintf(&buf[strlen(buf)], ")");
/* When changing the Physical Address on a LAN interface, VMS sends out a 
   loopback packet with the source and destination addresses set to the same 
   value as the Physical Address which is being setup.  This packet is
   designed to find and help diagnose MAC address conflicts (which also 
   include DECnet address conflicts). Normally, this packet would not be 
   seen by the sender, only by the other machine that has the same Physical 
   Address (or possibly DECnet address). If the ethernet subsystem is 
   reflecting packets, the network startup will fail to start if it sees the 
   reflected packet, since it thinks another system is using this Physical 
   Address (or DECnet address). We have to let these packets through, so 
   that if another machine has the same Physical Address (or DECnet address)
   that we can detect it. Both eth_write() and _eth_callback() help by 
   checking the reflection count - eth_write() adds the reflection count to
   dev->loopback_self_sent, and _eth_callback() check the value - if the
   dev->loopback_self_sent count is zero, then the packet has come from 
   another machine with the same address, and needs to be passed on to the 
   simulated machine. */

memset(dev->physical_addr, 0, sizeof(ETH_MAC));
dev->loopback_self_sent = 0;
/* check for physical address in filters */
if ((addr_count) && (dev->reflections > 0)) {
  for (i = 0; i < addr_count; i++) {
    if (dev->filter_address[i][0]&1)
      continue;  /* skip all multicast addresses */
    eth_mac_fmt(&dev->filter_address[i], mac);
    if (strcmp(mac, "00:00:00:00:00:00") != 0) {
      memcpy(dev->physical_addr, &dev->filter_address[i], sizeof(ETH_MAC));
      /* let packets through where dst and src are the same as our physical address */
      sprintf (&buf[strlen(buf)], " or ((ether dst %s) and (ether src %s))", mac, mac);
      if (dev->have_host_nic_phy_addr) {
        eth_mac_fmt(&dev->host_nic_phy_hw_addr, mac);
        sprintf(&buf[strlen(buf)], " or ((ether dst %s) and (ether proto 0x9000))", mac);
      }
      break;
      }
    }
  }
if ((0 == strlen(buf)) && (!dev->promiscuous)) /* Empty filter means match nothing */
  strcpy(buf, "ether host fe:ff:ff:ff:ff:ff"); /* this should be a good match nothing filter */
sim_debug(dev->dbit, dev->dptr, "BPF string is: |%s|\n", buf);







/* get netmask, which is a required argument for compiling.  The value, 
   in our case isn't actually interesting since the filters we generate 
   aren't referencing IP fields, networks or values */

#ifdef USE_BPF
if (dev->eth_api == ETH_API_PCAP) {
................................................................................
    bpf_netmask = 0;
  /* compile filter string */
  if ((status = pcap_compile((pcap_t*)dev->handle, &bpf, buf, 1, bpf_netmask)) < 0) {
    sprintf(errbuf, "%s", pcap_geterr((pcap_t*)dev->handle));
    sim_printf("Eth: pcap_compile error: %s\n", errbuf);
    /* show erroneous BPF string */
    sim_printf ("Eth: BPF string is: |%s|\n", buf);




















    }
  else {
    /* apply compiled filter string */
    if ((status = pcap_setfilter((pcap_t*)dev->handle, &bpf)) < 0) {
      sprintf(errbuf, "%s", pcap_geterr((pcap_t*)dev->handle));
      sim_printf("Eth: pcap_setfilter error: %s\n", errbuf);

      }
    else {
      /* Save BPF filter string */
      dev->bpf_filter = (char *)realloc(dev->bpf_filter, 1 + strlen(buf));
      strcpy (dev->bpf_filter, buf);
#ifdef USE_SETNONBLOCK
      /* set file non-blocking */
................................................................................
if (pcap_findalldevs(&alldevs, errbuf) == -1) {
  sim_printf ("Eth: error in pcap_findalldevs: %s\n", errbuf);
  }
else {
  /* copy device list into the passed structure */
  for (i=0, dev=alldevs; dev && (i < max); dev=dev->next, ++i) {
    if ((dev->flags & PCAP_IF_LOOPBACK) || (!strcmp("any", dev->name))) continue;
    strncpy(list[i].name, dev->name, sizeof(list[i].name)-1);
    if (dev->description)
      strncpy(list[i].desc, dev->description, sizeof(list[i].desc)-1);
    else
      strncpy(list[i].desc, "No description available", sizeof(list[i].desc)-1);
    }

  /* free device list */
  pcap_freealldevs(alldevs);
  }
#endif

................................................................................
  fprintf(st, "  BPF Filter: %s\n", dev->bpf_filter);
#if defined(HAVE_SLIRP_NETWORK)
if (dev->eth_api == ETH_API_NAT)
  sim_slirp_show ((SLIRP *)dev->handle, st);
#endif
}










































































































































































t_stat sim_ether_test (DEVICE *dptr)
{







return SCPE_OK;
}
#endif /* USE_NETWORK */







|


|



|







 







|








|


|









|













|




|









|


|







 







|





|










|





|







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>


|
<
|
|
|
|
|
|
<
<
<
<
<
<
|
|
|
|
<
<
<
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






>







 







|

|

|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>
>
|


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
....
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
....
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
....
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
....
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
....
3749
3750
3751
3752
3753
3754
3755

3756
3757
3758
3759
3760
3761
3762
....
3801
3802
3803
3804
3805
3806
3807




























































3808
3809
3810
3811

3812
3813
3814
3815
3816
3817






3818
3819
3820
3821



3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
....
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
....
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
....
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294

  /* Allow generated MAC address */
  /* XX:XX:XX:XX:XX:XX{/bits{>file}} */
  /* bits (if specified) must be from 16 thru 48 */

  memset (&state, 0, sizeof(state));
  _eth_get_system_id (state.system_id, sizeof(state.system_id));
  strlcpy (state.sim, sim_name, sizeof(state.sim));
  getcwd (state.cwd, sizeof(state.cwd));
  if (uptr)
    strlcpy (state.uname, sim_uname (uptr), sizeof(state.uname));
  cptr = strchr (strmac, '>');
  if (cptr) {
    state.file[sizeof(state.file)-1] = '\0';
    strlcpy (state.file, cptr + 1, sizeof(state.file));
    if ((f = fopen (state.file, "r"))) {
      filebuf[sizeof(filebuf)-1] = '\0';
      fgets (filebuf, sizeof(filebuf)-1, f);
      strmac = filebuf;
      fclose (f);
      strcpy (state.file, "");  /* avoid saving */
      }
................................................................................
    /* Set up interface flags */
    strcpy(ifr.ifr_name, devname);
    ifr.ifr_flags = IFF_TAP|IFF_NO_PI;

    /* Send interface requests to TUN/TAP driver. */
    if (ioctl(tun, TUNSETIFF, &ifr) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
        close(tun);
        }
      else {
        *fd_handle = tun;
        strcpy(savname, ifr.ifr_name);
        }
      }
    else
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    }
  else
    strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
#elif defined(HAVE_BSDTUNTAP) && defined(HAVE_TAP_NETWORK)
  if (1) {
    char dev_name[64] = "";

    snprintf(dev_name, sizeof(dev_name)-1, "/dev/%s", devname);
    dev_name[sizeof(dev_name)-1] = '\0';

    if ((tun = open(dev_name, O_RDWR)) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
        close(tun);
        }
      else {
        *fd_handle = tun;
        strcpy(savname, devname);
        }
#if defined (__APPLE__)
      if (1) {
        struct ifreq ifr;
        int s;

        memset (&ifr, 0, sizeof(ifr));
        ifr.ifr_addr.sa_family = AF_INET;
        strlcpy(ifr.ifr_name, savname, sizeof(ifr.ifr_name));
        if ((s = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
          if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) >= 0) {
            ifr.ifr_flags |= IFF_UP;
            if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&ifr)) {
              strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
              close(tun);
              }
            }
          close(s);
          }
        }
#endif
      }
    else
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
  }
#else
  strlcpy(errbuf, "No support for tap: devices", PCAP_ERRBUF_SIZE);
#endif /* !defined(__linux) && !defined(HAVE_BSDTUNTAP) */
  if (0 == errbuf[0]) {
    *eth_api = ETH_API_TAP;
    *handle = (void *)1;  /* Flag used to indicated open */
    }
  }
else { /* !tap: */
................................................................................

      voa.port = (int)get_uint (vdeport_s, 10, 255, &r);
      if (r != SCPE_OK)
          return sim_messagef (SCPE_OPENERR, "Eth: Invalid vde port number: %s in %s\n", vdeport_s, savname);
      }

    if (!(*handle = (void*) vde_open((char *)vdeswitch_s, (char *)"simh", &voa)))
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    else {
      *eth_api = ETH_API_VDE;
      *fd_handle = vde_datafd((VDECONN*)(*handle));
      }
#else
    strlcpy(errbuf, "No support for vde: network devices", PCAP_ERRBUF_SIZE);
#endif /* defined(HAVE_VDE_NETWORK) */
    }
  else { /* !vde: */
    if (0 == strncmp("nat:", savname, 4)) {
#if defined(HAVE_SLIRP_NETWORK)
      const char *devname = savname + 4;

      while (isspace(*devname))
        ++devname;
      if (!(*handle = (void*) sim_slirp_open(devname, opaque, &_slirp_callback, dptr, dbit)))
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
      else {
        *eth_api = ETH_API_NAT;
        *fd_handle = 0;
        }
#else
      strlcpy(errbuf, "No support for nat: network devices", PCAP_ERRBUF_SIZE);
#endif /* defined(HAVE_SLIRP_NETWORK) */
      }
    else { /* not nat: */
      if (0 == strncmp("udp:", savname, 4)) {
        char localport[CBUFSIZE], host[CBUFSIZE], port[CBUFSIZE];
        char hostport[2*CBUFSIZE];
        const char *devname = savname + 4;
................................................................................
           */
          int v = 1;
          ioctl(pcap_fileno(*handle), BIOCIMMEDIATE, &v);
          }
#endif /* defined (__APPLE__) */
#endif /* !defined (USE_READER_THREAD) */
#else
        strlcpy (errbuf, "Unknown or unsupported network device", PCAP_ERRBUF_SIZE);
#endif /* defined(HAVE_PCAP_NETWORK) */
        } /* not udp:, so attempt to open the parameter as if it were an explicit device name */
      } /* !nat: */
    } /* !vde: */
  } /* !tap: */
if (errbuf[0])
  return SCPE_OPENERR;
................................................................................
  pthread_mutex_unlock (&dev->lock);  
  if ((status) && (routine))
    routine(0);
#endif

return status;
}

t_stat eth_bpf_filter (ETH_DEV* dev, int addr_count, ETH_MAC* const filter_address,
                       ETH_BOOL all_multicast, ETH_BOOL promiscuous, 
                       int reflections,
                       ETH_MAC* physical_addr,
                       ETH_MAC* host_nic_phy_hw_addr,
                       ETH_MULTIHASH* const hash,
                       char *buf)
{
int i;
char mac[20];
char *buf2;

/* setup BPF filters and other fields to minimize packet delivery */
strcpy(buf, "");

/* construct destination filters - since the real ethernet interface was set
   into promiscuous mode by eth_open(), we need to filter out the packets that
   our simulated interface doesn't want. */
if (!promiscuous) {
  for (i = 0; i < addr_count; i++) {
    eth_mac_fmt(&filter_address[i], mac);
    if (!strstr(buf, mac))    /* eliminate duplicates */
      sprintf(&buf[strlen(buf)], "%s(ether dst %s)", (*buf) ? " or " : "((", mac);
    }
  if (all_multicast || hash)
    sprintf(&buf[strlen(buf)], "%s(ether multicast)", (*buf) ? " or " : "((");
  if (strlen(buf) > 0)
    sprintf(&buf[strlen(buf)], ")");
  }

/* construct source filters - this prevents packets from being reflected back 
   by systems where WinPcap and libpcap cause packet reflections. Note that
   some systems do not reflect packets at all. This *assumes* that the 
   simulated NIC will not send out packets with multicast source fields. */
if ((addr_count > 0) && (reflections > 0)) {
  if (strlen(buf) > 0)
    sprintf(&buf[strlen(buf)], " and ");
  else
    if (promiscuous)
      sprintf(&buf[strlen(buf)], "(");
  sprintf (&buf[strlen(buf)], "not (");
  buf2 = &buf[strlen(buf)];
  for (i = 0; i < addr_count; i++) {
    if (filter_address[i][0] & 0x01) continue; /* skip multicast addresses */
    eth_mac_fmt(&filter_address[i], mac);
    if (!strstr(buf2, mac))   /* only process each address once */
      sprintf(&buf2[strlen(buf2)], "%s(ether src %s)", (*buf2) ? " or " : "", mac);
    }
  sprintf (&buf[strlen(buf)], ")");
  if (1 == strlen(buf2)) {          /* all addresses were multicast? */
    buf[strlen(buf)-6] = '\0';      /* Remove "not ()" */
    if (strlen(buf) > 0)
        buf[strlen(buf)-5] = '\0';  /* remove " and " */
    }
  }
if (strlen(buf) > 0)
  sprintf(&buf[strlen(buf)], ")");
/* When changing the Physical Address on a LAN interface, VMS sends out a 
   loopback packet with the source and destination addresses set to the same 
   value as the Physical Address which is being setup.  This packet is
   designed to find and help diagnose MAC address conflicts (which also 
   include DECnet address conflicts). Normally, this packet would not be 
   seen by the sender, only by the other machine that has the same Physical 
   Address (or possibly DECnet address). If the ethernet subsystem is 
   reflecting packets, the network startup will fail to start if it sees the 
   reflected packet, since it thinks another system is using this Physical 
   Address (or DECnet address). We have to let these packets through, so 
   that if another machine has the same Physical Address (or DECnet address)
   that we can detect it. Both eth_write() and _eth_callback() help by 
   checking the reflection count - eth_write() adds the reflection count to
   dev->loopback_self_sent, and _eth_callback() check the value - if the
   dev->loopback_self_sent count is zero, then the packet has come from 
   another machine with the same address, and needs to be passed on to the 
   simulated machine. */
/* check for physical address in filters */
if ((!promiscuous) && (addr_count) && (reflections > 0)) {
  eth_mac_fmt(&physical_addr[0], mac);
  if (strcmp(mac, "00:00:00:00:00:00") != 0) {
    /* let packets through where dst and src are the same as our physical address */
    sprintf (&buf[strlen(buf)], " or ((ether dst %s) and (ether src %s))", mac, mac);
    if (host_nic_phy_hw_addr) {
      eth_mac_fmt(&host_nic_phy_hw_addr[0], mac);
      sprintf(&buf[strlen(buf)], " or ((ether dst %s) and (ether proto 0x9000))", mac);
      }
    }
  }
if ((0 == strlen(buf)) && (!promiscuous)) /* Empty filter means match nothing */
  strcpy(buf, "ether host fe:ff:ff:ff:ff:ff"); /* this should be a good match nothing filter */
sim_debug(dev->dbit, dev->dptr, "BPF string is: |%s|\n", buf);
return SCPE_OK;
}

t_stat eth_filter(ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                  ETH_BOOL all_multicast, ETH_BOOL promiscuous)
{
return eth_filter_hash(dev, addr_count, addresses, 
                       all_multicast, promiscuous, 
                       NULL);
................................................................................
t_stat eth_filter_hash(ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                       ETH_BOOL all_multicast, ETH_BOOL promiscuous, 
                       ETH_MULTIHASH* const hash)
{
int i;
char buf[116+66*ETH_FILTER_MAX];
char mac[20];

t_stat status;
#ifdef USE_BPF
struct bpf_program bpf;
#endif

/* make sure device exists */
if (!dev) return SCPE_UNATT;
................................................................................
  if (dev->all_multicast) {
    sim_debug(dev->dbit, dev->dptr, "All Multicast\n");
    }
  if (dev->promiscuous) {
    sim_debug(dev->dbit, dev->dptr, "Promiscuous\n");
    }
  }




























































/* Set the desired physical address */
memset(dev->physical_addr, 0, sizeof(ETH_MAC));
dev->loopback_self_sent = 0;
/* Find desired physical address in filters */

for (i = 0; i < addr_count; i++) {
  if (dev->filter_address[i][0]&1)
    continue;  /* skip all multicast addresses */
  eth_mac_fmt(&dev->filter_address[i], mac);
  if (strcmp(mac, "00:00:00:00:00:00") != 0) {
    memcpy(dev->physical_addr, &dev->filter_address[i], sizeof(ETH_MAC));






    break;
    }
  }




/* setup BPF filters and other fields to minimize packet delivery */
eth_bpf_filter (dev, dev->addr_count, dev->filter_address, 
                dev->all_multicast, dev->promiscuous, 
                dev->reflections, &dev->physical_addr, 
                dev->have_host_nic_phy_addr ? &dev->host_nic_phy_hw_addr: NULL,
                &dev->hash, buf);

/* get netmask, which is a required argument for compiling.  The value, 
   in our case isn't actually interesting since the filters we generate 
   aren't referencing IP fields, networks or values */

#ifdef USE_BPF
if (dev->eth_api == ETH_API_PCAP) {
................................................................................
    bpf_netmask = 0;
  /* compile filter string */
  if ((status = pcap_compile((pcap_t*)dev->handle, &bpf, buf, 1, bpf_netmask)) < 0) {
    sprintf(errbuf, "%s", pcap_geterr((pcap_t*)dev->handle));
    sim_printf("Eth: pcap_compile error: %s\n", errbuf);
    /* show erroneous BPF string */
    sim_printf ("Eth: BPF string is: |%s|\n", buf);
    sim_printf ("Eth: Input to BPF string construction:\n");
    sim_printf ("Eth: Reflections: %d\n", dev->reflections);
    sim_printf ("Eth: Filter Set:\n");
    for (i = 0; i < addr_count; i++) {
      char mac[20];
      eth_mac_fmt(&dev->filter_address[i], mac);
      sim_printf ("Eth:   Addr[%d]: %s\n", i, mac);
      }
    if (dev->all_multicast)
      sim_printf ("Eth: All Multicast\n");
    if (dev->promiscuous)
      sim_printf ("Eth: Promiscuous\n");
    if (dev->hash_filter)
      sim_printf ("Eth: Multicast Hash: %02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n",
                  dev->hash[0], dev->hash[1], dev->hash[2], dev->hash[3], 
                  dev->hash[4], dev->hash[5], dev->hash[6], dev->hash[7]);
    if (dev->have_host_nic_phy_addr) {
      eth_mac_fmt(&dev->host_nic_phy_hw_addr, mac);
      sim_printf ("Eth: host_nic_phy_hw_addr: %s\n", mac);
      }
    }
  else {
    /* apply compiled filter string */
    if ((status = pcap_setfilter((pcap_t*)dev->handle, &bpf)) < 0) {
      sprintf(errbuf, "%s", pcap_geterr((pcap_t*)dev->handle));
      sim_printf("Eth: pcap_setfilter error: %s\n", errbuf);
      sim_printf ("Eth: BPF string is: |%s|\n", buf);
      }
    else {
      /* Save BPF filter string */
      dev->bpf_filter = (char *)realloc(dev->bpf_filter, 1 + strlen(buf));
      strcpy (dev->bpf_filter, buf);
#ifdef USE_SETNONBLOCK
      /* set file non-blocking */
................................................................................
if (pcap_findalldevs(&alldevs, errbuf) == -1) {
  sim_printf ("Eth: error in pcap_findalldevs: %s\n", errbuf);
  }
else {
  /* copy device list into the passed structure */
  for (i=0, dev=alldevs; dev && (i < max); dev=dev->next, ++i) {
    if ((dev->flags & PCAP_IF_LOOPBACK) || (!strcmp("any", dev->name))) continue;
    strlcpy(list[i].name, dev->name, sizeof(list[i].name));
    if (dev->description)
      strlcpy(list[i].desc, dev->description, sizeof(list[i].desc));
    else
      strlcpy(list[i].desc, "No description available", sizeof(list[i].desc));
    }

  /* free device list */
  pcap_freealldevs(alldevs);
  }
#endif

................................................................................
  fprintf(st, "  BPF Filter: %s\n", dev->bpf_filter);
#if defined(HAVE_SLIRP_NETWORK)
if (dev->eth_api == ETH_API_NAT)
  sim_slirp_show ((SLIRP *)dev->handle, st);
#endif
}

static
t_stat eth_test_crc32 (DEVICE *dptr)
{
int errors = 0;
int val;
uint8 data[12];
static uint32 valcrc32[] = {
  0x7BD5C66F, 0x92C4D707, 0x7286E2FE, 0x9B97F396, 0x69738F4D, 0x80629E25, 0x6020ABDC, 0x8931BAB4,
  0x5E99542B, 0xB7884543, 0x57CA70BA, 0xBEDB61D2, 0x4C3F1D09, 0xA52E0C61, 0x456C3998, 0xAC7D28F0,
  0x314CE2E7, 0xD85DF38F, 0x381FC676, 0xD10ED71E, 0x23EAABC5, 0xCAFBBAAD, 0x2AB98F54, 0xC3A89E3C,
  0x140070A3, 0xFD1161CB, 0x1D535432, 0xF442455A, 0x06A63981, 0xEFB728E9, 0x0FF51D10, 0xE6E40C78,
  0xEEE78F7F, 0x07F69E17, 0xE7B4ABEE, 0x0EA5BA86, 0xFC41C65D, 0x1550D735, 0xF512E2CC, 0x1C03F3A4,
  0xCBAB1D3B, 0x22BA0C53, 0xC2F839AA, 0x2BE928C2, 0xD90D5419, 0x301C4571, 0xD05E7088, 0x394F61E0,
  0xA47EABF7, 0x4D6FBA9F, 0xAD2D8F66, 0x443C9E0E, 0xB6D8E2D5, 0x5FC9F3BD, 0xBF8BC644, 0x569AD72C,
  0x813239B3, 0x682328DB, 0x88611D22, 0x61700C4A, 0x93947091, 0x7A8561F9, 0x9AC75400, 0x73D64568,
  0x8AC0520E, 0x63D14366, 0x8393769F, 0x6A8267F7, 0x98661B2C, 0x71770A44, 0x91353FBD, 0x78242ED5,
  0xAF8CC04A, 0x469DD122, 0xA6DFE4DB, 0x4FCEF5B3, 0xBD2A8968, 0x543B9800, 0xB479ADF9, 0x5D68BC91,
  0xC0597686, 0x294867EE, 0xC90A5217, 0x201B437F, 0xD2FF3FA4, 0x3BEE2ECC, 0xDBAC1B35, 0x32BD0A5D,
  0xE515E4C2, 0x0C04F5AA, 0xEC46C053, 0x0557D13B, 0xF7B3ADE0, 0x1EA2BC88, 0xFEE08971, 0x17F19819,
  0x1FF21B1E, 0xF6E30A76, 0x16A13F8F, 0xFFB02EE7, 0x0D54523C, 0xE4454354, 0x040776AD, 0xED1667C5,
  0x3ABE895A, 0xD3AF9832, 0x33EDADCB, 0xDAFCBCA3, 0x2818C078, 0xC109D110, 0x214BE4E9, 0xC85AF581,
  0x556B3F96, 0xBC7A2EFE, 0x5C381B07, 0xB5290A6F, 0x47CD76B4, 0xAEDC67DC, 0x4E9E5225, 0xA78F434D,
  0x7027ADD2, 0x9936BCBA, 0x79748943, 0x9065982B, 0x6281E4F0, 0x8B90F598, 0x6BD2C061, 0x82C3D109,
  0x428FE8EC, 0xAB9EF984, 0x4BDCCC7D, 0xA2CDDD15, 0x5029A1CE, 0xB938B0A6, 0x597A855F, 0xB06B9437,
  0x67C37AA8, 0x8ED26BC0, 0x6E905E39, 0x87814F51, 0x7565338A, 0x9C7422E2, 0x7C36171B, 0x95270673,
  0x0816CC64, 0xE107DD0C, 0x0145E8F5, 0xE854F99D, 0x1AB08546, 0xF3A1942E, 0x13E3A1D7, 0xFAF2B0BF,
  0x2D5A5E20, 0xC44B4F48, 0x24097AB1, 0xCD186BD9, 0x3FFC1702, 0xD6ED066A, 0x36AF3393, 0xDFBE22FB,
  0xD7BDA1FC, 0x3EACB094, 0xDEEE856D, 0x37FF9405, 0xC51BE8DE, 0x2C0AF9B6, 0xCC48CC4F, 0x2559DD27,
  0xF2F133B8, 0x1BE022D0, 0xFBA21729, 0x12B30641, 0xE0577A9A, 0x09466BF2, 0xE9045E0B, 0x00154F63,
  0x9D248574, 0x7435941C, 0x9477A1E5, 0x7D66B08D, 0x8F82CC56, 0x6693DD3E, 0x86D1E8C7, 0x6FC0F9AF,
  0xB8681730, 0x51790658, 0xB13B33A1, 0x582A22C9, 0xAACE5E12, 0x43DF4F7A, 0xA39D7A83, 0x4A8C6BEB,
  0xB39A7C8D, 0x5A8B6DE5, 0xBAC9581C, 0x53D84974, 0xA13C35AF, 0x482D24C7, 0xA86F113E, 0x417E0056,
  0x96D6EEC9, 0x7FC7FFA1, 0x9F85CA58, 0x7694DB30, 0x8470A7EB, 0x6D61B683, 0x8D23837A, 0x64329212,
  0xF9035805, 0x1012496D, 0xF0507C94, 0x19416DFC, 0xEBA51127, 0x02B4004F, 0xE2F635B6, 0x0BE724DE,
  0xDC4FCA41, 0x355EDB29, 0xD51CEED0, 0x3C0DFFB8, 0xCEE98363, 0x27F8920B, 0xC7BAA7F2, 0x2EABB69A,
  0x26A8359D, 0xCFB924F5, 0x2FFB110C, 0xC6EA0064, 0x340E7CBF, 0xDD1F6DD7, 0x3D5D582E, 0xD44C4946,
  0x03E4A7D9, 0xEAF5B6B1, 0x0AB78348, 0xE3A69220, 0x1142EEFB, 0xF853FF93, 0x1811CA6A, 0xF100DB02,
  0x6C311115, 0x8520007D, 0x65623584, 0x8C7324EC, 0x7E975837, 0x9786495F, 0x77C47CA6, 0x9ED56DCE,
  0x497D8351, 0xA06C9239, 0x402EA7C0, 0xA93FB6A8, 0x5BDBCA73, 0xB2CADB1B, 0x5288EEE2, 0xBB99FF8A};

for (val=0; val <= 0xFF; val++) {
  memset (data, val, sizeof (data));
  if (valcrc32[val] != eth_crc32 (0, data, sizeof (data))) {
    printf("Unexpected CRC for %d byte buffer containing 0x%02X. Expected %08X, got %08X\n",
           (int)sizeof (data), val, valcrc32[val], eth_crc32 (0, data, sizeof (data)));
    ++errors;
    }
  }
return (errors == 0) ? SCPE_OK : SCPE_IERR;
}

static
t_stat eth_test_bpf (DEVICE *dptr)
{
int errors = 0;
#ifdef USE_BPF
t_stat r;
DEVICE eth_tst;
ETH_DEV dev;
int reflections, all_multicast, promiscuous;
char buf[116+66*ETH_FILTER_MAX];
char mac[20];
ETH_MAC filter_address[3] = {
    {0x04, 0x05, 0x06, 0x07, 0x08, 0x09},
    {0x09, 0x00, 0x2B, 0x02, 0x01, 0x07},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
  };
int addr_count;
ETH_MAC physical_addr = {0x04, 0x05, 0x06, 0x07, 0x08, 0x09};
ETH_MAC host_nic_phy_hw_addr = {0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
ETH_MAC *host_phy_addr_list[2] = {&host_nic_phy_hw_addr, NULL};
int host_phy_addr_listindex;
ETH_MULTIHASH hash = {0x01, 0x40, 0x00, 0x00, 0x48, 0x88, 0x40, 0x00};
ETH_MULTIHASH *hash_list[2] = {&hash, NULL};
int hash_listindex;
int bpf_count = 0;
int bpf_construct_error_count = 0;
int bpf_compile_error_count = 0;
int bpf_compile_skip_count = 0;
#define SIM_PRINT_BPF_ARGUMENTS                                 \
    if (1) {                                                    \
      sim_printf ("Eth: Input to BPF string construction:\n");  \
      sim_printf ("Eth: Reflections: %d\n", reflections);       \
      sim_printf ("Eth: Filter Set:\n");                        \
      for (i = 0; i < addr_count; i++) {                        \
        eth_mac_fmt(&filter_address[i], mac);                   \
        sim_printf ("Eth:   Addr[%d]: %s\n", i, mac);           \
        }                                                       \
      if (all_multicast)                                        \
        sim_printf ("Eth: All Multicast\n");                    \
      if (promiscuous)                                          \
        sim_printf ("Eth: Promiscuous\n");                      \
      if (hash_list[hash_listindex])                            \
        sim_printf ("Eth: Multicast Hash: %02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n",\
                    (*hash_list[hash_listindex])[0], (*hash_list[hash_listindex])[1], (*hash_list[hash_listindex])[2], (*hash_list[hash_listindex])[3], \
                    (*hash_list[hash_listindex])[4], (*hash_list[hash_listindex])[5], (*hash_list[hash_listindex])[6], (*hash_list[hash_listindex])[7]);\
      if (host_phy_addr_list[host_phy_addr_listindex]) {        \
        eth_mac_fmt(host_phy_addr_list[host_phy_addr_listindex], mac);\
        sim_printf ("Eth: host_nic_phy_hw_addr: %s\n", mac);    \
        }                                                       \
      }


memset (&eth_tst, 0, sizeof(eth_tst));
eth_open(&dev, "eth0", &eth_tst, 1);
for (reflections=0; reflections<=1; reflections++) {
  for (all_multicast=0; all_multicast<=1; all_multicast++) {
    for (promiscuous=0; promiscuous<=1; promiscuous++) {
      for (addr_count=1; addr_count<=2; addr_count++) {
        for (hash_listindex=0; hash_listindex<=1; hash_listindex++) {
          for (host_phy_addr_listindex=0; host_phy_addr_listindex<=1; host_phy_addr_listindex++) {
            int i;
            char errbuf[PCAP_ERRBUF_SIZE];

            ++bpf_count;
            r = eth_bpf_filter (&dev, addr_count, &filter_address[0], 
                                all_multicast, promiscuous, reflections, 
                                &filter_address[0], 
                                host_phy_addr_list[host_phy_addr_listindex],
                                hash_list[hash_listindex],
                                buf);
            if (r != SCPE_OK) {
              ++bpf_construct_error_count;
              sim_printf ("Eth: Error producing a BPF filter for:\n");
              SIM_PRINT_BPF_ARGUMENTS;
              }
            else {
              if (sim_switches & SWMASK('D')) {
                SIM_PRINT_BPF_ARGUMENTS;
                sim_printf ("Eth: BPF string is: |%s|\n", buf);
                }
              if (dev.eth_api == ETH_API_PCAP) {
                struct bpf_program bpf;

                if (pcap_compile ((pcap_t*)dev.handle, &bpf, buf, 1, (bpf_u_int32)0) < 0) {
                  ++bpf_compile_error_count;
                  sprintf(errbuf, "%s", pcap_geterr((pcap_t*)dev.handle));
                  sim_printf("Eth: pcap_compile error: %s\n", errbuf);
                  if (!(sim_switches & SWMASK('D'))) {
                    /* show erroneous BPF string */
                    SIM_PRINT_BPF_ARGUMENTS;
                    sim_printf ("Eth: BPF string is: |%s|\n", buf);
                    }
                  }
                pcap_freecode(&bpf);
                }
              else
                ++bpf_compile_skip_count;
              }
            }
          }
        }
      }
    }
  }
eth_close(&dev);
sim_printf ("BPF Filter Count:     %d\n", bpf_count);
if (bpf_construct_error_count)
  sim_printf ("BPF Construct Errors: %d\n", bpf_construct_error_count);
if (bpf_compile_error_count)
  sim_printf ("BPF Compile Errors:   %d\n", bpf_compile_error_count);
if (bpf_compile_skip_count)
  sim_printf ("BPF Compile Skipped:  %d\n", bpf_compile_skip_count);
#endif /* USE_BPF */
return (errors == 0) ? SCPE_OK : SCPE_IERR;
}

#include <setjmp.h>

t_stat sim_ether_test (DEVICE *dptr)
{
t_stat stat = SCPE_OK;
SIM_TEST_INIT;

sim_printf ("Testing %s device sim_ether APIs\n", dptr->name);

SIM_TEST(eth_test_crc32 (dptr));
SIM_TEST(eth_test_bpf (dptr));
return stat;
}
#endif /* USE_NETWORK */

Changes to src/SIMH/sim_fio.c.

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
...
201
202
203
204
205
206
207
208

209
210

211
212
213
214
215
216
217
   02-Jan-04    RMS     Split out from SCP

   This library includes:

   sim_finit         -       initialize package
   sim_fopen         -       open file
   sim_fread         -       endian independent read (formerly fxread)
   sim_write         -       endian independent write (formerly fxwrite)
   sim_fseek         -       conditionally extended (>32b) seek (
   sim_fseeko        -       extended seek (>32b if available)
   sim_fsize         -       get file size
   sim_fsize_name    -       get file size of named file
   sim_fsize_ex      -       get file size as a t_offset
   sim_fsize_name_ex -       get file size as a t_offset of named file
   sim_buf_copy_swapped -    copy data swapping elements along the way
................................................................................
t_offset sim_fsize_ex (FILE *fp)
{
t_offset pos, sz;

if (fp == NULL)
    return 0;
pos = sim_ftell (fp);
sim_fseeko (fp, 0, SEEK_END);

sz = sim_ftell (fp);
sim_fseeko (fp, pos, SEEK_SET);

return sz;
}

t_offset sim_fsize_name_ex (const char *fname)
{
FILE *fp;
t_offset sz;







|







 







|
>

|
>







37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
...
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
   02-Jan-04    RMS     Split out from SCP

   This library includes:

   sim_finit         -       initialize package
   sim_fopen         -       open file
   sim_fread         -       endian independent read (formerly fxread)
   sim_fwrite        -       endian independent write (formerly fxwrite)
   sim_fseek         -       conditionally extended (>32b) seek (
   sim_fseeko        -       extended seek (>32b if available)
   sim_fsize         -       get file size
   sim_fsize_name    -       get file size of named file
   sim_fsize_ex      -       get file size as a t_offset
   sim_fsize_name_ex -       get file size as a t_offset of named file
   sim_buf_copy_swapped -    copy data swapping elements along the way
................................................................................
t_offset sim_fsize_ex (FILE *fp)
{
t_offset pos, sz;

if (fp == NULL)
    return 0;
pos = sim_ftell (fp);
if (sim_fseeko (fp, 0, SEEK_END))
    return 0;
sz = sim_ftell (fp);
if (sim_fseeko (fp, pos, SEEK_SET))
    return 0;
return sz;
}

t_offset sim_fsize_name_ex (const char *fname)
{
FILE *fp;
t_offset sz;

Changes to src/SIMH/sim_serial.c.

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

static struct open_serial_device *_serial_add_to_open_list (SERHANDLE port, TMLN *line, const char *name, const char *config)
{
serial_open_devices = (struct open_serial_device *)realloc(serial_open_devices, (++serial_open_device_count)*sizeof(*serial_open_devices));
memset(&serial_open_devices[serial_open_device_count-1], 0, sizeof(serial_open_devices[serial_open_device_count-1]));
serial_open_devices[serial_open_device_count-1].port = port;
serial_open_devices[serial_open_device_count-1].line = line;
strncpy(serial_open_devices[serial_open_device_count-1].name, name, sizeof(serial_open_devices[serial_open_device_count-1].name)-1);
if (config)
    strncpy(serial_open_devices[serial_open_device_count-1].config, config, sizeof(serial_open_devices[serial_open_device_count-1].config)-1);
return &serial_open_devices[serial_open_device_count-1];
}

static void _serial_remove_from_open_list (SERHANDLE port)
{
int i, j;








|

|







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

static struct open_serial_device *_serial_add_to_open_list (SERHANDLE port, TMLN *line, const char *name, const char *config)
{
serial_open_devices = (struct open_serial_device *)realloc(serial_open_devices, (++serial_open_device_count)*sizeof(*serial_open_devices));
memset(&serial_open_devices[serial_open_device_count-1], 0, sizeof(serial_open_devices[serial_open_device_count-1]));
serial_open_devices[serial_open_device_count-1].port = port;
serial_open_devices[serial_open_device_count-1].line = line;
strlcpy(serial_open_devices[serial_open_device_count-1].name, name, sizeof(serial_open_devices[serial_open_device_count-1].name));
if (config)
    strlcpy(serial_open_devices[serial_open_device_count-1].config, config, sizeof(serial_open_devices[serial_open_device_count-1].config));
return &serial_open_devices[serial_open_device_count-1];
}

static void _serial_remove_from_open_list (SERHANDLE port)
{
int i, j;

Changes to src/SIMH/sim_sock.h.

86
87
88
89
90
91
92
93

94

95
96
97
98
99
100
101
#define WSAEHOSTUNREACH EHOSTUNREACH
#define WSAEADDRINUSE   EADDRINUSE
#if defined(EAFNOSUPPORT)
#define WSAEAFNOSUPPORT EAFNOSUPPORT
#endif
#define WSAEACCES       EACCES
#define WSAEINTR        EINTR
#define INVALID_SOCKET  ((SOCKET)-1) 

#define SOCKET_ERROR    -1

#endif

#if defined (VMS)                                       /* VMS unique */
#include <ioctl.h>                                      /* for ioctl */
#if !defined (AI_NUMERICHOST)
#define AI_NUMERICHOST 0
#endif







|
>
|
>







86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#define WSAEHOSTUNREACH EHOSTUNREACH
#define WSAEADDRINUSE   EADDRINUSE
#if defined(EAFNOSUPPORT)
#define WSAEAFNOSUPPORT EAFNOSUPPORT
#endif
#define WSAEACCES       EACCES
#define WSAEINTR        EINTR
#define INVALID_SOCKET  ((SOCKET)-1)
#if !defined(SOCKET_ERROR)
#define SOCKET_ERROR    (-1)
#endif
#endif

#if defined (VMS)                                       /* VMS unique */
#include <ioctl.h>                                      /* for ioctl */
#if !defined (AI_NUMERICHOST)
#define AI_NUMERICHOST 0
#endif

Changes to src/SIMH/sim_tape.c.

98
99
100
101
102
103
104
105
106

107
108
109
110
111
112
113
114

115
116
117
118
119
120
121
...
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
...
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
...
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
...
712
713
714
715
716
717
718


719

720
721
722
723
724

725
726
727
728
729
730
731
...
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
...
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
...
890
891
892
893
894
895
896
897
898

































899


































900


901
902
903
904
905
906
907
...
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
...
965
966
967
968
969
970
971


972
973
974
975
976
977

978
979
980
981
982
983
984
....
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
....
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
....
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
....
1176
1177
1178
1179
1180
1181
1182
1183

1184

1185
1186
1187
1188
1189
1190
1191
....
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
....
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
....
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
....
1381
1382
1383
1384
1385
1386
1387


1388
1389
1390
1391
1392
1393
1394
....
1403
1404
1405
1406
1407
1408
1409


1410
1411



1412

1413
1414
1415

1416
1417
1418
1419
1420
1421
1422
....
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
....
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
....
2348
2349
2350
2351
2352
2353
2354

2355
2356
2357
2358
2359
2360
2361
....
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
....
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602

2603






















2604
2605

























2606




2607





2608
2609

















2610
2611



















































2612




























2613
2614
2615
2616
2617
2618
2619
....
2746
2747
2748
2749
2750
2751
2752
2753




















































































































































































































































































































2754
2755


































2756
2757

#if defined SIM_ASYNCH_IO
#include <pthread.h>
#endif

struct sim_tape_fmt {
    const char          *name;                          /* name */
    int32               uflags;                         /* unit flags */
    t_addr              bot;                            /* bot test */

    };

static struct sim_tape_fmt fmts[MTUF_N_FMT] = {
    { "SIMH", 0,       sizeof (t_mtrlnt) - 1 },
    { "E11",  0,       sizeof (t_mtrlnt) - 1 },
    { "TPC",  UNIT_RO, sizeof (t_tpclnt) - 1 },
    { "P7B",  0,       0 },
/*  { "TPF",  UNIT_RO, 0 }, */

    { NULL,   0,       0 }
    };

static const uint32 bpi [] = {                          /* tape density table, indexed by MT_DENS constants */
    0,                                                  /*   0 = MT_DENS_NONE -- density not set */
    200,                                                /*   1 = MT_DENS_200  -- 200 bpi NRZI */
    556,                                                /*   2 = MT_DENS_556  -- 556 bpi NRZI */
................................................................................
    6250                                                /*   5 = MT_DENS_6250 -- 6250 bpi GCR */
    };

#define BPI_COUNT       (sizeof (bpi) / sizeof (bpi [0]))   /* count of density table entries */

static t_stat sim_tape_ioerr (UNIT *uptr);
static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat);
static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize);
static t_stat sim_tape_simh_check (UNIT *uptr);
static t_stat sim_tape_e11_check (UNIT *uptr);
static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map);
static void sim_tape_data_trace (UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason);
static t_stat tape_erase_fwd (UNIT *uptr, t_mtrlnt gap_size);
static t_stat tape_erase_rev (UNIT *uptr, t_mtrlnt gap_size);


struct tape_context {
    DEVICE              *dptr;              /* Device for unit (access to debug flags) */
    uint32              dbit;               /* debugging bit for trace */
    uint32              auto_format;        /* Format determined dynamically */
#if defined SIM_ASYNCH_IO
    int                 asynch_io;          /* Asynchronous Interrupt scheduling enabled */
................................................................................

t_stat sim_tape_attach (UNIT *uptr, CONST char *cptr)
{
DEVICE *dptr;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
return sim_tape_attach_ex (uptr, cptr, ((dptr->flags & DEV_DEBUG) || (dptr->debflags)) ? 0xFFFFFFFF : 0, 0);
}

t_stat sim_tape_attach_ex (UNIT *uptr, const char *cptr, uint32 dbit, int completion_delay)
{
struct tape_context *ctx;
uint32 objc;
DEVICE *dptr;
char gbuf[CBUFSIZE];
t_stat r;
t_bool auto_format = FALSE;




if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
if (sim_switches & SWMASK ('F')) {                      /* format spec? */
    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    if (sim_tape_set_fmt (uptr, 0, gbuf, NULL) != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Tape Format: %s\n", gbuf);
    sim_switches = sim_switches & ~(SWMASK ('F'));      /* Record Format specifier already processed */
    auto_format = TRUE;
    }
if (MT_GET_FMT (uptr) == MTUF_F_TPC)

















    sim_switches |= SWMASK ('R');                       /* Force ReadOnly attach for TPC tapes */
r = attach_unit (uptr, (CONST char *)cptr);             /* attach unit */
if (r != SCPE_OK)                                       /* error? */
    return sim_messagef (r, "Can't open tape image: %s\n", cptr);
switch (MT_GET_FMT (uptr)) {                            /* case on format */


    case MTUF_F_STD:                                    /* SIMH */
        if (SCPE_OK != sim_tape_simh_check (uptr)) {
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        break;


    case MTUF_F_E11:                                    /* E11 */
        if (SCPE_OK != sim_tape_e11_check (uptr)) {
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */

            }
        break;


    case MTUF_F_TPC:                                    /* TPC */
        objc = sim_tape_tpc_map (uptr, NULL, 0);        /* get # objects */
        if (objc == 0) {                                /* tape empty? */
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        uptr->filebuf = calloc (objc + 1, sizeof (t_addr));
        if (uptr->filebuf == NULL) {                    /* map allocated? */
            sim_tape_detach (uptr);
            return SCPE_MEM;                            /* no, complain */
            }
        uptr->hwmark = objc + 1;                        /* save map size */
        sim_tape_tpc_map (uptr, (t_addr *) uptr->filebuf, objc);/* fill map */
        break;





    default:
        break;
        }

uptr->tape_ctx = ctx = (struct tape_context *)calloc(1, sizeof(struct tape_context));
ctx->dptr = dptr;                                       /* save DEVICE pointer */
ctx->dbit = dbit;                                       /* save debug bit */
ctx->auto_format = auto_format;                         /* save that we auto selected format */



sim_tape_rewind (uptr);

#if defined (SIM_ASYNCH_IO)
sim_tape_set_async (uptr, completion_delay);
#endif
uptr->io_flush = _sim_tape_io_flush;






return SCPE_OK;
}

/* Detach tape unit */

t_stat sim_tape_detach (UNIT *uptr)
{
struct tape_context *ctx;
uint32 f;
t_stat r;
t_bool auto_format = FALSE;

if (uptr == NULL)
    return SCPE_IERR;



ctx = (struct tape_context *)uptr->tape_ctx;
f = MT_GET_FMT (uptr);
if ((ctx == NULL) || !(uptr->flags & UNIT_ATT))
    return SCPE_IERR;

if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */
if (ctx)
    auto_format = ctx->auto_format;

sim_tape_clr_async (uptr);


r = detach_unit (uptr);                                 /* detach unit */
if (r != SCPE_OK)
    return r;
switch (f) {                                            /* case on format */

    case MTUF_F_TPC:                                    /* TPC */
        if (uptr->filebuf)                              /* free map */
            free (uptr->filebuf);
        uptr->filebuf = NULL;
        uptr->hwmark = 0;
        break;

    default:
        break;
        }



sim_tape_rewind (uptr);
free (uptr->tape_ctx);
uptr->tape_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)    /* format was determined or specified at attach time? */
    sim_tape_set_fmt (uptr, 0, "SIMH", NULL);   /* restore default format */
................................................................................
else
    fprintf (st, "  sim> ATTACH {switches} %s tapefile\n\n", dptr->name);
fprintf (st, "Attach command switches\n");
fprintf (st, "    -R          Attach Read Only.\n");
fprintf (st, "    -E          Must Exist (if not specified an attempt to create the indicated\n");
fprintf (st, "                virtual tape will be attempted).\n");
fprintf (st, "    -F          Open the indicated tape container in a specific format (default\n");
fprintf (st, "                is SIMH, alternatives are E11, TPC and P7B)\n");










return SCPE_OK;
}

static void sim_tape_data_trace(UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)
    return;
if (sim_deb && (ctx->dptr->dctrl & reason))
    sim_data_trace(ctx->dptr, uptr, (detail ? data : NULL), "", len, txt, reason);
}

/* Read record length forward (internal routine).

   Inputs:
        uptr    =       pointer to tape unit
................................................................................
static t_stat sim_tape_rdlntf (UNIT *uptr, t_mtrlnt *bc)
{
uint8    c;
t_bool   all_eof;
uint32   f = MT_GET_FMT (uptr);
t_mtrlnt sbc;
t_tpclnt tpcbc;


t_mtrlnt buffer [256];                                  /* local tape buffer */

uint32   bufcntr, bufcap;                               /* buffer counter and capacity */
int32    runaway_counter, sizeof_gap;                   /* bytes remaining before runaway and bytes per gap */
t_stat   status = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */


if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */

if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* set the initial tape position; if it fails */
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    status = sim_tape_ioerr (uptr);                     /*     and quit with I/O error status */
................................................................................
                if (sizeof_gap > 0)                     /*   then if detection is enabled */
                    status = MTSE_RUNAWAY;              /*     then report a tape runaway */
                else                                    /*   otherwise report the physical EOF */
                    status = MTSE_EOM;                  /*     as the end-of-medium */
                break;
                }

            uptr->pos = uptr->pos + sizeof (t_mtrlnt);  /* space over the marker */

            if (*bc == MTR_TMK) {                       /* if the value is a tape mark */
                status = MTSE_TMK;                      /*   then quit with tape mark status */
                break;
                }

            else if (*bc == MTR_GAP)                    /* otherwise if the value is a full gap */
................................................................................
                if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* set the tape position; if it fails */
                    status = sim_tape_ioerr (uptr);                     /*   then quit with I/O error status */
                    break;
                    }

                bufcntr = bufcap;                       /* mark the buffer as invalid to force a read */

                *bc = MTR_GAP;                          /* reset the marker */
                runaway_counter -= sizeof_gap / 2;      /*   and decrement the gap counter */
                }

            else {                                                      /* otherwise it's a record marker */
                if (bufcntr < bufcap                                    /* if the position is within the buffer */
                  && sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {  /*   then seek to the data area; if it fails */
                    status = sim_tape_ioerr (uptr);                     /*     then quit with I/O error status */
                    break;
                    }

                sbc = MTR_L (*bc);                              /* extract the record length */
                uptr->pos = uptr->pos + sizeof (t_mtrlnt)       /* position to the start */
                  + (f == MTUF_F_STD ? (sbc + 1) & ~1 : sbc);   /*   of the record */
                }
            }
        while (*bc == MTR_GAP && runaway_counter > 0);  /* continue until data or runaway occurs */

        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */




























        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = tpcbc;                                    /* save rec lnt */

        if (ferror (uptr->fileref)) {                   /* error? */
            MT_SET_PNU (uptr);                          /* pos not upd */
            status = sim_tape_ioerr (uptr);
            }

        else if (feof (uptr->fileref)) {                /* eof? */


            MT_SET_PNU (uptr);                          /* pos not upd */
            status = MTSE_EOM;
            }
        else {
            uptr->pos = uptr->pos + sizeof (t_tpclnt);  /* spc over reclnt */
            if (tpcbc == TPC_TMK)                       /* tape mark? */
                status = MTSE_TMK;
            else
                uptr->pos = uptr->pos + ((tpcbc + 1) & ~1); /* spc over record */

            }
        break;

    case MTUF_F_P7B:
        for (sbc = 0, all_eof = 1; ; sbc++) {           /* loop thru record */
            sim_fread (&c, sizeof (uint8), 1, uptr->fileref);

            if (ferror (uptr->fileref)) {               /* error? */
                MT_SET_PNU (uptr);                      /* pos not upd */
                status = sim_tape_ioerr (uptr);
                break;
                }
            else if (feof (uptr->fileref)) {            /* eof? */
................................................................................
                break;
            else if ((c & P7B_DPAR) != P7B_EOF)
                all_eof = 0;
            }

        if (status == MTSE_OK) {
            *bc = sbc;                                      /* save rec lnt */
            sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for read */
            uptr->pos = uptr->pos + sbc;                    /* spc over record */

































            if (all_eof)                                    /* tape mark? */


































                status = MTSE_TMK;


            }
        break;

    default:
        status = MTSE_FMT;
    }

................................................................................
t_stat status;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */

status = sim_tape_rdlntf (uptr, bc);                    /* read the record length */

sim_debug (MTSE_DBG_STR, ctx->dptr, "rd_lnt: st: %d, lnt: %d, pos: %" T_ADDR_FMT "u\n", status, *bc, uptr->pos);

return status;
}

/* Read record length reverse (internal routine).

   Inputs:
................................................................................
{
uint8    c;
t_bool   all_eof;
uint32   f = MT_GET_FMT (uptr);
t_addr   ppos;
t_mtrlnt sbc;
t_tpclnt tpcbc;


t_mtrlnt buffer [256];                                  /* local tape buffer */
uint32   bufcntr, bufcap;                               /* buffer counter and capacity */
int32    runaway_counter, sizeof_gap;                   /* bytes remaining before runaway and bytes per gap */
t_stat   status = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */


if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */

if (sim_tape_bot (uptr))                                /* if the unit is positioned at the BOT */
    status = MTSE_BOT;                                  /*   then reading backward is not possible */

................................................................................
                runaway_counter -= sizeof_gap;          /*   then decrement the gap counter */

            else if ((*bc & MTR_M_RHGAP) == MTR_RHGAP           /* otherwise if the marker */
              || *bc == MTR_RRGAP) {                            /*   is a half gap */
                uptr->pos = uptr->pos + sizeof (t_mtrlnt) / 2;  /*     then position forward to resync */
                bufcntr = 0;                                    /* mark the buffer as invalid to force a read */

                *bc = MTR_GAP;                                  /* reset the marker */
                runaway_counter -= sizeof_gap / 2;              /*   and decrement the gap counter */
                }

            else {                                              /* otherwise it's a record marker */
                sbc = MTR_L (*bc);                              /* extract the record length */
                uptr->pos = uptr->pos - sizeof (t_mtrlnt)       /* position to the start */
                  - (f == MTUF_F_STD ? (sbc + 1) & ~1 : sbc);   /*   of the record */
................................................................................
        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        ppos = sim_tape_tpc_fnd (uptr, (t_addr *) uptr->filebuf); /* find prev rec */
        sim_fseek (uptr->fileref, ppos, SEEK_SET);      /* position */
        sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = tpcbc;                                    /* save rec lnt */

        if (ferror (uptr->fileref))                     /* error? */
            status = sim_tape_ioerr (uptr);
        else if (feof (uptr->fileref))                  /* eof? */
            status = MTSE_EOM;
        else {
            uptr->pos = ppos;                           /* spc over record */
            if (*bc == MTR_TMK)                         /* tape mark? */
                status = MTSE_TMK;
            else
                sim_fseek (uptr->fileref, uptr->pos + sizeof (t_tpclnt), SEEK_SET);
            }
        break;

    case MTUF_F_P7B:







        for (sbc = 1, all_eof = 1; (t_addr) sbc <= uptr->pos ; sbc++) {
            sim_fseek (uptr->fileref, uptr->pos - sbc, SEEK_SET);
            sim_fread (&c, sizeof (uint8), 1, uptr->fileref);











            if (ferror (uptr->fileref)) {               /* error? */
                status = sim_tape_ioerr (uptr);
                break;
                }
            else if (feof (uptr->fileref)) {            /* eof? */
                status = MTSE_EOM;
                break;
                }
            else {


                if ((c & P7B_DPAR) != P7B_EOF)
                    all_eof = 0;
                if (c & P7B_SOR)                        /* start of record? */
                    break;
                }
            }

        if (status == MTSE_OK) {
            uptr->pos = uptr->pos - sbc;                    /* update position */
            *bc = sbc;                                      /* save rec lnt */
            sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for read */
            if (all_eof)                                    /* tape mark? */
                status = MTSE_TMK;
            }
        break;

















































































    default:
        status = MTSE_FMT;
        }

return status;
}

static t_stat sim_tape_rdrlrev (UNIT *uptr, t_mtrlnt *bc)
................................................................................
t_stat status;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */

status = sim_tape_rdlntr (uptr, bc);                    /* read the record length */

sim_debug (MTSE_DBG_STR, ctx->dptr, "rd_lnt: st: %d, lnt: %d, pos: %" T_ADDR_FMT "u\n", status, *bc, uptr->pos);

return status;
}

/* Read record forward

   Inputs:
................................................................................

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_rdrecf(unit=%d, buf=%p, max=%d)\n", (int)(uptr-ctx->dptr->units), buf, max);

opos = uptr->pos;                                       /* old position */
st = sim_tape_rdrlfwd (uptr, &tbc);                     /* read rec lnt */
if (st != MTSE_OK)

    return st;

*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max) {                                        /* rec out of range? */
    MT_SET_PNU (uptr);
    uptr->pos = opos;
    return MTSE_INVRL;
    }
i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
................................................................................
    uptr->pos = opos;
    return sim_tape_ioerr (uptr);
    }
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read", ctx->dptr->dctrl & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
}

t_stat sim_tape_rdrecf_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback)
{
t_stat r = SCPE_OK;
AIO_CALLSETUP
................................................................................
t_stat st;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_rdrecr(unit=%d, buf=%p, max=%d)\n", (int)(uptr-ctx->dptr->units), buf, max);

st = sim_tape_rdrlrev (uptr, &tbc);                     /* read rec lnt */
if (st != MTSE_OK)

    return st;

*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max)                                          /* rec out of range? */
    return MTSE_INVRL;
i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
if (ferror (uptr->fileref))                             /* error? */
    return sim_tape_ioerr (uptr);
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read Reverse", ctx->dptr->dctrl & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
}

t_stat sim_tape_rdrecr_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback)
{
t_stat r = SCPE_OK;
AIO_CALLSETUP
................................................................................
*/

t_stat sim_tape_wrrecf (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt sbc;


if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wrrecf(unit=%d, buf=%p, bc=%d)\n", (int)(uptr-ctx->dptr->units), buf, bc);

sim_tape_data_trace(uptr, buf, bc, "Record Write", ctx->dptr->dctrl & MTSE_DBG_DAT, MTSE_DBG_STR);
MT_CLR_PNU (uptr);
sbc = MTR_L (bc);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
if (sbc == 0)                                           /* nothing to do? */
    return MTSE_OK;
sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set pos */

switch (f) {                                            /* case on format */

    case MTUF_F_STD:                                    /* standard */
        sbc = MTR_L ((bc + 1) & ~1);                    /* pad odd length */
        /* fall through into the E11 handler */
    case MTUF_F_E11:                                    /* E11 */
        sim_fwrite (&bc, sizeof (t_mtrlnt), 1, uptr->fileref);
        sim_fwrite (buf, sizeof (uint8), sbc, uptr->fileref);
        sim_fwrite (&bc, sizeof (t_mtrlnt), 1, uptr->fileref);
        if (ferror (uptr->fileref)) {                   /* error? */
            MT_SET_PNU (uptr);
            return sim_tape_ioerr (uptr);
            }
        uptr->pos = uptr->pos + sbc + (2 * sizeof (t_mtrlnt));  /* move tape */
        break;

    case MTUF_F_P7B:                                    /* Pierce 7B */
        buf[0] = buf[0] | P7B_SOR;                      /* mark start of rec */
        sim_fwrite (buf, sizeof (uint8), sbc, uptr->fileref);
        sim_fwrite (buf, sizeof (uint8), 1, uptr->fileref); /* delimit rec */
        if (ferror (uptr->fileref)) {                   /* error? */
            MT_SET_PNU (uptr);
            return sim_tape_ioerr (uptr);
            }
        uptr->pos = uptr->pos + sbc;                    /* move tape */
        break;





        }
sim_tape_data_trace(uptr, buf, sbc, "Record Written", ctx->dptr->dctrl & MTSE_DBG_DAT, MTSE_DBG_STR);
return MTSE_OK;
}

t_stat sim_tape_wrrecf_a (UNIT *uptr, uint8 *buf, t_mtrlnt bc, TAPE_PCALLBACK callback)
{
t_stat r = SCPE_OK;
AIO_CALLSETUP
    r = sim_tape_wrrecf (uptr, buf, bc);
AIO_CALL(TOP_WREC, buf, 0, NULL, 0, bc, 0, 0, NULL, callback);
return r;
}











































/* Write metadata forward (internal routine) */

static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

................................................................................
MT_CLR_PNU (uptr);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set pos */
sim_fwrite (&dat, sizeof (t_mtrlnt), 1, uptr->fileref);
if (ferror (uptr->fileref)) {                           /* error? */
    MT_SET_PNU (uptr);
    return sim_tape_ioerr (uptr);
    }
sim_debug (MTSE_DBG_STR, ctx->dptr, "wr_lnt: lnt: %d, pos: %" T_ADDR_FMT "u\n", dat, uptr->pos);
uptr->pos = uptr->pos + sizeof (t_mtrlnt);              /* move tape */
return MTSE_OK;
}

/* Write tape mark */

t_stat sim_tape_wrtmk (UNIT *uptr)
................................................................................
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wrtmk(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (MT_GET_FMT (uptr) == MTUF_F_P7B) {                  /* P7B? */
    uint8 buf = P7B_EOF;                                /* eof mark */
    return sim_tape_wrrecf (uptr, &buf, 1);             /* write char */
    }


return sim_tape_wrdata (uptr, MTR_TMK);
}

t_stat sim_tape_wrtmk_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
................................................................................
{
t_stat result;
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wreom(unit=%d)\n", (int)(uptr-ctx->dptr->units));


if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;





result = sim_tape_wrdata (uptr, MTR_EOM);               /* write the EOM marker */

uptr->pos = uptr->pos - sizeof (t_mtrlnt);              /* restore original tape position */

MT_SET_PNU (uptr);                                      /* indicate that position was not updated */

return result;
}

t_stat sim_tape_wreom_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
................................................................................
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat r;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wreomrw(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;
r = sim_tape_wrdata (uptr, MTR_EOM);
if (r == MTSE_OK)
    r = sim_tape_rewind (uptr);
return r;
}

t_stat sim_tape_wreomrw_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
................................................................................
        return MTSE_BOT;                                /*     then erasing backward is not possible */
    else                                                /*   otherwise */
        uptr->pos -= meta_size;                         /*     back up the file pointer */

    if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* position the tape; if it fails */
        return sim_tape_ioerr (uptr);                   /*   then quit with I/O error status */

    sim_fread (&metadatum, meta_size, 1, uptr->fileref);    /* read a metadatum */

    if (ferror (uptr->fileref))                             /* if a file I/O error occurred */
        return sim_tape_ioerr (uptr);                       /*   then report the error and quit */

    else if (metadatum == MTR_TMK)                          /* otherwise if a tape mark is present */
        if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /*   then reposition the tape; if it fails */
            return sim_tape_ioerr (uptr);                   /*     then quit with I/O error status */
................................................................................
if (uptr->flags & UNIT_ATT) {
    if (ctx == NULL)                                    /* if not properly attached? */
        return sim_messagef (SCPE_IERR, "Bad Attach\n");/*   that's a problem */
    sim_debug_unit (ctx->dbit, uptr, "sim_tape_rewind(unit=%d)\n", (int)(uptr-ctx->dptr->units));
    }
uptr->pos = 0;
MT_CLR_PNU (uptr);

return MTSE_OK;
}

t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
................................................................................
return (uptr->capac && (uptr->pos >= uptr->capac))? TRUE: FALSE;
}

/* Test for write protect */

t_bool sim_tape_wrp (UNIT *uptr)
{
return ((uptr->flags & MTUF_WRP) || (MT_GET_FMT (uptr) == MTUF_F_TPC))? TRUE: FALSE;
}

/* Process I/O error */

static t_stat sim_tape_ioerr (UNIT *uptr)
{
sim_printf ("%s: Magtape library I/O error: %s\n", sim_uname (uptr), strerror (errno));
................................................................................

/* Map a TPC format tape image */

static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize)
{
t_addr tpos, leot;
t_addr tape_size;
t_tpclnt bc, last_bc = 0xFFFF;
uint32 had_double_tape_mark = 0;
size_t i;
uint32 objc, sizec;
uint32 *countmap = NULL;
uint8 *recbuf = NULL;
DEVICE *dptr = find_dev_from_unit (uptr);

if ((uptr == NULL) || (uptr->fileref == NULL))
    return 0;
countmap = (uint32 *)calloc (65536, sizeof(*countmap));
recbuf = (uint8 *)malloc (65536);
tape_size = (t_addr)sim_fsize (uptr->fileref);
sim_debug (MTSE_DBG_STR, dptr, "tpc_map: tape_size: %" T_ADDR_FMT "u\n", tape_size);
for (objc = 0, sizec = 0, tpos = 0;; ) {
    sim_fseek (uptr->fileref, tpos, SEEK_SET);
    i = sim_fread (&bc, sizeof (t_tpclnt), 1, uptr->fileref);
    if (i == 0)     /* past or at eof? */
        break;
    if (countmap[bc] == 0)
        sizec++;
    ++countmap[bc];
    if (map && (objc < mapsize))
        map[objc] = tpos;
    if (bc) {
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: %d byte count at pos: %" T_ADDR_FMT "u\n", bc, tpos);
        if (sim_deb && (dptr->dctrl & MTSE_DBG_STR)) {
            sim_fread (recbuf, 1, bc, uptr->fileref);
            sim_data_trace(dptr, uptr, ((dptr->dctrl & MTSE_DBG_DAT) ? recbuf : NULL), "", bc, "Data Record", MTSE_DBG_STR);
            }
        }
    else
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: tape mark at pos: %" T_ADDR_FMT "u\n", tpos);
    objc++;
    tpos = tpos + ((bc + 1) & ~1) + sizeof (t_tpclnt);
    if ((bc == 0) && (last_bc == 0)) {  /* double tape mark? */
        had_double_tape_mark = objc;
        leot = tpos;
        }
    last_bc = bc;
    }
sim_debug (MTSE_DBG_STR, dptr, "tpc_map: objc: %u, different record sizes: %u\n", objc, sizec);
for (i=0; i<65535; i++) {
    if (countmap[i]) {
        if (i == 0)
            sim_debug (MTSE_DBG_STR, dptr, "tpc_map: summary - %u tape marks\n", countmap[i]);
        else
            sim_debug (MTSE_DBG_STR, dptr, "tpc_map: summary - %u %d byte record%s\n", countmap[i], (int)i, (countmap[i] > 1) ? "s" : "");
        }
    }
if (((last_bc != 0xffff) && 
     (tpos > tape_size) &&
     (!had_double_tape_mark))    ||
    (!had_double_tape_mark)      ||
    ((objc == countmap[0]) && 
     (countmap[0] != 2))) {     /* Unreasonable format? */
    if (last_bc != 0xffff)
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: ERROR unexpected EOT byte count: %d\n", last_bc);
    if (tpos > tape_size)
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: ERROR next record position %" T_ADDR_FMT "u beyond EOT: %" T_ADDR_FMT "u\n", tpos, tape_size);
    if (objc == countmap[0])
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: ERROR tape cnly contains tape marks\n");
    free (countmap);
    free (recbuf);
    return 0;
    }

if ((last_bc != 0xffff) && (tpos > tape_size)) {
    sim_debug (MTSE_DBG_STR, dptr, "tpc_map: WARNING unexpected EOT byte count: %d, double tape mark before %" T_ADDR_FMT "u provides logical EOT\n", last_bc, leot);
    objc = had_double_tape_mark;
    tpos = leot;
    }
if (map)
    map[objc] = tpos;
sim_debug (MTSE_DBG_STR, dptr, "tpc_map: OK objc: %d\n", objc);
free (countmap);
free (recbuf);
return objc;
}

/* Check the basic structure of a SIMH format tape image */
























static t_stat sim_tape_simh_check (UNIT *uptr)
{

























return SCPE_OK;




}






/* Check the basic structure of a E11 format tape image */


















static t_stat sim_tape_e11_check (UNIT *uptr)



















































{




























return SCPE_OK;
}

/* Find the preceding record in a TPC file */

static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map)
{
................................................................................
        fprintf (st, "density=%d bpi", tape_density);   /*   then report it */
    else                                                /* otherwise */
        fprintf (st, "density not set");                /*   it was never set by the caller */
    }

return SCPE_OK;
}





















































































































































































































































































































t_stat sim_tape_test (DEVICE *dptr)
{


































return SCPE_OK;
}







|

>



|
|
|
|
|
>







 







|
|
|




<







 







|










>
>
>






|





|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|



<

>
|
|
|
|
|
|
>

<
|
|
|
>
|
<
>





|




|





>
>
>
>




<
<
<
<
>
>

|


|

|
|
>
>
>
>
>
|













>
>
>


<
<








>









<





>
>







 







|
>
>
>
>
>
>
>
>
>
>









|







 







>
>

>





>







 







|







 







|




|
<
<
<
<
<










>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|
|





>
|
>
>
|
|
|
|
|
|
|
|
|
>





|







 







|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>







 







|







 







>
>






>







 







|







 







|
|
|










|




>
>
>
>
>
>
>
|
<
<
>
>
>
>
|
>
>
>
>
>
>
|
|
|
|
|
|
|
|
<
>
>





|
<
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|







 







|







 







|
>

>







 







|







 







|
>

>










|







 







>





|








|
>






|
|
|









|
|






>
>
>
>
>

|











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
|




|







 







>
>







 







>
>


>
>
>
|
>
|
<
|
>







 







<
<
|







 







|







 







>







 







|







 







|












|

|









|
|
|
|



|








|



|

|


|





|
|

|

|





|
|





|





|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
>
>
>
>
>
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


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
...
126
127
128
129
130
131
132
133
134
135
136
137
138
139

140
141
142
143
144
145
146
...
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
...
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
...
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
...
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
...
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
...
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
....
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
....
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
....
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
....
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
....
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
....
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
....
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
....
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
....
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
....
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
....
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
....
1733
1734
1735
1736
1737
1738
1739


1740
1741
1742
1743
1744
1745
1746
1747
....
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
....
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
....
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
....
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964

2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982

2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
....
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549

#if defined SIM_ASYNCH_IO
#include <pthread.h>
#endif

struct sim_tape_fmt {
    const char          *name;                          /* name */
    int32          uflags;                         /* unit flags */
    t_addr              bot;                            /* bot test */
    t_addr              eom_remnant;                    /* potentially unprocessed data */
    };

static struct sim_tape_fmt fmts[MTUF_N_FMT] = {
    { "SIMH", 0,       sizeof (t_mtrlnt) - 1,  sizeof (t_mtrlnt)},
    { "E11",  0,       sizeof (t_mtrlnt) - 1,  sizeof (t_mtrlnt) },
    { "TPC",  UNIT_RO, sizeof (t_tpclnt) - 1,  sizeof (t_tpclnt) },
    { "P7B",  0,       0,                      0 },
    { "AWS",  0,       0,                      0 },
    { "TAR",  0,       0,                      0 },
    { NULL,   0,       0 }
    };

static const uint32 bpi [] = {                          /* tape density table, indexed by MT_DENS constants */
    0,                                                  /*   0 = MT_DENS_NONE -- density not set */
    200,                                                /*   1 = MT_DENS_200  -- 200 bpi NRZI */
    556,                                                /*   2 = MT_DENS_556  -- 556 bpi NRZI */
................................................................................
    6250                                                /*   5 = MT_DENS_6250 -- 6250 bpi GCR */
    };

#define BPI_COUNT       (sizeof (bpi) / sizeof (bpi [0]))   /* count of density table entries */

static t_stat sim_tape_ioerr (UNIT *uptr);
static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat);
static t_stat sim_tape_aws_wrdata (UNIT *uptr, uint8 *buf, t_mtrlnt bc);
static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize);
static t_stat sim_tape_scan_tape (UNIT *uptr);
static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map);
static void sim_tape_data_trace (UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason);
static t_stat tape_erase_fwd (UNIT *uptr, t_mtrlnt gap_size);
static t_stat tape_erase_rev (UNIT *uptr, t_mtrlnt gap_size);


struct tape_context {
    DEVICE              *dptr;              /* Device for unit (access to debug flags) */
    uint32              dbit;               /* debugging bit for trace */
    uint32              auto_format;        /* Format determined dynamically */
#if defined SIM_ASYNCH_IO
    int                 asynch_io;          /* Asynchronous Interrupt scheduling enabled */
................................................................................

t_stat sim_tape_attach (UNIT *uptr, CONST char *cptr)
{
DEVICE *dptr;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
return sim_tape_attach_ex (uptr, cptr, ((dptr->flags & DEV_DEBUG) || (dptr->debflags)) ? MTSE_DBG_API : 0, 0);
}

t_stat sim_tape_attach_ex (UNIT *uptr, const char *cptr, uint32 dbit, int completion_delay)
{
struct tape_context *ctx;
uint32 objc;
DEVICE *dptr;
char gbuf[CBUFSIZE];
t_stat r;
t_bool auto_format = FALSE;
t_bool had_debug = (sim_deb != NULL);
uint32 starting_dctrl = uptr->dctrl;
int32 saved_switches = sim_switches;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
if (sim_switches & SWMASK ('F')) {                      /* format spec? */
    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return sim_messagef (SCPE_2FARG, "Missing Format specifier and filename to attach\n");
    if (sim_tape_set_fmt (uptr, 0, gbuf, NULL) != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Tape Format: %s\n", gbuf);
    sim_switches = sim_switches & ~(SWMASK ('F'));      /* Record Format specifier already processed */
    auto_format = TRUE;
    }
if (MT_GET_FMT (uptr) == MTUF_F_TAR) {
    if (sim_switches & SWMASK ('B')) {                  /* Record Size (blocking factor)? */
        uint32 recsize;

        cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
        if (*cptr == 0)                                     /* must be more */
            return sim_messagef (SCPE_2FARG, "Missing Record Size and filename to attach\n");
        recsize = (uint32) get_uint (gbuf, 10, 65536, &r);
        if ((r != SCPE_OK) || (recsize == 0))
            return sim_messagef (SCPE_ARG, "Invalid Tape Record Size: %s\n", gbuf);
        uptr->recsize = recsize;
        sim_switches = sim_switches & ~(SWMASK ('B'));      /* Record Blocking Factor */
        }
    if (uptr->recsize == 0)
        uptr->recsize = TAR_DFLT_RECSIZE;
    }
if ((MT_GET_FMT (uptr) == MTUF_F_TPC) ||
    (MT_GET_FMT (uptr) == MTUF_F_TAR))
    sim_switches |= SWMASK ('R');                       /* Force ReadOnly attach for TPC and TAR tapes */
r = attach_unit (uptr, (CONST char *)cptr);             /* attach unit */
if (r != SCPE_OK)                                       /* error? */
    return sim_messagef (r, "Can't open tape image: %s\n", cptr);


if ((sim_switches & SWMASK ('D')) && !had_debug) {
    sim_switches |= SWMASK ('E');
    sim_switches &= ~(SWMASK ('D') | SWMASK ('R') | SWMASK ('F'));
    sim_set_debon (0, "STDOUT");
    sim_switches = saved_switches;
    }
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = MTSE_DBG_STR | MTSE_DBG_DAT;


uptr->tape_ctx = ctx = (struct tape_context *)calloc(1, sizeof(struct tape_context));
ctx->dptr = dptr;                                       /* save DEVICE pointer */
ctx->dbit = dbit;                                       /* save debug bit */
ctx->auto_format = auto_format;                         /* save that we auto selected format */


switch (MT_GET_FMT (uptr)) {                            /* case on format */

    case MTUF_F_TPC:                                    /* TPC */
        objc = sim_tape_tpc_map (uptr, NULL, 0);        /* get # objects */
        if (objc == 0) {                                /* tape empty? */
            sim_tape_detach (uptr);
            r = SCPE_FMT;                               /* yes, complain */
            }
        uptr->filebuf = calloc (objc + 1, sizeof (t_addr));
        if (uptr->filebuf == NULL) {                    /* map allocated? */
            sim_tape_detach (uptr);
            r = SCPE_MEM;                               /* no, complain */
            }
        uptr->hwmark = objc + 1;                        /* save map size */
        sim_tape_tpc_map (uptr, (t_addr *) uptr->filebuf, objc);/* fill map */
        break;

    case MTUF_F_TAR:                                    /* TAR */
        uptr->hwmark = (t_addr)sim_fsize (uptr->fileref);
        break;

    default:
        break;
        }





if (r == SCPE_OK) {
    sim_tape_scan_tape (uptr);

    sim_tape_rewind (uptr);

#if defined (SIM_ASYNCH_IO)
    sim_tape_set_async (uptr, completion_delay);
#endif
    uptr->io_flush = _sim_tape_io_flush;
    }

if ((sim_switches & SWMASK ('D')) && !had_debug)
    sim_set_deboff (0, "");
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = starting_dctrl;
return r;
}

/* Detach tape unit */

t_stat sim_tape_detach (UNIT *uptr)
{
struct tape_context *ctx;
uint32 f;
t_stat r;
t_bool auto_format = FALSE;

if (uptr == NULL)
    return SCPE_IERR;
if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;

ctx = (struct tape_context *)uptr->tape_ctx;
f = MT_GET_FMT (uptr);



if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */
if (ctx)
    auto_format = ctx->auto_format;

sim_tape_clr_async (uptr);

MT_CLR_INMRK (uptr);                                    /* Not within an AWS or TAR tapemark */
r = detach_unit (uptr);                                 /* detach unit */
if (r != SCPE_OK)
    return r;
switch (f) {                                            /* case on format */

    case MTUF_F_TPC:                                    /* TPC */
        if (uptr->filebuf)                              /* free map */
            free (uptr->filebuf);
        uptr->filebuf = NULL;

        break;

    default:
        break;
        }
uptr->hwmark = 0;
uptr->recsize = 0;

sim_tape_rewind (uptr);
free (uptr->tape_ctx);
uptr->tape_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)    /* format was determined or specified at attach time? */
    sim_tape_set_fmt (uptr, 0, "SIMH", NULL);   /* restore default format */
................................................................................
else
    fprintf (st, "  sim> ATTACH {switches} %s tapefile\n\n", dptr->name);
fprintf (st, "Attach command switches\n");
fprintf (st, "    -R          Attach Read Only.\n");
fprintf (st, "    -E          Must Exist (if not specified an attempt to create the indicated\n");
fprintf (st, "                virtual tape will be attempted).\n");
fprintf (st, "    -F          Open the indicated tape container in a specific format (default\n");
fprintf (st, "                is SIMH, alternatives are E11, TPC, P7B, AWS and TAR)\n");
fprintf (st, "    -B          For TAR format tapes, the record size for data read from the\n");
fprintf (st, "                specified file.  This record size will be used for all but\n");
fprintf (st, "                possibly the last record which will be what remains unread.\n");
fprintf (st, "                The default TAR record size is 10240.\n");
fprintf (st, "    -V          Display some summary information about the record structure\n");
fprintf (st, "                contained in the tape image scan performed when it is attached.\n");
fprintf (st, "    -S          Perform reverse reads and forward skips during the attach time\n");
fprintf (st, "                tape image scan.\n");
fprintf (st, "    -D          Causes the internal tape structure information to be displayed\n");
fprintf (st, "                while the tape image is scanned.\n");
return SCPE_OK;
}

static void sim_tape_data_trace(UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)
    return;
if (sim_deb && ((uptr->dctrl | ctx->dptr->dctrl) & reason))
    sim_data_trace(ctx->dptr, uptr, (detail ? data : NULL), "", len, txt, reason);
}

/* Read record length forward (internal routine).

   Inputs:
        uptr    =       pointer to tape unit
................................................................................
static t_stat sim_tape_rdlntf (UNIT *uptr, t_mtrlnt *bc)
{
uint8    c;
t_bool   all_eof;
uint32   f = MT_GET_FMT (uptr);
t_mtrlnt sbc;
t_tpclnt tpcbc;
t_awshdr awshdr;
size_t   rdcnt;
t_mtrlnt buffer [256];                                  /* local tape buffer */
t_addr saved_pos;
uint32   bufcntr, bufcap;                               /* buffer counter and capacity */
int32    runaway_counter, sizeof_gap;                   /* bytes remaining before runaway and bytes per gap */
t_stat   status = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */
*bc = 0;

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */

if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* set the initial tape position; if it fails */
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    status = sim_tape_ioerr (uptr);                     /*     and quit with I/O error status */
................................................................................
                if (sizeof_gap > 0)                     /*   then if detection is enabled */
                    status = MTSE_RUNAWAY;              /*     then report a tape runaway */
                else                                    /*   otherwise report the physical EOF */
                    status = MTSE_EOM;                  /*     as the end-of-medium */
                break;
                }

            uptr->pos += sizeof (t_mtrlnt);             /* space over the marker */

            if (*bc == MTR_TMK) {                       /* if the value is a tape mark */
                status = MTSE_TMK;                      /*   then quit with tape mark status */
                break;
                }

            else if (*bc == MTR_GAP)                    /* otherwise if the value is a full gap */
................................................................................
                if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* set the tape position; if it fails */
                    status = sim_tape_ioerr (uptr);                     /*   then quit with I/O error status */
                    break;
                    }

                bufcntr = bufcap;                       /* mark the buffer as invalid to force a read */

                *bc = (t_mtrlnt)MTR_GAP;                /* reset the marker */
                runaway_counter -= sizeof_gap / 2;      /*   and decrement the gap counter */
                }

            else {                                                      /* otherwise it's a record marker */
                saved_pos = uptr->pos;                          /* Save data position */





                sbc = MTR_L (*bc);                              /* extract the record length */
                uptr->pos = uptr->pos + sizeof (t_mtrlnt)       /* position to the start */
                  + (f == MTUF_F_STD ? (sbc + 1) & ~1 : sbc);   /*   of the record */
                }
            }
        while (*bc == MTR_GAP && runaway_counter > 0);  /* continue until data or runaway occurs */

        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        if (status == MTSE_OK) {                        /* Validate the reverse record size */
            t_mtrlnt rev_lnt;

            if (sim_fseek (uptr->fileref, uptr->pos - sizeof (t_mtrlnt), SEEK_SET)){  /*   then seek to the end of record size; if it fails */
                status = sim_tape_ioerr (uptr);         /*     then quit with I/O error status */
                break;
                }

            (void)sim_fread (&rev_lnt,                  /* get the reverse length */
                             sizeof (t_mtrlnt),
                             1,
                             uptr->fileref);

            if (ferror (uptr->fileref)) {               /* if a file I/O error occurred */
                status = sim_tape_ioerr (uptr);         /* report the error and quit */
                break;
                }
            if (sim_fseek (uptr->fileref, saved_pos, SEEK_SET)){  /*   then seek back to the beginning of the data; if it fails */
                status = sim_tape_ioerr (uptr);         /*     then quit with I/O error status */
                break;
                }
            if (rev_lnt != *bc) {           /* size mismatch? */
                status = MTSE_INVRL;
                uptr->pos -= (sizeof (t_mtrlnt) + *bc + sizeof (t_mtrlnt));
                MT_SET_PNU (uptr);                      /* pos not upd */
                }
            }
        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        (void)sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = (t_mtrlnt)tpcbc;                          /* save rec lnt */

        if (ferror (uptr->fileref)) {                   /* error? */
            MT_SET_PNU (uptr);                          /* pos not upd */
            status = sim_tape_ioerr (uptr);
            }
        else {
            if ((feof (uptr->fileref)) ||               /* eof? */
                ((tpcbc == TPC_EOM) && 
                 (sim_fsize (uptr->fileref) == (uint32)sim_ftell (uptr->fileref)))) {
                MT_SET_PNU (uptr);                          /* pos not upd */
                status = MTSE_EOM;
                }
            else {
                uptr->pos = uptr->pos + sizeof (t_tpclnt);  /* spc over reclnt */
                if (tpcbc == TPC_TMK)                       /* tape mark? */
                    status = MTSE_TMK;
                else
                    uptr->pos = uptr->pos + ((tpcbc + 1) & ~1); /* spc over record */
                }
            }
        break;

    case MTUF_F_P7B:
        for (sbc = 0, all_eof = 1; ; sbc++) {           /* loop thru record */
            (void)sim_fread (&c, sizeof (uint8), 1, uptr->fileref);

            if (ferror (uptr->fileref)) {               /* error? */
                MT_SET_PNU (uptr);                      /* pos not upd */
                status = sim_tape_ioerr (uptr);
                break;
                }
            else if (feof (uptr->fileref)) {            /* eof? */
................................................................................
                break;
            else if ((c & P7B_DPAR) != P7B_EOF)
                all_eof = 0;
            }

        if (status == MTSE_OK) {
            *bc = sbc;                                      /* save rec lnt */
            (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for read */
            uptr->pos = uptr->pos + sbc;                    /* spc over record */
            if (all_eof) {                                  /* tape mark? */
                status = MTSE_TMK;
                *bc = 0;
                }
            }
        break;

    case MTUF_F_AWS:
        MT_CLR_INMRK (uptr);                        /* Not within an AWS tapemark */
        memset (&awshdr, 0, sizeof (awshdr));
        rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);

        if (ferror (uptr->fileref)) {               /* error? */
            MT_SET_PNU (uptr);                      /* pos not upd */
            status = sim_tape_ioerr (uptr);
            break;
            }
        if ((feof (uptr->fileref)) ||               /* eof? */
            (rdcnt < 3)) {
            MT_SET_PNU (uptr);                      /* pos not upd */
            status = MTSE_EOM;
            break;
            }
        uptr->pos += sizeof (t_awshdr);             /* spc over AWS header */
        if (awshdr.rectyp == AWS_TMK) {             /* tape mark? */
            status = MTSE_TMK;
            MT_SET_INMRK (uptr);                    /* within an AWS tapemark */
            }
        else
            if (awshdr.rectyp != AWS_REC) {         /* Unknown record type */
                MT_SET_PNU (uptr);                  /* pos not upd */
                status = MTSE_INVRL;
                }
            else {                                  /* tape data record */
                t_addr saved_pos;

                *bc = (t_mtrlnt)awshdr.nxtlen;      /* save rec lnt */
                uptr->pos += awshdr.nxtlen;         /* spc over record */
                memset (&awshdr, 0, sizeof (t_awslnt));
                saved_pos = (t_addr)sim_ftell (uptr->fileref);
                (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for read */
                (void)sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
                if (awshdr.rectyp == AWS_TMK)
                    MT_SET_INMRK (uptr);            /* within an AWS tapemark */
                if (awshdr.prelen != *bc) {
                    status = MTSE_INVRL;
                    uptr->pos = saved_pos - sizeof (t_awslnt);
                    MT_CLR_INMRK (uptr);            /* not within an AWS tapemark */
                    }
                else
                    (void)sim_fseek (uptr->fileref, saved_pos, SEEK_SET); /* Move back to the data */
                }
        break;

    case MTUF_F_TAR:
        if (uptr->pos < uptr->hwmark) {
            if ((uptr->hwmark - uptr->pos) >= uptr->recsize)
                *bc = (t_mtrlnt)uptr->recsize;              /* TAR record size */
            else
                *bc = (t_mtrlnt)(uptr->hwmark - uptr->pos); /* TAR remnant last record */
            (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); 
            uptr->pos += *bc;
            MT_CLR_INMRK (uptr);
            }
        else {
            if (MT_TST_INMRK (uptr))
                status = MTSE_EOM;
            else {
                status = MTSE_TMK;
                MT_SET_INMRK (uptr);
                }
            }
        break;

    default:
        status = MTSE_FMT;
    }

................................................................................
t_stat status;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */

status = sim_tape_rdlntf (uptr, bc);                    /* read the record length */

sim_debug_unit (MTSE_DBG_STR, uptr, "rd_lntf: st: %d, lnt: %d, pos: %" T_ADDR_FMT "u\n", status, *bc, uptr->pos);

return status;
}

/* Read record length reverse (internal routine).

   Inputs:
................................................................................
{
uint8    c;
t_bool   all_eof;
uint32   f = MT_GET_FMT (uptr);
t_addr   ppos;
t_mtrlnt sbc;
t_tpclnt tpcbc;
t_awshdr awshdr;
size_t   rdcnt;
t_mtrlnt buffer [256];                                  /* local tape buffer */
uint32   bufcntr, bufcap;                               /* buffer counter and capacity */
int32    runaway_counter, sizeof_gap;                   /* bytes remaining before runaway and bytes per gap */
t_stat   status = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */
*bc = 0;

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */

if (sim_tape_bot (uptr))                                /* if the unit is positioned at the BOT */
    status = MTSE_BOT;                                  /*   then reading backward is not possible */

................................................................................
                runaway_counter -= sizeof_gap;          /*   then decrement the gap counter */

            else if ((*bc & MTR_M_RHGAP) == MTR_RHGAP           /* otherwise if the marker */
              || *bc == MTR_RRGAP) {                            /*   is a half gap */
                uptr->pos = uptr->pos + sizeof (t_mtrlnt) / 2;  /*     then position forward to resync */
                bufcntr = 0;                                    /* mark the buffer as invalid to force a read */

                *bc = (t_mtrlnt)MTR_GAP;                        /* reset the marker */
                runaway_counter -= sizeof_gap / 2;              /*   and decrement the gap counter */
                }

            else {                                              /* otherwise it's a record marker */
                sbc = MTR_L (*bc);                              /* extract the record length */
                uptr->pos = uptr->pos - sizeof (t_mtrlnt)       /* position to the start */
                  - (f == MTUF_F_STD ? (sbc + 1) & ~1 : sbc);   /*   of the record */
................................................................................
        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        ppos = sim_tape_tpc_fnd (uptr, (t_addr *) uptr->filebuf); /* find prev rec */
        (void)sim_fseek (uptr->fileref, ppos, SEEK_SET);/* position */
        (void)sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = (t_mtrlnt)tpcbc;                          /* save rec lnt */

        if (ferror (uptr->fileref))                     /* error? */
            status = sim_tape_ioerr (uptr);
        else if (feof (uptr->fileref))                  /* eof? */
            status = MTSE_EOM;
        else {
            uptr->pos = ppos;                           /* spc over record */
            if (*bc == MTR_TMK)                         /* tape mark? */
                status = MTSE_TMK;
            else
                (void)sim_fseek (uptr->fileref, uptr->pos + sizeof (t_tpclnt), SEEK_SET);
            }
        break;

    case MTUF_F_P7B:
        if (1) {
#define BUF_SZ 512
            uint8 buf[BUF_SZ];
            t_addr buf_offset;
            size_t bytes_in_buf = 0;
            size_t read_size;

            for (sbc = 1, all_eof = 1; (t_addr) sbc <= uptr->pos ; sbc++) {


                if (bytes_in_buf == 0) {        /* Need to Fill Buffer */
                    if (uptr->pos < BUF_SZ) {
                        buf_offset = 0;
                        read_size = (size_t)uptr->pos;
                        }
                    else {
                        buf_offset = uptr->pos - (sbc - 1 + BUF_SZ);
                        read_size = BUF_SZ;
                        }
                    (void)sim_fseek (uptr->fileref, buf_offset, SEEK_SET);
                    bytes_in_buf = sim_fread (buf, sizeof (uint8), read_size, uptr->fileref);
                    if (ferror (uptr->fileref)) {               /* error? */
                        status = sim_tape_ioerr (uptr);
                        break;
                        }
                    if (feof (uptr->fileref)) {                 /* eof? */
                        status = MTSE_EOM;
                        break;
                        }

                    }
                c = buf[--bytes_in_buf];
                if ((c & P7B_DPAR) != P7B_EOF)
                    all_eof = 0;
                if (c & P7B_SOR)                        /* start of record? */
                    break;
                }


            if (status == MTSE_OK) {
                uptr->pos = uptr->pos - sbc;                    /* update position */
                *bc = sbc;                                      /* save rec lnt */
                (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for next read */
                if (all_eof)                                    /* tape mark? */
                    status = MTSE_TMK;
                }
            break;
            }

    case MTUF_F_AWS:
        *bc = sbc = 0;
        while ((sbc == 0) && (status == MTSE_OK)) {
            if (sim_tape_bot (uptr)) {                      /* if we start at BOT */
                status = MTSE_BOT;                          /*   then we're done */
                break;
                }
            (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);/* position */
            memset (&awshdr, 0, sizeof (awshdr));
            rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
            if (ferror (uptr->fileref)) {                   /* error? */
                status = sim_tape_ioerr (uptr);
                break;
                }
            if (feof (uptr->fileref)) {                 /* eof? */
                if ((uptr->pos > sizeof (t_awshdr)) &&
                    (uptr->pos >= sim_fsize (uptr->fileref))) {
                    if (MT_TST_INMRK (uptr)) {
                        status = MTSE_TMK;
                        MT_CLR_INMRK (uptr);
                        uptr->pos -= sizeof (awshdr);
                        }
                    else
                        status = MTSE_EOM;                  /*   then we're done */
                    break;
                    }
                }
            if ((rdcnt != 3) || 
                ((awshdr.rectyp != AWS_REC) && 
                 (awshdr.rectyp != AWS_TMK))) {
                status = MTSE_INVRL;
                break;
                }
            if (MT_TST_INMRK (uptr))                    /* already in a tapemark? */
                awshdr.rectyp = AWS_REC;
            MT_CLR_INMRK (uptr);                        /* No longer in a tapemark */
            *bc = (t_mtrlnt)((awshdr.rectyp == AWS_REC) ? awshdr.prelen : 0);/* save rec lnt */
            sbc = *bc;                                  /* extract the record length */
            if ((awshdr.rectyp != AWS_TMK) ||
                (awshdr.prelen == 0)) {
                uptr->pos -= sizeof (t_awshdr);         /* position to the start of the record */
                uptr->pos -= awshdr.prelen;             /* Including the data length */

                if (sim_fseek (uptr->fileref,           /* seek to the start of the data area; if it fails */
                               uptr->pos + sizeof (t_awshdr),
                               SEEK_SET)) {
                    status = sim_tape_ioerr (uptr);     /* then return with I/O error status */
                    break;
                    }
                }
            if (awshdr.rectyp == AWS_TMK) {             /* tape mark? */
                status = MTSE_TMK;
                if (awshdr.prelen != 0)
                    MT_SET_INMRK (uptr);                /* Flag processing a tapemark header */
                }
            }
        break;

     case MTUF_F_TAR:
         if (uptr->pos == uptr->hwmark) {
             if (MT_TST_INMRK (uptr)) {
                 status = MTSE_TMK;
                 MT_CLR_INMRK (uptr);
                 }
             else {
                 if (uptr->hwmark % uptr->recsize)
                     *bc = (t_mtrlnt)(uptr->hwmark % uptr->recsize);
                 else
                     *bc = (t_mtrlnt)uptr->recsize;
                 }
             }
         else
             *bc = (t_mtrlnt)uptr->recsize;
         if (*bc) {
             uptr->pos -= *bc;
             (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); 
             }
        break;

   default:
        status = MTSE_FMT;
        }

return status;
}

static t_stat sim_tape_rdrlrev (UNIT *uptr, t_mtrlnt *bc)
................................................................................
t_stat status;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */

status = sim_tape_rdlntr (uptr, bc);                    /* read the record length */

sim_debug_unit (MTSE_DBG_STR, uptr, "rd_lntr: st: %d, lnt: %d, pos: %" T_ADDR_FMT "u\n", status, *bc, uptr->pos);

return status;
}

/* Read record forward

   Inputs:
................................................................................

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_rdrecf(unit=%d, buf=%p, max=%d)\n", (int)(uptr-ctx->dptr->units), buf, max);

opos = uptr->pos;                                       /* old position */
st = sim_tape_rdrlfwd (uptr, &tbc);                     /* read rec lnt */
if (st != MTSE_OK) {
    *bc = 0;
    return st;
    }
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max) {                                        /* rec out of range? */
    MT_SET_PNU (uptr);
    uptr->pos = opos;
    return MTSE_INVRL;
    }
i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
................................................................................
    uptr->pos = opos;
    return sim_tape_ioerr (uptr);
    }
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
}

t_stat sim_tape_rdrecf_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback)
{
t_stat r = SCPE_OK;
AIO_CALLSETUP
................................................................................
t_stat st;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_rdrecr(unit=%d, buf=%p, max=%d)\n", (int)(uptr-ctx->dptr->units), buf, max);

st = sim_tape_rdrlrev (uptr, &tbc);                     /* read rec lnt */
if (st != MTSE_OK) {
    *bc = 0;
    return st;
    }
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max)                                          /* rec out of range? */
    return MTSE_INVRL;
i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
if (ferror (uptr->fileref))                             /* error? */
    return sim_tape_ioerr (uptr);
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read Reverse", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
}

t_stat sim_tape_rdrecr_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback)
{
t_stat r = SCPE_OK;
AIO_CALLSETUP
................................................................................
*/

t_stat sim_tape_wrrecf (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt sbc;
t_stat status = MTSE_OK;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wrrecf(unit=%d, buf=%p, bc=%d)\n", (int)(uptr-ctx->dptr->units), buf, bc);

sim_tape_data_trace(uptr, buf, bc, "Record Write", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
MT_CLR_PNU (uptr);
sbc = MTR_L (bc);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
if (sbc == 0)                                           /* nothing to do? */
    return MTSE_OK;
if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET))     /* set pos */
    return MTSE_IOERR;
switch (f) {                                            /* case on format */

    case MTUF_F_STD:                                    /* standard */
        sbc = MTR_L ((bc + 1) & ~1);                    /* pad odd length */
        /* fall through into the E11 handler */
    case MTUF_F_E11:                                    /* E11 */
        (void)sim_fwrite (&bc, sizeof (t_mtrlnt), 1, uptr->fileref);
        (void)sim_fwrite (buf, sizeof (uint8), sbc, uptr->fileref);
        (void)sim_fwrite (&bc, sizeof (t_mtrlnt), 1, uptr->fileref);
        if (ferror (uptr->fileref)) {                   /* error? */
            MT_SET_PNU (uptr);
            return sim_tape_ioerr (uptr);
            }
        uptr->pos = uptr->pos + sbc + (2 * sizeof (t_mtrlnt));  /* move tape */
        break;

    case MTUF_F_P7B:                                    /* Pierce 7B */
        buf[0] = buf[0] | P7B_SOR;                      /* mark start of rec */
        (void)sim_fwrite (buf, sizeof (uint8), sbc, uptr->fileref);
        (void)sim_fwrite (buf, sizeof (uint8), 1, uptr->fileref); /* delimit rec */
        if (ferror (uptr->fileref)) {                   /* error? */
            MT_SET_PNU (uptr);
            return sim_tape_ioerr (uptr);
            }
        uptr->pos = uptr->pos + sbc;                    /* move tape */
        break;
    case MTUF_F_AWS:                                    /* AWS */
        status = sim_tape_aws_wrdata (uptr, buf, bc);
        if (status != MTSE_OK)
            return status;
        break;
        }
sim_tape_data_trace(uptr, buf, sbc, "Record Written", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return MTSE_OK;
}

t_stat sim_tape_wrrecf_a (UNIT *uptr, uint8 *buf, t_mtrlnt bc, TAPE_PCALLBACK callback)
{
t_stat r = SCPE_OK;
AIO_CALLSETUP
    r = sim_tape_wrrecf (uptr, buf, bc);
AIO_CALL(TOP_WREC, buf, 0, NULL, 0, bc, 0, 0, NULL, callback);
return r;
}

/* Write AWS metadata (and possibly data) forward (internal routine) */

static t_stat sim_tape_aws_wrdata (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
t_awshdr awshdr;
size_t   rdcnt;
t_bool   replacing_record;

memset (&awshdr, 0, sizeof (t_awshdr));
if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* set pos */
    return MTSE_IOERR;
rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
if (ferror (uptr->fileref)) {               /* error? */
    MT_SET_PNU (uptr);                      /* pos not upd */
    return sim_tape_ioerr (uptr);
    }
if ((!sim_tape_bot (uptr)) && 
    (((feof (uptr->fileref)) && (rdcnt < 3)) || /* eof? */
     ((awshdr.rectyp != AWS_REC) && (awshdr.rectyp != AWS_TMK)))) {
    MT_SET_PNU (uptr);                      /* pos not upd */
    return MTSE_INVRL;
    }
if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* set pos */
    return MTSE_IOERR;
replacing_record = (awshdr.nxtlen == (t_awslnt)bc) && (awshdr.rectyp == (bc ? AWS_REC : AWS_TMK));
awshdr.nxtlen = (t_awslnt)bc;
awshdr.rectyp = (bc) ? AWS_REC : AWS_TMK;
(void)sim_fwrite (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
if (bc)
    (void)sim_fwrite (buf, sizeof (uint8), bc, uptr->fileref);
uptr->pos += sizeof (awshdr) + bc;
if ((!replacing_record) || (bc == 0)) {
    awshdr.prelen = bc;
    awshdr.nxtlen = 0;
    awshdr.rectyp = AWS_TMK;
    (void)sim_fwrite (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
    if (!replacing_record)
        sim_set_fsize (uptr->fileref, uptr->pos + sizeof (awshdr));
    }
return MTSE_OK;
}

/* Write metadata forward (internal routine) */

static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

................................................................................
MT_CLR_PNU (uptr);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
(void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set pos */
(void)sim_fwrite (&dat, sizeof (t_mtrlnt), 1, uptr->fileref);
if (ferror (uptr->fileref)) {                           /* error? */
    MT_SET_PNU (uptr);
    return sim_tape_ioerr (uptr);
    }
sim_debug_unit (MTSE_DBG_STR, uptr, "wr_lnt: lnt: %d, pos: %" T_ADDR_FMT "u\n", dat, uptr->pos);
uptr->pos = uptr->pos + sizeof (t_mtrlnt);              /* move tape */
return MTSE_OK;
}

/* Write tape mark */

t_stat sim_tape_wrtmk (UNIT *uptr)
................................................................................
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wrtmk(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (MT_GET_FMT (uptr) == MTUF_F_P7B) {                  /* P7B? */
    uint8 buf = P7B_EOF;                                /* eof mark */
    return sim_tape_wrrecf (uptr, &buf, 1);             /* write char */
    }
if (MT_GET_FMT (uptr) == MTUF_F_AWS)                    /* AWS? */
    return sim_tape_aws_wrdata (uptr, NULL, 0);
return sim_tape_wrdata (uptr, MTR_TMK);
}

t_stat sim_tape_wrtmk_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
................................................................................
{
t_stat result;
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wreom(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;
if (MT_GET_FMT (uptr) == MTUF_F_AWS) {
    sim_set_fsize (uptr->fileref, uptr->pos);
    result = MTSE_OK;
    }
else {
    result = sim_tape_wrdata (uptr, MTR_EOM);           /* write the EOM marker */

    uptr->pos = uptr->pos - sizeof (t_mtrlnt);              /* restore original tape position */
    }
MT_SET_PNU (uptr);                                      /* indicate that position was not updated */

return result;
}

t_stat sim_tape_wreom_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
................................................................................
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat r;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug_unit (ctx->dbit, uptr, "sim_tape_wreomrw(unit=%d)\n", (int)(uptr-ctx->dptr->units));


r = sim_tape_wreom (uptr);
if (r == MTSE_OK)
    r = sim_tape_rewind (uptr);
return r;
}

t_stat sim_tape_wreomrw_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
................................................................................
        return MTSE_BOT;                                /*     then erasing backward is not possible */
    else                                                /*   otherwise */
        uptr->pos -= meta_size;                         /*     back up the file pointer */

    if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* position the tape; if it fails */
        return sim_tape_ioerr (uptr);                   /*   then quit with I/O error status */

    (void)sim_fread (&metadatum, meta_size, 1, uptr->fileref);/* read a metadatum */

    if (ferror (uptr->fileref))                             /* if a file I/O error occurred */
        return sim_tape_ioerr (uptr);                       /*   then report the error and quit */

    else if (metadatum == MTR_TMK)                          /* otherwise if a tape mark is present */
        if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /*   then reposition the tape; if it fails */
            return sim_tape_ioerr (uptr);                   /*     then quit with I/O error status */
................................................................................
if (uptr->flags & UNIT_ATT) {
    if (ctx == NULL)                                    /* if not properly attached? */
        return sim_messagef (SCPE_IERR, "Bad Attach\n");/*   that's a problem */
    sim_debug_unit (ctx->dbit, uptr, "sim_tape_rewind(unit=%d)\n", (int)(uptr-ctx->dptr->units));
    }
uptr->pos = 0;
MT_CLR_PNU (uptr);
MT_CLR_INMRK (uptr);                                    /* Not within an AWS or TAR tapemark */
return MTSE_OK;
}

t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
................................................................................
return (uptr->capac && (uptr->pos >= uptr->capac))? TRUE: FALSE;
}

/* Test for write protect */

t_bool sim_tape_wrp (UNIT *uptr)
{
return ((uptr->flags & MTUF_WRP) || (uptr->flags & UNIT_RO) || (MT_GET_FMT (uptr) == MTUF_F_TPC))? TRUE: FALSE;
}

/* Process I/O error */

static t_stat sim_tape_ioerr (UNIT *uptr)
{
sim_printf ("%s: Magtape library I/O error: %s\n", sim_uname (uptr), strerror (errno));
................................................................................

/* Map a TPC format tape image */

static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize)
{
t_addr tpos, leot;
t_addr tape_size;
t_tpclnt bc, last_bc = TPC_EOM;
uint32 had_double_tape_mark = 0;
size_t i;
uint32 objc, sizec;
uint32 *countmap = NULL;
uint8 *recbuf = NULL;
DEVICE *dptr = find_dev_from_unit (uptr);

if ((uptr == NULL) || (uptr->fileref == NULL))
    return 0;
countmap = (uint32 *)calloc (65536, sizeof(*countmap));
recbuf = (uint8 *)malloc (65536);
tape_size = (t_addr)sim_fsize (uptr->fileref);
sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: tape_size: %" T_ADDR_FMT "u\n", tape_size);
for (objc = 0, sizec = 0, tpos = 0;; ) {
    (void)sim_fseek (uptr->fileref, tpos, SEEK_SET);
    i = sim_fread (&bc, sizeof (t_tpclnt), 1, uptr->fileref);
    if (i == 0)     /* past or at eof? */
        break;
    if (countmap[bc] == 0)
        sizec++;
    ++countmap[bc];
    if (map && (objc < mapsize))
        map[objc] = tpos;
    if (bc) {
        sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: %d byte count at pos: %" T_ADDR_FMT "u\n", bc, tpos);
        if (map && sim_deb && (dptr->dctrl & MTSE_DBG_STR)) {
            (void)sim_fread (recbuf, 1, bc, uptr->fileref);
            sim_data_trace(dptr, uptr, (((uptr->dctrl | dptr->dctrl) & MTSE_DBG_DAT) ? recbuf : NULL), "", bc, "Data Record", MTSE_DBG_STR);
            }
        }
    else
        sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: tape mark at pos: %" T_ADDR_FMT "u\n", tpos);
    objc++;
    tpos = tpos + ((bc + 1) & ~1) + sizeof (t_tpclnt);
    if ((bc == 0) && (last_bc == 0)) {  /* double tape mark? */
        had_double_tape_mark = objc;
        leot = tpos;
        }
    last_bc = bc;
    }
sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: objc: %u, different record sizes: %u\n", objc, sizec);
for (i=0; i<65535; i++) {
    if (countmap[i]) {
        if (i == 0)
            sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: summary - %u tape marks\n", countmap[i]);
        else
            sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: summary - %u %d byte record%s\n", countmap[i], (int)i, (countmap[i] > 1) ? "s" : "");
        }
    }
if (((last_bc != TPC_EOM) && 
     (tpos > tape_size) &&
     (!had_double_tape_mark))    ||
    (!had_double_tape_mark)      ||
    ((objc == countmap[0]) && 
     (countmap[0] != 2))) {     /* Unreasonable format? */
    if (last_bc != TPC_EOM)
        sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: ERROR unexpected EOT byte count: %d\n", last_bc);
    if (tpos > tape_size)
        sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: ERROR next record position %" T_ADDR_FMT "u beyond EOT: %" T_ADDR_FMT "u\n", tpos, tape_size);
    if (objc == countmap[0])
        sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: ERROR tape cnly contains tape marks\n");
    free (countmap);
    free (recbuf);
    return 0;
    }

if ((last_bc != TPC_EOM) && (tpos > tape_size)) {
    sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: WARNING unexpected EOT byte count: %d, double tape mark before %" T_ADDR_FMT "u provides logical EOT\n", last_bc, leot);
    objc = had_double_tape_mark;
    tpos = leot;
    }
if (map)
    map[objc] = tpos;
sim_debug_unit (MTSE_DBG_STR, uptr, "tpc_map: OK objc: %d\n", objc);
free (countmap);
free (recbuf);
return objc;
}

static 
const char *sim_tape_error_text (t_stat stat)
{
const char *mtse_errors[] = {
    "no error",
    "tape mark",
    "unattached",
    "I/O error",
    "invalid record length",
    "invalid format",
    "beginning of tape",
    "end of medium",
    "error in record",
    "write protected",
    "Logical End Of Tape",
    "tape runaway"
    };
static char msgbuf[64];

if (stat <= MTSE_MAX_ERR)
    return mtse_errors[stat];
sprintf(msgbuf, "Error %d", stat);
return msgbuf;
}

static t_stat sim_tape_scan_tape (UNIT *uptr)
{
t_addr saved_pos = uptr->pos;
uint32 record_in_file = 0;
uint32 data_total = 0;
uint32 tapemark_total = 0;
uint32 record_total = 0;
uint32 unique_record_sizes = 0;
t_stat r = SCPE_OK;
t_stat r_f;
t_stat r_r;
t_stat r_s;
uint8 *buf_f = NULL;
uint8 *buf_r = NULL;
uint32 *rec_sizes = NULL;
t_mtrlnt bc_f;
t_mtrlnt bc_r;
t_mtrlnt bc_s;
t_mtrlnt bc;
t_addr pos_f;
t_addr pos_r;
t_mtrlnt max = MTR_MAXLEN;

if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;
buf_f = (uint8 *)malloc (max);
if (buf_f == NULL)
    return SCPE_MEM;
buf_r = (uint8 *)malloc (max);
if (buf_r == NULL) {
    free (buf_f);
    return SCPE_MEM;
    }
rec_sizes = (uint32 *)calloc (max + 1, sizeof (*rec_sizes));
if (rec_sizes == NULL) {
    free (buf_f);
    free (buf_r);
    return SCPE_MEM;
    }

r = sim_tape_rewind (uptr);
while (r == SCPE_OK) {
    pos_f = uptr->pos;
    memset (buf_f, 0, max);
    r_f = sim_tape_rdrecf (uptr, buf_f, &bc_f, max);
    switch (r_f) {
    case MTSE_OK:                                   /* no error */
    case MTSE_TMK:                                  /* tape mark */
        if (r_f == MTSE_OK)
            ++record_total;
        else
            ++tapemark_total;
        data_total += bc_f;
        if (bc_f != 0) {
            if (rec_sizes[bc_f] == 0)
                ++unique_record_sizes;
            ++rec_sizes[bc_f];
            }

        if (sim_switches & SWMASK ('S')) {
            memset (buf_r, 0, max);
            r_r = sim_tape_rdrecr (uptr, buf_r, &bc_r, max);
            pos_r = uptr->pos;
            if (r_r != r_f) {
                sim_printf ("Forward Record Read returned: %s, Reverse read returned: %s\n", sim_tape_error_text (r_f), sim_tape_error_text (r_r));
                break;
                }
            if (bc_f != bc_r) {
                sim_printf ("Forward Record Read record length: %d, Reverse read record length: %d\n", bc_f, bc_r);
                break;
                }
            if (0 != memcmp (buf_f, buf_r, bc_f)) {
                sim_printf ("%d byte record contents differ when read forward amd backwards start from position %" T_ADDR_FMT "u\n", bc_f, pos_f);
                break;
                }
            if (pos_f != pos_r) {
                sim_printf ("Unexpected tape file position between forward and reverse record read: (%" T_ADDR_FMT "u, %" T_ADDR_FMT "u\n", pos_f, pos_r);
                break;
                }
            r_s = sim_tape_sprecf (uptr, &bc_s);
            if (r_s != r_f) {
                sim_printf ("Unexpected Space Record Status: %s vs %s\n", sim_tape_error_text (r_s), sim_tape_error_text (r_f));
                break;
                }
            if (bc_s != bc_f) {
                sim_printf ("Unexpected Space Record Length: %d vs %d\n", bc_s, bc_f);
                break;
                }
            }
        r = SCPE_OK;
        break;
    case MTSE_INVRL:                                /* invalid rec lnt */
    case MTSE_FMT:                                  /* invalid format */
    case MTSE_BOT:                                  /* beginning of tape */
    case MTSE_RECE:                                 /* error in record */
    case MTSE_WRP:                                  /* write protected */
    case MTSE_LEOT:                                 /* Logical End Of Tape */
    case MTSE_RUNAWAY:                              /* tape runaway */
    default:
        r = r_f;
        break;
    case MTSE_EOM:                                  /* end of medium */
        r = r_f;
        break;
        }
    }
if ((r != MTSE_EOM) || (sim_switches & SWMASK ('V')) || 
    ((uint32)(sim_fsize_ex (uptr->fileref) - (t_offset)uptr->pos) > fmts[MT_GET_FMT (uptr)].eom_remnant) ||
    (unique_record_sizes > 2 * tapemark_total)) {
    uint32 remaining_data = (uint32)(sim_fsize_ex (uptr->fileref) - (t_offset)uptr->pos);

    sim_printf ("Tape Image '%s' scanned as %s format.\n", uptr->filename, fmts[MT_GET_FMT (uptr)].name);
    if (r != MTSE_EOM)
        sim_printf ("After processing ");
    else
        sim_printf ("contains ");
    sim_printf ("%u bytes of tape data (%u records, %u tapemarks)\n",
                data_total, record_total, tapemark_total);
    if (record_total > 0) {
        sim_printf ("Comprising %d different sized records (in record size order):\n", unique_record_sizes);
        for (bc = 0; bc <= max; bc++) {
            if (rec_sizes[bc])
                sim_printf ("%8u %u byte records\n", rec_sizes[bc], (uint32)bc);
            }
        }
    if (r != MTSE_EOM)
        sim_printf ("Read Tape Record Returned Unexpected Status: %s\n", sim_tape_error_text (r));
    if (remaining_data > fmts[MT_GET_FMT (uptr)].eom_remnant)
        sim_printf ("%u bytes of unexamined data remain in the tape image file\n", remaining_data);
    }
if (unique_record_sizes > 2 * tapemark_total) {
    sim_printf ("An unreasonable number of record sizes(%u) vs tape marks (%u) have been found\n", unique_record_sizes, tapemark_total);
    sim_printf ("The tape format (%s) might not be correct for the '%s' tape image\n", fmts[MT_GET_FMT (uptr)].name, uptr->filename);
    }

free (buf_f);
free (buf_r);
free (rec_sizes);
uptr->pos = saved_pos;
return SCPE_OK;
}

/* Find the preceding record in a TPC file */

static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map)
{
................................................................................
        fprintf (st, "density=%d bpi", tape_density);   /*   then report it */
    else                                                /* otherwise */
        fprintf (st, "density not set");                /*   it was never set by the caller */
    }

return SCPE_OK;
}

/* list supported densities

   translates the mask of supported densities to a string list in the form: 
   
           "(800|1600|6250)"

   this string may be useful to construct a MTAB help string for a 
   SET <unit> DENSITY= command.

*/

t_stat sim_tape_density_supported (char *string, size_t string_size, int32 valid_bits)
{
uint32 density;
int32 count;

strlcpy (string, "", string_size);
if ((!valid_bits) || (valid_bits >> BPI_COUNT))
    return SCPE_ARG;
for (density = count = 0; density < BPI_COUNT; density++) {
    if (valid_bits & (1 << density)) {
        char density_str[20];

        ++count;
        if (count == 1)
            strlcat (string, "{", string_size);
        else
            strlcat (string, "|", string_size);
        sprintf (density_str, "%d", bpi[density]);
        strlcat (string, density_str, string_size);
        }
    }
if ((count == 1) && (string_size > 1))
    memmove (string, string + 1, strlen (string));
else
    strlcat (string, "}", string_size);
return SCPE_OK;
}

static DEBTAB tape_debug[] = {
  {"TRACE",     MTSE_DBG_API,       "API Trace"},
  {"DATA",      MTSE_DBG_DAT,       "Tape Data"},
  {"POS",       MTSE_DBG_POS,       "Positioning Activities"},
  {"STR",       MTSE_DBG_STR,       "Tape Structure"},
  {0}
};

t_stat sim_tape_add_debug (DEVICE *dptr)
{
if (DEV_TYPE(dptr) != DEV_TAPE)
    return SCPE_OK;
return sim_add_debug_flags (dptr, tape_debug);
}

static t_bool p7b_parity_inited = FALSE;
static uint8 p7b_odd_parity[64];
static uint8 p7b_even_parity[64];

static t_stat sim_tape_test_create_tape_files (UNIT *uptr, const char *filename, int files, int records, int max_size)
{
FILE *fSIMH = NULL;
FILE *fE11 = NULL;
FILE *fTPC = NULL;
FILE *fP7B = NULL;
FILE *fAWS = NULL;
FILE *fTAR = NULL;
FILE *fTAR2 = NULL;
int i, j, k;
t_tpclnt tpclnt;
t_mtrlnt mtrlnt;
t_awslnt awslnt;
t_awslnt awslnt_last = 0;
t_awslnt awsrec_typ = AWS_REC;
char name[256];
t_stat stat = SCPE_OPENERR;
uint8 *buf = NULL;
t_stat aws_stat;
int32 saved_switches = sim_switches;

srand (0);                      /* All devices use the same random sequence for file data */
if (max_size == 0)
    max_size = 65535;
if (!p7b_parity_inited) {
    for (i=0; i < 64; i++) {
        int bit_count = 0;

        for (j=0; j<6; j++) {
            if (i & (1 << j))
                ++bit_count;
            }
        p7b_odd_parity[i] = i | ((~bit_count & 1) << 6);
        p7b_even_parity[i] = i | ((bit_count & 1) << 6);
        }
    p7b_parity_inited = TRUE;
    }
buf = (uint8 *)malloc (65536);
if (buf == NULL)
    return SCPE_MEM;
sprintf (name, "%s.simh", filename);
fSIMH = fopen (name, "wb");
if (fSIMH  == NULL)
    goto Done_Files;
sprintf (name, "%s.e11", filename);
fE11 = fopen (name, "wb");
if (fE11  == NULL)
    goto Done_Files;
sprintf (name, "%s.tpc", filename);
fTPC = fopen (name, "wb");
if (fTPC  == NULL)
    goto Done_Files;
sprintf (name, "%s.p7b", filename);
fP7B = fopen (name, "wb");
if (fP7B  == NULL)
    goto Done_Files;
sprintf (name, "%s.tar", filename);
fTAR = fopen (name, "wb");
if (fTAR  == NULL)
    goto Done_Files;
sprintf (name, "%s.2.tar", filename);
fTAR2 = fopen (name, "wb");
if (fTAR2  == NULL)
    goto Done_Files;
sprintf (name, "%s.aws", filename);
fAWS = fopen (name, "wb");
if (fAWS  == NULL)
    goto Done_Files;
sprintf (name, "aws %s.aws.tape", filename);
(void)remove (name);
sim_switches = SWMASK ('F') | (sim_switches & SWMASK ('D')) | SWMASK ('N');
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = MTSE_DBG_STR | MTSE_DBG_DAT;
aws_stat = sim_tape_attach_ex (uptr, name, (saved_switches & SWMASK ('D')) ? MTSE_DBG_STR | MTSE_DBG_DAT: 0, 0);
sim_switches = saved_switches;
stat = SCPE_OK;
for (i=0; i<files; i++) {
    int rec_size = 1 + (rand () % max_size);

    awslnt = mtrlnt = tpclnt = rec_size;
    for (j=0; j<records; j++) {
        awsrec_typ = AWS_REC;
        if (sim_switches & SWMASK ('V'))
            sim_printf ("Writing %d byte record\n", rec_size);
        for (k=0; k<rec_size; k++)
            buf[k] = rand () & 0xFF;
        (void)sim_fwrite (&mtrlnt,       sizeof (mtrlnt),       1, fSIMH);
        (void)sim_fwrite (&mtrlnt,       sizeof (mtrlnt),       1, fE11);
        (void)sim_fwrite (&tpclnt,       sizeof (tpclnt),       1, fTPC);
        (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
        (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
        (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);
        awslnt_last = awslnt;
        (void)sim_fwrite (buf, 1, rec_size, fSIMH);
        (void)sim_fwrite (buf, 1, rec_size, fE11);
        (void)sim_fwrite (buf, 1, rec_size, fTPC);
        (void)sim_fwrite (buf, 1, rec_size, fAWS);
        stat = sim_tape_wrrecf (uptr, buf, rec_size);
        if (MTSE_OK != stat)
            goto Done_Files;
        if (rec_size & 1) {
            (void)sim_fwrite (&tpclnt, 1, 1, fSIMH);
            (void)sim_fwrite (&tpclnt, 1, 1, fTPC);
            }
        (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
        (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
        for (k=0; k<rec_size; k++)
            buf[k] = p7b_odd_parity[buf[k] & 0x3F]; /* Only 6 data bits plus parity */
        buf[0] |= P7B_SOR;
        (void)sim_fwrite (buf, 1, rec_size, fP7B);
        }
    awslnt_last = awslnt;
    mtrlnt = tpclnt = awslnt = 0;
    awsrec_typ = AWS_TMK;
    (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
    (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
    (void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
    buf[0] = P7B_SOR | P7B_EOF;
    (void)sim_fwrite (buf, 1, 1, fP7B);
    (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
    (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
    (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);
    awslnt_last = 0;
    stat = sim_tape_wrtmk (uptr);
    if (MTSE_OK != stat)
        goto Done_Files;
    }
mtrlnt = tpclnt = 0;
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
(void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
awslnt_last = awslnt;
awsrec_typ = AWS_TMK;
(void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
(void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
(void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);
mtrlnt = 0xffffffff;
tpclnt = 0xffff;
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
(void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
(void)sim_fwrite (buf, 1, 1, fP7B);
for (j=0; j<records; j++) {
    memset (buf, j, 10240);
    (void)sim_fwrite (buf, 1, 10240, fTAR);
    (void)sim_fwrite (buf, 1, 10240, fTAR2);
    }
memset (buf, j, 10240);
(void)sim_fwrite (buf, 1, 5120, fTAR2);
Done_Files:
if (fSIMH)
    fclose (fSIMH);
if (fE11)
    fclose (fE11);
if (fTPC)
    fclose (fTPC);
if (fP7B)
    fclose (fP7B);
if (fAWS)
    fclose (fAWS);
if (fTAR)
    fclose (fTAR);
if (fTAR2)
    fclose (fTAR2);
free (buf);
sim_tape_detach (uptr);
if (stat == SCPE_OK) {
    char name1[CBUFSIZE], name2[CBUFSIZE];

    sprintf (name1, "\"%s.aws\"", filename);
    sprintf (name2, "\"%s.aws.tape\"", filename);
    sim_switches = SWMASK ('F');
    if (sim_cmp_string (name1, name2))
        stat = 1;
    }
sim_switches = saved_switches;
return stat;
}

static t_stat sim_tape_test_process_tape_file (UNIT *uptr, const char *filename, const char *format)
{
char args[256];
t_stat stat;

sprintf (args, "%s %s.%s", format, filename, format);
sim_tape_detach (uptr);
sim_switches |= SWMASK ('F') | SWMASK ('V');
stat = sim_tape_attach_ex (uptr, args, 0, 0);
if (stat != SCPE_OK)
    return stat;
sim_tape_detach (uptr);
sim_switches = 0;
return SCPE_OK;
}

static t_stat sim_tape_test_remove_tape_files (UNIT *uptr, const char *filename)
{
char name[256];

sprintf (name, "%s.simh", filename);
(void)remove (name);
sprintf (name, "%s.e11", filename);
(void)remove (name);
sprintf (name, "%s.tpc", filename);
(void)remove (name);
sprintf (name, "%s.p7b", filename);
(void)remove (name);
sprintf (name, "%s.aws", filename);
(void)remove (name);
sprintf (name, "%s.tar", filename);
(void)remove (name);
sprintf (name, "%s.2.tar", filename);
(void)remove (name);
return SCPE_OK;
}

static t_stat sim_tape_test_density_string (void)
{
char buf[128];
int32 valid_bits = 0;
t_stat stat;

if ((SCPE_ARG != (stat = sim_tape_density_supported (buf, sizeof (buf), valid_bits))) ||
    (strcmp (buf, "")))
    return stat;
valid_bits = MT_556_VALID;
if ((SCPE_OK != (stat = sim_tape_density_supported (buf, sizeof (buf), valid_bits))) || 
    (strcmp (buf, "556")))
    return sim_messagef (SCPE_ARG, "stat was: %s, got string: %s\n", sim_error_text (stat), buf);
valid_bits = MT_800_VALID | MT_1600_VALID;
if ((SCPE_OK != (stat = sim_tape_density_supported (buf, sizeof (buf), valid_bits))) || 
    (strcmp (buf, "{800|1600}")))
    return sim_messagef (SCPE_ARG, "stat was: %s, got string: %s\n", sim_error_text (stat), buf);
valid_bits = MT_800_VALID | MT_1600_VALID | MT_6250_VALID;
if ((SCPE_OK != (stat = sim_tape_density_supported (buf, sizeof (buf), valid_bits))) || 
    (strcmp (buf, "{800|1600|6250}")))
    return sim_messagef (SCPE_ARG, "stat was: %s, got string: %s\n", sim_error_text (stat), buf);
valid_bits = MT_200_VALID | MT_800_VALID | MT_1600_VALID | MT_6250_VALID;
if ((SCPE_OK != (stat = sim_tape_density_supported (buf, sizeof (buf), valid_bits))) || 
    (strcmp (buf, "{200|800|1600|6250}")))
    return sim_messagef (SCPE_ARG, "stat was: %s, got string: %s\n", sim_error_text (stat), buf);
valid_bits = MT_NONE_VALID | MT_800_VALID | MT_1600_VALID | MT_6250_VALID;
if ((SCPE_OK != (stat = sim_tape_density_supported (buf, sizeof (buf), valid_bits))) || 
    (strcmp (buf, "{0|800|1600|6250}")))
    return sim_messagef (SCPE_ARG, "stat was: %s, got string: %s\n", sim_error_text (stat), buf);
return SCPE_OK;
}

#include <setjmp.h>

t_stat sim_tape_test (DEVICE *dptr)
{
int32 saved_switches = sim_switches;
SIM_TEST_INIT;

sim_printf ("\nTesting %s device sim_tape APIs\n", sim_uname(dptr->units));

SIM_TEST(sim_tape_test_density_string ());

SIM_TEST(sim_tape_test_remove_tape_files (dptr->units, "TapeTestFile1"));

SIM_TEST(sim_tape_test_create_tape_files (dptr->units, "TapeTestFile1", 2, 5, 4096));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "tar"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.2", "tar"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "aws"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "p7b"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "tpc"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "e11"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "simh"));

SIM_TEST(sim_tape_test_remove_tape_files (dptr->units, "TapeTestFile1"));

return SCPE_OK;
}

Changes to src/SIMH/sim_tape.h.

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
...
142
143
144
145
146
147
148

149
150
151
152
153

154
155
156
157
158
159
160
...
203
204
205
206
207
208
209

210
211
212

213
214
215
216
217
218
#define MTR_RRGAP       0xFFFFFFFF                      /* reverse read half gap */
#define MTR_FHGAP       0xFFFEFFFF                      /* fwd half gap (overwrite) */
#define MTR_RHGAP       0xFFFF0000                      /* rev half gap (overwrite) */
#define MTR_M_RHGAP     (~0x000080FF)                   /* range mask for rev gap */
#define MTR_MAXLEN      0x00FFFFFF                      /* max len is 24b */
#define MTR_ERF         0x80000000                      /* error flag */
#define MTR_F(x)        ((x) & MTR_ERF)                 /* record error flg */
#define MTR_L(x)        ((x) & ~MTR_ERF)                /* record length */

/* TPC tape format */

typedef uint16          t_tpclnt;                       /* magtape rec lnt */





/* P7B tape format */

#define P7B_SOR         0x80                            /* start of record */
#define P7B_PAR         0x40                            /* parity */
#define P7B_DATA        0x3F                            /* data */
#define P7B_DPAR        (P7B_PAR|P7B_DATA)              /* data and parity */
#define P7B_EOF         0x0F                            /* eof character */

#define TPC_TMK         0x0000                          /* tape mark */












/* Unit flags */

#define MTUF_V_PNU      (UNIT_V_UF + 0)                 /* position not upd */
#define MTUF_V_WLK      (UNIT_V_UF + 1)                 /* write locked */
#define MTUF_V_FMT      (UNIT_V_UF + 2)                 /* tape file format */
#define MTUF_W_FMT      3                               /* 3b of formats */
#define MTUF_N_FMT      (1u << MTUF_W_FMT)              /* number of formats */
#define MTUF_M_FMT      ((1u << MTUF_W_FMT) - 1)
#define MTUF_F_STD       0                              /* SIMH format */
#define MTUF_F_E11       1                              /* E11 format */
#define MTUF_F_TPC       2                              /* TPC format */
#define MTUF_F_P7B       3                              /* P7B format */
#define MUTF_F_TDF       4                              /* TDF format */

#define MTUF_V_UF       (MTUF_V_FMT + MTUF_W_FMT)
#define MTUF_PNU        (1u << MTUF_V_PNU)
#define MTUF_WLK        (1u << MTUF_V_WLK)
#define MTUF_FMT        (MTUF_M_FMT << MTUF_V_FMT)
#define MTUF_WRP        (MTUF_WLK | UNIT_RO)

#define MT_F_STD        (MTUF_F_STD << MTUF_V_FMT)
#define MT_F_E11        (MTUF_F_E11 << MTUF_V_FMT)
#define MT_F_TPC        (MTUF_F_TPC << MTUF_V_FMT)
#define MT_F_P7B        (MTUF_F_P7B << MTUF_V_FMT)
#define MT_F_TDF        (MTUF_F_TDF << MTUF_V_FMT)


#define MT_SET_PNU(u)   (u)->flags = (u)->flags | MTUF_PNU
#define MT_CLR_PNU(u)   (u)->flags = (u)->flags & ~MTUF_PNU
#define MT_TST_PNU(u)   ((u)->flags & MTUF_PNU)



#define MT_GET_FMT(u)   (((u)->flags >> MTUF_V_FMT) & MTUF_M_FMT)

/* sim_tape_position Position Flags */
#define MTPOS_V_REW     3
#define MTPOS_M_REW     (1u << MTPOS_V_REW)            /* Rewind First */
#define MTPOS_V_REV     2
#define MTPOS_M_REV     (1u << MTPOS_V_REV)            /* Reverse Direction */
................................................................................
#define MTSE_FMT        5                               /* invalid format */
#define MTSE_BOT        6                               /* beginning of tape */
#define MTSE_EOM        7                               /* end of medium */
#define MTSE_RECE       8                               /* error in record */
#define MTSE_WRP        9                               /* write protected */
#define MTSE_LEOT       10                              /* Logical End Of Tape */
#define MTSE_RUNAWAY    11                              /* tape runaway */


typedef void (*TAPE_PCALLBACK)(UNIT *unit, t_stat status);

/* Tape Internal Debug flags */


#define MTSE_DBG_DAT   0x20000000                       /* Debug Data */
#define MTSE_DBG_POS   0x40000000                       /* Debug Positioning activities */
#define MTSE_DBG_STR   0x80000000                       /* Debug Tape Structure */

/* Prototypes */

t_stat sim_tape_attach_ex (UNIT *uptr, const char *cptr, uint32 dbit, int completion_delay);
................................................................................
t_bool sim_tape_eot (UNIT *uptr);
t_stat sim_tape_set_fmt (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_capac (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_dens (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_dens (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

t_stat sim_tape_set_asynch (UNIT *uptr, int latency);
t_stat sim_tape_clr_asynch (UNIT *uptr);
t_stat sim_tape_test (DEVICE *dptr);


#ifdef  __cplusplus
}
#endif

#endif







|




>
>
>
>









|
>
>
>
>
>
>
>
>
>
>
>













|
>










|
>




>
>
>







 







>





>







 







>



>






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
...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#define MTR_RRGAP       0xFFFFFFFF                      /* reverse read half gap */
#define MTR_FHGAP       0xFFFEFFFF                      /* fwd half gap (overwrite) */
#define MTR_RHGAP       0xFFFF0000                      /* rev half gap (overwrite) */
#define MTR_M_RHGAP     (~0x000080FF)                   /* range mask for rev gap */
#define MTR_MAXLEN      0x00FFFFFF                      /* max len is 24b */
#define MTR_ERF         0x80000000                      /* error flag */
#define MTR_F(x)        ((x) & MTR_ERF)                 /* record error flg */
#define MTR_L(x)        ((t_mtrlnt)((x) & ~MTR_ERF))    /* record length */

/* TPC tape format */

typedef uint16          t_tpclnt;                       /* magtape rec lnt */

#define TPC_TMK         0x0000                          /* tape mark */
#define TPC_EOM         0xFFFF                          /* end of medium */


/* P7B tape format */

#define P7B_SOR         0x80                            /* start of record */
#define P7B_PAR         0x40                            /* parity */
#define P7B_DATA        0x3F                            /* data */
#define P7B_DPAR        (P7B_PAR|P7B_DATA)              /* data and parity */
#define P7B_EOF         0x0F                            /* eof character */

/* AWS tape format */
typedef uint16          t_awslnt;                       /* magtape rec lnt */
typedef struct {
    t_awslnt    nxtlen;
    t_awslnt    prelen;
    t_awslnt    rectyp;
#define AWS_TMK         0x0040
#define AWS_REC         0x00A0
    } t_awshdr;

/* TAR tape format */
#define TAR_DFLT_RECSIZE     10240                      /* Default Fixed record size */

/* Unit flags */

#define MTUF_V_PNU      (UNIT_V_UF + 0)                 /* position not upd */
#define MTUF_V_WLK      (UNIT_V_UF + 1)                 /* write locked */
#define MTUF_V_FMT      (UNIT_V_UF + 2)                 /* tape file format */
#define MTUF_W_FMT      3                               /* 3b of formats */
#define MTUF_N_FMT      (1u << MTUF_W_FMT)              /* number of formats */
#define MTUF_M_FMT      ((1u << MTUF_W_FMT) - 1)
#define MTUF_F_STD       0                              /* SIMH format */
#define MTUF_F_E11       1                              /* E11 format */
#define MTUF_F_TPC       2                              /* TPC format */
#define MTUF_F_P7B       3                              /* P7B format */
#define MTUF_F_AWS       4                              /* AWS format */
#define MTUF_F_TAR       5                              /* TAR format */
#define MTUF_V_UF       (MTUF_V_FMT + MTUF_W_FMT)
#define MTUF_PNU        (1u << MTUF_V_PNU)
#define MTUF_WLK        (1u << MTUF_V_WLK)
#define MTUF_FMT        (MTUF_M_FMT << MTUF_V_FMT)
#define MTUF_WRP        (MTUF_WLK | UNIT_RO)

#define MT_F_STD        (MTUF_F_STD << MTUF_V_FMT)
#define MT_F_E11        (MTUF_F_E11 << MTUF_V_FMT)
#define MT_F_TPC        (MTUF_F_TPC << MTUF_V_FMT)
#define MT_F_P7B        (MTUF_F_P7B << MTUF_V_FMT)
#define MT_F_AWS        (MTUF_F_AWS << MTUF_V_FMT)
#define MT_F_TAR        (MTUF_F_TAR << MTUF_V_FMT)

#define MT_SET_PNU(u)   (u)->flags = (u)->flags | MTUF_PNU
#define MT_CLR_PNU(u)   (u)->flags = (u)->flags & ~MTUF_PNU
#define MT_TST_PNU(u)   ((u)->flags & MTUF_PNU)
#define MT_SET_INMRK(u) (u)->dynflags = (u)->dynflags | UNIT_TAPE_MRK
#define MT_CLR_INMRK(u) (u)->dynflags = (u)->dynflags & ~UNIT_TAPE_MRK
#define MT_TST_INMRK(u) ((u)->dynflags & UNIT_TAPE_MRK)
#define MT_GET_FMT(u)   (((u)->flags >> MTUF_V_FMT) & MTUF_M_FMT)

/* sim_tape_position Position Flags */
#define MTPOS_V_REW     3
#define MTPOS_M_REW     (1u << MTPOS_V_REW)            /* Rewind First */
#define MTPOS_V_REV     2
#define MTPOS_M_REV     (1u << MTPOS_V_REV)            /* Reverse Direction */
................................................................................
#define MTSE_FMT        5                               /* invalid format */
#define MTSE_BOT        6                               /* beginning of tape */
#define MTSE_EOM        7                               /* end of medium */
#define MTSE_RECE       8                               /* error in record */
#define MTSE_WRP        9                               /* write protected */
#define MTSE_LEOT       10                              /* Logical End Of Tape */
#define MTSE_RUNAWAY    11                              /* tape runaway */
#define MTSE_MAX_ERR    11

typedef void (*TAPE_PCALLBACK)(UNIT *unit, t_stat status);

/* Tape Internal Debug flags */

#define MTSE_DBG_API   0x10000000                       /* API Trace */
#define MTSE_DBG_DAT   0x20000000                       /* Debug Data */
#define MTSE_DBG_POS   0x40000000                       /* Debug Positioning activities */
#define MTSE_DBG_STR   0x80000000                       /* Debug Tape Structure */

/* Prototypes */

t_stat sim_tape_attach_ex (UNIT *uptr, const char *cptr, uint32 dbit, int completion_delay);
................................................................................
t_bool sim_tape_eot (UNIT *uptr);
t_stat sim_tape_set_fmt (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_capac (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_dens (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_dens (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_density_supported (char *string, size_t string_size, int32 valid_bits);
t_stat sim_tape_set_asynch (UNIT *uptr, int latency);
t_stat sim_tape_clr_asynch (UNIT *uptr);
t_stat sim_tape_test (DEVICE *dptr);
t_stat sim_tape_add_debug (DEVICE *dptr);

#ifdef  __cplusplus
}
#endif

#endif

Changes to src/SIMH/sim_tmxr.c.

2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
....
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
    lp = mp->ldsc + i;                                  /* get line desc */
    if (lp->rxbpi == lp->rxbpr)                         /* if buf empty, */
        lp->rxbpi = lp->rxbpr = 0;                      /* reset pointers */
    }                                                   /* end for */
}


int32 tmxr_rqln_bare (const TMLN *lp, t_bool speed)
{
if (speed) {
    if (lp->send.extoff < lp->send.insoff) {/* buffered SEND data? */
        if (sim_gtime () < lp->send.next_time) 
            return 0;
        else
            return lp->send.delay ? 1 : (lp->send.insoff - lp->send.extoff);
        }
    if (lp->rxbps) {                        /* consider speed and rate limiting? */
        if (sim_gtime () < lp->rxnexttime)  /* too soon? */
            return 0;
        else
            return 1;
        }
    }
return (lp->rxbpi - lp->rxbpr + ((lp->rxbpi < lp->rxbpr)? lp->rxbsz: 0));
}

/* Return count of available characters ready to be read for line */

int32 tmxr_rqln (const TMLN *lp)
{
return tmxr_rqln_bare (lp, TRUE);
................................................................................
  {"EXPECT",    TMXR_DBG_EXP,       "Expect Activities"},
  {"SEND",      TMXR_DBG_SEND,      "Send Activities"},
  {0}
};

t_stat tmxr_add_debug (DEVICE *dptr)
{
if (!(dptr->flags & DEV_MUX))
    return SCPE_OK;
return sim_add_debug_flags (dptr, tmxr_debug);
}

/* Attach unit to master socket */

t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, CONST char *cptr, t_bool async)







|



|


|





|


|







 







|







2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
....
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
    lp = mp->ldsc + i;                                  /* get line desc */
    if (lp->rxbpi == lp->rxbpr)                         /* if buf empty, */
        lp->rxbpi = lp->rxbpr = 0;                      /* reset pointers */
    }                                                   /* end for */
}


static int32 tmxr_rqln_bare (const TMLN *lp, t_bool speed)
{
if (speed) {
    if (lp->send.extoff < lp->send.insoff) {/* buffered SEND data? */
        if (sim_gtime () < lp->send.next_time) /* too soon? */
            return 0;
        else
            return 1;
        }
    if (lp->rxbps) {                        /* consider speed and rate limiting? */
        if (sim_gtime () < lp->rxnexttime)  /* too soon? */
            return 0;
        else
            return ((lp->rxbpi - lp->rxbpr + ((lp->rxbpi < lp->rxbpr)? lp->rxbsz : 0)) > 0) ? 1 : 0;
        }
    }
return (lp->rxbpi - lp->rxbpr + ((lp->rxbpi < lp->rxbpr)? lp->rxbsz : 0));
}

/* Return count of available characters ready to be read for line */

int32 tmxr_rqln (const TMLN *lp)
{
return tmxr_rqln_bare (lp, TRUE);
................................................................................
  {"EXPECT",    TMXR_DBG_EXP,       "Expect Activities"},
  {"SEND",      TMXR_DBG_SEND,      "Send Activities"},
  {0}
};

t_stat tmxr_add_debug (DEVICE *dptr)
{
if (DEV_TYPE(dptr) != DEV_MUX)
    return SCPE_OK;
return sim_add_debug_flags (dptr, tmxr_debug);
}

/* Attach unit to master socket */

t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, CONST char *cptr, t_bool async)

Changes to src/SIMH/sim_video.c.

357
358
359
360
361
362
363

364
365
366
367
368
369
370
371
372
373
374
375
376
377
...
626
627
628
629
630
631
632









633
634
635
636
637
638
639
....
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
....
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
....
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
....
2334
2335
2336
2337
2338
2339
2340





2341
2342
2343
2344
2345
2346
2347
SDL_Surface *vid_image;                                 /* video buffer */
SDL_Surface *vid_window;                                /* window handle */
#else
t_bool vid_key_state[SDL_NUM_SCANCODES];
SDL_Texture *vid_texture;                               /* video buffer in GPU */
SDL_Renderer *vid_renderer;
SDL_Window *vid_window;                                 /* window handle */

uint32 vid_windowID;
#endif
SDL_Thread *vid_thread_handle = NULL;                   /* event thread handle */
SDL_Cursor *vid_cursor = NULL;                          /* current cursor */
t_bool vid_cursor_visible = FALSE;                      /* cursor visibility state */
uint32 vid_mono_palette[2];                             /* Monochrome Color Map */
SDL_Color vid_colors[256];
KEY_EVENT_QUEUE vid_key_events;                         /* keyboard events */
MOUSE_EVENT_QUEUE vid_mouse_events;                     /* mouse events */
DEVICE *vid_dev;

#if defined (SDL_MAIN_AVAILABLE)
#if defined (main)
#undef main
................................................................................
            }
        }
    if (SDL_SemPost (vid_mouse_events.sem))
        sim_printf ("%s: vid_poll_mouse(): SDL_SemPost error: %s\n", sim_dname(vid_dev), SDL_GetError());
    }
return stat;
}










void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf)
{
#if SDL_MAJOR_VERSION == 1
int32 i;
uint32* pixels;

................................................................................
     */
    eventtypes[SDL_USEREVENT] = "USEREVENT";
#endif  /* SDL_MAJOR_VERSION != 1 */
    }

sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Starting\n");

vid_mono_palette[0] = sim_end ? 0xFF000000 : 0x000000FF;        /* Black */
vid_mono_palette[1] = 0xFFFFFFFF;                               /* White */

memset (&vid_key_state, 0, sizeof(vid_key_state));

#if SDL_MAJOR_VERSION == 1
vid_window = SDL_SetVideoMode (vid_width, vid_height, 8, 0);

SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

................................................................................
    vid_renderer = NULL;
    SDL_DestroyWindow(vid_window);
    vid_window = NULL;
    SDL_Quit ();
    return 0;
    }



SDL_StopTextInput ();

vid_windowID = SDL_GetWindowID (vid_window);

#endif

if (vid_flags & SIM_VID_INPUTCAPTURED) {
    char title[150];

    memset (title, 0, sizeof(title));
    strncpy (title, vid_title, sizeof(title)-1);
    strncat (title, "                                             ReleaseKey=", sizeof(title)-(1+strlen(title)));
    strncat (title, vid_release_key, sizeof(title)-(1+strlen(title)));
#if SDL_MAJOR_VERSION == 1
    SDL_WM_SetCaption (title, title);
#else
    SDL_SetWindowTitle (vid_window, title);
#endif
    }
else
................................................................................
#endif
SDL_Delay (vid_beep_duration + 100);/* Wait for sound to finnish */
}

#else /* !(defined(USE_SIM_VIDEO) && defined(HAVE_LIBSDL)) */
/* Non-implemented versions */

uint32 vid_mono_palette[2];                             /* Monochrome Color Map */

t_stat vid_open (DEVICE *dptr, const char *title, uint32 width, uint32 height, int flags)
{
return SCPE_NOFNC;
}

t_stat vid_close (void)
{
................................................................................
return SCPE_EOF;
}

t_stat vid_poll_mouse (SIM_MOUSE_EVENT *ev)
{
return SCPE_EOF;
}






void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf)
{
return;
}

t_stat vid_set_cursor (t_bool visible, uint32 width, uint32 height, uint8 *data, uint8 *mask, uint32 hot_x, uint32 hot_y)







>





<
<







 







>
>
>
>
>
>
>
>
>







 







<
<
<







 







>
>










|
|
|







 







<
<







 







>
>
>
>
>







357
358
359
360
361
362
363
364
365
366
367
368
369


370
371
372
373
374
375
376
...
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
....
1608
1609
1610
1611
1612
1613
1614



1615
1616
1617
1618
1619
1620
1621
....
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
....
2320
2321
2322
2323
2324
2325
2326


2327
2328
2329
2330
2331
2332
2333
....
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
SDL_Surface *vid_image;                                 /* video buffer */
SDL_Surface *vid_window;                                /* window handle */
#else
t_bool vid_key_state[SDL_NUM_SCANCODES];
SDL_Texture *vid_texture;                               /* video buffer in GPU */
SDL_Renderer *vid_renderer;
SDL_Window *vid_window;                                 /* window handle */
SDL_PixelFormat *vid_format;
uint32 vid_windowID;
#endif
SDL_Thread *vid_thread_handle = NULL;                   /* event thread handle */
SDL_Cursor *vid_cursor = NULL;                          /* current cursor */
t_bool vid_cursor_visible = FALSE;                      /* cursor visibility state */


KEY_EVENT_QUEUE vid_key_events;                         /* keyboard events */
MOUSE_EVENT_QUEUE vid_mouse_events;                     /* mouse events */
DEVICE *vid_dev;

#if defined (SDL_MAIN_AVAILABLE)
#if defined (main)
#undef main
................................................................................
            }
        }
    if (SDL_SemPost (vid_mouse_events.sem))
        sim_printf ("%s: vid_poll_mouse(): SDL_SemPost error: %s\n", sim_dname(vid_dev), SDL_GetError());
    }
return stat;
}

uint32 vid_map_rgb (uint8 r, uint8 g, uint8 b)
{
#if SDL_MAJOR_VERSION == 1
return SDL_MapRGB (vid_image->format, r, g, b);
#else
return SDL_MapRGB (vid_format, r, g, b);
#endif
}

void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf)
{
#if SDL_MAJOR_VERSION == 1
int32 i;
uint32* pixels;

................................................................................
     */
    eventtypes[SDL_USEREVENT] = "USEREVENT";
#endif  /* SDL_MAJOR_VERSION != 1 */
    }

sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_thread() - Starting\n");




memset (&vid_key_state, 0, sizeof(vid_key_state));

#if SDL_MAJOR_VERSION == 1
vid_window = SDL_SetVideoMode (vid_width, vid_height, 8, 0);

SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

................................................................................
    vid_renderer = NULL;
    SDL_DestroyWindow(vid_window);
    vid_window = NULL;
    SDL_Quit ();
    return 0;
    }

vid_format = SDL_AllocFormat (SDL_PIXELFORMAT_ARGB8888);

SDL_StopTextInput ();

vid_windowID = SDL_GetWindowID (vid_window);

#endif

if (vid_flags & SIM_VID_INPUTCAPTURED) {
    char title[150];

    memset (title, 0, sizeof(title));
    strlcpy (title, vid_title, sizeof(title));
    strlcat (title, "                                             ReleaseKey=", sizeof(title));
    strlcat (title, vid_release_key, sizeof(title));
#if SDL_MAJOR_VERSION == 1
    SDL_WM_SetCaption (title, title);
#else
    SDL_SetWindowTitle (vid_window, title);
#endif
    }
else
................................................................................
#endif
SDL_Delay (vid_beep_duration + 100);/* Wait for sound to finnish */
}

#else /* !(defined(USE_SIM_VIDEO) && defined(HAVE_LIBSDL)) */
/* Non-implemented versions */



t_stat vid_open (DEVICE *dptr, const char *title, uint32 width, uint32 height, int flags)
{
return SCPE_NOFNC;
}

t_stat vid_close (void)
{
................................................................................
return SCPE_EOF;
}

t_stat vid_poll_mouse (SIM_MOUSE_EVENT *ev)
{
return SCPE_EOF;
}

uint32 vid_map_rgb (uint8 r, uint8 g, uint8 b)
{
return 0;
}

void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf)
{
return;
}

t_stat vid_set_cursor (t_bool visible, uint32 width, uint32 height, uint8 *data, uint8 *mask, uint32 hot_x, uint32 hot_y)

Changes to src/SIMH/sim_video.h.

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
#define SIM_VID_INPUTCAPTURED       1                       /* Mouse and Keyboard input captured (calling */
                                                            /* code responsible for cursor display in video) */
typedef void (*VID_QUIT_CALLBACK)(void);
t_stat vid_register_quit_callback (VID_QUIT_CALLBACK callback);
t_stat vid_close (void);
t_stat vid_poll_kb (SIM_KEY_EVENT *ev);
t_stat vid_poll_mouse (SIM_MOUSE_EVENT *ev);

void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf);
void vid_beep (void);
void vid_refresh (void);
const char *vid_version (void);
const char *vid_key_name (int32 key);
t_stat vid_set_cursor (t_bool visible, uint32 width, uint32 height, uint8 *data, uint8 *mask, uint32 hot_x, uint32 hot_y);
t_stat vid_set_release_key (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
t_stat vid_show_release_key (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
t_stat vid_show_video (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
t_stat vid_show (FILE* st, DEVICE *dptr,  UNIT* uptr, int32 val, CONST char* desc);
t_stat vid_screenshot (const char *filename);

extern t_bool vid_active;
extern uint32 vid_mono_palette[2];
void vid_set_cursor_position (int32 x, int32 y);        /* cursor position (set by calling code) */

/* A device simulator can optionally set the vid_display_kb_event_process
 * routine pointer to the address of a routine.
 * Simulator code which uses the display library which processes window 
 * keyboard data with code in display/sim_ws.c can use this routine to
 * explicitly get access to keyboard events that arrive in the display 







>













<







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
#define SIM_VID_INPUTCAPTURED       1                       /* Mouse and Keyboard input captured (calling */
                                                            /* code responsible for cursor display in video) */
typedef void (*VID_QUIT_CALLBACK)(void);
t_stat vid_register_quit_callback (VID_QUIT_CALLBACK callback);
t_stat vid_close (void);
t_stat vid_poll_kb (SIM_KEY_EVENT *ev);
t_stat vid_poll_mouse (SIM_MOUSE_EVENT *ev);
uint32 vid_map_rgb (uint8 r, uint8 g, uint8 b);
void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf);
void vid_beep (void);
void vid_refresh (void);
const char *vid_version (void);
const char *vid_key_name (int32 key);
t_stat vid_set_cursor (t_bool visible, uint32 width, uint32 height, uint8 *data, uint8 *mask, uint32 hot_x, uint32 hot_y);
t_stat vid_set_release_key (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
t_stat vid_show_release_key (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
t_stat vid_show_video (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
t_stat vid_show (FILE* st, DEVICE *dptr,  UNIT* uptr, int32 val, CONST char* desc);
t_stat vid_screenshot (const char *filename);

extern t_bool vid_active;

void vid_set_cursor_position (int32 x, int32 y);        /* cursor position (set by calling code) */

/* A device simulator can optionally set the vid_display_kb_event_process
 * routine pointer to the address of a routine.
 * Simulator code which uses the display library which processes window 
 * keyboard data with code in display/sim_ws.c can use this routine to
 * explicitly get access to keyboard events that arrive in the display