File: syswrap-main.c

package info (click to toggle)
valgrind 1%3A3.14.0-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 156,980 kB
  • sloc: ansic: 728,128; exp: 26,134; xml: 22,268; cpp: 7,638; asm: 7,312; makefile: 6,102; perl: 5,910; sh: 5,717
file content (2842 lines) | stat: -rw-r--r-- 106,501 bytes parent folder | download
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
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
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

/*--------------------------------------------------------------------*/
/*--- Handle system calls.                          syswrap-main.c ---*/
/*--------------------------------------------------------------------*/

/*
   This file is part of Valgrind, a dynamic binary instrumentation
   framework.

   Copyright (C) 2000-2017 Julian Seward 
      jseward@acm.org

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307, USA.

   The GNU General Public License is contained in the file COPYING.
*/

#include "libvex_guest_offsets.h"
#include "libvex_trc_values.h"
#include "pub_core_basics.h"
#include "pub_core_aspacemgr.h"
#include "pub_core_vki.h"
#include "pub_core_vkiscnums.h"
#include "pub_core_threadstate.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcassert.h"
#include "pub_core_libcprint.h"
#include "pub_core_libcproc.h"      // For VG_(getpid)()
#include "pub_core_libcsignal.h"
#include "pub_core_scheduler.h"     // For VG_({acquire,release}_BigLock),
                                    //   and VG_(vg_yield)
#include "pub_core_stacktrace.h"    // For VG_(get_and_pp_StackTrace)()
#include "pub_core_tooliface.h"
#include "pub_core_options.h"
#include "pub_core_signals.h"       // For VG_SIGVGKILL, VG_(poll_signals)
#include "pub_core_syscall.h"
#include "pub_core_machine.h"
#include "pub_core_mallocfree.h"
#include "pub_core_syswrap.h"
#include "pub_core_gdbserver.h"     // VG_(gdbserver_report_syscall)

#include "priv_types_n_macros.h"
#include "priv_syswrap-main.h"

#if defined(VGO_darwin)
#include "priv_syswrap-darwin.h"
#endif

/* Useful info which needs to be recorded somewhere:
   Use of registers in syscalls is:

          NUM   ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 RESULT
   LINUX:
   x86    eax   ebx  ecx  edx  esi  edi  ebp  n/a  n/a  eax       (== NUM)
   amd64  rax   rdi  rsi  rdx  r10  r8   r9   n/a  n/a  rax       (== NUM)
   ppc32  r0    r3   r4   r5   r6   r7   r8   n/a  n/a  r3+CR0.SO (== ARG1)
   ppc64  r0    r3   r4   r5   r6   r7   r8   n/a  n/a  r3+CR0.SO (== ARG1)
   arm    r7    r0   r1   r2   r3   r4   r5   n/a  n/a  r0        (== ARG1)
   mips32 v0    a0   a1   a2   a3 stack stack n/a  n/a  v0        (== NUM)
   mips64 v0    a0   a1   a2   a3   a4   a5   a6   a7   v0        (== NUM)
   arm64  x8    x0   x1   x2   x3   x4   x5   n/a  n/a  x0 ??     (== ARG1??)

   On s390x the svc instruction is used for system calls. The system call
   number is encoded in the instruction (8 bit immediate field). Since Linux
   2.6 it is also allowed to use svc 0 with the system call number in r1.
   This was introduced for system calls >255, but works for all. It is
   also possible to see the svc 0 together with an EXecute instruction, that
   fills in the immediate field.
   s390x r1/SVC r2   r3   r4   r5   r6   r7   n/a  n/a  r2        (== ARG1)

          NUM   ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 RESULT
   DARWIN:
   x86    eax   +4   +8   +12  +16  +20  +24  +28  +32  edx:eax, eflags.c
   amd64  rax   rdi  rsi  rdx  rcx  r8   r9   +8   +16  rdx:rax, rflags.c

   For x86-darwin, "+N" denotes "in memory at N(%esp)"; ditto
   amd64-darwin.  Apparently 0(%esp) is some kind of return address
   (perhaps for syscalls done with "sysenter"?)  I don't think it is
   relevant for syscalls done with "int $0x80/1/2".

   SOLARIS:
   x86    eax +4   +8   +12  +16  +20  +24  +28  +32  edx:eax, eflags.c
   amd64  rax rdi  rsi  rdx  r10  r8   r9   +8   +16  rdx:rax, rflags.c

   "+N" denotes "in memory at N(%esp)". Solaris also supports fasttrap
   syscalls. Fasttraps do not take any parameters (except of the sysno in eax)
   and never fail (if the sysno is valid).
*/

/* This is the top level of the system-call handler module.  All
   system calls are channelled through here, doing two things:

   * notify the tool of the events (mem/reg reads, writes) happening

   * perform the syscall, usually by passing it along to the kernel
     unmodified.

   A magical piece of assembly code, do_syscall_for_client_WRK, in
   syscall-$PLATFORM.S does the tricky bit of passing a syscall to the
   kernel, whilst having the simulator retain control.
*/

/* The main function is VG_(client_syscall).  The simulation calls it
   whenever a client thread wants to do a syscall.  The following is a
   sketch of what it does.

   * Ensures the root thread's stack is suitably mapped.  Tedious and
     arcane.  See big big comment in VG_(client_syscall).

   * First, it rounds up the syscall number and args (which is a
     platform dependent activity) and puts them in a struct ("args")
     and also a copy in "orig_args".

     The pre/post wrappers refer to these structs and so no longer
     need magic macros to access any specific registers.  This struct
     is stored in thread-specific storage.


   * The pre-wrapper is called, passing it a pointer to struct
     "args".


   * The pre-wrapper examines the args and pokes the tool
     appropriately.  It may modify the args; this is why "orig_args"
     is also stored.

     The pre-wrapper may choose to 'do' the syscall itself, and
     concludes one of three outcomes:

       Success(N)    -- syscall is already complete, with success;
                        result is N

       Fail(N)       -- syscall is already complete, with failure;
                        error code is N

       HandToKernel  -- (the usual case): this needs to be given to
                        the kernel to be done, using the values in
                        the possibly-modified "args" struct.

     In addition, the pre-wrapper may set some flags:

       MayBlock   -- only applicable when outcome==HandToKernel

       PostOnFail -- only applicable when outcome==HandToKernel or Fail


   * If the pre-outcome is HandToKernel, the syscall is duly handed
     off to the kernel (perhaps involving some thread switchery, but
     that's not important).  This reduces the possible set of outcomes
     to either Success(N) or Fail(N).


   * The outcome (Success(N) or Fail(N)) is written back to the guest
     register(s).  This is platform specific:

     x86:    Success(N) ==>  eax = N
             Fail(N)    ==>  eax = -N

     ditto amd64

     ppc32:  Success(N) ==>  r3 = N, CR0.SO = 0
             Fail(N) ==>     r3 = N, CR0.SO = 1

     Darwin:
     x86:    Success(N) ==>  edx:eax = N, cc = 0
             Fail(N)    ==>  edx:eax = N, cc = 1

     s390x:  Success(N) ==>  r2 = N
             Fail(N)    ==>  r2 = -N

     Solaris:
     x86:    Success(N) ==>  edx:eax = N, cc = 0
             Fail(N)    ==>      eax = N, cc = 1
     Same applies for fasttraps except they never fail.

   * The post wrapper is called if:

     - it exists, and
     - outcome==Success or (outcome==Fail and PostOnFail is set)

     The post wrapper is passed the adulterated syscall args (struct
     "args"), and the syscall outcome (viz, Success(N) or Fail(N)).

   There are several other complications, primarily to do with
   syscalls getting interrupted, explained in comments in the code.
*/

/* CAVEATS for writing wrappers.  It is important to follow these!

   The macros defined in priv_types_n_macros.h are designed to help
   decouple the wrapper logic from the actual representation of
   syscall args/results, since these wrappers are designed to work on
   multiple platforms.

   Sometimes a PRE wrapper will complete the syscall itself, without
   handing it to the kernel.  It will use one of SET_STATUS_Success,
   SET_STATUS_Failure or SET_STATUS_from_SysRes to set the return
   value.  It is critical to appreciate that use of the macro does not
   immediately cause the underlying guest state to be updated -- that
   is done by the driver logic in this file, when the wrapper returns.

   As a result, PRE wrappers of the following form will malfunction:

   PRE(fooble) 
   {
      ... do stuff ...
      SET_STATUS_Somehow(...)

      // do something that assumes guest state is up to date
   }

   In particular, direct or indirect calls to VG_(poll_signals) after
   setting STATUS can cause the guest state to be read (in order to
   build signal frames).  Do not do this.  If you want a signal poll
   after the syscall goes through, do "*flags |= SfPollAfter" and the
   driver logic will do it for you.

   -----------

   Another critical requirement following introduction of new address
   space manager (JRS, 20050923):

   In a situation where the mappedness of memory has changed, aspacem
   should be notified BEFORE the tool.  Hence the following is
   correct:

      Bool d = VG_(am_notify_munmap)(s->start, s->end+1 - s->start);
      VG_TRACK( die_mem_munmap, s->start, s->end+1 - s->start );
      if (d)
         VG_(discard_translations)(s->start, s->end+1 - s->start);

   whilst this is wrong:

      VG_TRACK( die_mem_munmap, s->start, s->end+1 - s->start );
      Bool d = VG_(am_notify_munmap)(s->start, s->end+1 - s->start);
      if (d)
         VG_(discard_translations)(s->start, s->end+1 - s->start);

   The reason is that the tool may itself ask aspacem for more shadow
   memory as a result of the VG_TRACK call.  In such a situation it is
   critical that aspacem's segment array is up to date -- hence the
   need to notify aspacem first.

   -----------

   Also .. take care to call VG_(discard_translations) whenever
   memory with execute permissions is unmapped.
*/


/* ---------------------------------------------------------------------
   Do potentially blocking syscall for the client, and mess with 
   signal masks at the same time. 
   ------------------------------------------------------------------ */

/* Perform a syscall on behalf of a client thread, using a specific
   signal mask.  On completion, the signal mask is set to restore_mask
   (which presumably blocks almost everything).  If a signal happens
   during the syscall, the handler should call
   VG_(fixup_guest_state_after_syscall_interrupted) to adjust the
   thread's context to do the right thing.

   The _WRK function is handwritten assembly, implemented per-platform
   in coregrind/m_syswrap/syscall-$PLAT.S.  It has some very magic
   properties.  See comments at the top of
   VG_(fixup_guest_state_after_syscall_interrupted) below for details.

   This function (these functions) are required to return zero in case
   of success (even if the syscall itself failed), and nonzero if the
   sigprocmask-swizzling calls failed.  We don't actually care about
   the failure values from sigprocmask, although most of the assembly
   implementations do attempt to return that, using the convention
   0 for success, or 0x8000 | error-code for failure.
*/
#if defined(VGO_linux)
extern
UWord ML_(do_syscall_for_client_WRK)( Word syscallno, 
                                      void* guest_state,
                                      const vki_sigset_t *syscall_mask,
                                      const vki_sigset_t *restore_mask,
                                      Word sigsetSzB );
#elif defined(VGO_darwin)
extern
UWord ML_(do_syscall_for_client_unix_WRK)( Word syscallno, 
                                           void* guest_state,
                                           const vki_sigset_t *syscall_mask,
                                           const vki_sigset_t *restore_mask,
                                           Word sigsetSzB ); /* unused */
extern
UWord ML_(do_syscall_for_client_mach_WRK)( Word syscallno, 
                                           void* guest_state,
                                           const vki_sigset_t *syscall_mask,
                                           const vki_sigset_t *restore_mask,
                                           Word sigsetSzB ); /* unused */
extern
UWord ML_(do_syscall_for_client_mdep_WRK)( Word syscallno, 
                                           void* guest_state,
                                           const vki_sigset_t *syscall_mask,
                                           const vki_sigset_t *restore_mask,
                                           Word sigsetSzB ); /* unused */
#elif defined(VGO_solaris)
extern
UWord ML_(do_syscall_for_client_WRK)( Word syscallno,
                                      void* guest_state,
                                      const vki_sigset_t *syscall_mask,
                                      const vki_sigset_t *restore_mask,
                                      UChar *cflag);
UWord ML_(do_syscall_for_client_dret_WRK)( Word syscallno,
                                           void* guest_state,
                                           const vki_sigset_t *syscall_mask,
                                           const vki_sigset_t *restore_mask,
                                           UChar *cflag);
#else
#  error "Unknown OS"
#endif


static
void do_syscall_for_client ( Int syscallno,
                             ThreadState* tst,
                             const vki_sigset_t* syscall_mask )
{
   vki_sigset_t saved;
   UWord err;
#  if defined(VGO_linux)
   err = ML_(do_syscall_for_client_WRK)(
            syscallno, &tst->arch.vex, 
            syscall_mask, &saved, sizeof(vki_sigset_t)
         );
#  elif defined(VGO_darwin)
   switch (VG_DARWIN_SYSNO_CLASS(syscallno)) {
      case VG_DARWIN_SYSCALL_CLASS_UNIX:
         err = ML_(do_syscall_for_client_unix_WRK)(
                  VG_DARWIN_SYSNO_FOR_KERNEL(syscallno), &tst->arch.vex, 
                  syscall_mask, &saved, 0/*unused:sigsetSzB*/
               );
         break;
      case VG_DARWIN_SYSCALL_CLASS_MACH:
         err = ML_(do_syscall_for_client_mach_WRK)(
                  VG_DARWIN_SYSNO_FOR_KERNEL(syscallno), &tst->arch.vex, 
                  syscall_mask, &saved, 0/*unused:sigsetSzB*/
               );
         break;
      case VG_DARWIN_SYSCALL_CLASS_MDEP:
         err = ML_(do_syscall_for_client_mdep_WRK)(
                  VG_DARWIN_SYSNO_FOR_KERNEL(syscallno), &tst->arch.vex, 
                  syscall_mask, &saved, 0/*unused:sigsetSzB*/
               );
         break;
      default:
         vg_assert(0);
         /*NOTREACHED*/
         break;
   }
#  elif defined(VGO_solaris)
   UChar cflag;

   /* Fasttraps or anything else cannot go through this path. */
   vg_assert(VG_SOLARIS_SYSNO_CLASS(syscallno)
             == VG_SOLARIS_SYSCALL_CLASS_CLASSIC);

   /* If the syscall is a door_return call then it has to be handled very
      differently. */
   if (tst->os_state.in_door_return)
      err = ML_(do_syscall_for_client_dret_WRK)(
                syscallno, &tst->arch.vex,
                syscall_mask, &saved, &cflag
            );
   else
      err = ML_(do_syscall_for_client_WRK)(
                syscallno, &tst->arch.vex,
                syscall_mask, &saved, &cflag
            );

   /* Save the carry flag. */
#  if defined(VGP_x86_solaris)
   LibVEX_GuestX86_put_eflag_c(cflag, &tst->arch.vex);
#  elif defined(VGP_amd64_solaris)
   LibVEX_GuestAMD64_put_rflag_c(cflag, &tst->arch.vex);
#  else
#    error "Unknown platform"
#  endif

#  else
#    error "Unknown OS"
#  endif
   vg_assert2(
      err == 0,
      "ML_(do_syscall_for_client_WRK): sigprocmask error %lu",
      err & 0xFFF
   );
}


