summaryrefslogtreecommitdiffhomepage
path: root/test/syscalls/linux/inotify.cc
blob: e2622232d7a36d58ebe2e73e429b3c242fb396d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
// 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 <fcntl.h>
#include <libgen.h>
#include <sched.h>
#include <sys/epoll.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/sendfile.h>
#include <sys/time.h>
#include <sys/xattr.h>

#include <atomic>
#include <list>
#include <string>
#include <vector>

#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/util/epoll_util.h"
#include "test/util/file_descriptor.h"
#include "test/util/fs_util.h"
#include "test/util/multiprocess_util.h"
#include "test/util/posix_error.h"
#include "test/util/temp_path.h"
#include "test/util/test_util.h"
#include "test/util/thread_util.h"

namespace gvisor {
namespace testing {
namespace {

using ::absl::StreamFormat;
using ::absl::StrFormat;

constexpr int kBufSize = 1024;

// C++-friendly version of struct inotify_event.
struct Event {
  int32_t wd;
  uint32_t mask;
  uint32_t cookie;
  uint32_t len;
  std::string name;

  Event(uint32_t mask, int32_t wd, absl::string_view name, uint32_t cookie)
      : wd(wd),
        mask(mask),
        cookie(cookie),
        len(name.size()),
        name(std::string(name)) {}
  Event(uint32_t mask, int32_t wd, absl::string_view name)
      : Event(mask, wd, name, 0) {}
  Event(uint32_t mask, int32_t wd) : Event(mask, wd, "", 0) {}
  Event() : Event(0, 0, "", 0) {}
};

// Prints the symbolic name for a struct inotify_event's 'mask' field.
std::string FlagString(uint32_t flags) {
  std::vector<std::string> names;

#define EMIT(target)          \
  if (flags & target) {       \
    names.push_back(#target); \
    flags &= ~target;         \
  }

  EMIT(IN_ACCESS);
  EMIT(IN_ATTRIB);
  EMIT(IN_CLOSE_WRITE);
  EMIT(IN_CLOSE_NOWRITE);
  EMIT(IN_CREATE);
  EMIT(IN_DELETE);
  EMIT(IN_DELETE_SELF);
  EMIT(IN_MODIFY);
  EMIT(IN_MOVE_SELF);
  EMIT(IN_MOVED_FROM);
  EMIT(IN_MOVED_TO);
  EMIT(IN_OPEN);

  EMIT(IN_DONT_FOLLOW);
  EMIT(IN_EXCL_UNLINK);
  EMIT(IN_ONESHOT);
  EMIT(IN_ONLYDIR);

  EMIT(IN_IGNORED);
  EMIT(IN_ISDIR);
  EMIT(IN_Q_OVERFLOW);
  EMIT(IN_UNMOUNT);

#undef EMIT

  // If we have anything left over at the end, print it as a hex value.
  if (flags) {
    names.push_back(absl::StrCat("0x", absl::Hex(flags)));
  }

  return absl::StrJoin(names, "|");
}

std::string DumpEvent(const Event& event) {
  return StrFormat(
      "%s, wd=%d%s%s", FlagString(event.mask), event.wd,
      (event.len > 0) ? StrFormat(", name=%s", event.name) : "",
      (event.cookie > 0) ? StrFormat(", cookie=%ud", event.cookie) : "");
}

std::string DumpEvents(const std::vector<Event>& events, int indent_level) {
  std::stringstream ss;
  ss << StreamFormat("%d event%s:\n", events.size(),
                     (events.size() > 1) ? "s" : "");
  int i = 0;
  for (const Event& ev : events) {
    ss << StreamFormat("%sevents[%d]: %s\n", std::string(indent_level, '\t'),
                       i++, DumpEvent(ev));
  }
  return ss.str();
}

// A matcher which takes an expected list of events to match against another
// list of inotify events, in order. This is similar to the ElementsAre matcher,
// but displays more informative messages on mismatch.
class EventsAreMatcher
    : public ::testing::MatcherInterface<std::vector<Event>> {
 public:
  explicit EventsAreMatcher(std::vector<Event> references)
      : references_(std::move(references)) {}

  bool MatchAndExplain(
      std::vector<Event> events,
      ::testing::MatchResultListener* const listener) const override {
    if (references_.size() != events.size()) {
      *listener << StreamFormat("\n\tCount mismatch, got %s",
                                DumpEvents(events, 2));
      return false;
    }

    bool success = true;
    for (unsigned int i = 0; i < references_.size(); ++i) {
      const Event& reference = references_[i];
      const Event& target = events[i];

      if (target.mask != reference.mask || target.wd != reference.wd ||
          target.name != reference.name || target.cookie != reference.cookie) {
        *listener << StreamFormat("\n\tMismatch at index %d, want %s, got %s,",
                                  i, DumpEvent(reference), DumpEvent(target));
        success = false;
      }
    }

    if (!success) {
      *listener << StreamFormat("\n\tIn total of %s", DumpEvents(events, 2));
    }
    return success;
  }

  void DescribeTo(::std::ostream* const os) const override {
    *os << StreamFormat("%s", DumpEvents(references_, 1));
  }

  void DescribeNegationTo(::std::ostream* const os) const override {
    *os << StreamFormat("mismatch from %s", DumpEvents(references_, 1));
  }

 private:
  std::vector<Event> references_;
};

::testing::Matcher<std::vector<Event>> Are(std::vector<Event> events) {
  return MakeMatcher(new EventsAreMatcher(std::move(events)));
}

// Similar to the EventsAre matcher, but the order of events are ignored.
class UnorderedEventsAreMatcher
    : public ::testing::MatcherInterface<std::vector<Event>> {
 public:
  explicit UnorderedEventsAreMatcher(std::vector<Event> references)
      : references_(std::move(references)) {}

  bool MatchAndExplain(
      std::vector<Event> events,
      ::testing::MatchResultListener* const listener) const override {
    if (references_.size() != events.size()) {
      *listener << StreamFormat("\n\tCount mismatch, got %s",
                                DumpEvents(events, 2));
      return false;
    }

    std::vector<Event> unmatched(references_);

    for (const Event& candidate : events) {
      for (auto it = unmatched.begin(); it != unmatched.end();) {
        const Event& reference = *it;
        if (candidate.mask == reference.mask && candidate.wd == reference.wd &&
            candidate.name == reference.name &&
            candidate.cookie == reference.cookie) {
          it = unmatched.erase(it);
          break;
        } else {
          ++it;
        }
      }
    }

    // Anything left unmatched? If so, the matcher fails.
    if (!unmatched.empty()) {
      *listener << StreamFormat("\n\tFailed to match %s",
                                DumpEvents(unmatched, 2));
      *listener << StreamFormat("\n\tIn total of %s", DumpEvents(events, 2));
      return false;
    }

    return true;
  }

  void DescribeTo(::std::ostream* const os) const override {
    *os << StreamFormat("unordered %s", DumpEvents(references_, 1));
  }

  void DescribeNegationTo(::std::ostream* const os) const override {
    *os << StreamFormat("mismatch from unordered %s",
                        DumpEvents(references_, 1));
  }

 private:
  std::vector<Event> references_;
};

::testing::Matcher<std::vector<Event>> AreUnordered(std::vector<Event> events) {
  return MakeMatcher(new UnorderedEventsAreMatcher(std::move(events)));
}

// Reads events from an inotify fd until either EOF, or read returns EAGAIN.
PosixErrorOr<std::vector<Event>> DrainEvents(int fd) {
  std::vector<Event> events;
  while (true) {
    int events_size = 0;
    if (ioctl(fd, FIONREAD, &events_size) < 0) {
      return PosixError(errno, "ioctl(FIONREAD) failed on inotify fd");
    }
    // Deliberately use a buffer that is larger than necessary, expecting to
    // only read events_size bytes.
    std::vector<char> buf(events_size + kBufSize, 0);
    const ssize_t readlen = read(fd, buf.data(), buf.size());
    MaybeSave();
    // Read error?
    if (readlen < 0) {
      if (errno == EAGAIN) {
        // If EAGAIN, no more events at the moment. Return what we have so far.
        return events;
      }
      // Some other read error. Return an error. Right now if we encounter this
      // after already reading some events, they get lost. However, we don't
      // expect to see any error, and the calling test will fail immediately if
      // we signal an error anyways, so this is acceptable.
      return PosixError(errno, "read() failed on inotify fd");
    }
    if (readlen < static_cast<int>(sizeof(struct inotify_event))) {
      // Impossibly short read.
      return PosixError(
          EIO,
          "read() didn't return enough data represent even a single event");
    }
    if (readlen != events_size) {
      return PosixError(EINVAL, absl::StrCat("read ", readlen,
                                             " bytes, expected ", events_size));
    }
    if (readlen == 0) {
      // EOF.
      return events;
    }

    // Normal read.
    const char* cursor = buf.data();
    while (cursor < (buf.data() + readlen)) {
      struct inotify_event event = {};
      memcpy(&event, cursor, sizeof(struct inotify_event));

      Event ev;
      ev.wd = event.wd;
      ev.mask = event.mask;
      ev.cookie = event.cookie;
      ev.len = event.len;
      if (event.len > 0) {
        TEST_CHECK(static_cast<int>(sizeof(struct inotify_event) + event.len) <=
                   readlen);
        ev.name = std::string(cursor +
                              offsetof(struct inotify_event, name));  // NOLINT
        // Name field should always be smaller than event.len, otherwise we have
        // a buffer overflow. The two sizes aren't equal because the string
        // constructor will stop at the first null byte, while event.name may be
        // padded up to event.len using multiple null bytes.
        TEST_CHECK(ev.name.size() <= event.len);
      }

      events.push_back(ev);
      cursor += sizeof(struct inotify_event) + event.len;
    }
  }
}

PosixErrorOr<FileDescriptor> InotifyInit1(int flags) {
  int fd = inotify_init1(flags);
  if (fd < 0) {
    return PosixError(errno, "inotify_init1() failed");
  }
  return FileDescriptor(fd);
}

PosixErrorOr<int> InotifyAddWatch(int fd, const std::string& path,
                                  uint32_t mask) {
  int wd = inotify_add_watch(fd, path.c_str(), mask);
  if (wd < 0) {
    return PosixError(errno, "inotify_add_watch() failed");
  }
  return wd;
}

TEST(Inotify, IllegalSeek) {
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(0));
  EXPECT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallFailsWithErrno(ESPIPE));
}

TEST(Inotify, IllegalPread) {
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(0));
  int val;
  EXPECT_THAT(pread(fd.get(), &val, sizeof(val), 0),
              SyscallFailsWithErrno(ESPIPE));
}

TEST(Inotify, IllegalPwrite) {
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(0));
  EXPECT_THAT(pwrite(fd.get(), "x", 1, 0), SyscallFailsWithErrno(ESPIPE));
}

