summaryrefslogtreecommitdiffhomepage
path: root/test/syscalls/linux/ptrace.cc
blob: f64c23ac03c9e264f1e7406aad4498601ebf6659 (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
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <elf.h>
#include <signal.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <unistd.h>

#include <iostream>
#include <utility>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/flags/flag.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/util/capability_util.h"
#include "test/util/fs_util.h"
#include "test/util/logging.h"
#include "test/util/memory_util.h"
#include "test/util/multiprocess_util.h"
#include "test/util/platform_util.h"
#include "test/util/signal_util.h"
#include "test/util/temp_path.h"
#include "test/util/test_util.h"
#include "test/util/thread_util.h"
#include "test/util/time_util.h"

ABSL_FLAG(bool, ptrace_test_execve_child, false,
          "If true, run the "
          "PtraceExecveTest_Execve_GetRegs_PeekUser_SIGKILL_TraceClone_"
          "TraceExit child workload.");
ABSL_FLAG(bool, ptrace_test_trace_descendants_allowed, false,
          "If set, run the child workload for "
          "PtraceTest_TraceDescendantsAllowed.");
ABSL_FLAG(bool, ptrace_test_ptrace_attacher, false,
          "If set, run the child workload for PtraceAttacherSubprocess.");
ABSL_FLAG(bool, ptrace_test_prctl_set_ptracer, false,
          "If set, run the child workload for PrctlSetPtracerSubprocess.");
ABSL_FLAG(bool, ptrace_test_prctl_set_ptracer_and_exit_tracee_thread, false,
          "If set, run the child workload for "
          "PtraceTest_PrctlSetPtracerPersistsPastTraceeThreadExit.");
ABSL_FLAG(bool, ptrace_test_prctl_set_ptracer_and_exec_non_leader, false,
          "If set, run the child workload for "
          "PtraceTest_PrctlSetPtracerDoesNotPersistPastNonLeaderExec.");
ABSL_FLAG(bool, ptrace_test_prctl_set_ptracer_and_exit_tracer_thread, false,
          "If set, run the child workload for "
          "PtraceTest_PrctlSetPtracerDoesNotPersistPastTracerThreadExit.");
ABSL_FLAG(int, ptrace_test_prctl_set_ptracer_and_exit_tracer_thread_tid, -1,
          "Specifies the tracee tid in the child workload for "
          "PtraceTest_PrctlSetPtracerDoesNotPersistPastTracerThreadExit.");
ABSL_FLAG(bool, ptrace_test_prctl_set_ptracer_respects_tracer_thread_id, false,
          "If set, run the child workload for PtraceTest_PrctlSetPtracePID.");
ABSL_FLAG(int, ptrace_test_prctl_set_ptracer_respects_tracer_thread_id_tid, -1,
          "Specifies the thread tid to be traced in the child workload "
          "for PtraceTest_PrctlSetPtracerRespectsTracerThreadID.");

ABSL_FLAG(bool, ptrace_test_tracee, false,
          "If true, run the tracee process for the "
          "PrctlSetPtracerDoesNotPersistPastLeaderExec and "
          "PrctlSetPtracerDoesNotPersistPastNonLeaderExec workloads.");
ABSL_FLAG(int, ptrace_test_trace_tid, -1,
          "If set, run a process to ptrace attach to the thread with the "
          "specified pid for the PrctlSetPtracerRespectsTracerThreadID "
          "workload.");
ABSL_FLAG(int, ptrace_test_fd, -1,
          "Specifies the fd used for communication between tracer and tracee "
          "processes across exec.");

namespace gvisor {
namespace testing {

namespace {

// PTRACE_GETSIGMASK and PTRACE_SETSIGMASK are not defined until glibc 2.23
// (fb53a27c5741 "Add new header definitions from Linux 4.4 (plus older ptrace
// definitions)").
constexpr auto kPtraceGetSigMask = static_cast<__ptrace_request>(0x420a);
constexpr auto kPtraceSetSigMask = static_cast<__ptrace_request>(0x420b);

// PTRACE_SYSEMU is not defined until glibc 2.27 (c48831d0eebf "linux/x86: sync
// sys/ptrace.h with Linux 4.14 [BZ #22433]").
constexpr auto kPtraceSysemu = static_cast<__ptrace_request>(31);

// PTRACE_EVENT_STOP is not defined until glibc 2.26 (3f67d1a7021e "Add Linux
// PTRACE_EVENT_STOP").
constexpr int kPtraceEventStop = 128;

// Sends sig to the current process with tgkill(2).
//
// glibc's raise(2) may change the signal mask before sending the signal. These
// extra syscalls make tests of syscall, signal interception, etc. difficult to
// write.
void RaiseSignal(int sig) {
  pid_t pid = getpid();
  TEST_PCHECK(pid > 0);
  pid_t tid = gettid();
  TEST_PCHECK(tid > 0);
  TEST_PCHECK(tgkill(pid, tid, sig) == 0);
}

constexpr char kYamaPtraceScopePath[] = "/proc/sys/kernel/yama/ptrace_scope";

// Returns the Yama ptrace scope.
PosixErrorOr<int> YamaPtraceScope() {
  ASSIGN_OR_RETURN_ERRNO(bool exists, Exists(kYamaPtraceScopePath));
  if (!exists) {
    // File doesn't exist means no Yama, so the scope is disabled -> 0.
    return 0;
  }

  std::string contents;
  RETURN_IF_ERRNO(GetContents(kYamaPtraceScopePath, &contents));

  int scope;
  if (!absl::SimpleAtoi(contents, &scope)) {
    return PosixError(EINVAL, absl::StrCat(contents, ": not a valid number"));
  }

  return scope;
}

int CheckPtraceAttach(pid_t pid) {
  int ret = ptrace(PTRACE_ATTACH, pid, 0, 0);
  MaybeSave();
  if (ret < 0) {
    return ret;
  }

  int status;
  TEST_PCHECK(waitpid(pid, &status, 0) == pid);
  MaybeSave();
  TEST_CHECK(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
  TEST_PCHECK(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
  MaybeSave();
  return 0;
}

class SimpleSubprocess {
 public:
  explicit SimpleSubprocess(absl::string_view child_flag) {
    int sockets[2];
    TEST_PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == 0);

    // Allocate vector before forking (not async-signal-safe).
    ExecveArray const owned_child_argv = {"/proc/self/exe", child_flag,
                                          "--ptrace_test_fd",
                                          std::to_string(sockets[0])};
    char* const* const child_argv = owned_child_argv.get();

    pid_ = fork();
    if (pid_ == 0) {
      TEST_PCHECK(close(sockets[1]) == 0);
      execve(child_argv[0], child_argv, /* envp = */ nullptr);
      TEST_PCHECK_MSG(false, "Survived execve to test child");
    }
    TEST_PCHECK(pid_ > 0);
    TEST_PCHECK(close(sockets[0]) == 0);
    sockfd_ = sockets[1];
  }

  SimpleSubprocess(SimpleSubprocess&& orig)
      : pid_(orig.pid_), sockfd_(orig.sockfd_) {
    orig.pid_ = -1;
    orig.sockfd_ = -1;
  }

  SimpleSubprocess& operator=(SimpleSubprocess&& orig) {
    if (this != &orig) {
      this->~SimpleSubprocess();
      pid_ = orig.pid_;
      sockfd_ = orig.sockfd_;
      orig.pid_ = -1;
      orig.sockfd_ = -1;
    }
    return *this;
  }

  SimpleSubprocess(SimpleSubprocess const&) = delete;
  SimpleSubprocess& operator=(SimpleSubprocess const&) = delete;

  ~SimpleSubprocess() {
    if (pid_ < 0) {
      return;
    }
    EXPECT_THAT(shutdown(sockfd_, SHUT_RDWR), SyscallSucceeds());
    EXPECT_THAT(close(sockfd_), SyscallSucceeds());
    int status;
    EXPECT_THAT(waitpid(pid_, &status, 0), SyscallSucceedsWithValue(pid_));
    EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
        << " status " << status;
  }

  pid_t pid() const { return pid_; }

  // Sends the child process the given value, receives an errno in response, and
  // returns a PosixError corresponding to the received errno.
  template <typename T>
  PosixError Cmd(T val) {
    if (WriteFd(sockfd_, &val, sizeof(val)) < 0) {
      return PosixError(errno, "write failed");
    }
    return RecvErrno();
  }

 private:
  PosixError RecvErrno() {
    int resp_errno;
    if (ReadFd(sockfd_, &resp_errno, sizeof(resp_errno)) < 0) {
      return PosixError(errno, "read failed");
    }
    return PosixError(resp_errno);
  }

  pid_t pid_ = -1;
  int sockfd_ = -1;
};

TEST(PtraceTest, AttachSelf) {
  EXPECT_THAT(ptrace(PTRACE_ATTACH, gettid(), 0, 0),
              SyscallFailsWithErrno(EPERM));
}

TEST(PtraceTest, AttachSameThreadGroup) {
  pid_t const tid = gettid();
  ScopedThread([&] {
    EXPECT_THAT(ptrace(PTRACE_ATTACH, tid, 0, 0), SyscallFailsWithErrno(EPERM));
  });
}

TEST(PtraceTest, TraceParentNotAllowed) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) < 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    TEST_CHECK(CheckPtraceAttach(getppid()) == -1);
    TEST_PCHECK(errno == EPERM);
    _exit(0);
  }
  ASSERT_THAT(child_pid, SyscallSucceeds());

  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

TEST(PtraceTest, TraceNonDescendantNotAllowed) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) < 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    TEST_CHECK(CheckPtraceAttach(tracee_pid) == -1);
    TEST_PCHECK(errno == EPERM);
    _exit(0);
  }
  EXPECT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, TraceNonDescendantWithCapabilityAllowed) {
  SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_PTRACE)));
  // Skip if disallowed by YAMA despite having CAP_SYS_PTRACE.
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) > 2);

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    TEST_PCHECK(CheckPtraceAttach(tracee_pid) == 0);
    _exit(0);
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, TraceDescendantsAllowed) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) > 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Use socket pair to communicate tids to this process from its grandchild.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  // Allocate vector before forking (not async-signal-safe).
  ExecveArray const owned_child_argv = {
      "/proc/self/exe", "--ptrace_test_trace_descendants_allowed",
      "--ptrace_test_fd", std::to_string(sockets[0])};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    TEST_PCHECK(close(sockets[1]) == 0);
    pid_t const grandchild_pid = fork();
    if (grandchild_pid == 0) {
      // This test will create a new thread in the grandchild process.
      // pthread_create(2) isn't async-signal-safe, so we execve() first.
      execve(child_argv[0], child_argv, /* envp = */ nullptr);
      TEST_PCHECK_MSG(false, "Survived execve to test child");
    }
    TEST_PCHECK(grandchild_pid > 0);
    MaybeSave();

    // Wait for grandchild. Our parent process will kill it once it's done.
    int status;
    TEST_PCHECK(waitpid(grandchild_pid, &status, 0) == grandchild_pid);
    TEST_CHECK(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL);
    MaybeSave();
    _exit(0);
  }
  ASSERT_THAT(child_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  // We should be able to attach to any thread in the grandchild.
  pid_t grandchild_tid1, grandchild_tid2;
  ASSERT_THAT(read(sockets[1], &grandchild_tid1, sizeof(grandchild_tid1)),
              SyscallSucceedsWithValue(sizeof(grandchild_tid1)));
  ASSERT_THAT(read(sockets[1], &grandchild_tid2, sizeof(grandchild_tid2)),
              SyscallSucceedsWithValue(sizeof(grandchild_tid2)));

  EXPECT_THAT(CheckPtraceAttach(grandchild_tid1), SyscallSucceeds());
  EXPECT_THAT(CheckPtraceAttach(grandchild_tid2), SyscallSucceeds());

  // Clean up grandchild.
  ASSERT_THAT(kill(grandchild_tid1, SIGKILL), SyscallSucceeds());

  // Clean up child.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

[[noreturn]] void RunTraceDescendantsAllowed(int fd) {
  // Let the tracer know our tid through the socket fd.
  pid_t const tid = gettid();
  TEST_PCHECK(write(fd, &tid, sizeof(tid)) == sizeof(tid));
  MaybeSave();

  ScopedThread t([fd] {
    // See if any arbitrary thread (whose tid differs from the process id) can
    // be traced as well.
    pid_t const tid = gettid();
    TEST_PCHECK(write(fd, &tid, sizeof(tid)) == sizeof(tid));
    MaybeSave();
    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  });

  while (true) {
    SleepSafe(absl::Seconds(1));
  }
}

TEST(PtraceTest, PrctlSetPtracerInvalidPID) {
  // EINVAL should also be returned if PR_SET_PTRACER is not supported.
  EXPECT_THAT(prctl(PR_SET_PTRACER, 123456789), SyscallFailsWithErrno(EINVAL));
}

SimpleSubprocess CreatePtraceAttacherSubprocess() {
  return SimpleSubprocess("--ptrace_test_ptrace_attacher");
}

[[noreturn]] static void RunPtraceAttacher(int sockfd) {
  // execve() may have restored CAP_SYS_PTRACE if we had real UID 0.
  TEST_CHECK(SetCapability(CAP_SYS_PTRACE, false).ok());
  // Perform PTRACE_ATTACH in a separate thread to verify that permissions
  // apply process-wide.
  ScopedThread t([&] {
    while (true) {
      pid_t pid;
      int rv = read(sockfd, &pid, sizeof(pid));
      if (rv == 0) {
        _exit(0);
      }
      if (rv < 0) {
        _exit(1);
      }
      int resp_errno = 0;
      if (CheckPtraceAttach(pid) < 0) {
        resp_errno = errno;
      }
      TEST_PCHECK(write(sockfd, &resp_errno, sizeof(resp_errno)) ==
                  sizeof(resp_errno));
    }
  });
  while (true) {
    SleepSafe(absl::Seconds(1));
  }
}

SimpleSubprocess CreatePrctlSetPtracerSubprocess() {
  return SimpleSubprocess("--ptrace_test_prctl_set_ptracer");
}

[[noreturn]] static void RunPrctlSetPtracer(int sockfd) {
  // Perform prctl in a separate thread to verify that it applies
  // process-wide.
  ScopedThread t([&] {
    while (true) {
      pid_t pid;
      int rv = read(sockfd, &pid, sizeof(pid));
      if (rv == 0) {
        _exit(0);
      }
      if (rv < 0) {
        _exit(1);
      }
      int resp_errno = 0;
      if (prctl(PR_SET_PTRACER, pid) < 0) {
        resp_errno = errno;
      }
      TEST_PCHECK(write(sockfd, &resp_errno, sizeof(resp_errno)) ==
                  sizeof(resp_errno));
    }
  });
  while (true) {
    SleepSafe(absl::Seconds(1));
  }
}

TEST(PtraceTest, PrctlSetPtracer) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);

  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Ensure that initially, no tracer exception is set.
  ASSERT_THAT(prctl(PR_SET_PTRACER, 0), SyscallSucceeds());

  SimpleSubprocess tracee = CreatePrctlSetPtracerSubprocess();
  SimpleSubprocess tracer = CreatePtraceAttacherSubprocess();

  // By default, Yama should prevent tracer from tracing its parent (this
  // process) or siblings (tracee).
  EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(EPERM));
  EXPECT_THAT(tracer.Cmd(tracee.pid()), PosixErrorIs(EPERM));

  // If tracee invokes PR_SET_PTRACER on either tracer's pid, the pid of any of
  // its ancestors (i.e. us), or PR_SET_PTRACER_ANY, then tracer can trace it
  // (but not us).

  ASSERT_THAT(tracee.Cmd(tracer.pid()), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(tracee.pid()), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(EPERM));

  ASSERT_THAT(tracee.Cmd(gettid()), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(tracee.pid()), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(EPERM));

  ASSERT_THAT(tracee.Cmd(static_cast<pid_t>(PR_SET_PTRACER_ANY)),
              PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(tracee.pid()), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(EPERM));

  // If tracee invokes PR_SET_PTRACER with pid 0, then tracer can no longer
  // trace it.
  ASSERT_THAT(tracee.Cmd(0), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(tracee.pid()), PosixErrorIs(EPERM));

  // If we invoke PR_SET_PTRACER with tracer's pid, then it can trace us (but
  // not our descendants).
  ASSERT_THAT(prctl(PR_SET_PTRACER, tracer.pid()), SyscallSucceeds());
  EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(0));
  EXPECT_THAT(tracer.Cmd(tracee.pid()), PosixErrorIs(EPERM));

  // If we invoke PR_SET_PTRACER with pid 0, then tracer can no longer trace us.
  ASSERT_THAT(prctl(PR_SET_PTRACER, 0), SyscallSucceeds());
  EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(EPERM));

  // Another thread in our thread group can invoke PR_SET_PTRACER instead; its
  // effect applies to the whole thread group.
  pid_t const our_tid = gettid();
  ScopedThread([&] {
    ASSERT_THAT(prctl(PR_SET_PTRACER, tracer.pid()), SyscallSucceeds());
    EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(0));
    EXPECT_THAT(tracer.Cmd(our_tid), PosixErrorIs(0));

    ASSERT_THAT(prctl(PR_SET_PTRACER, 0), SyscallSucceeds());
    EXPECT_THAT(tracer.Cmd(gettid()), PosixErrorIs(EPERM));
    EXPECT_THAT(tracer.Cmd(our_tid), PosixErrorIs(EPERM));
  }).Join();
}