/* ---------------------------------------------------------------------
   Impedance matchers and misc helpers
   ------------------------------------------------------------------ */

static
Bool eq_SyscallArgs ( SyscallArgs* a1, SyscallArgs* a2 )
{
   return a1->sysno == a2->sysno
          && a1->arg1 == a2->arg1
          && a1->arg2 == a2->arg2
          && a1->arg3 == a2->arg3
          && a1->arg4 == a2->arg4
          && a1->arg5 == a2->arg5
          && a1->arg6 == a2->arg6
          && a1->arg7 == a2->arg7
          && a1->arg8 == a2->arg8;
}

static
Bool eq_SyscallStatus ( UInt sysno, SyscallStatus* s1, SyscallStatus* s2 )
{
   /* was: return s1->what == s2->what && sr_EQ( s1->sres, s2->sres ); */
   if (s1->what == s2->what && sr_EQ( sysno, s1->sres, s2->sres ))
      return True;
#  if defined(VGO_darwin)
   /* Darwin-specific debugging guff */
   vg_assert(s1->what == s2->what);
   VG_(printf)("eq_SyscallStatus:\n");
   VG_(printf)("  {%lu %lu %u}\n", s1->sres._wLO, s1->sres._wHI, s1->sres._mode);
   VG_(printf)("  {%lu %lu %u}\n", s2->sres._wLO, s2->sres._wHI, s2->sres._mode);
   vg_assert(0);
#  endif
   return False;
}

/* Convert between SysRes and SyscallStatus, to the extent possible. */

static
SyscallStatus convert_SysRes_to_SyscallStatus ( SysRes res )
{
   SyscallStatus status;
   status.what = SsComplete;
   status.sres = res;
   return status;
}


/* Impedance matchers.  These convert syscall arg or result data from
   the platform-specific in-guest-state format to the canonical
   formats, and back. */

static 
void getSyscallArgsFromGuestState ( /*OUT*/SyscallArgs*       canonical,
                                    /*IN*/ VexGuestArchState* gst_vanilla, 
                                    /*IN*/ UInt trc )
{
#if defined(VGP_x86_linux)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   canonical->sysno = gst->guest_EAX;
   canonical->arg1  = gst->guest_EBX;
   canonical->arg2  = gst->guest_ECX;
   canonical->arg3  = gst->guest_EDX;
   canonical->arg4  = gst->guest_ESI;
   canonical->arg5  = gst->guest_EDI;
   canonical->arg6  = gst->guest_EBP;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_amd64_linux)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   canonical->sysno = gst->guest_RAX;
   canonical->arg1  = gst->guest_RDI;
   canonical->arg2  = gst->guest_RSI;
   canonical->arg3  = gst->guest_RDX;
   canonical->arg4  = gst->guest_R10;
   canonical->arg5  = gst->guest_R8;
   canonical->arg6  = gst->guest_R9;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_ppc32_linux)
   VexGuestPPC32State* gst = (VexGuestPPC32State*)gst_vanilla;
   canonical->sysno = gst->guest_GPR0;
   canonical->arg1  = gst->guest_GPR3;
   canonical->arg2  = gst->guest_GPR4;
   canonical->arg3  = gst->guest_GPR5;
   canonical->arg4  = gst->guest_GPR6;
   canonical->arg5  = gst->guest_GPR7;
   canonical->arg6  = gst->guest_GPR8;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
   VexGuestPPC64State* gst = (VexGuestPPC64State*)gst_vanilla;
   canonical->sysno = gst->guest_GPR0;
   canonical->arg1  = gst->guest_GPR3;
   canonical->arg2  = gst->guest_GPR4;
   canonical->arg3  = gst->guest_GPR5;
   canonical->arg4  = gst->guest_GPR6;
   canonical->arg5  = gst->guest_GPR7;
   canonical->arg6  = gst->guest_GPR8;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_arm_linux)
   VexGuestARMState* gst = (VexGuestARMState*)gst_vanilla;
   canonical->sysno = gst->guest_R7;
   canonical->arg1  = gst->guest_R0;
   canonical->arg2  = gst->guest_R1;
   canonical->arg3  = gst->guest_R2;
   canonical->arg4  = gst->guest_R3;
   canonical->arg5  = gst->guest_R4;
   canonical->arg6  = gst->guest_R5;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_arm64_linux)
   VexGuestARM64State* gst = (VexGuestARM64State*)gst_vanilla;
   canonical->sysno = gst->guest_X8;
   canonical->arg1  = gst->guest_X0;
   canonical->arg2  = gst->guest_X1;
   canonical->arg3  = gst->guest_X2;
   canonical->arg4  = gst->guest_X3;
   canonical->arg5  = gst->guest_X4;
   canonical->arg6  = gst->guest_X5;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_mips32_linux)
   VexGuestMIPS32State* gst = (VexGuestMIPS32State*)gst_vanilla;
   canonical->sysno = gst->guest_r2;    // v0
   if (canonical->sysno == __NR_exit) {
      canonical->arg1 = gst->guest_r4;    // a0
      canonical->arg2 = 0;
      canonical->arg3 = 0;
      canonical->arg4 = 0;
      canonical->arg5 = 0;
      canonical->arg6 = 0;
      canonical->arg8 = 0;
   } else if (canonical->sysno != __NR_syscall) {
      canonical->arg1  = gst->guest_r4;    // a0
      canonical->arg2  = gst->guest_r5;    // a1
      canonical->arg3  = gst->guest_r6;    // a2
      canonical->arg4  = gst->guest_r7;    // a3
      canonical->arg5  = *((UInt*) (gst->guest_r29 + 16));    // 16(guest_SP)
      canonical->arg6  = *((UInt*) (gst->guest_r29 + 20));    // 20(guest_SP)
      canonical->arg7  = *((UInt*) (gst->guest_r29 + 24));    // 24(guest_SP)
      canonical->arg8 = 0;
   } else {
      // Fixme hack handle syscall()
      canonical->sysno = gst->guest_r4;    // a0
      canonical->arg1  = gst->guest_r5;    // a1
      canonical->arg2  = gst->guest_r6;    // a2
      canonical->arg3  = gst->guest_r7;    // a3
      canonical->arg4  = *((UInt*) (gst->guest_r29 + 16));    // 16(guest_SP/sp)
      canonical->arg5  = *((UInt*) (gst->guest_r29 + 20));    // 20(guest_SP/sp)
      canonical->arg6  = *((UInt*) (gst->guest_r29 + 24));    // 24(guest_SP/sp)
      canonical->arg8 = __NR_syscall;
   }

#elif defined(VGP_mips64_linux)
   VexGuestMIPS64State* gst = (VexGuestMIPS64State*)gst_vanilla;
   canonical->sysno = gst->guest_r2;    // v0
   canonical->arg1  = gst->guest_r4;    // a0
   canonical->arg2  = gst->guest_r5;    // a1
   canonical->arg3  = gst->guest_r6;    // a2
   canonical->arg4  = gst->guest_r7;    // a3
   canonical->arg5  = gst->guest_r8;    // a4
   canonical->arg6  = gst->guest_r9;    // a5

#elif defined(VGP_x86_darwin)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_ESP;
   // GrP fixme hope syscalls aren't called with really shallow stacks...
   canonical->sysno = gst->guest_EAX;
   if (canonical->sysno != 0) {
      // stack[0] is return address
      canonical->arg1  = stack[1];
      canonical->arg2  = stack[2];
      canonical->arg3  = stack[3];
      canonical->arg4  = stack[4];
      canonical->arg5  = stack[5];
      canonical->arg6  = stack[6];
      canonical->arg7  = stack[7];
      canonical->arg8  = stack[8];
   } else {
      // GrP fixme hack handle syscall()
      // GrP fixme what about __syscall() ?
      // stack[0] is return address
      // DDD: the tool can't see that the params have been shifted!  Can
      //      lead to incorrect checking, I think, because the PRRAn/PSARn
      //      macros will mention the pre-shifted args.
      canonical->sysno = stack[1];
      vg_assert(canonical->sysno != 0);
      canonical->arg1  = stack[2];
      canonical->arg2  = stack[3];
      canonical->arg3  = stack[4];
      canonical->arg4  = stack[5];
      canonical->arg5  = stack[6];
      canonical->arg6  = stack[7];
      canonical->arg7  = stack[8];
      canonical->arg8  = stack[9];
      
      PRINT("SYSCALL[%d,?](0) syscall(%s, ...); please stand by...\n",
            VG_(getpid)(), /*tid,*/
            VG_SYSNUM_STRING(canonical->sysno));
   }

   // Here we determine what kind of syscall it was by looking at the
   // interrupt kind, and then encode the syscall number using the 64-bit
   // encoding for Valgrind's internal use.
   //
   // DDD: Would it be better to stash the JMP kind into the Darwin
   // thread state rather than passing in the trc?
   switch (trc) {
   case VEX_TRC_JMP_SYS_INT128:
      // int $0x80 = Unix, 64-bit result
      vg_assert(canonical->sysno >= 0);
      canonical->sysno = VG_DARWIN_SYSCALL_CONSTRUCT_UNIX(canonical->sysno);
      break;
   case VEX_TRC_JMP_SYS_SYSENTER:
      // syscall = Unix, 32-bit result
      // OR        Mach, 32-bit result
      if (canonical->sysno >= 0) {
         // GrP fixme hack:  0xffff == I386_SYSCALL_NUMBER_MASK
         canonical->sysno = VG_DARWIN_SYSCALL_CONSTRUCT_UNIX(canonical->sysno
                                                             & 0xffff);
      } else {
         canonical->sysno = VG_DARWIN_SYSCALL_CONSTRUCT_MACH(-canonical->sysno);
      }
      break;
   case VEX_TRC_JMP_SYS_INT129:
      // int $0x81 = Mach, 32-bit result
      vg_assert(canonical->sysno < 0);
      canonical->sysno = VG_DARWIN_SYSCALL_CONSTRUCT_MACH(-canonical->sysno);
      break;
   case VEX_TRC_JMP_SYS_INT130:
      // int $0x82 = mdep, 32-bit result
      vg_assert(canonical->sysno >= 0);
      canonical->sysno = VG_DARWIN_SYSCALL_CONSTRUCT_MDEP(canonical->sysno);
      break;
   default: 
      vg_assert(0);
      break;
   }
   
#elif defined(VGP_amd64_darwin)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_RSP;

   vg_assert(trc == VEX_TRC_JMP_SYS_SYSCALL);

   // GrP fixme hope syscalls aren't called with really shallow stacks...
   canonical->sysno = gst->guest_RAX;
   if (canonical->sysno != __NR_syscall) {
      // stack[0] is return address
      canonical->arg1  = gst->guest_RDI;
      canonical->arg2  = gst->guest_RSI;
      canonical->arg3  = gst->guest_RDX;
      canonical->arg4  = gst->guest_R10;  // not rcx with syscall insn
      canonical->arg5  = gst->guest_R8;
      canonical->arg6  = gst->guest_R9;
      canonical->arg7  = stack[1];
      canonical->arg8  = stack[2];
   } else {
      // GrP fixme hack handle syscall()
      // GrP fixme what about __syscall() ?
      // stack[0] is return address
      // DDD: the tool can't see that the params have been shifted!  Can
      //      lead to incorrect checking, I think, because the PRRAn/PSARn
      //      macros will mention the pre-shifted args.
      canonical->sysno = VG_DARWIN_SYSCALL_CONSTRUCT_UNIX(gst->guest_RDI);
      vg_assert(canonical->sysno != __NR_syscall);
      canonical->arg1  = gst->guest_RSI;
      canonical->arg2  = gst->guest_RDX;
      canonical->arg3  = gst->guest_R10;  // not rcx with syscall insn
      canonical->arg4  = gst->guest_R8;
      canonical->arg5  = gst->guest_R9;
      canonical->arg6  = stack[1];
      canonical->arg7  = stack[2];
      canonical->arg8  = stack[3];
      
      PRINT("SYSCALL[%d,?](0) syscall(%s, ...); please stand by...\n",
            VG_(getpid)(), /*tid,*/
            VG_SYSNUM_STRING(canonical->sysno));
   }

   // no canonical->sysno adjustment needed

#elif defined(VGP_s390x_linux)
   VexGuestS390XState* gst = (VexGuestS390XState*)gst_vanilla;
   canonical->sysno = gst->guest_SYSNO;
   canonical->arg1  = gst->guest_r2;
   canonical->arg2  = gst->guest_r3;
   canonical->arg3  = gst->guest_r4;
   canonical->arg4  = gst->guest_r5;
   canonical->arg5  = gst->guest_r6;
   canonical->arg6  = gst->guest_r7;
   canonical->arg7  = 0;
   canonical->arg8  = 0;