TEST(Inotify, IllegalWrite) {
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(0));
  int val = 0;
  EXPECT_THAT(write(fd.get(), &val, sizeof(val)), SyscallFailsWithErrno(EBADF));
}

TEST(Inotify, InitFlags) {
  EXPECT_THAT(inotify_init1(IN_NONBLOCK | IN_CLOEXEC), SyscallSucceeds());
  EXPECT_THAT(inotify_init1(12345), SyscallFailsWithErrno(EINVAL));
}

TEST(Inotify, NonBlockingReadReturnsEagain) {
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  std::vector<char> buf(kBufSize, 0);

  // The read below should return fail with EAGAIN because there is no data to
  // read and we've specified IN_NONBLOCK. We're guaranteed that there is no
  // data to read because we haven't registered any watches yet.
  EXPECT_THAT(read(fd.get(), buf.data(), buf.size()),
              SyscallFailsWithErrno(EAGAIN));
}

TEST(Inotify, AddWatchOnInvalidFdFails) {
  // Garbage fd.
  EXPECT_THAT(inotify_add_watch(-1, "/tmp", IN_ALL_EVENTS),
              SyscallFailsWithErrno(EBADF));
  EXPECT_THAT(inotify_add_watch(1337, "/tmp", IN_ALL_EVENTS),
              SyscallFailsWithErrno(EBADF));

  // Non-inotify fds.
  EXPECT_THAT(inotify_add_watch(0, "/tmp", IN_ALL_EVENTS),
              SyscallFailsWithErrno(EINVAL));
  EXPECT_THAT(inotify_add_watch(1, "/tmp", IN_ALL_EVENTS),
              SyscallFailsWithErrno(EINVAL));
  EXPECT_THAT(inotify_add_watch(2, "/tmp", IN_ALL_EVENTS),
              SyscallFailsWithErrno(EINVAL));
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open("/tmp", O_RDONLY));
  EXPECT_THAT(inotify_add_watch(fd.get(), "/tmp", IN_ALL_EVENTS),
              SyscallFailsWithErrno(EINVAL));
}

TEST(Inotify, RemovingWatchGeneratesEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  EXPECT_THAT(inotify_rm_watch(fd.get(), wd), SyscallSucceeds());

  // Read events, ensure the first event is IN_IGNORED.
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_THAT(events, Are({Event(IN_IGNORED, wd)}));
}

TEST(Inotify, CanDeleteFileAfterRemovingWatch) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  EXPECT_THAT(inotify_rm_watch(fd.get(), wd), SyscallSucceeds());
  file1.reset();
}

TEST(Inotify, RemoveWatchAfterDeletingFileFails) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  file1.reset();
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ATTRIB, wd), Event(IN_DELETE_SELF, wd),
                           Event(IN_IGNORED, wd)}));

  EXPECT_THAT(inotify_rm_watch(fd.get(), wd), SyscallFailsWithErrno(EINVAL));
}

TEST(Inotify, DuplicateWatchRemovalFails) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  EXPECT_THAT(inotify_rm_watch(fd.get(), wd), SyscallSucceeds());
  EXPECT_THAT(inotify_rm_watch(fd.get(), wd), SyscallFailsWithErrno(EINVAL));
}

TEST(Inotify, ConcurrentFileDeletionAndWatchRemoval) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const std::string filename = NewTempAbsPathInDir(root.path());

  auto file_create_delete = [filename]() {
    const DisableSave ds;  // Too expensive.
    for (int i = 0; i < 100; ++i) {
      FileDescriptor file_fd =
          ASSERT_NO_ERRNO_AND_VALUE(Open(filename, O_CREAT, S_IRUSR | S_IWUSR));
      // Close before unlinking (although S/R is disabled). Some filesystems
      // cannot restore an open fd on an unlinked file.
      file_fd.reset();
      EXPECT_THAT(unlink(filename.c_str()), SyscallSucceeds());
    }
  };

  const int shared_fd = fd.get();  // We need to pass it to the thread.
  auto add_remove_watch = [shared_fd, filename]() {
    for (int i = 0; i < 100; ++i) {
      int wd = inotify_add_watch(shared_fd, filename.c_str(), IN_ALL_EVENTS);
      MaybeSave();
      if (wd != -1) {
        // Watch added successfully, try removal.
        if (inotify_rm_watch(shared_fd, wd)) {
          // If removal fails, the only acceptable reason is if the wd
          // is invalid, which will be the case if we try to remove
          // the watch after the file has been deleted.
          EXPECT_EQ(errno, EINVAL);
        }
      } else {
        // Add watch failed, this should only fail if the target file doesn't
        // exist.
        EXPECT_EQ(errno, ENOENT);
      }
    }
  };

  ScopedThread t1(file_create_delete);
  ScopedThread t2(add_remove_watch);
}

TEST(Inotify, DeletingChildGeneratesEvents) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  const std::string file1_path = file1.reset();

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      AreUnordered({Event(IN_ATTRIB, file1_wd), Event(IN_DELETE_SELF, file1_wd),
                    Event(IN_IGNORED, file1_wd),
                    Event(IN_DELETE, root_wd, Basename(file1_path))}));
}

// Creating a file in "parent/child" should generate events for child, but not
// parent.
TEST(Inotify, CreatingFileGeneratesEvents) {
  const TempPath parent = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath child =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(parent.path()));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), parent.path(), IN_ALL_EVENTS));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), child.path(), IN_ALL_EVENTS));

  // Create a new file in the directory.
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(child.path()));
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));

  // The library function we use to create the new file opens it for writing to
  // create it and sets permissions on it, so we expect the three extra events.
  ASSERT_THAT(events, Are({Event(IN_CREATE, wd, Basename(file1.path())),
                           Event(IN_OPEN, wd, Basename(file1.path())),
                           Event(IN_CLOSE_WRITE, wd, Basename(file1.path())),
                           Event(IN_ATTRIB, wd, Basename(file1.path()))}));
}

TEST(Inotify, ReadingFileGeneratesAccessEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), "some content", TempPath::kDefaultFileMode));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  char buf;
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_ACCESS, wd, Basename(file1.path()))}));
}

TEST(Inotify, WritingFileGeneratesModifyEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  const std::string data = "some content";
  EXPECT_THAT(write(file1_fd.get(), data.c_str(), data.length()),
              SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_MODIFY, wd, Basename(file1.path()))}));
}

TEST(Inotify, SizeZeroReadWriteGeneratesNothing) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDWR));
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  // Read from the empty file.
  int val;
  ASSERT_THAT(read(file1_fd.get(), &val, sizeof(val)),
              SyscallSucceedsWithValue(0));

  // Write zero bytes.
  ASSERT_THAT(write(file1_fd.get(), "", 0), SyscallSucceedsWithValue(0));

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({}));
}

TEST(Inotify, FailedFileCreationGeneratesNoEvents) {
  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const std::string dir_path = dir.path();
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(fd.get(), dir_path, IN_ALL_EVENTS));

  const char* p = dir_path.c_str();
  ASSERT_THAT(mkdir(p, 0777), SyscallFails());
  ASSERT_THAT(mknod(p, S_IFIFO, 0777), SyscallFails());
  ASSERT_THAT(symlink(p, p), SyscallFails());
  ASSERT_THAT(link(p, p), SyscallFails());
  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({}));
}