// Tests that YAMA exceptions store tracees by thread group leader. Exceptions
// are preserved even after the tracee thread exits, as long as the tracee's
// thread group leader is still around.
TEST(PtraceTest, PrctlSetPtracerPersistsPastTraceeThreadExit) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Use sockets to synchronize between tracer and tracee.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  // Allocate vector before forking (not async-signal-safe).
  ExecveArray const owned_child_argv = {
      "/proc/self/exe",
      "--ptrace_test_prctl_set_ptracer_and_exit_tracee_thread",
      "--ptrace_test_fd", std::to_string(sockets[0])};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    // This test will create a new thread in the child process.
    // pthread_create(2) isn't async-signal-safe, so we execve() first.
    TEST_PCHECK(close(sockets[1]) == 0);
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    // Wait until the tracee thread calling prctl has terminated.
    char done;
    TEST_PCHECK(read(sockets[1], &done, 1) == 1);
    MaybeSave();

    TEST_PCHECK(CheckPtraceAttach(tracee_pid) == 0);
    _exit(0);
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

[[noreturn]] void RunPrctlSetPtracerPersistsPastTraceeThreadExit(int fd) {
  ScopedThread t([] {
    TEST_PCHECK(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) == 0);
    MaybeSave();
  });
  t.Join();
  // Indicate that thread setting the prctl has exited.
  TEST_PCHECK(write(fd, "x", 1) == 1);
  MaybeSave();

  while (true) {
    SleepSafe(absl::Seconds(1));
  }
}