#elif defined(VGP_x86_solaris)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_ESP;
   canonical->sysno = gst->guest_EAX;
   /* stack[0] is a return address. */
   canonical->arg1  = stack[1];
   canonical->arg2  = stack[2];
   canonical->arg3  = stack[3];
   canonical->arg4  = stack[4];
   canonical->arg5  = stack[5];
   canonical->arg6  = stack[6];
   canonical->arg7  = stack[7];
   canonical->arg8  = stack[8];

   switch (trc) {
   case VEX_TRC_JMP_SYS_INT145:
   case VEX_TRC_JMP_SYS_SYSENTER:
   case VEX_TRC_JMP_SYS_SYSCALL:
   /* These three are not actually valid syscall instructions on Solaris.
      Pretend for now that we handle them as normal syscalls. */
   case VEX_TRC_JMP_SYS_INT128:
   case VEX_TRC_JMP_SYS_INT129:
   case VEX_TRC_JMP_SYS_INT130:
      /* int $0x91, sysenter, syscall = normal syscall */
      break;
   case VEX_TRC_JMP_SYS_INT210:
      /* int $0xD2 = fasttrap */
      canonical->sysno
         = VG_SOLARIS_SYSCALL_CONSTRUCT_FASTTRAP(canonical->sysno);
      break;
   default:
      vg_assert(0);
      break;
   }

#elif defined(VGP_amd64_solaris)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_RSP;
   canonical->sysno = gst->guest_RAX;
   /* stack[0] is a return address. */
   canonical->arg1 = gst->guest_RDI;
   canonical->arg2 = gst->guest_RSI;
   canonical->arg3 = gst->guest_RDX;
   canonical->arg4 = gst->guest_R10;  /* Not RCX with syscall. */
   canonical->arg5 = gst->guest_R8;
   canonical->arg6 = gst->guest_R9;
   canonical->arg7 = stack[1];
   canonical->arg8 = stack[2];

   switch (trc) {
   case VEX_TRC_JMP_SYS_SYSCALL:
      /* syscall = normal syscall */
      break;
   case VEX_TRC_JMP_SYS_INT210:
      /* int $0xD2 = fasttrap */
      canonical->sysno
         = VG_SOLARIS_SYSCALL_CONSTRUCT_FASTTRAP(canonical->sysno);
      break;
   default:
      vg_assert(0);
      break;
   }

#else
#  error "getSyscallArgsFromGuestState: unknown arch"
#endif
}

static 
void putSyscallArgsIntoGuestState ( /*IN*/ SyscallArgs*       canonical,
                                    /*OUT*/VexGuestArchState* gst_vanilla )
{
#if defined(VGP_x86_linux)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   gst->guest_EAX = canonical->sysno;
   gst->guest_EBX = canonical->arg1;
   gst->guest_ECX = canonical->arg2;
   gst->guest_EDX = canonical->arg3;
   gst->guest_ESI = canonical->arg4;
   gst->guest_EDI = canonical->arg5;
   gst->guest_EBP = canonical->arg6;

#elif defined(VGP_amd64_linux)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   gst->guest_RAX = canonical->sysno;
   gst->guest_RDI = canonical->arg1;
   gst->guest_RSI = canonical->arg2;
   gst->guest_RDX = canonical->arg3;
   gst->guest_R10 = canonical->arg4;
   gst->guest_R8  = canonical->arg5;
   gst->guest_R9  = canonical->arg6;

#elif defined(VGP_ppc32_linux)
   VexGuestPPC32State* gst = (VexGuestPPC32State*)gst_vanilla;
   gst->guest_GPR0 = canonical->sysno;
   gst->guest_GPR3 = canonical->arg1;
   gst->guest_GPR4 = canonical->arg2;
   gst->guest_GPR5 = canonical->arg3;
   gst->guest_GPR6 = canonical->arg4;
   gst->guest_GPR7 = canonical->arg5;
   gst->guest_GPR8 = canonical->arg6;

#elif defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
   VexGuestPPC64State* gst = (VexGuestPPC64State*)gst_vanilla;
   gst->guest_GPR0 = canonical->sysno;
   gst->guest_GPR3 = canonical->arg1;
   gst->guest_GPR4 = canonical->arg2;
   gst->guest_GPR5 = canonical->arg3;
   gst->guest_GPR6 = canonical->arg4;
   gst->guest_GPR7 = canonical->arg5;
   gst->guest_GPR8 = canonical->arg6;

#elif defined(VGP_arm_linux)
   VexGuestARMState* gst = (VexGuestARMState*)gst_vanilla;
   gst->guest_R7 = canonical->sysno;
   gst->guest_R0 = canonical->arg1;
   gst->guest_R1 = canonical->arg2;
   gst->guest_R2 = canonical->arg3;
   gst->guest_R3 = canonical->arg4;
   gst->guest_R4 = canonical->arg5;
   gst->guest_R5 = canonical->arg6;

#elif defined(VGP_arm64_linux)
   VexGuestARM64State* gst = (VexGuestARM64State*)gst_vanilla;
   gst->guest_X8 = canonical->sysno;
   gst->guest_X0 = canonical->arg1;
   gst->guest_X1 = canonical->arg2;
   gst->guest_X2 = canonical->arg3;
   gst->guest_X3 = canonical->arg4;
   gst->guest_X4 = canonical->arg5;
   gst->guest_X5 = canonical->arg6;

#elif defined(VGP_x86_darwin)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_ESP;

   gst->guest_EAX = VG_DARWIN_SYSNO_FOR_KERNEL(canonical->sysno);

   // GrP fixme? gst->guest_TEMP_EFLAG_C = 0;
   // stack[0] is return address
   stack[1] = canonical->arg1;
   stack[2] = canonical->arg2;
   stack[3] = canonical->arg3;
   stack[4] = canonical->arg4;
   stack[5] = canonical->arg5;
   stack[6] = canonical->arg6;
   stack[7] = canonical->arg7;
   stack[8] = canonical->arg8;
   
#elif defined(VGP_amd64_darwin)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_RSP;

   gst->guest_RAX = VG_DARWIN_SYSNO_FOR_KERNEL(canonical->sysno);
   // GrP fixme? gst->guest_TEMP_EFLAG_C = 0;

   // stack[0] is return address
   gst->guest_RDI = canonical->arg1;
   gst->guest_RSI = canonical->arg2;
   gst->guest_RDX = canonical->arg3;
   gst->guest_RCX = canonical->arg4;
   gst->guest_R8  = canonical->arg5;
   gst->guest_R9  = canonical->arg6;
   stack[1]       = canonical->arg7;
   stack[2]       = canonical->arg8;

#elif defined(VGP_s390x_linux)
   VexGuestS390XState* gst = (VexGuestS390XState*)gst_vanilla;
   gst->guest_SYSNO  = canonical->sysno;
   gst->guest_r2     = canonical->arg1;
   gst->guest_r3     = canonical->arg2;
   gst->guest_r4     = canonical->arg3;
   gst->guest_r5     = canonical->arg4;
   gst->guest_r6     = canonical->arg5;
   gst->guest_r7     = canonical->arg6;

#elif defined(VGP_mips32_linux)
   VexGuestMIPS32State* gst = (VexGuestMIPS32State*)gst_vanilla;
   if (canonical->arg8 != __NR_syscall) {
      gst->guest_r2 = canonical->sysno;
      gst->guest_r4 = canonical->arg1;
      gst->guest_r5 = canonical->arg2;
      gst->guest_r6 = canonical->arg3;
      gst->guest_r7 = canonical->arg4;
      *((UInt*) (gst->guest_r29 + 16)) = canonical->arg5; // 16(guest_GPR29/sp)
      *((UInt*) (gst->guest_r29 + 20)) = canonical->arg6; // 20(sp)
   } else {
      canonical->arg8 = 0;
      gst->guest_r2 = __NR_syscall;
      gst->guest_r4 = canonical->sysno;
      gst->guest_r5 = canonical->arg1;
      gst->guest_r6 = canonical->arg2;
      gst->guest_r7 = canonical->arg3;
      *((UInt*) (gst->guest_r29 + 16)) = canonical->arg4; // 16(guest_GPR29/sp)
      *((UInt*) (gst->guest_r29 + 20)) = canonical->arg5; // 20(sp)
      *((UInt*) (gst->guest_r29 + 24)) = canonical->arg6; // 24(sp)
   }

#elif defined(VGP_mips64_linux)
   VexGuestMIPS64State* gst = (VexGuestMIPS64State*)gst_vanilla;
   gst->guest_r2 = canonical->sysno;
   gst->guest_r4 = canonical->arg1;
   gst->guest_r5 = canonical->arg2;
   gst->guest_r6 = canonical->arg3;
   gst->guest_r7 = canonical->arg4;
   gst->guest_r8 = canonical->arg5;
   gst->guest_r9 = canonical->arg6;

#elif defined(VGP_x86_solaris)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_ESP;

   /* Fasttraps or anything else cannot go through this way. */
   vg_assert(VG_SOLARIS_SYSNO_CLASS(canonical->sysno)
             == VG_SOLARIS_SYSCALL_CLASS_CLASSIC);
   gst->guest_EAX = canonical->sysno;
   /* stack[0] is a return address. */
   stack[1] = canonical->arg1;
   stack[2] = canonical->arg2;
   stack[3] = canonical->arg3;
   stack[4] = canonical->arg4;
   stack[5] = canonical->arg5;
   stack[6] = canonical->arg6;
   stack[7] = canonical->arg7;
   stack[8] = canonical->arg8;

#elif defined(VGP_amd64_solaris)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   UWord *stack = (UWord *)gst->guest_RSP;

   /* Fasttraps or anything else cannot go through this way. */
   vg_assert(VG_SOLARIS_SYSNO_CLASS(canonical->sysno)
             == VG_SOLARIS_SYSCALL_CLASS_CLASSIC);
   gst->guest_RAX = canonical->sysno;
   /* stack[0] is a return address. */
   gst->guest_RDI = canonical->arg1;
   gst->guest_RSI = canonical->arg2;
   gst->guest_RDX = canonical->arg3;
   gst->guest_R10 = canonical->arg4;
   gst->guest_R8  = canonical->arg5;
   gst->guest_R9  = canonical->arg6;
   stack[1] = canonical->arg7;
   stack[2] = canonical->arg8;

#else
#  error "putSyscallArgsIntoGuestState: unknown arch"
#endif
}

static
void getSyscallStatusFromGuestState ( /*OUT*/SyscallStatus*     canonical,
                                      /*IN*/ VexGuestArchState* gst_vanilla )
{
#  if defined(VGP_x86_linux)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   canonical->sres = VG_(mk_SysRes_x86_linux)( gst->guest_EAX );
   canonical->what = SsComplete;

#  elif defined(VGP_amd64_linux)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   canonical->sres = VG_(mk_SysRes_amd64_linux)( gst->guest_RAX );
   canonical->what = SsComplete;

#  elif defined(VGP_ppc32_linux)
   VexGuestPPC32State* gst   = (VexGuestPPC32State*)gst_vanilla;
   UInt                cr    = LibVEX_GuestPPC32_get_CR( gst );
   UInt                cr0so = (cr >> 28) & 1;
   canonical->sres = VG_(mk_SysRes_ppc32_linux)( gst->guest_GPR3, cr0so );
   canonical->what = SsComplete;

#  elif defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
   VexGuestPPC64State* gst   = (VexGuestPPC64State*)gst_vanilla;
   UInt                cr    = LibVEX_GuestPPC64_get_CR( gst );
   UInt                cr0so = (cr >> 28) & 1;
   canonical->sres = VG_(mk_SysRes_ppc64_linux)( gst->guest_GPR3, cr0so );
   canonical->what = SsComplete;

#  elif defined(VGP_arm_linux)
   VexGuestARMState* gst = (VexGuestARMState*)gst_vanilla;
   canonical->sres = VG_(mk_SysRes_arm_linux)( gst->guest_R0 );
   canonical->what = SsComplete;

#  elif defined(VGP_arm64_linux)
   VexGuestARM64State* gst = (VexGuestARM64State*)gst_vanilla;
   canonical->sres = VG_(mk_SysRes_arm64_linux)( gst->guest_X0 );
   canonical->what = SsComplete;

#  elif defined(VGP_mips32_linux)
   VexGuestMIPS32State* gst = (VexGuestMIPS32State*)gst_vanilla;
   UInt                v0 = gst->guest_r2;    // v0
   UInt                v1 = gst->guest_r3;    // v1
   UInt                a3 = gst->guest_r7;    // a3
   canonical->sres = VG_(mk_SysRes_mips32_linux)( v0, v1, a3 );
   canonical->what = SsComplete;

#  elif defined(VGP_mips64_linux)
   VexGuestMIPS64State* gst = (VexGuestMIPS64State*)gst_vanilla;
   ULong                v0 = gst->guest_r2;    // v0
   ULong                v1 = gst->guest_r3;    // v1
   ULong                a3 = gst->guest_r7;    // a3
   canonical->sres = VG_(mk_SysRes_mips64_linux)(v0, v1, a3);
   canonical->what = SsComplete;

#  elif defined(VGP_x86_darwin)
   /* duplicates logic in m_signals.VG_UCONTEXT_SYSCALL_SYSRES */
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   UInt carry = 1 & LibVEX_GuestX86_get_eflags(gst);
   UInt err = 0;
   UInt wLO = 0;
   UInt wHI = 0;
   switch (gst->guest_SC_CLASS) {
      case VG_DARWIN_SYSCALL_CLASS_UNIX:
         // int $0x80 = Unix, 64-bit result
         err = carry;
         wLO = gst->guest_EAX;
         wHI = gst->guest_EDX;
         break;
      case VG_DARWIN_SYSCALL_CLASS_MACH:
         // int $0x81 = Mach, 32-bit result
         wLO = gst->guest_EAX;
         break;
      case VG_DARWIN_SYSCALL_CLASS_MDEP:
         // int $0x82 = mdep, 32-bit result
         wLO = gst->guest_EAX;
         break;
      default: 
         vg_assert(0);
         break;
   }
   canonical->sres = VG_(mk_SysRes_x86_darwin)(
                        gst->guest_SC_CLASS, err ? True : False, 
                        wHI, wLO
                     );
   canonical->what = SsComplete;

#  elif defined(VGP_amd64_darwin)
   /* duplicates logic in m_signals.VG_UCONTEXT_SYSCALL_SYSRES */
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   ULong carry = 1 & LibVEX_GuestAMD64_get_rflags(gst);
   ULong err = 0;
   ULong wLO = 0;
   ULong wHI = 0;
   switch (gst->guest_SC_CLASS) {
      case VG_DARWIN_SYSCALL_CLASS_UNIX:
         // syscall = Unix, 128-bit result
         err = carry;
         wLO = gst->guest_RAX;
         wHI = gst->guest_RDX;
         break;
      case VG_DARWIN_SYSCALL_CLASS_MACH:
         // syscall = Mach, 64-bit result
         wLO = gst->guest_RAX;
         break;
      case VG_DARWIN_SYSCALL_CLASS_MDEP:
         // syscall = mdep, 64-bit result
         wLO = gst->guest_RAX;
         break;
      default: 
         vg_assert(0);
         break;
   }
   canonical->sres = VG_(mk_SysRes_amd64_darwin)(
                        gst->guest_SC_CLASS, err ? True : False, 
                        wHI, wLO
                     );
   canonical->what = SsComplete;

#  elif defined(VGP_s390x_linux)
   VexGuestS390XState* gst   = (VexGuestS390XState*)gst_vanilla;
   canonical->sres = VG_(mk_SysRes_s390x_linux)( gst->guest_r2 );
   canonical->what = SsComplete;

#  elif defined(VGP_x86_solaris)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   UInt carry = 1 & LibVEX_GuestX86_get_eflags(gst);

   canonical->sres = VG_(mk_SysRes_x86_solaris)(carry ? True : False,
                                                gst->guest_EAX,
                                                carry ? 0 : gst->guest_EDX);
   canonical->what = SsComplete;

#  elif defined(VGP_amd64_solaris)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   UInt carry = 1 & LibVEX_GuestAMD64_get_rflags(gst);

   canonical->sres = VG_(mk_SysRes_amd64_solaris)(carry ? True : False,
                                                  gst->guest_RAX,
                                                  carry ? 0 : gst->guest_RDX);
   canonical->what = SsComplete;

#  else
#    error "getSyscallStatusFromGuestState: unknown arch"
#  endif
}