TEST(Inotify, WatchSetAfterOpenReportsCloseFdEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  FileDescriptor file1_fd_writable =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));
  FileDescriptor file1_fd_not_writable =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  file1_fd_writable.reset();  // Close file1_fd_writable.
  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_CLOSE_WRITE, wd, Basename(file1.path()))}));

  file1_fd_not_writable.reset();  // Close file1_fd_not_writable.
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events,
              Are({Event(IN_CLOSE_NOWRITE, wd, Basename(file1.path()))}));
}

TEST(Inotify, ChildrenDeletionInWatchedDirGeneratesEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  TempPath dir1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  const std::string file1_path = file1.reset();
  const std::string dir1_path = dir1.release();
  EXPECT_THAT(rmdir(dir1_path.c_str()), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));

  ASSERT_THAT(events,
              Are({Event(IN_DELETE, wd, Basename(file1_path)),
                   Event(IN_DELETE | IN_ISDIR, wd, Basename(dir1_path))}));
}

TEST(Inotify, RmdirOnWatchedTargetGeneratesEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  EXPECT_THAT(rmdir(root.path().c_str()), SyscallSucceeds());
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_DELETE_SELF, wd), Event(IN_IGNORED, wd)}));
}

TEST(Inotify, MoveGeneratesEvents) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const TempPath dir1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));
  const TempPath dir2 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int dir1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), dir1.path(), IN_ALL_EVENTS));
  const int dir2_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), dir2.path(), IN_ALL_EVENTS));
  // Test move from root -> root.
  std::string newpath = NewTempAbsPathInDir(root.path());
  std::string oldpath = file1.release();
  EXPECT_THAT(rename(oldpath.c_str(), newpath.c_str()), SyscallSucceeds());
  file1.reset(newpath);
  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      Are({Event(IN_MOVED_FROM, root_wd, Basename(oldpath), events[0].cookie),
           Event(IN_MOVED_TO, root_wd, Basename(newpath), events[1].cookie)}));
  EXPECT_NE(events[0].cookie, 0);
  EXPECT_EQ(events[0].cookie, events[1].cookie);
  uint32_t last_cookie = events[0].cookie;

  // Test move from root -> root/dir1.
  newpath = NewTempAbsPathInDir(dir1.path());
  oldpath = file1.release();
  EXPECT_THAT(rename(oldpath.c_str(), newpath.c_str()), SyscallSucceeds());
  file1.reset(newpath);
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      Are({Event(IN_MOVED_FROM, root_wd, Basename(oldpath), events[0].cookie),
           Event(IN_MOVED_TO, dir1_wd, Basename(newpath), events[1].cookie)}));
  // Cookies should be distinct between distinct rename events.
  EXPECT_NE(events[0].cookie, last_cookie);
  EXPECT_EQ(events[0].cookie, events[1].cookie);
  last_cookie = events[0].cookie;

  // Test move from root/dir1 -> root/dir2.
  newpath = NewTempAbsPathInDir(dir2.path());
  oldpath = file1.release();
  EXPECT_THAT(rename(oldpath.c_str(), newpath.c_str()), SyscallSucceeds());
  file1.reset(newpath);
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      Are({Event(IN_MOVED_FROM, dir1_wd, Basename(oldpath), events[0].cookie),
           Event(IN_MOVED_TO, dir2_wd, Basename(newpath), events[1].cookie)}));
  EXPECT_NE(events[0].cookie, last_cookie);
  EXPECT_EQ(events[0].cookie, events[1].cookie);
  last_cookie = events[0].cookie;
}

TEST(Inotify, MoveWatchedTargetGeneratesEvents) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  const std::string newpath = NewTempAbsPathInDir(root.path());
  const std::string oldpath = file1.release();
  EXPECT_THAT(rename(oldpath.c_str(), newpath.c_str()), SyscallSucceeds());
  file1.reset(newpath);
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      Are({Event(IN_MOVED_FROM, root_wd, Basename(oldpath), events[0].cookie),
           Event(IN_MOVED_TO, root_wd, Basename(newpath), events[1].cookie),
           // Self move events do not have a cookie.
           Event(IN_MOVE_SELF, file1_wd)}));
  EXPECT_NE(events[0].cookie, 0);
  EXPECT_EQ(events[0].cookie, events[1].cookie);
}

// Tests that close events are only emitted when a file description drops its
// last reference.
TEST(Inotify, DupFD) {
  SKIP_IF(IsRunningWithVFS1());

  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));

  FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));
  FileDescriptor fd2 = ASSERT_NO_ERRNO_AND_VALUE(fd.Dup());

  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_OPEN, wd),
                      }));

  fd.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({}));

  fd2.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_CLOSE_NOWRITE, wd),
                      }));
}

TEST(Inotify, CoalesceEvents) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), "some content", TempPath::kDefaultFileMode));

  FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  // Read the file a few times. This will would generate multiple IN_ACCESS
  // events but they should get coalesced to a single event.
  char buf;
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());

  // Use the close event verify that we haven't simply left the additional
  // IN_ACCESS events unread.
  file1_fd.reset();  // Close file1_fd.

  const std::string file1_name = std::string(Basename(file1.path()));
  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_ACCESS, wd, file1_name),
                           Event(IN_CLOSE_NOWRITE, wd, file1_name)}));

  // Now let's try interleaving other events into a stream of repeated events.
  file1_fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDWR));

  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(write(file1_fd.get(), "x", 1), SyscallSucceeds());
  EXPECT_THAT(write(file1_fd.get(), "x", 1), SyscallSucceeds());
  EXPECT_THAT(write(file1_fd.get(), "x", 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());

  file1_fd.reset();  // Close the file.

  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      Are({Event(IN_OPEN, wd, file1_name), Event(IN_ACCESS, wd, file1_name),
           Event(IN_MODIFY, wd, file1_name), Event(IN_ACCESS, wd, file1_name),
           Event(IN_CLOSE_WRITE, wd, file1_name)}));

  // Ensure events aren't coalesced if they are from different files.
  const TempPath file2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), "some content", TempPath::kDefaultFileMode));
  // Discard events resulting from creation of file2.
  ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));

  file1_fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));
  FileDescriptor file2_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file2.path(), O_RDONLY));

  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file2_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());

  // Close both files.
  file1_fd.reset();
  file2_fd.reset();

  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  const std::string file2_name = std::string(Basename(file2.path()));
  ASSERT_THAT(
      events,
      Are({Event(IN_OPEN, wd, file1_name), Event(IN_OPEN, wd, file2_name),
           Event(IN_ACCESS, wd, file1_name), Event(IN_ACCESS, wd, file2_name),
           Event(IN_ACCESS, wd, file1_name),
           Event(IN_CLOSE_NOWRITE, wd, file1_name),
           Event(IN_CLOSE_NOWRITE, wd, file2_name)}));
}

TEST(Inotify, ClosingInotifyFdWithoutRemovingWatchesWorks) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));

  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));
  // Note: The check on close will happen in FileDescriptor::~FileDescriptor().
}

TEST(Inotify, NestedWatches) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), "some content", TempPath::kDefaultFileMode));
  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  // Read from file1. This should generate an event for both watches.
  char buf;
  EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_ACCESS, root_wd, Basename(file1.path())),
                           Event(IN_ACCESS, file1_wd)}));
}

TEST(Inotify, ConcurrentThreadsGeneratingEvents) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  std::vector<TempPath> files;
  files.reserve(10);
  for (int i = 0; i < 10; i++) {
    files.emplace_back(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
        root.path(), "some content", TempPath::kDefaultFileMode)));
  }

  auto test_thread = [&files]() {
    uint32_t seed = time(nullptr);
    for (int i = 0; i < 20; i++) {
      const TempPath& file = files[rand_r(&seed) % files.size()];
      const FileDescriptor file_fd =
          ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_WRONLY));
      TEST_PCHECK(write(file_fd.get(), "x", 1) == 1);
    }
  };

  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  std::list<ScopedThread> threads;
  for (int i = 0; i < 3; i++) {
    threads.emplace_back(test_thread);
  }
  for (auto& t : threads) {
    t.Join();
  }

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  // 3 threads doing 20 iterations, 3 events per iteration (open, write,
  // close). However, some events may be coalesced, and we can't reliably
  // predict how they'll be coalesced since the test threads aren't
  // synchronized. We can only check that we aren't getting unexpected events.
  for (const Event& ev : events) {
    EXPECT_NE(ev.mask & (IN_OPEN | IN_MODIFY | IN_CLOSE_WRITE), 0);
  }
}