// Tests that YAMA exceptions store tracees by thread group leader. Exceptions
// are preserved across exec as long as the thread group leader does not change,
// even if the tracee thread is terminated.
TEST(PtraceTest, PrctlSetPtracerPersistsPastLeaderExec) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Use sockets to synchronize between tracer and tracee.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  // Allocate vector before forking (not async-signal-safe).
  ExecveArray const owned_child_argv = {
      "/proc/self/exe", "--ptrace_test_tracee", "--ptrace_test_fd",
      std::to_string(sockets[0])};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    TEST_PCHECK(close(sockets[1]) == 0);
    TEST_PCHECK(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) == 0);
    MaybeSave();

    // This test will create a new thread in the child process.
    // pthread_create(2) isn't async-signal-safe, so we execve() first.
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    // Wait until the tracee has exec'd.
    char done;
    TEST_PCHECK(read(sockets[1], &done, 1) == 1);
    MaybeSave();

    TEST_PCHECK(CheckPtraceAttach(tracee_pid) == 0);
    _exit(0);
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

[[noreturn]] void RunTracee(int fd) {
  // Indicate that we have exec'd.
  TEST_PCHECK(write(fd, "x", 1) == 1);
  MaybeSave();

  while (true) {
    SleepSafe(absl::Seconds(1));
  }
}

// Tests that YAMA exceptions store tracees by thread group leader. Exceptions
// are cleared if the tracee process's thread group leader is terminated by
// exec.
TEST(PtraceTest, PrctlSetPtracerDoesNotPersistPastNonLeaderExec) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Use sockets to synchronize between tracer and tracee.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  // Allocate vector before forking (not async-signal-safe).
  ExecveArray const owned_child_argv = {
      "/proc/self/exe", "--ptrace_test_prctl_set_ptracer_and_exec_non_leader",
      "--ptrace_test_fd", std::to_string(sockets[0])};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    // This test will create a new thread in the child process.
    // pthread_create(2) isn't async-signal-safe, so we execve() first.
    TEST_PCHECK(close(sockets[1]) == 0);
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    // Wait until the tracee has exec'd.
    char done;
    TEST_PCHECK(read(sockets[1], &done, 1) == 1);
    MaybeSave();

    TEST_CHECK(CheckPtraceAttach(tracee_pid) == -1);
    TEST_PCHECK(errno == EPERM);
    _exit(0);
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

[[noreturn]] void RunPrctlSetPtracerDoesNotPersistPastNonLeaderExec(int fd) {
  ScopedThread t([fd] {
    TEST_PCHECK(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) == 0);
    MaybeSave();

    ExecveArray const owned_child_argv = {
        "/proc/self/exe", "--ptrace_test_tracee", "--ptrace_test_fd",
        std::to_string(fd)};
    char* const* const child_argv = owned_child_argv.get();

    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  });
  t.Join();
  TEST_CHECK_MSG(false, "Survived execve? (main)");
  _exit(1);
}

// Tests that YAMA exceptions store the tracer itself rather than the thread
// group leader. Exceptions are cleared when the tracer task exits, rather than
// when its thread group leader exits.
TEST(PtraceTest, PrctlSetPtracerDoesNotPersistPastTracerThreadExit) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);

  // Use sockets to synchronize between tracer and tracee.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    TEST_PCHECK(close(sockets[1]) == 0);
    pid_t tracer_tid;
    TEST_PCHECK(read(sockets[0], &tracer_tid, sizeof(tracer_tid)) ==
                sizeof(tracer_tid));
    MaybeSave();

    TEST_PCHECK(prctl(PR_SET_PTRACER, tracer_tid) == 0);
    MaybeSave();
    // Indicate that the prctl has been set.
    TEST_PCHECK(write(sockets[0], "x", 1) == 1);
    MaybeSave();

    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  // Allocate vector before forking (not async-signal-safe).
  ExecveArray const owned_child_argv = {
      "/proc/self/exe",
      "--ptrace_test_prctl_set_ptracer_and_exit_tracer_thread",
      "--ptrace_test_prctl_set_ptracer_and_exit_tracer_thread_tid",
      std::to_string(tracee_pid),
      "--ptrace_test_fd",
      std::to_string(sockets[1])};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    // This test will create a new thread in the child process.
    // pthread_create(2) isn't async-signal-safe, so we execve() first.
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

[[noreturn]] void RunPrctlSetPtracerDoesNotPersistPastTracerThreadExit(
    int tracee_tid, int fd) {
  AutoCapability cap(CAP_SYS_PTRACE, false);

  ScopedThread t([fd] {
    pid_t const tracer_tid = gettid();
    TEST_PCHECK(write(fd, &tracer_tid, sizeof(tracer_tid)) ==
                sizeof(tracer_tid));

    // Wait until the prctl has been set.
    char done;
    TEST_PCHECK(read(fd, &done, 1) == 1);
    MaybeSave();
  });
  t.Join();

  // Sleep for a bit before verifying the invalidation. The thread exit above
  // should cause the ptrace exception to be invalidated, but in Linux, this is
  // not done immediately. The YAMA exception is dropped during
  // __put_task_struct(), which occurs (at the earliest) one RCU grace period
  // after exit_notify() ==> release_task().
  SleepSafe(absl::Milliseconds(100));

  TEST_CHECK(CheckPtraceAttach(tracee_tid) == -1);
  TEST_PCHECK(errno == EPERM);
  _exit(0);
}

// Tests that YAMA exceptions store the tracer thread itself rather than the
// thread group leader. Exceptions are preserved across exec in the tracer
// thread, even if the thread group leader is terminated.
TEST(PtraceTest, PrctlSetPtracerRespectsTracerThreadID) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);

  // Use sockets to synchronize between tracer and tracee.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    TEST_PCHECK(close(sockets[1]) == 0);
    pid_t tracer_tid;
    TEST_PCHECK(read(sockets[0], &tracer_tid, sizeof(tracer_tid)) ==
                sizeof(tracer_tid));
    MaybeSave();

    TEST_PCHECK(prctl(PR_SET_PTRACER, tracer_tid) == 0);
    MaybeSave();
    // Indicate that the prctl has been set.
    TEST_PCHECK(write(sockets[0], "x", 1) == 1);
    MaybeSave();

    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  // Allocate vector before forking (not async-signal-safe).
  ExecveArray const owned_child_argv = {
      "/proc/self/exe",
      "--ptrace_test_prctl_set_ptracer_respects_tracer_thread_id",
      "--ptrace_test_prctl_set_ptracer_respects_tracer_thread_id_tid",
      std::to_string(tracee_pid),
      "--ptrace_test_fd",
      std::to_string(sockets[1])};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    // This test will create a new thread in the child process.
    // pthread_create(2) isn't async-signal-safe, so we execve() first.
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

[[noreturn]] void RunPrctlSetPtracerRespectsTracerThreadID(int tracee_tid,
                                                           int fd) {
  // Create a separate thread for tracing (i.e., not the thread group
  // leader). After the subsequent execve(), the current thread group leader
  // will no longer be exist, but the YAMA exception installed with this
  // thread should still be valid.
  ScopedThread t([tracee_tid, fd] {
    pid_t const tracer_tid = gettid();
    TEST_PCHECK(write(fd, &tracer_tid, sizeof(tracer_tid)));
    MaybeSave();

    // Wait until the tracee has made the PR_SET_PTRACER prctl.
    char done;
    TEST_PCHECK(read(fd, &done, 1) == 1);
    MaybeSave();

    ExecveArray const owned_child_argv = {
        "/proc/self/exe", "--ptrace_test_trace_tid", std::to_string(tracee_tid),
        "--ptrace_test_fd", std::to_string(fd)};
    char* const* const child_argv = owned_child_argv.get();

    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  });
  t.Join();
  TEST_CHECK_MSG(false, "Survived execve? (main)");
  _exit(1);
}

[[noreturn]] void RunTraceTID(int tracee_tid, int fd) {
  TEST_PCHECK(SetCapability(CAP_SYS_PTRACE, false).ok());
  TEST_PCHECK(CheckPtraceAttach(tracee_tid) == 0);
  _exit(0);
}