static 
void putSyscallStatusIntoGuestState ( /*IN*/ ThreadId tid, 
                                      /*IN*/ SyscallStatus*     canonical,
                                      /*OUT*/VexGuestArchState* gst_vanilla )
{
#  if defined(VGP_x86_linux)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      /* This isn't exactly right, in that really a Failure with res
         not in the range 1 .. 4095 is unrepresentable in the
         Linux-x86 scheme.  Oh well. */
      gst->guest_EAX = - (Int)sr_Err(canonical->sres);
   } else {
      gst->guest_EAX = sr_Res(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_x86_EAX, sizeof(UWord) );

#  elif defined(VGP_amd64_linux)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      /* This isn't exactly right, in that really a Failure with res
         not in the range 1 .. 4095 is unrepresentable in the
         Linux-amd64 scheme.  Oh well. */
      gst->guest_RAX = - (Long)sr_Err(canonical->sres);
   } else {
      gst->guest_RAX = sr_Res(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_amd64_RAX, sizeof(UWord) );

#  elif defined(VGP_ppc32_linux)
   VexGuestPPC32State* gst = (VexGuestPPC32State*)gst_vanilla;
   UInt old_cr = LibVEX_GuestPPC32_get_CR(gst);
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      /* set CR0.SO */
      LibVEX_GuestPPC32_put_CR( old_cr | (1<<28), gst );
      gst->guest_GPR3 = sr_Err(canonical->sres);
   } else {
      /* clear CR0.SO */
      LibVEX_GuestPPC32_put_CR( old_cr & ~(1<<28), gst );
      gst->guest_GPR3 = sr_Res(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_ppc32_GPR3, sizeof(UWord) );
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_ppc32_CR0_0, sizeof(UChar) );

#  elif defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
   VexGuestPPC64State* gst = (VexGuestPPC64State*)gst_vanilla;
   UInt old_cr = LibVEX_GuestPPC64_get_CR(gst);
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      /* set CR0.SO */
      LibVEX_GuestPPC64_put_CR( old_cr | (1<<28), gst );
      gst->guest_GPR3 = sr_Err(canonical->sres);
   } else {
      /* clear CR0.SO */
      LibVEX_GuestPPC64_put_CR( old_cr & ~(1<<28), gst );
      gst->guest_GPR3 = sr_Res(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_ppc64_GPR3, sizeof(UWord) );
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_ppc64_CR0_0, sizeof(UChar) );

#  elif defined(VGP_arm_linux)
   VexGuestARMState* gst = (VexGuestARMState*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      /* This isn't exactly right, in that really a Failure with res
         not in the range 1 .. 4095 is unrepresentable in the
         Linux-arm scheme.  Oh well. */
      gst->guest_R0 = - (Int)sr_Err(canonical->sres);
   } else {
      gst->guest_R0 = sr_Res(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_arm_R0, sizeof(UWord) );

#  elif defined(VGP_arm64_linux)
   VexGuestARM64State* gst = (VexGuestARM64State*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      /* This isn't exactly right, in that really a Failure with res
         not in the range 1 .. 4095 is unrepresentable in the
         Linux-arm64 scheme.  Oh well. */
      gst->guest_X0 = - (Long)sr_Err(canonical->sres);
   } else {
      gst->guest_X0 = sr_Res(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
             OFFSET_arm64_X0, sizeof(UWord) );

#elif defined(VGP_x86_darwin)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   SysRes sres = canonical->sres;
   vg_assert(canonical->what == SsComplete);
   /* Unfortunately here we have to break abstraction and look
      directly inside 'res', in order to decide what to do. */
   switch (sres._mode) {
      case SysRes_MACH: // int $0x81 = Mach, 32-bit result
      case SysRes_MDEP: // int $0x82 = mdep, 32-bit result
         gst->guest_EAX = sres._wLO;
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   OFFSET_x86_EAX, sizeof(UInt) );
         break;
      case SysRes_UNIX_OK:  // int $0x80 = Unix, 64-bit result
      case SysRes_UNIX_ERR: // int $0x80 = Unix, 64-bit error
         gst->guest_EAX = sres._wLO;
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   OFFSET_x86_EAX, sizeof(UInt) );
         gst->guest_EDX = sres._wHI;
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   OFFSET_x86_EDX, sizeof(UInt) );
         LibVEX_GuestX86_put_eflag_c( sres._mode==SysRes_UNIX_ERR ? 1 : 0,
                                      gst );
         // GrP fixme sets defined for entire eflags, not just bit c
         // DDD: this breaks exp-ptrcheck.
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   offsetof(VexGuestX86State, guest_CC_DEP1), sizeof(UInt) );
         break;
      default: 
         vg_assert(0);
         break;
   }
   
#elif defined(VGP_amd64_darwin)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   SysRes sres = canonical->sres;
   vg_assert(canonical->what == SsComplete);
   /* Unfortunately here we have to break abstraction and look
      directly inside 'res', in order to decide what to do. */
   switch (sres._mode) {
      case SysRes_MACH: // syscall = Mach, 64-bit result
      case SysRes_MDEP: // syscall = mdep, 64-bit result
         gst->guest_RAX = sres._wLO;
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   OFFSET_amd64_RAX, sizeof(ULong) );
         break;
      case SysRes_UNIX_OK:  // syscall = Unix, 128-bit result
      case SysRes_UNIX_ERR: // syscall = Unix, 128-bit error
         gst->guest_RAX = sres._wLO;
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   OFFSET_amd64_RAX, sizeof(ULong) );
         gst->guest_RDX = sres._wHI;
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   OFFSET_amd64_RDX, sizeof(ULong) );
         LibVEX_GuestAMD64_put_rflag_c( sres._mode==SysRes_UNIX_ERR ? 1 : 0,
                                        gst );
         // GrP fixme sets defined for entire rflags, not just bit c
         // DDD: this breaks exp-ptrcheck.
         VG_TRACK( post_reg_write, Vg_CoreSysCall, tid, 
                   offsetof(VexGuestAMD64State, guest_CC_DEP1), sizeof(ULong) );
         break;
      default: 
         vg_assert(0);
         break;
   }
   
#  elif defined(VGP_s390x_linux)
   VexGuestS390XState* gst = (VexGuestS390XState*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      gst->guest_r2 = - (Long)sr_Err(canonical->sres);
   } else {
      gst->guest_r2 = sr_Res(canonical->sres);
   }

#  elif defined(VGP_mips32_linux)
   VexGuestMIPS32State* gst = (VexGuestMIPS32State*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      gst->guest_r2 = (Int)sr_Err(canonical->sres);
      gst->guest_r7 = (Int)sr_Err(canonical->sres);
   } else {
      gst->guest_r2 = sr_Res(canonical->sres);
      gst->guest_r3 = sr_ResEx(canonical->sres);
      gst->guest_r7 = (Int)sr_Err(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid,
             OFFSET_mips32_r2, sizeof(UWord) );
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid,
             OFFSET_mips32_r3, sizeof(UWord) );
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid,
             OFFSET_mips32_r7, sizeof(UWord) );

#  elif defined(VGP_mips64_linux)
   VexGuestMIPS64State* gst = (VexGuestMIPS64State*)gst_vanilla;
   vg_assert(canonical->what == SsComplete);
   if (sr_isError(canonical->sres)) {
      gst->guest_r2 = (Int)sr_Err(canonical->sres);
      gst->guest_r7 = (Int)sr_Err(canonical->sres);
   } else {
      gst->guest_r2 = sr_Res(canonical->sres);
      gst->guest_r3 = sr_ResEx(canonical->sres);
      gst->guest_r7 = (Int)sr_Err(canonical->sres);
   }
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid,
             OFFSET_mips64_r2, sizeof(UWord) );
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid,
             OFFSET_mips64_r3, sizeof(UWord) );
   VG_TRACK( post_reg_write, Vg_CoreSysCall, tid,
             OFFSET_mips64_r7, sizeof(UWord) );

#  elif defined(VGP_x86_solaris)
   VexGuestX86State* gst = (VexGuestX86State*)gst_vanilla;
   SysRes sres = canonical->sres;
   vg_assert(canonical->what == SsComplete);

   if (sr_isError(sres)) {
      gst->guest_EAX = sr_Err(sres);
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, OFFSET_x86_EAX,
               sizeof(UInt));
      LibVEX_GuestX86_put_eflag_c(1, gst);
   }
   else {
      gst->guest_EAX = sr_Res(sres);
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, OFFSET_x86_EAX,
               sizeof(UInt));
      gst->guest_EDX = sr_ResHI(sres);
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, OFFSET_x86_EDX,
               sizeof(UInt));
      LibVEX_GuestX86_put_eflag_c(0, gst);
   }
   /* Make CC_DEP1 and CC_DEP2 defined.  This is inaccurate because it makes
      other eflags defined too (see README.solaris). */
   VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, offsetof(VexGuestX86State,
            guest_CC_DEP1), sizeof(UInt));
   VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, offsetof(VexGuestX86State,
            guest_CC_DEP2), sizeof(UInt));

#  elif defined(VGP_amd64_solaris)
   VexGuestAMD64State* gst = (VexGuestAMD64State*)gst_vanilla;
   SysRes sres = canonical->sres;
   vg_assert(canonical->what == SsComplete);

   if (sr_isError(sres)) {
      gst->guest_RAX = sr_Err(sres);
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, OFFSET_amd64_RAX,
               sizeof(ULong));
      LibVEX_GuestAMD64_put_rflag_c(1, gst);
   }
   else {
      gst->guest_RAX = sr_Res(sres);
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, OFFSET_amd64_RAX,
               sizeof(ULong));
      gst->guest_RDX = sr_ResHI(sres);
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, OFFSET_amd64_RDX,
               sizeof(ULong));
      LibVEX_GuestAMD64_put_rflag_c(0, gst);
   }
   /* Make CC_DEP1 and CC_DEP2 defined.  This is inaccurate because it makes
      other eflags defined too (see README.solaris). */
   VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, offsetof(VexGuestAMD64State,
            guest_CC_DEP1), sizeof(ULong));
   VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, offsetof(VexGuestAMD64State,
            guest_CC_DEP2), sizeof(ULong));

#  else
#    error "putSyscallStatusIntoGuestState: unknown arch"
#  endif
}


/* Tell me the offsets in the guest state of the syscall params, so
   that the scalar argument checkers don't have to have this info
   hardwired. */

