vmtools.cpp
72.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
/* vmtools.c ****************************************************
Anubis
Some useful tools to put virtual machines at work
****************************************************************/
#include "AnubisSupport.h"
//#include <malloc.h>
#include <stdio.h>
#include <assert.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include "bytecode.h"
#include "vm.h"
#include "dependencies.h"
#include "DebugLog.h"
#include "../../../third_dev/sqlite3/sqlite3.h"
#include "CMList.h"
#include "graphics.h"
#include "Library.h"
#ifdef WITH_SQLAPI
#include "SQLAPI.h"
#endif
#if defined (_LINUX_) || (__BEOS__)
#include <netdb.h>
#endif
#include "AnubisSupport.h"
U32 max_memory = 60<<20;
U32 current_memory = 0;
U32 default_stack_size = 50; /* does need to be big */
U32 stack_more_size = 50; /* idem */
U32 stack_per_machine = 1<<20; /* maximum */
//#define RELLOC(ptr, code) do { (((U32 *)ptr))[0] += (U32)code; ptr += sizeof(U32);} while(0)
#define RELLOC(ptr, code) do { void* s = code+*(U32*)ptr; memcpy(ptr, &s, sizeof(U32)); ptr += sizeof(U32);} while(0)
#ifdef WIN32
#include <sys/timeb.h>
#include <time.h>
#include <conio.h>
/* emulation of 'gettimeofday' for Windows */
int gettimeofday (struct timeval *TP, struct timezone *TZP)
{
struct timeb timebuf;
ftime (&timebuf);
TP->tv_sec = timebuf.time;
TP->tv_usec = (long)(timebuf.millitm) * (1000);
return 0;
}
int settimeofday(const struct timeval *tp, const struct timezone *tzp)
{
if (tp->tv_sec < 0)
{
return -1;
}
struct tm * new_time = gmtime((const time_t *)&tp->tv_sec);
SYSTEMTIME lpSystemTime;
if(new_time)
{
lpSystemTime.wHour = new_time->tm_hour;
lpSystemTime.wMinute = new_time->tm_min;
lpSystemTime.wSecond = new_time->tm_sec;
lpSystemTime.wDay = new_time->tm_mday;
lpSystemTime.wMonth = new_time->tm_mon + 1;
lpSystemTime.wYear = new_time->tm_year + 1900;
lpSystemTime.wMilliseconds = tp->tv_usec / 1000;
lpSystemTime.wDayOfWeek= 0;
if(SetSystemTime(&lpSystemTime))
{
return 0;
}
/*else
{
DWORD error = GetLastError();
}*/
}
return -1;
}
#endif
/*
This list contains all references (of type (void *)) to SQLite3 database handles which
are no more referenced by Anubis (in other words, the garbage-collector of Anubis has
decremented the counter (in the +++StructPtr(SQLite3)) down to 0 for this database
handle).
However, the handle is not closed because it is referenced to from within a SQLite3
statement. The SQLite3 primitive 'sqlite3_close' denies to close the handle if there is
still a reference like this one, and this can be tested when we try to close the
database handle.
Database handles in this list will be called 'candidates for closing'.
*/
List SqliteCloseList;
#ifdef _LINUX_
void host_free_child_pid(pid_t pid)
{
/* Actually, 'ptr' is of type 'pid_t'*/
}
#endif
#ifdef WIN32
void host_free_child_pid(pid_t pid)
{
/* Actually, 'ptr' is of type 'pid_t'*/
}
#endif
#ifdef _LINUX_ //emulation of getch for Linux
#include <termios.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit()
{
unsigned char ch;
int nread;
if (peek_character != -1)
return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}
int getch()
{
char ch;
if(peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
(void)read(0,&ch,1);
return ch;
}
#endif
void free_C_structure(void *ptr, U8 struct_id, AnubisAllocator *allocator)
{
U32 sqlite_result;
switch(struct_id)
{
#ifdef _WITH_SSL_
case C_struct_id_SSL:
SSL_shutdown((SSL *)ptr);
SSL_free((SSL *)ptr);
return;
case C_struct_id_X509:
X509_free((X509 *)ptr);
return;
#endif /* _WITH_SSL_ */
#ifdef _WITH_GRAPHISM_
case C_struct_id_HostWindow:
host_free_host_window((U32)ptr);
return;
case C_struct_id_HostGC:
host_free_host_gc((U32)ptr);
return;
case C_struct_id_HostImage:
host_free_host_pixmap((U32)ptr);
return;
#endif /* _WITH_GRAPHISM_ */
case C_struct_id_SysFont:
free_load_sf_font(100,NULL,(Font1)ptr);
return;
case C_struct_id_Exec:
host_free_child_pid((pid_t)ptr);
return;
/* SQLite3 */
case C_struct_id_SQLite3:
/*
We are here because the garbage-collector of Anubis has decremented down to 0
the counter for the database handle 'ptr'. If this handle cannot be closed, this
means that there is still at least one SQLite3 statement referring to this
database handle. In this case the handle must be added to the list, and becomes
a 'candidate for closing'.
*/
sqlite_result = sqlite3_close((sqlite3 *)ptr);
if(sqlite_result != SQLITE_OK)
{
//LOGINFO("SQLITE_DB must be [%d] Close \n",ptr);
SqliteCloseList.AddItem(ptr);
}
return;
case C_struct_id_SQLite3Stmt:
{
/*
Get the database handle for this SQLite3 statement, and close the statement.
*/
sqlite3 * his_db = sqlite3_db_handle((sqlite3_stmt*)ptr);
sqlite_result = sqlite3_finalize((sqlite3_stmt *)ptr);
/*
If the database handle is a candidate for closing, try to close it. If it is
possible, there is no more statement refering to it, and the database handle is
no more a candidate for closing. In this case, it must be removed from the list.
*/
if(SqliteCloseList.HasItem(his_db))
{
sqlite_result = sqlite3_close((sqlite3 *)his_db);
if (sqlite_result == SQLITE_OK)
{
//LOGINFO("SQLITE_DB [%d] has closed \n",his_db);
SqliteCloseList.RemoveItem(his_db);
//int count = SqliteCloseList.GetCount();
//LOGINFO("SQLITE_DB CloseList has %d items\n",SqliteCloseList.GetCount());
}
}
return;
}
case C_struct_id_Opaque:
{
/* ptr points to a segment allocated by the VM, and containing:
offset 0: deletion function of type void f(void *)
offset 4: number of data bytes
offset 8: data bytes
*/
void (*delfunc)(void *) = (void (*)(void *))(((U32 *)ptr)[0]); /* get the deletion function */
if (*delfunc) { (*delfunc)((void *)(((U8 *)ptr)+4)); } /* apply it (if function exists) */
allocator->FreeDataSegment((U32 *)ptr); /* delete the segment */
return;
}
case C_struct_id_Library:
{
Library * lib = (Library*)ptr;
SAFE_DELETE(lib);
}
return;
/* DBAPI */
case C_struct_id_DB:
{
#ifdef WITH_SQLAPI
SAConnection *cnx = (SAConnection*)ptr;
SAFE_DELETE(cnx);
#endif
return;
}
case C_struct_id_DbStmt:
{
#ifdef WITH_SQLAPI
SACommand *cmd = (SACommand*)ptr;
SAFE_DELETE(cmd);
#endif
return;
}
default:
assert(0);
}
}
char *name_from_path(char *path)
{
U32 i = 0;
while(path[i] != 0) i++; /* go the the end of path */
while (i > 0 && path[i] != '/' && path[i] != '\\') i--;
if (i == 0)
return path;
else
return (path+i+1);
}
U32 anubis_string_list_length(U32 l)
{
U32 len = 0;
while (l != 0)
{
len++;
l = *(((U32 *)(l&pointer_mask))+2); /* tail of list */
}
return len;
}
const char *work_sort_string[] =
{
#define item(n) #n,
work_sort_list
#undef item
"unknown"
};
//extern struct Machine_struct machines[max_machine];
#ifdef instruction_count
void show_instruction_count(U32 mid, FILE *fp)
{
U32 i;
U32 total = 0;
for (i = 0; i < i_dummy; i++)
{
fprintf(fp," %30s: %d\n",instr_names[i],(machines[mid].i_count)[i]);
total += (machines[mid].i_count)[i];
}
fprintf(fp," %30s: %d\n","total",total);
}
#endif
#ifdef WIN32
#define is_invalid_socket(s) ((s) == INVALID_SOCKET)
#else
#define is_invalid_socket(s) ((s) < 0)
#endif
/*--- add a memory segment to an allocator ---------------------------------------------*/
//int enlarge_memory(Allocator allocator)
//{
// U32 *new_segment;
// //U32 *old_ffss;
//
// /* get a new segment */
// if ((new_segment = (U32 *)malloc((6+memory_seg_size)*sizeof(U32))) == NULL)
// {
// return 0; /* go on waiting for memory... */
// }
//
// allocator->word_size += 6+memory_seg_size;
//
// /* chain the new segment of memory to the machine */
// new_segment[0] = (U32)(allocator->memory);
// new_segment[1] = (U32)(allocator->memory); /* duplicated chaining */
// new_segment[2] = (U32)(allocator->memory); /* duplicated chaining */
// new_segment[3] = (U32)memory_seg_size; /* size */
// new_segment[4] = (U32)memory_seg_size; /* duplicated */
// new_segment[5] = (U32)memory_seg_size; /* duplicated */
// allocator->memory = new_segment;
//
// /* update chain of free segments */
// new_segment[6] = (U32)memory_seg_size; /* size of new secondary segment */
// new_segment[7] = (U32)(allocator->ffss); /* tail of secondary segment chain */
// allocator->ffss = new_segment+6;
//
//#ifdef debug_vm
// if (heap_test)
// compute_memory_check_sums(allocator);
//#endif
//
// return 1;
//}
/*--- enlarge a machine's stack -------------------------------------------------------*/
//void enlarge_machine_stack(int mid) /* machine id */
//{
// U32 * stack = machines[mid].SP_begin;
// int oldsize = (machines[mid].SP_end) - (machines[mid].SP_begin);
// U32 relative_SP = (machines[mid].SP) - (machines[mid].SP_begin);
// U32 * new_stack;
//
// assert(machines[mid].status == need_bigger_stack);
//
// if (oldsize+stack_more_size > (stack_per_machine>>2))
// {
// {
// if (current_memory+stack_more_size >= max_memory)
// {
// LOGINFO("The stack of machine number %d has reached the maximum\n| allowed (%d bytes). This machine has been stopped.\n", mid,stack_per_machine);
// machines[mid].status = finished;
// return;
// }
// }
// }
//
// if ((new_stack = (U32 *)realloc(stack,(oldsize + stack_more_size)*sizeof(U32))) == NULL)
// return; /* go on waiting for stack memory... */
//
// /* the stack has been successfully reallocated */
// machines[mid].SP_begin = new_stack;
// machines[mid].SP = new_stack+relative_SP;
// machines[mid].SP_end = new_stack + oldsize + stack_more_size;
//
// /* change machine's status */
// machines[mid].status = running;
//
// /*
// printf("the stack of machine number %d has been enlarged (%d words --> %d words).\n",
// mid,oldsize,oldsize+stack_more_size);
// */
//}
//void enlarge_machine_locked_files_stack(int mid)
//{
// U32 * stack = machines[mid].locked_files;
// U32 oldsize = machines[mid].locked_files_stack_size;
// U32 * new_stack;
//
// assert(machines[mid].status == need_bigger_locked_files_stack);
//
// if (oldsize+default_locked_files_stack_size > (stack_per_machine)>>4)
// {
// LOGINFO("The number of locked files for machine number %d too big.\n"
// "| This machine has been stopped.\n",mid);
// machines[mid].status = finished;
// return;
// }
//
// new_stack = (U32 *)realloc(stack,(oldsize+default_locked_files_stack_size)*sizeof(U32));
// if (new_stack == NULL) return; /* wait ... */
//
// /* then stack has been successfully reallocated */
// machines[mid].locked_files = new_stack;
// machines[mid].locked_files_stack_size += default_locked_files_stack_size;
//
// /* let the scheduler restart this machine */
// machines[mid].status = running;
//}
//
/* debugging tool */
//void test_memory_chain(Allocator allocator)
//{
// U32 *aux;
//
// aux = allocator->memory;
//
// while (aux != NULL)
// {
// if (aux[0] != aux[1] || aux[0] != aux[2])
// {
// LOGINFO("in test_memory_chain: aux[0] == %.8x, aux[1] == %.8x, aux[2] == %.8x\n",
// aux[0], aux[1], aux[2]);
// my_exit(3);
// }
// if (aux[3] != aux[4] || aux[3] != aux[5])
// {
// LOGINFO("in test_memory_chain: aux[3] == %.8x, aux[4] == %.8x, aux[5] == %.8x\n",
// aux[3], aux[4], aux[5]);
// my_exit(3);
// }
// aux = (U32 *)aux[0];
// }
//}
//void check_segments_sizes(Allocator allocator)
//{
// U32 * ptr = allocator->ffss;
// while (ptr != NULL)
// {
// assert(ptr[0] <= memory_seg_size);
// ptr = (U32 *)(ptr[1]);
// }
//}
//void check_memory_pointers(Allocator allocator)
//{
// int dummy;
// U32 *mem;
// U32 *ptr = allocator->ffss;
// int checked;
//
// while (ptr != NULL)
// {
// checked = 0;
// mem = allocator->memory;
// while (mem != NULL)
// {
// if (mem <= ptr && ptr <= mem+mem[3])
// { checked = 1; break; }
// mem = (U32 *)(mem[0]);
// }
// if (!checked)
// {
// LOGINFO("\ncheck_memory_pointers: failed");
// fflush(stdout);
// dummy = ((char *)0)[0];
// }
// ptr = (U32 *)(ptr[1]);
// }
//}
//void show_heap(Allocator allocator)
//{
// U32 *ptr = allocator->ffss;
//
// LOGINFO("\n ---- heap ---- heap ----");
// while (ptr != NULL)
// {
// LOGINFO("\n heap: %p %u",ptr,ptr[0]);
// ptr = (U32 *)(ptr[1]);
// }
// LOGINFO("\n ---- heap ---- heap ----");
//}
//#ifdef debug_vm
//void compute_memory_check_sums(Allocator allocator)
//{
// U32 seg_num = 0;
// U32 size_sum = 0;
// U32 ptr_sum = 0;
// U32 *ptr = allocator->ffss;
//
// while (ptr != NULL)
// {
// seg_num++;
// size_sum += ptr[0];
// ptr_sum += (U32)(ptr);
// ptr = (U32 *)(ptr[1]);
// }
// allocator->ffss_seg_num = seg_num;
// allocator->ffss_size_sum = size_sum;
// allocator->ffss_ptr_sum = ptr_sum;
//}
//
//#endif
///* Compute the size of the free storage chain */
//U32 storage_chain_words(Allocator allocator)
//{
// U32 result = 0;
// U32 *ptr = allocator->ffss;
//
// while(ptr != NULL)
// {
// result += ptr[0];
// ptr = (U32 *)(ptr[1]);
// }
// return result;
//}
//
#ifdef debug_vm
//void test_memory_check_sums(Allocator allocator)
//{
// U32 seg_num = 0;
// U32 size_sum = 0;
// U32 ptr_sum = 0;
// U32 *ptr = allocator->ffss;
// int dummy;
// int count = 0;
//
// while (ptr != NULL)
// {
// count++;
// if (count > 10+(allocator->allocated_segments))
// {
// LOGINFO("\ntest_memory_check_sums: failed");
// LOGINFO("\nincompatible number of allocated segments");
// LOGINFO("\n(maybe a loop in free segments chain)");
// LOGINFO("\nIP - code = %d\n",IPcode);
// fflush(stdout);
// dummy = ((char *)0)[0];
// }
// seg_num++;
// size_sum += ptr[0];
// ptr_sum += (U32)(ptr);
// ptr = (U32 *)(ptr[1]);
// }
// if (
// allocator->ffss_seg_num != seg_num ||
// allocator->ffss_size_sum != size_sum ||
// allocator->ffss_ptr_sum != ptr_sum)
// {
// LOGINFO("\ntest_memory_check_sums: failed");
// LOGINFO("\nallocator->ffss_seg_num = %20u computed: %20u",allocator->ffss_seg_num,seg_num);
// LOGINFO("\nallocator->ffss_size_sum = %20u computed: %20u",allocator->ffss_size_sum,size_sum);
// LOGINFO("\nallocator->ffss_ptr_sum = %20u computed: %20u",allocator->ffss_ptr_sum,ptr_sum);
// show_heap(allocator);
// LOGINFO("\nIP - code = %d\n",IPcode);
// fflush(stdout);
// dummy = ((char *)0)[0];
// }
//}
//void test_memory_check_sums_IP(Allocator allocator, int IPcode)
//{
// U32 seg_num = 0;
// U32 size_sum = 0;
// U32 ptr_sum = 0;
// U32 *ptr = allocator->ffss;
// int dummy;
//
// while (ptr != NULL)
// {
// /*
// printf("\n ---- machine %d heap: %p %u",mid,ptr,ptr[0]);
// fflush(stdout);
// */
// seg_num++;
// size_sum += ptr[0];
// ptr_sum += (U32)(ptr);
// ptr = (U32 *)(ptr[1]);
// }
// if (
// allocator->ffss_seg_num != seg_num ||
// allocator->ffss_size_sum != size_sum ||
// allocator->ffss_ptr_sum != ptr_sum)
// {
// LOGINFO("\ntest_memory_check_sums: failed");
// LOGINFO("\nallocator->ffss_seg_num = %20u computed: %20u",allocator->ffss_seg_num,seg_num);
// LOGINFO("\nallocator->ffss_size_sum = %20u computed: %20u",allocator->ffss_size_sum,size_sum);
// LOGINFO("\nallocator->ffss_ptr_sum = %20u computed: %20u",allocator->ffss_ptr_sum,ptr_sum);
// show_heap(allocator);
// LOGINFO("\nIP - code = %d\n",IPcode);
// fflush(stdout);
// dummy = ((char *)0)[0];
// }
//}
#endif
/*--- release a machine --------------------------------------------------*/
//void release_machine(int mid)
//{
// assert(machines[mid].status != machine_not_used);
//
// /* free machine's stack */
// free(machines[mid].SP_begin);
//
// /* set machine's status to 'not_used' */
// machines[mid].status = machine_not_used;
// used_machines--;
//
//}
/* link and relocate addresses */
void link_globals_and_relocate(U8* code,
U32 size) // size of code
{
U8 *ptr = code;
U32 k;
//printf("link_globals: code size = %d\n",size); my_exit(1);
assert((((U32)code)&3) == 0); /* code must be aligned on 0 mod 4 */
while ( ((U32)(ptr-code)) < size)
{
#if 0
//if ((*ptr == i_word_64) || (*ptr == i_word_128) || (*ptr == i_load_int_big))
{
LOGINFO("relocating instr '%s' (%d) at offset %d\n",instr_names[*ptr],*ptr,ptr-code);
fflush(stdout);
//getchar();
}
#endif
switch (*ptr)
{
/* one byte instructions: nothing to relocate */
case i_odd_align:
case i_ret:
case i_del_index_direct:
case i_del_index_indirect:
case i_invalid:
case i_push:
case i_remove_monitor:
case i_unlock:
case i_lock:
case i_pop1:
case i_pop3:
case i_swap:
case i_push_eq_data:
case i_copy_ptr:
case i_copy_function:
case i_copy_int:
case i_vcopy_ptr:
case i_vcopy_function:
case i_vcopy_int:
case i_vcopy_null:
case i_index_indirect:
case i_free_seg_0:
case i_free_seg_1_pop2_ret:
case i_free_closure_1_pop2_ret:
case i_indirect_del_ptr:
case i_indirect_del_function:
case i_indirect_del_multiclosure:
case i_indirect_del_int:
case i_del_function:
case i_del_multiclosure:
case i_del_int:
case i_indirect_del_conn:
case i_indirect_del_queue_in:
case i_indirect_del_queue_out:
case i_eq_string:
case i_eq_byte_array:
case i_eq_int:
case i_give_up:
case i_start_debug_avm:
case i_stop_debug_avm:
case i_read_locvar:
case i_write_locvar:
case i_new_locvar:
case i_del_ptr:
case i_del_conn:
case i_finish:
/* primitive types pseudo-instructions */
#define item(n) case i_##n:
primitive_types_list
#undef item
#define item(n) case i_indirect_##n:
primitive_types_list
#undef item
case i_type_Opaque:
case i_indirect_type_Opaque:
case i_type_0:
case i_indirect_type_0:
case i_alt_number_indirect:
case i_free_var_seg:
case i_create_var:
case i_get_vv:
case i_xchg_vv:
case i_ret_if_zero:
case i_get_var_monitors:
case i_nop:
case i_execute_module:
case i_lock_var:
case i_unlock_var:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s",ptr-code,instr_names[*ptr]);
}
ptr += 1;
break;
/* two bytes instructions: nothing to relocate */
case i_glue_index:
case i_glue:
case i_store_index:
case i_store_0:
case i_store_1:
case i_store_2:
case i_store_4:
case i_glue_mixed_index:
case i_unstore_0:
case i_unstore_1:
case i_unstore_2:
case i_unstore_4:
case i_index_direct:
case i_alt_number_direct:
case i_alloc:
case i_increment_del:
case i_increment_eq:
case i_copy_mixed:
case i_vcopy_mixed:
case i_unstore_copy_ptr:
case i_unstore_copy_function:
case i_unstore_copy_int:
case i_copy_stack_ptr:
case i_copy_stack_function:
case i_copy_stack_int:
case i_mixed_alt_begin:
case i_large_alt_begin:
case i_mixed_alt_end:
case i_large_alt_end:
case i_revert_to_computing:
case i_success:
case i_protect:
case i_indirect_del_struct_ptr:
case i_apply:
case i_incr_indirect_del_ptr:
case i_incr_indirect_del_function:
case i_incr_indirect_del_conn:
case i_incr_indirect_del_int:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d",ptr-code,instr_names[*ptr],*(ptr+1));
}
ptr += 2;
break;
/* three bytes instructions: nothing to relocate */
case i_unglue:
case i_unstore_copy_mixed:
case i_copy_stack_mixed:
case i_syscall:
case i_put_copy_direct:
case i_put_copy_indirect:
case i_put_copy_function:
case i_put_copy_int:
case i_incr_indirect_del_struct_ptr:
case i_sdrep:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %d",ptr-code,instr_names[*ptr],*(ptr+1),*(ptr+2));
}
ptr += 3;
break;
/* five bytes instructions of the form (U8)instr (U32)address (address must be relocated) */
case i_address:
case i_call:
case i_del:
case i_false_jmp:
case i_indirect_del:
case i_jmp:
case i_jmp_eq_stack:
case i_jmp_false:
case i_jmp_neq_0:
case i_jmp_neq_1:
case i_jmp_neq_2:
case i_jmp_neq_4:
case i_jmp_neq_indexes_large:
case i_jmp_neq_string:
case i_jmp_neq_byte_array:
case i_jmp_neq_int:
case i_true_jmp:
case i_push_retpoint:
case i_push_function:
case i_type_large:
case i_indirect_type_large:
case i_serialize:
case i_unserialize:
case i_dec3:
case i_unprotect:
case i_get_var_handler:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)));
}
ptr++;
RELLOC(ptr, code);
break;
/* six bytes instructions of the form (U8)instr (U32)address (U8) (address must be relocated) */
case i_incr_indirect_del:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u %d",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)),*(ptr+5));
}
ptr++;
RELLOC(ptr,code);
ptr++;
break;
/* seven bytes instructions of the form (U8)instr (U8)mask (U32)address (U8) (address must be relocated) */
case i_incr_indirect_del_mixed:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %u %d",ptr-code,instr_names[*ptr],
*(ptr+1),*((U32 *)(ptr+2)),*(ptr+6));
}
ptr += 2;
RELLOC(ptr,code);
ptr++;
break;
/* four bytes instructions: no relocation */
case i_put_copy_mixed:
case i_put_micro_copy_direct:
case i_put_micro_copy_indirect:
case i_put_micro_copy_function:
case i_put_micro_copy_int:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %d %d",ptr-code,instr_names[*ptr],
*(ptr+1),*(ptr+2),*(ptr+3));
}
ptr += 4;
break;
/* five bytes instructions without relocation */
case i_put_micro_copy_mixed:
case i_load_int_small:
case i_load_int_small_push:
case i_load_word32:
case i_peek:
case i_peek_push:
case i_peek_copy_push_ptr:
case i_peek_copy_push_function:
case i_peek_copy_push_int:
case i_peek_copy_ptr:
case i_peek_copy_function:
case i_peek_copy_int:
case i_collapse:
case i_eq:
case i_del_stack_ptr:
case i_del_stack_conn:
case i_check_stack:
case i_del_stack_function:
case i_del_stack_multiclosure:
case i_del_stack_int:
case i_del_stack_queue_in:
case i_del_stack_queue_out:
case i_syscall32:
case i_push_word32:
case i_push_ffcomp:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %d %d %d",ptr-code,instr_names[*ptr],
*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4));
}
ptr += 5;
break;
/* six bytes instructions without relocation */
case i_peek_copy_push_mixed:
case i_peek_copy_mixed:
case i_del_stack_struct_ptr:
case i_peek_ffcomp:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %u",ptr-code,instr_names[*ptr],
*(ptr+1),*((U32 *)(ptr+2)));
}
ptr += 6;
break;
case i_end_op:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u %d", ptr-code, instr_names[*ptr],
*((U32 *)(ptr+1)), *(ptr+5));
}
ptr += 6;
break;
/* six bytes instructions of the form (U8)instr (U8) (U32)address (address must be relocated)*/
case i_select_index_indirect:
case i_del_mixed:
case i_indirect_del_mixed:
case i_start:
case i_startp:
case i_type_mixed:
case i_indirect_type_mixed:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %u",ptr-code,instr_names[*ptr],
*(ptr+1),*((U32 *)(ptr+2)));
}
ptr += 2;
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
break;
/* nine bytes instructions of the form (U8)instr (U32)address (U32)address (both addresses must be relocated)*/
case i_put_closure_labels:
case i_create_queue:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u %u",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)),*((U32 *)(ptr+5)));
}
ptr += 1;
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
break;
/* seven bytes instructions of the form (U8)instr (U8) (U8) (U32) address (address must be relocated)*/
case i_select_index_direct:
case i_jmp_neq_indexes_mixed:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %d %u",ptr-code,instr_names[*ptr],
*(ptr+1),*(ptr+2),*((U32 *)(ptr+3)));
}
ptr += 3;
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
break;
/* nine bytes instructions of the form (U8)instr (U32)depth (U32)address (address must be relocated) */
case i_del_stack:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u %u",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)),*((U32 *)(ptr+5)));
}
ptr += 5;
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
break;
/* ten bytes instructions of the form (U8)instr (U32) (U8) (U32)address (address must be relocated) */
case i_del_stack_mixed:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u %d %u",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)),*(ptr+5),*((U32 *)(ptr+6)));
}
ptr += 6;
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
break;
/* nine bytes instructions without relocation */
case i_load_float:
case i_micro_peek:
case i_micro_peek_push:
case i_micro_peek_copy_ptr:
case i_micro_peek_copy_push_ptr:
case i_micro_peek_copy_function:
case i_micro_peek_copy_push_function:
case i_micro_peek_copy_int:
case i_micro_peek_copy_push_int:
case i_mcollapse:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u %u",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)),*((U32 *)(ptr+5)));
}
ptr += 9;
break;
/* ten bytes instructions without relocation */
case i_micro_peek_copy_mixed:
case i_micro_peek_copy_push_mixed:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d, %u %u",ptr-code,instr_names[*ptr],
*((U8 *)(ptr+1)),*((U32 *)(ptr+2)),*((U32 *)(ptr+6)));
}
ptr += 10;
break;
/* (U8)instr (U8)k (U32)address_1 ... (U32)address_k (all addresses must be relocated) */
case i_switch:
case i_type_large_switch:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d",ptr-code,instr_names[*ptr], *(ptr+1));
for (k = 0; k < *(ptr+1); k++)
{
fprintf(nsc_file," %u",*((U32 *)(ptr+2+(k*4))));
}
}
ptr++;
k = *ptr;
ptr++;
for (; k >0; k--)
{
RELLOC(ptr,code);
}
break;
/* (U8)instr (U8)k (U32)address_0 (U32)address_1 ... (U32)address_k (all addresses must be relocated)
the same one, but with one more address.
*/
case i_put_multiclosure_labels:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d",ptr-code,instr_names[*ptr], *(ptr+1));
for (k = 0; k < *(ptr+1); k++)
{
fprintf(nsc_file," %u",*((U32 *)(ptr+2+(k*4))));
}
}
ptr++;
k = (*ptr)+1; // one more address
ptr++;
for (; k >0; k--)
{
RELLOC(ptr,code);
}
break;
/* (U8)instr (U8)mask (U8)k (U32)address_1 ... (U32)address_k (all addresses must be relocated) */
case i_type_mixed_switch:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %d",ptr-code,instr_names[*ptr],
*(ptr+1),*(ptr+2));
for (k = 0; k < *(ptr+2); k++)
{
fprintf(nsc_file," %u",*((U32 *)(ptr+3+(k*4))));
}
}
ptr++;
ptr++; /* mask for mixed type */
k = *ptr;
ptr++;
for (; k > 0; k--)
{
RELLOC(ptr, code);
// *(((U32 *)ptr)++) += (U32)code;
}
break;
case i_mdrep: /* mdrep U16 U16 (U16)n n*(U8,U16) nothing to relocate */
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d %d ",ptr-code,instr_names[*ptr],
*((U16 *)(ptr+1)),*((U16 *)(ptr+3)));
for (k = 0; k < *((U16 *)(ptr+5)); k++)
{
fprintf(nsc_file,"(%d . %d) ",*((U8 *)(ptr+7+3*k)),*((U16
*)(ptr+8+3*k)));
}
}
ptr += 7+3*(*((U16 *)(ptr+5)));
break;
/* strings must be 'deciphered' (each byte XORed with 172) */
case i_string:
case i_string_push:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u (\"",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)));
for (k = 0; k < (U32)(*((U32 *)(ptr+1))); k++)
{
fprintf(nsc_file,"%c",(*(ptr+5+k))^172);
}
fprintf(nsc_file,"\")");
}
for (k = 0; k < (U32)(*((U32 *)(ptr+1))); k++)
{
*(ptr+k+5) ^= 172;
}
ptr += 5+(U32)(*((U32 *)(ptr+1)));
break;
case i_byte_array:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %d ({",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)));
for (k = 0; k < (*((U32 *)(ptr+1))); k++)
{
fprintf(nsc_file,"%d ",(*(ptr+5+k)));
}
fprintf(nsc_file,"})");
}
ptr += 5+(*((U32 *)(ptr+1)));
break;
/* (U8)instr (U8)dec [dec align bytes] (U32)counter
(U32)numbigits (U32)bigit ... (U32)bigit
[3-dec align bytes]
total size: 1 + 1 +dec + 4 + 4 + 4*numbigits + (3-dec) = 13 + 4*numbigits
(no relocation) */
case i_load_int_big:
case i_load_int_big_push:
{
U32 n = *((U32 *)(ptr+1)); /* number of bigits */
ptr += 5 + 4*n;
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s ",ptr-code,instr_names[*ptr]);
fprintf(nsc_file,"(%u bigits) ",*((U32 *)(ptr+1)));
for (k = 0; k < (U32)(*((U32 *)(ptr+1))); k++)
{
fprintf(nsc_file,"%d ",(*(ptr+5+k)));
}
}
}
break;
/* (U8)instr (U32)k (U8)byte_1 ... (U8)byte_k (no relocation) */
case i_type_small_alt:
case i_type_8:
case i_type_16:
case i_type_32:
case i_indirect_type_8:
case i_indirect_type_16:
case i_indirect_type_32:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %u",ptr-code,instr_names[*ptr],
*((U32 *)(ptr+1)));
for (k = 0; k < (U32)(*((U32 *)(ptr+1))); k++)
{
fprintf(nsc_file,"%d ",*(ptr+5+k));
}
}
ptr++;
k = *(((U32 *)(ptr)));
ptr += sizeof(U32);
ptr += k;
break;
/* (U8)instr [25 bytes] (no relocation) */
case i_begin_op:
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s(%s)", ptr-code, instr_names[*ptr], ptr+4);
}
ptr += 26;
break;
/* (U8)instr [16 bytes] (no relocation) */
case i_word_64:
case i_word_64_push:
{
assert((((U32)ptr + 2 + (U32)(*(ptr+1))) & 3) == 0);
if (nsc_file != NULL)
{
U32 dec = *(ptr+1);
fprintf(nsc_file,"\n%8d | %s %ux %ux ", ptr-code, instr_names[*ptr],
(U32)(ptr+6+dec), (U32)(ptr+10+dec));
}
ptr += 17;
}
break;
/* (U8)instr [24 bytes] (no relocation) */
case i_word_128:
case i_word_128_push:
{
assert((((U32)ptr + 2 + (U32)(*(ptr+1)) ) & 3) == 0);
if (nsc_file != NULL)
{
fprintf(nsc_file,"\n%8d | %s %ux %ux %ux %ux ", ptr-code, instr_names[*ptr],
(U32)(ptr+5), (U32)(ptr+9), (U32)(ptr+13), (U32)(ptr+17));
}
ptr += 25;
}
break;
default:
LOGINFO("link_globals: unknown instruction: %d at %d\n",*ptr,ptr-code);
fflush(stdout);
my_exit(3);
assert(0);
}
}
}
/* making a virtual machine pair */
U32 anubis_cons(U32 h, U32 t, U32 index, AnubisAllocator *allocator)
{
U32 result;
if ((result = allocator->AllocateDataSegment(3)) == 0)
{
allocator->EnlargeMemory();
if ((result = allocator->AllocateDataSegment(3)) == 0)
{
printf("Cannot make a pair.\n");
return 0;
}
}
((U32 *)result)[1] = h;
((U32 *)result)[2] = t;
return result|index; /* glue mixed index */
}
/* making a virtual machine triple */
U32 anubis_mcons3(U32 h, U32 t, U32 u, U32 index, AnubisAllocator *allocator)
{
U32 result;
if ((result = allocator->AllocateDataSegment(4)) == 0)
return 0;
((U32 *)result)[1] = h;
((U32 *)result)[2] = t;
((U32 *)result)[3] = u;
return result|index; /* glue mixed index */
}
/*************** Connections tools ***************************/
/* opening a connection to a file */
U32 /* returns 1 if connection opened, 0 otherwise */
open_file_connection(U32 data_seg, /* segment, see vm.c and vm.h */
char *name, /* name of connection */
U32 read_or_write, /* 'conn_read' and friends ORed here */
U32 mode)
{
FILE *fp;
char cmode[4];
U32 i;
struct stat statbuf;
char new_name[1000];
strcpy(cmode, (read_or_write==conn_read) ? "rb" : ((mode==0) ? "w+b" : "a+b"));
snprintf(new_name,995,"%s",name);
i = 0;
while (new_name[i] != 0)
{
#ifdef WIN32
if (new_name[i] == '/') new_name[i] = '\\';
#else
if (new_name[i] == '\\') new_name[i] = '/';
#endif
i++;
}
if (read_or_write == conn_read)
{
if (stat(new_name,&statbuf)) return 0;
#ifdef WIN32
if (! (_S_IFREG & statbuf.st_mode)) return 0;
#else
if (! S_ISREG(statbuf.st_mode)) return 0;
#endif
}
//printf("Trying to open file %s ... ",new_name);
if ((fp = fopen(new_name,cmode)) == NULL)
{
//printf("Failed.\n");
return 0;
}
*(((U8 *)data_seg)+4) = (U8)conn_file;
*(((U8 *)data_seg)+5) = (U8)mode;
*((U32 *)(((U8 *)data_seg)+8)) = (U32)fp;
//printf("Succeeded.\n");
return 1;
}
/*** Network (IP) ***/
/* opening a connection to the network */
U32 /* returns: 0 success or still in progress
1 cannot create the socket
2 address:port not available on remote machine
3 connection refused by server
4 network unreachable
5 address:port already in use
*/
open_IP_connection(U32 conn_seg,
U32 ip_addr,
U32 ip_port,
U32 mode)
{
U32 sockError = 0;
#ifdef WIN32
U32 sock = 0;
#else
int sock = 0;
#endif
#if defined (_LINUX_) || (__BEOS__)
int oldflags;
#endif
struct sockaddr_in server_name;
/* create a socket */
sock = socket(AF_INET, SOCK_STREAM,0);
#ifdef WIN32
if (sock == INVALID_SOCKET)
{
fprintf(stderr, "[VM] Can't create socket. WSAGetLastError() = %d\n", WSAGetLastError());
#else
if (sock < 0)
{
fprintf(stderr, "[VM] Can't create socket. errno = %d\n", errno);
#endif
return 1;
}
// struct linger the_linger;
// the_linger.l_onoff = 1; /* transmit all before closing */
// the_linger.l_linger = 2; /* timeout = 2 sec */
// setsockopt(sock, SOL_SOCKET,SO_LINGER,(char*)&the_linger,sizeof(struct linger));
/* make the socket non blocking (this is required to
make connect return immediately) */
#if defined (_LINUX_) || (__BEOS__)
oldflags = fcntl(sock,F_GETFL,0);
if (oldflags == -1)
{
shutdown(sock, 2);
closesocket(sock);
return 1;
}
oldflags |= O_NONBLOCK;
fcntl(sock,F_SETFL,oldflags);
bool keepAlive = true;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &keepAlive, sizeof(bool));
#endif
#ifdef WIN32
{
u_long argp = 1;
ioctlsocket(sock,FIONBIO,&argp);
bool keepAlive = true;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &keepAlive, sizeof(bool));
}
#endif
/* initialize server_name */
memset(&server_name,0,sizeof(struct sockaddr_in));
server_name.sin_family = AF_INET;
server_name.sin_port = htons((U16)ip_port);
memcpy(&server_name.sin_addr, &ip_addr, sizeof(U32));
// printf("Socket %d port %d\n",sock,ip_port);
//printf("\ntry open %d.%d.%d.%d|%d socket %d ",server_name.sin_addr.S_un.S_un_b.s_b1,server_name.sin_addr.S_un.S_un_b.s_b2,server_name.sin_addr.S_un.S_un_b.s_b3,server_name.sin_addr.S_un.S_un_b.s_b4,ip_port,sock);
/* try to connect */
if (connect(sock,(struct sockaddr *)&server_name,sizeof(struct sockaddr)) == -1)
{
#if WIN32
sockError = GetLastError();
#else
sockError = errno;
#endif
switch (sockError)
{
case EINPROGRESS:
case EWOULDBLOCK:
//#ifdef WIN32
// case WSAEWOULDBLOCK:
//#endif
break;
case EADDRNOTAVAIL:
closesocket(sock);
return 2;
case ECONNREFUSED:
closesocket(sock);
return 3;
case ENETUNREACH:
closesocket(sock);
return 4;
case EADDRINUSE:
closesocket(sock);
return 5;
default:
closesocket(sock);
return 1;
}
}
/* at that point the connection is perhaps not established,
but we can't wait. The connection is flagged 'in_progress'.
This flag will be tested by another routine: is_IP_connection_ready. */
*(((U8 *)conn_seg)+4) = (U8)conn_network;
*(((U8 *)conn_seg)+5) = (U8)mode;
*(((U32 *)conn_seg)+4) = (U32)(time(NULL)+3600); /* timeout */
*((U32 *)(((U8 *)conn_seg)+8)) = (U32)sock;
return 0;
}
U32 /* returns: 0 ready
1 not yet ready
2 time is out
3 connection failed
*/
is_IP_connection_ready(U32 conn_seg)
{
#define flags (((U8 *)conn_seg)[5])
#define count (((U32 *)conn_seg)[4])
U32 optVal;
U32 optLen = sizeof(U32);
U32 sock = *(U32 *)(((U8 *)conn_seg)+8);
// FD_ZERO(&the_fd_set);
//
FD_SET(sock,&the_fd_set);
FD_ZERO(&the_fd_read_set);
FD_ZERO(&the_fd_write_set);
FD_ZERO(&the_fd_except_set);
FD_SET(sock, &the_fd_write_set);
FD_SET(sock, &the_fd_read_set);
FD_SET(sock, &the_fd_except_set);
//printf(".");
timeout_no_wait.tv_sec = 0;
timeout_no_wait.tv_usec = 0;
if (select(FD_SETSIZE,
&the_fd_read_set,
&the_fd_write_set,
&the_fd_except_set,
&timeout_no_wait) <= 0)
{
/* not yet ready */
if (count < (U32)time(NULL))
{
//printf("\ntime is out\n"); fflush(stdout);
shutdown(sock,2);
closesocket(sock);
return 2;
}
else
{
return 1;
}
}
else
{
if (FD_ISSET(sock, &the_fd_write_set))
{
// printf("Socket write status\n");
if(getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&optVal, (socklen_t*)&optLen) != SOCKET_ERROR)
{
switch(optVal)
{
case ECONNREFUSED:
// printf("socket %d connection refused\n", sock);
shutdown(sock,2);
closesocket(sock);
return 3;
case 0:
// printf("socket connection ok\n");
return 0;
default:;
// printf("socket %d error value [%d] ", sock, optVal);
}
}
// printf("SockOpt Value: %ld\n", optVal);
shutdown(sock,2);
closesocket(sock);
return 3;
}
if(FD_ISSET(sock, &the_fd_except_set))
{
// printf("Socket exception status\n");
if(getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&optVal, (socklen_t*)&optLen) != SOCKET_ERROR)
{
switch(optVal)
{
case ECONNREFUSED:
// printf("socket %d connection refused ", sock);
break;
default:;
// printf("socket %d error value [%d] ", sock, optVal);
}
}
// printf("SockOpt Value: %ld\n", optVal);
// printf("is_IP_connection_ready Socket [%d] exception\n", sock);
shutdown(sock,2);
closesocket(sock);
return 3;
}
/* connection is ready */
return 0;
}
#undef flags
#undef count
}
/**
* Return true if the connection is closed. Else the operation would block,
* then it should be tried again later.
*/
bool close_connection(U8 *conn)
{
#ifdef WIN32
SOCKET fdSocket = ~0;
#else
SOCKET fdSocket = -1;
#endif
bigtime_t t0 = 0;
switch (conn[4]) /* type of connection */
{
case conn_file:
{
FILE *fp = (FILE *)(*((U32 *)(((U8 *)conn)+8)));
if (fp != stdin && fp != stdout && fp != stderr)
{
int err = errno;
if(fclose(fp) != 0)
LOGERROR("close_connection: close on file(%d) failed with errno = %d.\n", fileno(fp), err);
}
return true;
}
case conn_network:
fdSocket = (*((int *)(conn+8)));
// LOGINFO("NETWORK SOCKET [%d] CLOSE REQUESTED\n",fdSocket);
FD_CLR(fdSocket, &descriptors_waited_for_input);
FD_CLR(fdSocket, &descriptors_waited_for_output);
t0 = system_time();
{
fd_set rfds, wfds, efds;
FD_ZERO(&rfds);
FD_SET(fdSocket,&rfds);
FD_ZERO(&wfds);
FD_SET(fdSocket,&wfds);
FD_ZERO(&efds);
FD_SET(fdSocket,&efds);
timeout_no_wait.tv_sec = 0;
timeout_no_wait.tv_usec = 0;
int nb = select(FD_SETSIZE, &rfds, &wfds, &efds, &timeout_no_wait);
if(nb < 0)
{
LOGERROR("close_connection: select() failed with errno = %d.\n", LAST_SOCKET_ERROR);
}
else if(nb == 0) // Some data needs to be sent. Closing the socket will lose these data.
{
//LOGINFO("All data not yet sent, delaying the socket (%d) close.\n", fdSocket);
return false;
}
else if(FD_ISSET(fdSocket, &efds))
{
LOGERROR("close_connection: socket (%d) was in error state.\n", fdSocket);
}
else if(! FD_ISSET(fdSocket, &wfds))
{
if(FD_ISSET(fdSocket, &rfds))
{
char buf[10];
int nb = recv(fdSocket, buf, 1, 0);
if(nb < 0)
LOGERROR("close_connection: Socket (%d) is ready for read, but reading it returns an error [%d].\n", fdSocket, LAST_SOCKET_ERROR);
// else if(nb == 0)
// LOGINFO("Socket (%d) was gracefully closed by client.\n", fdSocket);
// else
// LOGINFO("close_connection: Socket (%d) ready for reading with data available.\n", fdSocket);
}
else
LOGINFO("close_connection: Socket (%d) isn't in Ready state (read or write), nor in error state, but select() returns a positive value.\n", fdSocket);
}
// our socket is ready for writing, so all data are sent. We can close it.
}
if(shutdown(fdSocket, 2) == SOCKET_ERROR)
{
int err = LAST_SOCKET_ERROR;
if(err != ENOTCONN)
LOGERROR("close_connection: shutdown failed with errno = %d.\n", err);
}
case conn_listener:
if is_invalid_socket(fdSocket)
{
fdSocket = (*((int *)(conn+8)));
t0 = system_time(); // case of listener
}
if(closesocket(fdSocket) == SOCKET_ERROR)
{
int err = LAST_SOCKET_ERROR;
//LOGERROR("close_connection: close on socket(%d) failed with errno = %d.\n", fdSocket, err);
if(err == EWOULDBLOCK) // Only under Windows, but should never occur because of the previous select()
return false;
}
t0 = system_time() - t0;
if(t0 > 1000000)
{
printf("close_connection() too long (%.1f s)\n", (float)t0 / 1000000.0);
}
return true;
case conn_local:
return true;
default:
assert(0);
return true;
}
}
/* This function is never called (remarked 2006/07/11) */
U32 connection_is_closed(U32 c)
{
U8 *conn = (U8 *)c;
switch (conn[4])
{
case conn_file:
return 0;
case conn_listener:
return 0;
case conn_network:
// close(*((int *)(conn+8)));
return 0;
case conn_local:
return 0;
default:
assert(0);
return 0;
}
}
int /* returns EOF (connection closed by peer) or a
byte value or 2*EOF meaning 'wait' (connection still alive
but nothing to be read from it) */
read_byte(U8 *conn)
{
U8 str[2];
int i;
switch (conn[4]) /* type of connection (see vm.h) */
{
case conn_file:
FILE* fd;
fd = *((FILE **)(conn+8));
if (0 && fd == stdin) // inhibited because kbhit/getch do not work (try with syntactic_analysis/calculator_example.apg)
{
#ifdef WIN32
/* HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD events;
INPUT_RECORD buffer;
PeekConsoleInput(handle, &buffer, 1, &events);
if (events > 0)
{
if(buffer.EventType == KEY_EVENT & buffer.Event.KeyEvent.bKeyDown==1)
{
int read_char;
ReadConsoleInput(handle, &buffer, 1, &events);
read_char = buffer.Event.KeyEvent.uChar.AsciiChar;
FlushConsoleInputBuffer(handle);
if (read_char == 0)
{
return 2*EOF;
}
else
{
if (read_char != 27) //don't show escape
putchar(read_char);
//printf("Read char [%d]\n bKeyDown [%d]\n",read_char, buffer.Event.KeyEvent.bKeyDown);
return(read_char);
}
}
else if (buffer.EventType > 0)
{
FlushConsoleInputBuffer(handle);
}
}
return 2*EOF;
*/
#endif
if (kbhit()) //a character waiting to be read
return(getch());
else
return 2*EOF;
}
return getc(fd);
case conn_network:
{
int sock = *(int *)(conn+8);
//fprintf(stderr,"Trying to read a byte \n"); fflush(stderr);
FD_CLR(sock, &descriptors_waited_for_input);
/* read a byte from the connection */
i = recv(sock,(char *)str,1,0);
#if defined (_LINUX_) || (__BEOS__)
if (i == -1 && errno == EWOULDBLOCK)
{
//fprintf(stderr,"i = %d errno = EWOULDBLOCK \r",i); fflush(stderr);
printf("[READ_BYTE] sock=%d -> EWOULDBLOCK, re-register\n", sock);
FD_SET(sock,&descriptors_waited_for_input);
return 2*EOF;
}
#endif
#ifdef WIN32
if (i == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
printf("[READ_BYTE] sock=%d -> EWOULDBLOCK, re-register\n", sock);
FD_SET(sock,&descriptors_waited_for_input);
return 2*EOF;
}
#endif
else if (i > 0)
{
printf("[READ_BYTE] sock=%d -> byte=%d\n", sock, (int)str[0]);
return str[0];
}
else
{
//printf("Connection closed by peer.\n");
return EOF; /* connection has been closed by peer */
}
}
case conn_local:
return (int)(conn[8]);
default:
assert(0);
return EOF;
}
}
int /* returns a datum of type Maybe(One):
0 = failure,
1 = success(unique). */
write_byte(U8 value, U8 *conn)
{
U8 str[2];
str[0] = value;
str[1] = 0;
#ifdef WIN32
int flags = 0;
#else
int flags = 0;
#ifndef __APPLE__
flags = MSG_NOSIGNAL;
#endif
#endif
switch (conn[4]) /* connection type */
{
case conn_file:
if (putc(value,*((FILE **)(conn+8))) == EOF)
return 0;
else
return 1;
case conn_network:
if (send(*(int *)(conn+8),(const char *)str,1,flags) != 1)
return 0;
else
return 1;
case conn_local:
conn[8] = value;
return 1;
default:
assert(0);
return 0;
}
}
#ifdef WIN32
int winsock_dll_found = 0;
#endif
int create_listener_socket(int *socket_handle_addr)
{
#ifdef WIN32
if (!winsock_dll_found)
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2),&wsadata) != 0)
{
return 0;
}
winsock_dll_found = 1;
}
#endif
*socket_handle_addr = socket(PF_INET,SOCK_STREAM,0);
#ifdef WIN32
if (*socket_handle_addr == (int)INVALID_SOCKET)
{
fprintf(stderr, "[VM] Can't create socket. WSAGetLastError() = %d\n", WSAGetLastError());
#else
if (*socket_handle_addr < 0)
{
fprintf(stderr, "[VM] Can't create socket. errno = %d\n", errno);
#endif
return 0;
}
else
{
#if defined (_LINUX_) || (__BEOS__)
int oldflags;
oldflags = fcntl(*socket_handle_addr,F_GETFL,0);
if (oldflags == -1)
{
shutdown(*socket_handle_addr,2);
closesocket(*socket_handle_addr);
return 0;
}
oldflags |= O_NONBLOCK;
fcntl(*socket_handle_addr,F_SETFL,oldflags);
fcntl(*socket_handle_addr,F_SETFD,FD_CLOEXEC); /* needed by the 'must_restart' mecanism */
#endif
#ifdef WIN32
u_long argp = 1;
ioctlsocket(*socket_handle_addr,FIONBIO,&argp);
#endif
return 1;
}
}
int bind_socket_to_port(int socket_handle, U32 ip_addr, U32 ip_port)
{
struct sockaddr_in ip_name;
memset(&ip_name,0,sizeof(struct sockaddr_in));
ip_name.sin_family = AF_INET;
memcpy(&ip_name.sin_addr,&ip_addr,sizeof(long));
ip_name.sin_port = htons((unsigned short)ip_port);
#ifdef WIN32
bool reuse = true;
//setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(bool));
if(setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(bool)))
#else
int one = 1;
if(setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
#endif
{
LOGERROR("Bind socket SO_REUSEADDR error");
}
if (bind(socket_handle,(struct sockaddr *)&ip_name,sizeof(struct sockaddr_in)) < 0)
return 0;
else
return 1;
}
int begin_to_listen(int socket_handle)
{
if (listen(socket_handle,5) < 0)
return 0;
else
return 1;
}
void serialize_float(double d, U8 *dest)
{
*((double *)dest) = d;
}
#define test_dns
U32 call_dns(U32 host_name,U32 seg)
{
struct hostent *r;
//printf("host_name = %d\n",host_name); fflush(stdout);
//printf("(1) seg = %d\n",seg); fflush(stdout);
//printf("calling 'gethostbyname(%s)'\n",((char *)host_name)+4); fflush(stdout);
r = gethostbyname(((char *)host_name)+4); /* avoid counter */
//printf("(2) seg = %d\n",seg); fflush(stdout);
//printf("'gethostbyname' returned r = %p\n",r); fflush(stdout);
if (r == NULL)
{
//printf("r = 0\n"); fflush(stdout);
switch (h_errno)
{
case HOST_NOT_FOUND: ((U8 *)seg)[4] = 0; return seg; /* alt 0 of DNS_Result */
case NO_ADDRESS: ((U8 *)seg)[4] = 1; return seg;
case TRY_AGAIN: ((U8 *)seg)[4] = 2; return seg;
default: ((U8 *)seg)[4] = 3; return seg;
}
}
else
{
//printf("r != 0\n"); fflush(stdout);
//printf("(3) seg = %d\n",seg); fflush(stdout);
//printf("r->h_length = %d\n",r->h_length); fflush(stdout);
//printf("(4) seg = %d\n",seg); fflush(stdout);
if (r->h_length != 4) { printf("dns: IP address is not IPv4.\n"); return 3; }
((U8 *)seg)[4] = 4;
//printf("(5) seg = %d\n",seg); fflush(stdout);
*((U32 *)(((U8 *)seg)+4+1)) = *((U32 *)(r->h_addr));
//printf("(6) seg = %d\n",seg); fflush(stdout);
return seg;
}
}
#define wtfdebug(s)
//#define wtfdebug(s) printf("%s\n",s); fflush(stdout);
int write_to_file(U32 conn, // the connection or file
U8 *text, // pointer to bytes to write
U32 n) // maximal number of bytes to write
/*
returns either the number of bytes writen or
-1 if cannot write (disk file and TCP)
-2 if must wait (TCP only)
*/
{
wtfdebug("entering 'write_to_file'")
switch (((U8 *)conn)[4]) /* connection type */
{
case conn_file:
{
wtfdebug("case conn_file")
int r;
#ifdef WIN32
r = _write(fileno(*((FILE **)(((U8 *)conn)+8))), /* file descriptor */
text, /* address of first byte */
n); /* number of bytes to write */
#else
r = write(fileno(*((FILE **)(((U8 *)conn)+8))), /* file descriptor */
text, /* address of first byte */
n); /* number of bytes to write */
#endif
fflush(*((FILE **)(((U8 *)conn)+8)));
if (r < 0)
{
wtfdebug("exiting 'write_to_file' (1)")
return -1;
}
else
{
wtfdebug("exiting 'write_to_file' (2)")
return r;
}
}
break;
case conn_network:
{
wtfdebug("case conn_network (b)")
int sock = *((U32 *)(((U8 *)conn)+8));
wtfdebug("case conn_network (c)")
int r = 0;
#ifdef WIN32
int flags = 0;
#else
int flags = 0;
#ifndef __APPLE__
flags = MSG_NOSIGNAL;
#endif
#endif
//FD_CLR((unsigned int)sock,&descriptors_waited_for_output);
wtfdebug("calling 'send'")
r = send(sock, /* file descriptor */
(char*)text, /* address of first byte */
n, /* number of bytes to write */
flags);
wtfdebug("returning from 'send'")
#ifdef WIN32
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
FD_SET((unsigned int)sock,&descriptors_waited_for_output);
wtfdebug("exiting 'write_to_file' (3)")
return -2;
}
#endif
#if defined (_LINUX_) || (__BEOS__)
if (r == -1 && (errno == EWOULDBLOCK || errno == EINTR))
{
FD_SET((unsigned int)sock,&descriptors_waited_for_output);
wtfdebug("exiting 'write_to_file' (4)")
return -2;
}
#endif
else if (r >= 0)
{
wtfdebug("exiting 'write_to_file' (5)")
return r;
}
else
{
wtfdebug("exiting 'write_to_file' (6)")
return -1;
}
}
break;
default:
wtfdebug("exiting 'write_to_file' (7)")
return -1;
}
}
int read_from_file(U32 conn, int n, U32 ba)
/*
returns either the number of bytes read, or
-1 if cannot read (TCP/SSL = connection broken)
-2 if must wait (TCP/SSL)
*/
{
#define c ((U8 *)conn)
#define a ((U8 *)ba)
if (n <= 0) return 0;
switch (c[4])
{
case conn_file:
{
int i = 0;
FILE *fp = (*((FILE **)(c+8)));
i = fread(a+4+4,1, n, fp);
// if(i < n)
// {
// if (feof(fp))
// //printf("EOF reached\n");
// else if (ferror(fp))
// printf("errno %d\n",errno);
// }
return i;
}
break;
case conn_network:
{
int i;
int sock = *(int*)(c+8);
FD_CLR(sock,&descriptors_waited_for_input);
/* read n bytes from the connection */
i = recv(sock, (char *)a+4+4,n,0);
#ifdef WIN32
if (i == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
//FD_SET(sock,&descriptors_waited_for_input);
return -2;
}
#endif
#if defined (_LINUX_) || (__BEOS__)
//printf("i = %d n = %d\n",i,n); fflush(stdout);
if (i == -1 && errno == EWOULDBLOCK)
{
//FD_SET(sock,&descriptors_waited_for_input);
//printf(" wait\n"); fflush(stdout);
return -2;
}
#endif
else if (i > 0)
{
assert(i <= n);
//if (mf_using_ssl) store_random(a+4+4,i);
return i;
}
else
{
return -1;
}
}
break;
default:
return 0;
}
#undef c
#undef a
}
int read_from_file_or_tcp(U32 conn, int n, U8 *dest)
/*
returns either the number of bytes read, or
-1 if cannot read (connection closed)
-2 if must wait (TCP)
-3 end of file (end of file)
*/
{
#define c ((U8 *)conn)
#define a ((U8 *)dest)
if (n <= 0) return 0;
switch (c[4])
{
case conn_file:
{
int i = 0;
FILE *fp = (*((FILE **)(c+8)));
i = fread(a,1, n, fp);
if (i <= 0)
{
if (feof(fp))
return -3;
else
return 0;
}
else
return i;
}
break;
case conn_network:
{
int i;
int sock = *(int*)(c+8);
FD_CLR(sock,&descriptors_waited_for_input);
/* read n bytes from the connection */
i = recv(sock, (char *)a,n,0);
#ifdef WIN32
if (i == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
FD_SET(sock,&descriptors_waited_for_input);
return -2;
}
#endif
#if defined (_LINUX_) || (__BEOS__)
//printf("i = %d n = %d\n",i,n); fflush(stdout);
if (i == -1 && errno == EWOULDBLOCK)
{
FD_SET(sock, &descriptors_waited_for_input);
//printf(" wait\n"); fflush(stdout);
return -2;
}
#endif
else if (i > 0)
{
assert(i <= n);
return i;
}
else
{
return -1;
}
}
break;
default:
return 0;
}
#undef c
#undef a
}
int read_line_from_file(U32 conn, int n, U32 string, int *pos)
/*
returns either the line length, or
-1 if cannot read (TCP/SSL = connection broken)
-2 if must wait (TCP/SSL)
-3 if EOF is reached
*/
{
#define c ((U8 *)conn)
#define a ((U8 *)string)
if (n <= 0) return 0;
switch (c[4])
{
case conn_file:
{
//int i = *pos;
FILE *fp = (*((FILE **)(c+8)));
if(fgets((char*)a+4, n, fp))
{
char * p = (char*)a+4;
size_t len = strlen(p);
// while(len > 0 && (p[len -1] == '\n' || p[len -1] == '\r'))
// {
// len--;
// p[len] = '\0';
// }
return len;
}
else if(feof(fp))
{
*((char *)a+4) = '\0';
return -3;
}
else
return -1;
}
break;
case conn_network:
{
int ret = 0;
int sock = *(int*)(c+8);
int i = *pos;
char* buf = (char *)a+4;
char ch = '\0';
FD_CLR(sock,&descriptors_waited_for_input);
/* read n bytes from the connection */
while(i < n)
{
ret = recv(sock, &ch, 1, 0);
#ifdef WIN32
if (ret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
#endif
#if defined (_LINUX_) || (__BEOS__)
if (ret == -1 && errno == EWOULDBLOCK)
#endif
{
FD_SET(sock, &descriptors_waited_for_input);
*pos = i;
return -2;
}
else if (ret > 0)
{
assert(ret == 1);
*(buf + i) = ch;
i++;
if(ch == '\n')
break;
}
else
{
return -1;
}
}
*(buf + i) = '\0';
return i;
}
break;
default:
return 0;
}
#undef c
#undef a
}
U32 compute_file_size(U32 conn, AnubisAllocator *allocator)
{
#define c ((U8 *)conn)
int result;
switch (c[4])
{
case conn_file:
{
FILE *fp;
//long int pos;
struct stat st;
fp = *((FILE **)(c+8));
result = fstat(fileno(fp),&st);
if (result == 0)
{
return C_int64_to_Anubis_Int(st.st_size, allocator);
}
else
{
return 0;
}
}
break;
default: return 0;
}
#undef c
}
// U32 compute_file_size(U32 conn, AnubisAllocator *allocator)
// {
//#define c ((U8 *)conn)
// int result;
//
// switch (c[4])
// {
// case conn_file:
// {
// FILE *fp;
// //long int pos;
// struct stat st;
// fp = *((FILE **)(c+8));
//
//#ifdef WIN32
// int64 size = _filelengthi64(fileno(fp));
// return C_int64_to_Anubis_Int(size, allocator); //(U32)size;
//#else
// result = fstat(fileno(fp),&st);
//#endif
// if (result == 0)
// {
// return (U32)(st.st_size);
// }
// else
// {
// return 0;
// }
//
//#if 0
// pos = ftell(fp); /* remember current position */
// fseek(fp,0,SEEK_END); /* go to end of file */
// result = (U32)ftell(fp); /* get position, i.e. size of file */
// rewind(fp);
// fseek(fp,pos,SEEK_SET); /* return to initial position */
// return result;
//#endif
//
// }
// break;
//
// default: return 0;
// }
//#undef c
// }
/* convert an Unix file mode into an Anubis file mode (see predef.anubis)
taken from predef.anubis:
public type ReadMode:
non_readable, // -
readable. // r
public type WriteMode:
non_writable, // -
writable. // w
public type ExecMode:
non_executable, // -
executable. // x
public type PrivilegedExecMode:
non_executable, // -
executable, // x
may_change_id_no_exec, // S undocumented (?) Unix: means suid (guid) bit set but not executable
may_change_id, // s
public type FileMode: // corresponding UNIX permission
file(ReadMode user_readable, // r--------
WriteMode user_writable, // -w-------
PrivilegedExecMode user_executable, // --x------ --s------ --S------
ReadMode group_readable, // ---r-----
WriteMode group_writable, // ----w----
PrivilegedExecMode group_executable, // -----x--- -----s--- -----S---
ReadMode others_readable, // ------r--
WriteMode others_writable, // -------w-
ExecMode others_executable). // --------x
public type SearchMode:
non_searchable,
searchable.
public type DirectoryMode:
directory(ReadMode user_readable,
WriteMode user_writable,
SearchMode user_searchable,
ReadMode group_readable,
WriteMode group_writable,
SearchMode group_searchable,
ReadMode others_readable,
WriteMode others_writable,
SearchMode others_searchable).
*/
/* no need in WIN32 since we compile under mingw
#define S_IRUSR _S_IREAD
#define S_IWUSR _S_IWRITE
#define S_IXUSR _S_IEXEC
*/
#if defined (WIN32)
#define S_ISUID 0
//#define S_IRGRP _S_IREAD
//#define S_IWGRP 0
//#define S_IXGRP 0
#define S_ISGID 0
//#define S_IROTH _S_IREAD
//#define S_IWOTH 0
//#define S_IXOTH 0
#endif
U16 make_file_mode(mode_t unix_mode)
{
U16 result = 0;
if (unix_mode&S_IRUSR) result |= (1<<0);
if (unix_mode&S_IWUSR) result |= (1<<1);
if (unix_mode&S_IXUSR) result |= (1<<2);
if (unix_mode&S_ISUID) result |= (1<<3);
if (unix_mode&S_IRGRP) result |= (1<<4);
if (unix_mode&S_IWGRP) result |= (1<<5);
if (unix_mode&S_IXGRP) result |= (1<<6);
if (unix_mode&S_ISGID) result |= (1<<7);
if (unix_mode&S_IROTH) result |= (1<<8);
if (unix_mode&S_IWOTH) result |= (1<<9);
if (unix_mode&S_IXOTH) result |= (1<<10);
return result;
}
U16 make_dir_mode(mode_t unix_mode)
{
U16 result = 0;
if (unix_mode&S_IRUSR) result |= (1<<0);
if (unix_mode&S_IWUSR) result |= (1<<1);
if (unix_mode&S_IXUSR) result |= (1<<2);
if (unix_mode&S_IRGRP) result |= (1<<3);
if (unix_mode&S_IWGRP) result |= (1<<4);
if (unix_mode&S_IXGRP) result |= (1<<5);
if (unix_mode&S_IROTH) result |= (1<<6);
if (unix_mode&S_IWOTH) result |= (1<<7);
if (unix_mode&S_IXOTH) result |= (1<<8);
return result;
}
/* transforming an ANUBIS directory mode into an UNIX mode */
#if defined (_LINUX_) || (__BEOS__)
U32 anubis_directory_mode_to_UNIX(U32 amode)
{
U32 result = 0;
if (amode&1) result |= S_IRUSR; /* 1 = user readable */
if (amode&2) result |= S_IWUSR; /* 1 = user writable */
if (amode&4) result |= S_IXUSR; /* 1 = user searchable */
if (amode&8) result |= S_IRGRP; /* 1 = group readable */
if (amode&16) result |= S_IWGRP; /* 1 = group writable */
if (amode&32) result |= S_IXGRP; /* 1 = group searchable */
if (amode&64) result |= S_IROTH; /* 1 = others readable */
if (amode&128) result |= S_IWOTH; /* 1 = others writable */
if (amode&256) result |= S_IXOTH; /* 1 = others searchable */
return result;
}
#endif
U32 /* returns a result of type 'MakeDirectoryResult' (see predef.anubis):
permission_denied 0
name_already_exists 1
too_many_links 2
not_enough_room 3
read_only_file_system 4
ok 5
*/
make_directory(char *path, U32 amode)
{
#if defined (_LINUX_) || (__BEOS__)
if (mkdir(path,anubis_directory_mode_to_UNIX(amode)))
switch(errno)
{
case EEXIST: return 1;
case EMLINK: return 2;
case ENOSPC: return 3;
case EROFS: return 4;
default: return 0;
}
else
return 5;
#endif
#ifdef WIN32
if (mkdir(path))
switch(errno)
{
case EEXIST: return 1;
default: return 0;
}
else
return 5;
#endif
}
// #if defined (_LINUX_) || (__BEOS__)
U32 /* returns a result of type 'RemoveDirectoryResult' (see predef.anubis):
directory_does_not_exist 0
permission_denied 1
read_only_file_system 2
directory_not_empty 3
ok 4
*/
remove_directory(char *path)
{
if (rmdir(path))
switch(errno)
{
case EPERM: return 1;
case EROFS: return 2;
case ENOTEMPTY: return 3;
default: return 0;
}
else return 4; /* ok */
}
// #endif
// #ifdef WIN32
// U32 remove_directory(char *path)
// {
// if (rmdir(path))
// {
//
// }
// return 1;
// }
// #endif