aboutsummaryrefslogtreecommitdiff
path: root/coregrind/m_syswrap/syswrap-solaris.c
blob: 216e53c69ee46a492339dc5505ea1148fa9644bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
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
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541

/*--------------------------------------------------------------------*/
/*--- Solaris-specific syscalls, etc.            syswrap-solaris.c ---*/
/*--------------------------------------------------------------------*/

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

   Copyright (C) 2011-2015 Petr Pavlu
      setup@dagobah.cz

   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.
*/

/* Copyright 2013-2015, Ivo Raisr <ivosh@ivosh.net>. */

/* Copyright 2015-2015, Tomas Jedlicka <jedlickat@gmail.com>. */

/* Copyright 2013, OmniTI Computer Consulting, Inc. All rights reserved. */

#if defined(VGO_solaris)

#include "libvex_guest_offsets.h"
#include "pub_core_basics.h"
#include "pub_core_vki.h"
#include "pub_core_vkiscnums.h"
#include "pub_core_threadstate.h"
#include "pub_core_aspacemgr.h"
#include "pub_core_debuginfo.h"         // VG_(di_notify_*)
#include "pub_core_debuglog.h"
#include "pub_core_clientstate.h"
#include "pub_core_gdbserver.h"
#include "pub_core_inner.h"
#include "pub_core_libcassert.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcfile.h"
#include "pub_core_libcprint.h"
#include "pub_core_libcproc.h"
#include "pub_core_libcsignal.h"
#include "pub_core_machine.h"           // VG_(get_SP)
#include "pub_core_mallocfree.h"
#include "pub_core_options.h"
#include "pub_core_tooliface.h"
#include "pub_core_transtab.h"          // VG_(discard_translations)
#include "pub_core_scheduler.h"
#include "pub_core_sigframe.h"
#include "pub_core_signals.h"
#include "pub_core_stacks.h"
#include "pub_core_syscall.h"
#include "pub_core_syswrap.h"
#include "pub_core_ume.h"
#if defined(ENABLE_INNER_CLIENT_REQUEST)
#include "pub_core_clreq.h"
#endif

#include "priv_types_n_macros.h"
#include "priv_syswrap-generic.h"
#include "priv_syswrap-solaris.h"

/* Return the number of non-dead and daemon threads.
   count_daemon == True:  count daemon threads
   count_daemon == False: count non-daemon threads */
static UInt count_living_daemon_threads(Bool count_daemon)
{
   UInt count = 0;
   for (ThreadId tid = 1; tid < VG_N_THREADS; tid++)
      if (VG_(threads)[tid].status != VgTs_Empty &&
         VG_(threads)[tid].status != VgTs_Zombie &&
         VG_(threads)[tid].os_state.daemon_thread == count_daemon)
         count++;

   return count;
}

/* Note: The following functions (thread_wrapper, run_a_thread_NORETURN,
   ML_(start_thread_NORETURN), ML_(allocstack) and
   VG_(main_thread_wrapper_NORETURN)) are based on the code in
   syswrap-linux.c.  Keep them synchronized! */

/* Run a thread from beginning to end and return the thread's
   scheduler-return-code. */
static VgSchedReturnCode thread_wrapper(Word /*ThreadId*/ tidW)
{
   VgSchedReturnCode ret;
   ThreadId tid = (ThreadId)tidW;
   ThreadState *tst = VG_(get_ThreadState)(tid);

   VG_(debugLog)(1, "syswrap-solaris",
                    "thread_wrapper(tid=%u): entry\n",
                    tid);

   vg_assert(tst->status == VgTs_Init);

   /* Make sure we get the CPU lock before doing anything significant. */
   VG_(acquire_BigLock)(tid, "thread_wrapper(starting new thread)");

   if (0)
     VG_(printf)("thread tid %u started: stack = %p\n", tid, (void *)&tid);

   /* Make sure error reporting is enabled in the new thread. */
   tst->err_disablement_level = 0;

   if (tid == 1)
      VG_TRACK(pre_thread_first_insn, tid);
   else {
      /* For newly created threads, VG_TRACK(pre_thread_first_insn, tid) is
         invoked later from PRE(sys_getsetcontext)() when setucontext()
         called from _thrp_setup() concludes new thread setup. Invoking it
         here would be way too early - new thread has no stack, yet. */
   }

   tst->os_state.lwpid = VG_(gettid)();
   tst->os_state.threadgroup = VG_(getpid)();

   /* Thread created with all signals blocked; scheduler will set the
      appropriate mask. */

   ret = VG_(scheduler)(tid);

   vg_assert(VG_(is_exiting)(tid));

   vg_assert(tst->status == VgTs_Runnable);
   vg_assert(VG_(is_running_thread)(tid));

   VG_(debugLog)(1, "syswrap-solaris",
                    "thread_wrapper(tid=%u): exit, schedreturncode %s\n",
                    tid, VG_(name_of_VgSchedReturnCode)(ret));

   /* Return to caller, still holding the lock. */
   return ret;
}

/* Run a thread all the way to the end, then do appropriate exit actions
   (this is the last-one-out-turn-off-the-lights bit). */
static void run_a_thread_NORETURN(Word tidW)
{
   ThreadId tid = (ThreadId)tidW;
   VgSchedReturnCode src;
   Int c;
   ThreadState *tst;
#ifdef ENABLE_INNER_CLIENT_REQUEST
   Int registered_vgstack_id;
#endif

   VG_(debugLog)(1, "syswrap-solaris",
                    "run_a_thread_NORETURN(tid=%u): pre-thread_wrapper\n",
                    tid);

   tst = VG_(get_ThreadState)(tid);
   vg_assert(tst);

   /* A thread has two stacks:
      * the simulated stack (used by the synthetic cpu. Guest process
        is using this stack).
      * the valgrind stack (used by the real cpu. Valgrind code is running
        on this stack).
      When Valgrind runs as an inner, it must signal that its (real) stack
      is the stack to use by the outer to e.g. do stacktraces.
   */
   INNER_REQUEST
      (registered_vgstack_id
       = VALGRIND_STACK_REGISTER(tst->os_state.valgrind_stack_base,
                                 tst->os_state.valgrind_stack_init_SP));

   /* Run the thread all the way through. */
   src = thread_wrapper(tid);

   VG_(debugLog)(1, "syswrap-solaris",
                    "run_a_thread_NORETURN(tid=%u): post-thread_wrapper\n",
                    tid);

   c = count_living_daemon_threads(False);
   vg_assert(c >= 1); /* Stay sane. */

   /* Tell the tool that schedctl data belonging to this thread are gone. */
   Addr a = tst->os_state.schedctl_data;
   if (a != 0)
      VG_TRACK(die_mem_munmap, a, sizeof(struct vki_sc_shared));

   /* Deregister thread's stack. */
   if (tst->os_state.stk_id != (UWord)-1)
      VG_(deregister_stack)(tst->os_state.stk_id);

   /* Tell the tool this thread is exiting. */
   VG_TRACK(pre_thread_ll_exit, tid);

   /* If the thread is exiting with errors disabled, complain loudly;
      doing so is bad (does the user know this has happened?)  Also, in all
      cases, be paranoid and clear the flag anyway so that the thread slot is
      safe in this respect if later reallocated.  This should be unnecessary
      since the flag should be cleared when the slot is reallocated, in
      thread_wrapper(). */
   if (tst->err_disablement_level > 0) {
      VG_(umsg)(
         "WARNING: exiting thread has error reporting disabled.\n"
         "WARNING: possibly as a result of some mistake in the use\n"
         "WARNING: of the VALGRIND_DISABLE_ERROR_REPORTING macros.\n"
      );
      VG_(debugLog)(
         1, "syswrap-solaris",
            "run_a_thread_NORETURN(tid=%u): "
            "WARNING: exiting thread has err_disablement_level = %u\n",
            tid, tst->err_disablement_level
      );
   }
   tst->err_disablement_level = 0;

   if (c == 1) {
      UInt daemon_threads = count_living_daemon_threads(True);
      if (daemon_threads == 0)
         VG_(debugLog)(1, "syswrap-solaris",
                          "run_a_thread_NORETURN(tid=%u): "
                          "last one standing\n",
                          tid);
      else
         VG_(debugLog)(1, "syswrap-solaris",
                          "run_a_thread_NORETURN(tid=%u): "
                          "last non-daemon thread standing "
                          "[daemon threads=%u]\n",
                          tid, daemon_threads);

      /* We are the last non-daemon thread standing. Keep hold of the lock and
         carry on to show final tool results, then exit the entire system.
         Use the continuation pointer set at startup in m_main. */
      if ((src == VgSrc_ExitThread) && (daemon_threads > 0))
         src = VgSrc_ExitProcess;
      (*VG_(address_of_m_main_shutdown_actions_NORETURN))(tid, src);
   }
   else {
      VG_(debugLog)(1, "syswrap-solaris",
                       "run_a_thread_NORETURN(tid=%u): "
                       "not last one standing\n",
                       tid);

      /* OK, thread is dead, but others still exist.  Just exit. */

      /* This releases the run lock. */
      VG_(exit_thread)(tid);
      vg_assert(tst->status == VgTs_Zombie);
      vg_assert(sizeof(tst->status) == 4);

      INNER_REQUEST(VALGRIND_STACK_DEREGISTER(registered_vgstack_id));

      /* We have to use this sequence to terminate the thread to
         prevent a subtle race.  If VG_(exit_thread)() had left the
         ThreadState as Empty, then it could have been reallocated, reusing
         the stack while we're doing these last cleanups.  Instead,
         VG_(exit_thread) leaves it as Zombie to prevent reallocation.  We
         need to make sure we don't touch the stack between marking it Empty
         and exiting.  Hence the assembler. */
#if defined(VGP_x86_solaris)
      /* Luckily lwp_exit doesn't take any arguments so we don't have to mess
         with the stack. */
      __asm__ __volatile__ (
         "movl  %[EMPTY], %[status]\n"  /* set tst->status = VgTs_Empty */
         "movl  $"VG_STRINGIFY(__NR_lwp_exit)", %%eax\n"
         "int   $0x91\n"                /* lwp_exit() */
         : [status] "=m" (tst->status)
         : [EMPTY] "n" (VgTs_Empty)
         : "eax", "edx", "cc", "memory");
#elif defined(VGP_amd64_solaris)
      __asm__ __volatile__ (
         "movl  %[EMPTY], %[status]\n"  /* set tst->status = VgTs_Empty */
         "movq  $"VG_STRINGIFY(__NR_lwp_exit)", %%rax\n"
         "syscall\n"                    /* lwp_exit() */
         : [status] "=m" (tst->status)
         : [EMPTY] "n" (VgTs_Empty)
         : "rax", "rdx", "cc", "memory");
#else
#  error "Unknown platform"
#endif

      VG_(core_panic)("Thread exit failed?\n");
   }

   /*NOTREACHED*/
   vg_assert(0);
}

Word ML_(start_thread_NORETURN)(void *arg)
{
   ThreadState *tst = (ThreadState*)arg;
   ThreadId tid = tst->tid;

   run_a_thread_NORETURN((Word)tid);
   /*NOTREACHED*/
   vg_assert(0);
}

/* Allocate a stack for this thread, if it doesn't already have one.
   They're allocated lazily, and never freed.  Returns the initial stack
   pointer value to use, or 0 if allocation failed. */
Addr ML_(allocstack)(ThreadId tid)
{
   ThreadState *tst = VG_(get_ThreadState)(tid);
   VgStack *stack;
   Addr initial_SP;

   /* Either the stack_base and stack_init_SP are both zero (in which
      case a stack hasn't been allocated) or they are both non-zero,
      in which case it has. */

   if (tst->os_state.valgrind_stack_base == 0)
      vg_assert(tst->os_state.valgrind_stack_init_SP == 0);

   if (tst->os_state.valgrind_stack_base != 0)
      vg_assert(tst->os_state.valgrind_stack_init_SP != 0);

   /* If no stack is present, allocate one. */

   if (tst->os_state.valgrind_stack_base == 0) {
      stack = VG_(am_alloc_VgStack)( &initial_SP );
      if (stack) {
         tst->os_state.valgrind_stack_base = (Addr)stack;
         tst->os_state.valgrind_stack_init_SP = initial_SP;
      }
   }

   if (0)
      VG_(printf)("stack for tid %u at %p; init_SP=%p\n",
                  tid,
                  (void*)tst->os_state.valgrind_stack_base,
                  (void*)tst->os_state.valgrind_stack_init_SP);

   return tst->os_state.valgrind_stack_init_SP;
}

/* Allocate a stack for the main thread, and run it all the way to the
   end.  Although we already have a working VgStack (VG_(interim_stack)) it's
   better to allocate a new one, so that overflow detection works uniformly
   for all threads.  Also initialize the GDT (for normal threads, this is done
   in the PRE wrapper of lwp_create). */
void VG_(main_thread_wrapper_NORETURN)(ThreadId tid)
{
   Addr sp;

   VG_(debugLog)(1, "syswrap-solaris",
                    "entering VG_(main_thread_wrapper_NORETURN)\n");

   sp = ML_(allocstack)(tid);
#if defined(ENABLE_INNER_CLIENT_REQUEST)
   {
      // we must register the main thread stack before the call
      // to ML_(call_on_new_stack_0_1), otherwise the outer valgrind
      // reports 'write error' on the non registered stack.
      ThreadState *tst = VG_(get_ThreadState)(tid);
      INNER_REQUEST
         ((void) 
          VALGRIND_STACK_REGISTER(tst->os_state.valgrind_stack_base,
                                  tst->os_state.valgrind_stack_init_SP));
   }
#endif

#if defined(VGP_x86_solaris)
   {
      ThreadState *tst = VG_(get_ThreadState)(tid);
      ML_(setup_gdt)(&tst->arch.vex);
      ML_(update_gdt_lwpgs)(tid);
   }
#elif defined(VGP_amd64_solaris)
   /* Nothing to do. */
#else
#  error "Unknown platform"
#endif

   /* If we can't even allocate the first thread's stack, we're hosed.
      Give up. */
   vg_assert2(sp != 0, "Cannot allocate main thread's stack.");

   /* Shouldn't be any other threads around yet. */
   vg_assert(VG_(count_living_threads)() == 1);

   ML_(call_on_new_stack_0_1)(
      (Addr)sp,               /* stack */
      0,                      /* bogus return address */
      run_a_thread_NORETURN,  /* fn to call */
      (Word)tid               /* arg to give it */
   );

   /*NOTREACHED*/
   vg_assert(0);
}

/* Deallocate the GDT for a thread. */
void VG_(cleanup_thread)(ThreadArchState *arch)
{
#if defined(VGP_x86_solaris)
   ML_(cleanup_gdt)(&arch->vex);
#elif defined(VGP_amd64_solaris)
   /* Nothing to do. */
#else
#  error "Unknown platform"
#endif
}

/*
 * Notify core about spring cleaning of schedctl data pages for all threads
 * in child post-fork handler. Libc will issue new schedctl syscalls for threads
 * in the child when needs arise.
 *
 * See also POST(schedctl) and run_a_thread_NORETURN() when a thread exits.
 */
static void clean_schedctl_data(ThreadId tid)
{
   UInt i;
   for (i = 0; i < VG_N_THREADS; i++) {
      ThreadState *tst = &VG_(threads)[i];
      if (tst->status != VgTs_Empty) {
         Addr a = tst->os_state.schedctl_data;
         if (a != 0) {
            tst->os_state.schedctl_data = 0;
            a = VG_PGROUNDDN(a);
            if (VG_(am_find_anon_segment(a)))
               VG_(am_notify_munmap)(a, VKI_PAGE_SIZE);
         }
      }
   }
}

void VG_(syswrap_init)(void)
{
   VG_(atfork)(NULL, NULL, clean_schedctl_data);
}

/* Changes ownership of a memory mapping shared between kernel and the client
   process. This mapping should have already been pre-arranged during process
   address space initialization happening in kernel. Valgrind on startup created
   a segment for this mapping categorized as Valgrind's owned anonymous.
   Size of this mapping typically varies among Solaris versions but should be
   page aligned.
   If 'once_only' is 'True', it is expected this function is called once only
   and the mapping ownership has not been changed, yet [useful during
   initialization]. If 'False', this function can be called many times but does
   change ownership only upon the first invocation [useful in syscall wrappers].
 */
void VG_(change_mapping_ownership)(Addr addr, Bool once_only)
{
   const NSegment *seg = VG_(am_find_anon_segment)(addr);
   vg_assert(seg != NULL);
   vg_assert(seg->start == addr);
   vg_assert(VG_IS_PAGE_ALIGNED(seg->start));
   vg_assert(VG_IS_PAGE_ALIGNED(seg->end + 1));
   SizeT size = seg->end - seg->start + 1;
   vg_assert(size > 0);

   Bool do_change = False;
   if (once_only) {
      vg_assert(VG_(am_is_valid_for_valgrind)(addr, size, VKI_PROT_READ));
      do_change = True;
   } else {
      if (!VG_(am_is_valid_for_client)(addr, size, VKI_PROT_READ))
         do_change = True;
   }

   if (do_change) {
      Bool change_ownership_OK = VG_(am_change_ownership_v_to_c)(addr, size);
      vg_assert(change_ownership_OK);

      /* Tell the tool about just discovered mapping. */
      VG_TRACK(new_mem_startup,
               addr, size,
               True  /* readable? */,
               False /* writable? */,
               False /* executable? */,
               0     /* di_handle */);
   }
}

/* Calculate the Fletcher-32 checksum of a given buffer. */
UInt ML_(fletcher32)(UShort *buf, SizeT blocks)
{
   UInt sum1 = 0;
   UInt sum2 = 0;
   SizeT i;

   for (i = 0; i < blocks; i++) {
      sum1 = (sum1 + buf[i]) % 0xffff;
      sum2 = (sum2 + sum1) % 0xffff;
   }

   return (sum2 << 16) | sum1;
}

/* Calculate the Fletcher-64 checksum of a given buffer. */
ULong ML_(fletcher64)(UInt *buf, SizeT blocks)
{
   ULong sum1 = 0;
   ULong sum2 = 0;
   SizeT i;

   for (i = 0; i < blocks; i++) {
      sum1 = (sum1 + buf[i]) % 0xffffffff;
      sum2 = (sum2 + sum1) % 0xffffffff;
   }
   return (sum2 << 32) | sum1;
}

/* Save a complete context (VCPU state, sigmask) of a given client thread
   into the vki_ucontext_t structure.  This structure is supposed to be
   allocated in the client memory, a caller must make sure that the memory can
   be dereferenced.  The active tool is informed about the save. */
void VG_(save_context)(ThreadId tid, vki_ucontext_t *uc, CorePart part)
{
   ThreadState *tst = VG_(get_ThreadState)(tid);

   VG_TRACK(pre_mem_write, part, tid, "save_context(uc)", (Addr)uc,
            sizeof(*uc));

   uc->uc_flags = VKI_UC_ALL;
   VG_TRACK(post_mem_write, part, tid, (Addr)&uc->uc_flags,
            sizeof(uc->uc_flags));

   /* Old context */
   uc->uc_link = tst->os_state.oldcontext;
   VG_TRACK(post_mem_write, part, tid, (Addr)&uc->uc_link,
            sizeof(uc->uc_link));

   /* Clear uc->vki_uc_signo.  This slot is used by the signal machinery to
      store a signal number. */
   VKI_UC_SIGNO(uc) = 0;

   /* Sigmask */
   uc->uc_sigmask = tst->sig_mask;
   VG_TRACK(post_mem_write, part, tid, (Addr)&uc->uc_sigmask,
            sizeof(uc->uc_sigmask));

   /* Stack */
   {
      if (tst->os_state.ustack
          && ML_(safe_to_deref)(tst->os_state.ustack, sizeof(vki_stack_t))
          && tst->os_state.ustack->ss_size) {
         /* If ustack points to a valid stack copy it to ucontext. */
         uc->uc_stack = *tst->os_state.ustack;
      }
      else {
         /* Ustack is not valid.  A correct stack has to be figured out
            manually. */
         SysRes res;
         vki_stack_t altstack;

         /* Get information about alternate stack. */
         res = VG_(do_sys_sigaltstack)(tid, NULL, &altstack);
         vg_assert(!sr_isError(res));

         if (altstack.ss_flags == VKI_SS_ONSTACK) {
            /* If the alternate stack is active copy it to ucontext. */
            uc->uc_stack = altstack;
         }
         else {
            /* No information about stack is present, save information about
               current main stack to ucontext.  This branch should be reached
               only by the main thread. */
            ThreadState *tst2 = VG_(get_ThreadState)(1);
            uc->uc_stack.ss_sp = (void*)(tst2->client_stack_highest_byte + 1
                                         - tst2->client_stack_szB);
            uc->uc_stack.ss_size = tst2->client_stack_szB;
            uc->uc_stack.ss_flags = 0;
         }
      }

      VG_TRACK(post_mem_write, part, tid, (Addr)&uc->uc_stack,
               sizeof(uc->uc_stack));
   }

   /* Save the architecture-specific part of the context. */
   ML_(save_machine_context)(tid, uc, part);
}

/* Set a complete context (VCPU state, sigmask) of a given client thread
   according to values passed in the vki_ucontext_t structure.  This structure
   is supposed to be allocated in the client memory, a caller must make sure
   that the memory can be dereferenced.  The active tool is informed about
   what parts of the structure are read.

   This function is a counterpart to VG_(save_context)(). */
void VG_(restore_context)(ThreadId tid, vki_ucontext_t *uc, CorePart part,
                          Bool esp_is_thrptr)
{
   ThreadState *tst = VG_(get_ThreadState)(tid);
   Addr old_esp = VG_(get_SP)(tid);

   VG_TRACK(pre_mem_read, part, tid, "restore_context(uc->uc_flags)",
            (Addr)&uc->uc_flags, sizeof(uc->uc_flags));

   /* Old context */
   VG_TRACK(pre_mem_read, part, tid, "restore_context(uc->uc_link)",
            (Addr)&uc->uc_link, sizeof(uc->uc_link));
   tst->os_state.oldcontext = uc->uc_link;

   /* Sigmask */
   if (uc->uc_flags & VKI_UC_SIGMASK) {
      SysRes res;

      VG_TRACK(pre_mem_read, part, tid, "restore_context(uc->uc_sigmask)",
               (Addr)&uc->uc_sigmask, sizeof(uc->uc_sigmask));
      res = VG_(do_sys_sigprocmask)(tid, VKI_SIG_SETMASK, &uc->uc_sigmask,
                                    NULL);
      /* Setting signal mask should never fail. */
      vg_assert(!sr_isError(res));
   }

   /* Stack */
   if (uc->uc_flags & VKI_UC_STACK) {
      VG_TRACK(pre_mem_read, part, tid, "restore_context(uc->uc_stack)",
               (Addr)&uc->uc_stack, sizeof(uc->uc_stack));

      if (uc->uc_stack.ss_flags == VKI_SS_ONSTACK) {
         /* This seems to be a little bit dangerous but it is what the kernel
            does. */
         if (VG_(clo_trace_signals))
            VG_(dmsg)("restore_context, sigaltstack: tid %u, "
                      "ss %p{%p,sz=%lu,flags=%#x}\n",
                      tid, &uc->uc_stack, uc->uc_stack.ss_sp,
                      (SizeT)uc->uc_stack.ss_size, uc->uc_stack.ss_flags);

         tst->altstack.ss_sp = uc->uc_stack.ss_sp;
         tst->altstack.ss_size = uc->uc_stack.ss_size;
         /* Do not copy ss_flags, they are calculated dynamically by
            Valgrind. */
      }

      /* Copyout the new stack. */
      if (tst->os_state.ustack
          && VG_(am_is_valid_for_client)((Addr)tst->os_state.ustack,
                                         sizeof(*tst->os_state.ustack),
                                         VKI_PROT_WRITE))
         *tst->os_state.ustack = uc->uc_stack;
         VG_TRACK(post_mem_write, part, tid, (Addr)&tst->os_state.ustack,
                  sizeof(tst->os_state.ustack));
   }

   /* Restore the architecture-specific part of the context. */
   ML_(restore_machine_context)(tid, uc, part, esp_is_thrptr);

   /* If the thread stack is already known, kill the deallocated stack area.
      This is important when returning from a signal handler. */
   if (tst->client_stack_highest_byte && tst->client_stack_szB) {
      Addr end = tst->client_stack_highest_byte;
      Addr start = end + 1 - tst->client_stack_szB;
      Addr new_esp = VG_(get_SP)(tid);

      /* Make sure that the old and new stack pointer are on the same (active)
         stack.  Alternate stack is currently never affected by this code. */
      if (start <= old_esp && old_esp <= end
          && start <= new_esp && new_esp <= end
          && new_esp > old_esp)
         VG_TRACK(die_mem_stack, old_esp - VG_STACK_REDZONE_SZB,
                  (new_esp - old_esp) + VG_STACK_REDZONE_SZB);
   }
}

/* Set a client stack associated with a given thread id according to values
   passed in the vki_stack_t structure. */
static void set_stack(ThreadId tid, vki_stack_t *st)
{
   ThreadState *tst = VG_(get_ThreadState)(tid);
   Addr new_start, new_end;
   SizeT new_size;
   Addr cur_start;
   SizeT cur_size;

   VG_(debugLog)(2, "syswrap-solaris",
                    "set stack: sp=%#lx, size=%#lx.\n",
                    (Addr)st->ss_sp, (SizeT)st->ss_size);

   /* Stay sane. */
   vg_assert(st->ss_flags == 0);

   new_start = (Addr)st->ss_sp;
   new_end = new_start + st->ss_size - 1;
   new_size = st->ss_size;
   cur_start = tst->client_stack_highest_byte + 1
               - tst->client_stack_szB;
   cur_size = tst->client_stack_szB;

   if (new_start == cur_start && new_size == cur_size) {
      /* No change is requested, bail out. */
      return;
   }

   if (tid == 1 && (new_size == 0 || new_size > VG_(clstk_max_size))) {
      /* The main thread requests to use a stack without any size checking, or
         too big stack.  Fallback to the maximum allocated client stack. */

      /* TODO I think it is possible to give up on setting main stack anyway.
         Valgrind knows where it is located and it is already registered as
         VG_(clstk_id). */

      new_size = VG_(clstk_max_size);
      new_end = tst->client_stack_highest_byte;
      new_start = new_end + 1 - new_size;
   }

   if (tst->os_state.stk_id == (UWord)-1) {
      /* This thread doesn't have a stack set yet. */
      VG_(debugLog)(2, "syswrap-solaris",
                       "Stack set to %#lx-%#lx (new) for thread %u.\n",
                       new_start, new_end, tid);
      tst->os_state.stk_id = VG_(register_stack)(new_start, new_end);
   }
   else {
      /* Change a thread stack. */
      VG_(debugLog)(2, "syswrap-solaris",
                       "Stack set to %#lx-%#lx (change) for thread %u.\n",
                       new_start, new_end, tid);
      VG_(change_stack)(tst->os_state.stk_id, new_start, new_end);
   }
   tst->client_stack_highest_byte = new_end;
   tst->client_stack_szB = new_size;
}

/* ---------------------------------------------------------------------
   Door tracking. Used mainly for server side where door_return()
   parameters alone do not contain sufficient information.
   Also used on client side when new door descriptors are passed via
   door_call() in desc_ptr. Not used for tracking door descriptors
   explicitly open()'ed [generic fd tracking is used in that case].
   ------------------------------------------------------------------ */

/* One of these is allocated for each created door. */
typedef struct OpenDoor
{
   Bool server; /* TRUE = server door, FALSE = client door */
   Int fd;      /* The file descriptor. */
   union {
      /* Server side. */
      struct {
         Addr server_procedure;  /* The door server procedure. */
         HChar *pathname;        /* NULL if unknown. */
      };
      /* Client side. */
      struct {
         /* Hook called during PRE door_call()
            to check contents of params->data_ptr. */
         void (*pre_mem_hook)(ThreadId tid, Int fd,
                              void *data_ptr, SizeT data_size);
         /* Hook called during POST door_call()
            to define contents of params->rbuf. */
         void (*post_mem_hook)(ThreadId tid, Int fd,
                               void *rbuf, SizeT rsize);
      };
   };
   struct OpenDoor *next, *prev;
} OpenDoor;

/* List of allocated door fds. */
static OpenDoor *doors_recorded = NULL;
static UInt nr_doors_recorded = 0;

static OpenDoor *door_record_create(void)
{
   OpenDoor *d = VG_(malloc)("syswrap.door_record_create.1", sizeof(OpenDoor));
   d->prev = NULL;
   d->next = doors_recorded;
   if (doors_recorded != NULL)
      doors_recorded->prev = d;
   doors_recorded = d;
   nr_doors_recorded += 1;

   return d;
}

/* Records a server door. */
static void door_record_server(ThreadId tid, Addr server_procedure, Int fd)
{
   OpenDoor *d = doors_recorded;

   while (d != NULL) {
      if ((d->server == TRUE) && (d->server_procedure == server_procedure)) {
         if (d->pathname) {
            VG_(free)(d->pathname);
         }
         break;
      }
      d = d->next;
   }

   if (d == NULL)
      d = door_record_create();
   vg_assert(d != NULL);

   d->server = TRUE;
   d->fd = fd;
   d->server_procedure = server_procedure;
   d->pathname = NULL;
}

/* Records a client door. */
static void door_record_client(ThreadId tid, Int fd,
   void (*pre_mem_hook)(ThreadId tid, Int fd, void *data_ptr, SizeT data_size),
   void (*post_mem_hook)(ThreadId tid, Int fd, void *rbuf, SizeT rsize))
{
   OpenDoor *d = doors_recorded;

   while (d != NULL) {
      if ((d->server == FALSE) && (d->fd == fd))
         break;
      d = d->next;
   }

   if (d == NULL)
      d = door_record_create();
   vg_assert(d != NULL);

   d->server = FALSE;
   d->fd = fd;
   d->pre_mem_hook = pre_mem_hook;
   d->post_mem_hook = post_mem_hook;
}

/* Revokes an open door, be it server side or client side. */
static void door_revoke(ThreadId tid, Int fd)
{
   OpenDoor *d = doors_recorded;

   while (d != NULL) {
      if (d->fd == fd) {
         if (d->prev != NULL)
            d->prev->next = d->next;
         else
            doors_recorded = d->next;
         if (d->next != NULL)
            d->next->prev = d->prev;

         if ((d->server == TRUE) && (d->pathname != NULL))
            VG_(free)(d->pathname);
         VG_(free)(d);
         nr_doors_recorded -= 1;
         return;
      }
      d = d->next;
   }
}

/* Attaches a server door to a filename. */
static void door_server_fattach(Int fd, HChar *pathname)
{
   OpenDoor *d = doors_recorded;

   while (d != NULL) {
      if (d->fd == fd) {
         vg_assert(d->server == TRUE);

         if (d->pathname != NULL)
            VG_(free)(d->pathname);
         d->pathname = VG_(strdup)("syswrap.door_server_fattach.1", pathname);
         return;
      }
      d = d->next;
   }
}

/* Finds a server door based on server procedure. */
static const OpenDoor *door_find_by_proc(Addr server_procedure)
{
   OpenDoor *d = doors_recorded;

   while (d != NULL) {
      if ((d->server) && (d->server_procedure == server_procedure))
         return d;
      d = d->next;
   }

   return NULL;
}

/* Finds a client door based on fd. */
static const OpenDoor *door_find_by_fd(Int fd)
{
   OpenDoor *d = doors_recorded;

   while (d != NULL) {
      if ((d->server == FALSE) && (d->fd == fd))
         return d;
      d = d->next;
   }

   return NULL;
}

/* ---------------------------------------------------------------------
   PRE/POST wrappers for Solaris-specific syscalls
   ------------------------------------------------------------------ */

#define PRE(name)       DEFN_PRE_TEMPLATE(solaris, name)
#define POST(name)      DEFN_POST_TEMPLATE(solaris, name)

/* prototypes */
DECL_TEMPLATE(solaris, sys_exit);
#if defined(SOLARIS_SPAWN_SYSCALL)
DECL_TEMPLATE(solaris, sys_spawn);
#endif /* SOLARIS_SPAWN_SYSCALL */
#if defined(SOLARIS_OLD_SYSCALLS)
DECL_TEMPLATE(solaris, sys_open);
#endif /* SOLARIS_OLD_SYSCALLS */
DECL_TEMPLATE(solaris, sys_close);
DECL_TEMPLATE(solaris, sys_linkat);
DECL_TEMPLATE(solaris, sys_symlinkat);
DECL_TEMPLATE(solaris, sys_time);
DECL_TEMPLATE(solaris, sys_brk);
DECL_TEMPLATE(solaris, sys_stat);
DECL_TEMPLATE(solaris, sys_lseek);
DECL_TEMPLATE(solaris, sys_mount);
DECL_TEMPLATE(solaris, sys_readlinkat);
DECL_TEMPLATE(solaris, sys_stime);
DECL_TEMPLATE(solaris, sys_fstat);
#if defined(SOLARIS_FREALPATHAT_SYSCALL)
DECL_TEMPLATE(solaris, sys_frealpathat);
#endif /* SOLARIS_FREALPATHAT_SYSCALL */
DECL_TEMPLATE(solaris, sys_stty);
DECL_TEMPLATE(solaris, sys_gtty);
DECL_TEMPLATE(solaris, sys_pgrpsys);
DECL_TEMPLATE(solaris, sys_pipe);
DECL_TEMPLATE(solaris, sys_faccessat);
DECL_TEMPLATE(solaris, sys_mknodat);
DECL_TEMPLATE(solaris, sys_sysi86);
DECL_TEMPLATE(solaris, sys_shmsys);
DECL_TEMPLATE(solaris, sys_semsys);
DECL_TEMPLATE(solaris, sys_ioctl);
DECL_TEMPLATE(solaris, sys_fchownat);
DECL_TEMPLATE(solaris, sys_fdsync);
DECL_TEMPLATE(solaris, sys_execve);
DECL_TEMPLATE(solaris, sys_fcntl);
DECL_TEMPLATE(solaris, sys_renameat);
DECL_TEMPLATE(solaris, sys_unlinkat);
DECL_TEMPLATE(solaris, sys_fstatat);
DECL_TEMPLATE(solaris, sys_openat);
DECL_TEMPLATE(solaris, sys_tasksys);
DECL_TEMPLATE(solaris, sys_getpagesizes);
DECL_TEMPLATE(solaris, sys_lwp_park);
DECL_TEMPLATE(solaris, sys_sendfilev);
#if defined(SOLARIS_LWP_NAME_SYSCALL)
DECL_TEMPLATE(solaris, sys_lwp_name);
#endif /* SOLARIS_LWP_NAME_SYSCALL */
DECL_TEMPLATE(solaris, sys_privsys);
DECL_TEMPLATE(solaris, sys_ucredsys);
DECL_TEMPLATE(solaris, sys_getmsg);
DECL_TEMPLATE(solaris, sys_putmsg);
DECL_TEMPLATE(solaris, sys_lstat);
DECL_TEMPLATE(solaris, sys_sigprocmask);
DECL_TEMPLATE(solaris, sys_sigaction);
DECL_TEMPLATE(solaris, sys_sigpending);
DECL_TEMPLATE(solaris, sys_getsetcontext);
DECL_TEMPLATE(solaris, sys_fchmodat);
DECL_TEMPLATE(solaris, sys_mkdirat);
DECL_TEMPLATE(solaris, sys_statvfs);
DECL_TEMPLATE(solaris, sys_fstatvfs);
DECL_TEMPLATE(solaris, sys_nfssys);
DECL_TEMPLATE(solaris, sys_waitid);
#if defined(SOLARIS_UTIMESYS_SYSCALL)
DECL_TEMPLATE(solaris, sys_utimesys);
#endif /* SOLARIS_UTIMESYS_SYSCALL */
#if defined(SOLARIS_UTIMENSAT_SYSCALL)
DECL_TEMPLATE(solaris, sys_utimensat);
#endif /* SOLARIS_UTIMENSAT_SYSCALL */
DECL_TEMPLATE(solaris, sys_sigresend);
DECL_TEMPLATE(solaris, sys_priocntlsys);
DECL_TEMPLATE(solaris, sys_pathconf);
DECL_TEMPLATE(solaris, sys_mmap);
#if defined(SOLARIS_UUIDSYS_SYSCALL)
DECL_TEMPLATE(solaris, sys_uuidsys);
#endif /* SOLARIS_UUIDSYS_SYSCALL */
DECL_TEMPLATE(solaris, sys_mmapobj);
DECL_TEMPLATE(solaris, sys_memcntl);
DECL_TEMPLATE(solaris, sys_getpmsg);
DECL_TEMPLATE(solaris, sys_putpmsg);
#if defined(SOLARIS_OLD_SYSCALLS)
DECL_TEMPLATE(solaris, sys_rename);
#endif /* SOLARIS_OLD_SYSCALLS */
DECL_TEMPLATE(solaris, sys_uname);
DECL_TEMPLATE(solaris, sys_setegid);
DECL_TEMPLATE(solaris, sys_sysconfig);
DECL_TEMPLATE(solaris, sys_systeminfo);
DECL_TEMPLATE(solaris, sys_seteuid);
DECL_TEMPLATE(solaris, sys_forksys);
DECL_TEMPLATE(solaris, sys_sigtimedwait);
DECL_TEMPLATE(solaris, sys_yield);
DECL_TEMPLATE(solaris, sys_lwp_sema_post);
DECL_TEMPLATE(solaris, sys_lwp_sema_trywait);
DECL_TEMPLATE(solaris, sys_lwp_detach);
DECL_TEMPLATE(solaris, sys_fchroot);
#if defined(SOLARIS_SYSTEM_STATS_SYSCALL)
DECL_TEMPLATE(solaris, sys_system_stats);
#endif /* SOLARIS_SYSTEM_STATS_SYSCALL */
DECL_TEMPLATE(solaris, sys_gettimeofday);
DECL_TEMPLATE(solaris, sys_lwp_create);
DECL_TEMPLATE(solaris, sys_lwp_exit);
DECL_TEMPLATE(solaris, sys_lwp_suspend);
DECL_TEMPLATE(solaris, sys_lwp_continue);
#if defined(SOLARIS_LWP_SIGQUEUE_SYSCALL)
DECL_TEMPLATE(solaris, sys_lwp_sigqueue);
#else
DECL_TEMPLATE(solaris, sys_lwp_kill);
#endif /* SOLARIS_LWP_SIGQUEUE_SYSCALL */
DECL_TEMPLATE(solaris, sys_lwp_self);
DECL_TEMPLATE(solaris, sys_lwp_sigmask);
DECL_TEMPLATE(solaris, sys_lwp_private);
DECL_TEMPLATE(solaris, sys_lwp_wait);
DECL_TEMPLATE(solaris, sys_lwp_mutex_wakeup);
DECL_TEMPLATE(solaris, sys_lwp_cond_wait);
DECL_TEMPLATE(solaris, sys_lwp_cond_broadcast);
DECL_TEMPLATE(solaris, sys_pread);
DECL_TEMPLATE(solaris, sys_pwrite);
DECL_TEMPLATE(solaris, sys_rusagesys);
DECL_TEMPLATE(solaris, sys_port);
DECL_TEMPLATE(solaris, sys_pollsys);
DECL_TEMPLATE(solaris, sys_labelsys);
DECL_TEMPLATE(solaris, sys_acl);
DECL_TEMPLATE(solaris, sys_auditsys);
DECL_TEMPLATE(solaris, sys_p_online);
DECL_TEMPLATE(solaris, sys_sigqueue);
DECL_TEMPLATE(solaris, sys_clock_gettime);
DECL_TEMPLATE(solaris, sys_clock_settime);
DECL_TEMPLATE(solaris, sys_clock_getres);
DECL_TEMPLATE(solaris, sys_timer_create);
DECL_TEMPLATE(solaris, sys_timer_delete);
DECL_TEMPLATE(solaris, sys_timer_settime);
DECL_TEMPLATE(solaris, sys_timer_gettime);
DECL_TEMPLATE(solaris, sys_timer_getoverrun);
DECL_TEMPLATE(solaris, sys_facl);
DECL_TEMPLATE(solaris, sys_door);
DECL_TEMPLATE(solaris, sys_schedctl);
DECL_TEMPLATE(solaris, sys_pset);
DECL_TEMPLATE(solaris, sys_resolvepath);
DECL_TEMPLATE(solaris, sys_lwp_mutex_timedlock);
DECL_TEMPLATE(solaris, sys_lwp_rwlock_sys);
DECL_TEMPLATE(solaris, sys_lwp_sema_timedwait);
DECL_TEMPLATE(solaris, sys_zone);
DECL_TEMPLATE(solaris, sys_getcwd);
DECL_TEMPLATE(solaris, sys_so_socket);
DECL_TEMPLATE(solaris, sys_so_socketpair);
DECL_TEMPLATE(solaris, sys_bind);
DECL_TEMPLATE(solaris, sys_listen);
DECL_TEMPLATE(solaris, sys_accept);
DECL_TEMPLATE(solaris, sys_connect);
DECL_TEMPLATE(solaris, sys_shutdown);
DECL_TEMPLATE(solaris, sys_recv);
DECL_TEMPLATE(solaris, sys_recvfrom);
DECL_TEMPLATE(solaris, sys_recvmsg);
DECL_TEMPLATE(solaris, sys_send);
DECL_TEMPLATE(solaris, sys_sendmsg);
DECL_TEMPLATE(solaris, sys_sendto);
DECL_TEMPLATE(solaris, sys_getpeername);
DECL_TEMPLATE(solaris, sys_getsockname);
DECL_TEMPLATE(solaris, sys_getsockopt);
DECL_TEMPLATE(solaris, sys_setsockopt);
DECL_TEMPLATE(solaris, sys_lwp_mutex_register);
DECL_TEMPLATE(solaris, sys_uucopy);
DECL_TEMPLATE(solaris, sys_umount2);

DECL_TEMPLATE(solaris, fast_gethrtime);
DECL_TEMPLATE(solaris, fast_gethrvtime);
DECL_TEMPLATE(solaris, fast_gethrestime);
#if defined(SOLARIS_GETHRT_FASTTRAP)
DECL_TEMPLATE(solaris, fast_gethrt);
#endif /* SOLARIS_GETHRT_FASTTRAP */
#if defined(SOLARIS_GETZONEOFFSET_FASTTRAP)
DECL_TEMPLATE(solaris, fast_getzoneoffset);
#endif /* SOLARIS_GETZONEOFFSET_FASTTRAP */

/* implementation */
PRE(sys_exit)
{
   /* void exit(int status); */
   ThreadId t;

   PRINT("sys_exit( %ld )", SARG1);
   PRE_REG_READ1(void, "exit", int, status);

   for (t = 1; t < VG_N_THREADS; t++) {
      if (VG_(threads)[t].status == VgTs_Empty)
         continue;

      VG_(threads)[t].exitreason = VgSrc_ExitProcess;
      VG_(threads)[t].os_state.exitcode = ARG1;

      /* Unblock it, if blocked. */
      if (t != tid)
         VG_(get_thread_out_of_syscall)(t);
   }

   /* We have to claim the syscall already succeeded. */
   SET_STATUS_Success(0);
}

#if defined(SOLARIS_SPAWN_SYSCALL)
static Bool spawn_pre_check_kfa(ThreadId tid, SyscallStatus *status,
                                vki_kfile_attr_t *kfa)
{
   PRE_FIELD_READ("spawn(attrs->kfa_size)", kfa->kfa_size);
   PRE_FIELD_READ("spawn(attrs->kfa_type)", kfa->kfa_type);

   if (ML_(safe_to_deref)(kfa, kfa->kfa_size)) {
      switch (kfa->kfa_type) {
      case VKI_FA_DUP2:
         PRE_FIELD_READ("spawn(attrs->kfa_filedes)", kfa->kfa_filedes);
         PRE_FIELD_READ("spawn(attrs->kfa_newfiledes)", kfa->kfa_newfiledes);
         if (!ML_(fd_allowed)(kfa->kfa_filedes, "spawn(dup2)", tid, False) ||
             !ML_(fd_allowed)(kfa->kfa_newfiledes, "spawn(dup2)", tid, False)) {
            SET_STATUS_Failure(VKI_EBADF);
            return False;
         }
         break;
      case VKI_FA_CLOSE:
         PRE_FIELD_READ("spawn(attrs->kfa_filedes)", kfa->kfa_filedes);
         /* If doing -d style logging (which is to fd = 2 = stderr),
            don't allow that filedes to be closed. See ML_(fd_allowed)(). */
         if (!ML_(fd_allowed)(kfa->kfa_filedes, "spawn(close)", tid, False) ||
             (kfa->kfa_filedes == 2 && VG_(debugLog_getLevel)() > 0)) {
            SET_STATUS_Failure(VKI_EBADF);
            return False;
         }
         break;
      case VKI_FA_CLOSEFROM:
         /* :TODO: All file descriptors greater than or equal to
            kfa->kfa_filedes would have to be checked. */
         VG_(unimplemented)("Support for spawn() with file attribute type "
                            "FA_CLOSEFROM.");
         break;
      case VKI_FA_OPEN:
         PRE_FIELD_READ("spawn(attrs->kfa_filedes)", kfa->kfa_filedes);
         PRE_FIELD_READ("spawn(attrs->kfa_oflag)", kfa->kfa_oflag);
         PRE_FIELD_READ("spawn(attrs->kfa_mode)", kfa->kfa_mode);
         if (!ML_(fd_allowed)(kfa->kfa_filedes, "spawn(open)", tid, False)) {
            SET_STATUS_Failure(VKI_EBADF);
            return False;
         }
         /* fallthrough */
      case VKI_FA_CHDIR:
         PRE_FIELD_READ("spawn(attrs->kfa_pathsize)", kfa->kfa_pathsize);
         if (kfa->kfa_pathsize != 0) {
            PRE_MEM_RASCIIZ("spawn(attrs->kfa_data)", (Addr) kfa->kfa_data);
         }
         break;
      default:
         VG_(unimplemented)("Support for spawn() with file attribute type %u.",
                            kfa->kfa_type);
      }
   }

   return True;
}

PRE(sys_spawn)
{
   /* int spawn(char *path, void *attrs, size_t attrsize,
                char *argenv, size_t aesize); */
   PRINT("sys_spawn ( %#lx(%s), %#lx, %lu, %#lx, %lu )",
         ARG1, (HChar *) ARG1, ARG2, ARG3, ARG4, ARG5);
   PRE_REG_READ5(long, "spawn", const char *, path, void *, attrs,
                 size_t, attrsize, char *, argenv, size_t, aesize);

   /* First check input arguments. */
   PRE_MEM_RASCIIZ("spawn(path)", ARG1);
   if (ARG3 > 0) {
      /*  --- vki_kspawn_attr_t --
          | ksa_version          |
          | ksa_size             |
          | ksa_attr_off         |  -----| (only if != 0)
          | ksa_attr_size        |       |
          | ksa_path_off         |  =====|====| (only if != 0)
          | ksa_path_size        |       |    |
          | ksa_shell_off        |  -----|----|----| (only if != 0)
          | ksa_shell_size       |       |    |    |
          | ksa_data[0]          |       |    |    |
          ------------------------       |    |    |
          | vki_spawn_attr_t     |  <----|    |    |
          ------------------------            |    |
          | path                 |  <---------|    |
          ------------------------                 |
          | shell                |  <---------------
          ------------------------
          | file actions         |  (not included in ksa_size, only in ARG3)
          ------------------------

          ksa_size = sizeof(vki_kspawn_attr_t) + ksa_attr_size + ksa_path_size +
                     ksa_shell_size
          attrs_size (ARG3) = ksa_size + file actions size */

      vki_kspawn_attr_t *attrs = (vki_kspawn_attr_t *) ARG2;
      PRE_FIELD_READ("spawn(attrs->ksa_version)", attrs->ksa_version);
      PRE_FIELD_READ("spawn(attrs->ksa_size)", attrs->ksa_size);
      PRE_FIELD_READ("spawn(attrs->ksa_attr_off)", attrs->ksa_attr_off);
      PRE_FIELD_READ("spawn(attrs->ksa_path_off)", attrs->ksa_path_off);
      PRE_FIELD_READ("spawn(attrs->ksa_shell_off)", attrs->ksa_shell_off);

      if (ML_(safe_to_deref)(attrs, sizeof(vki_kspawn_attr_t))) {
         if (attrs->ksa_version != VKI_SPAWN_VERSION) {
            VG_(unimplemented)("Support for spawn() with attributes "
                               "version %u.", attrs->ksa_version);
         }

         if (attrs->ksa_attr_off != 0) {
            PRE_FIELD_READ("spawn(attrs->ksa_attr_size)", attrs->ksa_attr_size);
            vki_spawn_attr_t *sap =
                (vki_spawn_attr_t *) ((Addr) attrs + attrs->ksa_attr_off);
            PRE_MEM_READ("spawn(attrs->ksa_attr)",
                         (Addr) sap, attrs->ksa_attr_size);
            if (ML_(safe_to_deref)(sap, sizeof(vki_spawn_attr_t))) {
               if (sap->sa_psflags & VKI_POSIX_SPAWN_SETVAMASK_NP) {
                  VG_(unimplemented)("Support for spawn() with attributes flag "
                                     "including POSIX_SPAWN_SETVAMASK_NP.");
               }
               /* paranoia */
               Int rem = sap->sa_psflags & ~(
                  VKI_POSIX_SPAWN_RESETIDS      | VKI_POSIX_SPAWN_SETPGROUP |
                  VKI_POSIX_SPAWN_SETSIGDEF     | VKI_POSIX_SPAWN_SETSIGMASK |
                  VKI_POSIX_SPAWN_SETSCHEDPARAM | VKI_POSIX_SPAWN_SETSCHEDULER |
                  VKI_POSIX_SPAWN_SETSID_NP     | VKI_POSIX_SPAWN_SETVAMASK_NP |
                  VKI_POSIX_SPAWN_SETSIGIGN_NP  | VKI_POSIX_SPAWN_NOSIGCHLD_NP |
                  VKI_POSIX_SPAWN_WAITPID_NP    | VKI_POSIX_SPAWN_NOEXECERR_NP);
               if (rem != 0) {
                  VG_(unimplemented)("Support for spawn() with attributes flag "
                                     "%#x.", sap->sa_psflags);
               }
            }
         }

         if (attrs->ksa_path_off != 0) {
            PRE_FIELD_READ("spawn(attrs->ksa_path_size)", attrs->ksa_path_size);
            PRE_MEM_RASCIIZ("spawn(attrs->ksa_path)",
                            (Addr) attrs + attrs->ksa_path_off);
         }

         if (attrs->ksa_shell_off != 0) {
            PRE_FIELD_READ("spawn(attrs->ksa_shell_size)",
                           attrs->ksa_shell_size);
            PRE_MEM_RASCIIZ("spawn(attrs->ksa_shell)",
                            (Addr) attrs + attrs->ksa_shell_off);
         }

         vki_kfile_attr_t *kfa = (vki_kfile_attr_t *) (ARG2 + attrs->ksa_size);
         while ((Addr) kfa < ARG2 + ARG3) {
            if (spawn_pre_check_kfa(tid, status, kfa) == False) {
               return;
            }
            kfa = (vki_kfile_attr_t *) ((Addr) kfa + kfa->kfa_size);
         }
      }
   }
   PRE_MEM_READ("spawn(argenv)", ARG4, ARG5);

   /* Check that the name at least begins in client-accessible storage. */
   if ((ARG1 == 0) || !ML_(safe_to_deref)((HChar *) ARG1, 1)) {
      SET_STATUS_Failure(VKI_EFAULT);
      return;
   }

   /* Check that attrs reside in client-accessible storage. */
   if (ARG2 != 0) {
      if (!VG_(am_is_valid_for_client)(ARG2, ARG3, VKI_PROT_READ)) {
         SET_STATUS_Failure(VKI_EFAULT);
         return;
      }
   }

   /* Check that the argenv reside in client-accessible storage.
      Solaris disallows to perform spawn() without any arguments & environment
      variables specified. */
   if ((ARG4 == 0) /* obviously bogus */ ||
       !VG_(am_is_valid_for_client)(ARG4, ARG5, VKI_PROT_READ)) {
      SET_STATUS_Failure(VKI_EFAULT);
      return;
   }

   /* Copy existing attrs or create empty minimal ones. */
   vki_kspawn_attr_t *attrs;
   SizeT attrs_size;
   if (ARG2 == 0) {
      /* minimalistic kspawn_attr_t + spawn_attr_t */
      attrs_size = sizeof(vki_kspawn_attr_t) + sizeof(vki_spawn_attr_t);
      attrs = VG_(calloc)("syswrap.spawn.1", 1, attrs_size);
      attrs->ksa_version = VKI_SPAWN_VERSION;
      attrs->ksa_size = attrs_size;
      attrs->ksa_attr_off = sizeof(vki_kspawn_attr_t);
      attrs->ksa_attr_size = sizeof(vki_spawn_attr_t);
   } else if (((vki_kspawn_attr_t *) ARG2)->ksa_attr_off == 0) {
      /* existing kspawn_attr_t but missing spawn_attr_t */
      attrs_size = ARG3 + sizeof(vki_spawn_attr_t);
      attrs = VG_(calloc)("syswrap.spawn.2", 1, attrs_size);
      VG_(memcpy)(attrs, (void *) ARG2, sizeof(vki_kspawn_attr_t));
      SizeT file_actions_size = ARG3 - attrs->ksa_size;
      attrs->ksa_size += sizeof(vki_spawn_attr_t);
      attrs->ksa_attr_off = sizeof(vki_kspawn_attr_t);
      attrs->ksa_attr_size = sizeof(vki_spawn_attr_t);
      if (attrs->ksa_path_off != 0) {
         VG_(memcpy)((HChar *) attrs + attrs->ksa_path_off +
                     sizeof(vki_spawn_attr_t), (HChar *) ARG2 +
                     attrs->ksa_path_off, attrs->ksa_path_size);
         attrs->ksa_path_off += sizeof(vki_spawn_attr_t);
      }
      if (attrs->ksa_shell_off != 0) {
         VG_(memcpy)((HChar *) attrs + attrs->ksa_shell_off +
                     sizeof(vki_spawn_attr_t), (HChar *) ARG2 +
                     attrs->ksa_shell_off, attrs->ksa_shell_size);
         attrs->ksa_shell_off += sizeof(vki_spawn_attr_t);
      }
      if (file_actions_size > 0) {
         VG_(memcpy)((HChar *) attrs + attrs_size - file_actions_size,
                     (HChar *) ARG2 + ARG3 - file_actions_size,
                     file_actions_size);
      }
   } else {
      /* existing kspawn_attr_t + spawn_attr_t */
      attrs_size = ARG3;
      attrs = VG_(malloc)("syswrap.spawn.3", attrs_size);
      VG_(memcpy)(attrs, (void *) ARG2, attrs_size);
   }
   vki_spawn_attr_t *spa = (vki_spawn_attr_t *) ((HChar *) attrs +
                                                 attrs->ksa_attr_off);

   /* Convert argv and envp parts of argenv into their separate XArray's.
      Duplicate strings because argv and envp will be then modified. */
   XArray *argv = VG_(newXA)(VG_(malloc), "syswrap.spawn.4",
                             VG_(free), sizeof(HChar *));
   XArray *envp = VG_(newXA)(VG_(malloc), "syswrap.spawn.5",
                             VG_(free), sizeof(HChar *));

   HChar *argenv = (HChar *) ARG4;
   XArray *current_xa = argv;
   while ((Addr) argenv < ARG4 + ARG5) {
      if (*argenv == '\0') {
         argenv += 1;
         if (current_xa == argv) {
            current_xa = envp;
            if ((*argenv == '\0') && ((Addr) argenv == ARG4 + ARG5 - 1)) {
               /* envp part is empty, it contained only {NULL}. */
               break;
            }
         } else {
            if ((Addr) argenv != ARG4 + ARG5) {
               if (VG_(clo_trace_syscalls))
                  VG_(debugLog)(3, "syswrap-solaris", "spawn: bogus argenv\n");
               SET_STATUS_Failure(VKI_EINVAL);
               goto exit;
            }
            break;
         }
      }

      if (*argenv != '\1') {
         if (VG_(clo_trace_syscalls))
            VG_(debugLog)(3, "syswrap-solaris", "spawn: bogus argenv\n");
         SET_STATUS_Failure(VKI_EINVAL);
         goto exit;
      }
      argenv += 1;

      HChar *duplicate = VG_(strdup)("syswrap.spawn.6", argenv);
      VG_(addToXA)(current_xa, &duplicate);
      argenv += VG_(strlen)(argenv) + 1;
   }

   /* Debug-only printing. */
   if (0) {
      VG_(printf)("\nARG1 = %#lx(%s)\n", ARG1, (HChar *) ARG1);
      VG_(printf)("ARG4 (argv) = ");
      for (Word i = 0; i < VG_(sizeXA)(argv); i++) {
         VG_(printf)("%s ", *(HChar **) VG_(indexXA)(argv, i));
      }

      VG_(printf)("\nARG4 (envp) = ");
      for (Word i = 0; i < VG_(sizeXA)(envp); i++) {
         VG_(printf)("%s ", *(HChar **) VG_(indexXA)(envp, i));
      }
      VG_(printf)("\n");
   }

   /* Decide whether or not we want to trace the spawned child.
      Omit the executable name itself from child_argv. */
   const HChar **child_argv = VG_(malloc)("syswrap.spawn.7",
                                     (VG_(sizeXA)(argv) - 1) * sizeof(HChar *));
   for (Word i = 1; i < VG_(sizeXA)(argv); i++) {
      child_argv[i - 1] = *(HChar **) VG_(indexXA)(argv, i);
   }
   Bool trace_this_child = VG_(should_we_trace_this_child)((HChar *) ARG1,
                                                           child_argv);
   VG_(free)(child_argv);

   /* If we're tracing the child, and the launcher name looks bogus (possibly
      because launcher.c couldn't figure it out, see comments therein) then we
      have no option but to fail. */
   if (trace_this_child &&
       (!VG_(name_of_launcher) || VG_(name_of_launcher)[0] != '/')) {
      SET_STATUS_Failure(VKI_ECHILD); /* "No child processes." */
      goto exit;
   }

   /* Set up the child's exe path. */
   const HChar *path = (const HChar *) ARG1;
   const HChar *launcher_basename = NULL;
   if (trace_this_child) {
      /* We want to exec the launcher. */
      path = VG_(name_of_launcher);
      vg_assert(path != NULL);

      launcher_basename = VG_(strrchr)(path, '/');
      if ((launcher_basename == NULL) || (launcher_basename[1] == '\0')) {
         launcher_basename = path;  /* hmm, tres dubious */
      } else {
         launcher_basename++;
      }
   }

   /* Set up the child's environment.

      Remove the valgrind-specific stuff from the environment so the child
      doesn't get vgpreload_core.so, vgpreload_<tool>.so, etc. This is done
      unconditionally, since if we are tracing the child, the child valgrind
      will set up the appropriate client environment.

      Then, if tracing the child, set VALGRIND_LIB for it. */
   HChar **child_envp = VG_(calloc)("syswrap.spawn.8",
                                    VG_(sizeXA)(envp) + 1, sizeof(HChar *));
   for (Word i = 0; i < VG_(sizeXA)(envp); i++) {
      child_envp[i] = *(HChar **) VG_(indexXA)(envp, i);
   }
   VG_(env_remove_valgrind_env_stuff)(child_envp, /* ro_strings */ False,
                                      VG_(free));

   /* Stuff was removed from child_envp, reflect that in envp XArray. */
   VG_(dropTailXA)(envp, VG_(sizeXA)(envp));
   for (UInt i = 0; child_envp[i] != NULL; i++) {
      VG_(addToXA)(envp, &child_envp[i]);
   }
   VG_(free)(child_envp);

   if (trace_this_child) {
      /* Set VALGRIND_LIB in envp. */
      SizeT len = VG_(strlen)(VALGRIND_LIB) + VG_(strlen)(VG_(libdir)) + 2;
      HChar *valstr = VG_(malloc)("syswrap.spawn.9", len);
      VG_(sprintf)(valstr, "%s=%s", VALGRIND_LIB, VG_(libdir));
      VG_(addToXA)(envp, &valstr);
   }

   /* Set up the child's args. If not tracing it, they are left untouched.
      Otherwise, they are:

      [launcher_basename] ++ VG_(args_for_valgrind) ++ [ARG1] ++ ARG4[1..],

      except that the first VG_(args_for_valgrind_noexecpass) args are
      omitted. */
   if (trace_this_child) {
      vg_assert(VG_(args_for_valgrind) != NULL);
      vg_assert(VG_(args_for_valgrind_noexecpass) >= 0);
      vg_assert(VG_(args_for_valgrind_noexecpass)
                   <= VG_(sizeXA)(VG_(args_for_valgrind)));

      /* So what args will there be? Bear with me... */
      /* ... launcher basename, ... */
      HChar *duplicate = VG_(strdup)("syswrap.spawn.10", launcher_basename);
      VG_(insertIndexXA)(argv, 0, &duplicate);

      /* ... Valgrind's args, ... */
      UInt v_args = VG_(sizeXA)(VG_(args_for_valgrind));
      v_args -= VG_(args_for_valgrind_noexecpass);
      for (Word i = VG_(args_for_valgrind_noexecpass);
           i < VG_(sizeXA)(VG_(args_for_valgrind)); i++) {
         duplicate = VG_(strdup)("syswrap.spawn.11",
                           *(HChar **) VG_(indexXA)(VG_(args_for_valgrind), i));
         VG_(insertIndexXA)(argv, 1 + i, &duplicate);
      }

      /* ... name of client executable, ... */
      duplicate = VG_(strdup)("syswrap.spawn.12", (HChar *) ARG1);
      VG_(insertIndexXA)(argv, 1 + v_args, &duplicate);

      /* ... and args for client executable (without [0]). */
      duplicate = *(HChar **) VG_(indexXA)(argv, 1 + v_args + 1);
      VG_(free)(duplicate);
      VG_(removeIndexXA)(argv, 1 + v_args + 1);
   }

   /* Debug-only printing. */
   if (0) {
      VG_(printf)("\npath = %s\n", path);
      VG_(printf)("argv = ");
      for (Word i = 0; i < VG_(sizeXA)(argv); i++) {
         VG_(printf)("%s ", *(HChar **) VG_(indexXA)(argv, i));
      }

      VG_(printf)("\nenvp = ");
      for (Word i = 0; i < VG_(sizeXA)(envp); i++) {
         VG_(printf)("%s ", *(HChar **) VG_(indexXA)(envp, i));
      }
      VG_(printf)("\n");
   }

   /* Set the signal state up for spawned child.

      Signals set to be caught are equivalent to signals set to the default
      action, from the child's perspective.

      Therefore query SCSS and prepare default (DFL) and ignore (IGN) signal
      sets. Then combine these sets with those passed from client, if flags
      POSIX_SPAWN_SETSIGDEF, or POSIX_SPAWN_SETSIGIGN_NP have been specified.
   */
   vki_sigset_t sig_default;
   vki_sigset_t sig_ignore;
   VG_(sigemptyset)(&sig_default);
   VG_(sigemptyset)(&sig_ignore);
   for (Int i = 1; i < VG_(max_signal); i++) {
      vki_sigaction_fromK_t sa;
      VG_(do_sys_sigaction)(i, NULL, &sa); /* query SCSS */
      if (sa.sa_handler == VKI_SIG_IGN) {
         VG_(sigaddset)(&sig_ignore, i);
      } else {
         VG_(sigaddset)(&sig_default, i);
      }
   }

   if (spa->sa_psflags & VKI_POSIX_SPAWN_SETSIGDEF) {
      VG_(sigaddset_from_set)(&spa->sa_sigdefault, &sig_default);
   } else {
      spa->sa_psflags |= VKI_POSIX_SPAWN_SETSIGDEF;
      spa->sa_sigdefault = sig_default;
   }

   if (spa->sa_psflags & VKI_POSIX_SPAWN_SETSIGIGN_NP) {
      VG_(sigaddset_from_set)(&spa->sa_sigignore, &sig_ignore);
   } else {
      spa->sa_psflags |= VKI_POSIX_SPAWN_SETSIGIGN_NP;
      spa->sa_sigignore = sig_ignore;
   }

   /* Set the signal mask for spawned child.

      Analogous to signal handlers: query SCSS for blocked signals mask
      and combine this mask with that passed from client, if flag
      POSIX_SPAWN_SETSIGMASK has been specified. */
   vki_sigset_t *sigmask = &VG_(get_ThreadState)(tid)->sig_mask;
   if (spa->sa_psflags & VKI_POSIX_SPAWN_SETSIGMASK) {
      VG_(sigaddset_from_set)(&spa->sa_sigmask, sigmask);
   } else {
      spa->sa_psflags |= VKI_POSIX_SPAWN_SETSIGMASK;
      spa->sa_sigmask = *sigmask;
   }

   /* Lastly, reconstruct argenv from argv + envp. */
   SizeT argenv_size = 1 + 1;
   for (Word i = 0; i < VG_(sizeXA)(argv); i++) {
      argenv_size += VG_(strlen)(*(HChar **) VG_(indexXA)(argv, i)) + 2;
   }
   for (Word i = 0; i < VG_(sizeXA)(envp); i++) {
      argenv_size += VG_(strlen)(*(HChar **) VG_(indexXA)(envp, i)) + 2;
   }

   argenv = VG_(malloc)("syswrap.spawn.13", argenv_size);
   HChar *current = argenv;
#define COPY_CHAR_TO_ARGENV(dst, character) \
   do {                                     \
      *(dst) = character;                   \
      (dst) += 1;                           \
   } while (0)
#define COPY_STRING_TO_ARGENV(dst, src)       \
   do {                                       \
      COPY_CHAR_TO_ARGENV(dst, '\1');         \
      SizeT src_len = VG_(strlen)((src)) + 1; \
      VG_(memcpy)((dst), (src), src_len);     \
      (dst) += src_len;                       \
   } while (0)

   for (Word i = 0; i < VG_(sizeXA)(argv); i++) {
      COPY_STRING_TO_ARGENV(current, *(HChar **) VG_(indexXA)(argv, i));
   }
   COPY_CHAR_TO_ARGENV(current, '\0');
   for (Word i = 0; i < VG_(sizeXA)(envp); i++) {
      COPY_STRING_TO_ARGENV(current, *(HChar **) VG_(indexXA)(envp, i));
   }
   COPY_CHAR_TO_ARGENV(current, '\0');
   vg_assert(current == argenv + argenv_size);
#undef COPY_CHAR_TO_ARGENV
#undef COPY_STRING_TOARGENV

   /* HACK: Temporarily restore the DATA rlimit for spawned child.
      This is a terrible hack to provide sensible brk limit for child. */
   VG_(setrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));

   /* Actual spawn() syscall. */
   SysRes res = VG_(do_syscall5)(__NR_spawn, (UWord) path, (UWord) attrs,
                                 attrs_size, (UWord) argenv, argenv_size);
   SET_STATUS_from_SysRes(res);
   VG_(free)(argenv);

   /* Restore DATA rlimit back to its previous value set in m_main.c. */
   struct vki_rlimit zero = { 0, 0 };
   zero.rlim_max = VG_(client_rlimit_data).rlim_max;
   VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);

   if (SUCCESS) {
      PRINT("   spawn: process %d spawned child %ld\n", VG_(getpid)(), RES);
   }

exit:
   VG_(free)(attrs);
   for (Word i = 0; i < VG_(sizeXA)(argv); i++) {
      VG_(free)(*(HChar **) VG_(indexXA)(argv, i));
   }
   for (Word i = 0; i < VG_(sizeXA)(envp); i++) {
      VG_(free)(*(HChar **) VG_(indexXA)(envp, i));
   }
   VG_(deleteXA)(argv);
   VG_(deleteXA)(envp);
}
#endif /* SOLARIS_SPAWN_SYSCALL */

/* Handles the case where the open is of /proc/self/psinfo or
   /proc/<pid>/psinfo. Fetch fresh contents into psinfo_t,
   fake fname, psargs, argc and argv. Write the structure to the fake
   file we cooked up at startup (in m_main) and give out a copy of this
   fd. Also seek the cloned fd back to the start. */
static Bool handle_psinfo_open(SyscallStatus *status,
                               Bool use_openat,
                               const HChar *filename,
                               Int arg1, UWord arg3, UWord arg4)
{
   if (!ML_(safe_to_deref)((const void *) filename, 1))
      return False;

   HChar name[VKI_PATH_MAX];    // large enough
   VG_(sprintf)(name, "/proc/%d/psinfo", VG_(getpid)());

   if (!VG_STREQ(filename, name) && !VG_STREQ(filename, "/proc/self/psinfo"))
      return False;

   /* Use original arguments to open() or openat(). */
   SysRes sres;
#if defined(SOLARIS_OLD_SYSCALLS)
   if (use_openat)
      sres = VG_(do_syscall4)(SYS_openat, arg1, (UWord) filename,
                              arg3, arg4);
   else
      sres = VG_(do_syscall3)(SYS_open, (UWord) filename, arg3, arg4);
#else
   vg_assert(use_openat == True);
   sres = VG_(do_syscall4)(SYS_openat, arg1, (UWord) filename,
                           arg3, arg4);
#endif /* SOLARIS_OLD_SYSCALLS */

   if (sr_isError(sres)) {
      SET_STATUS_from_SysRes(sres);
      return True;
   }
   Int fd = sr_Res(sres);

   vki_psinfo_t psinfo;
   sres = VG_(do_syscall3)(SYS_read, fd, (UWord) &psinfo, sizeof(psinfo));
   if (sr_isError(sres)) {
      SET_STATUS_from_SysRes(sres);
      VG_(close)(fd);
      return True;
   }
   if (sr_Res(sres) != sizeof(psinfo)) {
      SET_STATUS_Failure(VKI_ENODATA);
      VG_(close)(fd);
      return True;
   }

   VG_(close)(fd);

   VG_(client_fname)(psinfo.pr_fname, sizeof(psinfo.pr_fname), True);
   VG_(client_cmd_and_args)(psinfo.pr_psargs, sizeof(psinfo.pr_psargs));

   Addr *ptr = (Addr *) VG_(get_initial_client_SP)();
   psinfo.pr_argc = *ptr++;
   psinfo.pr_argv = (Addr) ptr;

   sres = VG_(do_syscall4)(SYS_pwrite, VG_(cl_psinfo_fd),
                           (UWord) &psinfo, sizeof(psinfo), 0);
   if (sr_isError(sres)) {
      SET_STATUS_from_SysRes(sres);
      return True;
   }

   sres = VG_(dup)(VG_(cl_psinfo_fd));
   SET_STATUS_from_SysRes(sres);
   if (!sr_isError(sres)) {
      OffT off = VG_(lseek)(sr_Res(sres), 0, VKI_SEEK_SET);
      if (off < 0)
         SET_STATUS_Failure(VKI_EMFILE);
   }

   return True;
}

#if defined(SOLARIS_PROC_CMDLINE)
/* Handles the case where the open is of /proc/self/cmdline or
   /proc/<pid>/cmdline. Just give it a copy of VG_(cl_cmdline_fd) for the
   fake file we cooked up at startup (in m_main).  Also, seek the
   cloned fd back to the start. */
static Bool handle_cmdline_open(SyscallStatus *status, const HChar *filename)
{
   if (!ML_(safe_to_deref)((const void *) filename, 1))
      return False;

   HChar name[VKI_PATH_MAX];    // large enough
   VG_(sprintf)(name, "/proc/%d/cmdline", VG_(getpid)());

   if (!VG_STREQ(filename, name) && !VG_STREQ(filename, "/proc/self/cmdline"))
      return False;

   SysRes sres = VG_(dup)(VG_(cl_cmdline_fd));
   SET_STATUS_from_SysRes(sres);
   if (!sr_isError(sres)) {
      OffT off = VG_(lseek)(sr_Res(sres), 0, VKI_SEEK_SET);
      if (off < 0)
         SET_STATUS_Failure(VKI_EMFILE);
   }

   return True;
}
#endif /* SOLARIS_PROC_CMDLINE */


#if defined(SOLARIS_OLD_SYSCALLS)
PRE(sys_open)
{
   /* int open(const char *filename, int flags);
      int open(const char *filename, int flags, mode_t mode); */

   if (ARG2 & VKI_O_CREAT) {
      /* 3-arg version */
      PRINT("sys_open ( %#lx(%s), %ld, %ld )", ARG1, (HChar *) ARG1,
            SARG2, ARG3);
      PRE_REG_READ3(long, "open", const char *, filename,
                    int, flags, vki_mode_t, mode);
   } else {
      /* 2-arg version */
      PRINT("sys_open ( %#lx(%s), %ld )", ARG1, (HChar *) ARG1, SARG2);
      PRE_REG_READ2(long, "open", const char *, filename, int, flags);
   }

   PRE_MEM_RASCIIZ("open(filename)", ARG1);

   if (ML_(handle_auxv_open)(status, (const HChar*)ARG1, ARG2))
      return;

   if (handle_psinfo_open(status, False /*use_openat*/, (const HChar*)ARG1, 0,
                          ARG2, ARG3))
      return;

   *flags |= SfMayBlock;
}

POST(sys_open)
{
   if (!ML_(fd_allowed)(RES, "open", tid, True)) {
      VG_(close)(RES);
      SET_STATUS_Failure(VKI_EMFILE);
   } else if (VG_(clo_track_fds))
      ML_(record_fd_open_with_given_name)(tid, RES, (HChar *) ARG1);
}
#endif /* SOLARIS_OLD_SYSCALLS */

PRE(sys_close)
{
   WRAPPER_PRE_NAME(generic, sys_close)(tid, layout, arrghs, status,
                                        flags);
}

POST(sys_close)
{
   WRAPPER_POST_NAME(generic, sys_close)(tid, arrghs, status);
   door_revoke(tid, ARG1);
   /* Possibly an explicitly open'ed client door fd was just closed.
      Generic sys_close wrapper calls this only if VG_(clo_track_fds) = True. */
   if (!VG_(clo_track_fds))
      ML_(record_fd_close)(ARG1);
}

PRE(sys_linkat)
{
   /* int linkat(int fd1, const char *path1, int fd2,
                 const char *path2, int flag);
    */

   /* Interpret the first and third arguments as 32-bit values even on 64-bit
      architecture. This is different from Linux, for example, where glibc
      sign-extends them. */
   Int fd1 = (Int) ARG1;
   Int fd2 = (Int) ARG3;

   PRINT("sys_linkat ( %d, %#lx(%s), %d, %#lx(%s), %ld )",
         fd1, ARG2, (HChar *) ARG2, fd2, ARG4, (HChar *) ARG4, SARG5);
   PRE_REG_READ5(long, "linkat", int, fd1, const char *, path1,
                 int, fd2, const char *, path2, int, flags);
   PRE_MEM_RASCIIZ("linkat(path1)", ARG2);
   PRE_MEM_RASCIIZ("linkat(path2)", ARG4);

   /* Be strict but ignore fd1/fd2 for absolute path1/path2. */
   if (fd1 != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd1, "linkat", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
   }
   if (fd2 != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG4, 1)
       && ((HChar *) ARG4)[0] != '/'
       && !ML_(fd_allowed)(fd2, "linkat", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
   }

   *flags |= SfMayBlock;
}

PRE(sys_symlinkat)
{
   /* int symlinkat(const char *path1, int fd, const char *path2); */

   /* Interpret the second argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG2;

   PRINT("sys_symlinkat ( %#lx(%s), %d, %#lx(%s) )",
         ARG1, (HChar *) ARG1, fd, ARG3, (HChar *) ARG3);
   PRE_REG_READ3(long, "symlinkat", const char *, path1, int, fd,
                 const char *, path2);
   PRE_MEM_RASCIIZ("symlinkat(path1)", ARG1);
   PRE_MEM_RASCIIZ("symlinkat(path2)", ARG3);

   /* Be strict but ignore fd for absolute path2. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG3, 1)
       && ((HChar *) ARG3)[0] != '/'
       && !ML_(fd_allowed)(fd, "symlinkat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);

   *flags |= SfMayBlock;
}

PRE(sys_time)
{
   /* time_t time(); */
   PRINT("sys_time ( )");
   PRE_REG_READ0(long, "time");
}

/* Data segment for brk (heap). It is an expandable anonymous mapping
   abutting a 1-page reservation. The data segment starts at VG_(brk_base)
   and runs up to VG_(brk_limit). None of these two values have to be
   page-aligned.
   Initial data segment is established (see initimg-solaris.c for rationale):
   - directly during client program image initialization,
   - or on demand when the executed program is the runtime linker itself,
     after it has loaded its target dynamic executable (see PRE(sys_mmapobj)),
     or when the first brk() syscall is made.

   Notable facts:
   - VG_(brk_base) is not page aligned; does not move
   - VG_(brk_limit) moves between [VG_(brk_base), data segment end]
   - data segment end is always page aligned
   - right after data segment end is 1-page reservation

            |      heap           | 1 page
     +------+------+--------------+-------+
     | BSS  | anon |   anon       | resvn |
     +------+------+--------------+-------+

            ^      ^        ^    ^
            |      |        |    |
            |      |        |    data segment end
            |      |        VG_(brk_limit) -- no alignment constraint
            |      brk_base_pgup -- page aligned
            VG_(brk_base) -- not page aligned -- does not move

   Because VG_(brk_base) is not page-aligned and is initially located within
   pre-established BSS (data) segment, special care has to be taken in the code
   below to handle this feature.

   Reservation segment is used to protect the data segment merging with
   a pre-existing segment. This should be no problem because address space
   manager ensures that requests for client address space are satisfied from
   the highest available addresses. However when memory is low, data segment
   can meet with mmap'ed objects and the reservation segment separates these.
   The page that contains VG_(brk_base) is already allocated by the program's
   loaded data segment. The brk syscall wrapper handles this special case. */

static Bool brk_segment_established = False;

/* Establishes initial data segment for brk (heap). */
Bool VG_(setup_client_dataseg)(void)
{
   /* Segment size is initially at least 1 MB and at most 8 MB. */
   SizeT m1 = 1024 * 1024;
   SizeT m8 = 8 * m1;
   SizeT initial_size = VG_(client_rlimit_data).rlim_cur;
   VG_(debugLog)(1, "syswrap-solaris", "Setup client data (brk) segment "
                                       "at %#lx\n", VG_(brk_base));
   if (initial_size < m1)
      initial_size = m1;
   if (initial_size > m8)
      initial_size = m8;
   initial_size = VG_PGROUNDUP(initial_size);

   Addr anon_start = VG_PGROUNDUP(VG_(brk_base));
   SizeT anon_size = VG_PGROUNDUP(initial_size);
   Addr resvn_start = anon_start + anon_size;
   SizeT resvn_size = VKI_PAGE_SIZE;

   vg_assert(VG_IS_PAGE_ALIGNED(anon_size));
   vg_assert(VG_IS_PAGE_ALIGNED(resvn_size));
   vg_assert(VG_IS_PAGE_ALIGNED(anon_start));
   vg_assert(VG_IS_PAGE_ALIGNED(resvn_start));
   vg_assert(VG_(brk_base) == VG_(brk_limit));

   /* Find the loaded data segment and remember its protection. */
   const NSegment *seg = VG_(am_find_nsegment)(VG_(brk_base) - 1);
   vg_assert(seg != NULL);
   UInt prot = (seg->hasR ? VKI_PROT_READ : 0)
             | (seg->hasW ? VKI_PROT_WRITE : 0)
             | (seg->hasX ? VKI_PROT_EXEC : 0);

   /* Try to create the data segment and associated reservation where
      VG_(brk_base) says. */
   Bool ok = VG_(am_create_reservation)(resvn_start, resvn_size, SmLower,
                                        anon_size);
   if (!ok) {
      /* That didn't work, we're hosed. */
      return False;
   }

   /* Map the data segment. */
   SysRes sres = VG_(am_mmap_anon_fixed_client)(anon_start, anon_size, prot);
   vg_assert(!sr_isError(sres));
   vg_assert(sr_Res(sres) == anon_start);

   brk_segment_established = True;
   return True;
}

/* Tell the tool about the client data segment and then kill it which will
   make it initially inaccessible/unaddressable. */
void VG_(track_client_dataseg)(ThreadId tid)
{
   const NSegment *seg = VG_(am_find_nsegment)(VG_PGROUNDUP(VG_(brk_base)));
   vg_assert(seg != NULL);
   vg_assert(seg->kind == SkAnonC);

   VG_TRACK(new_mem_brk, VG_(brk_base), seg->end + 1 - VG_(brk_base), tid);
   VG_TRACK(die_mem_brk, VG_(brk_base), seg->end + 1 - VG_(brk_base));
}

PRE(sys_brk)
{
   /* unsigned long brk(caddr_t end_data_segment); */
   /* The Solaris kernel returns 0 on success.
      In addition to this, brk(0) returns current data segment end.  This is
      very different from the Linux kernel, for example. */

   Addr old_brk_limit = VG_(brk_limit);
   /* If VG_(brk_base) is page-aligned then old_brk_base_pgup is equal to
      VG_(brk_base). */
   Addr old_brk_base_pgup = VG_PGROUNDUP(VG_(brk_base));
   Addr new_brk = ARG1;
   const NSegment *seg, *seg2;

   PRINT("sys_brk ( %#lx )", ARG1);
   PRE_REG_READ1(unsigned long, "brk", vki_caddr_t, end_data_segment);

   if (new_brk == 0) {
      /* brk(0) - specific to Solaris 11 only. */
      SET_STATUS_Success(old_brk_limit);
      return;
   }

   /* Handle some trivial cases. */
   if (new_brk == old_brk_limit) {
      SET_STATUS_Success(0);
      return;
   }
   if (new_brk < VG_(brk_base)) {
      /* Clearly impossible. */
      SET_STATUS_Failure(VKI_ENOMEM);
      return;
   }
   if (new_brk - VG_(brk_base) > VG_(client_rlimit_data).rlim_cur) {
      SET_STATUS_Failure(VKI_ENOMEM);
      return;
   }

   /* The brk base and limit must have been already set. */
   vg_assert(VG_(brk_base) != -1);
   vg_assert(VG_(brk_limit) != -1);

   if (!brk_segment_established) {
      /* Stay sane (because there should have been no brk activity yet). */
      vg_assert(VG_(brk_base) == VG_(brk_limit));

      if (!VG_(setup_client_dataseg)()) {
         VG_(umsg)("Cannot map memory to initialize brk segment in thread #%d "
                   "at %#lx\n", tid, VG_(brk_base));
         SET_STATUS_Failure(VKI_ENOMEM);
         return;
      }

      VG_(track_client_dataseg)(tid);
   }

   if (new_brk < old_brk_limit) {
      /* Shrinking the data segment.  Be lazy and don't munmap the excess
         area. */
      if (old_brk_limit > old_brk_base_pgup) {
         /* Calculate new local brk (=MAX(new_brk, old_brk_base_pgup)). */
         Addr new_brk_local;
         if (new_brk < old_brk_base_pgup)
            new_brk_local = old_brk_base_pgup;
         else
            new_brk_local = new_brk;

         /* Find a segment at the beginning and at the end of the shrinked
            range. */
         seg = VG_(am_find_nsegment)(new_brk_local);
         seg2 = VG_(am_find_nsegment)(old_brk_limit - 1);
         vg_assert(seg);
         vg_assert(seg->kind == SkAnonC);
         vg_assert(seg2);
         vg_assert(seg == seg2);

         /* Discard any translations and zero-out the area. */
         if (seg->hasT)
            VG_(discard_translations)(new_brk_local,
                                      old_brk_limit - new_brk_local,
                                      "do_brk(shrink)");
        /* Since we're being lazy and not unmapping pages, we have to zero out
           the area, so that if the area later comes back into circulation, it
           will be filled with zeroes, as if it really had been unmapped and
           later remapped.  Be a bit paranoid and try hard to ensure we're not
           going to segfault by doing the write - check that segment is
           writable. */
         if (seg->hasW)
            VG_(memset)((void*)new_brk_local, 0, old_brk_limit - new_brk_local);
      }

      /* Fixup code if the VG_(brk_base) is not page-aligned. */
      if (new_brk < old_brk_base_pgup) {
         /* Calculate old local brk (=MIN(old_brk_limit, old_brk_base_up)). */
         Addr old_brk_local;
         if (old_brk_limit < old_brk_base_pgup)
            old_brk_local = old_brk_limit;
         else
            old_brk_local = old_brk_base_pgup;

         /* Find a segment at the beginning and at the end of the shrinked
            range. */
         seg = VG_(am_find_nsegment)(new_brk);
         seg2 = VG_(am_find_nsegment)(old_brk_local - 1);
         vg_assert(seg);
         vg_assert(seg2);
         vg_assert(seg == seg2);

         /* Discard any translations and zero-out the area. */
         if (seg->hasT)
            VG_(discard_translations)(new_brk, old_brk_local - new_brk,
                                      "do_brk(shrink)");
         if (seg->hasW)
            VG_(memset)((void*)new_brk, 0, old_brk_local - new_brk);
      }

      /* We are done, update VG_(brk_limit), tell the tool about the changes,
         and leave. */
      VG_(brk_limit) = new_brk;
      VG_TRACK(die_mem_brk, new_brk, old_brk_limit - new_brk);
      SET_STATUS_Success(0);
      return;
   }

   /* We are expanding the brk segment. */

   /* Fixup code if the VG_(brk_base) is not page-aligned. */
   if (old_brk_limit < old_brk_base_pgup) {
      /* Calculate new local brk (=MIN(new_brk, old_brk_base_pgup)). */
      Addr new_brk_local;
      if (new_brk < old_brk_base_pgup)
         new_brk_local = new_brk;
      else
         new_brk_local = old_brk_base_pgup;

      /* Find a segment at the beginning and at the end of the expanded
         range. */
      seg = VG_(am_find_nsegment)(old_brk_limit);
      seg2 = VG_(am_find_nsegment)(new_brk_local - 1);
      vg_assert(seg);
      vg_assert(seg2);
      vg_assert(seg == seg2);

      /* Nothing else to do. */
   }

   if (new_brk > old_brk_base_pgup) {
      /* Calculate old local brk (=MAX(old_brk_limit, old_brk_base_pgup)). */
      Addr old_brk_local;
      if (old_brk_limit < old_brk_base_pgup)
         old_brk_local = old_brk_base_pgup;
      else
         old_brk_local = old_brk_limit;

      /* Find a segment at the beginning of the expanded range. */
      if (old_brk_local > old_brk_base_pgup)
         seg = VG_(am_find_nsegment)(old_brk_local - 1);
      else
         seg = VG_(am_find_nsegment)(old_brk_local);
      vg_assert(seg);
      vg_assert(seg->kind == SkAnonC);

      /* Find the 1-page reservation segment. */
      seg2 = VG_(am_next_nsegment)(seg, True/*forwards*/);
      vg_assert(seg2);
      vg_assert(seg2->kind == SkResvn);
      vg_assert(seg->end + 1 == seg2->start);
      vg_assert(seg2->end - seg2->start + 1 == VKI_PAGE_SIZE);

      if (new_brk <= seg2->start) {
         /* Still fits within the existing anon segment, nothing to do. */
      } else {
         /* Data segment limit was already checked. */
         Addr anon_start = seg->end + 1;
         Addr resvn_start = VG_PGROUNDUP(new_brk);
         SizeT anon_size = resvn_start - anon_start;
         SizeT resvn_size = VKI_PAGE_SIZE;
         SysRes sres;

         vg_assert(VG_IS_PAGE_ALIGNED(anon_size));
         vg_assert(VG_IS_PAGE_ALIGNED(resvn_size));
         vg_assert(VG_IS_PAGE_ALIGNED(anon_start));
         vg_assert(VG_IS_PAGE_ALIGNED(resvn_start));
         vg_assert(anon_size > 0);

         /* Address space manager checks for free address space for us;
            reservation would not be otherwise created. */
         Bool ok = VG_(am_create_reservation)(resvn_start, resvn_size, SmLower,
                                              anon_size);
         if (!ok) {
            VG_(umsg)("brk segment overflow in thread #%d: can't grow "
                      "to %#lx\n", tid, new_brk);
            SET_STATUS_Failure(VKI_ENOMEM);
            return;
         }

         /* Establish protection from the existing segment. */
         UInt prot = (seg->hasR ? VKI_PROT_READ : 0)
                     | (seg->hasW ? VKI_PROT_WRITE : 0)
                     | (seg->hasX ? VKI_PROT_EXEC : 0);

         /* Address space manager will merge old and new data segments. */
         sres = VG_(am_mmap_anon_fixed_client)(anon_start, anon_size, prot);
         if (sr_isError(sres)) {
            VG_(umsg)("Cannot map memory to grow brk segment in thread #%d "
                      "to %#lx\n", tid, new_brk);
            SET_STATUS_Failure(VKI_ENOMEM);
            return;
         }
         vg_assert(sr_Res(sres) == anon_start);

         seg = VG_(am_find_nsegment)(old_brk_base_pgup);
         seg2 = VG_(am_find_nsegment)(VG_PGROUNDUP(new_brk) - 1);
         vg_assert(seg);
         vg_assert(seg2);
         vg_assert(seg == seg2);
         vg_assert(new_brk <= seg->end + 1);
      }
   }

   /* We are done, update VG_(brk_limit), tell the tool about the changes, and
      leave. */
   VG_(brk_limit) = new_brk;
   VG_TRACK(new_mem_brk, old_brk_limit, new_brk - old_brk_limit, tid);
   SET_STATUS_Success(0);
}

PRE(sys_stat)
{
   /* int stat(const char *path, struct stat *buf); */
   /* Note: We could use here the sys_newstat generic wrapper, but the 'new'
      in its name is rather confusing in the Solaris context, thus we provide
      our own wrapper. */
   PRINT("sys_stat ( %#lx(%s), %#lx )", ARG1, (HChar *) ARG1, ARG2);
   PRE_REG_READ2(long, "stat", const char *, path, struct stat *, buf);

   PRE_MEM_RASCIIZ("stat(path)", ARG1);
   PRE_MEM_WRITE("stat(buf)", ARG2, sizeof(struct vki_stat));
}

POST(sys_stat)
{
   POST_MEM_WRITE(ARG2, sizeof(struct vki_stat));
}

PRE(sys_lseek)
{
   /* off_t lseek(int fildes, off_t offset, int whence); */
   PRINT("sys_lseek ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
   PRE_REG_READ3(long, "lseek", int, fildes, vki_off_t, offset, int, whence);

   /* Stay sane. */
   if (!ML_(fd_allowed)(ARG1, "lseek", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_mount)
{
   /* int mount(const char *spec, const char *dir, int mflag, char *fstype,
                char *dataptr, int datalen, char *optptr, int optlen); */
   *flags |= SfMayBlock;
   if (ARG3 & VKI_MS_OPTIONSTR) {
      /* 8-argument mount */
      PRINT("sys_mount ( %#lx(%s), %#lx(%s), %ld, %#lx(%s), %#lx, %ld, "
            "%#lx(%s), %ld )", ARG1, (HChar *) ARG1, ARG2, (HChar *) ARG2, SARG3,
            ARG4, (HChar *) ARG4, ARG5, ARG6, ARG7, (HChar *) ARG7, SARG8);
      PRE_REG_READ8(long, "mount", const char *, spec, const char *, dir,
                    int, mflag, char *, fstype, char *, dataptr, int, datalen,
                    char *, optptr, int, optlen);
   }
   else if (ARG3 & VKI_MS_DATA) {
      /* 6-argument mount */
      PRINT("sys_mount ( %#lx(%s), %#lx(%s), %ld, %#lx(%s), %#lx, %ld )",
            ARG1, (HChar *) ARG1, ARG2, (HChar *) ARG2, SARG3, ARG4,
            (HChar *) ARG4, ARG5, SARG6);
      PRE_REG_READ6(long, "mount", const char *, spec, const char *, dir,
                    int, mflag, char *, fstype, char *, dataptr,
                    int, datalen);
   }
   else {
      /* 4-argument mount */
      PRINT("sys_mount ( %#lx(%s), %#lx(%s), %ld, %#lx(%s) )", ARG1,
            (HChar *) ARG1, ARG2, (HChar *) ARG2, SARG3, ARG4, (HChar *) ARG4);
      PRE_REG_READ4(long, "mount", const char *, spec, const char *, dir,
                    int, mflag, char *, fstype);
   }
   if (ARG1)
      PRE_MEM_RASCIIZ("mount(spec)", ARG1);
   PRE_MEM_RASCIIZ("mount(dir)", ARG2);
   if (ARG4 && ARG4 >= 256) {
      /* If ARG4 < 256, then it's an index to a fs table in the kernel. */
      PRE_MEM_RASCIIZ("mount(fstype)", ARG4);
   }
   if (ARG3 & (VKI_MS_DATA | VKI_MS_OPTIONSTR)) {
      if (ARG5)
         PRE_MEM_READ("mount(dataptr)", ARG5, ARG6);
      if ((ARG3 & VKI_MS_OPTIONSTR) && ARG7) {
         /* in/out buffer */
         PRE_MEM_RASCIIZ("mount(optptr)", ARG7);
         PRE_MEM_WRITE("mount(optptr)", ARG7, ARG8);
      }
   }
}

POST(sys_mount)
{
   if (ARG3 & VKI_MS_OPTIONSTR) {
      POST_MEM_WRITE(ARG7, VG_(strlen)((HChar*)ARG7) + 1);
   } else if (ARG3 & VKI_MS_DATA) {
      if ((ARG2) &&
          (ARG3 & MS_NOMNTTAB) &&
          (VG_STREQ((HChar *) ARG4, "namefs")) &&
          (ARG6 == sizeof(struct vki_namefd)) &&
          ML_(safe_to_deref)((void *) ARG5, ARG6)) {
         /* Most likely an fattach() call for a door file descriptor. */
         door_server_fattach(((struct vki_namefd *) ARG5)->fd, (HChar *) ARG2);
      }
   }
}

PRE(sys_readlinkat)
{
   /* ssize_t readlinkat(int dfd, const char *path, char *buf,
                         size_t bufsiz); */
   HChar name[30];    // large enough
   Word saved = SYSNO;

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int dfd = (Int) ARG1;

   PRINT("sys_readlinkat ( %d, %#lx(%s), %#lx, %ld )", dfd, ARG2,
         (HChar *) ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "readlinkat", int, dfd, const char *, path,
                 char *, buf, int, bufsiz);
   PRE_MEM_RASCIIZ("readlinkat(path)", ARG2);
   PRE_MEM_WRITE("readlinkat(buf)", ARG3, ARG4);

   /* Be strict but ignore dfd for absolute path. */
   if (dfd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(dfd, "readlinkat", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
      return;
   }

   /* Handle the case where readlinkat is looking at /proc/self/path/a.out or
      /proc/<pid>/path/a.out. */
   VG_(sprintf)(name, "/proc/%d/path/a.out", VG_(getpid)());
   if (ML_(safe_to_deref)((void*)ARG2, 1) &&
       (!VG_(strcmp)((HChar*)ARG2, name) ||
        !VG_(strcmp)((HChar*)ARG2, "/proc/self/path/a.out"))) {
      VG_(sprintf)(name, "/proc/self/path/%d", VG_(cl_exec_fd));
      SET_STATUS_from_SysRes(VG_(do_syscall4)(saved, dfd, (UWord)name, ARG3,
                                              ARG4));
   }
}

POST(sys_readlinkat)
{
   POST_MEM_WRITE(ARG3, RES);
}

PRE(sys_stime)
{
   /* Kernel: int stime(time_t time); */
   PRINT("sys_stime ( %ld )", ARG1);
   PRE_REG_READ1(long, "stime", vki_time_t, time);
}

PRE(sys_fstat)
{
   /* int fstat(int fildes, struct stat *buf); */
   /* Note: We could use here the sys_newfstat generic wrapper, but the 'new'
      in its name is rather confusing in the Solaris context, thus we provide
      our own wrapper. */
   PRINT("sys_fstat ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "fstat", int, fildes, struct stat *, buf);
   PRE_MEM_WRITE("fstat(buf)", ARG2, sizeof(struct vki_stat));

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "fstat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_fstat)
{
   POST_MEM_WRITE(ARG2, sizeof(struct vki_stat));
}

#if defined(SOLARIS_FREALPATHAT_SYSCALL)
PRE(sys_frealpathat)
{
   /* int frealpathat(int fd, char *path, char *buf, size_t buflen); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_frealpathat ( %d, %#lx(%s), %#lx, %lu )",
         fd, ARG2, (HChar *) ARG2, ARG3, ARG4);
   PRE_REG_READ4(long, "frealpathat", int, fd, char *, path,
                 char *, buf, vki_size_t, buflen);
   PRE_MEM_RASCIIZ("frealpathat(path)", ARG2);
   PRE_MEM_WRITE("frealpathat(buf)", ARG3, ARG4);

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "frealpathat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_frealpathat)
{
   POST_MEM_WRITE(ARG3, VG_(strlen)((HChar *) ARG3) + 1);
}
#endif /* SOLARIS_FREALPATHAT_SYSCALL */

PRE(sys_stty)
{
   /* int stty(int fd, const struct sgttyb *tty); */
   PRINT("sys_stty ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "stty", int, fd,
                 const struct vki_sgttyb *, tty);
   PRE_MEM_READ("stty(tty)", ARG2, sizeof(struct vki_sgttyb));

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "stty", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_gtty)
{
   /* int gtty(int fd, struct sgttyb *tty); */
   PRINT("sys_gtty ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "gtty", int, fd, struct vki_sgttyb *, tty);
   PRE_MEM_WRITE("gtty(tty)", ARG2, sizeof(struct vki_sgttyb));

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "gtty", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_gtty)
{
   POST_MEM_WRITE(ARG2, sizeof(struct vki_sgttyb));
}

PRE(sys_pgrpsys)
{
   /* Kernel: int setpgrp(int flag, int pid, int pgid); */
   switch (ARG1 /*flag*/) {
   case 0:
      /* Libc: pid_t getpgrp(void); */
      PRINT("sys_pgrpsys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("pgrpsys", "getpgrp"), int, flag);
      break;
   case 1:
      /* Libc: pid_t setpgrp(void); */
      PRINT("sys_pgrpsys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("pgrpsys", "setpgrp"), int, flag);
      break;
   case 2:
      /* Libc: pid_t getsid(pid_t pid); */
      PRINT("sys_pgrpsys ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("pgrpsys", "getsid"), int, flag,
                    vki_pid_t, pid);
      break;
   case 3:
      /* Libc: pid_t setsid(void); */
      PRINT("sys_pgrpsys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("pgrpsys", "setsid"), int, flag);
      break;
   case 4:
      /* Libc: pid_t getpgid(pid_t pid); */
      PRINT("sys_pgrpsys ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("pgrpsys", "getpgid"), int, flag,
                    vki_pid_t, pid);
      break;
   case 5:
      /* Libc: int setpgid(pid_t pid, pid_t pgid); */
      PRINT("sys_pgrpsys ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
      PRE_REG_READ3(long, SC2("pgrpsys", "setpgid"), int, flag,
                    vki_pid_t, pid, vki_pid_t, pgid);
      break;
   default:
      VG_(unimplemented)("Syswrap of the pgrpsys call with flag %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

PRE(sys_pipe)
{
#if defined(SOLARIS_NEW_PIPE_SYSCALL)
   /* int pipe(int fildes[2], int flags); */
   PRINT("sys_pipe ( %#lx, %ld )", ARG1, SARG2);
   PRE_REG_READ2(long, "pipe", int *, fildes, int, flags);
   PRE_MEM_WRITE("pipe(fildes)", ARG1, 2 * sizeof(int));
#else
   /* longlong_t pipe(); */
   PRINT("sys_pipe ( )");
   PRE_REG_READ0(long, "pipe");
#endif /* SOLARIS_NEW_PIPE_SYSCALL */
}

POST(sys_pipe)
{
   Int p0, p1;

#if defined(SOLARIS_NEW_PIPE_SYSCALL)
   int *fds = (int*)ARG1;
   p0 = fds[0];
   p1 = fds[1];
   POST_MEM_WRITE(ARG1, 2 * sizeof(int));
#else
   p0 = RES;
   p1 = RESHI;
#endif /* SOLARIS_NEW_PIPE_SYSCALL */

   if (!ML_(fd_allowed)(p0, "pipe", tid, True) ||
       !ML_(fd_allowed)(p1, "pipe", tid, True)) {
      VG_(close)(p0);
      VG_(close)(p1);
      SET_STATUS_Failure(VKI_EMFILE);
   }
   else if (VG_(clo_track_fds)) {
      ML_(record_fd_open_nameless)(tid, p0);
      ML_(record_fd_open_nameless)(tid, p1);
   }
}

PRE(sys_faccessat)
{
   /* int faccessat(int fd, const char *path, int amode, int flag); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_faccessat ( %d, %#lx(%s), %ld, %ld )", fd, ARG2,
         (HChar *) ARG2, SARG3, SARG4);
   PRE_REG_READ4(long, "faccessat", int, fd, const char *, path,
                 int, amode, int, flag);
   PRE_MEM_RASCIIZ("faccessat(path)", ARG2);

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "faccessat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_mknodat)
{
   /* int mknodat(int fd, char *fname, mode_t fmode, dev_t dev); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_mknodat ( %d, %#lx(%s), %ld, %ld )", fd, ARG2,
         (HChar *) ARG2, SARG3, SARG4);
   PRE_REG_READ4(long, "mknodat", int, fd, const char *, fname,
                 vki_mode_t, fmode, vki_dev_t, dev);
   PRE_MEM_RASCIIZ("mknodat(fname)", ARG2);

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "mknodat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);

   *flags |= SfMayBlock;
}

POST(sys_mknodat)
{
   if (!ML_(fd_allowed)(RES, "mknodat", tid, True)) {
      VG_(close)(RES);
      SET_STATUS_Failure(VKI_EMFILE);
   } else if (VG_(clo_track_fds))
      ML_(record_fd_open_with_given_name)(tid, RES, (HChar *) ARG2);
}

PRE(sys_sysi86)
{
   /* int sysi86(int cmd, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3); */
   PRINT("sys_sysi86 ( %ld, %#lx, %#lx, %#lx )", SARG1, ARG2, ARG3, ARG4);
   PRE_REG_READ4(long, "sysi86", int, cmd, uintptr_t, arg1, uintptr_t, arg2,
                 uintptr_t, arg3);

   switch (ARG1 /*cmd*/) {
   case VKI_SI86FPSTART:
      PRE_MEM_WRITE("sysi86(fp_hw)", ARG2, sizeof(vki_uint_t));
      /* ARG3 is a desired x87 FCW value, ARG4 is a desired SSE MXCSR value.
         They are passed to the kernel but V will change them later anyway
         (this is a general Valgrind limitation described in the official
         documentation). */
      break;
   default:
      VG_(unimplemented)("Syswrap of the sysi86 call with cmd %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_sysi86)
{
   switch (ARG1 /*cmd*/) {
   case VKI_SI86FPSTART:
      POST_MEM_WRITE(ARG2, sizeof(vki_uint_t));
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_shmsys)
{
   /* Kernel: uintptr_t shmsys(int opcode, uintptr_t a0, uintptr_t a1,
                               uintptr_t a2, uintptr_t a3);
    */
   *flags |= SfMayBlock;

   switch (ARG1 /*opcode*/) {
   case VKI_SHMAT:
      /* Libc: void *shmat(int shmid, const void *shmaddr, int shmflg); */
      PRINT("sys_shmsys ( %ld, %ld, %#lx, %ld )",
            SARG1, SARG2, ARG3, SARG4);
      PRE_REG_READ4(long, SC2("shmsys", "shmat"), int, opcode,
                    int, shmid, const void *, shmaddr, int, shmflg);

      UWord addr = ML_(generic_PRE_sys_shmat)(tid, ARG2, ARG3, ARG4);
      if (addr == 0)
         SET_STATUS_Failure(VKI_EINVAL);
      else
         ARG3 = addr;
      break;

   case VKI_SHMCTL:
      /* Libc: int shmctl(int shmid, int cmd, struct shmid_ds *buf); */
      switch (ARG3 /* cmd */) {
      case VKI_SHM_LOCK:
         PRINT("sys_shmsys ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
         PRE_REG_READ3(long, SC3("shmsys", "shmctl", "lock"),
                       int, opcode, int, shmid, int, cmd);
         break;
      case VKI_SHM_UNLOCK:
         PRINT("sys_shmsys ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
         PRE_REG_READ3(long, SC3("shmsys", "shmctl", "unlock"),
                       int, opcode, int, shmid, int, cmd);
         break;
      case VKI_IPC_RMID:
         PRINT("sys_shmsys ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
         PRE_REG_READ3(long, SC3("shmsys", "shmctl", "rmid"),
                       int, opcode, int, shmid, int, cmd);
         break;
      case VKI_IPC_SET:
         PRINT("sys_shmsys ( %ld, %ld, %ld, %#lx )",
               SARG1, SARG2, SARG3, ARG4);
         PRE_REG_READ4(long, SC3("shmsys", "shmctl", "set"),
                       int, opcode, int, shmid, int, cmd,
                       struct vki_shmid_ds *, buf);

         struct vki_shmid_ds *buf = (struct vki_shmid_ds *) ARG4;
         PRE_FIELD_READ("shmsys(shmctl, ipc_set, buf->shm_perm.uid)",
                        buf->shm_perm.uid);
         PRE_FIELD_READ("shmsys(shmctl, ipc_set, buf->shm_perm.gid)",
                        buf->shm_perm.gid);
         PRE_FIELD_READ("shmsys(shmctl, ipc_set, buf->shm_perm.mode)",
                        buf->shm_perm.mode);
         break;
      case VKI_IPC_STAT:
         PRINT("sys_shmsys ( %ld, %ld, %ld, %#lx )",
               SARG1, SARG2, SARG3, ARG4);
         PRE_REG_READ4(long, SC3("shmsys", "shmctl", "stat"),
                       int, opcode, int, shmid, int, cmd,
                       struct vki_shmid_ds *, buf);
         PRE_MEM_WRITE("shmsys(shmctl, ipc_stat, buf)", ARG4,
                       sizeof(struct vki_shmid_ds));
        break;
      case VKI_IPC_SET64:
         PRINT("sys_shmsys ( %ld, %ld, %ld, %#lx )",
               SARG1, SARG2, SARG3, ARG4);
         PRE_REG_READ4(long, SC3("shmsys", "shmctl", "set64"),
                       int, opcode, int, shmid, int, cmd,
                       struct vki_shmid_ds64 *, buf);

         struct vki_shmid_ds64 *buf64 = (struct vki_shmid_ds64 *) ARG4;
         PRE_FIELD_READ("shmsys(shmctl, ipc_set64, "
                        "buf->shmx_perm.ipcx_uid)",
                        buf64->shmx_perm.ipcx_uid);
         PRE_FIELD_READ("shmsys(shmctl, ipc_set64, "
                        "buf->shmx_perm.ipcx_gid)",
                        buf64->shmx_perm.ipcx_gid);
         PRE_FIELD_READ("shmsys(shmctl, ipc_set64, "
                        "buf->shmx_perm.ipcx_mode)",
                        buf64->shmx_perm.ipcx_mode);
         break;
      case VKI_IPC_STAT64:
         PRINT("sys_shmsys ( %ld, %ld, %ld, %#lx )",
               SARG1, SARG2, SARG3, ARG4);
         PRE_REG_READ4(long, SC3("shmsys", "shmctl", "stat64"),
                       int, opcode, int, shmid, int, cmd,
                       struct vki_shmid_ds64 *, buf);
         PRE_MEM_WRITE("shmsys(shmctl, ipc_stat64, buf)", ARG4,
                       sizeof(struct vki_shmid_ds64));
         break;
#if defined(SOLARIS_SHM_NEW)
      case VKI_IPC_XSTAT64:
         PRINT("sys_shmsys ( %ld, %ld, %ld, %#lx )",
               SARG1, SARG2, SARG3, ARG4);
         PRE_REG_READ4(long, SC3("shmsys", "shmctl", "xstat64"),
                       int, opcode, int, shmid, int, cmd,
                       struct vki_shmid_ds64 *, buf);
         PRE_MEM_WRITE("shmsys(shmctl, ipc_xstat64, buf)", ARG4,
                       sizeof(struct vki_shmid_xds64));
         break;
#endif /* SOLARIS_SHM_NEW */
      default:
         VG_(unimplemented)("Syswrap of the shmsys(shmctl) call with "
                            "cmd %ld.", SARG3);
         /*NOTREACHED*/
         break;
      }
      break;

   case VKI_SHMDT:
      /* Libc: int shmdt(const void *shmaddr); */
      PRINT("sys_shmsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("shmsys", "shmdt"), int, opcode,
                    const void *, shmaddr);

      if (!ML_(generic_PRE_sys_shmdt)(tid, ARG2))
	 SET_STATUS_Failure(VKI_EINVAL);
      break;

   case VKI_SHMGET:
      /* Libc: int shmget(key_t key, size_t size, int shmflg); */
      PRINT("sys_shmsys ( %ld, %ld, %lu, %ld )",
            SARG1, SARG2, ARG3, ARG4);
      PRE_REG_READ4(long, SC2("shmsys", "shmget"), int, opcode,
                    vki_key_t, key, vki_size_t, size, int, shmflg);
      break;

   case VKI_SHMIDS:
      /* Libc: int shmids(int *buf, uint_t nids, uint_t *pnids); */
      PRINT("sys_shmsys ( %ld, %#lx, %lu, %#lx )",
            SARG1, ARG2, ARG3, ARG4);
      PRE_REG_READ4(long, SC2("shmsys", "shmids"), int, opcode,
                    int *, buf, vki_uint_t, nids, vki_uint_t *, pnids);

      PRE_MEM_WRITE("shmsys(shmids, buf)", ARG2, ARG3 * sizeof(int *));
      PRE_MEM_WRITE("shmsys(shmids, pnids)", ARG4, sizeof(vki_uint_t));
      break;

#if defined(SOLARIS_SHM_NEW)
   case VKI_SHMADV:
      /* Libc: int shmadv(int shmid, uint_t cmd, uint_t *advice); */
      PRINT("sys_shmsys ( %ld, %ld, %lu, %ld )",
            SARG1, SARG2, ARG3, ARG4);
      PRE_REG_READ4(long, SC2("shmsys", "shmadv"), int, opcode,
                    int, shmid, vki_uint_t, cmd, vki_uint_t *, advice);

      switch (ARG3 /*cmd*/) {
      case VKI_SHM_ADV_GET:
         PRE_MEM_WRITE("shmsys(shmadv, advice)", ARG4,
                       sizeof(vki_uint_t));
         break;
      case VKI_SHM_ADV_SET:
         PRE_MEM_READ("shmsys(shmadv, advice)", ARG4,
                       sizeof(vki_uint_t));
         break;
      default:
         VG_(unimplemented)("Syswrap of the shmsys(shmadv) call with "
                            "cmd %lu.", ARG3);
         /*NOTREACHED*/
         break;
      }
      break;

   case VKI_SHMGET_OSM:
      /* Libc: int shmget_osm(key_t key, size_t size, int shmflg,
                              size_t granule_sz);
       */
      PRINT("sys_shmsys ( %ld, %ld, %lu, %ld, %lu )",
            SARG1, SARG2, ARG3, SARG4, ARG5);
      PRE_REG_READ5(long, SC2("shmsys", "shmget_osm"), int, opcode,
                    vki_key_t, key, vki_size_t, size, int, shmflg,
                    vki_size_t, granule_sz);
      break;
#endif /* SOLARIS_SHM_NEW */

   default:
      VG_(unimplemented)("Syswrap of the shmsys call with opcode %ld.",
                         SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_shmsys)
{
   switch (ARG1 /*opcode*/) {
   case VKI_SHMAT:
      ML_(generic_POST_sys_shmat)(tid, RES, ARG2, ARG3, ARG4);
      break;

   case VKI_SHMCTL:
      switch (ARG3 /*cmd*/) {
      case VKI_SHM_LOCK:
      case VKI_SHM_UNLOCK:
      case VKI_IPC_RMID:
      case VKI_IPC_SET:
         break;
      case VKI_IPC_STAT:
         POST_MEM_WRITE(ARG4, sizeof(struct vki_shmid_ds));
         break;
      case VKI_IPC_SET64:
         break;
      case VKI_IPC_STAT64:
         POST_MEM_WRITE(ARG4, sizeof(struct vki_shmid_ds64));
         break;
#if defined(SOLARIS_SHM_NEW)
      case VKI_IPC_XSTAT64:
         POST_MEM_WRITE(ARG4, sizeof(struct vki_shmid_xds64));
         break;
#endif /* SOLARIS_SHM_NEW */
      default:
         vg_assert(0);
         break;
      }
      break;

   case VKI_SHMDT:
      ML_(generic_POST_sys_shmdt)(tid, RES, ARG2);
      break;

   case VKI_SHMGET:
      break;

   case VKI_SHMIDS:
      {
         POST_MEM_WRITE(ARG4, sizeof(vki_uint_t));

         uint_t *pnids = (vki_uint_t *) ARG4;
         if (*pnids <= ARG3)
            POST_MEM_WRITE(ARG2, *pnids * sizeof(int *));
      }
      break;

#if defined(SOLARIS_SHM_NEW)
   case VKI_SHMADV:
      switch (ARG3 /*cmd*/) {
      case VKI_SHM_ADV_GET:
         POST_MEM_WRITE(ARG4, sizeof(vki_uint_t));
         break;
      case VKI_SHM_ADV_SET:
         break;
      default:
         vg_assert(0);
         break;
      }
      break;

   case VKI_SHMGET_OSM:
      break;
#endif /* SOLARIS_SHM_NEW */

   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_semsys)
{
   /* Kernel: int semsys(int opcode, uintptr_t a1, uintptr_t a2, uintptr_t a3,
                         uintptr_t a4);
    */
   *flags |= SfMayBlock;

   switch (ARG1 /*opcode*/) {
   case VKI_SEMCTL:
      /* Libc: int semctl(int semid, int semnum, int cmd...); */
      switch (ARG4) {
         case VKI_IPC_STAT:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG3, SARG4, ARG5);
            PRE_REG_READ5(long, SC3("semsys", "semctl", "stat"), int, opcode,
                          int, semid, int, semnum, int, cmd,
                          struct vki_semid_ds *, arg);
            break;
         case VKI_IPC_SET:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG3, SARG4, ARG5);
            PRE_REG_READ5(long, SC3("semsys", "semctl", "set"), int, opcode,
                          int, semid, int, semnum, int, cmd,
                          struct vki_semid_ds *, arg);
            break;
         case VKI_IPC_STAT64:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG3, SARG4, ARG5);
            PRE_REG_READ5(long, SC3("semsys", "semctl", "stat64"), int, opcode,
                          int, semid, int, semnum, int, cmd,
                          struct vki_semid64_ds *, arg);
            break;
         case VKI_IPC_SET64:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG3, SARG4, ARG5);
            PRE_REG_READ5(long, SC3("semsys", "semctl", "set64"), int, opcode,
                          int, semid, int, semnum, int, cmd,
                          struct vki_semid64_ds *, arg);
            break;
         case VKI_IPC_RMID:
            PRINT("sys_semsys ( %ld, %ld, %ld )", SARG1, SARG3, SARG4);
            PRE_REG_READ3(long, SC3("semsys", "semctl", "rmid"), int, opcode,
                          int, semid, int, cmd);
            break;
         case VKI_GETALL:
            PRINT("sys_semsys ( %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG4, ARG5);
            PRE_REG_READ4(long, SC3("semsys", "semctl", "getall"), int, opcode,
                          int, semid, int, cmd, ushort_t *, arg);
            break;
         case VKI_SETALL:
            PRINT("sys_semsys ( %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG4, ARG5);
            PRE_REG_READ4(long, SC3("semsys", "semctl", "setall"), int, opcode,
                          int, semid, int, cmd, ushort_t *, arg);
            break;
         case VKI_GETVAL:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld )",
                  SARG1, SARG2, SARG3, SARG4);
            PRE_REG_READ4(long, SC3("semsys", "semctl", "getval"), int, opcode,
                          int, semid, int, semnum, int, cmd);
            break;
         case VKI_SETVAL:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld, %#lx )",
                  SARG1, SARG2, SARG3, SARG4, ARG5);
            PRE_REG_READ5(long, SC3("semsys", "semctl", "setval"), int, opcode,
                          int, semid, int, semnum, int, cmd,
                          union vki_semun *, arg);
            break;
         case VKI_GETPID:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld )",
                  SARG1, SARG2, SARG3, SARG4);
            PRE_REG_READ4(long, SC3("semsys", "semctl", "getpid"), int, opcode,
                          int, semid, int, semnum, int, cmd);
            break;
         case VKI_GETNCNT:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld )",
                  SARG1, SARG2, SARG3, SARG4);
            PRE_REG_READ4(long, SC3("semsys", "semctl", "getncnt"),
                          int, opcode, int, semid, int, semnum, int, cmd);
            break;
         case VKI_GETZCNT:
            PRINT("sys_semsys ( %ld, %ld, %ld, %ld )",
                  SARG1, SARG2, SARG3, SARG4);
            PRE_REG_READ4(long, SC3("semsys", "semctl", "getzcnt"),
                          int, opcode, int, semid, int, semnum, int, cmd);
            break;
         default:
            VG_(unimplemented)("Syswrap of the semsys(semctl) call "
                               "with cmd %ld.", SARG4);
            /*NOTREACHED*/
            break;
      }
      ML_(generic_PRE_sys_semctl)(tid, ARG2, ARG3, ARG4, ARG5);
      break;
   case VKI_SEMGET:
      /* Libc: int semget(key_t key, int nsems, int semflg); */
      PRINT("sys_semsys ( %ld, %ld, %ld, %ld )", SARG1, SARG2, SARG3, SARG4);
      PRE_REG_READ4(long, SC2("semsys", "semget"), int, opcode,
                    vki_key_t, key, int, nsems, int, semflg);
      break;
   case VKI_SEMOP:
      /* Libc: int semop(int semid, struct sembuf *sops, size_t nsops); */
      PRINT("sys_semsys ( %ld, %ld, %#lx, %lu )", SARG1, SARG2, ARG3, ARG4);
      PRE_REG_READ4(long, SC2("semsys", "semop"), int, opcode, int, semid,
                    struct vki_sembuf *, sops, vki_size_t, nsops);
      ML_(generic_PRE_sys_semop)(tid, ARG2, ARG3, ARG4);
      break;
   case VKI_SEMIDS:
      /* Libc: int semids(int *buf, uint_t nids, uint_t *pnids); */
      PRINT("sys_semsys ( %ld, %#lx, %lu, %#lx )", SARG1, ARG2, ARG3, ARG4);
      PRE_REG_READ4(long, SC2("semsys", "semids"), int, opcode, int *, buf,
                   vki_uint_t, nids, vki_uint_t *, pnids);

      PRE_MEM_WRITE("semsys(semids, buf)", ARG2, ARG3 * sizeof(int *));
      PRE_MEM_WRITE("semsys(semids, pnids)", ARG4, sizeof(vki_uint_t));
      break;
   case VKI_SEMTIMEDOP:
      /* Libc: int semtimedop(int semid, struct sembuf *sops, size_t nsops,
                              const struct timespec *timeout);
       */
      PRINT("sys_semsys ( %ld, %ld, %#lx, %lu, %#lx )", SARG1, SARG2, ARG3,
            ARG4, ARG5);
      PRE_REG_READ5(long, SC2("semsys", "semtimedop"), int, opcode,
                    int, semid, struct vki_sembuf *, sops, vki_size_t, nsops,
                    struct vki_timespec *, timeout);
      ML_(generic_PRE_sys_semtimedop)(tid, ARG2, ARG3, ARG4, ARG5);
      break;
   default:
      VG_(unimplemented)("Syswrap of the semsys call with opcode %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_semsys)
{
   switch (ARG1 /*opcode*/) {
   case VKI_SEMCTL:
      ML_(generic_POST_sys_semctl)(tid, RES, ARG2, ARG3, ARG4, ARG5);
      break;
   case VKI_SEMGET:
   case VKI_SEMOP:
      break;
   case VKI_SEMIDS:
      {
         POST_MEM_WRITE(ARG4, sizeof(vki_uint_t));

         uint_t *pnids = (uint_t *)ARG4;
         if (*pnids <= ARG3)
            POST_MEM_WRITE(ARG2, *pnids * sizeof(int *));
      }
      break;
   case VKI_SEMTIMEDOP:
      break;
   default:
      vg_assert(0);
      break;
   }
}

/* ---------------------------------------------------------------------
   ioctl wrappers
   ------------------------------------------------------------------ */

PRE(sys_ioctl)
{
   /* int ioctl(int fildes, int request, ...); */
   *flags |= SfMayBlock;

   /* Prevent sign extending the switch case values to 64-bits on 64-bits
      architectures. */
   Int cmd = (Int) ARG2;

   switch (cmd /*request*/) {
      /* Handle 2-arg specially here (they do not use ARG3 at all). */
   case VKI_TIOCNOTTY:
   case VKI_TIOCSCTTY:
      PRINT("sys_ioctl ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, "ioctl", int, fd, int, request);
      break;
      /* And now come the 3-arg ones. */
   default:
      PRINT("sys_ioctl ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
      PRE_REG_READ3(long, "ioctl", int, fd, int, request, intptr_t, arg);
      break;
   }

   switch (cmd /*request*/) {
   /* pools */
   case VKI_POOL_STATUSQ:
      PRE_MEM_WRITE("ioctl(POOL_STATUSQ)", ARG3, sizeof(vki_pool_status_t));
      break;

   /* mntio */
   case VKI_MNTIOC_GETMNTANY:
      {
         PRE_MEM_READ("ioctl(MNTIOC_GETMNTANY)",
                      ARG3, sizeof(struct vki_mntentbuf));

         struct vki_mntentbuf *embuf = (struct vki_mntentbuf *) ARG3;
         if (ML_(safe_to_deref(embuf, sizeof(*embuf)))) {
            PRE_MEM_READ("ioctl(MNTIOC_GETMNTANY, embuf->mbuf_emp)",
                         (Addr) embuf->mbuf_emp,
                         sizeof(struct vki_mnttab));
            PRE_MEM_WRITE("ioctl(MNTIOC_GETMNTANY, embuf->mbuf_buf)",
                          (Addr) embuf->mbuf_buf,
                          embuf->mbuf_bufsize);
            struct vki_mnttab *mnt
               = (struct vki_mnttab *) embuf->mbuf_emp;
            if (ML_(safe_to_deref(mnt, sizeof(struct vki_mnttab)))) {
               if (mnt->mnt_special != NULL)
                  PRE_MEM_RASCIIZ("ioctl(MNTIOC_GETMNTANY, mnt->mnt_special)",
                                  (Addr) mnt->mnt_special);
               if (mnt->mnt_mountp != NULL)
                  PRE_MEM_RASCIIZ("ioctl(MNTIOC_GETMNTANY, mnt->mnt_mountp)",
                                  (Addr) mnt->mnt_mountp);
               if (mnt->mnt_fstype != NULL)
                  PRE_MEM_RASCIIZ("ioctl(MNTIOC_GETMNTANY, mnt->mnt_fstype)",
                                  (Addr) mnt->mnt_fstype);
               if (mnt->mnt_mntopts != NULL)
                  PRE_MEM_RASCIIZ("ioctl(MNTIOC_GETMNTANY, mnt->mnt_mntopts)",
                                  (Addr) mnt->mnt_mntopts);
               if (mnt->mnt_time != NULL)
                  PRE_MEM_RASCIIZ("ioctl(MNTIOC_GETMNTANY, mnt->mnt_time)",
                                  (Addr) mnt->mnt_time);
            }
         }
      }
      break;

   /* termio/termios */
   case VKI_TCGETA:
      PRE_MEM_WRITE("ioctl(TCGETA)", ARG3, sizeof(struct vki_termio));
      break;
   case VKI_TCGETS:
      PRE_MEM_WRITE("ioctl(TCGETS)", ARG3, sizeof(struct vki_termios));
      break;
   case VKI_TCSETS:
      PRE_MEM_READ("ioctl(TCSETS)", ARG3, sizeof(struct vki_termios));
      break;
   case VKI_TCSETSW:
      PRE_MEM_READ("ioctl(TCSETSW)", ARG3, sizeof(struct vki_termios));
      break;
   case VKI_TCSETSF:
      PRE_MEM_READ("ioctl(TCSETSF)", ARG3, sizeof(struct vki_termios));
      break;
   case VKI_TIOCGWINSZ:
      PRE_MEM_WRITE("ioctl(TIOCGWINSZ)", ARG3, sizeof(struct vki_winsize));
      break;
   case VKI_TIOCSWINSZ:
      PRE_MEM_READ("ioctl(TIOCSWINSZ)", ARG3, sizeof(struct vki_winsize));
      break;
   case VKI_TIOCGPGRP:
      PRE_MEM_WRITE("ioctl(TIOCGPGRP)", ARG3, sizeof(vki_pid_t));
      break;
   case VKI_TIOCSPGRP:
      PRE_MEM_READ("ioctl(TIOCSPGRP)", ARG3, sizeof(vki_pid_t));
      break;
   case VKI_TIOCGSID:
      PRE_MEM_WRITE("ioctl(TIOCGSID)", ARG3, sizeof(vki_pid_t));
      break;
   case VKI_TIOCNOTTY:
   case VKI_TIOCSCTTY:
      break;

   /* STREAMS */
   case VKI_I_PUSH:
      PRE_MEM_RASCIIZ("ioctl(I_PUSH)", ARG3);
      break;
   case VKI_I_STR:
      {
         PRE_MEM_READ("ioctl(I_STR)", ARG3, sizeof(struct vki_strioctl));

         struct vki_strioctl *p = (struct vki_strioctl *) ARG3;
         if (ML_(safe_to_deref(p, sizeof(*p)))) {
            if ((p->ic_dp != NULL) && (p->ic_len > 0)) {
               PRE_MEM_READ("ioctl(I_STR, strioctl->ic_dp)",
                            (Addr) p->ic_dp, p->ic_len);
            }
         }
      }
      break;
   case VKI_I_PEEK:
      {
         /* Try hard not to mark strpeek->*buf.len members as being read. */
         struct vki_strpeek *p = (struct vki_strpeek*)ARG3;

         PRE_FIELD_READ("ioctl(I_PEEK, strpeek->ctlbuf.maxlen)",
                        p->ctlbuf.maxlen);
         PRE_FIELD_WRITE("ioctl(I_PEEK, strpeek->ctlbuf.len)",
                         p->ctlbuf.len);
         PRE_FIELD_READ("ioctl(I_PEEK, strpeek->ctlbuf.buf)",
                        p->ctlbuf.buf);
         PRE_FIELD_READ("ioctl(I_PEEK, strpeek->databuf.maxlen)",
                        p->databuf.maxlen);
         PRE_FIELD_WRITE("ioctl(I_PEEK, strpeek->databuf.len)",
                         p->databuf.len);
         PRE_FIELD_READ("ioctl(I_PEEK, strpeek->databuf.buf)",
                        p->databuf.buf);
         PRE_FIELD_READ("ioctl(I_PEEK, strpeek->flags)", p->flags);
         /*PRE_FIELD_WRITE("ioctl(I_PEEK, strpeek->flags)", p->flags);*/

         if (ML_(safe_to_deref(p, sizeof(*p)))) {
            if (p->ctlbuf.buf && p->ctlbuf.maxlen > 0)
               PRE_MEM_WRITE("ioctl(I_PEEK, strpeek->ctlbuf.buf)",
                             (Addr)p->ctlbuf.buf, p->ctlbuf.maxlen);
            if (p->databuf.buf && p->databuf.maxlen > 0)
               PRE_MEM_WRITE("ioctl(I_PEEK, strpeek->databuf.buf)",
                             (Addr)p->databuf.buf, p->databuf.maxlen);
         }
      }
      break;
   case VKI_I_CANPUT:
      break;

   /* sockio */
   case VKI_SIOCGIFCONF:
      {
         struct vki_ifconf *p = (struct vki_ifconf *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGIFCONF, ifconf->ifc_len)", p->ifc_len);
         PRE_FIELD_READ("ioctl(SIOCGIFCONF, ifconf->ifc_buf)", p->ifc_buf);
         if (ML_(safe_to_deref)(p, sizeof(*p))) {
            if ((p->ifc_buf != NULL) && (p->ifc_len > 0))
               PRE_MEM_WRITE("ioctl(SIOCGIFCONF, ifconf->ifc_buf)",
                             (Addr) p->ifc_buf, p->ifc_len);
         }
         /* ifc_len gets also written to during SIOCGIFCONF ioctl. */
      }
      break;
   case VKI_SIOCGIFFLAGS:
      {
         struct vki_ifreq *p = (struct vki_ifreq *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGIFFLAGS, ifreq->ifr_name)", p->ifr_name);
         PRE_FIELD_WRITE("ioctl(SIOCGIFFLAGS, ifreq->ifr_flags)", p->ifr_flags);
      }
      break;
   case VKI_SIOCGIFNETMASK:
      {
         struct vki_ifreq *p = (struct vki_ifreq *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGIFFLAGS, ifreq->ifr_name)", p->ifr_name);
         PRE_FIELD_WRITE("ioctl(SIOCGIFFLAGS, ifreq->ifr_addr)", p->ifr_addr);
      }
      break;
   case VKI_SIOCGIFNUM:
      PRE_MEM_WRITE("ioctl(SIOCGIFNUM)", ARG3, sizeof(int));
      break;
   case VKI_SIOCGLIFBRDADDR:
      {
         struct vki_lifreq *p = (struct vki_lifreq *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGLIFBRDADDR, lifreq->lifr_name)",
                        p->lifr_name);
         PRE_FIELD_WRITE("ioctl(SIOCGLIFBRDADDR, lifreq->lifr_addr)",
                         p->lifr_addr);
      }
      break;
   case VKI_SIOCGLIFCONF:
      {
         struct vki_lifconf *p = (struct vki_lifconf *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGLIFCONF, lifconf->lifc_len)", p->lifc_len);
         PRE_FIELD_READ("ioctl(SIOCGLIFCONF, lifconf->lifc_buf)", p->lifc_buf);
         PRE_FIELD_READ("ioctl(SIOCGLIFCONF, lifconf->lifc_family)",
                        p->lifc_family);
         PRE_FIELD_READ("ioctl(SIOCGLIFCONF, lifconf->lifc_flags)",
                        p->lifc_flags);
         if (ML_(safe_to_deref)(p, sizeof(*p))) {
            if ((p->lifc_buf != NULL) && (p->lifc_len > 0))
               PRE_MEM_WRITE("ioctl(SIOCGLIFCONF, lifconf->lifc_buf)",
                             (Addr) p->lifc_buf, p->lifc_len);
         }
         /* lifc_len gets also written to during SIOCGLIFCONF ioctl. */
      }
      break;
   case VKI_SIOCGLIFFLAGS:
      {
         struct vki_lifreq *p = (struct vki_lifreq *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGLIFFLAGS, lifreq->lifr_name)",
                        p->lifr_name);
         PRE_FIELD_WRITE("ioctl(SIOCGLIFFLAGS, lifreq->lifr_flags)",
                         p->lifr_flags);
      }
      break;
   case VKI_SIOCGLIFNETMASK:
      {
         struct vki_lifreq *p = (struct vki_lifreq *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGLIFNETMASK, lifreq->lifr_name)",
                        p->lifr_name);
         PRE_FIELD_WRITE("ioctl(SIOCGLIFNETMASK, lifreq->lifr_addr)",
                         p->lifr_addr);
      }
      break;
   case VKI_SIOCGLIFNUM:
      {
         struct vki_lifnum *p = (struct vki_lifnum *) ARG3;
         PRE_FIELD_READ("ioctl(SIOCGLIFNUM, lifn->lifn_family)",
                        p->lifn_family);
         PRE_FIELD_READ("ioctl(SIOCGLIFNUM, lifn->lifn_flags)",
                        p->lifn_flags);
         PRE_FIELD_WRITE("ioctl(SIOCGLIFNUM, lifn->lifn_count)",
                         p->lifn_count);
      }
      break;

   /* filio */
   case VKI_FIOSETOWN:
      PRE_MEM_READ("ioctl(FIOSETOWN)", ARG3, sizeof(vki_pid_t));
      break;
   case VKI_FIOGETOWN:
      PRE_MEM_WRITE("ioctl(FIOGETOWN)", ARG3, sizeof(vki_pid_t));
      break;

   /* CRYPTO */
   case VKI_CRYPTO_GET_PROVIDER_LIST:
      {
         vki_crypto_get_provider_list_t *pl =
            (vki_crypto_get_provider_list_t *) ARG3;
         PRE_FIELD_READ("ioctl(CRYPTO_GET_PROVIDER_LIST, pl->pl_count)",
                        pl->pl_count);

         if (ML_(safe_to_deref)(pl, sizeof(*pl))) {
            PRE_MEM_WRITE("ioctl(CRYPTO_GET_PROVIDER_LIST)", ARG3,
                          MAX(1, pl->pl_count) *
                          sizeof(vki_crypto_get_provider_list_t));
         }
         /* Save the requested count to unused ARG4 below,
            when we know pre-handler succeeded.
          */
      }
      break; 

   /* dtrace */
   case VKI_DTRACEHIOC_REMOVE:
      break;
   case VKI_DTRACEHIOC_ADDDOF:
      {
         vki_dof_helper_t *dh = (vki_dof_helper_t *) ARG3;
         PRE_MEM_RASCIIZ("ioctl(DTRACEHIOC_ADDDOF, dh->dofhp_mod)",
                         (Addr) dh->dofhp_mod);
         PRE_FIELD_READ("ioctl(DTRACEHIOC_ADDDOF, dh->dofhp_addr",
                        dh->dofhp_addr);
         PRE_FIELD_READ("ioctl(DTRACEHIOC_ADDDOF, dh->dofhp_dof",
                        dh->dofhp_dof);
      }
      break;

   default:
      ML_(PRE_unknown_ioctl)(tid, ARG2, ARG3);
      break;
   }

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "ioctl", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
   } else if (ARG2 == VKI_CRYPTO_GET_PROVIDER_LIST) {
      /* Save the requested count to unused ARG4 now. */
      ARG4 = ARG3;
   }
}

POST(sys_ioctl)
{
   /* Prevent sign extending the switch case values to 64-bits on 64-bits
      architectures. */
   Int cmd = (Int) ARG2;

   switch (cmd /*request*/) {
   /* pools */
   case VKI_POOL_STATUSQ:
      POST_MEM_WRITE(ARG3, sizeof(vki_pool_status_t));
      break;

   /* mntio */
   case VKI_MNTIOC_GETMNTANY:
      {
         struct vki_mntentbuf *embuf = (struct vki_mntentbuf *) ARG3;
         struct vki_mnttab *mnt = (struct vki_mnttab *) embuf->mbuf_emp;

         POST_MEM_WRITE((Addr) mnt, sizeof(struct vki_mnttab));
         if (mnt != NULL) {
            if (mnt->mnt_special != NULL)
               POST_MEM_WRITE((Addr) mnt->mnt_special,
                              VG_(strlen)(mnt->mnt_special) + 1);
            if (mnt->mnt_mountp != NULL)
               POST_MEM_WRITE((Addr) mnt->mnt_mountp,
                              VG_(strlen)(mnt->mnt_mountp) + 1);
            if (mnt->mnt_fstype != NULL)
               POST_MEM_WRITE((Addr) mnt->mnt_fstype,
                              VG_(strlen)(mnt->mnt_fstype) + 1);
            if (mnt->mnt_mntopts != NULL)
               POST_MEM_WRITE((Addr) mnt->mnt_mntopts,
                              VG_(strlen)(mnt->mnt_mntopts) + 1);
            if (mnt->mnt_time != NULL)
               POST_MEM_WRITE((Addr) mnt->mnt_time,
                              VG_(strlen)(mnt->mnt_time) + 1);
         }
      }
      break;

   /* termio/termios */
   case VKI_TCGETA:
      POST_MEM_WRITE(ARG3, sizeof(struct vki_termio));
      break;
   case VKI_TCGETS:
      POST_MEM_WRITE(ARG3, sizeof(struct vki_termios));
      break;
   case VKI_TCSETS:
      break;
   case VKI_TCSETSW:
      break;
   case VKI_TCSETSF:
      break;
   case VKI_TIOCGWINSZ:
      POST_MEM_WRITE(ARG3, sizeof(struct vki_winsize));
      break;
   case VKI_TIOCSWINSZ:
      break;
   case VKI_TIOCGPGRP:
      POST_MEM_WRITE(ARG3, sizeof(vki_pid_t));
      break;
   case VKI_TIOCSPGRP:
      break;
   case VKI_TIOCGSID:
      POST_MEM_WRITE(ARG3, sizeof(vki_pid_t));
      break;
   case VKI_TIOCNOTTY:
   case VKI_TIOCSCTTY:
      break;

   /* STREAMS */
   case VKI_I_PUSH:
      break;
   case VKI_I_STR:
      {
         struct vki_strioctl *p = (struct vki_strioctl *) ARG3;

         POST_FIELD_WRITE(p->ic_len);
         if ((p->ic_dp != NULL) && (p->ic_len > 0))
            POST_MEM_WRITE((Addr) p->ic_dp, p->ic_len);
      }
      break;
   case VKI_I_PEEK:
      {
         struct vki_strpeek *p = (struct vki_strpeek*)ARG3;

         POST_FIELD_WRITE(p->ctlbuf.len);
         POST_FIELD_WRITE(p->databuf.len);
         POST_FIELD_WRITE(p->flags);

         if (p->ctlbuf.buf && p->ctlbuf.len > 0)
            POST_MEM_WRITE((Addr)p->ctlbuf.buf, p->ctlbuf.len);
         if (p->databuf.buf && p->databuf.len > 0)
            POST_MEM_WRITE((Addr)p->databuf.buf, p->databuf.len);
      }
      break;
   case VKI_I_CANPUT:
      break;

   /* sockio */
   case VKI_SIOCGIFCONF:
      {
         struct vki_ifconf *p = (struct vki_ifconf *) ARG3;
         POST_FIELD_WRITE(p->ifc_len);
         POST_FIELD_WRITE(p->ifc_req);
         if ((p->ifc_req != NULL) && (p->ifc_len > 0))
            POST_MEM_WRITE((Addr) p->ifc_req, p->ifc_len);
      }
      break;
   case VKI_SIOCGIFFLAGS:
      {
         struct vki_ifreq *p = (struct vki_ifreq *) ARG3;
         POST_FIELD_WRITE(p->ifr_flags);
      }
      break;
   case VKI_SIOCGIFNETMASK:
      {
         struct vki_ifreq *p = (struct vki_ifreq *) ARG3;
         POST_FIELD_WRITE(p->ifr_addr);
      }
      break;
   case VKI_SIOCGIFNUM:
      POST_MEM_WRITE(ARG3, sizeof(int));
      break;
   case VKI_SIOCGLIFBRDADDR:
      {
         struct vki_lifreq *p = (struct vki_lifreq *) ARG3;
         POST_FIELD_WRITE(p->lifr_addr);
      }
      break;
   case VKI_SIOCGLIFCONF:
      {
         struct vki_lifconf *p = (struct vki_lifconf *) ARG3;
         POST_FIELD_WRITE(p->lifc_len);
         POST_FIELD_WRITE(p->lifc_req);
         if ((p->lifc_req != NULL) && (p->lifc_len > 0))
            POST_MEM_WRITE((Addr) p->lifc_req, p->lifc_len);
      }
      break;
   case VKI_SIOCGLIFFLAGS:
      {
         struct vki_lifreq *p = (struct vki_lifreq *) ARG3;
         POST_FIELD_WRITE(p->lifr_flags);
      }
      break;
   case VKI_SIOCGLIFNETMASK:
      {
         struct vki_lifreq *p = (struct vki_lifreq *) ARG3;
         POST_FIELD_WRITE(p->lifr_addr);
      }
      break;
   case VKI_SIOCGLIFNUM:
      {
         struct vki_lifnum *p = (struct vki_lifnum *) ARG3;
         POST_FIELD_WRITE(p->lifn_count);
      }
      break;  

   /* filio */
   case VKI_FIOSETOWN:
      break;
   case VKI_FIOGETOWN:
      POST_MEM_WRITE(ARG3, sizeof(vki_pid_t));
      break;

   /* CRYPTO */
   case VKI_CRYPTO_GET_PROVIDER_LIST:
      {
         vki_crypto_get_provider_list_t *pl =
            (vki_crypto_get_provider_list_t *) ARG3;

         POST_FIELD_WRITE(pl->pl_count);
         POST_FIELD_WRITE(pl->pl_return_value);

         if ((ARG4 > 0) && (pl->pl_return_value == VKI_CRYPTO_SUCCESS))
            POST_MEM_WRITE((Addr) pl->pl_list, pl->pl_count *
                           sizeof(vki_crypto_provider_entry_t));
      }
      break;

   /* dtrace */
   case VKI_DTRACEHIOC_REMOVE:
   case VKI_DTRACEHIOC_ADDDOF:
      break;

   default:
      /* Not really anything to do since ioctl direction hints are hardly used
         on Solaris. */
      break;
   }
}

PRE(sys_fchownat)
{
   /* int fchownat(int fd, const char *path, uid_t owner, gid_t group,
                   int flag); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_fchownat ( %d, %#lx(%s), %ld, %ld, %ld )", fd,
         ARG2, (HChar *) ARG2, SARG3, SARG4, ARG5);
   PRE_REG_READ5(long, "fchownat", int, fd, const char *, path,
                 vki_uid_t, owner, vki_gid_t, group, int, flag);

   if (ARG2)
      PRE_MEM_RASCIIZ("fchownat(path)", ARG2);

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "fchownat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_fdsync)
{
   /* int fdsync(int fd, int flag); */
   PRINT("sys_fdsync ( %ld, %ld )", SARG1, SARG2);
   PRE_REG_READ2(long, "fdsync", int, fd, int, flag);

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "fdsync", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_execve)
{
   Int i, j;
   /* This is a Solaris specific version of the generic pre-execve wrapper. */

#if defined(SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS)
   /* int execve(uintptr_t file, const char **argv, const char **envp,
                 int flags); */
   PRINT("sys_execve ( %#lx, %#lx, %#lx, %ld )", ARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "execve", uintptr_t, file, const char **, argv,
                 const char **, envp, int, flags);

#else

   /* int execve(const char *fname, const char **argv, const char **envp); */
   PRINT("sys_execve ( %#lx(%s), %#lx, %#lx )",
         ARG1, (HChar *) ARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "execve", const char *, file, const char **, argv,
                 const char **, envp);
#endif /* SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS */

   Bool ARG1_is_fd = False;
#if defined(SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS)
   if (ARG4 & VKI_EXEC_DESCRIPTOR) {
      ARG1_is_fd = True;
   }
#endif /* SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS */

   if (ARG1_is_fd == False)
      PRE_MEM_RASCIIZ("execve(filename)", ARG1);
   if (ARG2)
      ML_(pre_argv_envp)(ARG2, tid, "execve(argv)", "execve(argv[i])");
   if (ARG3)
      ML_(pre_argv_envp)(ARG3, tid, "execve(envp)", "execve(envp[i])");

   /* Erk.  If the exec fails, then the following will have made a mess of
      things which makes it hard for us to continue.  The right thing to do is
      piece everything together again in POST(execve), but that's close to
      impossible.  Instead, we make an effort to check that the execve will
      work before actually doing it. */

   const HChar *fname = (const HChar *) ARG1;
   if (ARG1_is_fd) {
      if (!ML_(fd_allowed)(ARG1, "execve", tid, False)) {
         SET_STATUS_Failure(VKI_EBADF);
         return;
      }

      if (VG_(resolve_filename)(ARG1, &fname) == False) {
         SET_STATUS_Failure(VKI_EBADF);
         return;
      }

      struct vg_stat stats;
      if (VG_(fstat)(ARG1, &stats) != 0) {
         SET_STATUS_Failure(VKI_EBADF);
         return;
      }

      if (stats.nlink > 1)
         VG_(unimplemented)("Syswrap of execve where fd points to a hardlink.");
   }

   /* Check that the name at least begins in client-accessible storage. */
   if (ARG1_is_fd == False) {
      if ((fname == NULL) || !ML_(safe_to_deref)(fname, 1)) {
         SET_STATUS_Failure(VKI_EFAULT);
         return;
      }
   }

   /* Check that the args at least begin in client-accessible storage.
      Solaris disallows to perform the exec without any arguments specified.
    */
   if (!ARG2 /* obviously bogus */ ||
       !VG_(am_is_valid_for_client)(ARG2, 1, VKI_PROT_READ)) {
      SET_STATUS_Failure(VKI_EFAULT);
      return;
   }

   /* Debug-only printing. */
   if (0) {
      VG_(printf)("ARG1 = %#lx(%s)\n", ARG1, fname);
      if (ARG2) {
         Int q;
         HChar** vec = (HChar**)ARG2;

         VG_(printf)("ARG2 = ");
         for (q = 0; vec[q]; q++)
            VG_(printf)("%p(%s) ", vec[q], vec[q]);
         VG_(printf)("\n");
      }
      else
         VG_(printf)("ARG2 = null\n");
   }

   /* Decide whether or not we want to follow along. */
   /* Make 'child_argv' be a pointer to the child's arg vector (skipping the
      exe name) */
   const HChar **child_argv = (const HChar **) ARG2;
   if (child_argv[0] == NULL)
      child_argv = NULL;
   Bool trace_this_child = VG_(should_we_trace_this_child)(fname, child_argv);

   /* Do the important checks:  it is a file, is executable, permissions are
      ok, etc.  We allow setuid executables to run only in the case when
      we are not simulating them, that is, they to be run natively. */
   Bool setuid_allowed = trace_this_child ? False : True;
   SysRes res = VG_(pre_exec_check)(fname, NULL, setuid_allowed);
   if (sr_isError(res)) {
      SET_STATUS_Failure(sr_Err(res));
      return;
   }

   /* If we're tracing the child, and the launcher name looks bogus (possibly
      because launcher.c couldn't figure it out, see comments therein) then we
      have no option but to fail. */
   if (trace_this_child &&
       (!VG_(name_of_launcher) || VG_(name_of_launcher)[0] != '/')) {
      SET_STATUS_Failure(VKI_ECHILD); /* "No child processes." */
      return;
   }

   /* After this point, we can't recover if the execve fails. */
   VG_(debugLog)(1, "syswrap", "Exec of %s\n", fname);

   /* Terminate gdbserver if it is active. */
   if (VG_(clo_vgdb) != Vg_VgdbNo) {
      /* If the child will not be traced, we need to terminate gdbserver to
         cleanup the gdbserver resources (e.g. the FIFO files). If child will
         be traced, we also terminate gdbserver: the new Valgrind will start a
         fresh gdbserver after exec. */
      VG_(gdbserver)(0);
   }

   /* Resistance is futile.  Nuke all other threads.  POSIX mandates this.
      (Really, nuke them all, since the new process will make its own new
      thread.) */
   VG_(nuke_all_threads_except)(tid, VgSrc_ExitThread);
   VG_(reap_threads)(tid);

   /* Set up the child's exe path. */
   const HChar *path = fname;
   const HChar *launcher_basename = NULL;
   if (trace_this_child) {
      /* We want to exec the launcher.  Get its pre-remembered path. */
      path = VG_(name_of_launcher);
      /* VG_(name_of_launcher) should have been acquired by m_main at
         startup. */
      vg_assert(path);

      launcher_basename = VG_(strrchr)(path, '/');
      if (!launcher_basename || launcher_basename[1] == '\0')
         launcher_basename = path;  /* hmm, tres dubious */
      else
         launcher_basename++;
   }

   /* Set up the child's environment.

      Remove the valgrind-specific stuff from the environment so the child
      doesn't get vgpreload_core.so, vgpreload_<tool>.so, etc.  This is done
      unconditionally, since if we are tracing the child, the child valgrind
      will set up the appropriate client environment.  Nb: we make a copy of
      the environment before trying to mangle it as it might be in read-only
      memory (bug #101881).

      Then, if tracing the child, set VALGRIND_LIB for it. */
   HChar **envp = NULL;
   if (ARG3 != 0) {
      envp = VG_(env_clone)((HChar**)ARG3);
      vg_assert(envp != NULL);
      VG_(env_remove_valgrind_env_stuff)(envp, True /*ro_strings*/, NULL);
   }

   if (trace_this_child) {
      /* Set VALGRIND_LIB in ARG3 (the environment). */
      VG_(env_setenv)( &envp, VALGRIND_LIB, VG_(libdir));
   }

   /* Set up the child's args.  If not tracing it, they are simply ARG2.
      Otherwise, they are:

      [launcher_basename] ++ VG_(args_for_valgrind) ++ [ARG1] ++ ARG2[1..],

      except that the first VG_(args_for_valgrind_noexecpass) args are
      omitted. */
   HChar **argv = NULL;
   if (!trace_this_child)
      argv = (HChar **) ARG2;
   else {
      Int tot_args;

      vg_assert(VG_(args_for_valgrind));
      vg_assert(VG_(args_for_valgrind_noexecpass) >= 0);
      vg_assert(VG_(args_for_valgrind_noexecpass)
                   <= VG_(sizeXA)(VG_(args_for_valgrind)));

      /* How many args in total will there be? */
      /* launcher basename */
      tot_args = 1;
      /* V's args */
      tot_args += VG_(sizeXA)(VG_(args_for_valgrind));
      tot_args -= VG_(args_for_valgrind_noexecpass);
      /* name of client exe */
      tot_args++;
      /* args for client exe, skipping [0] */
      HChar **arg2copy = (HChar **) ARG2;
      if (arg2copy[0] != NULL)
         for (i = 1; arg2copy[i]; i++)
            tot_args++;
      /* allocate */
      argv = VG_(malloc)("syswrap.exec.5", (tot_args + 1) * sizeof(HChar*));
      /* copy */
      j = 0;
      argv[j++] = CONST_CAST(HChar *, launcher_basename);
      for (i = 0; i < VG_(sizeXA)(VG_(args_for_valgrind)); i++) {
         if (i < VG_(args_for_valgrind_noexecpass))
            continue;
         argv[j++] = *(HChar**)VG_(indexXA)(VG_(args_for_valgrind), i);
      }
      argv[j++] = CONST_CAST(HChar *, fname);
      if (arg2copy[0] != NULL)
         for (i = 1; arg2copy[i]; i++)
            argv[j++] = arg2copy[i];
      argv[j++] = NULL;
      /* check */
      vg_assert(j == tot_args + 1);
   }

   /* Set the signal state up for exec.

      We need to set the real signal state to make sure the exec'd process
      gets SIG_IGN properly.

      Also set our real sigmask to match the client's sigmask so that the
      exec'd child will get the right mask.  First we need to clear out any
      pending signals so they they don't get delivered, which would confuse
      things.

      XXX This is a bug - the signals should remain pending, and be delivered
      to the new process after exec.  There's also a race-condition, since if
      someone delivers us a signal between the sigprocmask and the execve,
      we'll still get the signal. Oh well.
   */
   {
      vki_sigset_t allsigs;
      vki_siginfo_t info;

      /* What this loop does: it queries SCSS (the signal state that the
         client _thinks_ the kernel is in) by calling VG_(do_sys_sigaction),
         and modifies the real kernel signal state accordingly. */
      for (i = 1; i < VG_(max_signal); i++) {
         vki_sigaction_fromK_t sa_f;
         vki_sigaction_toK_t   sa_t;
         VG_(do_sys_sigaction)(i, NULL, &sa_f);
         VG_(convert_sigaction_fromK_to_toK)(&sa_f, &sa_t);
         VG_(sigaction)(i, &sa_t, NULL);
      }

      VG_(sigfillset)(&allsigs);
      while (VG_(sigtimedwait_zero)(&allsigs, &info) > 0)
         ;

      ThreadState *tst = VG_(get_ThreadState)(tid);
      VG_(sigprocmask)(VKI_SIG_SETMASK, &tst->sig_mask, NULL);
   }

   /* Restore the DATA rlimit for the child. */
   VG_(setrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));

   /* Debug-only printing. */
   if (0) {
      HChar **cpp;
      VG_(printf)("exec: %s\n", path);
      for (cpp = argv; cpp && *cpp; cpp++)
         VG_(printf)("argv: %s\n", *cpp);
      if (0)
         for (cpp = envp; cpp && *cpp; cpp++)
            VG_(printf)("env: %s\n", *cpp);
   }

#if defined(SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS)
   res = VG_(do_syscall4)(__NR_execve, (UWord) path, (UWord) argv,
                          (UWord) envp, ARG4 & ~VKI_EXEC_DESCRIPTOR);
#else
   res = VG_(do_syscall3)(__NR_execve, (UWord) path, (UWord) argv,
                          (UWord) envp);
#endif /* SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS */
   SET_STATUS_from_SysRes(res);

   /* If we got here, then the execve failed.  We've already made way too much
      of a mess to continue, so we have to abort. */
   vg_assert(FAILURE);
#if defined(SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS)
   if (ARG1_is_fd)
      VG_(message)(Vg_UserMsg, "execve(%ld, %#lx, %#lx, %lu) failed, "
                   "errno %ld\n", SARG1, ARG2, ARG3, ARG4, ERR);
   else
      VG_(message)(Vg_UserMsg, "execve(%#lx(%s), %#lx, %#lx, %ld) failed, errno"
                   " %lu\n", ARG1, (HChar *) ARG1, ARG2, ARG3, SARG4, ERR);
#else
   VG_(message)(Vg_UserMsg, "execve(%#lx(%s), %#lx, %#lx) failed, errno %lu\n",
                ARG1, (HChar *) ARG1, ARG2, ARG3, ERR);
#endif /* SOLARIS_EXECVE_SYSCALL_TAKES_FLAGS */
   VG_(message)(Vg_UserMsg, "EXEC FAILED: I can't recover from "
                            "execve() failing, so I'm dying.\n");
   VG_(message)(Vg_UserMsg, "Add more stringent tests in PRE(sys_execve), "
                            "or work out how to recover.\n");
   VG_(exit)(101);
   /*NOTREACHED*/
}

static void pre_mem_read_flock(ThreadId tid, struct vki_flock *lock)
{
   PRE_FIELD_READ("fcntl(lock->l_type)", lock->l_type);
   PRE_FIELD_READ("fcntl(lock->l_whence)", lock->l_whence);
   PRE_FIELD_READ("fcntl(lock->l_start)", lock->l_start);
   PRE_FIELD_READ("fcntl(lock->l_len)", lock->l_len);
}

#if defined(VGP_x86_solaris)
static void pre_mem_read_flock64(ThreadId tid, struct vki_flock64 *lock)
{
   PRE_FIELD_READ("fcntl(lock->l_type)", lock->l_type);
   PRE_FIELD_READ("fcntl(lock->l_whence)", lock->l_whence);
   PRE_FIELD_READ("fcntl(lock->l_start)", lock->l_start);
   PRE_FIELD_READ("fcntl(lock->l_len)", lock->l_len);
}
#endif /* VGP_x86_solaris */

PRE(sys_fcntl)
{
   /* int fcntl(int fildes, int cmd, ...); */

   switch (ARG2 /*cmd*/) {
   /* These ones ignore ARG3. */
   case VKI_F_GETFD:
   case VKI_F_GETFL:
   case VKI_F_GETXFL:
      PRINT("sys_fcntl ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, "fcntl", int, fildes, int, cmd);
      break;

   /* These ones use ARG3 as "arg". */
   case VKI_F_DUPFD:
   case VKI_F_SETFD:
   case VKI_F_SETFL:
   case VKI_F_DUP2FD:
   case VKI_F_BADFD:
      PRINT("sys_fcntl ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
      PRE_REG_READ3(long, "fcntl", int, fildes, int, cmd, int, arg);
      /* Check if a client program isn't going to poison any of V's output
         fds. */
      if (ARG2 == VKI_F_DUP2FD &&
          !ML_(fd_allowed)(ARG3, "fcntl(F_DUP2FD)", tid, False)) {
         SET_STATUS_Failure(VKI_EBADF);
         return;
      }
      break;

   /* These ones use ARG3 as "native lock" (input only). */
   case VKI_F_SETLK:
   case VKI_F_SETLKW:
   case VKI_F_ALLOCSP:
   case VKI_F_FREESP:
   case VKI_F_SETLK_NBMAND:
      PRINT("sys_fcntl ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, "fcntl", int, fildes, int, cmd,
                    struct flock *, lock);
      pre_mem_read_flock(tid, (struct vki_flock*)ARG3);
      break;

   /* This one uses ARG3 as "native lock" (input&output). */
   case VKI_F_GETLK:
      PRINT("sys_fcntl ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, "fcntl", int, fildes, int, cmd,
                    struct flock *, lock);
      pre_mem_read_flock(tid, (struct vki_flock*)ARG3);
      PRE_MEM_WRITE("fcntl(lock)", ARG3, sizeof(struct vki_flock));
      break;

#if defined(VGP_x86_solaris)
   /* These ones use ARG3 as "transitional 64b lock" (input only). */
   case VKI_F_SETLK64:
   case VKI_F_SETLKW64:
   case VKI_F_ALLOCSP64:
   case VKI_F_FREESP64:
   case VKI_F_SETLK64_NBMAND:
      PRINT("sys_fcntl ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, "fcntl", int, fildes, int, cmd,
                    struct flock64 *, lock);
      pre_mem_read_flock64(tid, (struct vki_flock64*)ARG3);
      break;

   /* This one uses ARG3 as "transitional 64b lock" (input&output). */
   case VKI_F_GETLK64:
      PRINT("sys_fcntl ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, "fcntl", int, fildes, int, cmd,
                    struct flock64 *, lock);
      pre_mem_read_flock64(tid, (struct vki_flock64*)ARG3);
      PRE_MEM_WRITE("fcntl(lock)", ARG3, sizeof(struct vki_flock64));
      break;
#endif /* VGP_x86_solaris */

   /* These ones use ARG3 as "fshare". */
   case VKI_F_SHARE:
   case VKI_F_UNSHARE:
   case VKI_F_SHARE_NBMAND:
      PRINT("sys_fcntl[ARG3=='fshare'] ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, "fcntl", int, fildes, int, cmd,
                    struct fshare *, sh);
      PRE_MEM_READ("fcntl(fshare)", ARG3, sizeof(struct vki_fshare));
      break;

   default:
      VG_(unimplemented)("Syswrap of the fcntl call with cmd %ld.", SARG2);
      /*NOTREACHED*/
      break;
   }

   if (ARG2 == VKI_F_SETLKW
#if defined(VGP_x86_solaris)
       || ARG2 == VKI_F_SETLKW64
#endif /* VGP_x86_solaris */
       )
      *flags |= SfMayBlock;

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "fcntl", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_fcntl)
{
   switch (ARG2 /*cmd*/) {
   case VKI_F_DUPFD:
      if (!ML_(fd_allowed)(RES, "fcntl(F_DUPFD)", tid, True)) {
         VG_(close)(RES);
         SET_STATUS_Failure(VKI_EMFILE);
      }
      else if (VG_(clo_track_fds))
         ML_(record_fd_open_named)(tid, RES);
      break;

   case VKI_F_DUP2FD:
      if (!ML_(fd_allowed)(RES, "fcntl(F_DUP2FD)", tid, True)) {
         VG_(close)(RES);
         SET_STATUS_Failure(VKI_EMFILE);
      }
      else if (VG_(clo_track_fds))
         ML_(record_fd_open_named)(tid, RES);
      break;

   /* This one uses ARG3 as "native lock" (input&output). */
   case VKI_F_GETLK:
      POST_MEM_WRITE(ARG3, sizeof(struct vki_flock));
      break;

#if defined(VGP_x86_solaris)
   /* This one uses ARG3 as "transitional 64b lock" (input&output). */
   case VKI_F_GETLK64:
      POST_MEM_WRITE(ARG3, sizeof(struct vki_flock64));
      break;
#endif /* VGP_x86_solaris */

   default:
      break;
   }
}

PRE(sys_renameat)
{
   /* int renameat(int fromfd, const char *old, int tofd, const char *new); */

   /* Interpret the first and third arguments as 32-bit values even on 64-bit
      architecture. This is different from Linux, for example, where glibc
      sign-extends them. */
   Int fromfd = (Int) ARG1;
   Int tofd = (Int) ARG3;

   *flags |= SfMayBlock;
   PRINT("sys_renameat ( %d, %#lx(%s), %d, %#lx(%s) )", fromfd,
         ARG2, (HChar *) ARG2, tofd, ARG4, (HChar *) ARG4);
   PRE_REG_READ4(long, "renameat", int, fromfd, const char *, old,
                 int, tofd, const char *, new);

   PRE_MEM_RASCIIZ("renameat(old)", ARG2);
   PRE_MEM_RASCIIZ("renameat(new)", ARG4);

   /* Be strict but ignore fromfd/tofd for absolute old/new. */
   if (fromfd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fromfd, "renameat", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
   }
   if (tofd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG4, 1)
       && ((HChar *) ARG4)[0] != '/'
       && !ML_(fd_allowed)(tofd, "renameat", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
   }
}

PRE(sys_unlinkat)
{
   /* int unlinkat(int dirfd, const char *pathname, int flags); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int dfd = (Int) ARG1;

   *flags |= SfMayBlock;
   PRINT("sys_unlinkat ( %d, %#lx(%s), %ld )", dfd, ARG2, (HChar *) ARG2,
         SARG3);
   PRE_REG_READ3(long, "unlinkat", int, dirfd, const char *, pathname,
                 int, flags);
   PRE_MEM_RASCIIZ("unlinkat(pathname)", ARG2);

   /* Be strict but ignore dfd for absolute pathname. */
   if (dfd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(dfd, "unlinkat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_fstatat)
{
   /* int fstatat(int fildes, const char *path, struct stat *buf,
                    int flag); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_fstatat ( %d, %#lx(%s), %#lx, %ld )", fd, ARG2,
         (HChar *) ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "fstatat", int, fildes, const char *, path,
                 struct stat *, buf, int, flag);
   if (ARG2) {
      /* Only test ARG2 if it isn't NULL.  The kernel treats the NULL-case as
         fstat(fildes, buf). */
      PRE_MEM_RASCIIZ("fstatat(path)", ARG2);
   }
   PRE_MEM_WRITE("fstatat(buf)", ARG3, sizeof(struct vki_stat));

   /* Be strict but ignore fildes for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "fstatat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_fstatat)
{
   POST_MEM_WRITE(ARG3, sizeof(struct vki_stat));
}

PRE(sys_openat)
{
   /* int openat(int fildes, const char *filename, int flags);
      int openat(int fildes, const char *filename, int flags, mode_t mode); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   if (ARG3 & VKI_O_CREAT) {
      /* 4-arg version */
      PRINT("sys_openat ( %d, %#lx(%s), %ld, %ld )", fd, ARG2, (HChar *) ARG2,
            SARG3, SARG4);
      PRE_REG_READ4(long, "openat", int, fildes, const char *, filename,
                    int, flags, vki_mode_t, mode);
   }
   else {
      /* 3-arg version */
      PRINT("sys_openat ( %d, %#lx(%s), %ld )", fd, ARG2, (HChar *) ARG2,
            SARG3);
      PRE_REG_READ3(long, "openat", int, fildes, const char *, filename,
                    int, flags);
   }

   PRE_MEM_RASCIIZ("openat(filename)", ARG2);

   /* Be strict but ignore fildes for absolute pathname. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "openat", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
      return;
   }

   if (ML_(handle_auxv_open)(status, (const HChar *) ARG2, ARG3))
      return;

   if (handle_psinfo_open(status, True /*use_openat*/, (const HChar *) ARG2,
                          fd, ARG3, ARG4))
      return;

#if defined(SOLARIS_PROC_CMDLINE)
   if (handle_cmdline_open(status, (const HChar *) ARG2))
      return;
#endif /* SOLARIS_PROC_CMDLINE */

   *flags |= SfMayBlock;
}

POST(sys_openat)
{
   if (!ML_(fd_allowed)(RES, "openat", tid, True)) {
      VG_(close)(RES);
      SET_STATUS_Failure(VKI_EMFILE);
   }
   else if (VG_(clo_track_fds))
      ML_(record_fd_open_with_given_name)(tid, RES, (HChar*)ARG2);
}

PRE(sys_tasksys)
{
   /* Kernel: long tasksys(int code, projid_t projid, uint_t flags,
                           void *projidbuf, size_t pbufsz);
    */
   switch (ARG1 /*code*/) {
   case 0:
      /* Libc: taskid_t settaskid(projid_t project, uint_t flags); */
      PRINT("sys_tasksys ( %ld, %ld, %lu )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("tasksys", "settaskid"), int, code,
                    vki_projid_t, projid, vki_uint_t, flags);
      break;
   case 1:
      /* Libc: taskid_t gettaskid(void); */
      PRINT("sys_tasksys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("tasksys", "gettaskid"), int, code);
      break;
   case 2:
      /* Libc: projid_t getprojid(void); */
      PRINT("sys_tasksys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("tasksys", "getprojid"), int, code);
      break;
   case 3:
      /* Libproject: size_t projlist(id_t *idbuf, size_t idbufsz); */
      PRINT("sys_tasksys ( %ld, %#lx, %lu )", SARG1, ARG4, ARG5);
      PRE_REG_READ3(long, SC2("tasksys", "projlist"), int, code,
                    vki_id_t *, idbuf, vki_size_t, idbufsz);
      PRE_MEM_WRITE("tasksys(idbuf)", ARG4, ARG5);
      break;
   default:
      VG_(unimplemented)("Syswrap of the tasksys call with code %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_tasksys)
{
   switch (ARG1 /*code*/) {
   case 0:
   case 1:
   case 2:
      break;
   case 3:
      if ((ARG4 != 0) && (ARG5 != 0))
         POST_MEM_WRITE(ARG4, MIN(RES, ARG5));
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_lwp_park)
{
   /* Kernel: int lwp_park(int which, uintptr_t arg1, uintptr_t arg2);
    */
   *flags |= SfMayBlock;
   switch (ARG1 /*which*/) {
   case 0:
      /* Libc: int lwp_park(timespec_t *timeout, id_t lwpid); */
      PRINT("sys_lwp_park ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
      PRE_REG_READ3(long, SC2("lwp_park", "lwp_park"), int, which,
                    timespec_t *, timeout, vki_id_t, lwpid);
      if (ARG2) {
         PRE_MEM_READ("lwp_park(timeout)", ARG2, sizeof(vki_timespec_t));
         /*PRE_MEM_WRITE("lwp_park(timeout)", ARG2,
                         sizeof(vki_timespec_t));*/
      }
      break;
   case 1:
      /* Libc: int lwp_unpark(id_t lwpid); */
      PRINT("sys_lwp_park ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("lwp_park", "lwp_unpark"), int, which,
                    vki_id_t, lwpid);
      break;
   case 2:
      /* Libc: int lwp_unpark_all(id_t *lwpid, int nids); */
      PRINT("sys_lwp_park ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
      PRE_REG_READ3(long, SC2("lwp_park", "lwp_unpark_all"), int, which,
                    id_t *, lwpid, int, nids);
      PRE_MEM_READ("lwp_park(lwpid)", ARG2, ARG3 * sizeof(vki_id_t));
      break;
   default:
      VG_(unimplemented)("Syswrap of the lwp_park call with which %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_lwp_park)
{
   switch (ARG1 /*which*/) {
   case 0:
      if (ARG2)
         POST_MEM_WRITE(ARG2, sizeof(vki_timespec_t));
      break;
   case 1:
   case 2:
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_sendfilev)
{
   /* Kernel: ssize_t sendfilev(int opcode, int fd,
                                const struct sendfilevec *vec,
                                int sfvcnt, size_t *xferred);
    */
   PRINT("sys_sendfilev ( %ld, %ld, %#lx, %ld, %#lx )",
         SARG1, SARG2, ARG3, SARG4, ARG5);

   switch (ARG1 /*opcode*/) {
   case VKI_SENDFILEV:
      {
         PRE_REG_READ5(long, "sendfilev", int, opcode, int, fd,
                       const struct vki_sendfilevec *, vec,
                       int, sfvcnt, vki_size_t *, xferred);

         PRE_MEM_READ("sendfilev(vec)", ARG3,
                      ARG4 * sizeof(struct vki_sendfilevec));
         PRE_MEM_WRITE("sendfilev(xferred)", ARG5, sizeof(vki_size_t));

         struct vki_sendfilevec *vec = (struct vki_sendfilevec *) ARG3;
         if (ML_(safe_to_deref)(vec, ARG4 *
                                sizeof(struct vki_sendfilevec))) {
            UInt i;
            for (i = 0; i < ARG4; i++) {
               HChar desc[35];    // large enough
               if (vec[i].sfv_fd == VKI_SFV_FD_SELF) {
                  VG_(snprintf)(desc, sizeof(desc),
                                "sendfilev(vec[%u].sfv_off", i);
                  PRE_MEM_READ(desc, vec[i].sfv_off, vec[i].sfv_len);
               } else {
                  VG_(snprintf)(desc, sizeof(desc),
                                "sendfilev(vec[%u].sfv_fd)", i);
                  if (!ML_(fd_allowed)(vec[i].sfv_fd, desc, tid, False))
                     SET_STATUS_Failure(VKI_EBADF);
               }
            }
         }
      }
      break;
   case VKI_SENDFILEV64:
      {
         PRE_REG_READ5(long, "sendfilev", int, opcode, int, fd,
                       const struct vki_sendfilevec64 *, vec,
                       int, sfvcnt, vki_size_t *, xferred);

         PRE_MEM_READ("sendfilev(vec)", ARG3,
                      ARG4 * sizeof(struct vki_sendfilevec64));
         PRE_MEM_WRITE("sendfilev(xferred)", ARG5, sizeof(vki_size_t));

         struct vki_sendfilevec64 *vec64 =
            (struct vki_sendfilevec64 *) ARG3;
         if (ML_(safe_to_deref)(vec64, ARG4 *
                                sizeof(struct vki_sendfilevec64))) {
            UInt i;
            for (i = 0; i < ARG4; i++) {
               HChar desc[35];    // large enough
               if (vec64[i].sfv_fd == VKI_SFV_FD_SELF) {
                  VG_(snprintf)(desc, sizeof(desc),
                                "sendfilev(vec[%u].sfv_off", i);
                  PRE_MEM_READ(desc, vec64[i].sfv_off, vec64[i].sfv_len);
               } else {
                  VG_(snprintf)(desc, sizeof(desc),
                                "sendfilev(vec[%u].sfv_fd)", i);
                  if (!ML_(fd_allowed)(vec64[i].sfv_fd, desc,
                                       tid, False))
                     SET_STATUS_Failure(VKI_EBADF);
               }
            }
         }
      }
      break;
   default:
      VG_(unimplemented)("Syswrap of the sendfilev call with "
                         "opcode %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG2, "sendfilev(fd)", tid, False))
      SET_STATUS_Failure(VKI_EBADF);

   *flags |= SfMayBlock;
}

POST(sys_sendfilev)
{
   POST_MEM_WRITE(ARG5, sizeof(vki_size_t));
}

#if defined(SOLARIS_LWP_NAME_SYSCALL)
PRE(sys_lwp_name)
{
   /* int lwp_name(int opcode, id_t lwpid, char *name, size_t len); */
   PRINT("sys_lwp_name ( %ld, %ld, %#lx, %lu )", SARG1, SARG2, ARG3, ARG4);

   switch (ARG1 /*opcode*/) {
   case 0:
      /* lwp_setname */
      PRE_REG_READ3(long, "lwp_name", int, opcode, vki_id_t, lwpid,
                    char *, name);
      PRE_MEM_RASCIIZ("lwp_name(name)", ARG3);
      break;
   case 1:
      /* lwp_getname */
      PRE_REG_READ4(long, "lwp_name", int, opcode, vki_id_t, lwpid,
                    char *, name, vki_size_t, len);
      PRE_MEM_WRITE("lwp_name(name)", ARG3, ARG4);
      break;
   default:
      VG_(unimplemented)("Syswrap of the lwp_name call with opcode %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_lwp_name)
{
   switch (ARG1 /*opcode*/) {
   case 0:
      if (ARG3) { // Paranoia
         const HChar *new_name = (const HChar *) ARG3;
         ThreadState *tst = VG_(get_ThreadState)(tid);
         SizeT new_len = VG_(strlen)(new_name);

         /* Don't bother reusing the memory. This is a rare event. */
         tst->thread_name = VG_(realloc)("syswrap.lwp_name", tst->thread_name,
                                         new_len + 1);
         VG_(strcpy)(tst->thread_name, new_name);
      }
      break;
   case 1:
      POST_MEM_WRITE(ARG3, VG_(strlen)((HChar *) ARG3) + 1);
      break;
   default:
      vg_assert(0);
      break;
   }
}
#endif /* SOLARIS_LWP_NAME_SYSCALL */

PRE(sys_privsys)
{
   /* Kernel: int privsys(int code, priv_op_t op, priv_ptype_t type,
                          void *buf, size_t bufsize, int itype);
    */
   switch (ARG1 /*code*/) {
   case VKI_PRIVSYS_SETPPRIV:
      /* Libc: int setppriv(priv_op_t op, priv_ptype_t type,
                            const priv_set_t *pset);
       */
      PRINT("sys_privsys ( %ld, %ld, %ld, %#lx, %lu )", SARG1, SARG2, SARG3,
            ARG4, ARG5);
      PRE_REG_READ5(long, SC2("privsys", "setppriv"), int, code,
                    vki_priv_op_t, op, vki_priv_ptype_t, type,
                    const priv_set_t *, pset, vki_size_t, bufsize);
      PRE_MEM_READ("privsys(pset)", ARG4, ARG5);
      break;
   case VKI_PRIVSYS_GETPPRIV:
      /* Libc: int getppriv(priv_ptype_t type, priv_set_t *pset);
               priv_set_t *pset -> void *buf
       */
      PRINT("sys_privsys ( %ld, %ld, %ld, %#lx, %lu )", SARG1, SARG2, SARG3,
            ARG4, ARG5);
      PRE_REG_READ5(long, SC2("privsys", "getppriv"), int, code,
            vki_priv_op_t, op, vki_priv_ptype_t, type, priv_set_t *, pset,
            vki_size_t, bufsize);
      PRE_MEM_WRITE("privsys(pset)", ARG4, ARG5);
      break;
   case VKI_PRIVSYS_GETIMPLINFO:
      /* Libc: int getprivinfo(priv_impl_info_t *buf, size_t bufsize);
               priv_impl_info_t *buf -> void *buf
       */
      PRINT("sys_privsys ( %ld, %ld, %ld, %#lx, %lu )", SARG1, SARG2, SARG3,
            ARG4, ARG5);
      PRE_REG_READ5(long, SC2("privsys", "getprivinfo"), int, code,
            vki_priv_op_t, op, vki_priv_ptype_t, type,
            priv_impl_info_t *, buf, vki_size_t, bufsize);
      PRE_MEM_WRITE("privsys(buf)", ARG4, ARG5);
      break;
   case VKI_PRIVSYS_SETPFLAGS:
      /* Libc: int setpflags(uint_t flag, uint_t val);
               uint_t flag -> priv_op_t op
               uint_t val -> priv_ptype_t type
       */
      PRINT("sys_privsys ( %ld, %lu, %lu )", SARG1, ARG2, ARG3);
      PRE_REG_READ3(long, SC2("privsys", "setpflags"), int, code,
                    vki_uint_t, flag, vki_uint_t, val);
      break;
   case VKI_PRIVSYS_GETPFLAGS:
      /* Libc: uint_t getpflags(uint_t flag);
               uint_t flag -> priv_op_t op
       */
      PRINT("sys_privsys ( %ld, %lu )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("privsys", "setpflags"), int, code,
                    vki_uint_t, flag);
      break;
   case VKI_PRIVSYS_ISSETUGID:
      /* Libc: int issetugid(void); */
      PRINT("sys_privsys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("privsys", "issetugid"), int, code);
      break;
   case VKI_PRIVSYS_PFEXEC_REG:
      /* Libc: int register_pfexec(int did);
               int did -> priv_op_t op
       */
      PRINT("sys_privsys ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("privsys", "register_pfexec"), int, code,
                    int, did);
      break;
   case VKI_PRIVSYS_PFEXEC_UNREG:
      /* Libc: int unregister_pfexec(int did); */
      PRINT("sys_privsys ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("privsys", "unregister_pfexec"), int, code,
                    int, did);
      break;
   default:
      VG_(unimplemented)("Syswrap of the privsys call with code %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }

   /* Be strict. */
   if ((ARG1 == VKI_PRIVSYS_PFEXEC_REG ||
        ARG1 == VKI_PRIVSYS_PFEXEC_UNREG) &&
       !ML_(fd_allowed)(ARG2, "privsys", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_privsys)
{
   switch (ARG1 /*code*/) {
   case VKI_PRIVSYS_SETPPRIV:
      break;
   case VKI_PRIVSYS_GETPPRIV:
      POST_MEM_WRITE(ARG4, sizeof(vki_priv_set_t));
      break;
   case VKI_PRIVSYS_GETIMPLINFO:
      /* The kernel copy outs data of size min(bufsize, privinfosize).
         Unfortunately, it does not seem to be possible to easily obtain the
         privinfosize value.  The code below optimistically marks all ARG5
         bytes (aka bufsize) as written by the kernel. */
      POST_MEM_WRITE(ARG4, ARG5);
      break;
   case VKI_PRIVSYS_SETPFLAGS:
   case VKI_PRIVSYS_GETPFLAGS:
   case VKI_PRIVSYS_ISSETUGID:
   case VKI_PRIVSYS_PFEXEC_REG:
   case VKI_PRIVSYS_PFEXEC_UNREG:
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_ucredsys)
{
   /* Kernel: int ucredsys(int code, int obj, void *buf); */
   PRINT("sys_ucredsys ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);

   switch (ARG1 /*code*/) {
   case VKI_UCREDSYS_UCREDGET:
      /* Libc: ucred_t *ucred_get(pid_t pid); */
      PRE_REG_READ3(long, SC2("ucredsys", "ucredget"), int, code,
                    vki_pid_t, pid, vki_ucred_t *, buf);
      PRE_MEM_WRITE("ucredsys(buf)", ARG3, sizeof(vki_ucred_t));
      break;

   case VKI_UCREDSYS_GETPEERUCRED:
      /* Libc: int getpeerucred(int fd, ucred_t **ucred); */
      PRE_REG_READ3(long, SC2("ucredsys", "getpeerucred"), int, code,
                    int, fd, vki_ucred_t *, buf);
      PRE_MEM_WRITE("ucredsys(buf)", ARG3, sizeof(vki_ucred_t));

      /* Be strict. */
      if (!ML_(fd_allowed)(ARG2, "ucredsys", tid, False))
         SET_STATUS_Failure(VKI_EBADF);
      break;

   default:
      VG_(unimplemented)("Syswrap of the ucredsys call with code %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_ucredsys)
{
   switch (ARG1 /*code*/) {
   case VKI_UCREDSYS_UCREDGET:
   case VKI_UCREDSYS_GETPEERUCRED:
      vg_assert(ARG3 != 0);
      POST_MEM_WRITE(ARG3, ((vki_ucred_t *) ARG3)->uc_size);
      break;

   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_getmsg)
{
   /* int getmsg(int fildes, struct strbuf *ctlptr, struct strbuf *dataptr,
                 int *flagsp); */
   struct vki_strbuf *ctrlptr = (struct vki_strbuf *)ARG2;
   struct vki_strbuf *dataptr = (struct vki_strbuf *)ARG3;
   *flags |= SfMayBlock;
   PRINT("sys_getmsg ( %ld, %#lx, %#lx, %#lx )", SARG1, ARG2, ARG3, ARG4);
   PRE_REG_READ4(long, "getmsg", int, fildes, struct vki_strbuf *, ctlptr,
                 struct vki_strbuf *, dataptr, int *, flagsp);
   if (ctrlptr) {
      PRE_FIELD_READ("getmsg(ctrlptr->maxlen)", ctrlptr->maxlen);
      PRE_FIELD_WRITE("getmsg(ctrlptr->len)", ctrlptr->len);
      PRE_FIELD_READ("getmsg(ctrlptr->buf)", ctrlptr->buf);
      if (ML_(safe_to_deref)((void*)ARG2, sizeof(struct vki_strbuf))
          && ctrlptr->maxlen > 0)
         PRE_MEM_WRITE("getmsg(ctrlptr->buf)", (Addr)ctrlptr->buf,
                       ctrlptr->maxlen);
   }
   if (dataptr) {
      PRE_FIELD_READ("getmsg(dataptr->maxlen)", dataptr->maxlen);
      PRE_FIELD_WRITE("getmsg(dataptr->len)", dataptr->len);
      PRE_FIELD_READ("getmsg(dataptr->buf)", dataptr->buf);
      if (ML_(safe_to_deref)((void*)ARG3, sizeof(struct vki_strbuf))
          && dataptr->maxlen > 0)
         PRE_MEM_WRITE("getmsg(dataptr->buf)", (Addr)dataptr->buf,
                       dataptr->maxlen);
   }
   PRE_MEM_READ("getmsg(flagsp)", ARG4, sizeof(int));
   /*PRE_MEM_WRITE("getmsg(flagsp)", ARG4, sizeof(int));*/

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "getmsg", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_getmsg)
{
   struct vki_strbuf *ctrlptr = (struct vki_strbuf *)ARG2;
   struct vki_strbuf *dataptr = (struct vki_strbuf *)ARG3;

   if (ctrlptr && ctrlptr->len > 0)
      POST_MEM_WRITE((Addr)ctrlptr->buf, ctrlptr->len);
   if (dataptr && dataptr->len > 0)
      POST_MEM_WRITE((Addr)dataptr->buf, dataptr->len);
   POST_MEM_WRITE(ARG4, sizeof(int));
}

PRE(sys_putmsg)
{
   /* int putmsg(int fildes, struct strbuf *ctlptr, struct strbuf *dataptr,
                 int flags); */
   struct vki_strbuf *ctrlptr = (struct vki_strbuf *)ARG2;
   struct vki_strbuf *dataptr = (struct vki_strbuf *)ARG3;
   *flags |= SfMayBlock;
   PRINT("sys_putmsg ( %ld, %#lx, %#lx, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "putmsg", int, fildes, struct vki_strbuf *, ctrlptr,
                 struct vki_strbuf *, dataptr, int, flags);
   if (ctrlptr) {
      PRE_FIELD_READ("putmsg(ctrlptr->len)", ctrlptr->len);
      PRE_FIELD_READ("putmsg(ctrlptr->buf)", ctrlptr->buf);
      if (ML_(safe_to_deref)((void*)ARG2, sizeof(struct vki_strbuf))
          && ctrlptr->len > 0)
         PRE_MEM_READ("putmsg(ctrlptr->buf)", (Addr)ctrlptr->buf,
                      ctrlptr->len);
   }
   if (dataptr) {
      PRE_FIELD_READ("putmsg(dataptr->len)", dataptr->len);
      PRE_FIELD_READ("putmsg(dataptr->buf)", dataptr->buf);
      if (ML_(safe_to_deref)((void*)ARG3, sizeof(struct vki_strbuf))
          && dataptr->len > 0)
         PRE_MEM_READ("putmsg(dataptr->buf)", (Addr)dataptr->buf,
                      dataptr->len);
   }

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "putmsg", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_lstat)
{
   /* int lstat(const char *path, struct stat *buf); */
   /* Note: We could use here the sys_newlstat generic wrapper, but the 'new'
      in its name is rather confusing in the Solaris context, thus we provide
      our own wrapper. */
   PRINT("sys_lstat ( %#lx(%s), %#lx )", ARG1, (HChar *) ARG1, ARG2);
   PRE_REG_READ2(long, "lstat", const char *, path, struct stat *, buf);

   PRE_MEM_RASCIIZ("lstat(path)", ARG1);
   PRE_MEM_WRITE("lstat(buf)", ARG2, sizeof(struct vki_stat));
}

POST(sys_lstat)
{
   POST_MEM_WRITE(ARG2, sizeof(struct vki_stat));
}

PRE(sys_sigprocmask)
{
   /* int sigprocmask(int how, const sigset_t *set, sigset_t *oset); */
   PRINT("sys_sigprocmask ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "sigprocmask",
                 int, how, vki_sigset_t *, set, vki_sigset_t *, oset);
   if (ARG2)
      PRE_MEM_READ("sigprocmask(set)", ARG2, sizeof(vki_sigset_t));
   if (ARG3)
      PRE_MEM_WRITE("sigprocmask(oset)", ARG3, sizeof(vki_sigset_t));

   /* Be safe. */
   if (ARG2 && !ML_(safe_to_deref((void*)ARG2, sizeof(vki_sigset_t)))) {
      SET_STATUS_Failure(VKI_EFAULT);
   }
   if (ARG3 && !ML_(safe_to_deref((void*)ARG3, sizeof(vki_sigset_t)))) {
      SET_STATUS_Failure(VKI_EFAULT);
   }

   if (!FAILURE)
      SET_STATUS_from_SysRes(
         VG_(do_sys_sigprocmask)(tid, ARG1 /*how*/, (vki_sigset_t*)ARG2,
                                 (vki_sigset_t*)ARG3)
      );

   if (SUCCESS)
      *flags |= SfPollAfter;
}

POST(sys_sigprocmask)
{
   if (ARG3)
      POST_MEM_WRITE(ARG3, sizeof(vki_sigset_t));
}

PRE(sys_sigaction)
{
   /* int sigaction(int signal, const struct sigaction *act,
                    struct sigaction *oact); */
   PRINT("sys_sigaction ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "sigaction", int, signal,
                 const struct sigaction *, act, struct sigaction *, oact);

   /* Note that on Solaris, vki_sigaction_toK_t and vki_sigaction_fromK_t are
      both typedefs of 'struct sigaction'. */

   if (ARG2) {
      vki_sigaction_toK_t *sa = (vki_sigaction_toK_t*)ARG2;
      PRE_FIELD_READ("sigaction(act->sa_flags)", sa->sa_flags);
      PRE_FIELD_READ("sigaction(act->sa_handler)", sa->ksa_handler);
      PRE_FIELD_READ("sigaction(act->sa_mask)", sa->sa_mask);
   }
   if (ARG3)
      PRE_MEM_WRITE("sigaction(oact)", ARG3, sizeof(vki_sigaction_fromK_t));

   /* Be safe. */
   if (ARG2 && !ML_(safe_to_deref((void*)ARG2,
                                  sizeof(vki_sigaction_toK_t)))) {
      SET_STATUS_Failure(VKI_EFAULT);
   }
   if (ARG3 && !ML_(safe_to_deref((void*)ARG3,
                                   sizeof(vki_sigaction_fromK_t)))) {
      SET_STATUS_Failure(VKI_EFAULT);
   }

   if (!FAILURE)
      SET_STATUS_from_SysRes(
         VG_(do_sys_sigaction)(ARG1, (const vki_sigaction_toK_t*)ARG2,
                              (vki_sigaction_fromK_t*)ARG3));
}

POST(sys_sigaction)
{
   if (ARG3)
      POST_MEM_WRITE(ARG3, sizeof(vki_sigaction_fromK_t));
}

PRE(sys_sigpending)
{
   /* int sigpending(int flag, sigset_t *setp); */
   PRINT("sys_sigpending ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "sigpending", int, flag, sigset_t *, setp);
   PRE_MEM_WRITE("sigpending(setp)", ARG2, sizeof(vki_sigset_t));
}

POST(sys_sigpending)
{
   POST_MEM_WRITE(ARG2, sizeof(vki_sigset_t));
}

PRE(sys_getsetcontext)
{
   /* Kernel: int getsetcontext(int flag, void *arg) */
   ThreadState *tst = VG_(get_ThreadState)(tid);
   PRINT("sys_getsetcontext ( %ld, %#lx )", SARG1, ARG2);
   switch (ARG1 /*flag*/) {
   case VKI_GETCONTEXT:
      /* Libc: int getcontext(ucontext_t *ucp); */
      PRE_REG_READ2(long, SC2("getsetcontext", "getcontext"), int, flag,
                    ucontext_t *, ucp);
      PRE_MEM_WRITE("getsetcontext(ucp)", ARG2, sizeof(vki_ucontext_t));

      if (!ML_(safe_to_deref((void*)ARG2, sizeof(vki_ucontext_t)))) {
         SET_STATUS_Failure(VKI_EFAULT);
         return;
      }
      VG_(save_context)(tid, (vki_ucontext_t*)ARG2, Vg_CoreSysCall);
      SET_STATUS_Success(0);
      break;
   case VKI_SETCONTEXT:
      /* Libc: int setcontext(const ucontext_t *ucp); */
      PRE_REG_READ2(long, SC2("getsetcontext", "setcontext"), int, flag,
                    const ucontext_t *, ucp);

      if (!ARG2) {
         /* Setting NULL context causes thread exit. */
         tst->exitreason = VgSrc_ExitThread;
         tst->os_state.exitcode = 0;
         SET_STATUS_Success(0);
         return;
      }

      if (!ML_(safe_to_deref((void*)ARG2, sizeof(vki_ucontext_t)))) {
         SET_STATUS_Failure(VKI_EFAULT);
         return;
      }

      VG_(restore_context)(tid, (vki_ucontext_t*)ARG2,
                           Vg_CoreSysCall, False/*esp_is_thrptr*/);
      /* Tell the driver not to update the guest state with the "result". */
      *flags |= SfNoWriteResult;
      /* Check to see if any signals arose as a result of this. */
      *flags |= SfPollAfter;

      /* Check if this is a possible return from a signal handler. */
      VG_(sigframe_return)(tid, (vki_ucontext_t*)ARG2);

      SET_STATUS_Success(0);
      break;
   case VKI_GETUSTACK:
      /* Libc: int getustack(stack_t **spp); */
      PRE_REG_READ2(long, SC2("getsetcontext", "getustack"), int, flag,
                    stack_t **, spp);
      PRE_MEM_WRITE("getsetcontext(spp)", ARG2, sizeof(vki_stack_t*));

      if (!ML_(safe_to_deref((void*)ARG2, sizeof(vki_stack_t*)))) {
         SET_STATUS_Failure(VKI_EFAULT);
         return;
      }

      *(vki_stack_t**)ARG2 = tst->os_state.ustack;
      POST_MEM_WRITE(ARG2, sizeof(vki_stack_t*));
      SET_STATUS_Success(0);
      break;
   case VKI_SETUSTACK:
      {
         /* Libc: int setustack(stack_t *sp); */
         PRE_REG_READ2(long, SC2("getsetcontext", "setustack"), int, flag,
                       stack_t *, sp);

         /* The kernel does not read the stack data instantly but it can read
            them later so it is better to make sure the data are defined. */
         PRE_MEM_READ("getsetcontext_setustack(sp)", ARG2, sizeof(vki_stack_t));

         if (!ML_(safe_to_deref((void*)ARG2, sizeof(vki_stack_t)))) {
            SET_STATUS_Failure(VKI_EFAULT);
            return;
         }

         vki_stack_t *old_stack = tst->os_state.ustack;
         tst->os_state.ustack = (vki_stack_t*)ARG2;

         /* The thread is setting the ustack pointer.  It is a good time to get
            information about its stack. */
         if (tst->os_state.ustack->ss_flags == 0) {
            /* If the sanity check of ss_flags passed set the stack. */
            set_stack(tid, tst->os_state.ustack);

            if ((old_stack == NULL) && (tid > 1)) {
               /* New thread creation is now completed. Inform the tool. */
               VG_TRACK(pre_thread_first_insn, tid);
            }
         }

         SET_STATUS_Success(0);
      }
      break;
   default:
      VG_(unimplemented)("Syswrap of the context call with flag %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

PRE(sys_fchmodat)
{
   /* int fchmodat(int fd, const char *path, mode_t mode, int flag); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_fchmodat ( %d, %#lx(%s), %ld, %ld )",
         fd, ARG2, (HChar *) ARG2, SARG3, SARG4);
   PRE_REG_READ4(long, "fchmodat",
                 int, fd, const char *, path, vki_mode_t, mode, int, flag);

   if (ARG2)
      PRE_MEM_RASCIIZ("fchmodat(path)", ARG2);

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "fchmodat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_mkdirat)
{
   /* int mkdirat(int fd, const char *path, mode_t mode); */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   *flags |= SfMayBlock;
   PRINT("sys_mkdirat ( %d, %#lx(%s), %ld )", fd, ARG2, (HChar *) ARG2, SARG3);
   PRE_REG_READ3(long, "mkdirat", int, fd, const char *, path,
                 vki_mode_t, mode);
   PRE_MEM_RASCIIZ("mkdirat(path)", ARG2);

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "mkdirat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

static void do_statvfs_post(struct vki_statvfs *stats, ThreadId tid)
{
   POST_FIELD_WRITE(stats->f_bsize);
   POST_FIELD_WRITE(stats->f_frsize);
   POST_FIELD_WRITE(stats->f_blocks);
   POST_FIELD_WRITE(stats->f_bfree);
   POST_FIELD_WRITE(stats->f_bavail);
   POST_FIELD_WRITE(stats->f_files);
   POST_FIELD_WRITE(stats->f_ffree);
   POST_FIELD_WRITE(stats->f_favail);
   POST_FIELD_WRITE(stats->f_fsid);
   POST_MEM_WRITE((Addr) stats->f_basetype, VG_(strlen)(stats->f_basetype) + 1);
   POST_FIELD_WRITE(stats->f_flag);
   POST_FIELD_WRITE(stats->f_namemax);
   POST_MEM_WRITE((Addr) stats->f_fstr, VG_(strlen)(stats->f_fstr) + 1);
}

PRE(sys_statvfs)
{
   /* int statvfs(const char *path, struct statvfs *buf); */
   *flags |= SfMayBlock;
   PRINT("sys_statvfs ( %#lx(%s), %#lx )", ARG1, (HChar *) ARG1, ARG2);
   PRE_REG_READ2(long, "statvfs", const char *, path,
                 struct vki_statvfs *, buf);
   PRE_MEM_RASCIIZ("statvfs(path)", ARG1);
   PRE_MEM_WRITE("statvfs(buf)", ARG2, sizeof(struct vki_statvfs));
}

POST(sys_statvfs)
{
   do_statvfs_post((struct vki_statvfs *) ARG2, tid);
}

PRE(sys_fstatvfs)
{
   /* int fstatvfs(int fd, struct statvfs *buf); */
   *flags |= SfMayBlock;
   PRINT("sys_fstatvfs ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "fstatvfs", int, fd, struct vki_statvfs *, buf);
   PRE_MEM_WRITE("fstatvfs(buf)", ARG2, sizeof(struct vki_statvfs));

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "fstatvfs", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_fstatvfs)
{
   do_statvfs_post((struct vki_statvfs *) ARG2, tid);
}

PRE(sys_nfssys)
{
   /* int nfssys(enum nfssys_op opcode, void *arg); */
   *flags |= SfMayBlock;
   PRINT("sys_nfssys ( %ld, %#lx )", SARG1, ARG2);

   switch (ARG1 /*opcode*/) {
   case VKI_NFS_REVAUTH:
      PRE_REG_READ2(long, SC2("nfssys", "nfs_revauth"), int, opcode,
                    struct vki_nfs_revauth_args *, args);
      PRE_MEM_READ("nfssys(arg)", ARG2,
                   sizeof(struct vki_nfs_revauth_args));
      break;
   default:
      VG_(unimplemented)("Syswrap of the nfssys call with opcode %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_nfssys)
{
   switch (ARG1 /*opcode*/) {
   case VKI_NFS_REVAUTH:
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_waitid)
{
   /* int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options); */
   *flags |= SfMayBlock;
   PRINT("sys_waitid( %ld, %ld, %#lx, %ld )", SARG1, SARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "waitid", vki_idtype_t, idtype, vki_id_t, id,
                 siginfo_t *, infop, int, options);
   PRE_MEM_WRITE("waitid(infop)", ARG3, sizeof(vki_siginfo_t));
}

POST(sys_waitid)
{
   POST_MEM_WRITE(ARG3, sizeof(vki_siginfo_t));
}

#if defined(SOLARIS_UTIMESYS_SYSCALL)
PRE(sys_utimesys)
{
   /* Kernel: int utimesys(int code, uintptr_t arg1, uintptr_t arg2,
                           uintptr_t arg3, uintptr_t arg4);
    */

   switch (ARG1 /*code*/) {
   case 0:
      /* Libc: int futimens(int fd, const timespec_t times[2]); */
      PRINT("sys_utimesys ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, "utimesys", int, code, int, fd,
                    const vki_timespec_t *, times);
      if (ARG3)
         PRE_MEM_READ("utimesys(times)", ARG3, 2 * sizeof(vki_timespec_t));

      /* Be strict. */
      if (!ML_(fd_allowed)(ARG2, "utimesys", tid, False))
         SET_STATUS_Failure(VKI_EBADF);
      break;
   case 1:
      {
         /* Libc: int utimensat(int fd, const char *path,
                                const timespec_t times[2], int flag);
          */

         /* Interpret the second argument as 32-bit value even on 64-bit
            architecture. This is different from Linux, for example, where glibc
            sign-extends it. */
         Int fd = (Int) ARG2;

         PRINT("sys_utimesys ( %ld, %d, %#lx(%s), %#lx, %ld )",
               SARG1, fd, ARG3, (HChar *) ARG3, ARG4, SARG5);
         PRE_REG_READ5(long, "utimesys", int, code, int, fd, const char *, path,
                       const vki_timespec_t *, times, int, flag);
         if (ARG3)
            PRE_MEM_RASCIIZ("utimesys(path)", ARG3);
         if (ARG4)
            PRE_MEM_READ("utimesys(times)", ARG4, 2 * sizeof(vki_timespec_t));

         /* Be strict but ignore fd for absolute path. */
         if (fd != VKI_AT_FDCWD
             && ML_(safe_to_deref)((void *) ARG3, 1)
             && ((HChar *) ARG3)[0] != '/'
             && !ML_(fd_allowed)(fd, "utimesys", tid, False))
            SET_STATUS_Failure(VKI_EBADF);
         break;
      }
   default:
      VG_(unimplemented)("Syswrap of the utimesys call with code %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}
#endif /* SOLARIS_UTIMESYS_SYSCALL */

#if defined(SOLARIS_UTIMENSAT_SYSCALL)
PRE(sys_utimensat)
{
   /* int utimensat(int fd, const char *path, const timespec_t times[2],
                    int flag);
    */

   /* Interpret the first argument as 32-bit value even on 64-bit architecture.
      This is different from Linux, for example, where glibc sign-extends it. */
   Int fd = (Int) ARG1;

   PRINT("sys_utimensat ( %d, %#lx(%s), %#lx, %ld )",
         fd, ARG2, (HChar *) ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "utimensat", int, fd, const char *, path,
                 const vki_timespec_t *, times, int, flag);
   if (ARG2)
      PRE_MEM_RASCIIZ("utimensat(path)", ARG2);
   if (ARG3)
      PRE_MEM_READ("utimensat(times)", ARG3, 2 * sizeof(vki_timespec_t));

   /* Be strict but ignore fd for absolute path. */
   if (fd != VKI_AT_FDCWD
       && ML_(safe_to_deref)((void *) ARG2, 1)
       && ((HChar *) ARG2)[0] != '/'
       && !ML_(fd_allowed)(fd, "utimensat", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}
#endif /* SOLARIS_UTIMENSAT_SYSCALL */

PRE(sys_sigresend)
{
   /* int sigresend(int signal, siginfo_t *siginfo, sigset_t *mask); */
   /* Sends a signal to the calling thread, the mask parameter specifies a new
      signal mask. */

   /* Static (const) mask accessible from outside of this function. */
   static vki_sigset_t block_all;

   PRINT("sys_sigresend( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "sigresend", int, signal, vki_siginfo_t *, siginfo,
                 vki_sigset_t *, mask);

   if (ARG2)
      PRE_MEM_READ("sigresend(siginfo)", ARG2, sizeof(vki_siginfo_t));
   PRE_MEM_WRITE("sigresend(mask)", ARG3, sizeof(vki_sigset_t));

   /* Check the signal and mask. */
   if (!ML_(client_signal_OK)(ARG1)) {
      SET_STATUS_Failure(VKI_EINVAL);
   }
   if (!ML_(safe_to_deref)((void*)ARG3, sizeof(vki_sigset_t))) {
      SET_STATUS_Failure(VKI_EFAULT);
   }
   
   /* Exit early if there are problems. */
   if (FAILURE)
      return;

   /* Save the requested mask to unused ARG4. */
   ARG4 = ARG3;

   /* Fake the requested sigmask with a block-all mask.  If the syscall
      suceeds then we will block "all" signals for a few instructions (in
      syscall-x86-solaris.S) but the correct mask will be almost instantly set
      again by a call to sigprocmask (also in syscall-x86-solaris.S).  If the
      syscall fails then the mask is not changed, so everything is ok too. */
   VG_(sigfillset)(&block_all);
   ARG3 = (UWord)&block_all;

   /* Check to see if this gave us a pending signal. */
   *flags |= SfPollAfter;

   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg, "sigresend: resending signal %ld\n", ARG1);

   /* Handle SIGKILL specially. */
   if (ARG1 == VKI_SIGKILL && ML_(do_sigkill)(tid, -1)) {
      SET_STATUS_Success(0);
      return;
   }

   /* Ask to handle this syscall via the slow route, since that's the only one
      that sets tst->status to VgTs_WaitSys.  If the result of doing the
      syscall is an immediate run of async_signalhandler() in m_signals.c,
      then we need the thread to be properly tidied away. */
   *flags |= SfMayBlock;
}

POST(sys_sigresend)
{
   /* The syscall succeeded, set the requested mask. */
   VG_(do_sys_sigprocmask)(tid, VKI_SIG_SETMASK, (vki_sigset_t*)ARG4, NULL);

   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg, "sigresend: resent signal %lu\n", ARG1);
}

static void mem_priocntlsys_parm_ok(ThreadId tid, Bool pre, Bool reade,
                                    vki_pc_vaparm_t *parm)
{
   if (reade)
      return;

   if (pre)
      PRE_FIELD_WRITE("priocntlsys(parm)", parm->pc_parm);
   else
      POST_FIELD_WRITE(parm->pc_parm);
}

static void mem_priocntlsys_parm(ThreadId tid, Bool pre, Bool reade,
                                 const HChar *clname,
                                 vki_pc_vaparm_t *parm)
{
   /* This function is used to handle the PC_SETXPARMS and PC_GETXPARMS
      parameters.  In the case of PC_SETXPARMS, the code below merely checks
      if all parameters are scalar, PRE_MEM_READ() for these parameters is
      already done by the PC_SETXPARMS handler in PRE(sys_priocntlsys).

      A caller of this function is responsible for checking that clname and
      &parm->key can be dereferenced. */

   if (VG_STREQ(clname, "RT")) {
      switch (parm->pc_key) {
      case VKI_RT_KY_PRI:
      case VKI_RT_KY_TQSECS:
      case VKI_RT_KY_TQNSECS:
      case VKI_RT_KY_TQSIG:
         /* Scalar values that are stored directly in pc_parm. */
         mem_priocntlsys_parm_ok(tid, pre, reade, parm);
         return;
      }
   }
   else if (VG_STREQ(clname, "TS")) {
      switch (parm->pc_key) {
      case VKI_TS_KY_UPRILIM:
      case VKI_TS_KY_UPRI:
         /* Scalar values that are stored directly in pc_parm. */
         mem_priocntlsys_parm_ok(tid, pre, reade, parm);
         return;
      }
   }
   else if (VG_STREQ(clname, "IA")) {
      switch (parm->pc_key) {
      case VKI_IA_KY_UPRILIM:
      case VKI_IA_KY_UPRI:
      case VKI_IA_KY_MODE:
         /* Scalar values that are stored directly in pc_parm. */
         mem_priocntlsys_parm_ok(tid, pre, reade, parm);
         return;
      }
   }
   else if (VG_STREQ(clname, "FSS")) {
      switch (parm->pc_key) {
      case VKI_FSS_KY_UPRILIM:
      case VKI_FSS_KY_UPRI:
         /* Scalar values that are stored directly in pc_parm. */
         mem_priocntlsys_parm_ok(tid, pre, reade, parm);
         return;
      }
   }
   else if (VG_STREQ(clname, "FX")) {
      switch (parm->pc_key) {
      case VKI_FX_KY_UPRILIM:
      case VKI_FX_KY_UPRI:
      case VKI_FX_KY_TQSECS:
      case VKI_FX_KY_TQNSECS:
         /* Scalar values that are stored directly in pc_parm. */
         mem_priocntlsys_parm_ok(tid, pre, reade, parm);
         return;
      }
   }
   else {
      /* Unknown class. */
      VG_(unimplemented)("Syswrap of the priocntlsys call where clname=%s.",
                         clname);
      /*NOTREACHED*/
   }

   /* The class is known but pc_key is unknown. */
   VG_(unimplemented)("Syswrap of the priocntlsys call where clname=%s "
                      "and pc_key=%d.", clname, parm->pc_key);
   /*NOTREACHED*/
}

PRE(sys_priocntlsys)
{
   /* long priocntlsys(int pc_version, procset_t *psp, int cmd, caddr_t arg,
                       caddr_t arg2); */

   if (ARG1 != 1) {
      /* Only the first version of priocntlsys is supported by the code below.
       */
      VG_(unimplemented)("Syswrap of the priocntlsys where pc_version=%lu.",
                         ARG1);
      /*NOTREACHED*/
   }

   PRINT("sys_priocntlsys ( %ld, %#lx, %ld, %#lx, %#lx )", SARG1, ARG2, SARG3,
         ARG4, ARG5);
   PRE_REG_READ5(long, "priocntlsys", int, pc_version, procset_t *, psp,
                 int, cmd, void *, arg, void *, arg2);

   switch (ARG3 /*cmd*/) {
   case VKI_PC_GETCID:
      if (ARG4) {
         vki_pcinfo_t *info = (vki_pcinfo_t*)ARG4;
         PRE_MEM_RASCIIZ("priocntlsys(clname)", (Addr)info->pc_clname);
         /* The next line says that the complete pcinfo_t structure can be
            written, but this actually isn't true for pc_clname which is
            always only read. */
         PRE_MEM_WRITE("priocntlsys(pcinfo)", ARG4, sizeof(vki_pcinfo_t));
      }
      break;
   case VKI_PC_GETCLINFO:
      if (ARG4) {
         vki_pcinfo_t *info = (vki_pcinfo_t*)ARG4;
         PRE_FIELD_READ("priocntlsys(cid)", info->pc_cid);
         /* The next line says that the complete pcinfo_t structure can be
            written, but this actually isn't true for pc_cid which is
            always only read. */
         PRE_MEM_WRITE("priocntlsys(pcinfo)", ARG4, sizeof(vki_pcinfo_t));
      }
      break;
   case VKI_PC_SETPARMS:
      PRE_MEM_READ("priocntlsys(psp)", ARG2, sizeof(vki_procset_t));
      /* The next line says that the complete pcparms_t structure is read
         which is never actually true (we are too pessimistic here).
         Unfortunately we can't do better because we don't know what
         process class is involved. */
      PRE_MEM_READ("priocntlsys(parms)", ARG4, sizeof(vki_pcparms_t));
      break;
   case VKI_PC_GETPARMS:
      PRE_MEM_READ("priocntlsys(psp)", ARG2, sizeof(vki_procset_t));
      PRE_MEM_WRITE("priocntlsys(parms)", ARG4, sizeof(vki_pcparms_t));
      break;
   case VKI_PC_GETPRIRANGE:
      {
         vki_pcpri_t *pcpri = (vki_pcpri_t*)ARG4;
         PRE_FIELD_READ("priocntlsys(cid)", pcpri->pc_cid);
      }
      PRE_MEM_WRITE("priocntlsys(pri)", ARG4, sizeof(vki_pcpri_t));
      break;
   case VKI_PC_DONICE:
      PRE_MEM_READ("priocntlsys(psp)", ARG2, sizeof(vki_procset_t));
      {
         vki_pcnice_t *nicee = (vki_pcnice_t*)ARG4;
         PRE_FIELD_READ("priocntlsys(op)", nicee->pc_op);
         if (ML_(safe_to_deref)(&nicee->pc_op, sizeof(nicee->pc_op))) {
            switch (nicee->pc_op) {
            case VKI_PC_GETNICE:
               PRE_FIELD_WRITE("priocntlsys(val)", nicee->pc_val);
               break;
            case VKI_PC_SETNICE:
               PRE_FIELD_READ("priocntlsys(val)", nicee->pc_val);
               break;
            default:
               VG_(unimplemented)("Syswrap of the priocntlsys call where "
                                  "cmd=PC_DONICE and pc_op=%d", nicee->pc_op);
               /*NOTREACHED*/
               break;
            }
         }
      }
      break;
   case VKI_PC_SETXPARMS:
      PRE_MEM_READ("priocntlsys(psp)", ARG2, sizeof(vki_procset_t));
      PRE_MEM_RASCIIZ("priocntlsys(clname)", ARG4);
      if (ARG5) {
         vki_pc_vaparms_t *parms = (vki_pc_vaparms_t*)ARG5;
         PRE_FIELD_READ("priocntlsys(vaparmscnt)", parms->pc_vaparmscnt);
         if (ML_(safe_to_deref)(&parms->pc_vaparmscnt,
                                sizeof(parms->pc_vaparmscnt))) {
            vki_uint_t i;
            PRE_MEM_READ("priocntlsys(parms)", (Addr)parms->pc_parms,
                         parms->pc_vaparmscnt * sizeof(parms->pc_parms[0]));
            for (i = 0; i < parms->pc_vaparmscnt; i++) {
               vki_pc_vaparm_t *parm = &parms->pc_parms[i];
               if (ML_(safe_to_deref)(parm, sizeof(*parm)) &&
                   ML_(safe_to_deref)((void*)ARG4, 1))
                  mem_priocntlsys_parm(tid, True /*pre*/, True /*read*/,
                                       (HChar*)ARG4, parm);
            }
         }
      }
      break;
   case VKI_PC_GETXPARMS:
      PRE_MEM_READ("priocntlsys(psp)", ARG2, sizeof(vki_procset_t));
      if (ARG4)
         PRE_MEM_RASCIIZ("priocntlsys(clname)", ARG4);
      if (ARG5) {
         vki_pc_vaparms_t *parms = (vki_pc_vaparms_t*)ARG5;
         PRE_FIELD_READ("priocntlsys(vaparmscnt)", parms->pc_vaparmscnt);
         if (ML_(safe_to_deref)(&parms->pc_vaparmscnt,
                                sizeof(parms->pc_vaparmscnt))) {
            vki_uint_t i;
            for (i = 0; i < parms->pc_vaparmscnt; i++) {
               vki_pc_vaparm_t *parm = &parms->pc_parms[i];
               PRE_MEM_READ("priocntlsys(parms)", (Addr)&parm->pc_key,
                            parms->pc_vaparmscnt * sizeof(parm->pc_key));
               if (ML_(safe_to_deref)(&parm->pc_key,
                                      sizeof(parm->pc_key))) {
                  /* First handle PC_KY_CLNAME, then class specific keys.
                     Note that PC_KY_CLNAME can be used only with
                     ARG4==NULL && parms->pc_vaparmscnt==1.  We are not so
                     strict here and handle this special case as a regular
                     one which makes the code simpler. */
                  if (parm->pc_key == VKI_PC_KY_CLNAME)
                     PRE_MEM_WRITE("priocntlsys(clname)", parm->pc_parm,
                                   VKI_PC_CLNMSZ);
                  else if (ARG4 && ML_(safe_to_deref)((void*)ARG4, 1))
                     mem_priocntlsys_parm(tid, True /*pre*/,
                                          False /*read*/, (HChar*)ARG4,
                                          parm);
               }
            }
         }
      }
      break;
   case VKI_PC_SETDFLCL:
      PRE_MEM_RASCIIZ("priocntlsys(clname)", ARG4);
      break;
   case VKI_PC_GETDFLCL:
      if (ARG4) {
         /* GETDFLCL writes to the ARG4 buffer only if ARG4 isn't NULL.  Also
            note that if ARG4 is NULL then the syscall succeeds. */
         PRE_MEM_WRITE("priocntlsys(clname)", ARG4, VKI_PC_CLNMSZ);
      }
      break;
   case VKI_PC_DOPRIO:
      PRE_MEM_READ("priocntlsys(psp)", ARG2, sizeof(vki_procset_t));
      {
         vki_pcprio_t *prio = (vki_pcprio_t*)ARG4;
         PRE_FIELD_READ("priocntlsys(op)", prio->pc_op);
         if (ML_(safe_to_deref)(&prio->pc_op, sizeof(prio->pc_op))) {
            switch (prio->pc_op) {
            case VKI_PC_GETPRIO:
               PRE_FIELD_WRITE("priocntlsys(cid)", prio->pc_cid);
               PRE_FIELD_WRITE("priocntlsys(val)", prio->pc_val);
               break;
            case VKI_PC_SETPRIO:
               PRE_FIELD_READ("priocntlsys(cid)", prio->pc_cid);
               PRE_FIELD_READ("priocntlsys(val)", prio->pc_val);
               break;
            default:
               VG_(unimplemented)("Syswrap of the priocntlsys call where "
                                  "cmd=PC_DOPRIO and pc_op=%d", prio->pc_op);
               /*NOTREACHED*/
               break;
            }
         }
      }
      break;
   case VKI_PC_ADMIN:
   default:
      VG_(unimplemented)("Syswrap of the priocntlsys call with cmd %ld.", SARG3);
      /*NOTREACHED*/
      break;
   }
}

static void post_mem_write_priocntlsys_clinfo(ThreadId tid,
                                              const HChar *clname, Addr clinfo)
{
   if (VG_STREQ(clname, "RT"))
      POST_MEM_WRITE(clinfo, sizeof(vki_rtinfo_t));
   else if (VG_STREQ(clname, "TS"))
      POST_MEM_WRITE(clinfo, sizeof(vki_tsinfo_t));
   else if (VG_STREQ(clname, "IA"))
      POST_MEM_WRITE(clinfo, sizeof(vki_iainfo_t));
   else if (VG_STREQ(clname, "FSS"))
      POST_MEM_WRITE(clinfo, sizeof(vki_fssinfo_t));
   else if (VG_STREQ(clname, "FX"))
      POST_MEM_WRITE(clinfo, sizeof(vki_fxinfo_t));
   else if (VG_STREQ(clname, "SDC")) {
      /* Relax. */
   }
   else {
      VG_(unimplemented)("Syswrap of the priocntlsys call where clname=%s.",
                         clname);
      /*NOTREACHED*/
   }
}

POST(sys_priocntlsys)
{
   switch (ARG3 /*cmd*/) {
   case VKI_PC_GETCID:
      if (ARG4) {
         vki_pcinfo_t *info = (vki_pcinfo_t*)ARG4;
         POST_FIELD_WRITE(info->pc_cid);
         post_mem_write_priocntlsys_clinfo(tid, info->pc_clname,
                                           (Addr)&info->pc_clinfo);
      }
      break;
   case VKI_PC_GETCLINFO:
      if (ARG4) {
         vki_pcinfo_t *info = (vki_pcinfo_t*)ARG4;
         POST_MEM_WRITE((Addr)info->pc_clname,
                        VG_(strlen)((HChar*)info->pc_clname) + 1);
         post_mem_write_priocntlsys_clinfo(tid, info->pc_clname,
                                           (Addr)&info->pc_clinfo);
      }
      break;
   case VKI_PC_SETPARMS:
      /* Relax. */
      break;
   case VKI_PC_GETPARMS:
      /* The next line says that the complete pcparms_t structure is
         written which is never actually true (we are too optimistic here).
         Unfortunately we can't do better because we don't know what
         process class is involved. */
      POST_MEM_WRITE(ARG4, sizeof(vki_pcparms_t));
      break;
   case VKI_PC_GETPRIRANGE:
      POST_MEM_WRITE(ARG4, sizeof(vki_pcpri_t));
      break;
   case VKI_PC_DONICE:
      {
         vki_pcnice_t *nicee = (vki_pcnice_t*)ARG4;
         if (nicee->pc_op == VKI_PC_GETNICE)
            POST_FIELD_WRITE(nicee->pc_val);
      }
      break;
   case VKI_PC_SETXPARMS:
      /* Relax. */
      break;
   case VKI_PC_GETXPARMS:
      {
         vki_pc_vaparms_t *parms = (vki_pc_vaparms_t*)ARG5;
         vki_uint_t i;
         for (i = 0; i < parms->pc_vaparmscnt; i++) {
            vki_pc_vaparm_t *parm = &parms->pc_parms[i];
            if (parm->pc_key == VKI_PC_KY_CLNAME)
               POST_MEM_WRITE(parm->pc_parm,
                              VG_(strlen)((HChar*)(Addr)parm->pc_parm) + 1);
            else if (ARG4)
               mem_priocntlsys_parm(tid, False /*pre*/, False /*read*/,
                                    (HChar*)ARG4, parm);
         }
      }
      break;
   case VKI_PC_SETDFLCL:
      /* Relax. */
      break;
   case VKI_PC_GETDFLCL:
      if (ARG4)
         POST_MEM_WRITE(ARG4, VG_(strlen)((HChar*)ARG4) + 1);
      break;
   case VKI_PC_DOPRIO:
      {
         vki_pcprio_t *prio = (vki_pcprio_t*)ARG4;
         if (prio->pc_op == VKI_PC_GETPRIO) {
            POST_FIELD_WRITE(prio->pc_cid);
            POST_FIELD_WRITE(prio->pc_val);
         }
      }
      break;
   case VKI_PC_ADMIN:
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_pathconf)
{
   /* long pathconf(const char *path, int name); */
   PRINT("sys_pathconf ( %#lx(%s), %ld )", ARG1, (HChar *) ARG1, SARG2);
   PRE_REG_READ2(long, "pathconf", const char *, path, int, name);
   PRE_MEM_RASCIIZ("pathconf(path)", ARG1);
}

PRE(sys_mmap)
{
   /* void *mmap(void *addr, size_t len, int prot, int flags,
                 int fildes, off_t off); */
   SysRes r;
   OffT offset;

   /* Stay sane. */
   vg_assert(VKI_PAGE_SIZE == 4096);
   vg_assert(sizeof(offset) == sizeof(ARG6));

   PRINT("sys_mmap ( %#lx, %#lx, %#lx, %#lx, %ld, %#lx )",
         ARG1, ARG2, ARG3, ARG4, SARG5, ARG6);
   PRE_REG_READ6(long, "mmap", void *, start, vki_size_t, length,
                 int, prot, int, flags, int, fd, vki_off_t, offset);

   /* Make sure that if off < 0 then it's passed correctly to the generic mmap
      wraper. */
   offset = *(OffT*)&ARG6;

   r = ML_(generic_PRE_sys_mmap)(tid, ARG1, ARG2, ARG3, ARG4, ARG5, offset);
   SET_STATUS_from_SysRes(r);
}

#if defined(SOLARIS_UUIDSYS_SYSCALL)
PRE(sys_uuidsys)
{
   /* int uuidsys(struct uuid *uuid); */
   PRINT("sys_uuidsys ( %#lx )", ARG1);
   PRE_REG_READ1(long, "uuidsys", struct vki_uuid *, uuid);
   PRE_MEM_WRITE("uuidsys(uuid)", ARG1, sizeof(struct vki_uuid));
}

POST(sys_uuidsys)
{
   POST_MEM_WRITE(ARG1, sizeof(struct vki_uuid));
}
#endif /* SOLARIS_UUIDSYS_SYSCALL */

/* Syscall mmapobj emulation. Processes ELF program headers
   and maps them into correct place in memory. Not an easy task, though.
   ELF program header of PT_LOAD/PT_SUNWBSS type specifies:
   o p_vaddr  - actually a memory offset
   o p_memsz  - total segment size, including text, data and BSS
   o p_filesz - file-based segment size mapping (includes only text and data);
                p_memsz - p_filesz is the size of BSS
   o p_offset - offset into the ELF file where the file-based mapping starts
 
   Several problematic areas to cover here:
   1. p_offset can contain a value which is not page-aligned. In that case
      we mmap a part of the file prior to p_offset to make the start address
      page-aligned.
   2. Partially unused page after the file-based mapping must be zeroed.
   3. The first mapping is flagged with MR_HDR_ELF and needs to contain
      the ELF header. This information is used and verified by the dynamic
      linker (ld.so.1). */
static SysRes mmapobj_process_phdrs(ThreadId tid, Int fd,
                                    vki_mmapobj_result_t *storage,
                                    vki_uint_t *elements,
                                    const VKI_ESZ(Ehdr) *ehdr,
                                    const VKI_ESZ(Phdr) *phdrs)
{
#define ADVANCE_PHDR(ehdr, phdr) \
   (const VKI_ESZ(Phdr) *) ((const HChar *) (phdr) + (ehdr)->e_phentsize)

   SysRes res;
   Int i;
   Int first_segment_idx = -1;
   UInt idx;
   UInt segments = 0; /* loadable segments */
   Addr start_addr = 0;
   Addr end_addr = 0;
   Addr elfbrk = 0;
   SizeT max_align = VKI_PAGE_SIZE;

   /* 1. First pass over phdrs - determine number, span and max alignment. */
   const VKI_ESZ(Phdr) *phdr = phdrs;
   for (idx = 0; idx < ehdr->e_phnum; idx++, phdr = ADVANCE_PHDR(ehdr, phdr)) {
      /* Skip this header if no memory is requested. */
      if (phdr->p_memsz == 0)
         continue;

      if ((phdr->p_type == VKI_PT_LOAD) || (phdr->p_type == VKI_PT_SUNWBSS)) {
         Off64T offset = 0;

         if (VG_(clo_trace_syscalls))
            VG_(debugLog)(2, "syswrap-solaris", "mmapobj_process_phdrs: "
                             "program header #%u: addr=%#lx type=%#lx "
                             "prot=%#lx memsz=%#lx filesz=%#lx file "
                             "offset=%#lx\n", idx, phdr->p_vaddr,
                             (UWord) phdr->p_type, (UWord) phdr->p_flags,
                             phdr->p_memsz, phdr->p_filesz, phdr->p_offset);

         if (segments == 0) {
            first_segment_idx = idx;

            if (phdr->p_filesz == 0) {
               VG_(unimplemented)("Syswrap of the mmapobj call with the first "
                                  "loadable ELF program header specifying "
                                  "p_filesz == 0");
              /*NOTREACHED*/
              return res;
            }

            /* Address of the first segment must be either NULL or within the
               first page. */
            if ((ehdr->e_type == VKI_ET_DYN) &&
                ((phdr->p_vaddr & VKI_PAGEMASK) != 0)) {
               if (VG_(clo_trace_syscalls))
                  VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                                   "ELF program header #%u does not land on "
                                   "the first page (vaddr=%#lx)\n", idx,
                                   phdr->p_vaddr);
               return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
            }

            start_addr = phdr->p_vaddr;
            /* The first segment is mapped from the beginning of the file (to
               include also the ELF header), so include this memory as well.
               Later on we flag this mapping with MR_HDR_ELF. */
            offset = phdr->p_offset;
         }

         if (phdr->p_align > 1) {
            if ((phdr->p_vaddr % phdr->p_align) !=
                (phdr->p_offset % phdr->p_align)) {
               if (VG_(clo_trace_syscalls))
                  VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                                   "ELF program header #%u does not have "
                                   "congruent offset and vaddr (vaddr=%#lx "
                                   "file offset=%#lx align=%#lx)\n", idx,
                                   phdr->p_vaddr, phdr->p_offset,
                                   phdr->p_align);
               return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
            }
         }

         if (phdr->p_vaddr < end_addr) {
            if (VG_(clo_trace_syscalls))
               VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                                "ELF program header #%u specifies overlaping "
                                "address (vaddr=%#lx end_addr=%#lx)\n",
                                idx, phdr->p_vaddr, end_addr);
            return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
         }

         end_addr = elfbrk = phdr->p_vaddr + phdr->p_memsz + offset;
         end_addr = VG_PGROUNDUP(end_addr);
         if (phdr->p_align > max_align) {
            max_align = phdr->p_align;
         }

         segments += 1;
      }
   }

   /* Alignment check - it should be power of two. */
   if ((max_align & (max_align - 1)) != 0) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: alignment "
                          "is not a power of 2 (%#lx)\n", max_align);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }
   vg_assert(max_align >= VKI_PAGE_SIZE);

#if defined(VGP_x86_solaris)
   if (max_align > VKI_UINT_MAX) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: alignment "
                          "for 32-bit ELF is >32-bits (%#lx)\n", max_align);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }
#endif /* VGP_x86_solaris */

   if (segments == 0) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: nothing "
                          "to map (0 loadable segments)");
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   vg_assert(end_addr >= start_addr);
   SizeT span = end_addr - start_addr;
   if (span == 0) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: nothing "
                          "to map (%u loadable segments spanning 0 bytes)\n",
                          segments);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }
   vg_assert(first_segment_idx >= 0);

   if (segments > *elements) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: too many "
                          "segments (%u)\n", segments);
      return VG_(mk_SysRes_Error)(VKI_E2BIG);
   }

   if (VG_(clo_trace_syscalls))
      VG_(debugLog)(2, "syswrap-solaris", "mmapobj_process_phdrs: there "
                       "are %u loadable segments spanning %#lx bytes; max "
                       "align is %#lx\n", segments, span, max_align);

   /* Now get the aspacemgr oraculum advisory.
      Later on we mmap file-based and BSS mappings into this address space area
      as required and leave the holes unmapped. */
   if (ehdr->e_type == VKI_ET_DYN) {
      MapRequest mreq = {MAlign, max_align, span};
      Bool ok;
      start_addr = VG_(am_get_advisory)(&mreq, True /* forClient */, &ok);
      if (!ok) {
         if (VG_(clo_trace_syscalls))
            VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                             "failed to reserve address space of %#lx bytes "
                             "with alignment %#lx\n", span, max_align);
         return VG_(mk_SysRes_Error)(VKI_ENOMEM);
      }
      vg_assert(VG_ROUNDUP(start_addr, max_align) == start_addr);

      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(2, "syswrap-solaris", "PRE(sys_mmapobj): address space "
                          "reserved at: vaddr=%#lx size=%#lx\n",
                          start_addr, span);
   } else {
      vg_assert(ehdr->e_type == VKI_ET_EXEC);
      /* ET_EXEC uses fixed mappings. Will be checked when processing phdrs. */
   }

   /* This is an utterly ugly hack, the aspacemgr assumes that only one
      segment is added at the time. However we add here multiple segments so
      AM_SANITY_CHECK inside the aspacemgr can easily fail. We want to
      prevent that thus we disable these checks. The scheduler will check the
      aspacemgr sanity after the syscall. */
   UInt sanity_level = VG_(clo_sanity_level);
   VG_(clo_sanity_level) = 1;

   /* 2. Second pass over phdrs - map the program headers and fill in
         the mmapobj_result_t array. */
   phdr = phdrs;
   *elements = 0;
   for (idx = 0; idx < ehdr->e_phnum; idx++, phdr = ADVANCE_PHDR(ehdr, phdr)) {
      /* Skip this header if no memory is requested. */
      if (phdr->p_memsz == 0)
         continue;

      if ((phdr->p_type == VKI_PT_LOAD) || (phdr->p_type == VKI_PT_SUNWBSS)) {
         UInt prot = 0;
         if (phdr->p_flags & VKI_PF_R)
            prot |= VKI_PROT_READ;
         if (phdr->p_flags & VKI_PF_W)
            prot |= VKI_PROT_WRITE;
         if (phdr->p_flags & VKI_PF_X)
            prot |= VKI_PROT_EXEC;

         vki_mmapobj_result_t *mrp = &storage[*elements];
         mrp->mr_msize = phdr->p_memsz;
         mrp->mr_fsize = phdr->p_filesz;
         mrp->mr_offset = 0;
         mrp->mr_prot = prot;
         mrp->mr_flags = 0;
         Off64T file_offset = phdr->p_offset;
         if (idx == first_segment_idx) {
            mrp->mr_flags = VKI_MR_HDR_ELF;
            if (ehdr->e_type == VKI_ET_DYN) {
               if (phdr->p_offset > 0) {
                  /* Include the ELF header into the first segment.
                     This means we ignore p_offset from the program header
                     and map from file offset 0. */
                  mrp->mr_msize += phdr->p_offset;
                  mrp->mr_fsize += phdr->p_offset;
                  file_offset = 0;
               }
            } else {
               vg_assert(ehdr->e_type == VKI_ET_EXEC);
               start_addr = phdr->p_vaddr;
            }
         }

         /* p_vaddr is absolute for ET_EXEC, and relative for ET_DYN. */
         mrp->mr_addr = (vki_caddr_t) phdr->p_vaddr;
         if (ehdr->e_type == VKI_ET_DYN) {
            mrp->mr_addr += start_addr;
         }

         SizeT page_offset = (Addr) mrp->mr_addr & VKI_PAGEOFFSET;
         if (page_offset > 0) {
            vg_assert(file_offset >= page_offset);
            /* Mapping address does not start at the beginning of a page.
               Therefore include some bytes before to make it page aligned. */
            mrp->mr_addr -= page_offset;
            mrp->mr_msize += page_offset;
            mrp->mr_offset = page_offset;
            file_offset -= page_offset;
         }
         SizeT file_size = mrp->mr_fsize + mrp->mr_offset;
         if (VG_(clo_trace_syscalls))
            VG_(debugLog)(2, "syswrap-solaris", "mmapobj_process_phdrs: "
                             "mmapobj result #%u: addr=%#lx msize=%#lx "
                             "fsize=%#lx mr_offset=%#lx prot=%#x flags=%#x\n",
                             *elements, (Addr) mrp->mr_addr,
                             (UWord) mrp->mr_msize, (UWord) mrp->mr_fsize,
                             (UWord) mrp->mr_offset, mrp->mr_prot,
                             mrp->mr_flags);

         UInt flags = VKI_MAP_PRIVATE | VKI_MAP_FIXED;
         if ((mrp->mr_prot & (VKI_PROT_WRITE | VKI_PROT_EXEC)) ==
                                                               VKI_PROT_EXEC) {
            flags |= VKI_MAP_TEXT;
         } else {
            flags |= VKI_MAP_INITDATA;
         }

         /* Determine if there will be partially unused page after file-based
            mapping. If so, then we need to zero it explicitly afterwards. */
         Addr mapping_end = (Addr) mrp->mr_addr + file_size;
         SizeT zeroed_size = VG_PGROUNDUP(mapping_end) - mapping_end;
         Bool mprotect_needed = False;
         if ((zeroed_size > 0) && ((prot & VKI_PROT_WRITE) == 0)) {
            prot |= VKI_PROT_WRITE;
            mprotect_needed = True;
         }

         if (ehdr->e_type == VKI_ET_EXEC) {
            /* Now check if the requested address space is available. */
            if (!VG_(am_is_free_or_resvn)((Addr) mrp->mr_addr, mrp->mr_msize)) {
               if (VG_(clo_trace_syscalls))
                  VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                                   "requested segment at %#lx with size of "
                                   "%#lx bytes is not available\n",
                                   (Addr) mrp->mr_addr, (UWord) mrp->mr_msize);
               res = VG_(mk_SysRes_Error)(VKI_EADDRINUSE);
               goto mmap_error;
            }
         }

         if (file_size > 0) {
            res = VG_(am_mmap_file_fixed_client_flags)((Addr) mrp->mr_addr,
                                       file_size, prot, flags, fd, file_offset);
            if (sr_isError(res)) {
               if (VG_(clo_trace_syscalls))
                  VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                                   "mmap failed: addr=%#lx size=%#lx prot=%#x "
                                   "flags=%#x fd=%d file offset=%#llx\n",
                                   (Addr) mrp->mr_addr, file_size,
                                   prot, flags, fd, file_offset);
               goto mmap_error;
            }

            VG_(debugLog)(1, "syswrap-solaris", "PRE(sys_mmapobj): new "
                             "segment: vaddr=%#lx size=%#lx prot=%#x "
                             "flags=%#x fd=%d file offset=%#llx\n",
                             (Addr) mrp->mr_addr, file_size, mrp->mr_prot,
                             flags, fd, file_offset);
         }

         if (zeroed_size > 0) {
            /* Now zero out the end of partially used page. */
            VG_(memset)((void *) mapping_end, 0, zeroed_size);
            if (mprotect_needed) {
               prot &= ~VKI_PROT_WRITE;
               res = VG_(do_syscall3)(SYS_mprotect, (Addr) mrp->mr_addr,
                                      file_size, prot);
               if (sr_isError(res)) {
                  if (VG_(clo_trace_syscalls))
                     VG_(debugLog)(3, "syswrap-solaris",
                                      "mmapobj_process_phdrs: mprotect failed: "
                                      "addr=%#lx size=%#lx prot=%#x",
                                      (Addr) mrp->mr_addr, file_size, prot);
                  /* Mapping for this segment was already established. */
                  idx += 1;
                  goto mmap_error;
               }
            }
         }

         if (file_size > 0) {
            ML_(notify_core_and_tool_of_mmap)((Addr) mrp->mr_addr, file_size,
                                              prot, flags, fd, file_offset);
         }

         /* Page(s) after the mapping backed up by the file are part of BSS.
            They need to be mmap'ed over with correct flags and will be
            implicitly zeroed. */
         mapping_end = VG_PGROUNDUP(mrp->mr_addr + mrp->mr_msize);
         Addr page_end = VG_PGROUNDUP(mrp->mr_addr + file_size);
         vg_assert(mapping_end >= page_end);
         zeroed_size = mapping_end - page_end;
         if (zeroed_size > 0) {
            flags = VKI_MAP_FIXED | VKI_MAP_PRIVATE | VKI_MAP_ANONYMOUS;
            res = VG_(am_mmap_anon_fixed_client)(page_end, zeroed_size, prot);
            if (sr_isError(res)) {
               if (VG_(clo_trace_syscalls))
                  VG_(debugLog)(3, "syswrap-solaris", "mmapobj_process_phdrs: "
                                   "mmap_anon failed: addr=%#lx size=%#lx "
                                   "prot=%#x\n", page_end, zeroed_size, prot);
               idx += 1; /* mapping for this segment was already established */
               goto mmap_error;
            }

            VG_(debugLog)(1, "syswrap-solaris", "PRE(sys_mmapobj): new "
                             "anonymous segment (BSS): vaddr=%#lx size=%#lx "
                             "prot=%#x\n", page_end, zeroed_size, prot);
            ML_(notify_core_and_tool_of_mmap)(page_end, zeroed_size,
                                              prot, flags, -1, 0);
         }

         VG_(di_notify_mmap)((Addr) mrp->mr_addr, False /*allow_SkFileV*/, fd);

         *elements += 1;
         vg_assert(*elements <= segments);
      }
   }

   if ((ehdr->e_type == VKI_ET_EXEC) && (!brk_segment_established)) {
      vg_assert(VG_(brk_base) == VG_(brk_limit));
      vg_assert(VG_(brk_base) == -1);
      VG_(brk_base) = VG_(brk_limit) = elfbrk;

      if (!VG_(setup_client_dataseg)()) {
         VG_(umsg)("Cannot map memory to initialize brk segment in thread #%d "
                   "at %#lx\n", tid, VG_(brk_base));
         res = VG_(mk_SysRes_Error)(VKI_ENOMEM);
         goto mmap_error;
      }

      VG_(track_client_dataseg)(tid);
   }

   /* Restore VG_(clo_sanity_level). The scheduler will perform the aspacemgr
      sanity check after the syscall. */
   VG_(clo_sanity_level) = sanity_level;

   return VG_(mk_SysRes_Success)(0);

mmap_error:
   for (i = idx - 1; i > 0; i--) {
      Bool discard_translations;
      Addr addr = (Addr) storage[i].mr_addr;

      VG_(am_munmap_client)(&discard_translations, addr, storage[i].mr_msize);
      ML_(notify_core_and_tool_of_munmap)(addr, storage[i].mr_msize);
   }
   *elements = 0;
   return res;

#undef ADVANCE_PHDR
}

static SysRes mmapobj_interpret(ThreadId tid, Int fd,
                                vki_mmapobj_result_t *storage,
                                vki_uint_t *elements)
{
   SysRes res;

   struct vg_stat stats;
   if (VG_(fstat)(fd, &stats) != 0) {
      return VG_(mk_SysRes_Error)(VKI_EBADF);
   }

   if (stats.size < sizeof(VKI_ESZ(Ehdr))) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: insufficient "
                          "file size (%lld)\n", stats.size);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   /* Align the header buffer appropriately. */
   vki_ulong_t lheader[sizeof(VKI_ESZ(Ehdr)) / sizeof(vki_ulong_t) + 1];
   HChar *header = (HChar *) &lheader;

   res = VG_(pread)(fd, header, sizeof(VKI_ESZ(Ehdr)), 0);
   if (sr_isError(res)) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: read of ELF "
                          "header failed\n");
      return res;
   } else if (sr_Res(res) != sizeof(VKI_ESZ(Ehdr))) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: read of ELF "
                          "header failed - only %lu bytes out of %lu\n",
                          sr_Res(res), (UWord) sizeof(VKI_ESZ(Ehdr)));
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   /* Verify file type is ELF. */
   if ((header[VKI_EI_MAG0] != VKI_ELFMAG0) ||
       (header[VKI_EI_MAG1] != VKI_ELFMAG1) ||
       (header[VKI_EI_MAG2] != VKI_ELFMAG2) ||
       (header[VKI_EI_MAG3] != VKI_ELFMAG3)) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: ELF header "
                          "missing magic\n");
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   if (header[VKI_EI_CLASS] != VG_ELF_CLASS) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: ELF class "
                          "mismatch (%u vs %u)\n", header[VKI_EI_CLASS],
                          VG_ELF_CLASS);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   VKI_ESZ(Ehdr) *ehdr = (VKI_ESZ(Ehdr) *) header;
   if ((ehdr->e_type != VKI_ET_EXEC) && (ehdr->e_type != VKI_ET_DYN)) {
      VG_(unimplemented)("Syswrap of the mmapobj call with ELF type %u.",
                         ehdr->e_type);
      /*NOTREACHED*/
      return res;
   }

   if (ehdr->e_phnum == VKI_PN_XNUM) {
      VG_(unimplemented)("Syswrap of the mmapobj call with number of ELF "
                         "program headers == PN_XNUM");
      /*NOTREACHED*/
      return res;
   }

   /* Check alignment. */
#if defined(VGP_x86_solaris)
   if (!VG_IS_4_ALIGNED(ehdr->e_phentsize)) {
#elif defined(VGP_amd64_solaris)
   if (!VG_IS_8_ALIGNED(ehdr->e_phentsize)) {
#else
#  error "Unknown platform"
#endif
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: ELF header "
                          "phentsize not aligned properly (%u)\n",
                          ehdr->e_phentsize);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   SizeT phdrs_size = ehdr->e_phnum * ehdr->e_phentsize;
   if (phdrs_size == 0) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: no ELF "
                          "program headers\n");
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   VKI_ESZ(Phdr) *phdrs = VG_(malloc)("syswrap.mi.1", phdrs_size);
   res = VG_(pread)(fd, phdrs, phdrs_size, ehdr->e_phoff);
   if (sr_isError(res)) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: read of ELF "
                          "program headers failed\n");
      VG_(free)(phdrs);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   } else if (sr_Res(res) != phdrs_size) {
      if (VG_(clo_trace_syscalls))
         VG_(debugLog)(3, "syswrap-solaris", "mmapobj_interpret: read of ELF "
                          "program headers failed - only %lu bytes out of %lu\n",
                          sr_Res(res), phdrs_size);
      VG_(free)(phdrs);
      return VG_(mk_SysRes_Error)(VKI_ENOTSUP);
   }

   if (VG_(clo_trace_syscalls))
      VG_(debugLog)(2, "syswrap-solaris", "mmapobj_interpret: %u ELF "
                       "program headers with total size of %lu bytes\n",
                       ehdr->e_phnum, phdrs_size);

   /* Now process the program headers. */
   res = mmapobj_process_phdrs(tid, fd, storage, elements, ehdr, phdrs);
   VG_(free)(phdrs);
   return res;
}

PRE(sys_mmapobj)
{
   /* int mmapobj(int fd, uint_t flags, mmapobj_result_t *storage,
                  uint_t *elements, void *arg); */
   PRINT("sys_mmapobj ( %ld, %#lx, %#lx, %#lx, %#lx )", SARG1, ARG2, ARG3,
         ARG4, ARG5);
   PRE_REG_READ5(long, "mmapobj", int, fd, vki_uint_t, flags,
                 mmapobj_result_t *, storage, uint_t *, elements,
                 void *, arg);

   PRE_MEM_READ("mmapobj(elements)", ARG4, sizeof(vki_uint_t));
   /*PRE_MEM_WRITE("mmapobj(elements)", ARG4, sizeof(vki_uint_t));*/
   if (ML_(safe_to_deref)((void*)ARG4, sizeof(vki_uint_t))) {
      vki_uint_t *u = (vki_uint_t*)ARG4;
      PRE_MEM_WRITE("mmapobj(storage)", ARG3,
                    *u * sizeof(vki_mmapobj_result_t));
   }

   if (ARG2 & VKI_MMOBJ_PADDING)
      PRE_MEM_READ("mmapobj(arg)", ARG5, sizeof(vki_size_t));

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "mmapobj", tid, False)) {
      SET_STATUS_Failure(VKI_EBADF);
      return;
   }

   /* We cannot advise mmapobj about desired address(es). Unfortunately
      kernel places mappings from mmapobj at the end of process address
      space, defeating memcheck's optimized fast 2-level array algorithm.
      So we need to emulate what mmapobj does in the kernel. */

   /* Sanity check on parameters. */
   if ((ARG2 & ~VKI_MMOBJ_ALL_FLAGS) != 0) {
      SET_STATUS_Failure(VKI_EINVAL);
      return;
   }

   if (!ML_(safe_to_deref)((void *) ARG4, sizeof(vki_uint_t))) {
      SET_STATUS_Failure(VKI_EFAULT);
      return;
   }
   vki_uint_t *elements = (vki_uint_t *) ARG4;

   if (*elements > 0) {
      if (!ML_(safe_to_deref)((void *) ARG3,
                              *elements * sizeof(vki_mmapobj_result_t))) {
         SET_STATUS_Failure(VKI_EFAULT);
         return;
      }
   }

   /* For now, supported is only MMOBJ_INTERPRET and no MMOBJ_PADDING. */
   if (ARG2 != VKI_MMOBJ_INTERPRET) {
      VG_(unimplemented)("Syswrap of the mmapobj call with flags %lu.", ARG2);
      /*NOTREACHED*/
      return;
   }

   SysRes res = mmapobj_interpret(tid, (Int) ARG1,
                                  (vki_mmapobj_result_t *) ARG3, elements);
   SET_STATUS_from_SysRes(res);

   if (!sr_isError(res)) {
      POST_MEM_WRITE(ARG4, sizeof(vki_uint_t));

      UInt idx;
      for (idx = 0; idx < *(vki_uint_t *) ARG4; idx++) {
         vki_mmapobj_result_t *mrp = &((vki_mmapobj_result_t *) ARG3)[idx];
         POST_FIELD_WRITE(mrp->mr_addr);
         POST_FIELD_WRITE(mrp->mr_msize);
         POST_FIELD_WRITE(mrp->mr_fsize);
         POST_FIELD_WRITE(mrp->mr_prot);
         POST_FIELD_WRITE(mrp->mr_flags);
         POST_FIELD_WRITE(mrp->mr_offset);
      }
   }
}

PRE(sys_memcntl)
{
   /* int memcntl(caddr_t addr, size_t len, int cmd, caddr_t arg,
                  int attr, int mask); */
   PRINT("sys_memcntl ( %#lx, %#lx, %ld, %#lx, %#lx, %#lx )", ARG1, ARG2,
         SARG3, ARG4, ARG5, ARG6);
   PRE_REG_READ6(long, "memcntl", void *, addr, vki_size_t, len, int, cmd,
                 void *, arg, int, attr, int, mask);

   if (ARG3 != VKI_MC_LOCKAS && ARG3 != VKI_MC_UNLOCKAS &&
       !ML_(valid_client_addr)(ARG1, ARG2, tid, "memcntl")) {
      /* MC_LOCKAS and MC_UNLOCKAS work on the complete address space thus we
         don't check the address range validity if these commands are
         requested. */
      SET_STATUS_Failure(VKI_ENOMEM);
      return;
   }

   if (ARG3 == VKI_MC_HAT_ADVISE)
      PRE_MEM_READ("memcntl(arg)", ARG4, sizeof(struct vki_memcntl_mha));
}

PRE(sys_getpmsg)
{
   /* int getpmsg(int fildes, struct strbuf *ctlptr, struct strbuf *dataptr,
                  int *bandp, int *flagsp); */
   struct vki_strbuf *ctrlptr = (struct vki_strbuf *)ARG2;
   struct vki_strbuf *dataptr = (struct vki_strbuf *)ARG3;
   *flags |= SfMayBlock;
   PRINT("sys_getpmsg ( %ld, %#lx, %#lx, %#lx, %#lx )", SARG1, ARG2, ARG3,
         ARG4, ARG5);
   PRE_REG_READ5(long, "getpmsg", int, fildes, struct vki_strbuf *, ctlptr,
                 struct vki_strbuf *, dataptr, int *, bandp, int *, flagsp);
   if (ctrlptr) {
      PRE_FIELD_READ("getpmsg(ctrlptr->maxlen)", ctrlptr->maxlen);
      PRE_FIELD_WRITE("getpmsg(ctrlptr->len)", ctrlptr->len);
      PRE_FIELD_READ("getpmsg(ctrlptr->buf)", ctrlptr->buf);
      if (ML_(safe_to_deref)((void*)ARG2, sizeof(struct vki_strbuf))
          && ctrlptr->maxlen > 0)
         PRE_MEM_WRITE("getpmsg(ctrlptr->buf)", (Addr)ctrlptr->buf,
                       ctrlptr->maxlen);
   }
   if (dataptr) {
      PRE_FIELD_READ("getpmsg(dataptr->maxlen)", dataptr->maxlen);
      PRE_FIELD_WRITE("getpmsg(dataptr->len)", dataptr->len);
      PRE_FIELD_READ("getpmsg(dataptr->buf)", dataptr->buf);
      if (ML_(safe_to_deref)((void*)ARG3, sizeof(struct vki_strbuf))
          && dataptr->maxlen > 0)
         PRE_MEM_WRITE("getpmsg(dataptr->buf)", (Addr)dataptr->buf,
                       dataptr->maxlen);
   }
   PRE_MEM_READ("getpmsg(bandp)", ARG4, sizeof(int));
   /*PRE_MEM_WRITE("getpmsg(bandp)", ARG4, sizeof(int));*/
   PRE_MEM_READ("getpmsg(flagsp)", ARG5, sizeof(int));
   /*PRE_MEM_WRITE("getpmsg(flagsp)", ARG5, sizeof(int));*/

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "getpmsg", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_getpmsg)
{
   struct vki_strbuf *ctrlptr = (struct vki_strbuf *)ARG2;
   struct vki_strbuf *dataptr = (struct vki_strbuf *)ARG3;

   if (ctrlptr && ctrlptr->len > 0)
      POST_MEM_WRITE((Addr)ctrlptr->buf, ctrlptr->len);
   if (dataptr && dataptr->len > 0)
      POST_MEM_WRITE((Addr)dataptr->buf, dataptr->len);
   POST_MEM_WRITE(ARG4, sizeof(int));
   POST_MEM_WRITE(ARG5, sizeof(int));
}

PRE(sys_putpmsg)
{
   /* int putpmsg(int fildes, const struct strbuf *ctlptr,
                  const struct strbuf *dataptr, int band, int flags); */
   struct vki_strbuf *ctrlptr = (struct vki_strbuf *)ARG2;
   struct vki_strbuf *dataptr = (struct vki_strbuf *)ARG3;
   *flags |= SfMayBlock;
   PRINT("sys_putpmsg ( %ld, %#lx, %#lx, %ld, %ld )", SARG1, ARG2, ARG3, SARG4,
         SARG5);
   PRE_REG_READ5(long, "putpmsg", int, fildes, struct vki_strbuf *, ctrlptr,
                 struct vki_strbuf *, dataptr, int, band, int, flags);
   if (ctrlptr) {
      PRE_FIELD_READ("putpmsg(ctrlptr->len)", ctrlptr->len);
      PRE_FIELD_READ("putpmsg(ctrlptr->buf)", ctrlptr->buf);
      if (ML_(safe_to_deref)((void*)ARG2, sizeof(struct vki_strbuf))
          && ctrlptr->len > 0)
         PRE_MEM_READ("putpmsg(ctrlptr->buf)", (Addr)ctrlptr->buf,
                      ctrlptr->len);
   }
   if (dataptr) {
      PRE_FIELD_READ("putpmsg(dataptr->len)", dataptr->len);
      PRE_FIELD_READ("putpmsg(dataptr->buf)", dataptr->buf);
      if (ML_(safe_to_deref)((void*)ARG3, sizeof(struct vki_strbuf))
          && dataptr->len > 0)
         PRE_MEM_READ("putpmsg(dataptr->buf)", (Addr)dataptr->buf,
                      dataptr->len);
   }

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "putpmsg", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

#if defined(SOLARIS_OLD_SYSCALLS)
PRE(sys_rename)
{
   /* int rename(const char *from, const char *to); */

   *flags |= SfMayBlock;
   PRINT("sys_rename ( %#lx(%s), %#lx(%s) )",
         ARG1, (HChar *) ARG1, ARG2, (HChar *) ARG2);
   PRE_REG_READ2(long, "rename", const char *, from, const char *, to);

   PRE_MEM_RASCIIZ("rename(from)", ARG1);
   PRE_MEM_RASCIIZ("rename(to)", ARG2);
}
#endif /* SOLARIS_OLD_SYSCALLS */

PRE(sys_uname)
{
   /* int uname(struct utsname *name); */
   PRINT("sys_uname ( %#lx )", ARG1);
   PRE_REG_READ1(long, "uname", struct vki_utsname *, name);
   PRE_MEM_WRITE("uname(name)", ARG1, sizeof(struct vki_utsname));
}

POST(sys_uname)
{
   struct vki_utsname *name = (struct vki_utsname *) ARG1;
   POST_MEM_WRITE((Addr) name->sysname, VG_(strlen)(name->sysname) + 1);
   POST_MEM_WRITE((Addr) name->nodename, VG_(strlen)(name->nodename) + 1);
   POST_MEM_WRITE((Addr) name->release, VG_(strlen)(name->release) + 1);
   POST_MEM_WRITE((Addr) name->version, VG_(strlen)(name->version) + 1);
   POST_MEM_WRITE((Addr) name->machine, VG_(strlen)(name->machine) + 1);
}

PRE(sys_setegid)
{
   /* int setegid(gid_t egid); */
   PRINT("sys_setegid ( %ld )", SARG1);
   PRE_REG_READ1(long, "setegid", vki_gid_t, egid);
}

PRE(sys_sysconfig)
{
   /* long sysconf(int name); */
   PRINT("sys_sysconfig ( %ld )", SARG1);
   PRE_REG_READ1(long, "sysconf", int, name);

   if (ARG1 == VKI_CONFIG_OPEN_FILES)
      SET_STATUS_Success(VG_(fd_soft_limit));
}

PRE(sys_systeminfo)
{
   /* int sysinfo(int command, char *buf, long count); */
   PRINT("sys_systeminfo ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
   PRE_REG_READ3(long, "sysinfo", int, command, char *, buf, long, count);

   switch (ARG1 /*command*/) {
   case VKI_SI_SYSNAME:
   case VKI_SI_HOSTNAME:
   case VKI_SI_RELEASE:
   case VKI_SI_VERSION:
   case VKI_SI_MACHINE:
   case VKI_SI_ARCHITECTURE:
   case VKI_SI_HW_SERIAL:
   case VKI_SI_HW_PROVIDER:
   case VKI_SI_SRPC_DOMAIN:
   case VKI_SI_PLATFORM:
   case VKI_SI_ISALIST:
   case VKI_SI_DHCP_CACHE:
   case VKI_SI_ARCHITECTURE_32:
   case VKI_SI_ARCHITECTURE_64:
   case VKI_SI_ARCHITECTURE_K:
   case VKI_SI_ARCHITECTURE_NATIVE:
      PRE_MEM_WRITE("sysinfo(buf)", ARG2, ARG3);
      break;

   case VKI_SI_SET_HOSTNAME:
   case VKI_SI_SET_SRCP_DOMAIN:
      PRE_MEM_RASCIIZ("sysinfo(buf)", ARG2);
      break;

   default:
      VG_(unimplemented)("Syswrap of the sysinfo call with command %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_systeminfo)
{
   if (ARG1 != VKI_SI_SET_HOSTNAME && ARG1 != VKI_SI_SET_SRCP_DOMAIN)
      POST_MEM_WRITE(ARG2, MIN(RES, ARG3));
}

PRE(sys_seteuid)
{
   /* int seteuid(uid_t euid); */
   PRINT("sys_seteuid ( %ld )", SARG1);
   PRE_REG_READ1(long, "seteuid", vki_uid_t, euid);
}

PRE(sys_forksys)
{
   /* int64_t forksys(int subcode, int flags); */
   Int fds[2];
   Int res;
   PRINT("sys_forksys ( %ld, %ld )", SARG1, SARG2);
   PRE_REG_READ2(long, "forksys", int, subcode, int, flags);

   if (ARG1 == 1) {
      /* Support for forkall() requires changes to the big lock processing
         which are not yet implemented. */
      VG_(unimplemented)("Support for forkall().");
      /*NOTREACHED*/
      return;
   }

   if (ARG1 != 0 && ARG1 != 2) {
      VG_(unimplemented)("Syswrap of the forksys call where subcode=%ld.",
                         SARG1);
      /*NOTREACHED*/
   }

   if (ARG1 == 2) {
      /* vfork() is requested. Translate it to a normal fork() but work around
         a problem with posix_spawn() which relies on the real vfork()
         behaviour. See a description in vg_preloaded.c for details. */
      res = VG_(pipe)(fds);
      vg_assert(res == 0);

      vg_assert(fds[0] != fds[1]);

      /* Move to Valgrind fds and set close-on-exec flag on both of them (done
         by VG_(safe_fd). */
      fds[0] = VG_(safe_fd)(fds[0]);
      fds[1] = VG_(safe_fd)(fds[1]);
      vg_assert(fds[0] != fds[1]);

      vg_assert(VG_(vfork_fildes_addr) != NULL);
      vg_assert(*VG_(vfork_fildes_addr) == -1);
      *VG_(vfork_fildes_addr) = fds[0];
   }

   VG_(do_atfork_pre)(tid);
   SET_STATUS_from_SysRes(VG_(do_syscall2)(__NR_forksys, 0, ARG2));

   if (!SUCCESS) {
      /* vfork */
      if (ARG1 == 2) {
         VG_(close)(fds[0]);
         VG_(close)(fds[1]);
      }

      return;
   }

   if (RESHI) {
      VG_(do_atfork_child)(tid);

      /* If --child-silent-after-fork=yes was specified, set the output file
         descriptors to 'impossible' values.  This is noticed by
         send_bytes_to_logging_sink() in m_libcprint.c, which duly stops
         writing any further output. */
      if (VG_(clo_child_silent_after_fork)) {
         if (!VG_(log_output_sink).is_socket)
            VG_(log_output_sink).fd = -1;
         if (!VG_(xml_output_sink).is_socket)
            VG_(xml_output_sink).fd = -1;
      }

      /* vfork */
      if (ARG1 == 2)
         VG_(close)(fds[1]);
   }
   else {
      VG_(do_atfork_parent)(tid);

      /* Print information about the fork. */
      PRINT("   fork: process %d created child %d\n", VG_(getpid)(),
            (Int)RES);

      /* vfork */
      if (ARG1 == 2) {
         /* Wait for the child to finish (exec or exit). */
         UChar w;

         VG_(close)(fds[0]);

         res = VG_(read)(fds[1], &w, 1);
         if (res == 1)
            SET_STATUS_Failure(w);
         VG_(close)(fds[1]);

         *VG_(vfork_fildes_addr) = -1;
      }
   }
}

PRE(sys_sigtimedwait)
{
   /* int sigtimedwait(const sigset_t *set, siginfo_t *info,
                       const timespec_t *timeout); */
   *flags |= SfMayBlock;
   PRINT("sys_sigtimedwait ( %#lx, %#lx, %#lx )", ARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "sigtimedwait", vki_sigset_t *, set,
                 vki_siginfo_t *, info, vki_timespec_t *, timeout);
   PRE_MEM_READ("sigtimewait(set)", ARG1, sizeof(vki_sigset_t));
   if (ARG2)
      PRE_MEM_WRITE("sigtimedwait(info)", ARG2, sizeof(vki_siginfo_t));
   if (ARG3)
      PRE_MEM_READ("sigtimedwait(timeout)", ARG3, sizeof(vki_timespec_t));
}

POST(sys_sigtimedwait)
{
   if (ARG2)
      POST_MEM_WRITE(ARG2, sizeof(vki_siginfo_t));
}

PRE(sys_yield)
{
   /* void yield(void); */
   *flags |= SfMayBlock;
   PRINT("sys_yield ( )");
   PRE_REG_READ0(long, "yield");
}

PRE(sys_lwp_sema_post)
{
   /* int lwp_sema_post(lwp_sema_t *sema); */
   vki_lwp_sema_t *sema = (vki_lwp_sema_t*)ARG1;
   *flags |= SfMayBlock;
   PRINT("sys_lwp_sema_post ( %#lx )", ARG1);
   PRE_REG_READ1(long, "lwp_sema_post", lwp_sema_t *, sema);

   PRE_FIELD_READ("lwp_sema_post(sema->type)", sema->vki_sema_type);
   PRE_FIELD_READ("lwp_sema_post(sema->count)", sema->vki_sema_count);
   /*PRE_FIELD_WRITE("lwp_sema_post(sema->count)", sema->vki_sema_count);*/
   PRE_FIELD_READ("lwp_sema_post(sema->waiters)", sema->vki_sema_waiters);
   /*PRE_FIELD_WRITE("lwp_sema_post(sema->waiters)", sema->vki_sema_waiters);*/
}

POST(sys_lwp_sema_post)
{
   vki_lwp_sema_t *sema = (vki_lwp_sema_t*)ARG1;
   POST_FIELD_WRITE(sema->vki_sema_count);
   POST_FIELD_WRITE(sema->vki_sema_waiters);
}

PRE(sys_lwp_sema_trywait)
{
   /* int lwp_sema_trywait(lwp_sema_t *sema); */
   vki_lwp_sema_t *sema = (vki_lwp_sema_t*)ARG1;
   PRINT("sys_lwp_sema_trywait ( %#lx )", ARG1);
   PRE_REG_READ1(long, "lwp_sema_trywait", lwp_sema_t *, sema);

   PRE_FIELD_READ("lwp_sema_trywait(sema->type)", sema->vki_sema_type);
   PRE_FIELD_READ("lwp_sema_trywait(sema->count)", sema->vki_sema_count);
   /*PRE_FIELD_WRITE("lwp_sema_trywait(sema->count)", sema->vki_sema_count);*/
   PRE_FIELD_READ("lwp_sema_trywait(sema->waiters)", sema->vki_sema_waiters);
   /*PRE_FIELD_WRITE("lwp_sema_trywait(sema->waiters)",
     sema->vki_sema_waiters);*/
}

POST(sys_lwp_sema_trywait)
{
   vki_lwp_sema_t *sema = (vki_lwp_sema_t*)ARG1;
   POST_FIELD_WRITE(sema->vki_sema_count);
   POST_FIELD_WRITE(sema->vki_sema_waiters);
}

PRE(sys_lwp_detach)
{
   /* int lwp_detach(id_t lwpid); */
   PRINT("sys_lwp_detach ( %ld )", SARG1);
   PRE_REG_READ1(long, "lwp_detach", vki_id_t, lwpid);
}

PRE(sys_fchroot)
{
   /* int fchroot(int fd); */
   PRINT("sys_fchroot ( %ld )", SARG1);
   PRE_REG_READ1(long, "fchroot", int, fd);

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "fchroot", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

#if defined(SOLARIS_SYSTEM_STATS_SYSCALL)
PRE(sys_system_stats)
{
   /* void system_stats(int flag); */
   PRINT("sys_system_stats ( %ld )", SARG1);
   PRE_REG_READ1(void, "system_stats", int, flag);
}
#endif /* SOLARIS_SYSTEM_STATS_SYSCALL */

PRE(sys_gettimeofday)
{
   /* Kernel: int gettimeofday(struct timeval *tp); */
   PRINT("sys_gettimeofday ( %#lx )", ARG1);
   PRE_REG_READ1(long, "gettimeofday", struct timeval *, tp);
   if (ARG1)
      PRE_timeval_WRITE("gettimeofday(tp)", ARG1);
}

POST(sys_gettimeofday)
{
   if (ARG1)
      POST_timeval_WRITE(ARG1);
}

PRE(sys_lwp_create)
{
   /* int lwp_create(ucontext_t *ucp, int flags, id_t *new_lwp) */

   ThreadId ctid;
   ThreadState *ptst;
   ThreadState *ctst;
   Addr stack;
   SysRes res;
   vki_ucontext_t uc;
   Bool tool_informed = False;

   PRINT("sys_lwp_create ( %#lx, %ld, %#lx )", ARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "lwp_create", ucontext_t *, ucp, int, flags,
                 id_t *, new_lwp);

   if (ARG3 != 0)
      PRE_MEM_WRITE("lwp_create(new_lwp)", ARG3, sizeof(vki_id_t));

   /* If we can't deref ucontext_t then we can't do anything. */
   if (!ML_(safe_to_deref)((void*)ARG1, sizeof(vki_ucontext_t))) {
      SET_STATUS_Failure(VKI_EINVAL);
      return;
   }

   ctid = VG_(alloc_ThreadState)();
   ptst = VG_(get_ThreadState)(tid);
   ctst = VG_(get_ThreadState)(ctid);

   /* Stay sane. */
   vg_assert(VG_(is_running_thread)(tid));
   vg_assert(VG_(is_valid_tid)(ctid));

   stack = ML_(allocstack)(ctid);
   if (!stack) {
      res = VG_(mk_SysRes_Error)(VKI_ENOMEM);
      goto out;
   }

   /* First inherit parent's guest state */
   ctst->arch.vex = ptst->arch.vex;
   ctst->arch.vex_shadow1 = ptst->arch.vex_shadow1;
   ctst->arch.vex_shadow2 = ptst->arch.vex_shadow2;

   /* Set up some values. */
   ctst->os_state.parent = tid;
   ctst->os_state.threadgroup = ptst->os_state.threadgroup;
   ctst->sig_mask = ptst->sig_mask;
   ctst->tmp_sig_mask = ptst->sig_mask;

   /* No stack definition should be currently present.  The stack will be set
      later by libc by a setustack() call (the getsetcontext syscall). */
   ctst->client_stack_highest_byte = 0;
   ctst->client_stack_szB = 0;
   vg_assert(ctst->os_state.stk_id == (UWord)(-1));

   /* Inform a tool that a new thread is created.  This has to be done before
      any other core->tool event is sent. */
   vg_assert(VG_(owns_BigLock_LL)(tid));
   VG_TRACK(pre_thread_ll_create, tid, ctid);
   tool_informed = True;

#if defined(VGP_x86_solaris)
   /* Set up GDT (this has to be done before calling
      VG_(restore_context)(). */
   ML_(setup_gdt)(&ctst->arch.vex);
#elif defined(VGP_amd64_solaris)
   /* Nothing to do. */
#else
#  error "Unknown platform"
#endif

   /* Now set up the new thread according to ucontext_t. */
   VG_(restore_context)(ctid, (vki_ucontext_t*)ARG1, Vg_CoreSysCall,
                        True/*esp_is_thrptr*/);

   /* Set up V thread (this also tells the kernel to block all signals in the
      thread). */
   ML_(setup_start_thread_context)(ctid, &uc);

   /* Actually create the new thread. */
   res = VG_(do_syscall3)(__NR_lwp_create, (UWord)&uc, ARG2, ARG3);

   if (!sr_isError(res)) {
      if (ARG3 != 0)
         POST_MEM_WRITE(ARG3, sizeof(vki_id_t));
      if (ARG2 & VKI_LWP_DAEMON)
         ctst->os_state.daemon_thread = True;
   }

out:
   if (sr_isError(res)) {
      if (tool_informed) {
         /* Tell a tool the thread exited in a hurry. */
         VG_TRACK(pre_thread_ll_exit, ctid);
      }

      /* lwp_create failed. */
      VG_(cleanup_thread)(&ctst->arch);
      ctst->status = VgTs_Empty;
   }

   SET_STATUS_from_SysRes(res);
}

PRE(sys_lwp_exit)
{
   /* void syslwp_exit(); */
   ThreadState *tst = VG_(get_ThreadState)(tid);
   PRINT("sys_lwp_exit ( )");
   PRE_REG_READ0(long, "lwp_exit");

   /* Set the thread's status to be exiting, then claim that the syscall
      succeeded. */
   tst->exitreason = VgSrc_ExitThread;
   tst->os_state.exitcode = 0;
   SET_STATUS_Success(0);
}

PRE(sys_lwp_suspend)
{
   /* int lwp_suspend(id_t lwpid); */
   ThreadState *tst = VG_(get_ThreadState)(tid);
   PRINT("sys_lwp_suspend ( %ld )", SARG1);
   PRE_REG_READ1(long, "lwp_suspend", vki_id_t, lwpid);

   if (ARG1 == tst->os_state.lwpid) {
      /* Set the SfMayBlock flag only if the currently running thread should
         be suspended. If this flag was used also when suspending other
         threads then it could happen that a thread holding the_BigLock would
         be suspended and Valgrind would hang. */
      *flags |= SfMayBlock;
   }
}

PRE(sys_lwp_continue)
{
   /* int lwp_continue(id_t target_lwp); */
   PRINT("sys_lwp_continue ( %ld )", SARG1);
   PRE_REG_READ1(long, "lwp_continue", vki_id_t, target_lwp);
}

static void
do_lwp_sigqueue(const HChar *syscall_name, UWord target_lwp, UWord signo,
                SyscallStatus *status, UWord *flags)
{
   if (!ML_(client_signal_OK)(signo)) {
      SET_STATUS_Failure(VKI_EINVAL);
      return;
   }

   /* Check to see if this gave us a pending signal. */
   *flags |= SfPollAfter;

   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg, "%s: sending signal %lu to thread %lu\n",
                   syscall_name, signo, target_lwp);

   /* If we're sending SIGKILL, check to see if the target is one of our
      threads and handle it specially. */
   if (signo == VKI_SIGKILL && ML_(do_sigkill)(target_lwp, -1)) {
      SET_STATUS_Success(0);
      return;
   }

   /* Ask to handle this syscall via the slow route, since that's the only one
      that sets tst->status to VgTs_WaitSys.  If the result of doing the
      syscall is an immediate run of async_signalhandler() in m_signals.c,
      then we need the thread to be properly tidied away. */
   *flags |= SfMayBlock;
}

#if defined(SOLARIS_LWP_SIGQUEUE_SYSCALL)
#if defined(SOLARIS_LWP_SIGQUEUE_SYSCALL_TAKES_PID)
PRE(sys_lwp_sigqueue)
{
   /* int lwp_sigqueue(pid_t target_pid, id_t target_lwp, int signal,
                       void *value, int si_code, timespec_t *timeout);
    */
   PRINT("sys_lwp_sigqueue ( %ld, %ld, %ld, %#lx, %ld, %#lx )",
         SARG1, SARG2, SARG3, ARG4, SARG5, ARG6);
   PRE_REG_READ6(long, "lwp_sigqueue", vki_pid_t, target_pid,
                 vki_id_t, target_lwp, int, signal, void *, value, int, si_code,
                 vki_timespec_t *, timeout);

   if (ARG6)
      PRE_MEM_READ("lwp_sigqueue(timeout)", ARG6, sizeof(vki_timespec_t));

   if ((ARG1 == 0) || (ARG1 == VG_(getpid)())) {
      do_lwp_sigqueue("lwp_sigqueue", ARG2, ARG3, status, flags);
   } else {
      /* Signal is sent to a different process. */
      if (VG_(clo_trace_signals))
         VG_(message)(Vg_DebugMsg, "lwp_sigqueue: sending signal %ld to "
                      "process %ld, thread %ld\n", SARG3, SARG1, SARG2);
     *flags |= SfMayBlock;
   }
}

POST(sys_lwp_sigqueue)
{
   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg, "lwp_sigqueue: sent signal %ld to process %ld, "
                   "thread %ld\n", SARG3, SARG1, SARG2);
}

#else

PRE(sys_lwp_sigqueue)
{
   /* int lwp_sigqueue(id_t target_lwp, int signal, void *value,
                       int si_code, timespec_t *timeout);
    */
   PRINT("sys_lwp_sigqueue ( %ld, %ld, %#lx, %ld, %#lx )",
         SARG1, SARG2, ARG3, SARG4, ARG5);
   PRE_REG_READ5(long, "lwp_sigqueue", vki_id_t, target_lwp, int, signal,
                 void *, value, int, si_code, vki_timespec_t *, timeout);

   if (ARG5)
      PRE_MEM_READ("lwp_sigqueue(timeout)", ARG5, sizeof(vki_timespec_t));

   do_lwp_sigqueue("lwp_sigqueue", ARG1, ARG2, status, flags);
}

POST(sys_lwp_sigqueue)
{
   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg, "lwp_sigqueue: sent signal %lu to thread %lu\n",
                   ARG2, ARG1);
}


#endif /* SOLARIS_LWP_SIGQUEUE_SYSCALL_TAKES_PID */

#else

PRE(sys_lwp_kill)
{
   /* int lwp_kill(id_t target_lwp, int signal); */
   PRINT("sys_lwp_kill ( %ld, %ld )", SARG1, SARG2);
   PRE_REG_READ2(long, "lwp_kill", vki_id_t, target_lwp, int, signal);

   do_lwp_sigqueue("lwp_kill", ARG1, ARG2, status, flags);
}

POST(sys_lwp_kill)
{
   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg, "lwp_kill: sent signal %lu to thread %lu\n",
                   ARG2, ARG1);
}
#endif /* SOLARIS_LWP_SIGQUEUE_SYSCALL */

PRE(sys_lwp_self)
{
   /* id_t lwp_self(void); */
   PRINT("sys_lwp_self ( )");
   PRE_REG_READ0(long, "lwp_self");
}

PRE(sys_lwp_sigmask)
{
   /* int64_t lwp_sigmask(int how, uint_t bits0, uint_t bits1, uint_t bits2,
                          uint_t bits3); */
   vki_sigset_t sigset;
   PRINT("sys_lwp_sigmask ( %ld, %#lx, %#lx, %#lx, %#lx )", SARG1, ARG2, ARG3,
         ARG4, ARG5);
   PRE_REG_READ5(long, "lwp_sigmask", int, how, vki_uint_t, bits0,
                 vki_uint_t, bits1, vki_uint_t, bits2, vki_uint_t, bits3);

   sigset.__sigbits[0] = ARG2;
   sigset.__sigbits[1] = ARG3;
   sigset.__sigbits[2] = ARG4;
   sigset.__sigbits[3] = ARG5;

   SET_STATUS_from_SysRes(
      VG_(do_sys_sigprocmask)(tid, ARG1 /*how*/, &sigset, NULL)
   );

   if (SUCCESS)
      *flags |= SfPollAfter;
}

PRE(sys_lwp_private)
{
   /* int lwp_private(int cmd, int which, uintptr_t base); */
   ThreadState *tst = VG_(get_ThreadState)(tid);
   Int supported_base, supported_sel;
   PRINT("sys_lwp_private ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
   PRE_REG_READ3(long, "lwp_private", int, cmd, int, which,
                 uintptr_t, base);

   /* Note: Only the %gs base is currently supported on x86 and the %fs base
      on amd64.  Support for the %fs base on x86 and for the %gs base on amd64
      should be added.  Anything else is probably a client program error. */
#if defined(VGP_x86_solaris)
   supported_base = VKI_LWP_GSBASE;
   supported_sel = VKI_LWPGS_SEL;
#elif defined(VGP_amd64_solaris)
   supported_base = VKI_LWP_FSBASE;
   supported_sel = 0;
#else
#error "Unknown platform"
#endif
   if (ARG2 != supported_base) {
      VG_(unimplemented)("Syswrap of the lwp_private call where which=%ld.",
                         SARG2);
      /*NOTREACHED*/
   }

   switch (ARG1 /*cmd*/) {
   case VKI_LWP_SETPRIVATE:
#if defined(VGP_x86_solaris)
      tst->os_state.thrptr = ARG3;
      ML_(update_gdt_lwpgs)(tid);
#elif defined(VGP_amd64_solaris)
      tst->arch.vex.guest_FS_CONST = ARG3;
#else
#error "Unknown platform"
#endif
      SET_STATUS_Success(supported_sel);
      break;
   case VKI_LWP_GETPRIVATE:
      {
         int thrptr;
#if defined(VGP_x86_solaris)
         thrptr = tst->os_state.thrptr;
#elif defined(VGP_amd64_solaris)
         thrptr = tst->arch.vex.guest_FS_CONST;
#else
#error "Unknown platform"
#endif

         if (thrptr == 0) {
            SET_STATUS_Failure(VKI_EINVAL);
            return;
         }

#if defined(VGP_x86_solaris)
         if (tst->arch.vex.guest_GS != supported_sel) {
            SET_STATUS_Failure(VKI_EINVAL);
            return;
         }
#elif defined(VGP_amd64_solaris)
         /* Valgrind on amd64 does not allow to change the gs register so
            a check that guest_GS is equal to supported_sel is not needed
            here. */
#else
#error "Unknown platform"
#endif

         PRE_MEM_WRITE("lwp_private(base)", ARG3, sizeof(Addr));
         if (!ML_(safe_to_deref((void*)ARG3, sizeof(Addr)))) {
            SET_STATUS_Failure(VKI_EFAULT);
            return;
         }
         *(Addr*)ARG3 = thrptr;
         POST_MEM_WRITE((Addr)ARG3, sizeof(Addr));
         SET_STATUS_Success(0);
         break;
      }
   default:
      VG_(unimplemented)("Syswrap of the lwp_private call where cmd=%ld.",
                         SARG1);
      /*NOTREACHED*/
      break;
   }
}

PRE(sys_lwp_wait)
{
   /* int lwp_wait(id_t lwpid, id_t *departed); */
   *flags |= SfMayBlock;
   PRINT("sys_lwp_wait ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "lwp_wait", vki_id_t, lwpid, vki_id_t *, departed);
   if (ARG2)
      PRE_MEM_WRITE("lwp_wait(departed)", ARG2, sizeof(vki_id_t));
}

POST(sys_lwp_wait)
{
   POST_MEM_WRITE(ARG2, sizeof(vki_id_t));
}

PRE(sys_lwp_mutex_wakeup)
{
   /* int lwp_mutex_wakeup(lwp_mutex_t *lp, int release_all); */
   *flags |= SfMayBlock;
   PRINT("sys_lwp_mutex_wakeup ( %#lx, %ld )", ARG1, SARG2);
   PRE_REG_READ2(long, "lwp_mutex_wakeup", vki_lwp_mutex_t *, lp,
                 int, release_all);
   vki_lwp_mutex_t *lp = (vki_lwp_mutex_t *) ARG1;
   PRE_FIELD_READ("lwp_mutex_wakeup(lp->mutex_type)", lp->vki_mutex_type);
   PRE_FIELD_WRITE("lwp_mutex_wakeup(lp->mutex_waiters)",
                   lp->vki_mutex_waiters);
}

POST(sys_lwp_mutex_wakeup)
{
   vki_lwp_mutex_t *lp = (vki_lwp_mutex_t *) ARG1;
   POST_FIELD_WRITE(lp->vki_mutex_waiters);
}

PRE(sys_lwp_cond_wait)
{
   /* int lwp_cond_wait(lwp_cond_t *cvp, lwp_mutex_t *mp, timespec_t *tsp,
                        int check_park); */
   *flags |= SfMayBlock;
   PRINT("sys_lwp_cond_wait( %#lx, %#lx, %#lx, %ld )", ARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "lwp_cond_wait", vki_lwp_cond_t *, cvp,
                 vki_lwp_mutex_t *, mp, vki_timespec_t *, tsp, int, check_part);

   vki_lwp_cond_t *cvp = (vki_lwp_cond_t *) ARG1;
   vki_lwp_mutex_t *mp = (vki_lwp_mutex_t *) ARG2;
   PRE_FIELD_READ("lwp_cond_wait(cvp->type)", cvp->vki_cond_type);
   PRE_FIELD_READ("lwp_cond_wait(cvp->waiters_kernel)",
                  cvp->vki_cond_waiters_kernel);
   PRE_FIELD_READ("lwp_cond_wait(mp->mutex_type)", mp->vki_mutex_type);
   PRE_FIELD_WRITE("lwp_cond_wait(mp->mutex_waiters)", mp->vki_mutex_waiters);
   if (ARG3 != 0)
      PRE_MEM_READ("lwp_cond_wait(tsp)", ARG3, sizeof(vki_timespec_t));
}

POST(sys_lwp_cond_wait)
{
   vki_lwp_cond_t *cvp = (vki_lwp_cond_t *) ARG1;
   vki_lwp_mutex_t *mp = (vki_lwp_mutex_t *) ARG2;
   POST_FIELD_WRITE(cvp->vki_cond_waiters_kernel);
   POST_FIELD_WRITE(mp->vki_mutex_waiters);
   if (ARG3 != 0)
      POST_MEM_WRITE(ARG3, sizeof(vki_timespec_t));
}

PRE(sys_lwp_cond_broadcast)
{
   /* int lwp_cond_broadcast(lwp_cond_t *cvp); */
   *flags |= SfMayBlock;
   PRINT("sys_lwp_cond_broadcast ( %#lx )", ARG1);
   PRE_REG_READ1(long, "lwp_cond_broadcast", vki_lwp_cond_t *, cvp);

   vki_lwp_cond_t *cvp = (vki_lwp_cond_t *) ARG1;
   PRE_FIELD_READ("lwp_cond_broadcast(cvp->type)", cvp->vki_cond_type);
   PRE_FIELD_READ("lwp_cond_broadcast(cvp->waiters_kernel)",
                  cvp->vki_cond_waiters_kernel);
   /*PRE_FIELD_WRITE("lwp_cond_broadcast(cvp->waiters_kernel)",
                     cvp->vki_cond_waiters_kernel);*/
}

POST(sys_lwp_cond_broadcast)
{
   vki_lwp_cond_t *cvp = (vki_lwp_cond_t *) ARG1;
   POST_FIELD_WRITE(cvp->vki_cond_waiters_kernel);
}

PRE(sys_pread)
{
   /* ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset); */
   *flags |= SfMayBlock;
   PRINT("sys_pread ( %ld, %#lx, %lu, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "pread", int, fildes, void *, buf,
                 vki_size_t, nbyte, vki_off_t, offset);
   PRE_MEM_WRITE("pread(buf)", ARG2, ARG3);

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "pread", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_pread)
{
   POST_MEM_WRITE(ARG2, RES);
}

PRE(sys_pwrite)
{
   /* ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
                     off_t offset); */
   *flags |= SfMayBlock;
   PRINT("sys_pwrite ( %ld, %#lx, %lu, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "pwrite", int, fildes, const void *, buf,
                 vki_size_t, nbyte, vki_off_t, offset);
   PRE_MEM_READ("pwrite(buf)", ARG2, ARG3);

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "pwrite", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_getpagesizes)
{
   /* int getpagesizes(int legacy, size_t *buf, int nelem); */
   PRINT("sys_getpagesizes ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
   PRE_REG_READ3(long, "getpagesizes", int, legacy, size_t *, buf,
                 int, nelem);
   if (ARG2)
      PRE_MEM_WRITE("getpagesizes(buf)", ARG2, ARG3 * sizeof(vki_size_t));
}

POST(sys_getpagesizes)
{
   if (ARG2)
      POST_MEM_WRITE(ARG2, RES * sizeof(vki_size_t));
}

PRE(sys_rusagesys)
{
   /* Kernel: int rusagesys(int code, void *arg1, void *arg2,
                            void *arg3, void *arg4); */
   switch (ARG1 /*code*/) {
   case VKI__RUSAGESYS_GETRUSAGE:
   case VKI__RUSAGESYS_GETRUSAGE_CHLD:
   case VKI__RUSAGESYS_GETRUSAGE_LWP:
      /* Libc: int getrusage(int who, struct rusage *r_usage); */
      PRINT("sys_rusagesys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("rusagesys", "getrusage"), int, code,
                    struct vki_rusage *, r_usage);
      PRE_MEM_WRITE("rusagesys(r_usage)", ARG2, sizeof(struct vki_rusage));
      break;

   case VKI__RUSAGESYS_GETVMUSAGE:
      /* Libc: int getvmusage(uint_t flags, time_t age,
                              vmusage_t *buf, size_t *nres); */
      PRINT("sys_rusagesys ( %ld, %lu, %ld, %#lx, %#lx )",
            SARG1, ARG2, SARG3, ARG4, ARG5);
      PRE_REG_READ5(long, SC2("rusagesys", "getvmusage"), int, code,
                    vki_uint_t, flags, vki_time_t, age,
                    vki_vmusage_t *, buf, vki_size_t *, nres);
      PRE_MEM_READ("rusagesys(nres)", ARG5, sizeof(vki_size_t));
      /* PRE_MEM_WRITE("rusagesys(nres)", ARG5, sizeof(vki_size_t)); */

      if (ML_(safe_to_deref)((void *) ARG5, sizeof(vki_size_t))) {
         vki_size_t *nres = (vki_size_t *) ARG5;
         PRE_MEM_WRITE("rusagesys(buf)", ARG4,
                       *nres * sizeof(vki_vmusage_t));
      }
      *flags |= SfMayBlock;
      break;

   default:
      VG_(unimplemented)("Syswrap of the rusagesys call with code %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_rusagesys)
{
   switch (ARG1 /*code*/) {
   case VKI__RUSAGESYS_GETRUSAGE:
   case VKI__RUSAGESYS_GETRUSAGE_CHLD:
   case VKI__RUSAGESYS_GETRUSAGE_LWP:
      POST_MEM_WRITE(ARG2, sizeof(struct vki_rusage));
      break;
   case VKI__RUSAGESYS_GETVMUSAGE:
      {
         vki_size_t *nres = (vki_size_t *) ARG5;
         POST_MEM_WRITE(ARG5, sizeof(vki_size_t));
         POST_MEM_WRITE(ARG4, *nres * sizeof(vki_vmusage_t));
      }
      break;
   default:
      vg_assert(0);
      break;
   }

}

PRE(sys_port)
{
   /* Kernel: int64_t portfs(int opcode, uintptr_t a0, uintptr_t a1,
                             uintptr_t a2, uintptr_t a3, uintptr_t a4); */
   Int opcode = ARG1 & VKI_PORT_CODE_MASK;
   *flags |= SfMayBlock;
   switch (opcode) {
   case VKI_PORT_CREATE:
      PRINT("sys_port ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("port", "create"), int, opcode);
      break;
   case VKI_PORT_ASSOCIATE:
   case VKI_PORT_DISSOCIATE:
      PRINT("sys_port ( %ld, %ld, %ld, %#lx, %ld, %#lx )", SARG1, SARG2, SARG3,
            ARG4, SARG5, ARG6);
      if (opcode == VKI_PORT_ASSOCIATE) {
         PRE_REG_READ6(long, SC2("port", "associate"), int, opcode, int, a0,
                       int, a1, uintptr_t, a2, int, a3, void *, a4);
      }
      else {
         PRE_REG_READ6(long, SC2("port", "dissociate"), int, opcode, int, a0,
                       int, a1, uintptr_t, a2, int, a3, void *, a4);
      }

      switch (ARG3 /*source*/) {
      case VKI_PORT_SOURCE_FD:
         if (!ML_(fd_allowed)(ARG4, "port", tid, False)) {
            SET_STATUS_Failure(VKI_EBADF);
         }
         break;
      case VKI_PORT_SOURCE_FILE:
         {
            struct vki_file_obj *fo = (struct vki_file_obj *)ARG4;
            PRE_MEM_READ("port(file_obj)", ARG4, sizeof(struct vki_file_obj));
            if (ML_(safe_to_deref)(&fo->fo_name, sizeof(fo->fo_name)))
               PRE_MEM_RASCIIZ("port(file_obj->fo_name)", (Addr)fo->fo_name);
         }
         break;
      default:
         VG_(unimplemented)("Syswrap of the port_associate/dissociate call "
                            "type %ld.", SARG3);
         /*NOTREACHED*/
         break;
      }
      break;
   case VKI_PORT_SEND:
      PRINT("sys_port ( %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3, ARG4);
      PRE_REG_READ4(long, SC2("port", "send"), int, opcode, int, a0, int, a1,
                    void *, a2);
      break;
   case VKI_PORT_SENDN:
      PRINT("sys_port ( %ld, %#lx, %#lx, %lu, %lx, %#lx)", SARG1, ARG2, ARG3,
            ARG4, ARG5, ARG6);
      PRE_REG_READ6(long, SC2("port", "sendn"), int, opcode, int *, a0,
                    int *, a1, vki_uint_t, a2, int, a3, void *, a4);
      PRE_MEM_READ("port(ports)", ARG2, ARG4 * sizeof(int));
      PRE_MEM_WRITE("port(errors)", ARG3, ARG4 * sizeof(int));
      break;
   case VKI_PORT_GET:
      PRINT("sys_port ( %ld, %ld, %#lx, %ld, %ld, %#lx )", SARG1, SARG2, ARG3,
            SARG4, SARG5, ARG6);
      PRE_REG_READ6(long, SC2("port", "get"), int, opcode, int, a0,
                    port_event_t *, a1, vki_time_t, a2, long, a3,
                    timespec_t *, a4);
      PRE_MEM_WRITE("port(uevp)", ARG3, sizeof(vki_port_event_t));
      break;
   case VKI_PORT_GETN:
      PRINT("sys_port ( %ld, %ld, %#lx, %lu, %lu, %#lx )", SARG1, SARG2, ARG3,
            ARG4, ARG5, ARG6);
      PRE_REG_READ6(long, SC2("port", "getn"), int, opcode, int, a0,
                    port_event_t *, a1, vki_uint_t, a2, vki_uint_t, a3,
                    timespec_t *, a4);
      if (ARG6)
         PRE_MEM_READ("port(timeout)", ARG6, sizeof(vki_timespec_t));
      PRE_MEM_WRITE("port(uevp)", ARG3, ARG4 * sizeof(vki_port_event_t));
      break;
   case VKI_PORT_ALERT:
      PRINT("sys_port ( %ld, %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3, SARG4,
            ARG5);
      PRE_REG_READ5(long, SC2("port", "alert"), int, opcode, int, a0, int, a1,
                    int, a2, void *, a3);
      break;
   case VKI_PORT_DISPATCH:
      // FIXME: check order: SARG2, SARG1  or   SARG1, SARG2  ??
      PRINT("sys_port ( %ld, %ld, %ld, %ld, %#lx, %#lx )", SARG2, SARG1, SARG3,
            SARG4, ARG5, ARG6);
      PRE_REG_READ6(long, SC2("port", "dispatch"), int, opcode, int, a0,
                    int, a1, int, a2, uintptr_t, a3, void *, a4);
      break;
   default:
      VG_(unimplemented)("Syswrap of the port call with opcode %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }

   /* Be strict. */
   if ((opcode != VKI_PORT_CREATE && opcode != VKI_PORT_SENDN) &&
       !ML_(fd_allowed)(ARG2, "port", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_port)
{
   Int opcode = ARG1 & VKI_PORT_CODE_MASK;
   switch (opcode) {
   case VKI_PORT_CREATE:
      if (!ML_(fd_allowed)(RES, "port", tid, True)) {
         VG_(close)(RES);
         SET_STATUS_Failure(VKI_EMFILE);
      }
      else if (VG_(clo_track_fds))
         ML_(record_fd_open_named)(tid, RES);
      break;
   case VKI_PORT_ASSOCIATE:
   case VKI_PORT_DISSOCIATE:
   case VKI_PORT_SEND:
      break;
   case VKI_PORT_SENDN:
      if (RES != ARG4) {
         /* If there is any error then the whole errors area is written. */
         POST_MEM_WRITE(ARG3, ARG4 * sizeof(int));
      }
      break;
   case VKI_PORT_GET:
      POST_MEM_WRITE(ARG3, sizeof(vki_port_event_t));
      break;
   case VKI_PORT_GETN:
      POST_MEM_WRITE(ARG3, RES * sizeof(vki_port_event_t));
      break;
   case VKI_PORT_ALERT:
   case VKI_PORT_DISPATCH:
      break;
   default:
      VG_(unimplemented)("Syswrap of the port call with opcode %lu.", ARG1);
      /*NOTREACHED*/
      break;
   }
}

PRE(sys_pollsys)
{
   /* int pollsys(pollfd_t *fds, nfds_t nfds, timespec_t *timeout,
                  sigset_t *set); */
   UWord i;
   struct vki_pollfd *ufds = (struct vki_pollfd *)ARG1;

   *flags |= SfMayBlock;

   PRINT("sys_pollsys ( %#lx, %lu, %#lx, %#lx )", ARG1, ARG2, ARG3, ARG4);
   PRE_REG_READ4(long, "poll", pollfd_t *, fds, vki_nfds_t, nfds,
                 timespec_t *, timeout, sigset_t *, set);

   for (i = 0; i < ARG2; i++) {
      vki_pollfd_t *u = &ufds[i];
      PRE_FIELD_READ("poll(ufds.fd)", u->fd);
      /* XXX Check if it's valid? */
      PRE_FIELD_READ("poll(ufds.events)", u->events);
      PRE_FIELD_WRITE("poll(ufds.revents)", u->revents);
   }

   if (ARG3)
      PRE_MEM_READ("poll(timeout)", ARG3, sizeof(vki_timespec_t));
   if (ARG4)
      PRE_MEM_READ("poll(set)", ARG4, sizeof(vki_sigset_t));
}

POST(sys_pollsys)
{
   if (RES >= 0) {
      UWord i;
      vki_pollfd_t *ufds = (vki_pollfd_t*)ARG1;
      for (i = 0; i < ARG2; i++)
         POST_FIELD_WRITE(ufds[i].revents);
   }
}

PRE(sys_labelsys)
{
   /* Kernel: int labelsys(int op, void *a1, void *a2, void *a3,
                           void *a4, void *a5); */

   switch (ARG1 /*op*/) {
   case VKI_TSOL_SYSLABELING:
      /* Libc: int is_system_labeled(void); */
      PRINT("sys_labelsys ( %ld )", SARG1);
      PRE_REG_READ1(long, SC2("labelsys", "syslabeling"), int, op);
      break;

   case VKI_TSOL_TNRH:
      /* Libtsnet: int tnrh(int cmd, tsol_rhent_t *buf); */
      PRINT("sys_labelsys ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("labelsys", "tnrh"), int, op, int, cmd,
                    vki_tsol_rhent_t *, buf);
      if (ARG2 != VKI_TNDB_FLUSH)
         PRE_MEM_READ("labelsys(buf)", ARG3, sizeof(vki_tsol_rhent_t));
      break;

   case VKI_TSOL_TNRHTP:
      /* Libtsnet: int tnrhtp(int cmd, tsol_tpent_t *buf); */
      PRINT("sys_labelsys ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("labelsys", "tnrhtp"), int, op, int, cmd,
                    vki_tsol_tpent_t *, buf);
      if (ARG2 != VKI_TNDB_FLUSH)
         PRE_MEM_READ("labelsys(buf)", ARG3, sizeof(vki_tsol_tpent_t));
      break;

   case VKI_TSOL_TNMLP:
      /* Libtsnet: int tnmlp(int cmd, tsol_mlpent_t *buf); */
      PRINT("sys_labelsys ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("labelsys", "tnmlp"), int, op, int, cmd,
                    vki_tsol_mlpent_t *, buf);
      PRE_MEM_READ("labelsys(buf)", ARG3, sizeof(vki_tsol_mlpent_t));
      break;

   case VKI_TSOL_GETLABEL:
      /* Libtsol: int getlabel(const char *path, bslabel_t *label); */
      PRINT("sys_labelsys ( %ld, %#lx(%s), %#lx )",
            SARG1, ARG2, (HChar *) ARG2, ARG3);
      PRE_REG_READ3(long, SC2("labelsys", "getlabel"), int, op,
                    const char *, path, vki_bslabel_t *, label);
      PRE_MEM_RASCIIZ("labelsys(path)", ARG2);
      PRE_MEM_WRITE("labelsys(label)", ARG3, sizeof(vki_bslabel_t));
      break;

   case VKI_TSOL_FGETLABEL:
      /* Libtsol: int fgetlabel(int fd, bslabel_t *label); */
      PRINT("sys_labelsys ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("labelsys", "fgetlabel"), int, op,
                    int, fd, vki_bslabel_t *, label);
      /* Be strict. */
      if (!ML_(fd_allowed)(ARG2, "labelsys(fgetlabel)", tid, False))
         SET_STATUS_Failure(VKI_EBADF);
      PRE_MEM_WRITE("labelsys(label)", ARG3, sizeof(vki_bslabel_t));
      break;

#if defined(SOLARIS_TSOL_CLEARANCE)
   case VKI_TSOL_GETCLEARANCE:
      /* Libtsol: int getclearance(bslabel_t *clearance); */
      PRINT("sys_labelsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("labelsys", "getclearance"), int, op,
                    vki_bslabel_t *, clearance);
      PRE_MEM_WRITE("labelsys(clearance)", ARG2, sizeof(vki_bslabel_t));
      break;

   case VKI_TSOL_SETCLEARANCE:
      /* Libtsol: int setclearance(bslabel_t *clearance); */
      PRINT("sys_labelsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("labelsys", "setclearance"), int, op,
                    vki_bslabel_t *, clearance);
      PRE_MEM_READ("labelsys(clearance)", ARG2, sizeof(vki_bslabel_t));
      break;
#endif /* SOLARIS_TSOL_CLEARANCE */

   default:
      VG_(unimplemented)("Syswrap of the labelsys call with op %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_labelsys)
{
   switch (ARG1 /*op*/) {
   case VKI_TSOL_SYSLABELING:
      break;

   case VKI_TSOL_TNRH:
      switch (ARG2 /*cmd*/) {
      case VKI_TNDB_LOAD:
      case VKI_TNDB_DELETE:
      case VKI_TNDB_FLUSH:
         break;
#if defined(SOLARIS_TNDB_GET_TNIP)
      case TNDB_GET_TNIP:
#endif /* SOLARIS_TNDB_GET_TNIP */
      case VKI_TNDB_GET:
         POST_MEM_WRITE(ARG3, sizeof(vki_tsol_rhent_t));
         break;
      default:
         vg_assert(0);
         break;
      }
      break;

   case VKI_TSOL_TNRHTP:
      switch (ARG2 /*cmd*/) {
      case VKI_TNDB_LOAD:
      case VKI_TNDB_DELETE:
      case VKI_TNDB_FLUSH:
         break;
      case VKI_TNDB_GET:
         POST_MEM_WRITE(ARG3, sizeof(vki_tsol_tpent_t));
         break;
      default:
         vg_assert(0);
         break;
      }
      break;

   case VKI_TSOL_TNMLP:
      switch (ARG2 /*cmd*/) {
      case VKI_TNDB_LOAD:
      case VKI_TNDB_DELETE:
      case VKI_TNDB_FLUSH:
         break;
      case VKI_TNDB_GET:
         POST_MEM_WRITE(ARG3, sizeof(vki_tsol_mlpent_t));
         break;
      default:
         vg_assert(0);
         break;
      }
      break;

   case VKI_TSOL_GETLABEL:
   case VKI_TSOL_FGETLABEL:
      POST_MEM_WRITE(ARG3, sizeof(vki_bslabel_t));
      break;

#if defined(SOLARIS_TSOL_CLEARANCE)
   case VKI_TSOL_GETCLEARANCE:
      POST_MEM_WRITE(ARG2, sizeof(vki_bslabel_t));
      break;

   case VKI_TSOL_SETCLEARANCE:
      break;
#endif /* SOLARIS_TSOL_CLEARANCE */

   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_acl)
{
   /* int acl(char *pathp, int cmd, int nentries, void *aclbufp); */
   PRINT("sys_acl ( %#lx(%s), %ld, %ld, %#lx )", ARG1, (HChar *) ARG1, SARG2,
         SARG3, ARG4);

   PRE_REG_READ4(long, "acl", char *, pathp, int, cmd,
                 int, nentries, void *, aclbufp);
   PRE_MEM_RASCIIZ("acl(pathp)", ARG1);

   switch (ARG2 /*cmd*/) {
   case VKI_SETACL:
      if (ARG4)
         PRE_MEM_READ("acl(aclbufp)", ARG4, ARG3 * sizeof(vki_aclent_t));
      break;
   case VKI_GETACL:
      PRE_MEM_WRITE("acl(aclbufp)", ARG4, ARG3 * sizeof(vki_aclent_t));
      break;
   case VKI_GETACLCNT:
      break;
   case VKI_ACE_SETACL:
      if (ARG4)
         PRE_MEM_READ("acl(aclbufp)", ARG4, ARG3 * sizeof(vki_ace_t));
      break;
   case VKI_ACE_GETACL:
      PRE_MEM_WRITE("acl(aclbufp)", ARG4, ARG3 * sizeof(vki_ace_t));
      break;
   case VKI_ACE_GETACLCNT:
      break;
   default:
      VG_(unimplemented)("Syswrap of the acl call with cmd %ld.", SARG2);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_acl)
{
   switch (ARG2 /*cmd*/) {
   case VKI_SETACL:
      break;
   case VKI_GETACL:
      POST_MEM_WRITE(ARG4, ARG3 * sizeof(vki_aclent_t));
      break;
   case VKI_GETACLCNT:
      break;
   case VKI_ACE_SETACL:
      break;
   case VKI_ACE_GETACL:
      POST_MEM_WRITE(ARG4, ARG3 * sizeof(vki_ace_t));
      break;
   case VKI_ACE_GETACLCNT:
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_auditsys)
{
   /* Kernel: int auditsys(long code, long a1, long a2, long a3, long a4); */
   switch (ARG1 /*code*/) {
   case VKI_BSM_GETAUID:
      /* Libbsm: int getauid(au_id_t *auid); */
      PRINT("sys_auditsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("auditsys", "getauid"), long, code,
                    vki_au_id_t *, auid);
      PRE_MEM_WRITE("auditsys(auid)", ARG2, sizeof(vki_au_id_t));
      break;
   case VKI_BSM_SETAUID:
      /* Libbsm: int setauid(au_id_t *auid); */
      PRINT("sys_auditsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("auditsys", "setauid"), long, code,
                    vki_au_id_t *, auid);
      PRE_MEM_READ("auditsys(auid)", ARG2, sizeof(vki_au_id_t));
      break;
   case VKI_BSM_GETAUDIT:
      /* Libbsm: int getaudit(auditinfo_t *ai); */
      PRINT("sys_auditsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("auditsys", "getaudit"), long, code,
                    vki_auditinfo_t *, ai);
      PRE_MEM_WRITE("auditsys(ai)", ARG2, sizeof(vki_auditinfo_t));
      break;
   case VKI_BSM_SETAUDIT:
      /* Libbsm: int setaudit(auditinfo_t *ai); */
      PRINT("sys_auditsys ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("auditsys", "setaudit"), long, code,
                    vki_auditinfo_t *, ai);
      PRE_MEM_READ("auditsys(ai)", ARG2, sizeof(vki_auditinfo_t));
      break;
   case VKI_BSM_AUDIT:
      /* Libbsm: int audit(void *record, int length); */
      PRINT("sys_auditsys ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
      PRE_REG_READ3(long, SC2("auditsys", "audit"), long, code,
                    void *, record, int, length);
      PRE_MEM_READ("auditsys(record)", ARG2, ARG3);
      break;
   case VKI_BSM_AUDITCTL:
      /* Libbsm: int auditon(int cmd, caddr_t data, int length); */
      PRINT("sys_auditsys ( %ld, %ld, %#lx, %ld )",
            SARG1, SARG2, ARG3, SARG4);

      switch (ARG2 /*cmd*/) {
      case VKI_A_GETPOLICY:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getpolicy"),
                       long, code, int, cmd, vki_uint32_t *, policy);
         PRE_MEM_WRITE("auditsys(policy)", ARG3, sizeof(vki_uint32_t));
         break;
      case VKI_A_SETPOLICY:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setpolicy"),
                       long, code, int, cmd, vki_uint32_t *, policy);
         PRE_MEM_READ("auditsys(policy)", ARG3, sizeof(vki_uint32_t));
         break;
      case VKI_A_GETKMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getkmask"),
                       long, code, int, cmd, vki_au_mask_t *, kmask);
         PRE_MEM_WRITE("auditsys(kmask)", ARG3, sizeof(vki_au_mask_t));
         break;
      case VKI_A_SETKMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setkmask"),
                       long, code, int, cmd, vki_au_mask_t *, kmask);
         PRE_MEM_READ("auditsys(kmask)", ARG3, sizeof(vki_au_mask_t));
         break;
      case VKI_A_GETQCTRL:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getqctrl"),
                       long, code, int, cmd,
                       struct vki_au_qctrl *, qctrl);
         PRE_MEM_WRITE("auditsys(qctrl)", ARG3,
                       sizeof(struct vki_au_qctrl));
         break;
      case VKI_A_SETQCTRL:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setqctrl"),
                       long, code, int, cmd,
                       struct vki_au_qctrl *, qctrl);
         PRE_MEM_READ("auditsys(qctrl)", ARG3,
                      sizeof(struct vki_au_qctrl));
         break;
      case VKI_A_GETCWD:
         PRE_REG_READ4(long, SC3("auditsys", "auditctl", "getcwd"),
                       long, code, int, cmd, char *, data, int, length);
         PRE_MEM_WRITE("auditsys(data)", ARG3, ARG4);
         break;
      case VKI_A_GETCAR:
         PRE_REG_READ4(long, SC3("auditsys", "auditctl", "getcar"),
                       long, code, int, cmd, char *, data, int, length);
         PRE_MEM_WRITE("auditsys(data)", ARG3, ARG4);
         break;
      case VKI_A_GETSTAT:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getstat"),
                       long, code, int, cmd, vki_au_stat_t *, stats);
         PRE_MEM_WRITE("auditsys(stats)", ARG3, sizeof(vki_au_stat_t));
         break;
      case VKI_A_SETSTAT:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setstat"),
                       long, code, int, cmd, vki_au_stat_t *, stats);
         PRE_MEM_READ("auditsys(stats)", ARG3, sizeof(vki_au_stat_t));
         break;
      case VKI_A_SETUMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setumask"),
                       long, code, int, cmd, vki_auditinfo_t *, umask);
         PRE_MEM_READ("auditsys(umask)", ARG3, sizeof(vki_auditinfo_t));
         break;
      case VKI_A_SETSMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setsmask"),
                       long, code, int, cmd, vki_auditinfo_t *, smask);
         PRE_MEM_READ("auditsys(smask)", ARG3, sizeof(vki_auditinfo_t));
         break;
      case VKI_A_GETCOND:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getcond"),
                       long, code, int, cmd, int *, cond);
         PRE_MEM_WRITE("auditsys(cond)", ARG3, sizeof(int));
         break;
      case VKI_A_SETCOND:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setcond"),
                       long, code, int, cmd, int *, state);
         PRE_MEM_READ("auditsys(cond)", ARG3, sizeof(int));
         break;
      case VKI_A_GETCLASS:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getclass"),
                       long, code, int, cmd,
                       vki_au_evclass_map_t *, classmap);

         if (ML_(safe_to_deref((void *) ARG3,
                               sizeof(vki_au_evclass_map_t)))) {
            vki_au_evclass_map_t *classmap =
               (vki_au_evclass_map_t *) ARG3;
            PRE_FIELD_READ("auditsys(classmap.ec_number)",
                           classmap->ec_number);
            PRE_MEM_WRITE("auditsys(classmap)", ARG3,
                          sizeof(vki_au_evclass_map_t));
         }
         break;
      case VKI_A_SETCLASS:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setclass"),
                       long, code, int, cmd,
                       vki_au_evclass_map_t *, classmap);

         if (ML_(safe_to_deref((void *) ARG3, 
                               sizeof(vki_au_evclass_map_t)))) {
            vki_au_evclass_map_t *classmap =
               (vki_au_evclass_map_t *) ARG3;
            PRE_FIELD_READ("auditsys(classmap.ec_number)", 
                           classmap->ec_number);  
            PRE_FIELD_READ("auditsys(classmap.ec_class)", 
                           classmap->ec_class);
         }
         break;
      case VKI_A_GETPINFO:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getpinfo"),
                       long, code, int, cmd,
                       struct vki_auditpinfo *, apinfo);

         if (ML_(safe_to_deref((void *) ARG3,
                               sizeof(struct vki_auditpinfo)))) {
            struct vki_auditpinfo *apinfo =
               (struct vki_auditpinfo *) ARG3;
            PRE_FIELD_READ("auditsys(apinfo.ap_pid)", apinfo->ap_pid);
            PRE_MEM_WRITE("auditsys(apinfo)", ARG3,
                          sizeof(struct vki_auditpinfo));
         }
         break;
      case VKI_A_SETPMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setpmask"),
                       long, code, int, cmd,
                       struct vki_auditpinfo *, apinfo);
         PRE_MEM_WRITE("auditsys(apinfo)", ARG3,
                       sizeof(struct vki_auditpinfo));
         break;
      case VKI_A_GETPINFO_ADDR:
         PRE_REG_READ4(long, SC3("auditsys", "auditctl", "getpinfo_addr"),
                       long, code, int, cmd,
                       struct vki_auditpinfo_addr *, apinfo, int, length);

         if (ML_(safe_to_deref((void *) ARG3,
                               sizeof(struct vki_auditpinfo_addr)))) {
            struct vki_auditpinfo_addr *apinfo_addr =
               (struct vki_auditpinfo_addr *) ARG3;
            PRE_FIELD_READ("auditsys(apinfo_addr.ap_pid)",
                           apinfo_addr->ap_pid);
            PRE_MEM_WRITE("auditsys(apinfo_addr)", ARG3, ARG4);
         }
         break;
      case VKI_A_GETKAUDIT:
         PRE_REG_READ4(long, SC3("auditsys", "auditctl", "getkaudit"),
                       long, code, int, cmd,
                       vki_auditinfo_addr_t *, kaudit, int, length);
         PRE_MEM_WRITE("auditsys(kaudit)", ARG3, ARG4);
         break;
      case VKI_A_SETKAUDIT:
         PRE_REG_READ4(long, SC3("auditsys", "auditctl", "setkaudit"),
                       long, code, int, cmd,
                       vki_auditinfo_addr_t *, kaudit, int, length);
         PRE_MEM_READ("auditsys(kaudit)", ARG3, ARG4);
         break;
      case VKI_A_GETAMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "getamask"),
                       long, code, int, cmd, vki_au_mask_t *, amask);
         PRE_MEM_WRITE("auditsys(amask)", ARG3, sizeof(vki_au_mask_t));
         break;
      case VKI_A_SETAMASK:
         PRE_REG_READ3(long, SC3("auditsys", "auditctl", "setamask"),
                       long, code, int, cmd, vki_au_mask_t *, amask);
         PRE_MEM_READ("auditsys(amask)", ARG3, sizeof(vki_au_mask_t));
         break;
      default:
         VG_(unimplemented)("Syswrap of the auditsys(auditctl) call "
                            "with cmd %lu.", ARG2);
         /*NOTREACHED*/
         break;
      }
      break;
   case VKI_BSM_GETAUDIT_ADDR:
      /* Libbsm: int getaudit_addr(auditinfo_addr_t *ai, int len); */
      PRINT("sys_auditsys ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
      PRE_REG_READ3(long, SC2("auditsys", "getaudit_addr"), long, code,
                    vki_auditinfo_addr_t *, ai, int, len);
      PRE_MEM_WRITE("auditsys(ai)", ARG2, ARG3);
      break;
   case VKI_BSM_SETAUDIT_ADDR:
      /* Libbsm: int setaudit_addr(auditinfo_addr_t *ai, int len); */
      PRINT("sys_auditsys ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
      PRE_REG_READ3(long, SC2("auditsys", "setaudit_addr"), long, code,
                    vki_auditinfo_addr_t *, ai, int, len);
      PRE_MEM_READ("auditsys(ai)", ARG2, ARG3);
      break;
   case VKI_BSM_AUDITDOOR:
      /* Libbsm: int auditdoor(int fd); */
      PRINT("sys_auditsys ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("auditsys", "door"), long, code, int, fd);

      /* Be strict. */
      if (!ML_(fd_allowed)(ARG2, SC2("auditsys", "door")"(fd)",
                           tid, False))
         SET_STATUS_Failure(VKI_EBADF);
      break;
   default:
      VG_(unimplemented)("Syswrap of the auditsys call with code %lu.", ARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_auditsys)
{
   switch (ARG1 /*code*/) {
   case VKI_BSM_GETAUID:
      POST_MEM_WRITE(ARG2, sizeof(vki_au_id_t));
      break;
   case VKI_BSM_SETAUID:
      break;
   case VKI_BSM_GETAUDIT:
      POST_MEM_WRITE(ARG2, sizeof(vki_auditinfo_t));
      break;
   case VKI_BSM_SETAUDIT:
   case VKI_BSM_AUDIT:
      break;
   case VKI_BSM_AUDITCTL:
      switch (ARG2 /*cmd*/) {
         case VKI_A_GETPOLICY:
            POST_MEM_WRITE(ARG3, sizeof(vki_uint32_t));
            break;
         case VKI_A_SETPOLICY:
            break;
         case VKI_A_GETKMASK:
            POST_MEM_WRITE(ARG3, sizeof(vki_au_mask_t));
            break;
         case VKI_A_SETKMASK:
            break;
         case VKI_A_GETQCTRL:
            POST_MEM_WRITE(ARG3, sizeof(struct vki_au_qctrl));
            break;
         case VKI_A_SETQCTRL:
            break;
         case VKI_A_GETCWD:
         case VKI_A_GETCAR:
            POST_MEM_WRITE(ARG3, VG_(strlen)((HChar *) ARG3) + 1);
            break;
         case VKI_A_GETSTAT:
            POST_MEM_WRITE(ARG3, sizeof(vki_au_stat_t));
            break;
         case VKI_A_SETSTAT:
         case VKI_A_SETUMASK:
         case VKI_A_SETSMASK:
            break;
         case VKI_A_GETCOND:
            POST_MEM_WRITE(ARG3, sizeof(int));
            break;
         case VKI_A_SETCOND:
            break;
         case VKI_A_GETCLASS:
            POST_MEM_WRITE(ARG3, sizeof(vki_au_evclass_map_t));
            break;
         case VKI_A_SETCLASS:
            break;
         case VKI_A_GETPINFO:
            POST_MEM_WRITE(ARG3, sizeof(struct vki_auditpinfo));
            break;
         case VKI_A_SETPMASK:
            break;
         case VKI_A_GETPINFO_ADDR:
            POST_MEM_WRITE(ARG3, sizeof(struct auditpinfo_addr));
            break;
         case VKI_A_GETKAUDIT:
            POST_MEM_WRITE(ARG3, sizeof(vki_auditinfo_addr_t));
            break;
         case VKI_A_SETKAUDIT:
            break;
         case VKI_A_GETAMASK:
            POST_MEM_WRITE(ARG3, sizeof(vki_au_mask_t));
            break;
         case VKI_A_SETAMASK:
            break;
      }
      break;
   case VKI_BSM_GETAUDIT_ADDR:
      POST_MEM_WRITE(ARG2, sizeof(vki_auditinfo_addr_t));
      break;
   case VKI_BSM_SETAUDIT_ADDR:
      break;
   case VKI_BSM_AUDITDOOR:
      break;
   }
}

PRE(sys_p_online)
{
   /* int p_online(processorid_t processorid, int flag); */
   PRINT("sys_p_online ( %ld, %ld )", SARG1, SARG2);
   PRE_REG_READ2(long, "p_online", vki_processorid_t, processorid, int, flag);
}

PRE(sys_sigqueue)
{
   /* int sigqueue(pid_t pid, int signo, void *value,
                   int si_code, timespec_t *timeout);
    */
   PRINT("sys_sigqueue ( %ld, %ld, %#lx, %ld, %#lx )",
         SARG1, SARG2, ARG3, SARG4, ARG5);
   PRE_REG_READ5(long, "sigqueue", vki_pid_t, pid, int, signo,
                 void *, value, int, si_code,
                 vki_timespec_t *, timeout);

   if (ARG5)
      PRE_MEM_READ("sigqueue(timeout)", ARG5, sizeof(vki_timespec_t));

   if (!ML_(client_signal_OK)(ARG2)) {
      SET_STATUS_Failure(VKI_EINVAL);
      return;
   }

   /* If we're sending SIGKILL, check to see if the target is one of
      our threads and handle it specially. */
   if (ARG2 == VKI_SIGKILL && ML_(do_sigkill)(ARG1, -1)) {
      SET_STATUS_Success(0);
   } else {
      SysRes res = VG_(do_syscall5)(SYSNO, ARG1, ARG2, ARG3, ARG4,
                                    ARG5);
      SET_STATUS_from_SysRes(res);
   }

   if (VG_(clo_trace_signals))
      VG_(message)(Vg_DebugMsg,
                   "sigqueue: signal %lu queued for pid %lu\n",
                   ARG2, ARG1);

   /* Check to see if this gave us a pending signal. */
   *flags |= SfPollAfter;
}

PRE(sys_clock_gettime)
{
   /* int clock_gettime(clockid_t clock_id, struct timespec *tp); */
   PRINT("sys_clock_gettime ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "clock_gettime", vki_clockid_t, clock_id,
                 struct timespec *, tp);
   PRE_MEM_WRITE("clock_gettime(tp)", ARG2, sizeof(struct vki_timespec));
}

POST(sys_clock_gettime)
{
   POST_MEM_WRITE(ARG2, sizeof(struct vki_timespec));
}

PRE(sys_clock_settime)
{
   /* int clock_settime(clockid_t clock_id, const struct timespec *tp); */
   PRINT("sys_clock_settime ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "clock_settime", vki_clockid_t, clock_id,
                 const struct timespec *, tp);
   PRE_MEM_READ("clock_settime(tp)", ARG2, sizeof(struct vki_timespec));
}

PRE(sys_clock_getres)
{
   /* int clock_getres(clockid_t clock_id, struct timespec *res); */
   PRINT("sys_clock_getres ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "clock_getres", vki_clockid_t, clock_id,
                 struct timespec *, res);

   if (ARG2)
      PRE_MEM_WRITE("clock_getres(res)", ARG2, sizeof(struct vki_timespec));
}

POST(sys_clock_getres)
{
   if (ARG2)
      POST_MEM_WRITE(ARG2, sizeof(struct vki_timespec));
}

PRE(sys_timer_create)
{
   /* int timer_create(clockid_t clock_id,
                       struct sigevent *evp, timer_t *timerid);
    */
   PRINT("sys_timer_create ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "timer_create", vki_clockid_t, clock_id,
                 struct vki_sigevent *, evp, vki_timer_t *, timerid);

   if (ARG2) {
      struct vki_sigevent *evp = (struct vki_sigevent *) ARG2;
      PRE_FIELD_READ("timer_create(evp.sigev_notify)", evp->sigev_notify);
      PRE_FIELD_READ("timer_create(evp.sigev_signo)", evp->sigev_signo);
      PRE_FIELD_READ("timer_create(evp.sigev_value.sival_int)",
         evp->sigev_value.sival_int);

      /* Be safe. */
      if (ML_(safe_to_deref(evp, sizeof(struct vki_sigevent)))) {
         if ((evp->sigev_notify == VKI_SIGEV_PORT) ||
             (evp->sigev_notify == VKI_SIGEV_THREAD))
            PRE_MEM_READ("timer_create(evp.sigev_value.sival_ptr)", 
                         (Addr) evp->sigev_value.sival_ptr,
                         sizeof(vki_port_notify_t));
      }
   }

   PRE_MEM_WRITE("timer_create(timerid)", ARG3, sizeof(vki_timer_t));
}

POST(sys_timer_create)
{
   POST_MEM_WRITE(ARG3, sizeof(vki_timer_t));
}

PRE(sys_timer_delete)
{
   /* int timer_delete(timer_t timerid); */
   PRINT("sys_timer_delete ( %ld )", SARG1);
   PRE_REG_READ1(long, "timer_delete", vki_timer_t, timerid);
}

PRE(sys_timer_settime)
{
   /* int timer_settime(timer_t timerid, int flags,
                        const struct itimerspec *value,
                        struct itimerspec *ovalue);
    */
   PRINT("sys_timer_settime ( %ld, %ld, %#lx, %#lx )",
         SARG1, SARG2, ARG3, ARG4);
   PRE_REG_READ4(long, "timer_settime", vki_timer_t, timerid,
                 int, flags, const struct vki_itimerspec *, value,
                 struct vki_itimerspec *, ovalue);
   PRE_MEM_READ("timer_settime(value)",
                ARG3, sizeof(struct vki_itimerspec));
   if (ARG4)
      PRE_MEM_WRITE("timer_settime(ovalue)",
                    ARG4, sizeof(struct vki_itimerspec));
}

POST(sys_timer_settime)
{
   if (ARG4)
      POST_MEM_WRITE(ARG4, sizeof(struct vki_itimerspec));
}

PRE(sys_timer_gettime)
{
   /* int timer_gettime(timer_t timerid, struct itimerspec *value); */
   PRINT("sys_timer_gettime ( %ld, %#lx )", SARG1, ARG2);
   PRE_REG_READ2(long, "timer_gettime", vki_timer_t, timerid,
                 struct vki_itimerspec *, value);
   PRE_MEM_WRITE("timer_gettime(value)",
                 ARG2, sizeof(struct vki_itimerspec));
}

POST(sys_timer_gettime)
{
   POST_MEM_WRITE(ARG2, sizeof(struct vki_itimerspec));
}

PRE(sys_timer_getoverrun)
{
   /* int timer_getoverrun(timer_t timerid); */
   PRINT("sys_timer_getoverrun ( %ld )", SARG1);
   PRE_REG_READ1(long, "timer_getoverrun", vki_timer_t, timerid);
}

PRE(sys_facl)
{
   /* int facl(int fildes, int cmd, int nentries, void *aclbufp); */
   PRINT("sys_facl ( %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3, ARG4);

   PRE_REG_READ4(long, "facl", int, fildes, int, cmd,
                 int, nentries, void *, aclbufp);

   switch (ARG2 /*cmd*/) {
   case VKI_SETACL:
      if (ARG4)
         PRE_MEM_READ("facl(aclbufp)", ARG4, sizeof(vki_aclent_t));
      break;
   case VKI_GETACL:
      PRE_MEM_WRITE("facl(aclbufp)", ARG4, ARG3 * sizeof(vki_aclent_t));
      break;
   case VKI_GETACLCNT:
      break;
   case VKI_ACE_SETACL:
      if (ARG4)
         PRE_MEM_READ("facl(aclbufp)", ARG4, sizeof(vki_ace_t));
      break;
   case VKI_ACE_GETACL:
      PRE_MEM_WRITE("facl(aclbufp)", ARG4, ARG3 * sizeof(vki_ace_t));
      break;
   case VKI_ACE_GETACLCNT:
      break;
   default:
      VG_(unimplemented)("Syswrap of the facl call with cmd %ld.", SARG2);
      /*NOTREACHED*/
      break;
   }

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "facl", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_facl)
{
   switch (ARG2 /*cmd*/) {
   case VKI_SETACL:
      break;
   case VKI_GETACL:
      POST_MEM_WRITE(ARG4, ARG3 * sizeof(vki_aclent_t));
      break;
   case VKI_GETACLCNT:
      break;
   case VKI_ACE_SETACL:
      break;
   case VKI_ACE_GETACL:
      POST_MEM_WRITE(ARG4, ARG3 * sizeof(vki_ace_t));
      break;
   case VKI_ACE_GETACLCNT:
      break;
   default:
      vg_assert(0);
      break;
   }
}

static Int pre_check_and_close_fds(ThreadId tid, const HChar *name,
                                   vki_door_desc_t *desc_ptr,
                                   vki_uint_t desc_num)
{
   vki_uint_t i;

   /* Verify passed file descriptors. */
   for (i = 0; i < desc_num; i++) {
      vki_door_desc_t *desc = &desc_ptr[i];
      if ((desc->d_attributes & DOOR_DESCRIPTOR) &&
          (desc->d_attributes & DOOR_RELEASE)) {
         Int fd = desc->d_data.d_desc.d_descriptor;

         /* Detect and negate attempts by the client to close Valgrind's fds.
            Also if doing -d style logging (which is to fd = 2 = stderr),
            don't allow that to be closed either. */
         if (!ML_(fd_allowed)(fd, name, tid, False) ||
             (fd == 2 && VG_(debugLog_getLevel)() > 0))
            return VKI_EBADF;
      }
   }

   /* All fds are allowed, record information about the closed ones.

      Note: Recording information about any closed fds should generally happen
      in a post wrapper but it is not possible in this case because door calls
      are "very blocking", if the information was recorded after the syscall
      finishes then it would be out-of-date during the call, i.e. while the
      syscall is blocked in the kernel.  Therefore, we record closed fds for
      this specific syscall in the PRE wrapper.  Unfortunately, this creates
      a problem when the syscall fails, for example, door_call() can fail with
      EBADF or EFAULT and then no fds are released.  If that happens the
      information about opened fds is incorrect.  This should be very rare (I
      hope) and such a condition is also reported in the post wrapper. */
   if (VG_(clo_track_fds)) {
      for (i = 0; i < desc_num; i++) {
         vki_door_desc_t *desc = &desc_ptr[i];
         if ((desc->d_attributes & DOOR_DESCRIPTOR) &&
             (desc->d_attributes & DOOR_RELEASE)) {
            Int fd = desc->d_data.d_desc.d_descriptor;
            ML_(record_fd_close)(fd);
         }
      }
   }

   return 0;
}

static void post_record_fds(ThreadId tid, const HChar *name,
                            vki_door_desc_t *desc_ptr, vki_uint_t desc_num)
{
   vki_uint_t i;

   /* Record returned file descriptors. */
   for (i = 0; i < desc_num; i++) {
      vki_door_desc_t *desc = &desc_ptr[i];
      if (desc->d_attributes & DOOR_DESCRIPTOR) {
         Int fd = desc->d_data.d_desc.d_descriptor;
         if (!ML_(fd_allowed)(fd, name, tid, True)) {
            /* Unfortunately, we cannot recover at this point and have to fail
               hard. */
            VG_(message)(Vg_UserMsg, "The %s syscall returned an unallowed"
                                     "file descriptor %d.\n", name, fd);
            VG_(exit)(101);
         }
         else if (VG_(clo_track_fds))
            ML_(record_fd_open_named)(tid, fd);
      }
   }
}

/* Handles repository door protocol request over client door fd. */
static void repository_door_pre_mem_door_call_hook(ThreadId tid, Int fd,
                                                   void *data_ptr,
                                                   SizeT data_size)
{
   vki_rep_protocol_request_t *p = (vki_rep_protocol_request_t *) data_ptr;
   PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                  "request->rpr_request)", p->rpr_request);

   if (ML_(safe_to_deref)(p, sizeof(vki_rep_protocol_request_t))) {
      switch (p->rpr_request) {
      case VKI_REP_PROTOCOL_CLOSE:
         break;
      case VKI_REP_PROTOCOL_ENTITY_SETUP:
         {
            struct vki_rep_protocol_entity_setup *r =
               (struct vki_rep_protocol_entity_setup *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_setup->rpr_entityid)", r->rpr_entityid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_setup->rpr_entitytype)", r->rpr_entitytype);
         }
         break;
      case VKI_REP_PROTOCOL_ENTITY_NAME:
         {
            struct vki_rep_protocol_entity_name *r =
               (struct vki_rep_protocol_entity_name *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_name->rpr_entityid)", r->rpr_entityid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_name->rpr_answertype)", r->rpr_answertype);
         }
         break;
#if (SOLARIS_REPCACHE_PROTOCOL_VERSION >= 25)
      case VKI_REP_PROTOCOL_ENTITY_GET_ROOT:
         {
            struct vki_rep_protocol_entity_root *r =
               (struct vki_rep_protocol_entity_root *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_root->rpr_entityid)", r->rpr_entityid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_root->rpr_outid)", r->rpr_outid);
         }
         break;
#endif /* SOLARIS_REPCACHE_PROTOCOL_VERSION >= 25 */
      case VKI_REP_PROTOCOL_ENTITY_GET:
         {
            struct vki_rep_protocol_entity_get *r =
               (struct vki_rep_protocol_entity_get *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_get->rpr_entityid)", r->rpr_entityid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_get->rpr_object)", r->rpr_object);
         }
         break;
      case VKI_REP_PROTOCOL_ENTITY_GET_CHILD:
         {
            struct vki_rep_protocol_entity_get_child *r =
               (struct vki_rep_protocol_entity_get_child *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_get_child->rpr_entityid)", r->rpr_entityid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_get_child->rpr_childid)", r->rpr_childid);
            PRE_MEM_RASCIIZ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                            "entity_get_child->rpr_name)", (Addr) r->rpr_name);
         }
         break;
      case VKI_REP_PROTOCOL_ENTITY_GET_PARENT:
         {
            struct vki_rep_protocol_entity_parent *r =
               (struct vki_rep_protocol_entity_parent *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_get_parent->rpr_entityid)", r->rpr_entityid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_get_parent->rpr_outid)", r->rpr_outid);
         }
         break;
      case VKI_REP_PROTOCOL_ENTITY_RESET:
         {
            struct vki_rep_protocol_entity_reset *r =
               (struct vki_rep_protocol_entity_reset *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_reset->rpr_entityid)", r->rpr_entityid);
         }
         break;
      case VKI_REP_PROTOCOL_ENTITY_TEARDOWN:
         {
            struct vki_rep_protocol_entity_teardown *r =
               (struct vki_rep_protocol_entity_teardown *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "entity_teardown->rpr_entityid)", r->rpr_entityid);
         }
         break;
      case VKI_REP_PROTOCOL_ITER_READ:
         {
            struct vki_rep_protocol_iter_read *r =
               (struct vki_rep_protocol_iter_read *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_read->rpr_iterid)", r->rpr_iterid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_read->rpr_sequence)", r->rpr_sequence);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_read->rpr_entityid)", r->rpr_entityid);
         }
         break;
      case VKI_REP_PROTOCOL_ITER_READ_VALUE:
         {
            struct vki_rep_protocol_iter_read_value *r =
               (struct vki_rep_protocol_iter_read_value *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_read_value->rpr_iterid)", r->rpr_iterid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_read_value->rpr_sequence)", r->rpr_sequence);
         }
         break;
      case VKI_REP_PROTOCOL_ITER_RESET:
      case VKI_REP_PROTOCOL_ITER_SETUP:
      case VKI_REP_PROTOCOL_ITER_TEARDOWN:
         {
            struct vki_rep_protocol_iter_request *r =
               (struct vki_rep_protocol_iter_request *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_request->rpr_iterid)", r->rpr_iterid);
         }
         break;
      case VKI_REP_PROTOCOL_ITER_START:
         {
            struct vki_rep_protocol_iter_start *r =
               (struct vki_rep_protocol_iter_start *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_start->rpr_iterid)", r->rpr_iterid);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_start->rpr_entity)", r->rpr_entity);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_start->rpr_itertype)", r->rpr_itertype);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "iter_start->rpr_flags)", r->rpr_flags);
            PRE_MEM_RASCIIZ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                            "iter_start->rpr_pattern)", (Addr) r->rpr_pattern);
         }
         break;
      case VKI_REP_PROTOCOL_PROPERTY_GET_TYPE:
      case VKI_REP_PROTOCOL_PROPERTY_GET_VALUE:
         {
            struct vki_rep_protocol_property_request *r =
               (struct vki_rep_protocol_property_request *) p;
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "property_request->rpr_entityid)", r->rpr_entityid);
         }
         break;
      default:
         VG_(unimplemented)("Door wrapper of " VKI_REPOSITORY_DOOR_NAME
                            " where rpr_request=%u.", p->rpr_request);
         /* NOTREACHED */
         break;
      }        
   }
}

/* Handles repository door protocol response over client door fd. */
static void repository_door_post_mem_door_call_hook(ThreadId tid, Int fd,
                                                    void *rbuf, SizeT rsize)
{
   /* :TODO: Ideally we would need to match the response type with the
      previous request because response itself does not contain any
      type identification.
      For now simply make defined whole response buffer. */
   POST_MEM_WRITE((Addr) rbuf, rsize);
}

/* Pre-syscall checks for params->data_ptr contents of a door_call(). */
static void door_call_pre_mem_params_data(ThreadId tid, Int fd,
                                          void *data_ptr, SizeT data_size)
{
   const HChar *pathname;

   /* Get pathname of the door file descriptor, if not already done.
      Needed to dissect door service on the pathname below. */
   if (!VG_(clo_track_fds) && !ML_(fd_recorded)(fd)) {
      ML_(record_fd_open_named)(tid, fd);
   }
   pathname = ML_(find_fd_recorded_by_fd)(fd);

   /* Debug-only printing. */
   if (0) {
      VG_(printf)("PRE(door_call) with fd=%d and filename=%s\n",
                  fd, pathname);
   }

   if (VG_STREQ(pathname, VKI__PATH_KCFD_DOOR)) {
      vki_kcf_door_arg_t *p = (vki_kcf_door_arg_t *) data_ptr;

      PRE_FIELD_READ("door_call(\"" VKI__PATH_KCFD_DOOR "\", "
                     "kcf_door_arg_t->da_version)", p->da_version);
      PRE_FIELD_READ("door_call(\"" VKI__PATH_KCFD_DOOR "\", "
                     "kcf_door_arg_t->da_iskernel)", p->da_iskernel);
      PRE_MEM_RASCIIZ("door_call(\"" VKI__PATH_KCFD_DOOR "\", "
                      "kcf_door_arg_t->da_u.filename)",
                      (Addr) p->vki_da_u.filename);
   } else if (VG_STREQ(pathname, VKI_NAME_SERVICE_DOOR)) {
      vki_nss_pheader_t *p = (vki_nss_pheader_t *) data_ptr;

      PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                     "nss_pheader->nsc_callnumber)", p->nsc_callnumber);
      if (ML_(safe_to_deref)(p, sizeof(vki_nss_pheader_t))) {
         if ((p->nsc_callnumber & VKI_NSCDV2CATMASK) == VKI_NSCD_CALLCAT_APP) {
            /* request from an application towards nscd */
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->p_version)", p->p_version);
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->dbd_off)", p->dbd_off);
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->dbd_len)", p->dbd_len);
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->key_off)", p->key_off);
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->key_len)", p->key_len);
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->data_off)", p->data_off);
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->data_len)", p->data_len);
            /* Fields ext_off and ext_len are set only sporadically. */
            PRE_FIELD_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->pbufsiz)", p->pbufsiz);
            PRE_MEM_WRITE("door_call(\"" VKI_NAME_SERVICE_DOOR "\", pbuf)",
                          (Addr) p, p->pbufsiz);

            if (p->dbd_len > 0) {
               vki_nss_dbd_t *dbd
                  = (vki_nss_dbd_t *) ((HChar *) p + p->dbd_off);

               PRE_MEM_READ("door_call(\"" VKI_NAME_SERVICE_DOOR
                            "\", nss_dbd)", (Addr) dbd, sizeof(vki_nss_dbd_t));
               if (ML_(safe_to_deref)(dbd, sizeof(vki_nss_dbd_t))) {
                  if (dbd->o_name != 0)
                     PRE_MEM_RASCIIZ("door_call(\"" VKI_NAME_SERVICE_DOOR
                                     "\", nss_dbd->o_name)", (Addr) ((HChar *) p
                                     + p->dbd_off + dbd->o_name));
                  if (dbd->o_config_name != 0)
                     PRE_MEM_RASCIIZ("door_call(\"" VKI_NAME_SERVICE_DOOR
                                     "\", nss_dbd->o_config_name)",
                                     (Addr) ((HChar *) p + p->dbd_off
                                     + dbd->o_config_name));
                  if (dbd->o_default_config != 0)
                     PRE_MEM_RASCIIZ("door_call(\"" VKI_NAME_SERVICE_DOOR
                                     "\", nss_dbd->o_default_config)",
                                     (Addr) ((HChar *) p + p->dbd_off +
                                     dbd->o_default_config));
              }
           }

           PRE_MEM_READ("door_call(\"" VKI_NAME_SERVICE_DOOR "\", nss->key)",
                        (Addr) ((HChar *) p + p->key_off), p->key_len);
         } else {
            /* request from a child nscd towards parent nscd */
            VG_(unimplemented)("Door wrapper of child/parent nscd.");
         }
      }
   } else if (VG_STREQ(pathname, VKI_REPOSITORY_DOOR_NAME)) {
      vki_repository_door_request_t *p =	
         (vki_repository_door_request_t *) data_ptr;

      PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                     "request->rdr_version)", p->rdr_version);
      PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                     "request->rdr_request)", p->rdr_request);
      if (ML_(safe_to_deref)(p, sizeof(vki_repository_door_request_t))) {
         if (p->rdr_version == VKI_REPOSITORY_DOOR_VERSION) {
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "request->rdr_flags)", p->rdr_flags);
            PRE_FIELD_READ("door_call(\"" VKI_REPOSITORY_DOOR_NAME "\", "
                           "request->rdr_debug)", p->rdr_debug);
         } else {
            VG_(unimplemented)("Door wrapper of " VKI_REPOSITORY_DOOR_NAME
                               " where version=%u.", p->rdr_version);
         }
      }
   } else {
      const OpenDoor *open_door = door_find_by_fd(fd);
      if ((open_door != NULL) && (open_door->pre_mem_hook != NULL)) {
         open_door->pre_mem_hook(tid, fd, data_ptr, data_size);
      } else {
         if (SimHintiS(SimHint_lax_doors, VG_(clo_sim_hints))) {
            /*
             * Be very lax about door syscall handling over unrecognized
             * door file descriptors. Does not require that full buffer
             * is initialized when writing. Without this, programs using
             * libdoor(3LIB) functionality with completely proprietary
             * semantics may report large number of false positives.
             */
         } else {
            static Int moans = 3;

            /* generic default */
            if (moans > 0 && !VG_(clo_xml)) {
               moans--;
               VG_(umsg)(
"Warning: noted and generically handled door call\n"
"   on file descriptor %d (filename: %s).\n"
"   This could cause spurious value errors to appear.\n"
"   See README_MISSING_SYSCALL_OR_IOCTL for guidance on writing a proper wrapper.\n"
"   Alternatively you may find '--sim-hints=lax-doors' option useful.\n",
                         fd, pathname);
            }
            PRE_MEM_READ("door_call(params->data_ptr)",
                         (Addr) data_ptr, data_size);
         }
      }
   }
}

/* Post-syscall checks for params->rbuf contents of a door_call(). */
static void door_call_post_mem_params_rbuf(ThreadId tid, Int fd,
                                           void *rbuf, SizeT rsize,
                                           const vki_door_desc_t *desc_ptr,
                                           vki_uint_t desc_num)
{
   const HChar *pathname = ML_(find_fd_recorded_by_fd)(fd);

   /* Debug-only printing. */
   if (0) {
      VG_(printf)("POST(door_call) with fd=%d and filename=%s\n",
                  fd, pathname);
   }

   if (VG_STREQ(pathname, VKI__PATH_KCFD_DOOR)) {
      vki_kcf_door_arg_t *p = (vki_kcf_door_arg_t *) rbuf;

      POST_FIELD_WRITE(p->da_version);
      POST_FIELD_WRITE(p->vki_da_u.result.status);
      POST_MEM_WRITE((Addr) p->vki_da_u.result.signature,
                     p->vki_da_u.result.siglen);
   } else if (VG_STREQ(pathname, VKI_NAME_SERVICE_DOOR)) {
      vki_nss_pheader_t *p = (vki_nss_pheader_t *) rbuf;

      POST_FIELD_WRITE(p->nsc_callnumber);
      if (ML_(safe_to_deref)(p, sizeof(vki_nss_pheader_t))) {
         if ((p->nsc_callnumber & VKI_NSCDV2CATMASK) == VKI_NSCD_CALLCAT_APP) {
            /* response from nscd to an application */
            POST_FIELD_WRITE(p->p_status);
            POST_FIELD_WRITE(p->p_errno);
            POST_FIELD_WRITE(p->p_herrno);
            POST_FIELD_WRITE(p->dbd_off);
            POST_FIELD_WRITE(p->dbd_len);
            POST_FIELD_WRITE(p->key_off);
            POST_FIELD_WRITE(p->key_len);
            POST_FIELD_WRITE(p->data_off);
            POST_FIELD_WRITE(p->data_len);
            POST_FIELD_WRITE(p->ext_off);
            POST_FIELD_WRITE(p->ext_len);
            POST_FIELD_WRITE(p->pbufsiz);

            if (p->pbufsiz <= rsize) {
               if (p->dbd_off < p->pbufsiz - sizeof(vki_nss_pheader_t)) {
                  SizeT len = MIN(p->dbd_len, p->pbufsiz - p->dbd_off);
                  POST_MEM_WRITE((Addr) ((HChar *) p + p->dbd_off), len);
               }

               if (p->key_off < p->pbufsiz - sizeof(vki_nss_pheader_t)) {
                  SizeT len = MIN(p->key_len, p->pbufsiz - p->key_off);
                  POST_MEM_WRITE((Addr) ((HChar *) p + p->key_off), len);
               }

               if (p->data_off < p->pbufsiz - sizeof(vki_nss_pheader_t)) {
                  SizeT len = MIN(p->data_len, p->pbufsiz - p->data_off);
                  POST_MEM_WRITE((Addr) ((HChar *) p + p->data_off), len);
               }

               if (p->ext_off < p->pbufsiz - sizeof(vki_nss_pheader_t)) {
                  SizeT len = MIN(p->ext_len, p->pbufsiz - p->ext_off);
                  POST_MEM_WRITE((Addr) ((HChar *) p + p->ext_off), len);
               }
            }
         } else {
            /* response from parent nscd to a child nscd */
            VG_(unimplemented)("Door wrapper of child/parent nscd.");
         }
      }
   } else if (VG_STREQ(pathname, VKI_REPOSITORY_DOOR_NAME)) {
      POST_FIELD_WRITE(((vki_repository_door_response_t *) rbuf)->rdr_status);
      /* A new client door fd is passed over the global repository door. */
      if ((desc_ptr != NULL) && (desc_num > 0)) {
         if (desc_ptr[0].d_attributes & DOOR_DESCRIPTOR) {
            door_record_client(tid, desc_ptr[0].d_data.d_desc.d_descriptor,
                               repository_door_pre_mem_door_call_hook,
                               repository_door_post_mem_door_call_hook);
         }
      }
   } else {
      const OpenDoor *open_door = door_find_by_fd(fd);
      if ((open_door != NULL) && (open_door->post_mem_hook != NULL)) {
         open_door->post_mem_hook(tid, fd, rbuf, rsize);
      } else {
         /* generic default */
         POST_MEM_WRITE((Addr) rbuf, rsize);
      }
   }
}

/* Pre-syscall checks for data_ptr contents in a door_return(). */
static void door_return_pre_mem_data(ThreadId tid, Addr server_procedure,
                                     void *data_ptr, SizeT data_size)
{
   if ((data_size == 0) || (server_procedure == 0)) {
      /* There is nothing to check. This usually happens during thread's
         first call to door_return(). */
      return;
   }

   /* Get pathname of the door file descriptor based on the
      door server procedure (that's all we have).
      Needed to dissect door service on the pathname below. */
   const OpenDoor *open_door = door_find_by_proc(server_procedure);
   const HChar *pathname = (open_door != NULL) ? open_door->pathname : NULL;
   Int fd = (open_door != NULL) ? open_door->fd : -1;

   /* Debug-only printing. */
   if (0) {
      VG_(printf)("PRE(door_return) with fd=%d and filename=%s "
                  "(nr_doors_recorded=%u)\n",
                  fd, pathname, nr_doors_recorded);
   }

   if (VG_STREQ(pathname, VKI__PATH_KCFD_DOOR)) {
      vki_kcf_door_arg_t *p = (vki_kcf_door_arg_t *) data_ptr;

      PRE_FIELD_READ("door_return(\"" VKI__PATH_KCFD_DOOR "\", "
                     "kcf_door_arg_t->da_version)", p->da_version);
      PRE_FIELD_READ("door_return(\"" VKI__PATH_KCFD_DOOR "\", "
                     "kcf_door_arg_t->da_u.result.status)",
                     p->vki_da_u.result.status);
      PRE_MEM_READ("door_return(\"" VKI__PATH_KCFD_DOOR "\", "
                   "kcf_door_arg_t->da_u.result.signature)",
                   (Addr) p->vki_da_u.result.signature,
                   p->vki_da_u.result.siglen);
   } else if (VG_STREQ(pathname, VKI_NAME_SERVICE_DOOR)) {
      vki_nss_pheader_t *p = (vki_nss_pheader_t *) data_ptr;

      PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                     "nss_pheader->nsc_callnumber)", p->nsc_callnumber);
      if (ML_(safe_to_deref)(p, sizeof(vki_nss_pheader_t))) {
         if ((p->nsc_callnumber & VKI_NSCDV2CATMASK) == VKI_NSCD_CALLCAT_APP) {
            /* response from nscd to an application */
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->p_status)", p->p_status);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->p_errno)", p->p_errno);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->p_herrno)", p->p_herrno);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->dbd_off)", p->dbd_off);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->dbd_len)", p->dbd_len);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->data_off)", p->data_off);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->data_len)", p->data_len);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->ext_off)", p->ext_off);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->ext_len)", p->ext_len);
            PRE_FIELD_READ("door_return(\"" VKI_NAME_SERVICE_DOOR "\", "
                           "nss_pheader->pbufsiz)", p->pbufsiz);
            PRE_MEM_WRITE("door_return(\"" VKI_NAME_SERVICE_DOOR "\", pbuf)",
                          (Addr) p, p->pbufsiz);
            PRE_MEM_READ("door_return(\"" VKI_NAME_SERVICE_DOOR
                         "\", nss->data)",
                         (Addr) ((HChar *) p + p->data_off), p->data_len);
            PRE_MEM_READ("door_return(\"" VKI_NAME_SERVICE_DOOR
                         "\", nss->ext)",
                         (Addr) ((HChar *) p + p->ext_off), p->ext_len);
         } else {
            /* response from parent nscd to a child nscd */
            VG_(unimplemented)("Door wrapper of child/parent nscd.");
         }
      }
   } else if (VG_STREQ(pathname, VKI_REPOSITORY_DOOR_NAME)) {
            VG_(unimplemented)("Door wrapper of " VKI_REPOSITORY_DOOR_NAME);
   } else {
      if (SimHintiS(SimHint_lax_doors, VG_(clo_sim_hints))) {
         /*
          * Be very lax about door syscall handling over unrecognized
          * door file descriptors. Does not require that full buffer
          * is initialized when writing. Without this, programs using
          * libdoor(3LIB) functionality with completely proprietary
          * semantics may report large number of false positives.
          */
      } else {
         static Int moans = 3;

         /* generic default */
         if (moans > 0 && !VG_(clo_xml)) {
            moans--;
            VG_(umsg)(
"Warning: noted and generically handled door return\n"
"   on file descriptor %d (filename: %s).\n"
"   This could cause spurious value errors to appear.\n"
"   See README_MISSING_SYSCALL_OR_IOCTL for guidance on writing a proper wrapper.\n"
"   Alternatively you may find '--sim-hints=lax-doors' option useful.\n",
                   fd, pathname);
         }
         PRE_MEM_READ("door_return(data_ptr)",
                      (Addr) data_ptr, data_size);
      }
   }
}

/* Post-syscall checks for data_ptr contents in a door_return(). */
static void door_return_post_mem_data(ThreadId tid, Addr server_procedure,
                                      void *data_ptr, SizeT data_size)
{
   const OpenDoor *open_door = door_find_by_proc(server_procedure);
   const HChar *pathname = (open_door != NULL) ? open_door->pathname : NULL;

   /* Debug-only printing. */
   if (0) {
      Int fd = (open_door != NULL) ? open_door->fd : -1;
      VG_(printf)("POST(door_return) with fd=%d and filename=%s "
                  "(nr_doors_recorded=%u)\n",
                  fd, pathname, nr_doors_recorded);
   }

   if (VG_STREQ(pathname, VKI__PATH_KCFD_DOOR)) {
      vki_kcf_door_arg_t *p = (vki_kcf_door_arg_t *) data_ptr;

      POST_FIELD_WRITE(p->da_version);
      POST_FIELD_WRITE(p->da_iskernel);
      POST_MEM_WRITE((Addr) p->vki_da_u.filename,
                     VG_(strlen)(p->vki_da_u.filename) + 1);
   } else if (VG_STREQ(pathname, VKI_NAME_SERVICE_DOOR)) {
      vki_nss_pheader_t *p = (vki_nss_pheader_t *) data_ptr;

      POST_FIELD_WRITE(p->nsc_callnumber);
      if (ML_(safe_to_deref)(p, sizeof(vki_nss_pheader_t))) {
         if ((p->nsc_callnumber & VKI_NSCDV2CATMASK) == VKI_NSCD_CALLCAT_APP) {
            /* request from an application towards nscd */
            POST_FIELD_WRITE(p->p_version);
            POST_FIELD_WRITE(p->dbd_off);
            POST_FIELD_WRITE(p->dbd_len);
            POST_FIELD_WRITE(p->key_off);
            POST_FIELD_WRITE(p->key_len);
            POST_FIELD_WRITE(p->data_off);
            POST_FIELD_WRITE(p->data_len);
            POST_FIELD_WRITE(p->ext_off);
            POST_FIELD_WRITE(p->ext_len);
            POST_FIELD_WRITE(p->pbufsiz);

            if (p->dbd_len > 0) {
               vki_nss_dbd_t *dbd
                  = (vki_nss_dbd_t *) ((HChar *) p + p->dbd_off);

               POST_MEM_WRITE((Addr) dbd, sizeof(vki_nss_dbd_t));
               if (ML_(safe_to_deref)(dbd, sizeof(vki_nss_dbd_t))) {
                  SizeT headers_size = sizeof(vki_nss_pheader_t)
                     + sizeof(vki_nss_dbd_t);

                  if (dbd->o_name != 0) {
                     HChar *name = (HChar *) p + p->dbd_off + dbd->o_name;
                     SizeT name_len = VG_(strlen)(name) + 1;
                     if (name_len <= data_size - headers_size)
                        POST_MEM_WRITE((Addr) name, name_len);
                  }
                  if (dbd->o_config_name != 0) {
                     HChar *name = (HChar *) p + p->dbd_off + dbd->o_config_name;
                     SizeT name_len = VG_(strlen)(name) + 1;
                     if (name_len <= data_size - headers_size)
                        POST_MEM_WRITE((Addr) name, name_len);
                  }
                  if (dbd->o_default_config != 0) {
                     HChar *name = (HChar *) p + p->dbd_off
                        + dbd->o_default_config;
                     SizeT name_len = VG_(strlen)(name) + 1;
                     if (name_len <= data_size - headers_size)
                        POST_MEM_WRITE((Addr) name, name_len);
                  }
              }
           }

           if (p->key_len <= data_size - p->key_off)
              POST_MEM_WRITE((Addr) ((HChar *) p + p->key_off), p->key_len);
         } else {
            /* request from a child nscd towards parent nscd */
            VG_(unimplemented)("Door wrapper of child/parent nscd.");
         }
      }
   } else if (VG_STREQ(pathname, VKI_REPOSITORY_DOOR_NAME)) {
            VG_(unimplemented)("Door wrapper of " VKI_REPOSITORY_DOOR_NAME);
   } else {
      /* generic default */
      POST_MEM_WRITE((Addr) data_ptr, data_size);
   }
}

PRE(sys_door)
{
   /* int doorfs(long arg1, long arg2, long arg3, long arg4, long arg5,
                 long subcode); */
   ThreadState *tst = VG_(get_ThreadState)(tid);
   *flags |= SfMayBlock | SfPostOnFail;

   PRINT("sys_door ( %#lx, %#lx, %#lx, %#lx, %#lx, %ld )", ARG1, ARG2, ARG3,
         ARG4, ARG5, SARG6);

   /* Macro PRE_REG_READ6 cannot be simply used because not all ARGs are used
      in door() syscall variants. Note that ARG6 (subcode) is used always. */
#define PRE_REG_READ_SIXTH_ONLY         \
   if (VG_(tdict).track_pre_reg_read) { \
      PRA6("door", long, subcode);      \
   }

   switch (ARG6 /*subcode*/) {
   case VKI_DOOR_CREATE:
      PRE_REG_READ3(long, "door", long, arg1, long, arg2, long, arg3);
      PRE_REG_READ_SIXTH_ONLY;
      /* Note: the first argument to DOOR_CREATE is a server procedure.
         This could lead to a problem if the kernel tries to force the
         execution of this procedure, similarly to how signal handlers are
         executed.   Fortunately, the kernel never does that (for user-space
         server procedures).  The procedure is always executed by the standard
         library. */
      break;
   case VKI_DOOR_REVOKE:
      PRE_REG_READ1(long, "door", long, arg1);
      PRE_REG_READ_SIXTH_ONLY;
      if (!ML_(fd_allowed)(ARG1, "door_revoke", tid, False))
         SET_STATUS_Failure(VKI_EBADF);
      break;
   case VKI_DOOR_INFO:
      PRE_REG_READ2(long, "door", long, arg1, long, arg2);
      PRE_REG_READ_SIXTH_ONLY;
      PRE_MEM_WRITE("door_info(info)", ARG2, sizeof(vki_door_info_t));
      break;
   case VKI_DOOR_CALL:
      {
         PRE_REG_READ2(long, "door", long, arg1, long, arg2);
         PRE_REG_READ_SIXTH_ONLY;

         Int rval = 0;
         vki_door_arg_t *params = (vki_door_arg_t*)ARG2;

         if (!ML_(fd_allowed)(ARG1, "door_call", tid, False))
            rval = VKI_EBADF;

         PRE_FIELD_READ("door_call(params->data_ptr)", params->data_ptr);
         PRE_FIELD_READ("door_call(params->data_size)", params->data_size);
         PRE_FIELD_READ("door_call(params->desc_ptr)", params->desc_ptr);
         PRE_FIELD_READ("door_call(params->desc_num)", params->desc_num);
         PRE_FIELD_READ("door_call(params->rbuf)", params->rbuf);
         PRE_FIELD_READ("door_call(params->rsize)", params->rsize);

         if (ML_(safe_to_deref)(params, sizeof(*params))) {
            if (params->data_ptr)
               door_call_pre_mem_params_data(tid, ARG1, params->data_ptr,
                                             params->data_size);

            if (params->desc_ptr) {
               SizeT desc_size = params->desc_num * sizeof(*params->desc_ptr);
               PRE_MEM_READ("door_call(params->desc_ptr)",
                            (Addr)params->desc_ptr, desc_size);

               /* Do not record information about closed fds if we are going
                  to fail the syscall and so no fds will be closed. */
               if ((rval == 0) &&
                   (ML_(safe_to_deref)(params->desc_ptr, desc_size))) {
                     rval = pre_check_and_close_fds(tid, "door_call",
                                                    params->desc_ptr,
                                                    params->desc_num);
               }
            }

            if (params->rbuf)
               PRE_MEM_WRITE("door_call(params->rbuf)", (Addr)params->rbuf,
                             params->rsize);
         }

         if (rval)
            SET_STATUS_Failure(rval);
      }
      break;
   case VKI_DOOR_BIND:
      PRE_REG_READ1(long, "door", long, arg1);
      PRE_REG_READ_SIXTH_ONLY;
      VG_(unimplemented)("DOOR_BIND");
      break;
   case VKI_DOOR_UNBIND:
      PRE_REG_READ0(long, "door");
      PRE_REG_READ_SIXTH_ONLY;
      VG_(unimplemented)("DOOR_UNBIND");
      break;
   case VKI_DOOR_UNREFSYS:
      PRE_REG_READ0(long, "door");
      PRE_REG_READ_SIXTH_ONLY;
      VG_(unimplemented)("DOOR_UNREFSYS");
      break;
   case VKI_DOOR_UCRED:
      PRE_REG_READ1(long, "door", long, arg1);
      PRE_REG_READ_SIXTH_ONLY;
      VG_(unimplemented)("DOOR_UCRED");
      break;
   case VKI_DOOR_RETURN:
      PRE_REG_READ6(long, "door", long, arg1, long, arg2, long, arg3,
                    long, arg4, long, arg5, long, subcode);

      /* Register %esp/%rsp is read and modified by the syscall. */
      VG_TRACK(pre_reg_read, Vg_CoreSysCall, tid, "door_return(sp)",
               VG_O_STACK_PTR, sizeof(UWord));
      /* Register %ebp/%rbp is not really read by the syscall, it is only
         written by it, but it is hard to determine when it is written so we
         make sure it is always valid prior to making the syscall. */
      VG_TRACK(pre_reg_read, Vg_CoreSysCall, tid, "door_return(bp)",
               VG_O_FRAME_PTR, sizeof(UWord));

      door_return_pre_mem_data(tid, tst->os_state.door_return_procedure,
                               (void *) ARG1, ARG2);

      /* Do not tell the tool where the syscall is going to write the
         resulting data.  It is necessary to skip this check because the data
         area starting at ARG4-ARG5 (of length ARG5) is usually on a client
         thread stack below the stack pointer and therefore it can be marked
         by a tool (for example, Memcheck) as inaccessible.  It is ok to skip
         this check in this case because if there is something wrong with the
         data area then the syscall will fail or the error will be handled by
         POST_MEM_WRITE() in the post wrapper. */
      /*PRE_MEM_WRITE("door_return(sp)", ARG4 - ARG5, ARG5);*/

      if (ARG3) {
         vki_door_return_desc_t *desc_env = (vki_door_return_desc_t*)ARG3;

         PRE_MEM_READ("door_return(desc_env)", ARG3,
                      sizeof(vki_door_return_desc_t));

         if (ML_(safe_to_deref)(desc_env, sizeof(*desc_env)) &&
             desc_env->desc_ptr) {
            Int rval;

            PRE_MEM_READ("door_return(desc_env->desc_ptr)",
                         (Addr)desc_env->desc_ptr,
                         desc_env->desc_num * sizeof(*desc_env->desc_ptr));

            rval = pre_check_and_close_fds(tid, "door_return",
                                           desc_env->desc_ptr,
                                           desc_env->desc_num);
            if (rval)
               SET_STATUS_Failure(rval);
         }
      }
      tst->os_state.in_door_return = True;
      tst->os_state.door_return_procedure = 0;
      break;
   case VKI_DOOR_GETPARAM:
      PRE_REG_READ3(long, "door", long, arg1, long, arg2, long, arg3);
      PRE_REG_READ_SIXTH_ONLY;
      VG_(unimplemented)("DOOR_GETPARAM");
      break;
   case VKI_DOOR_SETPARAM:
      PRE_REG_READ3(long, "door", long, arg1, long, arg2, long, arg3);
      PRE_REG_READ_SIXTH_ONLY;
      VG_(unimplemented)("DOOR_SETPARAM");
      break;
   default:
      VG_(unimplemented)("Syswrap of the door call with subcode %ld.", SARG6);
      /*NOTREACHED*/
      break;
   }

#undef PRE_REG_READ_SIXTH_ONLY
}

POST(sys_door)
{
   ThreadState *tst = VG_(get_ThreadState)(tid);

   vg_assert(SUCCESS || FAILURE);

   /* Alter the tst->os_state.in_door_return flag. */
   if (ARG6 == VKI_DOOR_RETURN) {
      vg_assert(tst->os_state.in_door_return == True);
      tst->os_state.in_door_return = False;

      /* Inform the tool that %esp/%rsp and %ebp/%rbp were (potentially)
         modified. */
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, VG_O_STACK_PTR,
               sizeof(UWord));
      VG_TRACK(post_reg_write, Vg_CoreSysCall, tid, VG_O_FRAME_PTR,
               sizeof(UWord));
   }
   else
      vg_assert(tst->os_state.in_door_return == False);

   if (FAILURE) {
      if (VG_(clo_track_fds)) {
         /* See the discussion in pre_check_and_close_fds() to understand this
            part. */
         Bool loss = False;
         switch (ARG6 /*subcode*/) {
         case VKI_DOOR_CALL:
            if (ERR == VKI_EFAULT || ERR == VKI_EBADF)
               loss = True;
            break;
         case VKI_DOOR_RETURN:
            if (ERR == VKI_EFAULT || ERR == VKI_EINVAL)
               loss = True;
            break;
         default:
            break;
         }
         if (loss)
            VG_(message)(Vg_UserMsg, "The door call failed with an "
                                     "unexpected error and information "
                                     "about open file descriptors can be "
                                     "now imprecise.\n");
      }

      return;
   }

   vg_assert(SUCCESS);

   switch (ARG6 /*subcode*/) {
   case VKI_DOOR_CREATE:
      door_record_server(tid, ARG1, RES);
      break;
   case VKI_DOOR_REVOKE:
      door_revoke(tid, ARG1);
      if (VG_(clo_track_fds))
         ML_(record_fd_close)(ARG1);
      break;
   case VKI_DOOR_INFO:
      POST_MEM_WRITE(ARG2, sizeof(vki_door_info_t));
      break;
   case VKI_DOOR_CALL:
      {
         /* Note that all returned values are stored in the rbuf, i.e.
            data_ptr and desc_ptr points into this buffer. */
         vki_door_arg_t *params = (vki_door_arg_t*)ARG2;

         if (params->rbuf) {
            Addr addr = (Addr)params->rbuf;
            if (!VG_(am_find_anon_segment(addr))) {
               /* This segment is new and was mapped by the kernel. */
               UInt prot, flags;
               SizeT size;

               prot = VKI_PROT_READ | VKI_PROT_WRITE | VKI_PROT_EXEC;
               flags = VKI_MAP_ANONYMOUS;
               size = VG_PGROUNDUP(params->rsize);

               VG_(debugLog)(1, "syswrap-solaris", "POST(sys_door), "
                                "new segment: vaddr=%#lx, size=%#lx, "
                                "prot=%#x, flags=%#x, fd=%ld, offset=%#llx\n",
                                addr, size, prot, flags, (UWord)-1, (ULong)0);

               ML_(notify_core_and_tool_of_mmap)(addr, size, prot, flags,
                                                 -1, 0);

               /* Note: We don't notify the debuginfo reader about this
                  mapping because there are no debug information stored in
                  this segment. */
            }

            door_call_post_mem_params_rbuf(tid, ARG1, (void *) addr,
                                           params->rsize, params->desc_ptr,
                                           params->desc_num);
         }

         if (params->desc_ptr) {
            POST_MEM_WRITE((Addr)params->desc_ptr,
                           params->desc_num * sizeof(vki_door_desc_t));
            post_record_fds(tid, "door_call", params->desc_ptr,
                            params->desc_num);
         }
      }
      break;
   case VKI_DOOR_BIND:
      break;
   case VKI_DOOR_UNBIND:
      break;
   case VKI_DOOR_UNREFSYS:
      break;
   case VKI_DOOR_UCRED:
      break;
   case VKI_DOOR_RETURN:
      {
         struct vki_door_results *results
            = (struct vki_door_results*)VG_(get_SP)(tid);

         tst->os_state.door_return_procedure = (Addr)results->pc;

         POST_MEM_WRITE((Addr)results, sizeof(*results));
         if (results->data_ptr)
            door_return_post_mem_data(tid,
                                      tst->os_state.door_return_procedure,
                                      results->data_ptr,
                                      results->data_size);
         if (results->desc_ptr) {
            POST_MEM_WRITE((Addr)results->desc_ptr,
                           results->desc_num * sizeof(vki_door_desc_t));
            post_record_fds(tid, "door_return", results->desc_ptr,
                            results->desc_num);
         }

         POST_MEM_WRITE((Addr)results->door_info,
                        sizeof(*results->door_info));
      }
      break;
   case VKI_DOOR_GETPARAM:
      break;
   case VKI_DOOR_SETPARAM:
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_schedctl)
{
   /* caddr_t schedctl(void); */
   /* This syscall returns an address that points to struct sc_shared.
      This per-thread structure is used as an interface between the libc and
      the kernel. */
   PRINT("sys_schedctl ( )");
   PRE_REG_READ0(long, "schedctl");
}

POST(sys_schedctl)
{
   Addr a = RES;
   ThreadState *tst = VG_(get_ThreadState)(tid);

   /* Stay sane. */
   vg_assert((tst->os_state.schedctl_data == 0) ||
             (tst->os_state.schedctl_data == a));
   tst->os_state.schedctl_data = a;

   /* Returned address points to a block in a mapped page. */
   if (!VG_(am_find_anon_segment(a))) {
      Addr page = VG_PGROUNDDN(a);
      UInt prot = VKI_PROT_READ | VKI_PROT_WRITE | VKI_PROT_EXEC;
      UInt flags = VKI_MAP_ANONYMOUS;
      /* The kernel always allocates one page for the sc_shared struct. */
      SizeT size = VKI_PAGE_SIZE;

      VG_(debugLog)(1, "syswrap-solaris", "POST(sys_schedctl), new segment: "
                    "vaddr=%#lx, size=%#lx, prot=%#x, flags=%#x, fd=-1, "
                    "offset=0\n", page, size, prot, flags);

      /* The kernel always places redzone before and after the allocated page.
         Check this assertion now; the tool can later request to allocate
         a Valgrind segment and aspacemgr will place it adjacent. */
      const NSegment *seg = VG_(am_find_nsegment(page - 1));
      vg_assert(seg == NULL || seg->kind == SkResvn);
      seg = VG_(am_find_nsegment(page + VKI_PAGE_SIZE));
      vg_assert(seg == NULL || seg->kind == SkResvn);

      /* The address space manager works with whole pages. */
      VG_(am_notify_client_mmap)(page, size, prot, flags, -1, 0);

      /* Note: It isn't needed to notify debuginfo about the new mapping
         because it's only an anonymous mapping. */
      /* Note: schedctl data are cleaned in two places:
         - for the tool when the thread exits
         - for the core in child's post-fork handler clean_schedctl_data(). */
   }

   /* The tool needs per-thread granularity, not whole pages. */
   VG_TRACK(new_mem_mmap, a, sizeof(struct vki_sc_shared), True, True, True, 0);
   POST_MEM_WRITE(a, sizeof(struct vki_sc_shared));
}

PRE(sys_pset)
{
   /* Kernel: int pset(int subcode, long arg1, long arg2, long arg3,
                       long arg4); */
   switch (ARG1 /* subcode */) {
   case VKI_PSET_CREATE:
      /* Libc: int pset_create(psetid_t *newpset); */
      PRINT("sys_pset ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("pset", "create"), int, subcode,
                    vki_psetid_t *, newpset);
      PRE_MEM_WRITE("pset(newpset)", ARG2, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_DESTROY:
      /* Libc: int pset_destroy(psetid_t pset); */
      PRINT("sys_pset ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("pset", "destroy"), int, subcode,
                    vki_psetid_t, pset);
      break;
   case VKI_PSET_ASSIGN:
      /* Libc: int pset_assign(psetid_t pset, processorid_t cpu,
                               psetid_t *opset); */
      PRINT("sys_pset ( %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3, ARG4);
      PRE_REG_READ4(long, SC2("pset", "assign"), int, subcode,
                    vki_psetid_t, pset, vki_processorid_t, cpu,
                    vki_psetid_t *, opset);
      if (ARG4 != 0)
         PRE_MEM_WRITE("pset(opset)", ARG4, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_INFO:
      /* Libc: int pset_info(psetid_t pset, int *type, uint_t *numcpus,
                             processorid_t *cpulist); */
      PRINT("sys_pset ( %ld, %ld, %#lx, %#lx, %#lx )", SARG1, SARG2, ARG3,
                                                       ARG4, ARG5);
      PRE_REG_READ5(long, SC2("pset", "info"), int, subcode, vki_psetid_t, pset,
                    int *, type, vki_uint_t *, numcpus,
                    vki_processorid_t *, cpulist);
      if (ARG3 != 0)
         PRE_MEM_WRITE("pset(type)", ARG3, sizeof(int));
      if (ARG4 != 0)
         PRE_MEM_WRITE("pset(numcpus)", ARG4, sizeof(vki_uint_t));
      if ((ARG4 != 0) && (ARG5 != 0)) {
         vki_uint_t *numcpus = (vki_uint_t *) ARG4;
         if (ML_(safe_to_deref(numcpus, sizeof(vki_uint_t)))) {
            PRE_MEM_WRITE("pset(cpulist)", ARG5,
                          *numcpus * sizeof(vki_processorid_t));
            /* If cpulist buffer is not large enough, it will hold only as many
               entries as fit in the buffer. However numcpus will contain the
               real number of cpus which will be greater than originally passed
               in. Stash the original value in unused ARG6. */
            ARG6 = *numcpus;
         }
      }
      break;
   case VKI_PSET_BIND:
      /* Libc: int pset_bind(psetid_t pset, idtype_t idtype, id_t id,
                             psetid_t *opset); */
      PRINT("sys_pset ( %ld, %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3,
                                                     SARG4, ARG5);
      PRE_REG_READ5(long, SC2("pset", "bind"), int, subcode, vki_psetid_t, pset,
                    vki_idtype_t, idtype, vki_id_t, id, vki_psetid_t *, opset);
      if (ARG5 != 0)
         PRE_MEM_WRITE("pset(opset)", ARG5, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_BIND_LWP:
      /* Libc: int pset_bind_lwp(psetid_t pset, id_t id, pid_t pid,
                                 psetid_t *opset); */
      PRINT("sys_pset ( %ld, %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3,
                                                     SARG4, ARG5);
      PRE_REG_READ5(long, SC2("pset", "bind_lwp"), int, subcode,
                    vki_psetid_t, pset, vki_id_t, id, vki_pid_t, pid,
                    vki_psetid_t *, opset);
      if (ARG5 != 0)
         PRE_MEM_WRITE("pset(opset)", ARG5, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_GETLOADAVG:
      /* Libc: int pset_getloadavg(psetid_t pset, double loadavg[],
                                   int nelem); */
      PRINT("sys_pset ( %ld, %ld, %#lx, %ld )", SARG1, SARG2, ARG3, SARG4);
      PRE_REG_READ4(long, SC2("pset", "getloadavg"), int, subcode,
                    vki_psetid_t, pset, double, loadavg[], int, nelem);
      if (ARG3 != 0)
         PRE_MEM_WRITE("pset(loadavg)", ARG3, SARG4 * sizeof(double));
      break;
   case VKI_PSET_LIST:
      /* Libc: int pset_list(psetid_t *psetlist, uint_t *numpsets); */
      PRINT("sys_pset ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
      PRE_REG_READ3(long, SC2("pset", "list"), int, subcode,
                    vki_psetid_t *, psetlist, vki_uint_t *, numpsets);
      if (ARG3 != 0)
         PRE_MEM_WRITE("pset(numpsets)", ARG3, sizeof(vki_uint_t));
      if ((ARG2 != 0) && (ARG3 != 0)) {
         vki_uint_t *numpsets = (vki_uint_t *) ARG3;
         if (ML_(safe_to_deref(numpsets, sizeof(vki_uint_t)))) {
            PRE_MEM_WRITE("pset(psetlist)", ARG2,
                          *numpsets * sizeof(vki_psetid_t));
            /* If psetlist buffer is not large enough, it will hold only as many
               entries as fit in the buffer. However numpsets will contain the
               real number of processor sets which will be greater than
               originally passed in. Stash the original value in unused ARG6. */
            ARG6 = *numpsets;
         }
      }
      break;
#  if defined(SOLARIS_PSET_GET_NAME)
   case VKI_PSET_GET_NAME:
      /* Libc: int pset_get_name(psetid_t psetid, char *buf, uint_t len); */
      PRINT("sys_pset ( %ld, %ld, %#lx, %ld )", SARG1, SARG2, ARG3, SARG4);
      PRE_REG_READ4(long, SC2("pset", "get_name"), int, subcode,
                    vki_psetid_t, pset, char *, buf, vki_uint_t, len);
      PRE_MEM_WRITE("pset(buf)", ARG3, ARG4);
      break;
#  endif /* SOLARIS_PSET_GET_NAME */
   case VKI_PSET_SETATTR:
      /* Libc: int pset_setattr(psetid_t pset, uint_t attr); */
      PRINT("sys_pset ( %ld, %ld, %ld )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("pset", "setattr"), int, subcode,
                    vki_psetid_t, pset, vki_uint_t, attr);
      break;
   case VKI_PSET_GETATTR:
      /* Libc: int pset_getattr(psetid_t pset, uint_t *attr); */
      PRINT("sys_pset ( %ld, %ld, %#lx )", SARG1, SARG2, ARG3);
      PRE_REG_READ3(long, SC2("pset", "getattr"), int, subcode,
                    vki_psetid_t, pset, vki_uint_t *, attr);
      PRE_MEM_WRITE("pset(attr)", ARG3, sizeof(vki_uint_t));
      break;
   case VKI_PSET_ASSIGN_FORCED:
      /* Libc: int pset_assign_forced(psetid_t pset, processorid_t cpu,
                                      psetid_t *opset); */
      PRINT("sys_pset ( %ld, %ld, %ld, %#lx )", SARG1, SARG2, SARG3, ARG4);
      PRE_REG_READ4(long, SC2("pset", "assign_forced"), int, subcode,
                    vki_psetid_t, pset, vki_processorid_t, cpu,
                    vki_psetid_t *, opset);
      if (ARG4 != 0)
         PRE_MEM_WRITE("pset(opset)", ARG4, sizeof(vki_psetid_t));
      break;
   default:
      VG_(unimplemented)("Syswrap of pset syscall with subcode %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_pset)
{
   switch (ARG1 /*subcode*/) {
   case VKI_PSET_CREATE:
      POST_MEM_WRITE(ARG2, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_DESTROY:
      break;
   case VKI_PSET_ASSIGN:
      if (ARG4 != 0)
         POST_MEM_WRITE(ARG4, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_INFO:
      if (ARG3 != 0)
         POST_MEM_WRITE(ARG3, sizeof(int));
      if (ARG4 != 0)
         POST_MEM_WRITE(ARG4, sizeof(vki_uint_t));
      if ((ARG4 != 0) && (ARG5 != 0)) {
         vki_uint_t *numcpus = (vki_uint_t *) ARG4;
         POST_MEM_WRITE(ARG5, MIN(*numcpus, ARG6) * sizeof(vki_processorid_t));
      }
      break;
   case VKI_PSET_BIND:
      if (ARG5 != 0)
         POST_MEM_WRITE(ARG5, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_BIND_LWP:
      if (ARG5 != 0)
         POST_MEM_WRITE(ARG5, sizeof(vki_psetid_t));
      break;
   case VKI_PSET_GETLOADAVG:
      if (ARG3 != 0)
         POST_MEM_WRITE(ARG3, MIN(SARG4, VKI_LOADAVG_NSTATS) * sizeof(double));
      break;
   case VKI_PSET_LIST:
      if (ARG3 != 0)
         POST_MEM_WRITE(ARG3, sizeof(vki_uint_t));
      if ((ARG2 != 0) && (ARG3 != 0)) {
         vki_uint_t *numpsets = (vki_uint_t *) ARG3;
         POST_MEM_WRITE(ARG2, MIN(*numpsets, ARG6) * sizeof(vki_psetid_t));
      }
      break;
#  if defined(SOLARIS_PSET_GET_NAME)
   case VKI_PSET_GET_NAME:
      POST_MEM_WRITE(ARG3, VG_(strlen)((HChar *) ARG3) + 1);
      break;
#  endif /* SOLARIS_PSET_GET_NAME */
   case VKI_PSET_SETATTR:
      break;
   case VKI_PSET_GETATTR:
      POST_MEM_WRITE(ARG3, sizeof(vki_uint_t));
      break;
   case VKI_PSET_ASSIGN_FORCED:
      if (ARG4 != 0)
         POST_MEM_WRITE(ARG4, sizeof(vki_psetid_t));
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_resolvepath)
{
   /* int resolvepath(const char *path, char *buf, size_t bufsiz); */
   PRINT("sys_resolvepath ( %#lx(%s), %#lx, %lu )", ARG1, (HChar *) ARG1, ARG2,
         ARG3);
   PRE_REG_READ3(long, "resolvepath", const char *, path, char *, buf,
                 vki_size_t, bufsiz);

   PRE_MEM_RASCIIZ("resolvepath(path)", ARG1);
   PRE_MEM_WRITE("resolvepath(buf)", ARG2, ARG3);
}

POST(sys_resolvepath)
{
   POST_MEM_WRITE(ARG2, RES);
}

PRE(sys_lwp_mutex_timedlock)
{
   /* int lwp_mutex_timedlock(lwp_mutex_t *lp, timespec_t *tsp,
                              uintptr_t owner); */
   vki_lwp_mutex_t *lp = (vki_lwp_mutex_t *)ARG1;
   *flags |= SfMayBlock;
   PRINT("lwp_mutex_timedlock ( %#lx, %#lx, %#lx )", ARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "lwp_mutex_timedlock", lwp_mutex_t *, lp,
                 timespec_t *, tsp, uintptr_t, owner);

   PRE_FIELD_READ("lwp_mutex_timedlock(lp->mutex_flag)", lp->vki_mutex_flag);
   PRE_FIELD_READ("lwp_mutex_timedlock(lp->mutex_type)", lp->vki_mutex_type);
   PRE_FIELD_WRITE("lwp_mutex_timedlock(lp->mutex_owner)",
                   lp->vki_mutex_owner);
   PRE_FIELD_WRITE("lwp_mutex_timedlock(lp->mutex_ownerpid)",
                   lp->vki_mutex_ownerpid);
   PRE_FIELD_READ("lwp_mutex_timedlock(lp->mutex_lockw)", lp->vki_mutex_lockw);
   /*PRE_FIELD_WRITE("lwp_mutex_timedlock(lp->mutex_lockw)",
                     lp->vki_mutex_lockw);*/
   PRE_FIELD_READ("lwp_mutex_timedlock(lp->mutex_waiters)",
                  lp->vki_mutex_waiters);
   /*PRE_FIELD_WRITE("lwp_mutex_timedlock(lp->mutex_waiters)",
                     lp->vki_mutex_waiters);*/
   if (ARG2) {
      PRE_MEM_READ("lwp_mutex_timedlock(tsp)", ARG2, sizeof(vki_timespec_t));
      /*PRE_MEM_WRITE("lwp_mutex_timedlock(tsp)", ARG2,
                      sizeof(vki_timespec_t));*/
   }
}

POST(sys_lwp_mutex_timedlock)
{
   vki_lwp_mutex_t *lp = (vki_lwp_mutex_t *)ARG1;
   POST_FIELD_WRITE(lp->vki_mutex_owner);
   POST_FIELD_WRITE(lp->vki_mutex_ownerpid);
   POST_FIELD_WRITE(lp->vki_mutex_lockw);
   POST_FIELD_WRITE(lp->vki_mutex_waiters);
   if (ARG2)
      POST_MEM_WRITE(ARG2, sizeof(vki_timespec_t));
}

PRE(sys_lwp_rwlock_sys)
{
   /* int lwp_rwlock_sys(int subcode, lwp_rwlock_t *rwlp, timespec_t *tsp); */
   vki_lwp_rwlock_t *rwlp = (vki_lwp_rwlock_t *)ARG2;
   switch (ARG1 /*subcode*/) {
   case 0:
   case 1:
   case 2:
   case 3:
      *flags |= SfMayBlock;
      switch (ARG1 /*subcode*/) {
      case 0:
         PRINT("sys_lwp_rwlock ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
         PRE_REG_READ3(long, SC2("lwp_rwlock", "rdlock"), int, subcode,
                       lwp_rwlock_t *, rwlp, timespec_t *, tsp);
         break;
      case 1:
         PRINT("sys_lwp_rwlock ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
         PRE_REG_READ3(long, SC2("lwp_rwlock", "wrlock"), int, subcode,
                       lwp_rwlock_t *, rwlp, timespec_t *, tsp);
         break;
      case 2:
         PRINT("sys_lwp_rwlock ( %ld, %#lx )", SARG1, ARG2);
         PRE_REG_READ2(long, SC2("lwp_rwlock", "tryrdlock"), int, subcode,
                       lwp_rwlock_t *, rwlp);
         break;
      case 3:
         PRINT("sys_lwp_rwlock ( %ld, %#lx )", SARG1, ARG2);
         PRE_REG_READ2(long, SC2("lwp_rwlock", "trywrlock"), int, subcode,
                       lwp_rwlock_t *, rwlp);
         break;
      default:
         vg_assert(0);
         break;
      }

      PRE_FIELD_READ("lwp_rwlock(rwlp->rwlock_type)", rwlp->vki_rwlock_type);
      PRE_FIELD_READ("lwp_rwlock(rwlp->rwlock_readers)",
                     rwlp->vki_rwlock_readers);
      /*PRE_FIELD_WRITE("lwp_rwlock(rwlp->rwlock_readers)",
                        rwlp->vki_rwlock_readers);*/

      PRE_FIELD_READ("lwp_rwlock(rwlp->mutex.mutex_type)",
                     rwlp->mutex.vki_mutex_type);
      PRE_FIELD_WRITE("lwp_rwlock(rwlp->mutex.mutex_owner)",
                      rwlp->mutex.vki_mutex_owner);
      PRE_FIELD_WRITE("lwp_rwlock(rwlp->mutex.mutex_ownerpid)",
                      rwlp->mutex.vki_mutex_ownerpid);
      /* The mutex_lockw member is not really read by the kernel for this
         syscall but it seems better to mark it that way because when locking
         an rwlock the associated mutex has to be locked. */
      PRE_FIELD_READ("lwp_rwlock(rwlp->mutex.mutex_lockw)",
                     rwlp->mutex.vki_mutex_lockw);
      /*PRE_FIELD_WRITE("lwp_rwlock(rwlp->mutex.mutex_lockw)",
                        rwlp->mutex.vki_mutex_lockw);*/
      PRE_FIELD_READ("lwp_rwlock(rwlp->mutex.mutex_waiters)",
                     rwlp->mutex.vki_mutex_waiters);
      /*PRE_FIELD_WRITE("lwp_rwlock(rwlp->mutex.mutex_waiters)",
                        rwlp->mutex.vki_mutex_waiters);*/

      if ((ARG1 == 0 || ARG1 == 1) && ARG3)
         PRE_MEM_READ("lwp_rwlock(tsp)", ARG3, sizeof(vki_timespec_t));
      break;
   case 4:
      PRINT("sys_lwp_rwlock( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("lwp_rwlock", "unlock"), int, subcode,
                    lwp_rwlock_t *, rwlp);
      PRE_FIELD_READ("lwp_rwlock(rwlp->mutex.mutex_type)",
                     rwlp->mutex.vki_mutex_type);
      PRE_FIELD_READ("lwp_rwlock(rwlp->rwlock_readers)",
                     rwlp->vki_rwlock_readers);
      /*PRE_FIELD_WRITE("lwp_rwlock(rwlp->rwlock_readers)",
                        rwlp->vki_rwlock_readers);*/
      break;
   default:
      VG_(unimplemented)("Syswrap of the lwp_rwlock_sys call with subcode %ld.",
                         SARG1);
      /*NOTREACHED*/
      break;
   }
}

POST(sys_lwp_rwlock_sys)
{
   vki_lwp_rwlock_t *rwlp = (vki_lwp_rwlock_t *)ARG2;
   switch (ARG1 /*subcode*/) {
   case 0:
   case 1:
   case 2:
   case 3:
      POST_FIELD_WRITE(rwlp->vki_rwlock_readers);
      POST_FIELD_WRITE(rwlp->vki_rwlock_owner);
      POST_FIELD_WRITE(rwlp->vki_rwlock_ownerpid);
      POST_FIELD_WRITE(rwlp->mutex.vki_mutex_lockw);
      POST_FIELD_WRITE(rwlp->mutex.vki_mutex_waiters);
      break;
   case 4:
      POST_FIELD_WRITE(rwlp->vki_rwlock_readers);
      break;
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_lwp_sema_timedwait)
{
   /* int lwp_sema_timedwait(lwp_sema_t *sema, timespec_t *timeout,
                             int check_park); */
   vki_lwp_sema_t *sema = (vki_lwp_sema_t*)ARG1;
   *flags |= SfMayBlock;
   PRINT("sys_lwp_sema_timewait ( %#lx, %#lx, %ld )", ARG1, ARG2, SARG3);
   PRE_REG_READ3(long, "lwp_sema_timedwait", lwp_sema_t *, sema,
                 timespec_t *, timeout, int, check_park);

   PRE_FIELD_READ("lwp_sema_timedwait(sema->type)", sema->vki_sema_type);
   PRE_FIELD_READ("lwp_sema_timedwait(sema->count)", sema->vki_sema_count);
   /*PRE_FIELD_WRITE("lwp_sema_timedwait(sema->count)",
                     sema->vki_sema_count);*/
   PRE_FIELD_READ("lwp_sema_timedwait(sema->waiters)", sema->vki_sema_waiters);
   /*PRE_FIELD_WRITE("lwp_sema_timedwait(sema->waiters)",
                     sema->vki_sema_waiters);*/
   if (ARG2) {
      PRE_MEM_READ("lwp_sema_timedwait(timeout)", ARG2,
                   sizeof(vki_timespec_t));
      /*PRE_MEM_WRITE("lwp_sema_timedwait(timeout)", ARG2,
                      sizeof(vki_timespec_t));*/
   }
}

POST(sys_lwp_sema_timedwait)
{
   vki_lwp_sema_t *sema = (vki_lwp_sema_t*)ARG1;
   POST_FIELD_WRITE(sema->vki_sema_count);
   POST_FIELD_WRITE(sema->vki_sema_waiters);
   if (ARG2)
      POST_MEM_WRITE(ARG2, sizeof(vki_timespec_t));
}

PRE(sys_zone)
{
   /* Kernel: long zone(int cmd, void *arg1, void *arg2, void *arg3,
                        void *arg4);
    */
   switch (ARG1 /*cmd*/) {
   case VKI_ZONE_CREATE:
      /* Libc: zoneid_t zone_create(const char *name, const char *root,
                                    const struct priv_set *privs,
                                    const char *rctls, size_t rctlsz,
                                    const char *zfs, size_t zfssz,
                                    int *extended_error, int match,
                                    int doi, const bslabel_t *label,
                                    int flags);
        Kernel: zoneid_t zone_create(zone_def *zd);
       */
      PRINT("sys_zone ( %ld, %#lx )", SARG1, ARG2);
      PRE_REG_READ2(long, SC2("zone", "create"), int, cmd,
                    vki_zone_def *, zd);

      vki_zone_def *zd = (vki_zone_def *) ARG2;
      PRE_FIELD_READ("zone(zd.zone_name)", zd->zone_name);
      PRE_FIELD_READ("zone(zd.zone_root)", zd->zone_root);
      PRE_FIELD_READ("zone(zd.zone_privs)", zd->zone_privs);
      PRE_FIELD_READ("zone(zd.zone_privssz)", zd->zone_privssz);
      PRE_FIELD_READ("zone(zd.rctlbuf)", zd->rctlbuf);
      PRE_FIELD_READ("zone(zd.rctlbufsz)", zd->rctlbufsz);
      PRE_FIELD_READ("zone(zd.zfsbuf)", zd->zfsbuf);
      PRE_FIELD_READ("zone(zd.zfsbufsz)", zd->zfsbufsz);
      PRE_FIELD_READ("zone(zd.extended_error)", zd->extended_error);
      PRE_FIELD_READ("zone(zd.match)", zd->match);
      PRE_FIELD_READ("zone(zd.doi)", zd->doi);
      PRE_FIELD_READ("zone(zd.label)", zd->label);
      PRE_FIELD_READ("zone(zd.flags)", zd->flags);

      if (ML_(safe_to_deref((void *)ARG2, sizeof(vki_zone_def)))) {
         if (zd->zone_name)
            PRE_MEM_RASCIIZ("zone(zd.zone_name)", (Addr) zd->zone_name);
         if (zd->zone_root)
            PRE_MEM_RASCIIZ("zone(zd.zone_root)", (Addr) zd->zone_root);
         PRE_MEM_READ("zone(zd.zone_privs)", (Addr) zd->zone_privs,
                      zd->zone_privssz);
         PRE_MEM_READ("zone(zd.rctlbuf)", (Addr) zd->rctlbuf,
                      zd->rctlbufsz);
         PRE_MEM_READ("zone(zd.zfsbuf)",
                      (Addr) zd->zfsbuf, zd->zfsbufsz);
         if (zd->label)
            PRE_MEM_READ("zone(zd.label)", (Addr) zd->label,
                         sizeof(vki_bslabel_t));
      }
      break;
   case VKI_ZONE_DESTROY:
      /* Libc: int zone_destroy(zoneid_t zoneid); */
      PRINT("sys_zone ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("zone", "destroy"), int, cmd,
                    vki_zoneid_t, zoneid);
      break;
   case VKI_ZONE_GETATTR:
      /* Libc: ssize_t zone_getattr(zoneid_t zoneid, int attr,
                                    void *valp, size_t size);
       */
      PRINT("sys_zone ( %ld, %ld, %ld, %#lx, %ld )",
            SARG1, SARG2, SARG3, ARG4, SARG5);
      PRE_REG_READ5(long, SC2("zone", "getattr"), int, cmd,
                    vki_zoneid_t, zoneid, int, attr, void *, valp,
                    vki_size_t, size);
      PRE_MEM_WRITE("zone(valp)", ARG4, ARG5);
      break;
   case VKI_ZONE_ENTER:
      /* Libc: int zone_enter(zoneid_t zoneid); */
      PRINT("sys_zone ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("zone", "enter"), int, cmd,
                    vki_zoneid_t, zoneid);
      break;
   case VKI_ZONE_LIST:
      /* Libc: int zone_list(zoneid_t *zonelist, uint_t *numzones); */
      PRINT("sys_zone ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
      PRE_REG_READ3(long, SC2("zone", "list"), int, cmd,
                    vki_zoneid_t *, zonelist, vki_uint_t *, numzones);

      PRE_MEM_WRITE("zone(numzones)", ARG3, sizeof(vki_uint_t));

      if (ML_(safe_to_deref((void *) ARG3, sizeof(vki_uint_t)))) {
         if (ARG2)
            PRE_MEM_WRITE("zone(zonelist)", ARG2,
                          *(vki_uint_t *) ARG3 * sizeof(vki_zoneid_t));
      }
      break;
   case VKI_ZONE_SHUTDOWN:
      /* Libc: int zone_shutdown(zoneid_t zoneid); */
      PRINT("sys_zone ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("zone", "shutdown"), int, cmd,
                    vki_zoneid_t, zoneid);
      break;
   case VKI_ZONE_LOOKUP:
      /* Libc: zoneid_t zone_lookup(const char *name); */
      PRINT("sys_zone ( %ld, %#lx(%s) )", SARG1, ARG2, (HChar *) ARG2);
      PRE_REG_READ2(long, SC2("zone", "lookup"), int, cmd,
                    const char *, name);
      if (ARG2)
         PRE_MEM_RASCIIZ("zone(name)", ARG2);
      break;
   case VKI_ZONE_BOOT:
      /* Libc: int zone_boot(zoneid_t zoneid); */
      PRINT("sys_zone ( %ld, %ld )", SARG1, SARG2);
      PRE_REG_READ2(long, SC2("zone", "boot"), int, cmd,
                    vki_zoneid_t, zoneid);
      break;
   case VKI_ZONE_SETATTR:
      /* Libc: int zone_setattr(zoneid_t zoneid, int attr, void *valp,
                                size_t size);
       */
      PRINT("sys_zone ( %ld, %ld, %ld, %#lx, %lu )",
            SARG1, SARG2, SARG3, ARG4, ARG5);
      PRE_REG_READ5(long, SC2("zone", "setattr"), int, cmd,
                    vki_zoneid_t, zoneid, int, attr, void *, valp,
                    vki_size_t, size);
      PRE_MEM_READ("zone(valp)", ARG4, ARG5);
      break;
   case VKI_ZONE_ADD_DATALINK:
      /* Libc: int zone_add_datalink(zoneid_t zoneid,
                                     datalink_id_t linkid);
       */
      PRINT("sys_zone ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
      PRE_REG_READ3(long, SC2("zone", "add_datalink"), int, cmd,
                    vki_zoneid_t, zoneid, vki_datalink_id_t, linkid);
      break;
   case VKI_ZONE_DEL_DATALINK:
      /* Libc: int zone_remove_datalink(zoneid_t zoneid,
                                        datalink_id_t linkid);
       */
      PRINT("sys_zone ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
      PRE_REG_READ3(long, SC2("zone", "del_datalink"), int, cmd,
                    vki_zoneid_t, zoneid, vki_datalink_id_t, linkid);
      break;
   case VKI_ZONE_CHECK_DATALINK:
      /* Libc: int zone_check_datalink(zoneid_t *zoneidp,
                                       datalink_id_t linkid);
      */
      PRINT("sys_zone ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
      PRE_REG_READ3(long, SC2("zone", "check_datalink"), int, cmd,
                    vki_zoneid_t *, zoneidp, vki_datalink_id_t, linkid);
      PRE_MEM_WRITE("zone(zoneidp)", ARG2, sizeof(vki_zoneid_t));
      break;
   case VKI_ZONE_LIST_DATALINK:
      /* Libc: int zone_list_datalink(zoneid_t zoneid, int *dlnump,
                                      datalink_id_t *linkids);
       */
      PRINT("sys_zone ( %ld, %ld, %#lx, %#lx )", SARG1, SARG2, ARG3, ARG4);
      PRE_REG_READ4(long, SC2("zone", "list_datalink"), int, cmd,
                    vki_zoneid_t, zoneid, int *, dlnump,
                    vki_datalink_id_t *, linkids);

      PRE_MEM_WRITE("zone(dlnump)", ARG3, sizeof(int));
      if (ML_(safe_to_deref((void *) ARG3, sizeof(int)))) {
         if (ARG4)
            PRE_MEM_WRITE("zone(linkids)", ARG4,
                          *(int *) ARG3 * sizeof(vki_datalink_id_t));
      }
      break;
#if defined(SOLARIS_ZONE_DEFUNCT)
   case VKI_ZONE_LIST_DEFUNCT:
      /* Libc: int zone_list_defunct(uint64_t *uniqidlist,
                                     uint_t *numzones);
       */
      PRINT("sys_zone ( %ld, %#lx, %#lx )", SARG1, ARG2, ARG3);
      PRE_REG_READ3(long, SC2("zone", "list_defunct"), int, cmd,
                    vki_uint64_t *, uniqidlist, vki_uint_t *, numzones);

      PRE_MEM_WRITE("zone(numzones)", ARG3, sizeof(vki_uint_t));

      if (ML_(safe_to_deref((void *) ARG3, sizeof(vki_uint_t)))) {
         if (ARG2)
            PRE_MEM_WRITE("zone(uniqidlist)", ARG2,
                          *(vki_uint_t *) ARG3 * sizeof(vki_uint64_t));
      }
      break;
   case VKI_ZONE_GETATTR_DEFUNCT:
      /* Libc: ssize_t zone_getattr_defunct(uint64_t uniqid, int attr,
                                            void *valp, size_t size);
         Kernel: ssize_t zone_getattr_defunct(uint64_t *uniqid, int attr,
                                              void *valp, size_t size);
       */
      PRINT("sys_zone ( %ld, %#lx, %ld, %#lx, %lu )",
            SARG1, ARG2, SARG3, ARG4, ARG5);
      PRE_REG_READ5(long, SC2("zone", "getattr_defunct"), int, cmd,
                    vki_uint64_t *, uniqid, int, attr,
                    void *, valp, vki_size_t, size);

      PRE_MEM_READ("zone(uniqid)", ARG2, sizeof(vki_uint64_t));
      PRE_MEM_WRITE("zone(valp)", ARG4, ARG5);
      break;
#endif /* SOLARIS_ZONE_DEFUNCT */
   default:
      VG_(unimplemented)("Syswrap of the zone call with cmd %ld.", SARG1);
      /*NOTREACHED*/
      break;
   }

}

POST(sys_zone)
{
   switch (ARG1 /*cmd*/) {
   case VKI_ZONE_CREATE:
   case VKI_ZONE_DESTROY:
      break;
   case VKI_ZONE_GETATTR:
      POST_MEM_WRITE(ARG4, MIN(RES, ARG5));
      break;
   case VKI_ZONE_ENTER:
      break;
   case VKI_ZONE_LIST:
      POST_MEM_WRITE(ARG2, *(vki_uint_t *) ARG3 * sizeof(vki_zoneid_t));
      break;
   case VKI_ZONE_SHUTDOWN:
   case VKI_ZONE_LOOKUP:
   case VKI_ZONE_BOOT:
   case VKI_ZONE_SETATTR:
   case VKI_ZONE_ADD_DATALINK:
   case VKI_ZONE_DEL_DATALINK:
      break;
   case VKI_ZONE_CHECK_DATALINK:
      POST_MEM_WRITE(ARG2, sizeof(vki_zoneid_t));
      break;
   case VKI_ZONE_LIST_DATALINK:
      POST_MEM_WRITE(ARG4, *(int *) ARG3 * sizeof(vki_datalink_id_t));
      break;
#if defined(SOLARIS_ZONE_DEFUNCT)
   case VKI_ZONE_LIST_DEFUNCT:
      POST_MEM_WRITE(ARG2, *(vki_uint_t *) ARG3 * sizeof(vki_uint64_t));
      break;
   case VKI_ZONE_GETATTR_DEFUNCT:
      POST_MEM_WRITE(ARG4, MIN(RES, ARG5));
      break;
#endif /* SOLARIS_ZONE_DEFUNCT */
   default:
      vg_assert(0);
      break;
   }
}

PRE(sys_getcwd)
{
   /* int getcwd(char *buf, size_t size); */
   /* Note: Generic getcwd() syswrap can't be used because it expects
      a different return value. */
   PRINT("sys_getcwd ( %#lx, %lu )", ARG1, ARG2);
   PRE_REG_READ2(long, "getcwd", char *, buf, vki_size_t, size);
   PRE_MEM_WRITE("getcwd(buf)", ARG1, ARG2);
}

POST(sys_getcwd)
{
   POST_MEM_WRITE(ARG1, VG_(strlen)((HChar*)ARG1) + 1);
}

PRE(sys_so_socket)
{
   /* int so_socket(int family, int type, int protocol, char *devpath,
                    int version); */
   PRINT("sys_so_socket ( %ld, %ld, %ld, %#lx(%s), %ld)", SARG1, SARG2, SARG3,
         ARG4, (HChar *) ARG4, SARG5);
   PRE_REG_READ5(long, "socket", int, family, int, type, int, protocol,
                 char *, devpath, int, version);
   if (ARG4)
      PRE_MEM_RASCIIZ("socket(devpath)", ARG4);
}

POST(sys_so_socket)
{
   SysRes r;
   r = ML_(generic_POST_sys_socket)(tid, VG_(mk_SysRes_Success)(RES));
   SET_STATUS_from_SysRes(r);
}

PRE(sys_so_socketpair)
{
   /* int so_socketpair(int sv[2]); */
   /* This syscall is used to connect two already created sockets together. */
   PRINT("sys_so_socketpair ( %#lx )", ARG1);
   PRE_REG_READ1(long, "socketpair", int *, sv);
   PRE_MEM_READ("socketpair(sv)", ARG1, 2 * sizeof(int));
   /*PRE_MEM_WRITE("socketpair(sv)", ARG1, 2 * sizeof(int));*/
   if (ML_(safe_to_deref)((void*)ARG1, 2 * sizeof(int))) {
      int *fds = (int*)ARG1;
      if (!ML_(fd_allowed)(fds[0], "socketpair", tid, False))
         SET_STATUS_Failure(VKI_EBADF);
      else if (!ML_(fd_allowed)(fds[1], "socketpair", tid, False))
         SET_STATUS_Failure(VKI_EBADF);
   }
}

POST(sys_so_socketpair)
{
   /* The kernel can return new file descriptors, in such a case we have to
      validate them. */
   int *fds = (int*)ARG1;
   POST_MEM_WRITE(ARG1, 2 * sizeof(int));
   if (!ML_(fd_allowed)(fds[0], "socketpair", tid, True))
      SET_STATUS_Failure(VKI_EMFILE);
   if (!ML_(fd_allowed)(fds[1], "socketpair", tid, True))
      SET_STATUS_Failure(VKI_EMFILE);
   if (FAILURE) {
      /* One or both of the file descriptors weren't allowed, close newly
         created file descriptors but don't close the already recorded
         ones. */
      if (!ML_(fd_recorded)(fds[0]))
         VG_(close)(fds[0]);
      if (!ML_(fd_recorded)(fds[1]))
         VG_(close)(fds[1]);
   }
   else if (VG_(clo_track_fds)) {
      /* Everything went better than expected, record the newly created file
         descriptors.  Note: If the kernel actually returns the original file
         descriptors, then ML_(record_fd_open_nameless) notices that these
         file descriptors have been already recorded. */
      ML_(record_fd_open_nameless)(tid, fds[0]);
      ML_(record_fd_open_nameless)(tid, fds[1]);
   }
}

PRE(sys_bind)
{
   /* int bind(int s, struct sockaddr *name, socklen_t namelen,
               int version); */
   PRINT("sys_bind ( %ld, %#lx, %lu, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "bind", int, s, struct sockaddr *, name,
                 vki_socklen_t, namelen, int, version);
   ML_(generic_PRE_sys_bind)(tid, ARG1, ARG2, ARG3);
}

PRE(sys_listen)
{
   /* int listen(int s, int backlog, int version); */
   PRINT("sys_listen ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
   PRE_REG_READ3(long, "listen", int, s, int, backlog, int, version);
}

PRE(sys_accept)
{
#if defined(SOLARIS_NEW_ACCEPT_SYSCALL)
   /* int accept(int s, struct sockaddr *addr, socklen_t *addrlen,
                 int version, int flags); */
   *flags |= SfMayBlock;
   PRINT("sys_accept ( %ld, %#lx, %#lx, %ld, %ld )", SARG1, ARG2, ARG3, SARG4,
         SARG5);
   PRE_REG_READ5(long, "accept", int, s, struct sockaddr *, addr,
                 socklen_t *, addrlen, int, version, int, flags);
#else
   /* int accept(int s, struct sockaddr *addr, socklen_t *addrlen,
                 int version); */
   *flags |= SfMayBlock;
   PRINT("sys_accept ( %ld, %#lx, %#lx, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "accept", int, s, struct sockaddr *, addr,
                 socklen_t *, addrlen, int, version);
#endif /* SOLARIS_NEW_ACCEPT_SYSCALL */
   ML_(generic_PRE_sys_accept)(tid, ARG1, ARG2, ARG3);
}

POST(sys_accept)
{
   SysRes r;
   r = ML_(generic_POST_sys_accept)(tid, VG_(mk_SysRes_Success)(RES),
                                    ARG1, ARG2, ARG3);
   SET_STATUS_from_SysRes(r);
}

PRE(sys_connect)
{
   /* int connect(int s, struct sockaddr *name, socklen_t namelen,
                  int version); */
   *flags |= SfMayBlock;
   PRINT("sys_connect ( %ld, %#lx, %lu, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "connect", int, s, struct sockaddr *, name,
                 vki_socklen_t, namelen, int, version);
   ML_(generic_PRE_sys_connect)(tid, ARG1, ARG2, ARG3);
}

PRE(sys_shutdown)
{
   /* Kernel: int shutdown(int sock, int how, int version);
      Libc:   int shutdown(int sock, int how);
    */
   *flags |= SfMayBlock;
   PRINT("sys_shutdown ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
   PRE_REG_READ3(int, "shutdown", int, sock, int, how, int, version);

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "shutdown", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

PRE(sys_recv)
{
   /* ssize_t recv(int s, void *buf, size_t len, int flags); */
   *flags |= SfMayBlock;
   PRINT("sys_recv ( %ld, %#lx, %lu, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "recv", int, s, void *, buf, vki_size_t, len,
                 int, flags);
   ML_(generic_PRE_sys_recv)(tid, ARG1, ARG2, ARG3);
}

POST(sys_recv)
{
   ML_(generic_POST_sys_recv)(tid, RES, ARG1, ARG2, ARG3);
}

PRE(sys_recvfrom)
{
   /* ssize_t recvfrom(int s, void *buf, size_t len, int flags,
                       struct sockaddr *from, socklen_t *fromlen); */
   *flags |= SfMayBlock;
   PRINT("sys_recvfrom ( %ld, %#lx, %lu, %ld, %#lx, %#lx )", SARG1, ARG2, ARG3,
         SARG4, ARG5, ARG6);
   PRE_REG_READ6(long, "recvfrom", int, s, void *, buf, vki_size_t, len,
                 int, flags, struct sockaddr *, from, socklen_t *, fromlen);
   ML_(generic_PRE_sys_recvfrom)(tid, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
}

POST(sys_recvfrom)
{
   ML_(generic_POST_sys_recvfrom)(tid, VG_(mk_SysRes_Success)(RES),
                                  ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
}

PRE(sys_recvmsg)
{
   /* ssize_t recvmsg(int s, struct msghdr *msg, int flags); */
   *flags |= SfMayBlock;
   PRINT("sys_recvmsg ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
   PRE_REG_READ3(long, "recvmsg", int, s, struct msghdr *, msg, int, flags);
   ML_(generic_PRE_sys_recvmsg)(tid, "msg", (struct vki_msghdr*)ARG2);
}

POST(sys_recvmsg)
{
   ML_(generic_POST_sys_recvmsg)(tid, "msg", (struct vki_msghdr*)ARG2, RES);
}

PRE(sys_send)
{
   /* ssize_t send(int s, const void *msg, size_t len, int flags); */
   *flags |= SfMayBlock;
   PRINT("sys_send ( %ld, %#lx, %lu, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "send", int, s, const void *, msg, vki_size_t, len,
                 int, flags);
   ML_(generic_PRE_sys_send)(tid, ARG1, ARG2, ARG3);
}

PRE(sys_sendmsg)
{
   /* ssize_t sendmsg(int s, const struct msghdr *msg, int flags); */
   *flags |= SfMayBlock;
   PRINT("sys_sendmsg ( %ld, %#lx, %ld )", SARG1, ARG2, SARG3);
   PRE_REG_READ3(long, "sendmsg", int, s, const struct msghdr *, msg,
                 int, flags);
   ML_(generic_PRE_sys_sendmsg)(tid, "msg", (struct vki_msghdr*)ARG2);
}

PRE(sys_sendto)
{
   /* ssize_t sendto(int s, const void *msg, size_t len, int flags,
                     const struct sockaddr *to, int tolen); */
   *flags |= SfMayBlock;
   PRINT("sys_sendto ( %ld, %#lx, %lu, %ld, %#lx, %ld )", SARG1, ARG2, ARG3,
         SARG4, ARG5, SARG6);
   PRE_REG_READ6(long, "sendto", int, s, const void *, msg, vki_size_t, len,
                 int, flags, const struct sockaddr *, to, int, tolen);
   ML_(generic_PRE_sys_sendto)(tid, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
}

PRE(sys_getpeername)
{
   /* Kernel: int getpeername(int s, struct sockaddr *name,
                              socklen_t *namelen, int version);
      Libc:   int getpeername(int s, struct sockaddr *name,
                              socklen_t *namelen);
    */
   *flags |= SfMayBlock;
   PRINT("sys_getpeername ( %ld, %#lx, %#lx, %ld )",
         SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "getpeername", int, s, struct vki_sockaddr *, name,
                 vki_socklen_t *, namelen, int, version);
   ML_(buf_and_len_pre_check)(tid, ARG2, ARG3, "getpeername(name)",
                              "getpeername(namelen)");

   /* Be strict. */
   if (!ML_(fd_allowed)(ARG1, "getpeername", tid, False))
      SET_STATUS_Failure(VKI_EBADF);
}

POST(sys_getpeername)
{
   ML_(buf_and_len_post_check)(tid, VG_(mk_SysRes_Success)(RES),
                               ARG2, ARG3, "getpeername(namelen)");
}

PRE(sys_getsockname)
{
   /* int getsockname(int s, struct sockaddr *name, socklen_t *namelen,
                      int version); */
   PRINT("sys_getsockname ( %ld, %#lx, %#lx, %ld )", SARG1, ARG2, ARG3, SARG4);
   PRE_REG_READ4(long, "getsockname", int, s, struct sockaddr *, name,
                 socklen_t *, namelen, int, version);
   ML_(generic_PRE_sys_getsockname)(tid, ARG1, ARG2, ARG3);
}

POST(sys_getsockname)
{
   ML_(generic_POST_sys_getsockname)(tid, VG_(mk_SysRes_Success)(RES),
                                     ARG1, ARG2, ARG3);
}

PRE(sys_getsockopt)
{
   /* int getsockopt(int s, int level, int optname, void *optval,
                     socklen_t *optlen, int version); */
   PRINT("sys_getsockopt ( %ld, %ld, %ld, %#lx, %#lx, %ld )", SARG1, SARG2,
         SARG3, ARG4, ARG5, SARG6);
   PRE_REG_READ6(long, "getsockopt", int, s, int, level, int, optname,
                 void *, optval, socklen_t *, option, int, version);
   if (ARG4)
      ML_(buf_and_len_pre_check)(tid, ARG4, ARG5, "getsockopt(optval)",
                                 "getsockopt(optlen)");
}

POST(sys_getsockopt)
{
   if (ARG4)
      ML_(buf_and_len_post_check)(tid, VG_(mk_SysRes_Success)(RES), ARG4,
                                  ARG5, "getsockopt(optlen_out)");
}

PRE(sys_setsockopt)
{
   /* int setsockopt(int s, int level, int optname, const void *optval,
                     socklen_t optlen, int version); */
   PRINT("sys_setsockopt ( %ld, %ld, %ld, %#lx, %lu, %ld )", SARG1, SARG2,
         SARG3, ARG4, ARG5, SARG6);
   PRE_REG_READ6(long, "setsockopt", int, s, int, level, int, optname,
                 const void *, optval, vki_socklen_t, optlen, int, version);
   ML_(generic_PRE_sys_setsockopt)(tid, ARG1, ARG2, ARG3, ARG4, ARG5);
}

PRE(sys_lwp_mutex_register)
{
   /* int lwp_mutex_register(lwp_mutex_t *mp, caddr_t uaddr); */
   vki_lwp_mutex_t *mp = (vki_lwp_mutex_t*)ARG1;
   PRINT("sys_lwp_mutex_register ( %#lx, %#lx )", ARG1, ARG2);
   PRE_REG_READ2(long, "lwp_mutex_register", lwp_mutex_t *, mp,
                 void *, uaddr);
   PRE_FIELD_READ("lwp_mutex_register(mp->mutex_type)", mp->vki_mutex_type);
}

PRE(sys_uucopy)
{
   /* int uucopy(const void *s1, void *s2, size_t n); */
   PRINT("sys_uucopy ( %#lx, %#lx, %lu )", ARG1, ARG2, ARG3);
   PRE_REG_READ3(long, "uucopy", const void *, s1, void *, s2, vki_size_t, n);

   /* Stay away from V segments. */
   if (!ML_(valid_client_addr)(ARG1, ARG3, tid, "uucopy(s1)")) {
      SET_STATUS_Failure(VKI_EFAULT);
   }
   if (!ML_(valid_client_addr)(ARG2, ARG3, tid, "uucopy(s2)")) {
      SET_STATUS_Failure(VKI_EFAULT);
   }

   if (FAILURE)
      return;

   /* XXX This is actually incorrect, we should be able to copy undefined
      values through to their new destination. */
   PRE_MEM_READ("uucopy(s1)", ARG1, ARG3);
   PRE_MEM_WRITE("uucopy(s2)", ARG2, ARG3);
}

POST(sys_uucopy)
{
   POST_MEM_WRITE(ARG2, ARG3);
}

PRE(sys_umount2)
{
   /* int umount2(const char *file, int mflag); */
   *flags |= SfMayBlock;
   PRINT("sys_umount2 ( %#lx(%s), %ld )", ARG1, (HChar *) ARG1, SARG2);
   PRE_REG_READ2(long, "umount2", const char *, file, int, mflag);
   PRE_MEM_RASCIIZ("umount2(file)", ARG1);
}

PRE(fast_gethrtime)
{
   PRINT("fast_gethrtime ( )");
   PRE_REG_READ0(long, "gethrtime");
}

PRE(fast_gethrvtime)
{
   PRINT("fast_gethrvtime ( )");
   PRE_REG_READ0(long, "gethrvtime");
}

PRE(fast_gethrestime)
{
   /* Used by gettimeofday(3C). */
   PRINT("fast_gethrestime ( )");
   PRE_REG_READ0(long, "gethrestime");
}

#if defined(SOLARIS_GETHRT_FASTTRAP)
PRE(fast_gethrt)
{
   /* Used by gethrtime(3C) when tsp & tscp HWCAPs are present. */
   PRINT("fast_gethrt ( )");
   PRE_REG_READ0(long, "gethrt");
}

POST(fast_gethrt)
{
   if (RES == 0)
      return;

   VG_(change_mapping_ownership)(RES, False);
}
#endif /* SOLARIS_GETHRT_FASTTRAP */

#if defined(SOLARIS_GETZONEOFFSET_FASTTRAP)
PRE(fast_getzoneoffset)
{
   /* Returns kernel's time zone offset data. */
   PRINT("fast_getzoneoffset ( )");
   PRE_REG_READ0(long, "get_zone_offset");
}

POST(fast_getzoneoffset)
{
   if (RES == 0)
      return;

   VG_(change_mapping_ownership)(RES, False);
}
#endif /* SOLARIS_GETZONEOFFSET_FASTTRAP */

#undef PRE
#undef POST

/* ---------------------------------------------------------------------
   The Solaris syscall table
   ------------------------------------------------------------------ */

/* Add a Solaris-specific, arch-independent wrapper to a syscall table. */
#define SOLX_(sysno, name) \
   WRAPPER_ENTRY_X_(solaris, VG_SOLARIS_SYSNO_INDEX(sysno), name)
#define SOLXY(sysno, name) \
   WRAPPER_ENTRY_XY(solaris, VG_SOLARIS_SYSNO_INDEX(sysno), name)

#if defined(VGP_x86_solaris)
/* Add an x86-solaris specific wrapper to a syscall table. */
#define PLAX_(sysno, name) \
   WRAPPER_ENTRY_X_(x86_solaris, VG_SOLARIS_SYSNO_INDEX(sysno), name)
#define PLAXY(sysno, name) \
   WRAPPER_ENTRY_XY(x86_solaris, VG_SOLARIS_SYSNO_INDEX(sysno), name)

#elif defined(VGP_amd64_solaris)
/* Add an amd64-solaris specific wrapper to a syscall table. */
#define PLAX_(sysno, name) \
   WRAPPER_ENTRY_X_(amd64_solaris, VG_SOLARIS_SYSNO_INDEX(sysno), name)
#define PLAXY(sysno, name) \
   WRAPPER_ENTRY_XY(amd64_solaris, VG_SOLARIS_SYSNO_INDEX(sysno), name)

#else
#  error "Unknown platform"
#endif

/*
   GEN   : handlers are in syswrap-generic.c
   SOL   : handlers are in this file
      X_ : PRE handler only
      XY : PRE and POST handlers
*/

static SyscallTableEntry syscall_table[] = {
   SOLX_(__NR_exit,                 sys_exit),                  /*   1 */
#if defined(SOLARIS_SPAWN_SYSCALL)
   SOLX_(__NR_spawn,                sys_spawn),                 /*   2 */
#endif /* SOLARIS_SPAWN_SYSCALL */
   GENXY(__NR_read,                 sys_read),                  /*   3 */
   GENX_(__NR_write,                sys_write),                 /*   4 */
#if defined(SOLARIS_OLD_SYSCALLS)
   SOLXY(__NR_open,                 sys_open),                  /*   5 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLXY(__NR_close,                sys_close),                 /*   6 */
   SOLX_(__NR_linkat,               sys_linkat),                /*   7 */
#if defined(SOLARIS_OLD_SYSCALLS)
   GENX_(__NR_link,                 sys_link),                  /*   9 */
   GENX_(__NR_unlink,               sys_unlink),                /*  10 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLX_(__NR_symlinkat,            sys_symlinkat),             /*  11 */
   GENX_(__NR_chdir,                sys_chdir),                 /*  12 */
   SOLX_(__NR_time,                 sys_time),                  /*  13 */
#if defined(SOLARIS_OLD_SYSCALLS)
   GENX_(__NR_chmod,                sys_chmod),                 /*  15 */
   GENX_(__NR_chown,                sys_chown),                 /*  16 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLX_(__NR_brk,                  sys_brk),                   /*  17 */
#if defined(SOLARIS_OLD_SYSCALLS)
   SOLXY(__NR_stat,                 sys_stat),                  /*  18 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLX_(__NR_lseek,                sys_lseek),                 /*  19 */
   GENX_(__NR_getpid,               sys_getpid),                /*  20 */
   SOLXY(__NR_mount,                sys_mount),                 /*  21 */
   SOLXY(__NR_readlinkat,           sys_readlinkat),            /*  22 */
   GENX_(__NR_setuid,               sys_setuid),                /*  23 */
   GENX_(__NR_getuid,               sys_getuid),                /*  24 */
   SOLX_(__NR_stime,                sys_stime),                 /*  25 */
   GENX_(__NR_alarm,                sys_alarm),                 /*  27 */
#if defined(SOLARIS_OLD_SYSCALLS)
   SOLXY(__NR_fstat,                sys_fstat),                 /*  28 */
#endif /* SOLARIS_OLD_SYSCALLS */
   GENX_(__NR_pause,                sys_pause),                 /*  29 */
#if defined(SOLARIS_FREALPATHAT_SYSCALL)
   SOLXY(__NR_frealpathat,          sys_frealpathat),           /*  30 */
#endif /* SOLARIS_FREALPATHAT_SYSCALL */
   SOLX_(__NR_stty,                 sys_stty),                  /*  31 */
   SOLXY(__NR_gtty,                 sys_gtty),                  /*  32 */
#if defined(SOLARIS_OLD_SYSCALLS)
   GENX_(__NR_access,               sys_access),                /*  33 */
#endif /* SOLARIS_OLD_SYSCALLS */
   GENX_(__NR_kill,                 sys_kill),                  /*  37 */
   SOLX_(__NR_pgrpsys,              sys_pgrpsys),               /*  39 */
   SOLXY(__NR_pipe,                 sys_pipe),                  /*  42 */
   GENXY(__NR_times,                sys_times),                 /*  43 */
   SOLX_(__NR_faccessat,            sys_faccessat),             /*  45 */
   GENX_(__NR_setgid,               sys_setgid),                /*  46 */
   GENX_(__NR_getgid,               sys_getgid),                /*  47 */
   SOLXY(__NR_mknodat,              sys_mknodat),               /*  48 */
   SOLXY(__NR_sysi86,               sys_sysi86),                /*  50 */
   SOLXY(__NR_shmsys,               sys_shmsys),                /*  52 */
   SOLXY(__NR_semsys,               sys_semsys),                /*  53 */
   SOLXY(__NR_ioctl,                sys_ioctl),                 /*  54 */
   SOLX_(__NR_fchownat,             sys_fchownat),              /*  56 */
   SOLX_(__NR_fdsync,               sys_fdsync),                /*  58 */
   SOLX_(__NR_execve,               sys_execve),                /*  59 */
   GENX_(__NR_umask,                sys_umask),                 /*  60 */
   GENX_(__NR_chroot,               sys_chroot),                /*  61 */
   SOLXY(__NR_fcntl,                sys_fcntl),                 /*  62 */
   SOLX_(__NR_renameat,             sys_renameat),              /*  64 */
   SOLX_(__NR_unlinkat,             sys_unlinkat),              /*  65 */
   SOLXY(__NR_fstatat,              sys_fstatat),               /*  66 */
#if defined(VGP_x86_solaris)
   PLAXY(__NR_fstatat64,            sys_fstatat64),             /*  67 */
#endif /* VGP_x86_solaris */
   SOLXY(__NR_openat,               sys_openat),                /*  68 */
#if defined(VGP_x86_solaris)
   PLAXY(__NR_openat64,             sys_openat64),              /*  69 */
#endif /* VGP_x86_solaris */
   SOLXY(__NR_tasksys,              sys_tasksys),               /*  70 */
   SOLXY(__NR_getpagesizes,         sys_getpagesizes),          /*  73 */
   SOLXY(__NR_lwp_park,             sys_lwp_park),              /*  77 */
   SOLXY(__NR_sendfilev,            sys_sendfilev),             /*  78 */
#if defined(SOLARIS_LWP_NAME_SYSCALL)
   SOLXY(__NR_lwp_name,             sys_lwp_name),              /*  79 */
#endif /* SOLARIS_LWP_NAME_SYSCALL */
#if defined(SOLARIS_OLD_SYSCALLS)
   GENX_(__NR_rmdir,                sys_rmdir),                 /*  79 */
   GENX_(__NR_mkdir,                sys_mkdir),                 /*  80 */
#endif /* SOLARIS_OLD_SYSCALLS */
   GENXY(__NR_getdents,             sys_getdents),              /*  81 */
   SOLXY(__NR_privsys,              sys_privsys),               /*  82 */
   SOLXY(__NR_ucredsys,             sys_ucredsys),              /*  83 */
   SOLXY(__NR_getmsg,               sys_getmsg),                /*  85 */
   SOLX_(__NR_putmsg,               sys_putmsg),                /*  86 */
#if defined(SOLARIS_OLD_SYSCALLS)
   SOLXY(__NR_lstat,                sys_lstat),                 /*  88 */
   GENX_(__NR_symlink,              sys_symlink),               /*  89 */
   GENX_(__NR_readlink,             sys_readlink),              /*  90 */
#endif /* SOLARIS_OLD_SYSCALLS */
   GENX_(__NR_setgroups,            sys_setgroups),             /*  91 */
   GENXY(__NR_getgroups,            sys_getgroups),             /*  92 */
#if defined(SOLARIS_OLD_SYSCALLS)
   GENX_(__NR_fchmod,               sys_fchmod),                /*  93 */
   GENX_(__NR_fchown,               sys_fchown),                /*  94 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLXY(__NR_sigprocmask,          sys_sigprocmask),           /*  95 */
   GENXY(__NR_sigaltstack,          sys_sigaltstack),           /*  97 */
   SOLXY(__NR_sigaction,            sys_sigaction),             /*  98 */
   SOLXY(__NR_sigpending,           sys_sigpending),            /*  99 */
   SOLX_(__NR_context,              sys_getsetcontext),         /* 100 */
   SOLX_(__NR_fchmodat,             sys_fchmodat),              /* 101 */
   SOLX_(__NR_mkdirat,              sys_mkdirat),               /* 102 */
   SOLXY(__NR_statvfs,              sys_statvfs),               /* 103 */
   SOLXY(__NR_fstatvfs,             sys_fstatvfs),              /* 104 */
   SOLXY(__NR_nfssys,               sys_nfssys),                /* 106 */
   SOLXY(__NR_waitid,               sys_waitid),                /* 107 */
#if defined(SOLARIS_UTIMESYS_SYSCALL)
   SOLX_(__NR_utimesys,             sys_utimesys),              /* 110 */
#endif /* SOLARIS_UTIMESYS_SYSCALL */
#if defined(SOLARIS_UTIMENSAT_SYSCALL)
   SOLX_(__NR_utimensat,            sys_utimensat),             /* 110 */
#endif /* SOLARIS_UTIMENSAT_SYSCALL */
   SOLXY(__NR_sigresend,            sys_sigresend),             /* 111 */
   SOLXY(__NR_priocntlsys,          sys_priocntlsys),           /* 112 */
   SOLX_(__NR_pathconf,             sys_pathconf),              /* 113 */
   SOLX_(__NR_mmap,                 sys_mmap),                  /* 115 */
   GENXY(__NR_mprotect,             sys_mprotect),              /* 116 */
   GENXY(__NR_munmap,               sys_munmap),                /* 117 */
   GENX_(__NR_fchdir,               sys_fchdir),                /* 120 */
   GENXY(__NR_readv,                sys_readv),                 /* 121 */
   GENX_(__NR_writev,               sys_writev),                /* 122 */
#if defined(SOLARIS_UUIDSYS_SYSCALL)
   SOLXY(__NR_uuidsys,              sys_uuidsys),               /* 124 */
#endif /* SOLARIS_UUIDSYS_SYSCALL */
   SOLX_(__NR_mmapobj,              sys_mmapobj),               /* 127 */
   GENX_(__NR_setrlimit,            sys_setrlimit),             /* 128 */
   GENXY(__NR_getrlimit,            sys_getrlimit),             /* 129 */
#if defined(SOLARIS_OLD_SYSCALLS)
   GENX_(__NR_lchown,               sys_lchown),                /* 130 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLX_(__NR_memcntl,              sys_memcntl),               /* 131 */
   SOLXY(__NR_getpmsg,              sys_getpmsg),               /* 132 */
   SOLX_(__NR_putpmsg,              sys_putpmsg),               /* 133 */
#if defined(SOLARIS_OLD_SYSCALLS)
   SOLX_(__NR_rename,               sys_rename),                /* 134 */
#endif /* SOLARIS_OLD_SYSCALLS */
   SOLXY(__NR_uname,                sys_uname),                 /* 135 */
   SOLX_(__NR_setegid,              sys_setegid),               /* 136 */
   SOLX_(__NR_sysconfig,            sys_sysconfig),             /* 137 */
   SOLXY(__NR_systeminfo,           sys_systeminfo),            /* 139 */
   SOLX_(__NR_seteuid,              sys_seteuid),               /* 141 */
   SOLX_(__NR_forksys,              sys_forksys),               /* 142 */
   SOLXY(__NR_sigtimedwait,         sys_sigtimedwait),          /* 144 */
   SOLX_(__NR_yield,                sys_yield),                 /* 146 */
   SOLXY(__NR_lwp_sema_post,        sys_lwp_sema_post),         /* 148 */
   SOLXY(__NR_lwp_sema_trywait,     sys_lwp_sema_trywait),      /* 149 */
   SOLX_(__NR_lwp_detach,           sys_lwp_detach),            /* 150 */
   SOLX_(__NR_fchroot,              sys_fchroot),               /* 153 */
#if defined(SOLARIS_SYSTEM_STATS_SYSCALL)
   SOLX_(__NR_system_stats,         sys_system_stats),          /* 154 */
#endif /* SOLARIS_SYSTEM_STATS_SYSCALL */
   SOLXY(__NR_gettimeofday,         sys_gettimeofday),          /* 156 */
   GENXY(__NR_getitimer,            sys_getitimer),             /* 157 */
   GENXY(__NR_setitimer,            sys_setitimer),             /* 158 */
   SOLX_(__NR_lwp_create,           sys_lwp_create),            /* 159 */
   SOLX_(__NR_lwp_exit,             sys_lwp_exit),              /* 160 */
   SOLX_(__NR_lwp_suspend,          sys_lwp_suspend),           /* 161 */
   SOLX_(__NR_lwp_continue,         sys_lwp_continue),          /* 162 */
#if defined(SOLARIS_LWP_SIGQUEUE_SYSCALL)
   SOLXY(__NR_lwp_sigqueue,         sys_lwp_sigqueue),          /* 163 */
#else
   SOLXY(__NR_lwp_kill,             sys_lwp_kill),              /* 163 */
#endif /* SOLARIS_LWP_SIGQUEUE_SYSCALL */
   SOLX_(__NR_lwp_self,             sys_lwp_self),              /* 164 */
   SOLX_(__NR_lwp_sigmask,          sys_lwp_sigmask),           /* 165 */
   SOLX_(__NR_lwp_private,          sys_lwp_private),           /* 166 */
   SOLXY(__NR_lwp_wait,             sys_lwp_wait),              /* 167 */
   SOLXY(__NR_lwp_mutex_wakeup,     sys_lwp_mutex_wakeup),      /* 168 */
   SOLXY(__NR_lwp_cond_wait,        sys_lwp_cond_wait),         /* 170 */
   SOLX_(__NR_lwp_cond_broadcast,   sys_lwp_cond_broadcast),    /* 172 */
   SOLXY(__NR_pread,                sys_pread),                 /* 173 */
   SOLX_(__NR_pwrite,               sys_pwrite),                /* 174 */
#if defined(VGP_x86_solaris)
   PLAX_(__NR_llseek,               sys_llseek32),              /* 175 */
#endif /* VGP_x86_solaris */
   SOLXY(__NR_rusagesys,            sys_rusagesys),             /* 181 */
   SOLXY(__NR_port,                 sys_port),                  /* 182 */
   SOLXY(__NR_pollsys,              sys_pollsys),               /* 183 */
   SOLXY(__NR_labelsys,             sys_labelsys),              /* 184 */
   SOLXY(__NR_acl,                  sys_acl),                   /* 185 */
   SOLXY(__NR_auditsys,             sys_auditsys),              /* 186 */
   SOLX_(__NR_p_online,             sys_p_online),              /* 189 */
   SOLX_(__NR_sigqueue,             sys_sigqueue),              /* 190 */
   SOLX_(__NR_clock_gettime,        sys_clock_gettime),         /* 191 */
   SOLX_(__NR_clock_settime,        sys_clock_settime),         /* 192 */
   SOLXY(__NR_clock_getres,         sys_clock_getres),          /* 193 */
   SOLXY(__NR_timer_create,         sys_timer_create),          /* 194 */
   SOLX_(__NR_timer_delete,         sys_timer_delete),          /* 195 */
   SOLXY(__NR_timer_settime,        sys_timer_settime),         /* 196 */
   SOLXY(__NR_timer_gettime,        sys_timer_gettime),         /* 197 */
   SOLX_(__NR_timer_getoverrun,     sys_timer_getoverrun),      /* 198 */
   GENXY(__NR_nanosleep,            sys_nanosleep),             /* 199 */
   SOLXY(__NR_facl,                 sys_facl),                  /* 200 */
   SOLXY(__NR_door,                 sys_door),                  /* 201 */
   GENX_(__NR_setreuid,             sys_setreuid),              /* 202 */
   GENX_(__NR_setregid,             sys_setregid),              /* 202 */
   SOLXY(__NR_schedctl,             sys_schedctl),              /* 206 */
   SOLXY(__NR_pset,                 sys_pset),                  /* 207 */
   SOLXY(__NR_resolvepath,          sys_resolvepath),           /* 209 */
   SOLXY(__NR_lwp_mutex_timedlock,  sys_lwp_mutex_timedlock),   /* 210 */
   SOLXY(__NR_lwp_sema_timedwait,   sys_lwp_sema_timedwait),    /* 211 */
   SOLXY(__NR_lwp_rwlock_sys,       sys_lwp_rwlock_sys),        /* 212 */
#if defined(VGP_x86_solaris)
   GENXY(__NR_getdents64,           sys_getdents64),            /* 213 */
   PLAX_(__NR_mmap64,               sys_mmap64),                /* 214 */
#if defined(SOLARIS_OLD_SYSCALLS)
   PLAXY(__NR_stat64,               sys_stat64),                /* 215 */
   PLAXY(__NR_lstat64,              sys_lstat64),               /* 216 */
   PLAXY(__NR_fstat64,              sys_fstat64),               /* 217 */
#endif /* SOLARIS_OLD_SYSCALLS */
   PLAXY(__NR_statvfs64,            sys_statvfs64),             /* 218 */
   PLAXY(__NR_fstatvfs64,           sys_fstatvfs64),            /* 219 */
#endif /* VGP_x86_solaris */
#if defined(VGP_x86_solaris)
   PLAX_(__NR_setrlimit64,          sys_setrlimit64),           /* 220 */
   PLAXY(__NR_getrlimit64,          sys_getrlimit64),           /* 221 */
   PLAXY(__NR_pread64,              sys_pread64),               /* 222 */
   PLAX_(__NR_pwrite64,             sys_pwrite64),              /* 223 */
#if defined(SOLARIS_OLD_SYSCALLS)
   PLAXY(__NR_open64,               sys_open64),                /* 225 */
#endif /* SOLARIS_OLD_SYSCALLS */
#endif /* VGP_x86_solaris */
   SOLXY(__NR_zone,                 sys_zone),                  /* 227 */
   SOLXY(__NR_getcwd,               sys_getcwd),                /* 229 */
   SOLXY(__NR_so_socket,            sys_so_socket),             /* 230 */
   SOLXY(__NR_so_socketpair,        sys_so_socketpair),         /* 231 */
   SOLX_(__NR_bind,                 sys_bind),                  /* 232 */
   SOLX_(__NR_listen,               sys_listen),                /* 233 */
   SOLXY(__NR_accept,               sys_accept),                /* 234 */
   SOLX_(__NR_connect,              sys_connect),               /* 235 */
   SOLX_(__NR_shutdown,             sys_shutdown),              /* 236 */
   SOLXY(__NR_recv,                 sys_recv),                  /* 237 */
   SOLXY(__NR_recvfrom,             sys_recvfrom),              /* 238 */
   SOLXY(__NR_recvmsg,              sys_recvmsg),               /* 239 */
   SOLX_(__NR_send,                 sys_send),                  /* 240 */
   SOLX_(__NR_sendmsg,              sys_sendmsg),               /* 241 */
   SOLX_(__NR_sendto,               sys_sendto),                /* 242 */
   SOLXY(__NR_getpeername,          sys_getpeername),           /* 243 */
   SOLXY(__NR_getsockname,          sys_getsockname),           /* 244 */
   SOLXY(__NR_getsockopt,           sys_getsockopt),            /* 245 */
   SOLX_(__NR_setsockopt,           sys_setsockopt),            /* 246 */
   SOLX_(__NR_lwp_mutex_register,   sys_lwp_mutex_register),    /* 252 */
   SOLXY(__NR_uucopy,               sys_uucopy),                /* 254 */
   SOLX_(__NR_umount2,              sys_umount2)                /* 255 */
};

static SyscallTableEntry fasttrap_table[] = {
   SOLX_(__NR_gethrtime,            fast_gethrtime),            /*   3 */
   SOLX_(__NR_gethrvtime,           fast_gethrvtime),           /*   4 */
   SOLX_(__NR_gethrestime,          fast_gethrestime)           /*   5 */
#if defined(SOLARIS_GETHRT_FASTTRAP)
   ,
   SOLXY(__NR_gethrt,               fast_gethrt)                /*   7 */
#endif /* SOLARIS_GETHRT_FASTTRAP */
#if defined(SOLARIS_GETZONEOFFSET_FASTTRAP)
   ,
   SOLXY(__NR_getzoneoffset,        fast_getzoneoffset)         /*   8 */
#endif /* SOLARIS_GETZONEOFFSET_FASTTRAP */

};

SyscallTableEntry *ML_(get_solaris_syscall_entry)(UInt sysno)
{
   const UInt syscall_table_size
      = sizeof(syscall_table) / sizeof(syscall_table[0]);
   const UInt fasttrap_table_size
      = sizeof(fasttrap_table) / sizeof(fasttrap_table[0]);

   SyscallTableEntry *table;
   Int size;

   switch (VG_SOLARIS_SYSNO_CLASS(sysno)) {
   case VG_SOLARIS_SYSCALL_CLASS_CLASSIC:
      table = syscall_table;
      size = syscall_table_size;
      break;
   case VG_SOLARIS_SYSCALL_CLASS_FASTTRAP:
      table = fasttrap_table;
      size = fasttrap_table_size;
      break;
   default:
      vg_assert(0);
      break;
   }
   sysno = VG_SOLARIS_SYSNO_INDEX(sysno);
   if (sysno < size) {
      SyscallTableEntry *sys = &table[sysno];
      if (!sys->before)
         return NULL; /* no entry */
      return sys;
   }

   /* Can't find a wrapper. */
   return NULL;
}

#endif // defined(VGO_solaris)

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