static
void getSyscallArgLayout ( /*OUT*/SyscallArgLayout* layout )
{
   VG_(bzero_inline)(layout, sizeof(*layout));

#if defined(VGP_x86_linux)
   layout->o_sysno  = OFFSET_x86_EAX;
   layout->o_arg1   = OFFSET_x86_EBX;
   layout->o_arg2   = OFFSET_x86_ECX;
   layout->o_arg3   = OFFSET_x86_EDX;
   layout->o_arg4   = OFFSET_x86_ESI;
   layout->o_arg5   = OFFSET_x86_EDI;
   layout->o_arg6   = OFFSET_x86_EBP;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_amd64_linux)
   layout->o_sysno  = OFFSET_amd64_RAX;
   layout->o_arg1   = OFFSET_amd64_RDI;
   layout->o_arg2   = OFFSET_amd64_RSI;
   layout->o_arg3   = OFFSET_amd64_RDX;
   layout->o_arg4   = OFFSET_amd64_R10;
   layout->o_arg5   = OFFSET_amd64_R8;
   layout->o_arg6   = OFFSET_amd64_R9;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_ppc32_linux)
   layout->o_sysno  = OFFSET_ppc32_GPR0;
   layout->o_arg1   = OFFSET_ppc32_GPR3;
   layout->o_arg2   = OFFSET_ppc32_GPR4;
   layout->o_arg3   = OFFSET_ppc32_GPR5;
   layout->o_arg4   = OFFSET_ppc32_GPR6;
   layout->o_arg5   = OFFSET_ppc32_GPR7;
   layout->o_arg6   = OFFSET_ppc32_GPR8;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
   layout->o_sysno  = OFFSET_ppc64_GPR0;
   layout->o_arg1   = OFFSET_ppc64_GPR3;
   layout->o_arg2   = OFFSET_ppc64_GPR4;
   layout->o_arg3   = OFFSET_ppc64_GPR5;
   layout->o_arg4   = OFFSET_ppc64_GPR6;
   layout->o_arg5   = OFFSET_ppc64_GPR7;
   layout->o_arg6   = OFFSET_ppc64_GPR8;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_arm_linux)
   layout->o_sysno  = OFFSET_arm_R7;
   layout->o_arg1   = OFFSET_arm_R0;
   layout->o_arg2   = OFFSET_arm_R1;
   layout->o_arg3   = OFFSET_arm_R2;
   layout->o_arg4   = OFFSET_arm_R3;
   layout->o_arg5   = OFFSET_arm_R4;
   layout->o_arg6   = OFFSET_arm_R5;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_arm64_linux)
   layout->o_sysno  = OFFSET_arm64_X8;
   layout->o_arg1   = OFFSET_arm64_X0;
   layout->o_arg2   = OFFSET_arm64_X1;
   layout->o_arg3   = OFFSET_arm64_X2;
   layout->o_arg4   = OFFSET_arm64_X3;
   layout->o_arg5   = OFFSET_arm64_X4;
   layout->o_arg6   = OFFSET_arm64_X5;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_mips32_linux)
   layout->o_sysno  = OFFSET_mips32_r2;
   layout->o_arg1   = OFFSET_mips32_r4;
   layout->o_arg2   = OFFSET_mips32_r5;
   layout->o_arg3   = OFFSET_mips32_r6;
   layout->o_arg4   = OFFSET_mips32_r7;
   layout->s_arg5   = sizeof(UWord) * 4;
   layout->s_arg6   = sizeof(UWord) * 5;
   layout->s_arg7   = sizeof(UWord) * 6;
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_mips64_linux)
   layout->o_sysno  = OFFSET_mips64_r2;
   layout->o_arg1   = OFFSET_mips64_r4;
   layout->o_arg2   = OFFSET_mips64_r5;
   layout->o_arg3   = OFFSET_mips64_r6;
   layout->o_arg4   = OFFSET_mips64_r7;
   layout->o_arg5   = OFFSET_mips64_r8;
   layout->o_arg6   = OFFSET_mips64_r9;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_x86_darwin)
   layout->o_sysno  = OFFSET_x86_EAX;
   // syscall parameters are on stack in C convention
   layout->s_arg1   = sizeof(UWord) * 1;
   layout->s_arg2   = sizeof(UWord) * 2;
   layout->s_arg3   = sizeof(UWord) * 3;
   layout->s_arg4   = sizeof(UWord) * 4;
   layout->s_arg5   = sizeof(UWord) * 5;
   layout->s_arg6   = sizeof(UWord) * 6;
   layout->s_arg7   = sizeof(UWord) * 7;
   layout->s_arg8   = sizeof(UWord) * 8;
   
#elif defined(VGP_amd64_darwin)
   layout->o_sysno  = OFFSET_amd64_RAX;
   layout->o_arg1   = OFFSET_amd64_RDI;
   layout->o_arg2   = OFFSET_amd64_RSI;
   layout->o_arg3   = OFFSET_amd64_RDX;
   layout->o_arg4   = OFFSET_amd64_RCX;
   layout->o_arg5   = OFFSET_amd64_R8;
   layout->o_arg6   = OFFSET_amd64_R9;
   layout->s_arg7   = sizeof(UWord) * 1;
   layout->s_arg8   = sizeof(UWord) * 2;

#elif defined(VGP_s390x_linux)
   layout->o_sysno  = OFFSET_s390x_SYSNO;
   layout->o_arg1   = OFFSET_s390x_r2;
   layout->o_arg2   = OFFSET_s390x_r3;
   layout->o_arg3   = OFFSET_s390x_r4;
   layout->o_arg4   = OFFSET_s390x_r5;
   layout->o_arg5   = OFFSET_s390x_r6;
   layout->o_arg6   = OFFSET_s390x_r7;
   layout->uu_arg7  = -1; /* impossible value */
   layout->uu_arg8  = -1; /* impossible value */

#elif defined(VGP_x86_solaris)
   layout->o_sysno  = OFFSET_x86_EAX;
   /* Syscall parameters are on the stack. */
   layout->s_arg1   = sizeof(UWord) * 1;
   layout->s_arg2   = sizeof(UWord) * 2;
   layout->s_arg3   = sizeof(UWord) * 3;
   layout->s_arg4   = sizeof(UWord) * 4;
   layout->s_arg5   = sizeof(UWord) * 5;
   layout->s_arg6   = sizeof(UWord) * 6;
   layout->s_arg7   = sizeof(UWord) * 7;
   layout->s_arg8   = sizeof(UWord) * 8;

#elif defined(VGP_amd64_solaris)
   layout->o_sysno  = OFFSET_amd64_RAX;
   layout->o_arg1   = OFFSET_amd64_RDI;
   layout->o_arg2   = OFFSET_amd64_RSI;
   layout->o_arg3   = OFFSET_amd64_RDX;
   layout->o_arg4   = OFFSET_amd64_R10;
   layout->o_arg5   = OFFSET_amd64_R8;
   layout->o_arg6   = OFFSET_amd64_R9;
   layout->s_arg7   = sizeof(UWord) * 1;
   layout->s_arg8   = sizeof(UWord) * 2;

#else
#  error "getSyscallLayout: unknown arch"
#endif
}


/* ---------------------------------------------------------------------
   The main driver logic
   ------------------------------------------------------------------ */

/* Finding the handlers for a given syscall, or faking up one
   when no handler is found. */

static 
void bad_before ( ThreadId              tid,
                  SyscallArgLayout*     layout,
                  /*MOD*/SyscallArgs*   args,
                  /*OUT*/SyscallStatus* status,
                  /*OUT*/UWord*         flags )
{
   VG_(dmsg)("WARNING: unhandled %s syscall: %s\n",
      VG_PLATFORM, VG_SYSNUM_STRING(args->sysno));
   if (VG_(clo_verbosity) > 1) {
      VG_(get_and_pp_StackTrace)(tid, VG_(clo_backtrace_size));
   }
   VG_(dmsg)("You may be able to write your own handler.\n");
   VG_(dmsg)("Read the file README_MISSING_SYSCALL_OR_IOCTL.\n");
   VG_(dmsg)("Nevertheless we consider this a bug.  Please report\n");
   VG_(dmsg)("it at http://valgrind.org/support/bug_reports.html.\n");

   SET_STATUS_Failure(VKI_ENOSYS);

#  if defined(VGO_solaris)
   VG_(exit)(1);
#  endif
}

static SyscallTableEntry bad_sys =
   { bad_before, NULL };

static const SyscallTableEntry* get_syscall_entry ( Int syscallno )
{
   const SyscallTableEntry* sys = NULL;

#  if defined(VGO_linux)
   sys = ML_(get_linux_syscall_entry)( syscallno );

#  elif defined(VGO_darwin)
   Int idx = VG_DARWIN_SYSNO_INDEX(syscallno);

   switch (VG_DARWIN_SYSNO_CLASS(syscallno)) {
   case VG_DARWIN_SYSCALL_CLASS_UNIX:
      if (idx >= 0 && idx < ML_(syscall_table_size) &&
          ML_(syscall_table)[idx].before != NULL)
         sys = &ML_(syscall_table)[idx];
         break;
   case VG_DARWIN_SYSCALL_CLASS_MACH:
      if (idx >= 0 && idx < ML_(mach_trap_table_size) &&
          ML_(mach_trap_table)[idx].before != NULL)
         sys = &ML_(mach_trap_table)[idx];
         break;
   case VG_DARWIN_SYSCALL_CLASS_MDEP:
      if (idx >= 0 && idx < ML_(mdep_trap_table_size) &&
          ML_(mdep_trap_table)[idx].before != NULL)
         sys = &ML_(mdep_trap_table)[idx];
         break;
   default: 
      vg_assert(0);
      break;
   }

#  elif defined(VGO_solaris)
   sys = ML_(get_solaris_syscall_entry)(syscallno);

#  else
#    error Unknown OS
#  endif

   return sys == NULL  ? &bad_sys  : sys;
}


/* Add and remove signals from mask so that we end up telling the
   kernel the state we actually want rather than what the client
   wants. */
void VG_(sanitize_client_sigmask)(vki_sigset_t *mask)
{
   VG_(sigdelset)(mask, VKI_SIGKILL);
   VG_(sigdelset)(mask, VKI_SIGSTOP);
   VG_(sigdelset)(mask, VG_SIGVGKILL); /* never block */
}

typedef
   struct {
      SyscallArgs   orig_args;
      SyscallArgs   args;
      SyscallStatus status;
      UWord         flags;
   }
   SyscallInfo;

SyscallInfo *syscallInfo;

/* The scheduler needs to be able to zero out these records after a
   fork, hence this is exported from m_syswrap. */
void VG_(clear_syscallInfo) ( ThreadId tid )
{
   vg_assert(syscallInfo);
   vg_assert(tid >= 0 && tid < VG_N_THREADS);
   VG_(memset)( & syscallInfo[tid], 0, sizeof( syscallInfo[tid] ));
   syscallInfo[tid].status.what = SsIdle;
}

Bool VG_(is_in_syscall) ( ThreadId tid )
{
   vg_assert(tid >= 0 && tid < VG_N_THREADS);
   return (syscallInfo[tid].status.what != SsIdle);
}

Word VG_(is_in_syscall_no) (ThreadId tid )
{
   vg_assert(tid >= 0 && tid < VG_N_THREADS);
   return syscallInfo[tid].orig_args.sysno;
}

static void ensure_initialised ( void )
{
   Int i;
   static Bool init_done = False;
   if (init_done) 
      return;
   init_done = True;

   syscallInfo = VG_(malloc)("scinfo", VG_N_THREADS * sizeof syscallInfo[0]);

   for (i = 0; i < VG_N_THREADS; i++) {
      VG_(clear_syscallInfo)( i );
   }
}

/* --- This is the main function of this file. --- */