TEST(Inotify, ReadWithTooSmallBufferFails) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  // Open the file to queue an event. This event will not have a filename, so
  // reading from the inotify fd should return sizeof(struct inotify_event)
  // bytes of data.
  FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));
  std::vector<char> buf(kBufSize, 0);
  ssize_t readlen;

  // Try a buffer too small to hold any potential event. This is rejected
  // outright without the event being dequeued.
  EXPECT_THAT(read(fd.get(), buf.data(), sizeof(struct inotify_event) - 1),
              SyscallFailsWithErrno(EINVAL));
  // Try a buffer just large enough. This should succeeed.
  EXPECT_THAT(
      readlen = read(fd.get(), buf.data(), sizeof(struct inotify_event)),
      SyscallSucceeds());
  EXPECT_EQ(readlen, sizeof(struct inotify_event));
  // Event queue is now empty, the next read should return EAGAIN.
  EXPECT_THAT(read(fd.get(), buf.data(), sizeof(struct inotify_event)),
              SyscallFailsWithErrno(EAGAIN));

  // Now put a watch on the directory, so that generated events contain a name.
  EXPECT_THAT(inotify_rm_watch(fd.get(), wd), SyscallSucceeds());

  // Drain the event generated from the watch removal.
  ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));

  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  file1_fd.reset();  // Close file to generate an event.

  // Try a buffer too small to hold any event and one too small to hold an event
  // with a name. These should both fail without consuming the event.
  EXPECT_THAT(read(fd.get(), buf.data(), sizeof(struct inotify_event) - 1),
              SyscallFailsWithErrno(EINVAL));
  EXPECT_THAT(read(fd.get(), buf.data(), sizeof(struct inotify_event)),
              SyscallFailsWithErrno(EINVAL));
  // Now try with a large enough buffer. This should return the one event.
  EXPECT_THAT(readlen = read(fd.get(), buf.data(), buf.size()),
              SyscallSucceeds());
  EXPECT_GE(readlen,
            sizeof(struct inotify_event) + Basename(file1.path()).size());
  // With the single event read, the queue should once again be empty.
  EXPECT_THAT(read(fd.get(), buf.data(), sizeof(struct inotify_event)),
              SyscallFailsWithErrno(EAGAIN));
}

TEST(Inotify, BlockingReadOnInotifyFd) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(0));
  const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), "some content", TempPath::kDefaultFileMode));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));

  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  // Spawn a thread performing a blocking read for new events on the inotify fd.
  std::vector<char> buf(kBufSize, 0);
  const int shared_fd = fd.get();  // The thread needs it.
  ScopedThread t([shared_fd, &buf]() {
    ssize_t readlen;
    EXPECT_THAT(readlen = read(shared_fd, buf.data(), buf.size()),
                SyscallSucceeds());
  });

  // Perform a read on the watched file, which should generate an IN_ACCESS
  // event, unblocking the event_reader thread.
  char c;
  EXPECT_THAT(read(file1_fd.get(), &c, 1), SyscallSucceeds());

  // Wait for the thread to read the event and exit.
  t.Join();

  // Make sure the event we got back is sane.
  uint32_t event_mask;
  memcpy(&event_mask, buf.data() + offsetof(struct inotify_event, mask),
         sizeof(event_mask));
  EXPECT_EQ(event_mask, IN_ACCESS);
}

TEST(Inotify, WatchOnRelativePath) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), "some content", TempPath::kDefaultFileMode));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));

  // Change working directory to root.
  const FileDescriptor cwd = ASSERT_NO_ERRNO_AND_VALUE(Open(".", O_PATH));
  EXPECT_THAT(chdir(root.path().c_str()), SyscallSucceeds());

  // Add a watch on file1 with a relative path.
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      fd.get(), std::string(Basename(file1.path())), IN_ALL_EVENTS));

  // Perform a read on file1, this should generate an IN_ACCESS event.
  char c;
  EXPECT_THAT(read(file1_fd.get(), &c, 1), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ACCESS, wd)}));

  // Explicitly reset the working directory so that we don't continue to
  // reference "root". Once the test ends, "root" will get unlinked. If we
  // continue to hold a reference, random save/restore tests can fail if a save
  // is triggered after "root" is unlinked; we can't save deleted fs objects
  // with active references.
  EXPECT_THAT(fchdir(cwd.get()), SyscallSucceeds());
}

TEST(Inotify, ZeroLengthReadWriteDoesNotGenerateEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const char kContent[] = "some content";
  TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      root.path(), kContent, TempPath::kDefaultFileMode));
  const int kContentSize = sizeof(kContent) - 1;

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDWR));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  std::vector<char> buf(kContentSize, 0);
  // Read all available data.
  ssize_t readlen;
  EXPECT_THAT(readlen = read(file1_fd.get(), buf.data(), kContentSize),
              SyscallSucceeds());
  EXPECT_EQ(readlen, kContentSize);
  // Drain all events and make sure we got the IN_ACCESS for the read.
  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ACCESS, wd, Basename(file1.path()))}));

  // Now try read again. This should be a 0-length read, since we're at EOF.
  char c;
  EXPECT_THAT(readlen = read(file1_fd.get(), &c, 1), SyscallSucceeds());
  EXPECT_EQ(readlen, 0);
  // We should have no new events.
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_TRUE(events.empty());

  // Try issuing a zero-length read.
  EXPECT_THAT(readlen = read(file1_fd.get(), &c, 0), SyscallSucceeds());
  EXPECT_EQ(readlen, 0);
  // We should have no new events.
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_TRUE(events.empty());

  // Try issuing a zero-length write.
  ssize_t writelen;
  EXPECT_THAT(writelen = write(file1_fd.get(), &c, 0), SyscallSucceeds());
  EXPECT_EQ(writelen, 0);
  // We should have no new events.
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_TRUE(events.empty());
}

TEST(Inotify, ChmodGeneratesAttribEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  FileDescriptor root_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(root.path(), O_RDONLY));
  FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDWR));
  FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  auto verify_chmod_events = [&]() {
    std::vector<Event> events =
        ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
    ASSERT_THAT(events, Are({Event(IN_ATTRIB, root_wd, Basename(file1.path())),
                             Event(IN_ATTRIB, file1_wd)}));
  };

  // Don't do cooperative S/R tests for any of the {f}chmod* syscalls below, the
  // test will always fail because nodes cannot be saved when they have stricter
  // permissions than the original host node.
  const DisableSave ds;

  // Chmod.
  ASSERT_THAT(chmod(file1.path().c_str(), S_IWGRP), SyscallSucceeds());
  verify_chmod_events();

  // Fchmod.
  ASSERT_THAT(fchmod(file1_fd.get(), S_IRGRP | S_IWGRP), SyscallSucceeds());
  verify_chmod_events();

  // Fchmodat.
  const std::string file1_basename = std::string(Basename(file1.path()));
  ASSERT_THAT(fchmodat(root_fd.get(), file1_basename.c_str(), S_IWGRP, 0),
              SyscallSucceeds());
  verify_chmod_events();

  // Make sure the chmod'ed file descriptors are destroyed before DisableSave
  // is destructed.
  root_fd.reset();
  file1_fd.reset();
}

TEST(Inotify, TruncateGeneratesModifyEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDWR));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  auto verify_truncate_events = [&]() {
    std::vector<Event> events =
        ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
    ASSERT_THAT(events, Are({Event(IN_MODIFY, root_wd, Basename(file1.path())),
                             Event(IN_MODIFY, file1_wd)}));
  };

  // Truncate.
  EXPECT_THAT(truncate(file1.path().c_str(), 4096), SyscallSucceeds());
  verify_truncate_events();

  // Ftruncate.
  EXPECT_THAT(ftruncate(file1_fd.get(), 8192), SyscallSucceeds());
  verify_truncate_events();

  // No events if truncate fails.
  EXPECT_THAT(ftruncate(file1_fd.get(), -1), SyscallFailsWithErrno(EINVAL));
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({}));
}

TEST(Inotify, GetdentsGeneratesAccessEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  // This internally calls getdents(2). We also expect to see an open/close
  // event for the dirfd.
  ASSERT_NO_ERRNO_AND_VALUE(ListDir(root.path(), false));
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));

  // Linux only seems to generate access events on getdents() on some
  // calls. Allow the test to pass even if it isn't generated. gVisor will
  // always generate the IN_ACCESS event so the test will at least ensure gVisor
  // behaves reasonably.
  int i = 0;
  EXPECT_EQ(events[i].mask, IN_OPEN | IN_ISDIR);
  ++i;
  if (IsRunningOnGvisor()) {
    EXPECT_EQ(events[i].mask, IN_ACCESS | IN_ISDIR);
    ++i;
  } else {
    if (events[i].mask == (IN_ACCESS | IN_ISDIR)) {
      // Skip over the IN_ACCESS event on Linux, it only shows up some of the
      // time so we can't assert its existence.
      ++i;
    }
  }
  EXPECT_EQ(events[i].mask, IN_CLOSE_NOWRITE | IN_ISDIR);
}

TEST(Inotify, MknodGeneratesCreateEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  const TempPath file1(root.path() + "/file1");
  ASSERT_THAT(mknod(file1.path().c_str(), S_IFREG, 0), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_CREATE, wd, Basename(file1.path()))}));
}