// Tests that removing a YAMA exception does not affect a tracer that is already
// attached.
TEST(PtraceTest, PrctlClearPtracerDoesNotAffectCurrentTracer) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Use sockets to synchronize between tracer and tracee.
  int sockets[2];
  ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    TEST_PCHECK(close(sockets[1]) == 0);
    TEST_PCHECK(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) == 0);
    MaybeSave();
    // Indicate that the prctl has been set.
    TEST_PCHECK(write(sockets[0], "x", 1) == 1);
    MaybeSave();

    // Wait until tracer has attached before clearing PR_SET_PTRACER.
    char done;
    TEST_PCHECK(read(sockets[0], &done, 1) == 1);
    MaybeSave();

    TEST_PCHECK(prctl(PR_SET_PTRACER, 0) == 0);
    MaybeSave();
    // Indicate that the prctl has been set.
    TEST_PCHECK(write(sockets[0], "x", 1) == 1);
    MaybeSave();

    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());
  ASSERT_THAT(close(sockets[0]), SyscallSucceeds());

  std::string mem_path = "/proc/" + std::to_string(tracee_pid) + "/mem";
  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    // Wait until tracee has called prctl, or else we won't be able to attach.
    char done;
    TEST_PCHECK(read(sockets[1], &done, 1) == 1);
    MaybeSave();

    TEST_PCHECK(ptrace(PTRACE_ATTACH, tracee_pid, 0, 0) == 0);
    MaybeSave();
    // Indicate that we have attached.
    TEST_PCHECK(write(sockets[1], &done, 1) == 1);
    MaybeSave();

    // Block until tracee enters signal-delivery-stop as a result of the
    // SIGSTOP sent by PTRACE_ATTACH.
    int status;
    TEST_PCHECK(waitpid(tracee_pid, &status, 0) == tracee_pid);
    MaybeSave();
    TEST_CHECK(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
    MaybeSave();

    TEST_PCHECK(ptrace(PTRACE_CONT, tracee_pid, 0, 0) == 0);
    MaybeSave();

    // Wait until tracee has cleared PR_SET_PTRACER. Even though it was cleared,
    // we should still be able to access /proc/[pid]/mem because we are already
    // attached.
    TEST_PCHECK(read(sockets[1], &done, 1) == 1);
    MaybeSave();
    TEST_PCHECK(open(mem_path.c_str(), O_RDONLY) != -1);
    MaybeSave();
    _exit(0);
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, PrctlNotInherited) {
  SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope()) != 1);
  AutoCapability cap(CAP_SYS_PTRACE, false);

  // Allow any ptracer. This should not affect the child processes.
  ASSERT_THAT(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY), SyscallSucceeds());

  pid_t const tracee_pid = fork();
  if (tracee_pid == 0) {
    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }
  ASSERT_THAT(tracee_pid, SyscallSucceeds());

  pid_t const tracer_pid = fork();
  if (tracer_pid == 0) {
    TEST_CHECK(CheckPtraceAttach(tracee_pid) == -1);
    TEST_PCHECK(errno == EPERM);
    _exit(0);
  }
  ASSERT_THAT(tracer_pid, SyscallSucceeds());

  // Clean up tracer.
  int status;
  ASSERT_THAT(waitpid(tracer_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Clean up tracee.
  ASSERT_THAT(kill(tracee_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(tracee_pid, &status, 0),
              SyscallSucceedsWithValue(tracee_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, AttachParent_PeekData_PokeData_SignalSuppression) {
  // Yama prevents attaching to a parent. Skip the test if the scope is anything
  // except disabled.
  const int yama_scope = ASSERT_NO_ERRNO_AND_VALUE(YamaPtraceScope());
  SKIP_IF(yama_scope > 1);
  if (yama_scope == 1) {
    // Allow child to trace us.
    ASSERT_THAT(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY), SyscallSucceeds());
  }

  // Test PTRACE_POKE/PEEKDATA on both anonymous and file mappings.
  const auto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  ASSERT_NO_ERRNO(Truncate(file.path(), kPageSize));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));
  const auto file_mapping = ASSERT_NO_ERRNO_AND_VALUE(Mmap(
      nullptr, kPageSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0));

  constexpr long kBeforePokeDataAnonValue = 10;
  constexpr long kAfterPokeDataAnonValue = 20;
  constexpr long kBeforePokeDataFileValue = 0;  // implicit, due to truncate()
  constexpr long kAfterPokeDataFileValue = 30;

  volatile long anon_word = kBeforePokeDataAnonValue;
  auto* file_word_ptr = static_cast<volatile long*>(file_mapping.ptr());

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Attach to the parent.
    pid_t const parent_pid = getppid();
    TEST_PCHECK(ptrace(PTRACE_ATTACH, parent_pid, 0, 0) == 0);
    MaybeSave();

    // Block until the parent enters signal-delivery-stop as a result of the
    // SIGSTOP sent by PTRACE_ATTACH.
    int status;
    TEST_PCHECK(waitpid(parent_pid, &status, 0) == parent_pid);
    MaybeSave();
    TEST_CHECK(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);

    // Replace the value of anon_word in the parent process with
    // kAfterPokeDataAnonValue.
    long parent_word = ptrace(PTRACE_PEEKDATA, parent_pid, &anon_word, 0);
    MaybeSave();
    TEST_CHECK(parent_word == kBeforePokeDataAnonValue);
    TEST_PCHECK(ptrace(PTRACE_POKEDATA, parent_pid, &anon_word,
                       kAfterPokeDataAnonValue) == 0);
    MaybeSave();

    // Replace the value pointed to by file_word_ptr in the mapped file with
    // kAfterPokeDataFileValue, via the parent process' mapping.
    parent_word = ptrace(PTRACE_PEEKDATA, parent_pid, file_word_ptr, 0);
    MaybeSave();
    TEST_CHECK(parent_word == kBeforePokeDataFileValue);
    TEST_PCHECK(ptrace(PTRACE_POKEDATA, parent_pid, file_word_ptr,
                       kAfterPokeDataFileValue) == 0);
    MaybeSave();

    // Detach from the parent and suppress the SIGSTOP. If the SIGSTOP is not
    // suppressed, the parent will hang in group-stop, causing the test to time
    // out.
    TEST_PCHECK(ptrace(PTRACE_DETACH, parent_pid, 0, 0) == 0);
    MaybeSave();
    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to complete.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Check that the child's PTRACE_POKEDATA was effective.
  EXPECT_EQ(kAfterPokeDataAnonValue, anon_word);
  EXPECT_EQ(kAfterPokeDataFileValue, *file_word_ptr);
}

TEST(PtraceTest, GetSigMask) {
  // glibc and the Linux kernel define a sigset_t with different sizes. To avoid
  // creating a kernel_sigset_t and recreating all the modification functions
  // (sigemptyset, etc), we just hardcode the kernel sigset size.
  constexpr int kSizeofKernelSigset = 8;
  constexpr int kBlockSignal = SIGUSR1;
  sigset_t blocked;
  sigemptyset(&blocked);
  sigaddset(&blocked, kBlockSignal);

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Install a signal handler for kBlockSignal to avoid termination and block
    // it.
    TEST_PCHECK(signal(
                    kBlockSignal, +[](int signo) {}) != SIG_ERR);
    MaybeSave();
    TEST_PCHECK(sigprocmask(SIG_SETMASK, &blocked, nullptr) == 0);
    MaybeSave();

    // Enable tracing.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();

    // This should be blocked.
    RaiseSignal(kBlockSignal);

    // This should be suppressed by parent, who will change signal mask in the
    // meantime, which means kBlockSignal should be delivered once this resumes.
    RaiseSignal(SIGSTOP);

    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Get current signal mask.
  sigset_t set;
  EXPECT_THAT(ptrace(kPtraceGetSigMask, child_pid, kSizeofKernelSigset, &set),
              SyscallSucceeds());
  EXPECT_THAT(blocked, EqualsSigset(set));

  // Try to get current signal mask with bad size argument.
  EXPECT_THAT(ptrace(kPtraceGetSigMask, child_pid, 0, nullptr),
              SyscallFailsWithErrno(EINVAL));

  // Try to set bad signal mask.
  sigset_t* bad_addr = reinterpret_cast<sigset_t*>(-1);
  EXPECT_THAT(
      ptrace(kPtraceSetSigMask, child_pid, kSizeofKernelSigset, bad_addr),
      SyscallFailsWithErrno(EFAULT));

  // Set signal mask to empty set.
  sigset_t set1;
  sigemptyset(&set1);
  EXPECT_THAT(ptrace(kPtraceSetSigMask, child_pid, kSizeofKernelSigset, &set1),
              SyscallSucceeds());

  // Suppress SIGSTOP and resume the child. It should re-enter
  // signal-delivery-stop for kBlockSignal.
  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == kBlockSignal)
      << " status " << status;

  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  // Let's see that process exited normally.
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

TEST(PtraceTest, GetSiginfo_SetSiginfo_SignalInjection) {
  constexpr int kOriginalSigno = SIGUSR1;
  constexpr int kInjectedSigno = SIGUSR2;

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Override all signal handlers.
    struct sigaction sa = {};
    sa.sa_handler = +[](int signo) { _exit(signo); };
    TEST_PCHECK(sigfillset(&sa.sa_mask) == 0);
    for (int signo = 1; signo < 32; signo++) {
      if (signo == SIGKILL || signo == SIGSTOP) {
        continue;
      }
      TEST_PCHECK(sigaction(signo, &sa, nullptr) == 0);
    }
    for (int signo = SIGRTMIN; signo <= SIGRTMAX; signo++) {
      TEST_PCHECK(sigaction(signo, &sa, nullptr) == 0);
    }

    // Unblock all signals.
    TEST_PCHECK(sigprocmask(SIG_UNBLOCK, &sa.sa_mask, nullptr) == 0);
    MaybeSave();

    // Send ourselves kOriginalSignal while ptraced and exit with the signal we
    // actually receive via the signal handler, if any, or 0 if we don't receive
    // a signal.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();
    RaiseSignal(kOriginalSigno);
    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself kOriginalSigno and enter
  // signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == kOriginalSigno)
      << " status " << status;

  siginfo_t siginfo = {};
  ASSERT_THAT(ptrace(PTRACE_GETSIGINFO, child_pid, 0, &siginfo),
              SyscallSucceeds());
  EXPECT_EQ(kOriginalSigno, siginfo.si_signo);
  EXPECT_EQ(SI_TKILL, siginfo.si_code);

  // Replace the signal with kInjectedSigno, and check that the child exits
  // with kInjectedSigno, indicating that signal injection was successful.
  siginfo.si_signo = kInjectedSigno;
  ASSERT_THAT(ptrace(PTRACE_SETSIGINFO, child_pid, 0, &siginfo),
              SyscallSucceeds());
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, kInjectedSigno),
              SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == kInjectedSigno)
      << " status " << status;
}