void VG_(client_syscall) ( ThreadId tid, UInt trc )
{
   Word                     sysno;
   ThreadState*             tst;
   const SyscallTableEntry* ent;
   SyscallArgLayout         layout;
   SyscallInfo*             sci;

   ensure_initialised();

   vg_assert(VG_(is_valid_tid)(tid));
   vg_assert(tid >= 1 && tid < VG_N_THREADS);
   vg_assert(VG_(is_running_thread)(tid));

#  if !defined(VGO_darwin)
   // Resync filtering is meaningless on non-Darwin targets.
   vg_assert(VG_(clo_resync_filter) == 0);
#  endif

   tst = VG_(get_ThreadState)(tid);

   /* BEGIN ensure root thread's stack is suitably mapped */
   /* In some rare circumstances, we may do the syscall without the
      bottom page of the stack being mapped, because the stack pointer
      was moved down just a few instructions before the syscall
      instruction, and there have been no memory references since
      then, that would cause a call to VG_(extend_stack) to have
      happened.

      In native execution that's OK: the kernel automagically extends
      the stack's mapped area down to cover the stack pointer (or sp -
      redzone, really).  In simulated normal execution that's OK too,
      since any signals we get from accessing below the mapped area of
      the (guest's) stack lead us to VG_(extend_stack), where we
      simulate the kernel's stack extension logic.  But that leaves
      the problem of entering a syscall with the SP unmapped.  Because
      the kernel doesn't know that the segment immediately above SP is
      supposed to be a grow-down segment, it causes the syscall to
      fail, and thereby causes a divergence between native behaviour
      (syscall succeeds) and simulated behaviour (syscall fails).

      This is quite a rare failure mode.  It has only been seen
      affecting calls to sys_readlink on amd64-linux, and even then it
      requires a certain code sequence around the syscall to trigger
      it.  Here is one:

      extern int my_readlink ( const char* path );
      asm(
      ".text\n"
      ".globl my_readlink\n"
      "my_readlink:\n"
      "\tsubq    $0x1008,%rsp\n"
      "\tmovq    %rdi,%rdi\n"              // path is in rdi
      "\tmovq    %rsp,%rsi\n"              // &buf[0] -> rsi
      "\tmovl    $0x1000,%edx\n"           // sizeof(buf) in rdx
      "\tmovl    $"__NR_READLINK",%eax\n"  // syscall number
      "\tsyscall\n"
      "\taddq    $0x1008,%rsp\n"
      "\tret\n"
      ".previous\n"
      );

      For more details, see bug #156404
      (https://bugs.kde.org/show_bug.cgi?id=156404).

      The fix is actually very simple.  We simply need to call
      VG_(extend_stack) for this thread, handing it the lowest
      possible valid address for stack (sp - redzone), to ensure the
      pages all the way down to that address, are mapped.  Because
      this is a potentially expensive and frequent operation, we
      do the following:

      Only the main thread (tid=1) has a growdown stack.  So
      ignore all others.  It is conceivable, although highly unlikely,
      that the main thread exits, and later another thread is
      allocated tid=1, but that's harmless, I believe;
      VG_(extend_stack) will do nothing when applied to a non-root
      thread.

      All this guff is of course Linux-specific.  Hence the ifdef.
   */
#  if defined(VGO_linux)
   if (tid == 1/*ROOT THREAD*/) {
      Addr     stackMin   = VG_(get_SP)(tid) - VG_STACK_REDZONE_SZB;

      /* The precise thing to do here would be to extend the stack only
         if the system call can be proven to access unmapped user stack
         memory. That is an enormous amount of work even if a proper
         spec of system calls was available. 

         In the case where the system call does not access user memory
         the stack pointer here can have any value. A legitimate testcase
         that exercises this is none/tests/s390x/stmg.c:
         The stack pointer happens to be in the reservation segment near
         the end of the addressable memory and there is no SkAnonC segment
         above.

         So the approximation we're taking here is to extend the stack only
         if the client stack pointer does not look bogus. */
      if (VG_(am_addr_is_in_extensible_client_stack)(stackMin))
         VG_(extend_stack)( tid, stackMin );
   }
#  endif
   /* END ensure root thread's stack is suitably mapped */

   /* First off, get the syscall args and number.  This is a
      platform-dependent action. */

   sci = & syscallInfo[tid];
   vg_assert(sci->status.what == SsIdle);

   getSyscallArgsFromGuestState( &sci->orig_args, &tst->arch.vex, trc );

   /* Copy .orig_args to .args.  The pre-handler may modify .args, but
      we want to keep the originals too, just in case. */
   sci->args = sci->orig_args;

   /* Save the syscall number in the thread state in case the syscall 
      is interrupted by a signal. */
   sysno = sci->orig_args.sysno;

   /* It's sometimes useful, as a crude debugging hack, to get a
      stack trace at each (or selected) syscalls. */
   if (0 && sysno == __NR_ioctl) {
      VG_(umsg)("\nioctl:\n");
      VG_(get_and_pp_StackTrace)(tid, 10);
      VG_(umsg)("\n");
   }

#  if defined(VGO_darwin)
   /* Record syscall class.  But why?  Because the syscall might be
      interrupted by a signal, and in the signal handler (which will
      be m_signals.async_signalhandler) we will need to build a SysRes
      reflecting the syscall return result.  In order to do that we
      need to know the syscall class.  Hence stash it in the guest
      state of this thread.  This madness is not needed on Linux
      because it only has a single syscall return convention and so
      there is no ambiguity involved in converting the post-signal
      machine state into a SysRes. */
   tst->arch.vex.guest_SC_CLASS = VG_DARWIN_SYSNO_CLASS(sysno);
#  endif

   /* The default what-to-do-next thing is hand the syscall to the
      kernel, so we pre-set that here.  Set .sres to something
      harmless looking (is irrelevant because .what is not
      SsComplete.) */
   sci->status.what = SsHandToKernel;
   sci->status.sres = VG_(mk_SysRes_Error)(0);
   sci->flags       = 0;

   /* Fetch the syscall's handlers.  If no handlers exist for this
      syscall, we are given dummy handlers which force an immediate
      return with ENOSYS. */
   ent = get_syscall_entry(sysno);

   /* Fetch the layout information, which tells us where in the guest
      state the syscall args reside.  This is a platform-dependent
      action.  This info is needed so that the scalar syscall argument
      checks (PRE_REG_READ calls) know which bits of the guest state
      they need to inspect. */
   getSyscallArgLayout( &layout );

   /* Make sure the tmp signal mask matches the real signal mask;
      sigsuspend may change this. */
   vg_assert(VG_(iseqsigset)(&tst->sig_mask, &tst->tmp_sig_mask));

   /* Right, we're finally ready to Party.  Call the pre-handler and
      see what we get back.  At this point: 

        sci->status.what  is Unset (we don't know yet).
        sci->orig_args    contains the original args.
        sci->args         is the same as sci->orig_args.
        sci->flags        is zero.
   */

   PRINT("SYSCALL[%d,%u](%s) ",
      VG_(getpid)(), tid, VG_SYSNUM_STRING(sysno));

   /* Do any pre-syscall actions */
   if (VG_(needs).syscall_wrapper) {
      UWord tmpv[8];
      tmpv[0] = sci->orig_args.arg1;
      tmpv[1] = sci->orig_args.arg2;
      tmpv[2] = sci->orig_args.arg3;
      tmpv[3] = sci->orig_args.arg4;
      tmpv[4] = sci->orig_args.arg5;
      tmpv[5] = sci->orig_args.arg6;
      tmpv[6] = sci->orig_args.arg7;
      tmpv[7] = sci->orig_args.arg8;
      VG_TDICT_CALL(tool_pre_syscall, tid, sysno,
                    &tmpv[0], sizeof(tmpv)/sizeof(tmpv[0]));
   }

   vg_assert(ent);
   vg_assert(ent->before);
   (ent->before)( tid,
                  &layout, 
                  &sci->args, &sci->status, &sci->flags );
   
   /* If needed, gdbserver will report syscall entry to GDB */
   VG_(gdbserver_report_syscall)(True, sysno, tid);

   /* The pre-handler may have modified:
         sci->args
         sci->status
         sci->flags
      All else remains unchanged. 
      Although the args may be modified, pre handlers are not allowed
      to change the syscall number.
   */
   /* Now we proceed according to what the pre-handler decided. */
   vg_assert(sci->status.what == SsHandToKernel
             || sci->status.what == SsComplete);
   vg_assert(sci->args.sysno == sci->orig_args.sysno);

   if (sci->status.what == SsComplete && !sr_isError(sci->status.sres)) {
      /* The pre-handler completed the syscall itself, declaring
         success. */
      if (sci->flags & SfNoWriteResult) {
         PRINT(" --> [pre-success] NoWriteResult");
      } else {
         PRINT(" --> [pre-success] %s", VG_(sr_as_string)(sci->status.sres));
      }                                      
      /* In this case the allowable flags are to ask for a signal-poll
         and/or a yield after the call.  Changing the args isn't
         allowed. */
      vg_assert(0 == (sci->flags 
                      & ~(SfPollAfter | SfYieldAfter | SfNoWriteResult)));
      vg_assert(eq_SyscallArgs(&sci->args, &sci->orig_args));
   }

   else
   if (sci->status.what == SsComplete && sr_isError(sci->status.sres)) {
      /* The pre-handler decided to fail syscall itself. */
      PRINT(" --> [pre-fail] %s", VG_(sr_as_string)(sci->status.sres));
      /* In this case, the pre-handler is also allowed to ask for the
         post-handler to be run anyway.  Changing the args is not
         allowed. */
      vg_assert(0 == (sci->flags & ~(SfMayBlock | SfPostOnFail | SfPollAfter)));
      vg_assert(eq_SyscallArgs(&sci->args, &sci->orig_args));
   }

   else
   if (sci->status.what != SsHandToKernel) {
      /* huh?! */
      vg_assert(0);
   }

   else /* (sci->status.what == HandToKernel) */ {
      /* Ok, this is the usual case -- and the complicated one.  There
         are two subcases: sync and async.  async is the general case
         and is to be used when there is any possibility that the
         syscall might block [a fact that the pre-handler must tell us
         via the sci->flags field.]  Because the tidying-away /
         context-switch overhead of the async case could be large, if
         we are sure that the syscall will not block, we fast-track it
         by doing it directly in this thread, which is a lot
         simpler. */

      /* Check that the given flags are allowable: MayBlock, PollAfter
         and PostOnFail are ok. */
      vg_assert(0 == (sci->flags & ~(SfMayBlock | SfPostOnFail | SfPollAfter)));

      if (sci->flags & SfMayBlock) {

         /* Syscall may block, so run it asynchronously */
         vki_sigset_t mask;

         PRINT(" --> [async] ... \n");

         mask = tst->sig_mask;
         VG_(sanitize_client_sigmask)(&mask);

         /* Gack.  More impedance matching.  Copy the possibly
            modified syscall args back into the guest state. */
         /* JRS 2009-Mar-16: if the syscall args are possibly modified,
            then this assertion is senseless:
              vg_assert(eq_SyscallArgs(&sci->args, &sci->orig_args));
            The case that exposed it was sys_posix_spawn on Darwin,
            which heavily modifies its arguments but then lets the call
            go through anyway, with SfToBlock set, hence we end up here. */
         putSyscallArgsIntoGuestState( &sci->args, &tst->arch.vex );

         /* SfNoWriteResult flag is invalid for blocking signals because
            do_syscall_for_client() directly modifies the guest state. */
         vg_assert(!(sci->flags & SfNoWriteResult));

         /* Drop the bigLock */
         VG_(release_BigLock)(tid, VgTs_WaitSys, "VG_(client_syscall)[async]");
         /* Urr.  We're now in a race against other threads trying to
            acquire the bigLock.  I guess that doesn't matter provided
            that do_syscall_for_client only touches thread-local
            state. */

         /* Do the call, which operates directly on the guest state,
            not on our abstracted copies of the args/result. */
         do_syscall_for_client(sysno, tst, &mask);

         /* do_syscall_for_client may not return if the syscall was
            interrupted by a signal.  In that case, flow of control is
            first to m_signals.async_sighandler, which calls
            VG_(fixup_guest_state_after_syscall_interrupted), which
            fixes up the guest state, and possibly calls
            VG_(post_syscall).  Once that's done, control drops back
            to the scheduler.  */

         /* Darwin: do_syscall_for_client may not return if the 
            syscall was workq_ops(WQOPS_THREAD_RETURN) and the kernel 
            responded by starting the thread at wqthread_hijack(reuse=1)
            (to run another workqueue item). In that case, wqthread_hijack 
            calls ML_(wqthread_continue), which is similar to 
            VG_(fixup_guest_state_after_syscall_interrupted). */

         /* Reacquire the lock */
         VG_(acquire_BigLock)(tid, "VG_(client_syscall)[async]");

         /* Even more impedance matching.  Extract the syscall status
            from the guest state. */
         getSyscallStatusFromGuestState( &sci->status, &tst->arch.vex );
         vg_assert(sci->status.what == SsComplete);

         /* Be decorative, if required. */
         if (VG_(clo_trace_syscalls)) {
            PRINT("SYSCALL[%d,%u](%s) ... [async] --> %s",
                  VG_(getpid)(), tid, VG_SYSNUM_STRING(sysno),
                  VG_(sr_as_string)(sci->status.sres));
         }

      } else {

         /* run the syscall directly */
         /* The pre-handler may have modified the syscall args, but
            since we're passing values in ->args directly to the
            kernel, there's no point in flushing them back to the
            guest state.  Indeed doing so could be construed as
            incorrect. */
         SysRes sres 
            = VG_(do_syscall)(sysno, sci->args.arg1, sci->args.arg2, 
                                     sci->args.arg3, sci->args.arg4, 
                                     sci->args.arg5, sci->args.arg6,
                                     sci->args.arg7, sci->args.arg8 );
         sci->status = convert_SysRes_to_SyscallStatus(sres);

         /* Be decorative, if required. */
         if (VG_(clo_trace_syscalls)) {
           PRINT("[sync] --> %s", VG_(sr_as_string)(sci->status.sres));
         }
      }
   }

   vg_assert(sci->status.what == SsComplete);

   vg_assert(VG_(is_running_thread)(tid));

   /* Dump the syscall result back in the guest state.  This is
      a platform-specific action. */
   if (!(sci->flags & SfNoWriteResult))
      putSyscallStatusIntoGuestState( tid, &sci->status, &tst->arch.vex );

   /* If needed, gdbserver will report syscall return to GDB */
   VG_(gdbserver_report_syscall)(False, sysno, tid);

   /* Situation now:
      - the guest state is now correctly modified following the syscall
      - modified args, original args and syscall status are still
        available in the syscallInfo[] entry for this syscall.

      Now go on to do the post-syscall actions (read on down ..)
   */
   PRINT(" ");
   VG_(post_syscall)(tid);
   PRINT("\n");
}


/* Perform post syscall actions.  The expected state on entry is
   precisely as at the end of VG_(client_syscall), that is:

   - guest state up to date following the syscall
   - modified args, original args and syscall status are still
     available in the syscallInfo[] entry for this syscall.
   - syscall status matches what's in the guest state.

   There are two ways to get here: the normal way -- being called by
   VG_(client_syscall), and the unusual way, from
   VG_(fixup_guest_state_after_syscall_interrupted).
   Darwin: there's a third way, ML_(wqthread_continue). 
*/
void VG_(post_syscall) (ThreadId tid)
{
   SyscallInfo*             sci;
   const SyscallTableEntry* ent;
   SyscallStatus            test_status;
   ThreadState*             tst;
   Word sysno;

   /* Preliminaries */
   vg_assert(VG_(is_valid_tid)(tid));
   vg_assert(tid >= 1 && tid < VG_N_THREADS);
   vg_assert(VG_(is_running_thread)(tid));

   tst = VG_(get_ThreadState)(tid);
   sci = & syscallInfo[tid];

   /* m_signals.sigvgkill_handler might call here even when not in
      a syscall. */
   if (sci->status.what == SsIdle || sci->status.what == SsHandToKernel) {
      sci->status.what = SsIdle;
      return;
   }

   /* Validate current syscallInfo entry.  In particular we require
      that the current .status matches what's actually in the guest
      state.  At least in the normal case where we have actually
      previously written the result into the guest state. */
   vg_assert(sci->status.what == SsComplete);

   /* Get the system call number.  Because the pre-handler isn't
      allowed to mess with it, it should be the same for both the
      original and potentially-modified args. */
   vg_assert(sci->args.sysno == sci->orig_args.sysno);
   sysno = sci->args.sysno;

   getSyscallStatusFromGuestState( &test_status, &tst->arch.vex );
   if (!(sci->flags & SfNoWriteResult))
      vg_assert(eq_SyscallStatus( sysno, &sci->status, &test_status ));
   /* Failure of the above assertion on Darwin can indicate a problem
      in the syscall wrappers that pre-fail or pre-succeed the
      syscall, by calling SET_STATUS_Success or SET_STATUS_Failure,
      when they really should call SET_STATUS_from_SysRes.  The former
      create a UNIX-class syscall result on Darwin, which may not be
      correct for the syscall; if that's the case then this assertion
      fires.  See PRE(thread_fast_set_cthread_self) for an example.  On
      non-Darwin platforms this assertion is should never fail, and this
      comment is completely irrelevant. */
   /* Ok, looks sane */

   /* pre: status == Complete (asserted above) */
   /* Consider either success or failure.  Now run the post handler if:
      - it exists, and
      - Success or (Failure and PostOnFail is set)
   */
   ent = get_syscall_entry(sysno);
   if (ent->after
       && ((!sr_isError(sci->status.sres))
           || (sr_isError(sci->status.sres)
               && (sci->flags & SfPostOnFail) ))) {

      (ent->after)( tid, &sci->args, &sci->status );
   }

   /* Because the post handler might have changed the status (eg, the
      post-handler for sys_open can change the result from success to
      failure if the kernel supplied a fd that it doesn't like), once
      again dump the syscall result back in the guest state.*/
   if (!(sci->flags & SfNoWriteResult))
      putSyscallStatusIntoGuestState( tid, &sci->status, &tst->arch.vex );

   /* Do any post-syscall actions required by the tool. */
   if (VG_(needs).syscall_wrapper) {
      UWord tmpv[8];
      tmpv[0] = sci->orig_args.arg1;
      tmpv[1] = sci->orig_args.arg2;
      tmpv[2] = sci->orig_args.arg3;
      tmpv[3] = sci->orig_args.arg4;
      tmpv[4] = sci->orig_args.arg5;
      tmpv[5] = sci->orig_args.arg6;
      tmpv[6] = sci->orig_args.arg7;
      tmpv[7] = sci->orig_args.arg8;
      VG_TDICT_CALL(tool_post_syscall, tid, 
                    sysno,
                    &tmpv[0], sizeof(tmpv)/sizeof(tmpv[0]),
                    sci->status.sres);
   }

   /* The syscall is done. */
   vg_assert(sci->status.what == SsComplete);
   sci->status.what = SsIdle;

   /* The pre/post wrappers may have concluded that pending signals
      might have been created, and will have set SfPollAfter to
      request a poll for them once the syscall is done. */
   if (sci->flags & SfPollAfter)
      VG_(poll_signals)(tid);

   /* Similarly, the wrappers might have asked for a yield
      afterwards. */
   if (sci->flags & SfYieldAfter)
      VG_(vg_yield)();
}