TEST(Inotify, SymlinkGeneratesCreateEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const TempPath link1(NewTempAbsPathInDir(root.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  ASSERT_THAT(symlink(file1.path().c_str(), link1.path().c_str()),
              SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));

  ASSERT_THAT(events, Are({Event(IN_CREATE, root_wd, Basename(link1.path()))}));
}

TEST(Inotify, LinkGeneratesAttribAndCreateEvents) {
  // Inotify does not work properly with hard links in gofer and overlay fs.
  SKIP_IF(IsRunningOnGvisor() &&
          !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));

  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const TempPath link1(root.path() + "/link1");
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  ASSERT_THAT(link(file1.path().c_str(), link1.path().c_str()),
              SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_ATTRIB, file1_wd),
                           Event(IN_CREATE, root_wd, Basename(link1.path()))}));
}

TEST(Inotify, UtimesGeneratesAttribEvent) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDWR));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));

  const struct timeval times[2] = {{1, 0}, {2, 0}};
  EXPECT_THAT(futimes(file1_fd.get(), times), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_ATTRIB, wd, Basename(file1.path()))}));
}

TEST(Inotify, HardlinksReuseSameWatch) {
  // Inotify does not work properly with hard links in gofer and overlay fs.
  SKIP_IF(IsRunningOnGvisor() &&
          !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));

  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  TempPath file =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  TempPath file2(root.path() + "/file2");
  ASSERT_THAT(link(file.path().c_str(), file2.path().c_str()),
              SyscallSucceeds());

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int root_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file.path(), IN_ALL_EVENTS));
  const int file2_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file2.path(), IN_ALL_EVENTS));

  // The watch descriptors for watches on different links to the same file
  // should be identical.
  EXPECT_NE(root_wd, file_wd);
  EXPECT_EQ(file_wd, file2_wd);

  FileDescriptor file_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_WRONLY));

  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events,
              AreUnordered({Event(IN_OPEN, root_wd, Basename(file.path())),
                            Event(IN_OPEN, file_wd)}));

  // For the next step, we want to ensure all fds to the file are closed. Do
  // that now and drain the resulting events.
  file_fd.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      AreUnordered({Event(IN_CLOSE_WRITE, root_wd, Basename(file.path())),
                    Event(IN_CLOSE_WRITE, file_wd)}));

  // Try removing the link and let's see what events show up. Note that after
  // this, we still have a link to the file so the watch shouldn't be
  // automatically removed.
  const std::string file2_path = file2.reset();

  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events,
              AreUnordered({Event(IN_ATTRIB, file2_wd),
                            Event(IN_DELETE, root_wd, Basename(file2_path))}));

  // Now remove the other link. Since this is the last link to the file, the
  // watch should be automatically removed.
  const std::string file_path = file.reset();

  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      AreUnordered({Event(IN_ATTRIB, file_wd), Event(IN_DELETE_SELF, file_wd),
                    Event(IN_IGNORED, file_wd),
                    Event(IN_DELETE, root_wd, Basename(file_path))}));
}

// Calling mkdir within "parent/child" should generate an event for child, but
// not parent.
TEST(Inotify, MkdirGeneratesCreateEventWithDirFlag) {
  const TempPath parent = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath child =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(parent.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), parent.path(), IN_ALL_EVENTS));
  const int child_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), child.path(), IN_ALL_EVENTS));

  const TempPath dir1(NewTempAbsPathInDir(child.path()));
  ASSERT_THAT(mkdir(dir1.path().c_str(), 0777), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(
      events,
      Are({Event(IN_CREATE | IN_ISDIR, child_wd, Basename(dir1.path()))}));
}

TEST(Inotify, MultipleInotifyInstancesAndWatchesAllGetEvents) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));
  constexpr int kNumFds = 30;
  std::vector<FileDescriptor> inotify_fds;

  for (int i = 0; i < kNumFds; ++i) {
    const DisableSave ds;  // Too expensive.
    inotify_fds.emplace_back(
        ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK)));
    const FileDescriptor& fd = inotify_fds[inotify_fds.size() - 1];  // Back.
    ASSERT_NO_ERRNO_AND_VALUE(
        InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
    ASSERT_NO_ERRNO_AND_VALUE(
        InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));
  }

  const std::string data = "some content";
  EXPECT_THAT(write(file1_fd.get(), data.c_str(), data.length()),
              SyscallSucceeds());

  for (const FileDescriptor& fd : inotify_fds) {
    const DisableSave ds;  // Too expensive.
    const std::vector<Event> events =
        ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
    if (events.size() >= 2) {
      EXPECT_EQ(events[0].mask, IN_MODIFY);
      EXPECT_EQ(events[0].wd, 1);
      EXPECT_EQ(events[0].name, Basename(file1.path()));
      EXPECT_EQ(events[1].mask, IN_MODIFY);
      EXPECT_EQ(events[1].wd, 2);
      EXPECT_EQ(events[1].name, "");
    }
  }
}

TEST(Inotify, EventsGoUpAtMostOneLevel) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath dir1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));
  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir1.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));
  const int dir1_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), dir1.path(), IN_ALL_EVENTS));

  const std::string file1_path = file1.reset();

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_DELETE, dir1_wd, Basename(file1_path))}));
}

TEST(Inotify, DuplicateWatchReturnsSameWatchDescriptor) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd1 = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));
  const int wd2 = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));

  EXPECT_EQ(wd1, wd2);

  const FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));
  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  // The watch shouldn't be duplicated, we only expect one event.
  ASSERT_THAT(events, Are({Event(IN_OPEN, wd1)}));
}

TEST(Inotify, UnmatchedEventsAreDiscarded) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_ACCESS));

  FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));

  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  // We only asked for access events, the open event should be discarded.
  ASSERT_THAT(events, Are({}));

  // IN_IGNORED events are always generated, regardless of the mask.
  file1_fd.reset();
  file1.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_IGNORED, wd)}));
}

TEST(Inotify, AddWatchWithInvalidEventMaskFails) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  EXPECT_THAT(inotify_add_watch(fd.get(), root.path().c_str(), 0),
              SyscallFailsWithErrno(EINVAL));
}

TEST(Inotify, AddWatchOnInvalidPathFails) {
  const TempPath nonexistent(NewTempAbsPath());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  // Non-existent path.
  EXPECT_THAT(
      inotify_add_watch(fd.get(), nonexistent.path().c_str(), IN_CREATE),
      SyscallFailsWithErrno(ENOENT));

  // Garbage path pointer.
  EXPECT_THAT(inotify_add_watch(fd.get(), nullptr, IN_CREATE),
              SyscallFailsWithErrno(EFAULT));
}

TEST(Inotify, InOnlyDirFlagRespected) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  EXPECT_THAT(
      inotify_add_watch(fd.get(), root.path().c_str(), IN_ACCESS | IN_ONLYDIR),
      SyscallSucceeds());

  EXPECT_THAT(
      inotify_add_watch(fd.get(), file1.path().c_str(), IN_ACCESS | IN_ONLYDIR),
      SyscallFailsWithErrno(ENOTDIR));
}

TEST(Inotify, MaskAddMergesWithExistingEventMask) {
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file1 =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  FileDescriptor file1_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_OPEN | IN_CLOSE_WRITE));

  const std::string data = "some content";
  EXPECT_THAT(write(file1_fd.get(), data.c_str(), data.length()),
              SyscallSucceeds());

  // We shouldn't get any events, since IN_MODIFY wasn't in the event mask.
  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({}));

  // Add IN_MODIFY to event mask.
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), file1.path(), IN_MODIFY | IN_MASK_ADD));

  EXPECT_THAT(write(file1_fd.get(), data.c_str(), data.length()),
              SyscallSucceeds());

  // This time we should get the modify event.
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_MODIFY, wd)}));

  // Now close the fd. If the modify event was added to the event mask rather
  // than replacing the event mask we won't get the close event.
  file1_fd.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events, Are({Event(IN_CLOSE_WRITE, wd)}));
}

// Test that control events bits are not considered when checking event mask.
TEST(Inotify, ControlEvents) {
  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), dir.path(), IN_ACCESS));

  // Check that events in the mask are dispatched and that control bits are
  // part of the event mask.
  std::vector<std::string> files =
      ASSERT_NO_ERRNO_AND_VALUE(ListDir(dir.path(), false));
  ASSERT_EQ(files.size(), 2);

  const std::vector<Event> events1 =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events1, Are({Event(IN_ACCESS | IN_ISDIR, wd)}));

  // Check that events not in the mask are discarded.
  const FileDescriptor dir_fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(dir.path(), O_RDONLY | O_DIRECTORY));

  const std::vector<Event> events2 =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  ASSERT_THAT(events2, Are({}));
}