TEST(PtraceTest, SIGKILLDoesNotCauseSignalDeliveryStop) {
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();
    RaiseSignal(SIGKILL);
    TEST_CHECK_MSG(false, "Survived SIGKILL?");
    _exit(1);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Expect the child to die to SIGKILL without entering signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, PtraceKill) {
  constexpr int kOriginalSigno = SIGUSR1;

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();

    // PTRACE_KILL only works if tracee has entered signal-delivery-stop.
    RaiseSignal(kOriginalSigno);
    TEST_CHECK_MSG(false, "Failed to kill the process?");
    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself kOriginalSigno and enter
  // signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == kOriginalSigno)
      << " status " << status;

  ASSERT_THAT(ptrace(PTRACE_KILL, child_pid, 0, 0), SyscallSucceeds());

  // Expect the child to die with SIGKILL.
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, GetRegSet) {
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Enable tracing.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();

    // Use kill explicitly because we check the syscall argument register below.
    kill(getpid(), SIGSTOP);

    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Get the general registers.
  struct user_regs_struct regs;
  struct iovec iov;
  iov.iov_base = &regs;
  iov.iov_len = sizeof(regs);
  EXPECT_THAT(ptrace(PTRACE_GETREGSET, child_pid, NT_PRSTATUS, &iov),
              SyscallSucceeds());

  // Read exactly the full register set.
  EXPECT_EQ(iov.iov_len, sizeof(regs));

#if defined(__x86_64__)
  // Child called kill(2), with SIGSTOP as arg 2.
  EXPECT_EQ(regs.rsi, SIGSTOP);
#elif defined(__aarch64__)
  EXPECT_EQ(regs.regs[1], SIGSTOP);
#endif

  // Suppress SIGSTOP and resume the child.
  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  // Let's see that process exited normally.
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

TEST(PtraceTest, AttachingConvertsGroupStopToPtraceStop) {
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    while (true) {
      pause();
    }
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // SIGSTOP the child and wait for it to stop.
  ASSERT_THAT(kill(child_pid, SIGSTOP), SyscallSucceeds());
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, WUNTRACED),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Attach to the child and expect it to re-enter a traced group-stop despite
  // already being stopped.
  ASSERT_THAT(ptrace(PTRACE_ATTACH, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Verify that the child is ptrace-stopped by checking that it can receive
  // ptrace commands requiring a ptrace-stop.
  EXPECT_THAT(ptrace(PTRACE_SETOPTIONS, child_pid, 0, 0), SyscallSucceeds());

  // Group-stop is distinguished from signal-delivery-stop by PTRACE_GETSIGINFO
  // failing with EINVAL.
  siginfo_t siginfo = {};
  EXPECT_THAT(ptrace(PTRACE_GETSIGINFO, child_pid, 0, &siginfo),
              SyscallFailsWithErrno(EINVAL));

  // Detach from the child and expect it to stay stopped without a notification.
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, WUNTRACED | WNOHANG),
              SyscallSucceedsWithValue(0));

  // Sending it SIGCONT should cause it to leave its stop.
  ASSERT_THAT(kill(child_pid, SIGCONT), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, WCONTINUED),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFCONTINUED(status)) << " status " << status;

  // Clean up the child.
  ASSERT_THAT(kill(child_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

// Fixture for tests parameterized by whether or not to use PTRACE_O_TRACEEXEC.
class PtraceExecveTest : public ::testing::TestWithParam<bool> {
 protected:
  bool TraceExec() const { return GetParam(); }
};

TEST_P(PtraceExecveTest, Execve_GetRegs_PeekUser_SIGKILL_TraceClone_TraceExit) {
  ExecveArray const owned_child_argv = {"/proc/self/exe",
                                        "--ptrace_test_execve_child"};
  char* const* const child_argv = owned_child_argv.get();

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process. The test relies on calling execve() in a non-leader
    // thread; pthread_create() isn't async-signal-safe, so the safest way to
    // do this is to execve() first, then enable tracing and run the expected
    // child process behavior in the new subprocess.
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve to test child");
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Enable PTRACE_O_TRACECLONE so we can get the ID of the child's non-leader
  // thread, PTRACE_O_TRACEEXIT so we can observe the leader's death, and
  // PTRACE_O_TRACEEXEC if required by the test. (The leader doesn't call
  // execve, but options should be inherited across clone.)
  long opts = PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT;
  if (TraceExec()) {
    opts |= PTRACE_O_TRACEEXEC;
  }
  ASSERT_THAT(ptrace(PTRACE_SETOPTIONS, child_pid, 0, opts), SyscallSucceeds());

  // Suppress the SIGSTOP and wait for the child's leader thread to report
  // PTRACE_EVENT_CLONE. Get the new thread's ID from the event.
  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGTRAP | (PTRACE_EVENT_CLONE << 8), status >> 8);
  unsigned long eventmsg;
  ASSERT_THAT(ptrace(PTRACE_GETEVENTMSG, child_pid, 0, &eventmsg),
              SyscallSucceeds());
  pid_t const nonleader_tid = eventmsg;
  pid_t const leader_tid = child_pid;

  // The new thread should be ptraced and in signal-delivery-stop by SIGSTOP due
  // to PTRACE_O_TRACECLONE.
  //
  // Before bf959931ddb88c4e4366e96dd22e68fa0db9527c "wait/ptrace: assume __WALL
  // if the child is traced" (4.7) , waiting on it requires __WCLONE since, as a
  // non-leader, its termination signal is 0. After, a standard wait is
  // sufficient.
  ASSERT_THAT(waitpid(nonleader_tid, &status, __WCLONE),
              SyscallSucceedsWithValue(nonleader_tid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Resume both child threads.
  for (pid_t const tid : {leader_tid, nonleader_tid}) {
    ASSERT_THAT(ptrace(PTRACE_CONT, tid, 0, 0), SyscallSucceeds());
  }

  // The non-leader child thread should call execve, causing the leader thread
  // to enter PTRACE_EVENT_EXIT with an apparent exit code of 0. At this point,
  // the leader has not yet exited, so the non-leader should be blocked in
  // execve.
  ASSERT_THAT(waitpid(leader_tid, &status, 0),
              SyscallSucceedsWithValue(leader_tid));
  EXPECT_EQ(SIGTRAP | (PTRACE_EVENT_EXIT << 8), status >> 8);
  ASSERT_THAT(ptrace(PTRACE_GETEVENTMSG, leader_tid, 0, &eventmsg),
              SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(eventmsg) && WEXITSTATUS(eventmsg) == 0)
      << " eventmsg " << eventmsg;
  EXPECT_THAT(waitpid(nonleader_tid, &status, __WCLONE | WNOHANG),
              SyscallSucceedsWithValue(0));

  // Allow the leader to continue exiting. This should allow the non-leader to
  // complete its execve, causing the original leader to be reaped without
  // further notice and the non-leader to steal its ID.
  ASSERT_THAT(ptrace(PTRACE_CONT, leader_tid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(leader_tid, &status, 0),
              SyscallSucceedsWithValue(leader_tid));
  if (TraceExec()) {
    // If PTRACE_O_TRACEEXEC was enabled, the execing thread should be in
    // PTRACE_EVENT_EXEC-stop, with the event message set to its old thread ID.
    EXPECT_EQ(SIGTRAP | (PTRACE_EVENT_EXEC << 8), status >> 8);
    ASSERT_THAT(ptrace(PTRACE_GETEVENTMSG, leader_tid, 0, &eventmsg),
                SyscallSucceeds());
    EXPECT_EQ(nonleader_tid, eventmsg);
  } else {
    // Otherwise, the execing thread should have received SIGTRAP and should now
    // be in signal-delivery-stop.
    EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
        << " status " << status;
  }

#ifdef __x86_64__
  {
    // CS should be 0x33, indicating an 64-bit binary.
    constexpr uint64_t kAMD64UserCS = 0x33;
    EXPECT_THAT(ptrace(PTRACE_PEEKUSER, leader_tid,
                       offsetof(struct user_regs_struct, cs), 0),
                SyscallSucceedsWithValue(kAMD64UserCS));
    struct user_regs_struct regs = {};
    ASSERT_THAT(ptrace(PTRACE_GETREGS, leader_tid, 0, &regs),
                SyscallSucceeds());
    EXPECT_EQ(kAMD64UserCS, regs.cs);
  }
#endif  // defined(__x86_64__)

  // PTRACE_O_TRACEEXIT should have been inherited across execve. Send SIGKILL,
  // which should end the PTRACE_EVENT_EXEC-stop or signal-delivery-stop and
  // leave the child in PTRACE_EVENT_EXIT-stop.
  ASSERT_THAT(kill(leader_tid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(leader_tid, &status, 0),
              SyscallSucceedsWithValue(leader_tid));
  EXPECT_EQ(SIGTRAP | (PTRACE_EVENT_EXIT << 8), status >> 8);
  ASSERT_THAT(ptrace(PTRACE_GETEVENTMSG, leader_tid, 0, &eventmsg),
              SyscallSucceeds());
  EXPECT_TRUE(WIFSIGNALED(eventmsg) && WTERMSIG(eventmsg) == SIGKILL)
      << " eventmsg " << eventmsg;

  // End the PTRACE_EVENT_EXIT stop, allowing the child to exit.
  ASSERT_THAT(ptrace(PTRACE_CONT, leader_tid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(leader_tid, &status, 0),
              SyscallSucceedsWithValue(leader_tid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

[[noreturn]] void RunExecveChild() {
  // Enable tracing, then raise SIGSTOP and expect our parent to suppress it.
  TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
  MaybeSave();
  RaiseSignal(SIGSTOP);
  MaybeSave();

  // Call execve() in a non-leader thread. As long as execve() succeeds, what
  // exactly we execve() shouldn't really matter, since the tracer should kill
  // us after execve() completes.
  ScopedThread t([&] {
    ExecveArray const owned_child_argv = {"/proc/self/exe",
                                          "--this_flag_shouldnt_exist"};
    char* const* const child_argv = owned_child_argv.get();
    execve(child_argv[0], child_argv, /* envp = */ nullptr);
    TEST_PCHECK_MSG(false, "Survived execve? (thread)");
  });
  t.Join();
  TEST_CHECK_MSG(false, "Survived execve? (main)");
  _exit(1);
}

INSTANTIATE_TEST_SUITE_P(TraceExec, PtraceExecveTest, ::testing::Bool());

// This test has expectations on when syscall-enter/exit-stops occur that are
// violated if saving occurs, since saving interrupts all syscalls, causing
// premature syscall-exit.
TEST(PtraceTest, ExitWhenParentIsNotTracer_Syscall_TraceVfork_TraceVforkDone) {
  constexpr int kExitTraceeExitCode = 99;

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Block SIGCHLD so it doesn't interrupt wait4.
    sigset_t mask;
    TEST_PCHECK(sigemptyset(&mask) == 0);
    TEST_PCHECK(sigaddset(&mask, SIGCHLD) == 0);
    TEST_PCHECK(sigprocmask(SIG_SETMASK, &mask, nullptr) == 0);
    MaybeSave();

    // Enable tracing, then raise SIGSTOP and expect our parent to suppress it.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();
    RaiseSignal(SIGSTOP);
    MaybeSave();

    // Spawn a vfork child that exits immediately, and reap it. Don't save
    // after vfork since the parent expects to see wait4 as the next syscall.
    pid_t const pid = vfork();
    if (pid == 0) {
      _exit(kExitTraceeExitCode);
    }
    TEST_PCHECK_MSG(pid > 0, "vfork failed");

    int status;
    TEST_PCHECK(wait4(pid, &status, 0, nullptr) > 0);
    MaybeSave();
    TEST_CHECK(WIFEXITED(status) && WEXITSTATUS(status) == kExitTraceeExitCode);
    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(child_pid, SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Enable PTRACE_O_TRACEVFORK so we can get the ID of the grandchild,
  // PTRACE_O_TRACEVFORKDONE so we can observe PTRACE_EVENT_VFORK_DONE, and
  // PTRACE_O_TRACESYSGOOD so syscall-enter/exit-stops are unambiguously
  // indicated by a stop signal of SIGTRAP|0x80 rather than just SIGTRAP.
  ASSERT_THAT(ptrace(PTRACE_SETOPTIONS, child_pid, 0,
                     PTRACE_O_TRACEVFORK | PTRACE_O_TRACEVFORKDONE |
                         PTRACE_O_TRACESYSGOOD),
              SyscallSucceeds());

  // Suppress the SIGSTOP and wait for the child to report PTRACE_EVENT_VFORK.
  // Get the new process' ID from the event.
  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGTRAP | (PTRACE_EVENT_VFORK << 8), status >> 8);
  unsigned long eventmsg;
  ASSERT_THAT(ptrace(PTRACE_GETEVENTMSG, child_pid, 0, &eventmsg),
              SyscallSucceeds());
  pid_t const grandchild_pid = eventmsg;

  // The grandchild should be traced by us and in signal-delivery-stop by
  // SIGSTOP due to PTRACE_O_TRACEVFORK. This allows us to wait on it even
  // though we're not its parent.
  ASSERT_THAT(waitpid(grandchild_pid, &status, 0),
              SyscallSucceedsWithValue(grandchild_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Resume the child with PTRACE_SYSCALL. Since the grandchild is still in
  // signal-delivery-stop, the child should remain in vfork() waiting for the
  // grandchild to exec or exit.
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  absl::SleepFor(absl::Seconds(1));
  ASSERT_THAT(waitpid(child_pid, &status, WNOHANG),
              SyscallSucceedsWithValue(0));

  // Suppress the grandchild's SIGSTOP and wait for the grandchild to exit. Pass
  // WNOWAIT to waitid() so that we don't acknowledge the grandchild's exit yet.
  ASSERT_THAT(ptrace(PTRACE_CONT, grandchild_pid, 0, 0), SyscallSucceeds());
  siginfo_t siginfo = {};
  ASSERT_THAT(waitid(P_PID, grandchild_pid, &siginfo, WEXITED | WNOWAIT),
              SyscallSucceeds());
  EXPECT_EQ(SIGCHLD, siginfo.si_signo);
  EXPECT_EQ(CLD_EXITED, siginfo.si_code);
  EXPECT_EQ(kExitTraceeExitCode, siginfo.si_status);
  EXPECT_EQ(grandchild_pid, siginfo.si_pid);
  EXPECT_EQ(getuid(), siginfo.si_uid);

  // The child should now be in PTRACE_EVENT_VFORK_DONE stop. The event
  // message should still be the grandchild's PID.
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8), status >> 8);
  ASSERT_THAT(ptrace(PTRACE_GETEVENTMSG, child_pid, 0, &eventmsg),
              SyscallSucceeds());
  EXPECT_EQ(grandchild_pid, eventmsg);

  // Resume the child with PTRACE_SYSCALL again and expect it to enter
  // syscall-exit-stop for vfork() or clone(), either of which should return the
  // grandchild's PID from the syscall. Aside from PTRACE_O_TRACESYSGOOD,
  // syscall-stops are distinguished from signal-delivery-stop by
  // PTRACE_GETSIGINFO returning a siginfo for which si_code == SIGTRAP or
  // SIGTRAP|0x80.
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80))
      << " status " << status;
  ASSERT_THAT(ptrace(PTRACE_GETSIGINFO, child_pid, 0, &siginfo),
              SyscallSucceeds());
  EXPECT_TRUE(siginfo.si_code == SIGTRAP || siginfo.si_code == (SIGTRAP | 0x80))
      << "si_code = " << siginfo.si_code;

  {
    struct user_regs_struct regs = {};
    struct iovec iov;
    iov.iov_base = &regs;
    iov.iov_len = sizeof(regs);
    EXPECT_THAT(ptrace(PTRACE_GETREGSET, child_pid, NT_PRSTATUS, &iov),
                SyscallSucceeds());
#if defined(__x86_64__)
    EXPECT_TRUE(regs.orig_rax == SYS_vfork || regs.orig_rax == SYS_clone)
        << "orig_rax = " << regs.orig_rax;
    EXPECT_EQ(grandchild_pid, regs.rax);
#elif defined(__aarch64__)
    EXPECT_TRUE(regs.regs[8] == SYS_clone) << "regs[8] = " << regs.regs[8];
    EXPECT_EQ(grandchild_pid, regs.regs[0]);
#endif  // defined(__x86_64__)
  }

  // After this point, the child will be making wait4 syscalls that will be
  // interrupted by saving, so saving is not permitted. Note that this is
  // explicitly released below once the grandchild exits.
  DisableSave ds;

  // Resume the child with PTRACE_SYSCALL again and expect it to enter
  // syscall-enter-stop for wait4().
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80))
      << " status " << status;
  ASSERT_THAT(ptrace(PTRACE_GETSIGINFO, child_pid, 0, &siginfo),
              SyscallSucceeds());
  EXPECT_TRUE(siginfo.si_code == SIGTRAP || siginfo.si_code == (SIGTRAP | 0x80))
      << "si_code = " << siginfo.si_code;
#ifdef __x86_64__
  {
    EXPECT_THAT(ptrace(PTRACE_PEEKUSER, child_pid,
                       offsetof(struct user_regs_struct, orig_rax), 0),
                SyscallSucceedsWithValue(SYS_wait4));
  }
#endif  // defined(__x86_64__)

  // Resume the child with PTRACE_SYSCALL again. Since the grandchild is
  // waiting for the tracer (us) to acknowledge its exit first, wait4 should
  // block.
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  absl::SleepFor(absl::Seconds(1));
  ASSERT_THAT(waitpid(child_pid, &status, WNOHANG),
              SyscallSucceedsWithValue(0));

  // Acknowledge the grandchild's exit.
  ASSERT_THAT(waitpid(grandchild_pid, &status, 0),
              SyscallSucceedsWithValue(grandchild_pid));
  ds.reset();

  // Now the child should enter syscall-exit-stop for wait4, returning with the
  // grandchild's PID.
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80))
      << " status " << status;
  {
    struct user_regs_struct regs = {};
    struct iovec iov;
    iov.iov_base = &regs;
    iov.iov_len = sizeof(regs);
    EXPECT_THAT(ptrace(PTRACE_GETREGSET, child_pid, NT_PRSTATUS, &iov),
                SyscallSucceeds());
#if defined(__x86_64__)
    EXPECT_EQ(SYS_wait4, regs.orig_rax);
    EXPECT_EQ(grandchild_pid, regs.rax);
#elif defined(__aarch64__)
    EXPECT_EQ(SYS_wait4, regs.regs[8]);
    EXPECT_EQ(grandchild_pid, regs.regs[0]);
#endif  // defined(__x86_64__)
  }

  // Detach from the child and wait for it to exit.
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

// These tests requires knowledge of architecture-specific syscall convention.
#ifdef __x86_64__
TEST(PtraceTest, Int3) {
  SKIP_IF(PlatformSupportInt3() == PlatformSupport::NotSupported);

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Enable tracing.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);

    // Interrupt 3 - trap to debugger
    asm("int3");

    _exit(56);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
      << " status " << status;

  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());

  // The child should validate the injected return value and then exit normally.
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 56)
      << " status " << status;
}

TEST(PtraceTest, Sysemu_PokeUser) {
  constexpr int kSysemuHelperFirstExitCode = 126;
  constexpr uint64_t kSysemuInjectedExitGroupReturn = 42;

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Enable tracing, then raise SIGSTOP and expect our parent to suppress it.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    RaiseSignal(SIGSTOP);

    // Try to exit_group, expecting the tracer to skip the syscall and set its
    // own return value.
    int const rv = syscall(SYS_exit_group, kSysemuHelperFirstExitCode);
    TEST_PCHECK_MSG(rv == kSysemuInjectedExitGroupReturn,
                    "exit_group returned incorrect value");

    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Suppress the SIGSTOP and wait for the child to enter syscall-enter-stop
  // for its first exit_group syscall.
  ASSERT_THAT(ptrace(kPtraceSysemu, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
      << " status " << status;

  struct user_regs_struct regs = {};
  ASSERT_THAT(ptrace(PTRACE_GETREGS, child_pid, 0, &regs), SyscallSucceeds());
  EXPECT_EQ(SYS_exit_group, regs.orig_rax);
  EXPECT_EQ(-ENOSYS, regs.rax);
  EXPECT_EQ(kSysemuHelperFirstExitCode, regs.rdi);

  // Replace the exit_group return value, then resume the child, which should
  // automatically skip the syscall.
  ASSERT_THAT(
      ptrace(PTRACE_POKEUSER, child_pid, offsetof(struct user_regs_struct, rax),
             kSysemuInjectedExitGroupReturn),
      SyscallSucceeds());
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());

  // The child should validate the injected return value and then exit normally.
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

// This test also cares about syscall-exit-stop.
TEST(PtraceTest, ERESTART) {
  constexpr int kSigno = SIGUSR1;

  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.

    // Ignore, but unblock, kSigno.
    struct sigaction sa = {};
    sa.sa_handler = SIG_IGN;
    TEST_PCHECK(sigfillset(&sa.sa_mask) == 0);
    TEST_PCHECK(sigaction(kSigno, &sa, nullptr) == 0);
    MaybeSave();
    TEST_PCHECK(sigprocmask(SIG_UNBLOCK, &sa.sa_mask, nullptr) == 0);
    MaybeSave();

    // Enable tracing, then raise SIGSTOP and expect our parent to suppress it.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    RaiseSignal(SIGSTOP);

    // Invoke the pause syscall, which normally should not return until we
    // receive a signal that "either terminates the process or causes the
    // invocation of a signal-catching function".
    pause();

    _exit(0);
  }
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // After this point, the child's pause syscall will be interrupted by saving,
  // so saving is not permitted. Note that this is explicitly released below
  // once the child is stopped.
  DisableSave ds;

  // Suppress the SIGSTOP and wait for the child to enter syscall-enter-stop for
  // its pause syscall.
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
      << " status " << status;

  struct user_regs_struct regs = {};
  ASSERT_THAT(ptrace(PTRACE_GETREGS, child_pid, 0, &regs), SyscallSucceeds());
  EXPECT_EQ(SYS_pause, regs.orig_rax);
  EXPECT_EQ(-ENOSYS, regs.rax);

  // Resume the child with PTRACE_SYSCALL and expect it to block in the pause
  // syscall.
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  absl::SleepFor(absl::Seconds(1));
  ASSERT_THAT(waitpid(child_pid, &status, WNOHANG),
              SyscallSucceedsWithValue(0));

  // Send the child kSigno, causing it to return ERESTARTNOHAND and enter
  // syscall-exit-stop from the pause syscall.
  constexpr int ERESTARTNOHAND = 514;
  ASSERT_THAT(kill(child_pid, kSigno), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
      << " status " << status;
  ds.reset();

  ASSERT_THAT(ptrace(PTRACE_GETREGS, child_pid, 0, &regs), SyscallSucceeds());
  EXPECT_EQ(SYS_pause, regs.orig_rax);
  EXPECT_EQ(-ERESTARTNOHAND, regs.rax);

  // Replace the return value from pause with 0, causing pause to not be
  // restarted despite kSigno being ignored.
  ASSERT_THAT(ptrace(PTRACE_POKEUSER, child_pid,
                     offsetof(struct user_regs_struct, rax), 0),
              SyscallSucceeds());

  // Detach from the child and wait for it to exit.
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}
#endif  // defined(__x86_64__)

TEST(PtraceTest, Seize_Interrupt_Listen) {
  volatile long child_should_spin = 1;
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    while (child_should_spin) {
      SleepSafe(absl::Seconds(1));
    }
    _exit(1);
  }

  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Attach to the child with PTRACE_SEIZE; doing so should not stop the child.
  ASSERT_THAT(ptrace(PTRACE_SEIZE, child_pid, 0, 0), SyscallSucceeds());
  int status;
  EXPECT_THAT(waitpid(child_pid, &status, WNOHANG),
              SyscallSucceedsWithValue(0));

  // Stop the child with PTRACE_INTERRUPT.
  ASSERT_THAT(ptrace(PTRACE_INTERRUPT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGTRAP | (kPtraceEventStop << 8), status >> 8);

  // Unset child_should_spin to verify that the child never leaves the spin
  // loop.
  ASSERT_THAT(ptrace(PTRACE_POKEDATA, child_pid, &child_should_spin, 0),
              SyscallSucceeds());

  // Send SIGSTOP to the child, then resume it, allowing it to proceed to
  // signal-delivery-stop.
  ASSERT_THAT(kill(child_pid, SIGSTOP), SyscallSucceeds());
  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // Release the child from signal-delivery-stop without suppressing the
  // SIGSTOP, causing it to enter group-stop.
  ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, SIGSTOP), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGSTOP | (kPtraceEventStop << 8), status >> 8);

  // "The state of the tracee after PTRACE_LISTEN is somewhat of a gray area: it
  // is not in any ptrace-stop (ptrace commands won't work on it, and it will
  // deliver waitpid(2) notifications), but it also may be considered 'stopped'
  // because it is not executing instructions (is not scheduled), and if it was
  // in group-stop before PTRACE_LISTEN, it will not respond to signals until
  // SIGCONT is received." - ptrace(2).
  ASSERT_THAT(ptrace(PTRACE_LISTEN, child_pid, 0, 0), SyscallSucceeds());
  EXPECT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0),
              SyscallFailsWithErrno(ESRCH));
  EXPECT_THAT(waitpid(child_pid, &status, WNOHANG),
              SyscallSucceedsWithValue(0));
  EXPECT_THAT(kill(child_pid, SIGTERM), SyscallSucceeds());
  absl::SleepFor(absl::Seconds(1));
  EXPECT_THAT(waitpid(child_pid, &status, WNOHANG),
              SyscallSucceedsWithValue(0));

  // Send SIGCONT to the child, causing it to leave group-stop and re-trap due
  // to PTRACE_LISTEN.
  EXPECT_THAT(kill(child_pid, SIGCONT), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGTRAP | (kPtraceEventStop << 8), status >> 8);

  // Detach the child and expect it to exit due to the SIGTERM we sent while
  // it was stopped by PTRACE_LISTEN.
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM)
      << " status " << status;
}