/* ---------------------------------------------------------------------
   Dealing with syscalls which get interrupted by a signal:
   VG_(fixup_guest_state_after_syscall_interrupted)
   ------------------------------------------------------------------ */

/* Syscalls done on behalf of the client are finally handed off to the
   kernel in VG_(client_syscall) above, either by calling
   do_syscall_for_client (the async case), or by calling
   VG_(do_syscall6) (the sync case).

   If the syscall is not interrupted by a signal (it may block and
   later unblock, but that's irrelevant here) then those functions
   eventually return and so control is passed to VG_(post_syscall).
   NB: not sure if the sync case can actually get interrupted, as it
   operates with all signals masked.

   However, the syscall may get interrupted by an async-signal.  In
   that case do_syscall_for_client/VG_(do_syscall6) do not
   return.  Instead we wind up in m_signals.async_sighandler.  We need
   to fix up the guest state to make it look like the syscall was
   interrupted for guest.  So async_sighandler calls here, and this
   does the fixup.  Note that from here we wind up calling
   VG_(post_syscall) too.
*/


/* These are addresses within ML_(do_syscall_for_client_WRK).  See
   syscall-$PLAT.S for details. 
*/
#if defined(VGO_linux)
  extern const Addr ML_(blksys_setup);
  extern const Addr ML_(blksys_restart);
  extern const Addr ML_(blksys_complete);
  extern const Addr ML_(blksys_committed);
  extern const Addr ML_(blksys_finished);
#elif defined(VGO_darwin)
  /* Darwin requires extra uglyness */
  extern const Addr ML_(blksys_setup_MACH);
  extern const Addr ML_(blksys_restart_MACH);
  extern const Addr ML_(blksys_complete_MACH);
  extern const Addr ML_(blksys_committed_MACH);
  extern const Addr ML_(blksys_finished_MACH);
  extern const Addr ML_(blksys_setup_MDEP);
  extern const Addr ML_(blksys_restart_MDEP);
  extern const Addr ML_(blksys_complete_MDEP);
  extern const Addr ML_(blksys_committed_MDEP);
  extern const Addr ML_(blksys_finished_MDEP);
  extern const Addr ML_(blksys_setup_UNIX);
  extern const Addr ML_(blksys_restart_UNIX);
  extern const Addr ML_(blksys_complete_UNIX);
  extern const Addr ML_(blksys_committed_UNIX);
  extern const Addr ML_(blksys_finished_UNIX);
#elif defined(VGO_solaris)
  extern const Addr ML_(blksys_setup);
  extern const Addr ML_(blksys_complete);
  extern const Addr ML_(blksys_committed);
  extern const Addr ML_(blksys_finished);
  extern const Addr ML_(blksys_setup_DRET);
  extern const Addr ML_(blksys_complete_DRET);
  extern const Addr ML_(blksys_committed_DRET);
  extern const Addr ML_(blksys_finished_DRET);
#else
# error "Unknown OS"
#endif


/* Back up guest state to restart a system call. */

void ML_(fixup_guest_state_to_restart_syscall) ( ThreadArchState* arch )
{
#if defined(VGP_x86_linux)
   arch->vex.guest_EIP -= 2;             // sizeof(int $0x80)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      int $0x80 == CD 80 
   */
   {
      UChar *p = (UChar *)arch->vex.guest_EIP;
      
      if (p[0] != 0xcd || p[1] != 0x80)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#x %02x %02x\n",
                      arch->vex.guest_EIP, p[0], p[1]); 

      vg_assert(p[0] == 0xcd && p[1] == 0x80);
   }

#elif defined(VGP_amd64_linux)
   arch->vex.guest_RIP -= 2;             // sizeof(syscall)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      syscall == 0F 05 
   */
   {
      UChar *p = (UChar *)arch->vex.guest_RIP;
      
      if (p[0] != 0x0F || p[1] != 0x05)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x\n",
                      arch->vex.guest_RIP, p[0], p[1]); 

      vg_assert(p[0] == 0x0F && p[1] == 0x05);
   }

#elif defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux)
   arch->vex.guest_CIA -= 4;             // sizeof(ppc32 instr)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      sc == 44 00 00 02
   */
   {
      UChar *p = (UChar *)arch->vex.guest_CIA;

      if (p[0] != 0x44 || p[1] != 0x0 || p[2] != 0x0 || p[3] != 0x02)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x %02x %02x\n",
                      (ULong)arch->vex.guest_CIA, p[0], p[1], p[2], p[3]);

      vg_assert(p[0] == 0x44 && p[1] == 0x0 && p[2] == 0x0 && p[3] == 0x2);
   }

#elif defined(VGP_ppc64le_linux)
   arch->vex.guest_CIA -= 4;             // sizeof(ppc32 instr)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      sc == 44 00 00 02
   */
   {
      UChar *p = (UChar *)arch->vex.guest_CIA;

      if (p[3] != 0x44 || p[2] != 0x0 || p[1] != 0x0 || p[0] != 0x02)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x %02x %02x\n",
                      arch->vex.guest_CIA, p[3], p[2], p[1], p[0]);

      vg_assert(p[3] == 0x44 && p[2] == 0x0 && p[1] == 0x0 && p[0] == 0x2);
   }

#elif defined(VGP_arm_linux)
   if (arch->vex.guest_R15T & 1) {
      // Thumb mode.  SVC is a encoded as
      //   1101 1111 imm8
      // where imm8 is the SVC number, and we only accept 0.
      arch->vex.guest_R15T -= 2;   // sizeof(thumb 16 bit insn)
      UChar* p     = (UChar*)(arch->vex.guest_R15T - 1);
      Bool   valid = p[0] == 0 && p[1] == 0xDF;
      if (!valid) {
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over (Thumb) syscall that is not syscall "
                      "at %#x %02x %02x\n",
                      arch->vex.guest_R15T - 1, p[0], p[1]);
      }
      vg_assert(valid);
      // FIXME: NOTE, this really isn't right.  We need to back up
      // ITSTATE to what it was before the SVC instruction, but we
      // don't know what it was.  At least assert that it is now
      // zero, because if it is nonzero then it must also have
      // been nonzero for the SVC itself, which means it was
      // conditional.  Urk.
      vg_assert(arch->vex.guest_ITSTATE == 0);
   } else {
      // ARM mode.  SVC is encoded as 
      //   cond 1111 imm24
      // where imm24 is the SVC number, and we only accept 0.
      arch->vex.guest_R15T -= 4;   // sizeof(arm instr)
      UChar* p     = (UChar*)arch->vex.guest_R15T;
      Bool   valid = p[0] == 0 && p[1] == 0 && p[2] == 0
                     && (p[3] & 0xF) == 0xF;
      if (!valid) {
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over (ARM) syscall that is not syscall "
                      "at %#x %02x %02x %02x %02x\n",
                      arch->vex.guest_R15T, p[0], p[1], p[2], p[3]);
      }
      vg_assert(valid);
   }

#elif defined(VGP_arm64_linux)
   arch->vex.guest_PC -= 4;             // sizeof(arm64 instr)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      svc #0 == d4 00 00 01
   */
   {
      UChar *p = (UChar *)arch->vex.guest_PC;

      if (p[0] != 0x01 || p[1] != 0x00 || p[2] != 0x00 || p[3] != 0xD4)
         VG_(message)(
            Vg_DebugMsg,
            "?! restarting over syscall at %#llx %02x %02x %02x %02x\n",
            arch->vex.guest_PC, p[0], p[1], p[2], p[3]
          );

      vg_assert(p[0] == 0x01 && p[1] == 0x00 && p[2] == 0x00 && p[3] == 0xD4);
   }

#elif defined(VGP_x86_darwin)
   arch->vex.guest_EIP = arch->vex.guest_IP_AT_SYSCALL; 

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      int $0x80 == CD 80  // Used to communicate with BSD syscalls
      int $0x81 == CD 81  // Used to communicate with Mach traps
      int $0x82 == CD 82  // Used to communicate with "thread" ?
      sysenter  == 0F 34  // Used to communicate with Unix syscalls
   */
   {
       UChar *p = (UChar *)arch->vex.guest_EIP;
       Bool  ok = (p[0] == 0xCD && p[1] == 0x80) 
                  || (p[0] == 0xCD && p[1] == 0x81)
                  || (p[0] == 0xCD && p[1] == 0x82)  
                  || (p[0] == 0x0F && p[1] == 0x34);
       if (!ok)
           VG_(message)(Vg_DebugMsg,
                        "?! restarting over syscall at %#x %02x %02x\n",
                        arch->vex.guest_EIP, p[0], p[1]);
       vg_assert(ok);
   }
   
#elif defined(VGP_amd64_darwin)
   arch->vex.guest_RIP = arch->vex.guest_IP_AT_SYSCALL;
    
   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      syscall   == 0F 05
   */
   {
       UChar *p = (UChar *)arch->vex.guest_RIP;
        
       Bool  ok = (p[0] == 0x0F && p[1] == 0x05);
       if (!ok)
           VG_(message)(Vg_DebugMsg,
                        "?! restarting over syscall at %#llx %02x %02x\n",
                        arch->vex.guest_RIP, p[0], p[1]);
       vg_assert(ok);
   }
   
#elif defined(VGP_s390x_linux)
   arch->vex.guest_IA -= 2;             // sizeof(syscall)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      syscall == 0A <num>
   */
   {
      UChar *p = (UChar *)arch->vex.guest_IA;
      if (p[0] != 0x0A)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x\n",
                      arch->vex.guest_IA, p[0], p[1]);

      vg_assert(p[0] == 0x0A);
   }

#elif defined(VGP_mips32_linux) || defined(VGP_mips64_linux)

   arch->vex.guest_PC -= 4;             // sizeof(mips instr)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.
      
      syscall == 00 00 00 0C 
      big endian
      syscall == 0C 00 00 00
   */
   {
      UChar *p = (UChar *)(Addr)(arch->vex.guest_PC);
#     if defined (VG_LITTLEENDIAN)
      if (p[0] != 0x0c || p[1] != 0x00 || p[2] != 0x00 || p[3] != 0x00)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x %02x %02x\n",
                      (ULong)arch->vex.guest_PC, p[0], p[1], p[2], p[3]);

      vg_assert(p[0] == 0x0c && p[1] == 0x00 && p[2] == 0x00 && p[3] == 0x00);
#     elif defined (VG_BIGENDIAN)
      if (p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x00 || p[3] != 0x0c)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x %02x %02x\n",
                      (ULong)arch->vex.guest_PC, p[0], p[1], p[2], p[3]);

      vg_assert(p[0] == 0x00 && p[1] == 0x00 && p[2] == 0x00 && p[3] == 0x0c);
#     else
#        error "Unknown endianness"
#     endif
   }

#elif defined(VGP_x86_solaris)
   arch->vex.guest_EIP -= 2;   // sizeof(int $0x91) or sizeof(syscall)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      int $0x91 == CD 91
      syscall   == 0F 05
      sysenter  == 0F 34

      Handle also other syscall instructions because we also handle them in
      the scheduler.
      int $0x80 == CD 80
      int $0x81 == CD 81
      int $0x82 == CD 82
   */
   {
      UChar *p = (UChar *)arch->vex.guest_EIP;

      Bool  ok = (p[0] == 0xCD && p[1] == 0x91)
                  || (p[0] == 0x0F && p[1] == 0x05)
                  || (p[0] == 0x0F && p[1] == 0x34)
                  || (p[0] == 0xCD && p[1] == 0x80)
                  || (p[0] == 0xCD && p[1] == 0x81)
                  || (p[0] == 0xCD && p[1] == 0x82);
      if (!ok)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#x %02x %02x\n",
                      arch->vex.guest_EIP, p[0], p[1]);
      vg_assert(ok);
   }

#elif defined(VGP_amd64_solaris)
   arch->vex.guest_RIP -= 2;   // sizeof(syscall)

   /* Make sure our caller is actually sane, and we're really backing
      back over a syscall.

      syscall   == 0F 05
   */
   {
      UChar *p = (UChar *)arch->vex.guest_RIP;

      Bool  ok = (p[0] == 0x0F && p[1] == 0x05);
      if (!ok)
         VG_(message)(Vg_DebugMsg,
                      "?! restarting over syscall at %#llx %02x %02x\n",
                      arch->vex.guest_RIP, p[0], p[1]);
      vg_assert(ok);
   }