// Regression test to ensure epoll and directory access doesn't deadlock.
TEST(Inotify, EpollNoDeadlock) {
  const DisableSave ds;  // Too many syscalls.

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  // Create lots of directories and watch all of them.
  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  std::vector<TempPath> children;
  for (size_t i = 0; i < 1000; ++i) {
    auto child = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));
    ASSERT_NO_ERRNO_AND_VALUE(
        InotifyAddWatch(fd.get(), child.path(), IN_ACCESS));
    children.emplace_back(std::move(child));
  }

  // Run epoll_wait constantly in a separate thread.
  std::atomic<bool> done(false);
  ScopedThread th([&fd, &done] {
    for (auto start = absl::Now(); absl::Now() - start < absl::Seconds(5);) {
      FileDescriptor epoll_fd = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());
      ASSERT_NO_ERRNO(RegisterEpollFD(epoll_fd.get(), fd.get(),
                                      EPOLLIN | EPOLLOUT | EPOLLET, 0));
      struct epoll_event result[1];
      EXPECT_THAT(RetryEINTR(epoll_wait)(epoll_fd.get(), result, 1, -1),
                  SyscallSucceedsWithValue(1));

      sched_yield();
    }
    done = true;
  });

  // While epoll thread is running, constantly access all directories to
  // generate inotify events.
  while (!done) {
    std::vector<std::string> files =
        ASSERT_NO_ERRNO_AND_VALUE(ListDir(root.path(), false));
    ASSERT_EQ(files.size(), 1002);
    for (const auto& child : files) {
      if (child == "." || child == "..") {
        continue;
      }
      ASSERT_NO_ERRNO_AND_VALUE(ListDir(JoinPath(root.path(), child), false));
    }
    sched_yield();
  }
}

TEST(Inotify, Fallocate) {
  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));

  // Do an arbitrary modification with fallocate.
  ASSERT_THAT(RetryEINTR(fallocate)(fd.get(), 0, 0, 123), SyscallSucceeds());
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_MODIFY, wd)}));
}

TEST(Inotify, Utimensat) {
  SKIP_IF(IsRunningWithVFS1());

  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));

  // Just update the access time.
  struct timespec times[2] = {};
  times[0].tv_nsec = UTIME_NOW;
  times[1].tv_nsec = UTIME_OMIT;
  ASSERT_THAT(RetryEINTR(utimensat)(AT_FDCWD, file.path().c_str(), times, 0),
              SyscallSucceeds());
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ACCESS, wd)}));

  // Just the modify time.
  times[0].tv_nsec = UTIME_OMIT;
  times[1].tv_nsec = UTIME_NOW;
  ASSERT_THAT(utimensat(AT_FDCWD, file.path().c_str(), times, 0),
              SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_MODIFY, wd)}));

  // Both together.
  times[0].tv_nsec = UTIME_NOW;
  times[1].tv_nsec = UTIME_NOW;
  ASSERT_THAT(utimensat(AT_FDCWD, file.path().c_str(), times, 0),
              SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ATTRIB, wd)}));
}

TEST(Inotify, Sendfile) {
  SKIP_IF(IsRunningWithVFS1());

  const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(
      TempPath::CreateFileWith(root.path(), "x", 0644));
  const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const FileDescriptor in =
      ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));
  const FileDescriptor out =
      ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_WRONLY));

  // Create separate inotify instances for the in and out fds. If both watches
  // were on the same instance, we would have discrepancies between Linux and
  // gVisor (order of events, duplicate events), which is not that important
  // since inotify is asynchronous anyway.
  const FileDescriptor in_inotify =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const FileDescriptor out_inotify =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int in_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(in_inotify.get(), in_file.path(), IN_ALL_EVENTS));
  const int out_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(out_inotify.get(), out_file.path(), IN_ALL_EVENTS));

  ASSERT_THAT(sendfile(out.get(), in.get(), /*offset=*/nullptr, 1),
              SyscallSucceeds());

  // Expect a single access event and a single modify event.
  std::vector<Event> in_events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(in_inotify.get()));
  std::vector<Event> out_events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(out_inotify.get()));
  EXPECT_THAT(in_events, Are({Event(IN_ACCESS, in_wd)}));
  EXPECT_THAT(out_events, Are({Event(IN_MODIFY, out_wd)}));
}

TEST(Inotify, SpliceOnWatchTarget) {
  int pipefds[2];
  ASSERT_THAT(pipe2(pipefds, O_NONBLOCK), SyscallSucceeds());

  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      dir.path(), "some content", TempPath::kDefaultFileMode));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));
  const int dir_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), dir.path(), IN_ALL_EVENTS));
  const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));

  EXPECT_THAT(splice(fd.get(), nullptr, pipefds[1], nullptr, 1, /*flags=*/0),
              SyscallSucceedsWithValue(1));

  // Surprisingly, events may not be generated in Linux if we read from a file.
  // fs/splice.c:generic_file_splice_read, which is used most often, does not
  // generate events, whereas fs/splice.c:default_file_splice_read does.
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  if (IsRunningOnGvisor() && !IsRunningWithVFS1()) {
    ASSERT_THAT(events, Are({Event(IN_ACCESS, dir_wd, Basename(file.path())),
                             Event(IN_ACCESS, file_wd)}));
  }

  EXPECT_THAT(splice(pipefds[0], nullptr, fd.get(), nullptr, 1, /*flags=*/0),
              SyscallSucceedsWithValue(1));

  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  ASSERT_THAT(events, Are({
                          Event(IN_MODIFY, dir_wd, Basename(file.path())),
                          Event(IN_MODIFY, file_wd),
                      }));
}

// Watches on a parent should not be triggered by actions on a hard link to one
// of its children that has a different parent.
TEST(Inotify, LinkOnOtherParent) {
  // Inotify does not work properly with hard links in gofer and overlay fs.
  SKIP_IF(IsRunningOnGvisor() &&
          !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));

  const TempPath dir1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath dir2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir1.path()));
  std::string link_path = NewTempAbsPathInDir(dir2.path());

  ASSERT_THAT(link(file.path().c_str(), link_path.c_str()), SyscallSucceeds());

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), dir1.path(), IN_ALL_EVENTS));

  // Perform various actions on the link outside of dir1, which should trigger
  // no inotify events.
  FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(link_path.c_str(), O_RDWR));
  int val = 0;
  ASSERT_THAT(write(fd.get(), &val, sizeof(val)), SyscallSucceeds());
  ASSERT_THAT(read(fd.get(), &val, sizeof(val)), SyscallSucceeds());
  ASSERT_THAT(ftruncate(fd.get(), 12345), SyscallSucceeds());

  // Close before unlinking; some filesystems cannot restore an open fd on an
  // unlinked file.
  fd.reset();
  ASSERT_THAT(unlink(link_path.c_str()), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({}));
}

TEST(Inotify, Xattr) {
  // TODO(gvisor.dev/issue/1636): Support extended attributes in runsc gofer.
  SKIP_IF(IsRunningOnGvisor());

  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const std::string path = file.path();
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_RDWR));
  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), path, IN_ALL_EVENTS));

  const char* cpath = path.c_str();
  const char* name = "user.test";
  int val = 123;
  ASSERT_THAT(setxattr(cpath, name, &val, sizeof(val), /*flags=*/0),
              SyscallSucceeds());
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ATTRIB, wd)}));

  ASSERT_THAT(getxattr(cpath, name, &val, sizeof(val)), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({}));

  char list[100];
  ASSERT_THAT(listxattr(cpath, list, sizeof(list)), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({}));

  ASSERT_THAT(removexattr(cpath, name), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ATTRIB, wd)}));

  ASSERT_THAT(fsetxattr(fd.get(), name, &val, sizeof(val), /*flags=*/0),
              SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ATTRIB, wd)}));

  ASSERT_THAT(fgetxattr(fd.get(), name, &val, sizeof(val)), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({}));

  ASSERT_THAT(flistxattr(fd.get(), list, sizeof(list)), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({}));

  ASSERT_THAT(fremovexattr(fd.get(), name), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({Event(IN_ATTRIB, wd)}));
}

TEST(Inotify, Exec) {
  SKIP_IF(IsRunningWithVFS1());
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(fd.get(), "/bin/true", IN_ALL_EVENTS));

  // Perform exec.
  pid_t child = -1;
  int execve_errno = -1;
  auto kill = ASSERT_NO_ERRNO_AND_VALUE(
      ForkAndExec("/bin/true", {}, {}, nullptr, &child, &execve_errno));
  ASSERT_EQ(0, execve_errno);

  int status;
  ASSERT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceeds());
  EXPECT_EQ(0, status);

  // Process cleanup no longer needed.
  kill.Release();

  std::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));
  EXPECT_THAT(events, Are({Event(IN_OPEN, wd), Event(IN_ACCESS, wd),
                           Event(IN_CLOSE_NOWRITE, wd)}));
}

// Watches without IN_EXCL_UNLINK, should continue to emit events for file
// descriptors after their corresponding files have been unlinked.
//
// We need to disable S/R because there are filesystems where we cannot re-open
// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.
TEST(Inotify, IncludeUnlinkedFile) {
  const DisableSave ds;

  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(
      TempPath::CreateFileWith(dir.path(), "123", TempPath::kDefaultFileMode));
  FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int dir_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), dir.path(), IN_ALL_EVENTS));
  const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));

  ASSERT_THAT(unlink(file.path().c_str()), SyscallSucceeds());
  int val = 0;
  ASSERT_THAT(read(fd.get(), &val, sizeof(val)), SyscallSucceeds());
  ASSERT_THAT(write(fd.get(), &val, sizeof(val)), SyscallSucceeds());
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, AnyOf(Are({
                                Event(IN_ATTRIB, file_wd),
                                Event(IN_DELETE, dir_wd, Basename(file.path())),
                                Event(IN_ACCESS, dir_wd, Basename(file.path())),
                                Event(IN_ACCESS, file_wd),
                                Event(IN_MODIFY, dir_wd, Basename(file.path())),
                                Event(IN_MODIFY, file_wd),
                            }),
                            Are({
                                Event(IN_DELETE, dir_wd, Basename(file.path())),
                                Event(IN_ATTRIB, file_wd),
                                Event(IN_ACCESS, dir_wd, Basename(file.path())),
                                Event(IN_ACCESS, file_wd),
                                Event(IN_MODIFY, dir_wd, Basename(file.path())),
                                Event(IN_MODIFY, file_wd),
                            })));

  fd.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_CLOSE_WRITE, dir_wd, Basename(file.path())),
                          Event(IN_CLOSE_WRITE, file_wd),
                          Event(IN_DELETE_SELF, file_wd),
                          Event(IN_IGNORED, file_wd),
                      }));
}