TEST(PtraceTest, Interrupt_Listen_RequireSeize) {
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);
    MaybeSave();
    raise(SIGSTOP);
    _exit(0);
  }
  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
      << " status " << status;

  // PTRACE_INTERRUPT and PTRACE_LISTEN should fail since the child wasn't
  // attached with PTRACE_SEIZE, leaving the child in signal-delivery-stop.
  EXPECT_THAT(ptrace(PTRACE_INTERRUPT, child_pid, 0, 0),
              SyscallFailsWithErrno(EIO));
  EXPECT_THAT(ptrace(PTRACE_LISTEN, child_pid, 0, 0),
              SyscallFailsWithErrno(EIO));

  // Suppress SIGSTOP and detach from the child, expecting it to exit normally.
  ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;
}

TEST(PtraceTest, SeizeSetOptions) {
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    // In child process.
    while (true) {
      SleepSafe(absl::Seconds(1));
    }
  }

  // In parent process.
  ASSERT_THAT(child_pid, SyscallSucceeds());

  // Attach to the child with PTRACE_SEIZE while setting PTRACE_O_TRACESYSGOOD.
  ASSERT_THAT(ptrace(PTRACE_SEIZE, child_pid, 0, PTRACE_O_TRACESYSGOOD),
              SyscallSucceeds());

  // Stop the child with PTRACE_INTERRUPT.
  ASSERT_THAT(ptrace(PTRACE_INTERRUPT, child_pid, 0, 0), SyscallSucceeds());
  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_EQ(SIGTRAP | (kPtraceEventStop << 8), status >> 8);

  // Resume the child with PTRACE_SYSCALL and wait for it to enter
  // syscall-enter-stop. The stop signal status from the syscall stop should be
  // SIGTRAP|0x80, reflecting PTRACE_O_TRACESYSGOOD.
  ASSERT_THAT(ptrace(PTRACE_SYSCALL, child_pid, 0, 0), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80))
      << " status " << status;

  // Clean up the child.
  ASSERT_THAT(kill(child_pid, SIGKILL), SyscallSucceeds());
  ASSERT_THAT(waitpid(child_pid, &status, 0),
              SyscallSucceedsWithValue(child_pid));
  if (WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80)) {
    // "SIGKILL kills even within system calls (syscall-exit-stop is not
    // generated prior to death by SIGKILL). The net effect is that SIGKILL
    // always kills the process (all its threads), even if some threads of the
    // process are ptraced." - ptrace(2). This is technically true, but...
    //
    // When we send SIGKILL to the child, kernel/signal.c:complete_signal() =>
    // signal_wake_up(resume=1) kicks the tracee out of the syscall-enter-stop.
    // The pending SIGKILL causes the syscall to be skipped, but the child
    // thread still reports syscall-exit before checking for pending signals; in
    // current kernels, this is
    // arch/x86/entry/common.c:syscall_return_slowpath() =>
    // syscall_slow_exit_work() =>
    // include/linux/tracehook.h:tracehook_report_syscall_exit() =>
    // ptrace_report_syscall() => kernel/signal.c:ptrace_notify() =>
    // ptrace_do_notify() => ptrace_stop().
    //
    // ptrace_stop() sets the task's state to TASK_TRACED and the task's
    // exit_code to SIGTRAP|0x80 (passed by ptrace_report_syscall()), then calls
    // freezable_schedule(). freezable_schedule() eventually reaches
    // __schedule(), which detects signal_pending_state() due to the pending
    // SIGKILL, sets the task's state back to TASK_RUNNING, and returns without
    // descheduling. Thus, the task never enters syscall-exit-stop. However, if
    // our wait4() => kernel/exit.c:wait_task_stopped() racily observes the
    // TASK_TRACED state and the non-zero exit code set by ptrace_stop() before
    // __schedule() sets the state back to TASK_RUNNING, it will return the
    // task's exit_code as status W_STOPCODE(SIGTRAP|0x80). So we get a spurious
    // syscall-exit-stop notification, and need to wait4() again for task exit.
    //
    // gVisor is not susceptible to this race because
    // kernel.Task.waitCollectTraceeStopLocked() checks specifically for an
    // active ptraceStop, which is not initiated if SIGKILL is pending.
    std::cout << "Observed syscall-exit after SIGKILL" << std::endl;
    ASSERT_THAT(waitpid(child_pid, &status, 0),
                SyscallSucceedsWithValue(child_pid));
  }
  EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
      << " status " << status;
}