#else
#  error "ML_(fixup_guest_state_to_restart_syscall): unknown plat"
#endif
}


/* 
   Fix up the guest state when a syscall is interrupted by a signal
   and so has been forced to return 'sysret'.

   To do this, we determine the precise state of the syscall by
   looking at the (real) IP at the time the signal happened.  The
   syscall sequence looks like:

     1. unblock signals
     2. perform syscall
     3. save result to guest state (EAX, RAX, R3+CR0.SO, R0, V0)
     4. re-block signals

   If a signal
   happens at      Then     Why?
   [1-2)           restart  nothing has happened (restart syscall)
   [2]             restart  syscall hasn't started, or kernel wants to restart
   [2-3)           save     syscall complete, but results not saved
   [3-4)           syscall complete, results saved

   Sometimes we never want to restart an interrupted syscall (because
   sigaction says not to), so we only restart if "restart" is True.

   This will also call VG_(post_syscall) if the syscall has actually
   completed (either because it was interrupted, or because it
   actually finished).  It will not call VG_(post_syscall) if the
   syscall is set up for restart, which means that the pre-wrapper may
   get called multiple times.
*/

void 
VG_(fixup_guest_state_after_syscall_interrupted)( ThreadId tid, 
                                                  Addr     ip, 
                                                  SysRes   sres,
                                                  Bool     restart,
                                                  struct vki_ucontext *uc)
{
   /* Note that we don't know the syscall number here, since (1) in
      general there's no reliable way to get hold of it short of
      stashing it in the guest state before the syscall, and (2) in
      any case we don't need to know it for the actions done by this
      routine.

      Furthermore, 'sres' is only used in the case where the syscall
      is complete, but the result has not been committed to the guest
      state yet.  In any other situation it will be meaningless and
      therefore ignored. */

   ThreadState*     tst;
   SyscallStatus    canonical;
   ThreadArchState* th_regs;
   SyscallInfo*     sci;

   /* Compute some Booleans indicating which range we're in. */
   Bool outside_range, 
        in_setup_to_restart,      // [1,2) in the .S files
        at_restart,               // [2]   in the .S files
        in_complete_to_committed, // [3,4) in the .S files
        in_committed_to_finished; // [4,5) in the .S files

   if (VG_(clo_trace_signals))
      VG_(message)( Vg_DebugMsg,
                    "interrupted_syscall: tid=%u, ip=%#lx, "
                    "restart=%s, sres.isErr=%s, sres.val=%" FMT_REGWORD "u\n",
                    tid,
                    ip,
                    restart ? "True" : "False",
                    sr_isError(sres) ? "True" : "False",
                    sr_isError(sres) ? (RegWord)sr_Err(sres) :
                                       (RegWord)sr_Res(sres));

   vg_assert(VG_(is_valid_tid)(tid));
   vg_assert(tid >= 1 && tid < VG_N_THREADS);
   vg_assert(VG_(is_running_thread)(tid));

   tst     = VG_(get_ThreadState)(tid);
   th_regs = &tst->arch;
   sci     = & syscallInfo[tid];

#  if defined(VGO_linux)
   outside_range
      = ip < ML_(blksys_setup) || ip >= ML_(blksys_finished);
   in_setup_to_restart
      = ip >= ML_(blksys_setup) && ip < ML_(blksys_restart); 
   at_restart
      = ip == ML_(blksys_restart); 
   in_complete_to_committed
      = ip >= ML_(blksys_complete) && ip < ML_(blksys_committed); 
   in_committed_to_finished
      = ip >= ML_(blksys_committed) && ip < ML_(blksys_finished);
#  elif defined(VGO_darwin)
   outside_range
      =  (ip < ML_(blksys_setup_MACH) || ip >= ML_(blksys_finished_MACH))
      && (ip < ML_(blksys_setup_MDEP) || ip >= ML_(blksys_finished_MDEP))
      && (ip < ML_(blksys_setup_UNIX) || ip >= ML_(blksys_finished_UNIX));
   in_setup_to_restart
      =  (ip >= ML_(blksys_setup_MACH) && ip < ML_(blksys_restart_MACH))
      || (ip >= ML_(blksys_setup_MDEP) && ip < ML_(blksys_restart_MDEP))
      || (ip >= ML_(blksys_setup_UNIX) && ip < ML_(blksys_restart_UNIX));
   at_restart
      =  (ip == ML_(blksys_restart_MACH))
      || (ip == ML_(blksys_restart_MDEP))
      || (ip == ML_(blksys_restart_UNIX));
   in_complete_to_committed
      =  (ip >= ML_(blksys_complete_MACH) && ip < ML_(blksys_committed_MACH))
      || (ip >= ML_(blksys_complete_MDEP) && ip < ML_(blksys_committed_MDEP))
      || (ip >= ML_(blksys_complete_UNIX) && ip < ML_(blksys_committed_UNIX));
   in_committed_to_finished
      =  (ip >= ML_(blksys_committed_MACH) && ip < ML_(blksys_finished_MACH))
      || (ip >= ML_(blksys_committed_MDEP) && ip < ML_(blksys_finished_MDEP))
      || (ip >= ML_(blksys_committed_UNIX) && ip < ML_(blksys_finished_UNIX));
   /* Wasn't that just So Much Fun?  Does your head hurt yet?  Mine does. */
#  elif defined(VGO_solaris)
   /* The solaris port is never outside the range. */
   outside_range = False;
   /* The Solaris kernel never restarts syscalls directly! */
   at_restart = False;
   if (tst->os_state.in_door_return) {
      vg_assert(ip >= ML_(blksys_setup_DRET)
                && ip < ML_(blksys_finished_DRET));

      in_setup_to_restart
         = ip >= ML_(blksys_setup_DRET) && ip < ML_(blksys_complete_DRET);
      in_complete_to_committed
         = ip >= ML_(blksys_complete_DRET) && ip < ML_(blksys_committed_DRET);
      in_committed_to_finished
         = ip >= ML_(blksys_committed_DRET) && ip < ML_(blksys_finished_DRET);
   }
   else {
      vg_assert(ip >= ML_(blksys_setup) && ip < ML_(blksys_finished));

      in_setup_to_restart
         = ip >= ML_(blksys_setup) && ip < ML_(blksys_complete);
      in_complete_to_committed
         = ip >= ML_(blksys_complete) && ip < ML_(blksys_committed);
      in_committed_to_finished
         = ip >= ML_(blksys_committed) && ip < ML_(blksys_finished);
   }
#  else
#    error "Unknown OS"
#  endif

   /* Figure out what the state of the syscall was by examining the
      (real) IP at the time of the signal, and act accordingly. */
   if (outside_range) {
      if (VG_(clo_trace_signals))
         VG_(message)( Vg_DebugMsg,
                       "  not in syscall at all: hmm, very suspicious\n" );
      /* Looks like we weren't in a syscall at all.  Hmm. */
      vg_assert(sci->status.what != SsIdle);
      return;
   }

   /* We should not be here unless this thread had first started up
      the machinery for a syscall by calling VG_(client_syscall).
      Hence: */
   vg_assert(sci->status.what != SsIdle);

   /* now, do one of four fixup actions, depending on where the IP has
      got to. */

   if (in_setup_to_restart) {
      /* syscall hasn't even started; go around again */
      if (VG_(clo_trace_signals))
         VG_(message)( Vg_DebugMsg, "  not started: restarting\n");
      vg_assert(sci->status.what == SsHandToKernel);
      ML_(fixup_guest_state_to_restart_syscall)(th_regs);
   } 

   else 
   if (at_restart) {
#     if defined(VGO_solaris)
      /* We should never hit this branch on Solaris, see the comment above. */
      vg_assert(0);
#     endif

      /* We're either about to run the syscall, or it was interrupted
         and the kernel restarted it.  Restart if asked, otherwise
         EINTR it. */
      if (restart) {
         if (VG_(clo_trace_signals))
            VG_(message)( Vg_DebugMsg, "  at syscall instr: restarting\n");
         ML_(fixup_guest_state_to_restart_syscall)(th_regs);
      } else {
         if (VG_(clo_trace_signals))
            VG_(message)( Vg_DebugMsg, "  at syscall instr: returning EINTR\n");
         canonical = convert_SysRes_to_SyscallStatus( 
                        VG_(mk_SysRes_Error)( VKI_EINTR ) 
                     );
         if (!(sci->flags & SfNoWriteResult))
            putSyscallStatusIntoGuestState( tid, &canonical, &th_regs->vex );
         sci->status = canonical;
         VG_(post_syscall)(tid);
      }
   }

   else 
   if (in_complete_to_committed) {
      /* Syscall complete, but result hasn't been written back yet.
         Write the SysRes we were supplied with back to the guest
         state. */
      if (VG_(clo_trace_signals))
         VG_(message)( Vg_DebugMsg,
                       "  completed, but uncommitted: committing\n");
      canonical = convert_SysRes_to_SyscallStatus( sres );
      vg_assert(!(sci->flags & SfNoWriteResult));
      putSyscallStatusIntoGuestState( tid, &canonical, &th_regs->vex );
#     if defined(VGO_solaris)
      if (tst->os_state.in_door_return) {
#        if defined(VGP_x86_solaris)
         /* Registers %esp and %ebp were also modified by the syscall. */
         tst->arch.vex.guest_ESP = uc->uc_mcontext.gregs[VKI_UESP];
         tst->arch.vex.guest_EBP = uc->uc_mcontext.gregs[VKI_EBP];
#        elif defined(VGP_amd64_solaris)
         tst->arch.vex.guest_RSP = uc->uc_mcontext.gregs[VKI_REG_RSP];
         tst->arch.vex.guest_RBP = uc->uc_mcontext.gregs[VKI_REG_RBP];
#        endif
      }
#     endif
      sci->status = canonical;
      VG_(post_syscall)(tid);
   } 

   else  
   if (in_committed_to_finished) {
      /* Result committed, but the signal mask has not been restored;
         we expect our caller (the signal handler) will have fixed
         this up. */
      if (VG_(clo_trace_signals))
         VG_(message)( Vg_DebugMsg,
                       "  completed and committed: nothing to do\n");
#     if defined(VGP_x86_solaris)
      /* The %eax and %edx values are committed but the carry flag is still
         uncommitted.  Save it now. */
      LibVEX_GuestX86_put_eflag_c(sr_isError(sres), &th_regs->vex);
#     elif defined(VGP_amd64_solaris)
      LibVEX_GuestAMD64_put_rflag_c(sr_isError(sres), &th_regs->vex);
#     endif
      getSyscallStatusFromGuestState( &sci->status, &th_regs->vex );
      vg_assert(sci->status.what == SsComplete);
      VG_(post_syscall)(tid);
   } 

   else
      VG_(core_panic)("?? strange syscall interrupt state?");

   /* In all cases, the syscall is now finished (even if we called
      ML_(fixup_guest_state_to_restart_syscall), since that just
      re-positions the guest's IP for another go at it).  So we need
      to record that fact. */
   sci->status.what = SsIdle;
}


#if defined(VGO_solaris)
/* Returns True if ip is inside a fixable syscall code in syscall-*-*.S.  This
   function can be called by a 'non-running' thread! */
Bool VG_(is_ip_in_blocking_syscall)(ThreadId tid, Addr ip)
{
   ThreadState *tst = VG_(get_ThreadState)(tid);

   if (tst->os_state.in_door_return)
      return ip >= ML_(blksys_setup_DRET) && ip < ML_(blksys_finished_DRET);
   else
      return ip >= ML_(blksys_setup) && ip < ML_(blksys_finished);
}
#endif


#if defined(VGO_darwin)
// Clean up after workq_ops(WQOPS_THREAD_RETURN) jumped to wqthread_hijack. 
// This is similar to VG_(fixup_guest_state_after_syscall_interrupted).
// This longjmps back to the scheduler.
void ML_(wqthread_continue_NORETURN)(ThreadId tid)
{
   ThreadState*     tst;
   SyscallInfo*     sci;

   VG_(acquire_BigLock)(tid, "wqthread_continue_NORETURN");

   PRINT("SYSCALL[%d,%u](%s) workq_ops() starting new workqueue item\n", 
         VG_(getpid)(), tid, VG_SYSNUM_STRING(__NR_workq_ops));

   vg_assert(VG_(is_valid_tid)(tid));
   vg_assert(tid >= 1 && tid < VG_N_THREADS);
   vg_assert(VG_(is_running_thread)(tid));

   tst     = VG_(get_ThreadState)(tid);
   sci     = & syscallInfo[tid];
   vg_assert(sci->status.what != SsIdle);
   vg_assert(tst->os_state.wq_jmpbuf_valid);  // check this BEFORE post_syscall

   // Pretend the syscall completed normally, but don't touch the thread state.
   sci->status = convert_SysRes_to_SyscallStatus( VG_(mk_SysRes_Success)(0) );
   sci->flags |= SfNoWriteResult;
   VG_(post_syscall)(tid);

   ML_(sync_mappings)("in", "ML_(wqthread_continue_NORETURN)", 0);

   sci->status.what = SsIdle;

   vg_assert(tst->sched_jmpbuf_valid);
   VG_MINIMAL_LONGJMP(tst->sched_jmpbuf);

   /* NOTREACHED */
   vg_assert(0);
}
#endif


/* ---------------------------------------------------------------------
   A place to store the where-to-call-when-really-done pointer
   ------------------------------------------------------------------ */

// When the final thread is done, where shall I call to shutdown the
// system cleanly?  Is set once at startup (in m_main) and never
// changes after that.  Is basically a pointer to the exit
// continuation.  This is all just a nasty hack to avoid calling
// directly from m_syswrap to m_main at exit, since that would cause
// m_main to become part of a module cycle, which is silly.
void (* VG_(address_of_m_main_shutdown_actions_NORETURN) )
       (ThreadId,VgSchedReturnCode)
   = NULL;

/*--------------------------------------------------------------------*/
/*--- end                                                          ---*/
/*--------------------------------------------------------------------*/