// Watches created with IN_EXCL_UNLINK will stop emitting events on fds for
// children that have already been unlinked.
//
// We need to disable S/R because there are filesystems where we cannot re-open
// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.
TEST(Inotify, ExcludeUnlink) {
  const DisableSave ds;
  // TODO(gvisor.dev/issue/1624): This test fails on VFS1.
  SKIP_IF(IsRunningWithVFS1());

  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir.path()));

  FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int dir_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), dir.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));
  const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), file.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));

  // Unlink the child, which should cause further operations on the open file
  // descriptor to be ignored.
  ASSERT_THAT(unlink(file.path().c_str()), SyscallSucceeds());
  int val = 0;
  ASSERT_THAT(write(fd.get(), &val, sizeof(val)), SyscallSucceeds());
  ASSERT_THAT(read(fd.get(), &val, sizeof(val)), SyscallSucceeds());
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, AreUnordered({
                          Event(IN_ATTRIB, file_wd),
                          Event(IN_DELETE, dir_wd, Basename(file.path())),
                      }));

  fd.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  ASSERT_THAT(events, Are({
                          Event(IN_DELETE_SELF, file_wd),
                          Event(IN_IGNORED, file_wd),
                      }));
}

// We need to disable S/R because there are filesystems where we cannot re-open
// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.
TEST(Inotify, ExcludeUnlinkDirectory) {
  // TODO(gvisor.dev/issue/1624): This test fails on VFS1. Remove once VFS1 is
  // deleted.
  SKIP_IF(IsRunningWithVFS1());

  const DisableSave ds;

  const TempPath parent = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  TempPath dir =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(parent.path()));
  std::string dirPath = dir.path();
  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(dirPath.c_str(), O_RDONLY | O_DIRECTORY));
  const int parent_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), parent.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));
  const int self_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), dir.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));

  // Unlink the dir, and then close the open fd.
  ASSERT_THAT(rmdir(dirPath.c_str()), SyscallSucceeds());
  dir.reset();

  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  // No close event should appear.
  ASSERT_THAT(events,
              Are({Event(IN_DELETE | IN_ISDIR, parent_wd, Basename(dirPath))}));

  fd.reset();
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  ASSERT_THAT(events, Are({
                          Event(IN_DELETE_SELF, self_wd),
                          Event(IN_IGNORED, self_wd),
                      }));
}

// If "dir/child" and "dir/child2" are links to the same file, and "dir/child"
// is unlinked, a watch on "dir" with IN_EXCL_UNLINK will exclude future events
// for fds on "dir/child" but not "dir/child2".
//
// We need to disable S/R because there are filesystems where we cannot re-open
// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.
TEST(Inotify, ExcludeUnlinkMultipleChildren) {
  // Inotify does not work properly with hard links in gofer and overlay fs.
  SKIP_IF(IsRunningOnGvisor() &&
          !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));
  // TODO(gvisor.dev/issue/1624): This test fails on VFS1.
  SKIP_IF(IsRunningWithVFS1());

  const DisableSave ds;

  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir.path()));
  std::string path1 = file.path();
  std::string path2 = NewTempAbsPathInDir(dir.path());
  ASSERT_THAT(link(path1.c_str(), path2.c_str()), SyscallSucceeds());

  const FileDescriptor fd1 =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path1.c_str(), O_RDWR));
  const FileDescriptor fd2 =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path2.c_str(), O_RDWR));

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), dir.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));

  // After unlinking path1, only events on the fd for path2 should be generated.
  ASSERT_THAT(unlink(path1.c_str()), SyscallSucceeds());
  ASSERT_THAT(write(fd1.get(), "x", 1), SyscallSucceeds());
  ASSERT_THAT(write(fd2.get(), "x", 1), SyscallSucceeds());

  const std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_DELETE, wd, Basename(path1)),
                          Event(IN_MODIFY, wd, Basename(path2)),
                      }));
}

// On native Linux, actions of data type FSNOTIFY_EVENT_INODE are not affected
// by IN_EXCL_UNLINK (see
// fs/notify/inotify/inotify_fsnotify.c:inotify_handle_event). Inode-level
// events include changes to metadata and extended attributes.
//
// We need to disable S/R because there are filesystems where we cannot re-open
// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.
TEST(Inotify, ExcludeUnlinkInodeEvents) {
  // TODO(gvisor.dev/issue/1624): Fails on VFS1.
  SKIP_IF(IsRunningWithVFS1());

  // NOTE(gvisor.dev/issue/3654): In the gofer filesystem, we do not allow
  // setting attributes through an fd if the file at the open path has been
  // deleted.
  SKIP_IF(IsRunningOnGvisor() &&
          !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));

  const DisableSave ds;

  const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const TempPath file =
      ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir.path()));

  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(file.path().c_str(), O_RDWR));

  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
  const int dir_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), dir.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));
  const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(
      inotify_fd.get(), file.path(), IN_ALL_EVENTS | IN_EXCL_UNLINK));

  // Even after unlinking, inode-level operations will trigger events regardless
  // of IN_EXCL_UNLINK.
  ASSERT_THAT(unlink(file.path().c_str()), SyscallSucceeds());

  // Perform various actions on fd.
  ASSERT_THAT(ftruncate(fd.get(), 12345), SyscallSucceeds());
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, AnyOf(Are({
                                Event(IN_ATTRIB, file_wd),
                                Event(IN_DELETE, dir_wd, Basename(file.path())),
                                Event(IN_MODIFY, dir_wd, Basename(file.path())),
                                Event(IN_MODIFY, file_wd),
                            }),
                            Are({
                                Event(IN_DELETE, dir_wd, Basename(file.path())),
                                Event(IN_ATTRIB, file_wd),
                                Event(IN_MODIFY, dir_wd, Basename(file.path())),
                                Event(IN_MODIFY, file_wd),
                            })));

  const struct timeval times[2] = {{1, 0}, {2, 0}};
  ASSERT_THAT(futimes(fd.get(), times), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_ATTRIB, dir_wd, Basename(file.path())),
                          Event(IN_ATTRIB, file_wd),
                      }));

  // S/R is disabled on this entire test due to behavior with unlink; it must
  // also be disabled after this point because of fchmod.
  ASSERT_THAT(fchmod(fd.get(), 0777), SyscallSucceeds());
  events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_ATTRIB, dir_wd, Basename(file.path())),
                          Event(IN_ATTRIB, file_wd),
                      }));
}

TEST(Inotify, OneShot) {
  // TODO(gvisor.dev/issue/1624): IN_ONESHOT not supported in VFS1.
  SKIP_IF(IsRunningWithVFS1());

  const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const FileDescriptor inotify_fd =
      ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));

  const int wd = ASSERT_NO_ERRNO_AND_VALUE(
      InotifyAddWatch(inotify_fd.get(), file.path(), IN_MODIFY | IN_ONESHOT));

  // Open an fd, write to it, and then close it.
  FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_WRONLY));
  ASSERT_THAT(write(fd.get(), "x", 1), SyscallSucceedsWithValue(1));
  fd.reset();

  // We should get a single event followed by IN_IGNORED indicating removal
  // of the one-shot watch. Prior activity (i.e. open) that is not in the mask
  // should not trigger removal, and activity after removal (i.e. close) should
  // not generate events.
  std::vector<Event> events =
      ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));
  EXPECT_THAT(events, Are({
                          Event(IN_MODIFY, wd),
                          Event(IN_IGNORED, wd),
                      }));

  // The watch should already have been removed.
  EXPECT_THAT(inotify_rm_watch(inotify_fd.get(), wd),
              SyscallFailsWithErrno(EINVAL));
}