TEST(PtraceTest, SetYAMAPtraceScope) {
  SKIP_IF(IsRunningWithVFS1());

  // Do not modify the ptrace scope on the host.
  SKIP_IF(!IsRunningOnGvisor());
  SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));

  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(
      Open(std::string(kYamaPtraceScopePath), O_RDWR));

  ASSERT_THAT(write(fd.get(), "0", 1), SyscallSucceedsWithValue(1));

  ASSERT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceeds());
  std::vector<char> buf(10);
  EXPECT_THAT(read(fd.get(), buf.data(), buf.size()), SyscallSucceeds());
  EXPECT_STREQ(buf.data(), "0\n");

  // Test that a child can attach to its parent when ptrace_scope is 0.
  AutoCapability cap(CAP_SYS_PTRACE, false);
  pid_t const child_pid = fork();
  if (child_pid == 0) {
    TEST_PCHECK(CheckPtraceAttach(getppid()) == 0);
    _exit(0);
  }
  ASSERT_THAT(child_pid, SyscallSucceeds());

  int status;
  ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());
  EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
      << " status " << status;

  // Set ptrace_scope back to 1 (and try writing with a newline).
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceeds());
  ASSERT_THAT(write(fd.get(), "1\n", 2), SyscallSucceedsWithValue(2));

  ASSERT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceeds());
  EXPECT_THAT(read(fd.get(), buf.data(), buf.size()), SyscallSucceeds());
  EXPECT_STREQ(buf.data(), "1\n");
}

}  // namespace

}  // namespace testing
}  // namespace gvisor