// This test helps verify that the lock order of filesystem and inotify locks
// is respected when inotify instances and watch targets are concurrently being
// destroyed.
TEST(InotifyTest, InotifyAndTargetDestructionDoNotDeadlock) {
  const DisableSave ds;  // Too many syscalls.

  // A file descriptor protected by a mutex. This ensures that while a
  // descriptor is in use, it cannot be closed and reused for a different file
  // description.
  struct atomic_fd {
    int fd;
    absl::Mutex mu;
  };

  // Set up initial inotify instances.
  constexpr int num_fds = 3;
  std::vector<atomic_fd> fds(num_fds);
  for (int i = 0; i < num_fds; i++) {
    int fd;
    ASSERT_THAT(fd = inotify_init1(IN_NONBLOCK), SyscallSucceeds());
    fds[i].fd = fd;
  }

  // Set up initial watch targets.
  std::vector<std::string> paths;
  for (int i = 0; i < 3; i++) {
    paths.push_back(NewTempAbsPath());
    ASSERT_THAT(mknod(paths[i].c_str(), S_IFREG | 0600, 0), SyscallSucceeds());
  }

  constexpr absl::Duration runtime = absl::Seconds(4);

  // Constantly replace each inotify instance with a new one.
  auto replace_fds = [&] {
    for (auto start = absl::Now(); absl::Now() - start < runtime;) {
      for (auto& afd : fds) {
        int new_fd;
        ASSERT_THAT(new_fd = inotify_init1(IN_NONBLOCK), SyscallSucceeds());
        absl::MutexLock l(&afd.mu);
        ASSERT_THAT(close(afd.fd), SyscallSucceeds());
        afd.fd = new_fd;
        for (auto& p : paths) {
          // inotify_add_watch may fail if the file at p was deleted.
          ASSERT_THAT(inotify_add_watch(afd.fd, p.c_str(), IN_ALL_EVENTS),
                      AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(ENOENT)));
        }
      }
      sched_yield();
    }
  };

  std::list<ScopedThread> ts;
  for (int i = 0; i < 3; i++) {
    ts.emplace_back(replace_fds);
  }

  // Constantly replace each watch target with a new one.
  for (auto start = absl::Now(); absl::Now() - start < runtime;) {
    for (auto& p : paths) {
      ASSERT_THAT(unlink(p.c_str()), SyscallSucceeds());
      ASSERT_THAT(mknod(p.c_str(), S_IFREG | 0600, 0), SyscallSucceeds());
    }
    sched_yield();
  }
}

// This test helps verify that the lock order of filesystem and inotify locks
// is respected when adding/removing watches occurs concurrently with the
// removal of their targets.
TEST(InotifyTest, AddRemoveUnlinkDoNotDeadlock) {
  const DisableSave ds;  // Too many syscalls.

  // Set up inotify instances.
  constexpr int num_fds = 3;
  std::vector<int> fds(num_fds);
  for (int i = 0; i < num_fds; i++) {
    ASSERT_THAT(fds[i] = inotify_init1(IN_NONBLOCK), SyscallSucceeds());
  }

  // Set up initial watch targets.
  std::vector<std::string> paths;
  for (int i = 0; i < 3; i++) {
    paths.push_back(NewTempAbsPath());
    ASSERT_THAT(mknod(paths[i].c_str(), S_IFREG | 0600, 0), SyscallSucceeds());
  }

  constexpr absl::Duration runtime = absl::Seconds(1);

  // Constantly add/remove watches for each inotify instance/watch target pair.
  auto add_remove_watches = [&] {
    for (auto start = absl::Now(); absl::Now() - start < runtime;) {
      for (int fd : fds) {
        for (auto& p : paths) {
          // Do not assert on inotify_add_watch and inotify_rm_watch. They may
          // fail if the file at p was deleted. inotify_add_watch may also fail
          // if another thread beat us to adding a watch.
          const int wd = inotify_add_watch(fd, p.c_str(), IN_ALL_EVENTS);
          if (wd > 0) {
            inotify_rm_watch(fd, wd);
          }
        }
      }
      sched_yield();
    }
  };

  std::list<ScopedThread> ts;
  for (int i = 0; i < 15; i++) {
    ts.emplace_back(add_remove_watches);
  }

  // Constantly replace each watch target with a new one.
  for (auto start = absl::Now(); absl::Now() - start < runtime;) {
    for (auto& p : paths) {
      ASSERT_THAT(unlink(p.c_str()), SyscallSucceeds());
      ASSERT_THAT(mknod(p.c_str(), S_IFREG | 0600, 0), SyscallSucceeds());
    }
    sched_yield();
  }
}

// This test helps verify that the lock order of filesystem and inotify locks
// is respected when many inotify events and filesystem operations occur
// simultaneously.
TEST(InotifyTest, NotifyNoDeadlock) {
  const DisableSave ds;  // Too many syscalls.

  const TempPath parent = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
  const std::string dir = parent.path();

  // mu protects file, which will change on rename.
  absl::Mutex mu;
  std::string file = NewTempAbsPathInDir(dir);
  ASSERT_THAT(mknod(file.c_str(), 0644 | S_IFREG, 0), SyscallSucceeds());

  const absl::Duration runtime = absl::Milliseconds(300);

  // Add/remove watches on dir and file.
  ScopedThread add_remove_watches([&] {
    const FileDescriptor ifd =
        ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));
    int dir_wd = ASSERT_NO_ERRNO_AND_VALUE(
        InotifyAddWatch(ifd.get(), dir, IN_ALL_EVENTS));
    int file_wd;
    {
      absl::ReaderMutexLock l(&mu);
      file_wd = ASSERT_NO_ERRNO_AND_VALUE(
          InotifyAddWatch(ifd.get(), file, IN_ALL_EVENTS));
    }
    for (auto start = absl::Now(); absl::Now() - start < runtime;) {
      ASSERT_THAT(inotify_rm_watch(ifd.get(), file_wd), SyscallSucceeds());
      ASSERT_THAT(inotify_rm_watch(ifd.get(), dir_wd), SyscallSucceeds());
      dir_wd = ASSERT_NO_ERRNO_AND_VALUE(
          InotifyAddWatch(ifd.get(), dir, IN_ALL_EVENTS));
      {
        absl::ReaderMutexLock l(&mu);
        file_wd = ASSERT_NO_ERRNO_AND_VALUE(
            InotifyAddWatch(ifd.get(), file, IN_ALL_EVENTS));
      }
      sched_yield();
    }
  });

  // Modify attributes on dir and file.
  ScopedThread stats([&] {
    int fd, dir_fd;
    {
      absl::ReaderMutexLock l(&mu);
      ASSERT_THAT(fd = open(file.c_str(), O_RDONLY), SyscallSucceeds());
    }
    ASSERT_THAT(dir_fd = open(dir.c_str(), O_RDONLY | O_DIRECTORY),
                SyscallSucceeds());
    const struct timeval times[2] = {{1, 0}, {2, 0}};

    for (auto start = absl::Now(); absl::Now() - start < runtime;) {
      {
        absl::ReaderMutexLock l(&mu);
        EXPECT_THAT(utimes(file.c_str(), times), SyscallSucceeds());
      }
      EXPECT_THAT(futimes(fd, times), SyscallSucceeds());
      EXPECT_THAT(utimes(dir.c_str(), times), SyscallSucceeds());
      EXPECT_THAT(futimes(dir_fd, times), SyscallSucceeds());
      sched_yield();
    }
  });

  // Modify extended attributes on dir and file.
  ScopedThread xattrs([&] {
    // TODO(gvisor.dev/issue/1636): Support extended attributes in runsc gofer.
    if (!IsRunningOnGvisor()) {
      int fd;
      {
        absl::ReaderMutexLock l(&mu);
        ASSERT_THAT(fd = open(file.c_str(), O_RDONLY), SyscallSucceeds());
      }

      const char* name = "user.test";
      int val = 123;
      for (auto start = absl::Now(); absl::Now() - start < runtime;) {
        {
          absl::ReaderMutexLock l(&mu);
          ASSERT_THAT(
              setxattr(file.c_str(), name, &val, sizeof(val), /*flags=*/0),
              SyscallSucceeds());
          ASSERT_THAT(removexattr(file.c_str(), name), SyscallSucceeds());
        }

        ASSERT_THAT(fsetxattr(fd, name, &val, sizeof(val), /*flags=*/0),
                    SyscallSucceeds());
        ASSERT_THAT(fremovexattr(fd, name), SyscallSucceeds());
        sched_yield();
      }
    }
  });

  // Read and write file's contents. Read and write dir's entries.
  ScopedThread read_write([&] {
    int fd;
    {
      absl::ReaderMutexLock l(&mu);
      ASSERT_THAT(fd = open(file.c_str(), O_RDWR), SyscallSucceeds());
    }
    for (auto start = absl::Now(); absl::Now() - start < runtime;) {
      int val = 123;
      ASSERT_THAT(write(fd, &val, sizeof(val)), SyscallSucceeds());
      ASSERT_THAT(read(fd, &val, sizeof(val)), SyscallSucceeds());
      TempPath new_file =
          ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir));
      ASSERT_NO_ERRNO(ListDir(dir, false));
      new_file.reset();
      sched_yield();
    }
  });

  // Rename file.
  for (auto start = absl::Now(); absl::Now() - start < runtime;) {
    const std::string new_path = NewTempAbsPathInDir(dir);
    {
      absl::WriterMutexLock l(&mu);
      ASSERT_THAT(rename(file.c_str(), new_path.c_str()), SyscallSucceeds());
      file = new_path;
    }
    sched_yield();
  }
}

}  // namespace
}  // namespace testing
}  // namespace gvisor