int main(int argc, char** argv) {
  gvisor::testing::TestInit(&argc, &argv);

  if (absl::GetFlag(FLAGS_ptrace_test_execve_child)) {
    gvisor::testing::RunExecveChild();
  }

  int fd = absl::GetFlag(FLAGS_ptrace_test_fd);

  if (absl::GetFlag(FLAGS_ptrace_test_trace_descendants_allowed)) {
    gvisor::testing::RunTraceDescendantsAllowed(fd);
  }

  if (absl::GetFlag(FLAGS_ptrace_test_ptrace_attacher)) {
    gvisor::testing::RunPtraceAttacher(fd);
  }

  if (absl::GetFlag(FLAGS_ptrace_test_prctl_set_ptracer)) {
    gvisor::testing::RunPrctlSetPtracer(fd);
  }

  if (absl::GetFlag(
          FLAGS_ptrace_test_prctl_set_ptracer_and_exit_tracee_thread)) {
    gvisor::testing::RunPrctlSetPtracerPersistsPastTraceeThreadExit(fd);
  }

  if (absl::GetFlag(FLAGS_ptrace_test_prctl_set_ptracer_and_exec_non_leader)) {
    gvisor::testing::RunPrctlSetPtracerDoesNotPersistPastNonLeaderExec(
        fd);
  }

  if (absl::GetFlag(
          FLAGS_ptrace_test_prctl_set_ptracer_and_exit_tracer_thread)) {
    gvisor::testing::RunPrctlSetPtracerDoesNotPersistPastTracerThreadExit(
        absl::GetFlag(
            FLAGS_ptrace_test_prctl_set_ptracer_and_exit_tracer_thread_tid),
        fd);
  }

  if (absl::GetFlag(
          FLAGS_ptrace_test_prctl_set_ptracer_respects_tracer_thread_id)) {
    gvisor::testing::RunPrctlSetPtracerRespectsTracerThreadID(
        absl::GetFlag(
            FLAGS_ptrace_test_prctl_set_ptracer_respects_tracer_thread_id_tid),
        fd);
  }

  if (absl::GetFlag(FLAGS_ptrace_test_tracee)) {
    gvisor::testing::RunTracee(fd);
  }

  int pid = absl::GetFlag(FLAGS_ptrace_test_trace_tid);
  if (pid != -1) {
    gvisor::testing::RunTraceTID(pid, fd);
  }

  return gvisor::testing::RunAllTests();
}