forked from shenghaozou/gvisor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproc.cc
1837 lines (1563 loc) · 61.2 KB
/
proc.cc
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
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <syscall.h>
#include <unistd.h>
#include <algorithm>
#include <atomic>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/util/capability_util.h"
#include "test/util/cleanup.h"
#include "test/util/file_descriptor.h"
#include "test/util/fs_util.h"
#include "test/util/memory_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"
#include "test/util/timer_util.h"
// NOTE: No, this isn't really a syscall but this is a really simple
// way to get it tested on both gVisor, PTrace and Linux.
using ::testing::AllOf;
using ::testing::ContainerEq;
using ::testing::Contains;
using ::testing::ContainsRegex;
using ::testing::Gt;
using ::testing::HasSubstr;
using ::testing::IsSupersetOf;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
// Exported by glibc.
extern char** environ;
namespace gvisor {
namespace testing {
namespace {
// O_LARGEFILE as defined by Linux. glibc tries to be clever by setting it to 0
// because "it isn't needed", even though Linux can return it via F_GETFL.
constexpr int kOLargeFile = 00100000;
// Takes the subprocess command line and pid.
// If it returns !OK, WithSubprocess returns immediately.
using SubprocessCallback = std::function<PosixError(int)>;
std::vector<std::string> saved_argv; // NOLINT
// Helper function to dump /proc/{pid}/status and check the
// state data. State should = "Z" for zombied or "RSD" for
// running, interruptible sleeping (S), or uninterruptible sleep
// (D).
void CompareProcessState(absl::string_view state, int pid) {
auto status_file = ASSERT_NO_ERRNO_AND_VALUE(
GetContents(absl::StrCat("/proc/", pid, "/status")));
EXPECT_THAT(status_file, ContainsRegex(absl::StrCat("State:.[", state,
"]\\s+\\(\\w+\\)")));
}
// Run callbacks while a subprocess is running, zombied, and/or exited.
PosixError WithSubprocess(SubprocessCallback const& running,
SubprocessCallback const& zombied,
SubprocessCallback const& exited) {
int pipe_fds[2] = {};
if (pipe(pipe_fds) < 0) {
return PosixError(errno, "pipe");
}
int child_pid = fork();
if (child_pid < 0) {
return PosixError(errno, "fork");
}
if (child_pid == 0) {
close(pipe_fds[0]); // Close the read end.
const DisableSave ds; // Timing issues.
// Write to the pipe to tell it we're ready.
char buf = 'a';
int res = 0;
res = WriteFd(pipe_fds[1], &buf, sizeof(buf));
TEST_CHECK_MSG(res == sizeof(buf), "Write failure in subprocess");
while (true) {
SleepSafe(absl::Milliseconds(100));
}
__builtin_unreachable();
}
close(pipe_fds[1]); // Close the write end.
int status = 0;
auto wait_cleanup = Cleanup([child_pid, &status] {
EXPECT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());
});
auto kill_cleanup = Cleanup([child_pid] {
EXPECT_THAT(kill(child_pid, SIGKILL), SyscallSucceeds());
});
// Wait for the child.
char buf = 0;
int res = ReadFd(pipe_fds[0], &buf, sizeof(buf));
if (res < 0) {
return PosixError(errno, "Read from pipe");
} else if (res == 0) {
return PosixError(EPIPE, "Unable to read from pipe: EOF");
}
if (running) {
// The first arg, RSD, refers to a "running process", or a process with a
// state of Running (R), Interruptable Sleep (S) or Uninterruptable
// Sleep (D).
CompareProcessState("RSD", child_pid);
RETURN_IF_ERRNO(running(child_pid));
}
// Kill the process.
kill_cleanup.Release()();
siginfo_t info;
// Wait until the child process has exited (WEXITED flag) but don't
// reap the child (WNOWAIT flag).
waitid(P_PID, child_pid, &info, WNOWAIT | WEXITED);
if (zombied) {
// Arg of "Z" refers to a Zombied Process.
CompareProcessState("Z", child_pid);
RETURN_IF_ERRNO(zombied(child_pid));
}
// Wait on the process.
wait_cleanup.Release()();
// If the process is reaped, then then this should return
// with ECHILD.
EXPECT_THAT(waitpid(child_pid, &status, WNOHANG),
SyscallFailsWithErrno(ECHILD));
if (exited) {
RETURN_IF_ERRNO(exited(child_pid));
}
return NoError();
}
// Access the file returned by name when a subprocess is running.
PosixError AccessWhileRunning(std::function<std::string(int pid)> name, int flags,
std::function<void(int fd)> access) {
FileDescriptor fd;
return WithSubprocess(
[&](int pid) -> PosixError {
// Running.
ASSIGN_OR_RETURN_ERRNO(fd, Open(name(pid), flags));
access(fd.get());
return NoError();
},
nullptr, nullptr);
}
// Access the file returned by name when the a subprocess is zombied.
PosixError AccessWhileZombied(std::function<std::string(int pid)> name, int flags,
std::function<void(int fd)> access) {
FileDescriptor fd;
return WithSubprocess(
[&](int pid) -> PosixError {
// Running.
ASSIGN_OR_RETURN_ERRNO(fd, Open(name(pid), flags));
return NoError();
},
[&](int pid) -> PosixError {
// Zombied.
access(fd.get());
return NoError();
},
nullptr);
}
// Access the file returned by name when the a subprocess is exited.
PosixError AccessWhileExited(std::function<std::string(int pid)> name, int flags,
std::function<void(int fd)> access) {
FileDescriptor fd;
return WithSubprocess(
[&](int pid) -> PosixError {
// Running.
ASSIGN_OR_RETURN_ERRNO(fd, Open(name(pid), flags));
return NoError();
},
nullptr,
[&](int pid) -> PosixError {
// Exited.
access(fd.get());
return NoError();
});
}
// ReadFd(fd=/proc/PID/basename) while PID is running.
int ReadWhileRunning(std::string const& basename, void* buf, size_t count) {
int ret = 0;
int err = 0;
EXPECT_NO_ERRNO(AccessWhileRunning(
[&](int pid) -> std::string {
return absl::StrCat("/proc/", pid, "/", basename);
},
O_RDONLY,
[&](int fd) {
ret = ReadFd(fd, buf, count);
err = errno;
}));
errno = err;
return ret;
}
// ReadFd(fd=/proc/PID/basename) while PID is zombied.
int ReadWhileZombied(std::string const& basename, void* buf, size_t count) {
int ret = 0;
int err = 0;
EXPECT_NO_ERRNO(AccessWhileZombied(
[&](int pid) -> std::string {
return absl::StrCat("/proc/", pid, "/", basename);
},
O_RDONLY,
[&](int fd) {
ret = ReadFd(fd, buf, count);
err = errno;
}));
errno = err;
return ret;
}
// ReadFd(fd=/proc/PID/basename) while PID is exited.
int ReadWhileExited(std::string const& basename, void* buf, size_t count) {
int ret = 0;
int err = 0;
EXPECT_NO_ERRNO(AccessWhileExited(
[&](int pid) -> std::string {
return absl::StrCat("/proc/", pid, "/", basename);
},
O_RDONLY,
[&](int fd) {
ret = ReadFd(fd, buf, count);
err = errno;
}));
errno = err;
return ret;
}
// readlinkat(fd=/proc/PID/, basename) while PID is running.
int ReadlinkWhileRunning(std::string const& basename, char* buf, size_t count) {
int ret = 0;
int err = 0;
EXPECT_NO_ERRNO(AccessWhileRunning(
[&](int pid) -> std::string { return absl::StrCat("/proc/", pid, "/"); },
O_DIRECTORY,
[&](int fd) {
ret = readlinkat(fd, basename.c_str(), buf, count);
err = errno;
}));
errno = err;
return ret;
}
// readlinkat(fd=/proc/PID/, basename) while PID is zombied.
int ReadlinkWhileZombied(std::string const& basename, char* buf, size_t count) {
int ret = 0;
int err = 0;
EXPECT_NO_ERRNO(AccessWhileZombied(
[&](int pid) -> std::string { return absl::StrCat("/proc/", pid, "/"); },
O_DIRECTORY,
[&](int fd) {
ret = readlinkat(fd, basename.c_str(), buf, count);
err = errno;
}));
errno = err;
return ret;
}
// readlinkat(fd=/proc/PID/, basename) while PID is exited.
int ReadlinkWhileExited(std::string const& basename, char* buf, size_t count) {
int ret = 0;
int err = 0;
EXPECT_NO_ERRNO(AccessWhileExited(
[&](int pid) -> std::string { return absl::StrCat("/proc/", pid, "/"); },
O_DIRECTORY,
[&](int fd) {
ret = readlinkat(fd, basename.c_str(), buf, count);
err = errno;
}));
errno = err;
return ret;
}
TEST(ProcTest, NotFoundInRoot) {
struct stat s;
EXPECT_THAT(stat("/proc/foobar", &s), SyscallFailsWithErrno(ENOENT));
}
TEST(ProcSelfTest, IsThreadGroupLeader) {
ScopedThread([] {
const pid_t tgid = getpid();
const pid_t tid = syscall(SYS_gettid);
EXPECT_NE(tgid, tid);
auto link = ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/self"));
EXPECT_EQ(link, absl::StrCat(tgid));
});
}
TEST(ProcThreadSelfTest, Basic) {
const pid_t tgid = getpid();
const pid_t tid = syscall(SYS_gettid);
EXPECT_EQ(tgid, tid);
auto link_threadself =
ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/thread-self"));
EXPECT_EQ(link_threadself, absl::StrCat(tgid, "/task/", tid));
// Just read one file inside thread-self to ensure that the link is valid.
auto link_threadself_exe =
ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/thread-self/exe"));
auto link_procself_exe =
ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/self/exe"));
EXPECT_EQ(link_threadself_exe, link_procself_exe);
}
TEST(ProcThreadSelfTest, Thread) {
ScopedThread([] {
const pid_t tgid = getpid();
const pid_t tid = syscall(SYS_gettid);
EXPECT_NE(tgid, tid);
auto link_threadself =
ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/thread-self"));
EXPECT_EQ(link_threadself, absl::StrCat(tgid, "/task/", tid));
// Just read one file inside thread-self to ensure that the link is valid.
auto link_threadself_exe =
ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/thread-self/exe"));
auto link_procself_exe =
ASSERT_NO_ERRNO_AND_VALUE(ReadLink("/proc/self/exe"));
EXPECT_EQ(link_threadself_exe, link_procself_exe);
// A thread should not have "/proc/<tid>/task".
struct stat s;
EXPECT_THAT(stat("/proc/thread-self/task", &s),
SyscallFailsWithErrno(ENOENT));
});
}
// Returns the /proc/PID/maps entry for the MAP_PRIVATE | MAP_ANONYMOUS mapping
// m with start address addr and length len.
std::string AnonymousMapsEntry(uintptr_t addr, size_t len, int prot) {
return absl::StrCat(absl::Hex(addr, absl::PadSpec::kZeroPad8), "-",
absl::Hex(addr + len, absl::PadSpec::kZeroPad8), " ",
prot & PROT_READ ? "r" : "-",
prot & PROT_WRITE ? "w" : "-",
prot & PROT_EXEC ? "x" : "-", "p 00000000 00:00 0 ");
}
std::string AnonymousMapsEntryForMapping(const Mapping& m, int prot) {
return AnonymousMapsEntry(m.addr(), m.len(), prot);
}
PosixErrorOr<std::map<uint64_t, uint64_t>> ReadProcSelfAuxv() {
std::string auxv_file;
RETURN_IF_ERRNO(GetContents("/proc/self/auxv", &auxv_file));
const Elf64_auxv_t* auxv_data =
reinterpret_cast<const Elf64_auxv_t*>(auxv_file.data());
std::map<uint64_t, uint64_t> auxv_entries;
for (int i = 0; auxv_data[i].a_type != AT_NULL; i++) {
auto a_type = auxv_data[i].a_type;
EXPECT_EQ(0, auxv_entries.count(a_type)) << "a_type: " << a_type;
auxv_entries.emplace(a_type, auxv_data[i].a_un.a_val);
}
return auxv_entries;
}
TEST(ProcSelfAuxv, EntryPresence) {
auto auxv_entries = ASSERT_NO_ERRNO_AND_VALUE(ReadProcSelfAuxv());
EXPECT_EQ(auxv_entries.count(AT_ENTRY), 1);
EXPECT_EQ(auxv_entries.count(AT_PHDR), 1);
EXPECT_EQ(auxv_entries.count(AT_PHENT), 1);
EXPECT_EQ(auxv_entries.count(AT_PHNUM), 1);
EXPECT_EQ(auxv_entries.count(AT_BASE), 1);
EXPECT_EQ(auxv_entries.count(AT_CLKTCK), 1);
EXPECT_EQ(auxv_entries.count(AT_RANDOM), 1);
EXPECT_EQ(auxv_entries.count(AT_EXECFN), 1);
EXPECT_EQ(auxv_entries.count(AT_PAGESZ), 1);
EXPECT_EQ(auxv_entries.count(AT_SYSINFO_EHDR), 1);
}
TEST(ProcSelfAuxv, EntryValues) {
auto proc_auxv = ASSERT_NO_ERRNO_AND_VALUE(ReadProcSelfAuxv());
// We need to find the ELF auxiliary vector. The section of memory pointed to
// by envp contains some pointers to non-null pointers, followed by a single
// pointer to a null pointer, followed by the auxiliary vector.
char** envpi = environ;
while (*envpi) {
++envpi;
}
const Elf64_auxv_t* envp_auxv =
reinterpret_cast<const Elf64_auxv_t*>(envpi + 1);
int i;
for (i = 0; envp_auxv[i].a_type != AT_NULL; i++) {
auto a_type = envp_auxv[i].a_type;
EXPECT_EQ(proc_auxv.count(a_type), 1);
EXPECT_EQ(proc_auxv[a_type], envp_auxv[i].a_un.a_val)
<< "a_type: " << a_type;
}
EXPECT_EQ(i, proc_auxv.size());
}
// Just open and read /proc/self/maps, check that we can find [stack]
TEST(ProcSelfMaps, Basic) {
auto proc_self_maps =
ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
std::vector<std::string> strings = absl::StrSplit(proc_self_maps, '\n');
std::vector<std::string> stacks;
// Make sure there's a stack in there.
for (const auto& str : strings) {
if (str.find("[stack]") != std::string::npos) {
stacks.push_back(str);
}
}
ASSERT_EQ(1, stacks.size()) << "[stack] not found in: " << proc_self_maps;
// Linux pads to 73 characters then we add 7.
EXPECT_EQ(80, stacks[0].length());
}
TEST(ProcSelfMaps, Map1) {
Mapping mapping =
ASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_READ, MAP_PRIVATE));
auto proc_self_maps =
ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
std::vector<std::string> strings = absl::StrSplit(proc_self_maps, '\n');
std::vector<std::string> addrs;
// Make sure if is listed.
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(mapping, PROT_READ)) {
addrs.push_back(str);
}
}
ASSERT_EQ(1, addrs.size());
}
TEST(ProcSelfMaps, Map2) {
// NOTE: The permissions must be different or the pages will get merged.
Mapping map1 = ASSERT_NO_ERRNO_AND_VALUE(
MmapAnon(kPageSize, PROT_READ | PROT_EXEC, MAP_PRIVATE));
Mapping map2 =
ASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_WRITE, MAP_PRIVATE));
auto proc_self_maps =
ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
std::vector<std::string> strings = absl::StrSplit(proc_self_maps, '\n');
std::vector<std::string> addrs;
// Make sure if is listed.
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(map1, PROT_READ | PROT_EXEC)) {
addrs.push_back(str);
}
}
ASSERT_EQ(1, addrs.size());
addrs.clear();
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(map2, PROT_WRITE)) {
addrs.push_back(str);
}
}
ASSERT_EQ(1, addrs.size());
}
TEST(ProcSelfMaps, MapUnmap) {
Mapping map1 = ASSERT_NO_ERRNO_AND_VALUE(
MmapAnon(kPageSize, PROT_READ | PROT_EXEC, MAP_PRIVATE));
Mapping map2 =
ASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_WRITE, MAP_PRIVATE));
auto proc_self_maps =
ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
std::vector<std::string> strings = absl::StrSplit(proc_self_maps, '\n');
std::vector<std::string> addrs;
// Make sure if is listed.
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(map1, PROT_READ | PROT_EXEC)) {
addrs.push_back(str);
}
}
ASSERT_EQ(1, addrs.size()) << proc_self_maps;
addrs.clear();
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(map2, PROT_WRITE)) {
addrs.push_back(str);
}
}
ASSERT_EQ(1, addrs.size());
map2.reset();
// Read it again.
proc_self_maps = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
strings = absl::StrSplit(proc_self_maps, '\n');
// First entry should be there.
addrs.clear();
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(map1, PROT_READ | PROT_EXEC)) {
addrs.push_back(str);
}
}
ASSERT_EQ(1, addrs.size());
addrs.clear();
// But not the second.
for (const auto& str : strings) {
if (str == AnonymousMapsEntryForMapping(map2, PROT_WRITE)) {
addrs.push_back(str);
}
}
ASSERT_EQ(0, addrs.size());
}
TEST(ProcSelfMaps, Mprotect) {
if (!IsRunningOnGvisor()) {
// FIXME: Linux's mprotect() sometimes fails to merge VMAs in this
// case.
LOG(WARNING) << "Skipping test on Linux";
return;
}
// Reserve 5 pages of address space.
Mapping m = ASSERT_NO_ERRNO_AND_VALUE(
MmapAnon(5 * kPageSize, PROT_NONE, MAP_PRIVATE));
// Change the permissions on the middle 3 pages. (The first and last pages may
// be merged with other vmas on either side, so they aren't tested directly;
// they just ensure that the middle 3 pages are bracketed by VMAs with
// incompatible permissions.)
ASSERT_THAT(mprotect(reinterpret_cast<void*>(m.addr() + kPageSize),
3 * kPageSize, PROT_READ),
SyscallSucceeds());
// Check that the middle 3 pages make up a single VMA.
auto proc_self_maps =
ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
std::vector<std::string> strings = absl::StrSplit(proc_self_maps, '\n');
EXPECT_THAT(strings, Contains(AnonymousMapsEntry(m.addr() + kPageSize,
3 * kPageSize, PROT_READ)));
// Change the permissions on the middle page only.
ASSERT_THAT(mprotect(reinterpret_cast<void*>(m.addr() + 2 * kPageSize),
kPageSize, PROT_READ | PROT_WRITE),
SyscallSucceeds());
// Check that the single VMA has been split into 3 VMAs.
proc_self_maps = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
strings = absl::StrSplit(proc_self_maps, '\n');
EXPECT_THAT(
strings,
IsSupersetOf(
{AnonymousMapsEntry(m.addr() + kPageSize, kPageSize, PROT_READ),
AnonymousMapsEntry(m.addr() + 2 * kPageSize, kPageSize,
PROT_READ | PROT_WRITE),
AnonymousMapsEntry(m.addr() + 3 * kPageSize, kPageSize,
PROT_READ)}));
// Change the permissions on the middle page back.
ASSERT_THAT(mprotect(reinterpret_cast<void*>(m.addr() + 2 * kPageSize),
kPageSize, PROT_READ),
SyscallSucceeds());
// Check that the 3 VMAs have been merged back into a single VMA.
proc_self_maps = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/self/maps"));
strings = absl::StrSplit(proc_self_maps, '\n');
EXPECT_THAT(strings, Contains(AnonymousMapsEntry(m.addr() + kPageSize,
3 * kPageSize, PROT_READ)));
}
TEST(ProcSelfFd, OpenFd) {
int pipe_fds[2];
ASSERT_THAT(pipe2(pipe_fds, O_CLOEXEC), SyscallSucceeds());
// Reopen the write end.
const std::string path = absl::StrCat("/proc/self/fd/", pipe_fds[1]);
const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_WRONLY));
// Ensure that a read/write works.
const std::string data = "hello";
std::unique_ptr<char[]> buffer(new char[data.size()]);
EXPECT_THAT(write(fd.get(), data.c_str(), data.size()),
SyscallSucceedsWithValue(5));
EXPECT_THAT(read(pipe_fds[0], buffer.get(), data.size()),
SyscallSucceedsWithValue(5));
EXPECT_EQ(strncmp(buffer.get(), data.c_str(), data.size()), 0);
// Cleanup.
ASSERT_THAT(close(pipe_fds[0]), SyscallSucceeds());
ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());
}
TEST(ProcSelfFdInfo, CorrectFds) {
// Make sure there is at least one open file.
auto f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(f.path(), O_RDONLY));
// Get files in /proc/self/fd.
auto fd_files = ASSERT_NO_ERRNO_AND_VALUE(ListDir("/proc/self/fd", false));
// Get files in /proc/self/fdinfo.
auto fdinfo_files =
ASSERT_NO_ERRNO_AND_VALUE(ListDir("/proc/self/fdinfo", false));
// They should contain the same fds.
EXPECT_THAT(fd_files, UnorderedElementsAreArray(fdinfo_files));
// Both should contain fd.
auto fd_s = absl::StrCat(fd.get());
EXPECT_THAT(fd_files, Contains(fd_s));
}
TEST(ProcSelfFdInfo, Flags) {
std::string path = NewTempAbsPath();
// Create file here with O_CREAT to test that O_CREAT does not appear in
// fdinfo flags.
int flags = O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC;
const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, flags, 0644));
// Automatically delete path.
TempPath temp_path(path);
// O_CREAT does not appear in fdinfo flags.
flags &= ~O_CREAT;
// O_LARGEFILE always appears (on x86_64).
flags |= kOLargeFile;
auto fd_info = ASSERT_NO_ERRNO_AND_VALUE(
GetContents(absl::StrCat("/proc/self/fdinfo/", fd.get())));
EXPECT_THAT(fd_info, HasSubstr(absl::StrFormat("flags:\t%#o", flags)));
}
TEST(ProcSelfExe, Absolute) {
auto exe = ASSERT_NO_ERRNO_AND_VALUE(
ReadLink(absl::StrCat("/proc/", getpid(), "/exe")));
EXPECT_EQ(exe[0], '/');
}
// Sanity check for /proc/cpuinfo fields that must be present.
TEST(ProcCpuinfo, RequiredFieldsArePresent) {
std::string proc_cpuinfo = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/cpuinfo"));
ASSERT_FALSE(proc_cpuinfo.empty());
std::vector<std::string> cpuinfo_fields = absl::StrSplit(proc_cpuinfo, '\n');
// This list of "required" fields is taken from reading the file
// arch/x86/kernel/cpu/proc.c and seeing which fields will be unconditionally
// printed by the kernel.
static const char* required_fields[] = {
"processor",
"vendor_id",
"cpu family",
"model\t\t:",
"model name",
"stepping",
"cpu MHz",
"fpu\t\t:",
"fpu_exception",
"cpuid level",
"wp",
"bogomips",
"clflush size",
"cache_alignment",
"address sizes",
"power management",
};
// Check that the usual fields are there. We don't really care about the
// contents.
for (const std::string& field : required_fields) {
EXPECT_THAT(proc_cpuinfo, HasSubstr(field));
}
}
// Sanity checks that uptime is present.
TEST(ProcUptime, IsPresent) {
std::string proc_uptime = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/uptime"));
ASSERT_FALSE(proc_uptime.empty());
std::vector<std::string> uptime_parts = absl::StrSplit(proc_uptime, ' ');
// Parse once.
double uptime0, uptime1, idletime0, idletime1;
ASSERT_TRUE(absl::SimpleAtod(uptime_parts[0], &uptime0));
ASSERT_TRUE(absl::SimpleAtod(uptime_parts[1], &idletime0));
// Sleep for one second.
absl::SleepFor(absl::Seconds(1));
// Parse again.
proc_uptime = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/uptime"));
ASSERT_FALSE(proc_uptime.empty());
uptime_parts = absl::StrSplit(proc_uptime, ' ');
ASSERT_TRUE(absl::SimpleAtod(uptime_parts[0], &uptime1));
ASSERT_TRUE(absl::SimpleAtod(uptime_parts[1], &idletime1));
// Sanity check.
//
// We assert that between 0.99 and 59.99 seconds have passed. If more than a
// minute has passed, then we must be executing really, really slowly.
EXPECT_GE(uptime0, 0.0);
EXPECT_GE(idletime0, 0.0);
EXPECT_GT(uptime1, uptime0);
EXPECT_GE(uptime1, uptime0 + 0.99);
EXPECT_LE(uptime1, uptime0 + 59.99);
EXPECT_GE(idletime1, idletime0);
}
TEST(ProcMeminfo, ContainsBasicFields) {
std::string proc_meminfo = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/meminfo"));
EXPECT_THAT(proc_meminfo, AllOf(ContainsRegex(R"(MemTotal:\s+[0-9]+ kB)"),
ContainsRegex(R"(MemFree:\s+[0-9]+ kB)")));
}
TEST(ProcStat, ContainsBasicFields) {
std::string proc_stat = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/stat"));
std::vector<std::string> names;
for (auto const& line : absl::StrSplit(proc_stat, '\n')) {
std::vector<std::string> fields =
absl::StrSplit(line, ' ', absl::SkipWhitespace());
if (fields.empty()) {
continue;
}
names.push_back(fields[0]);
}
EXPECT_THAT(names,
IsSupersetOf({"cpu", "intr", "ctxt", "btime", "processes",
"procs_running", "procs_blocked", "softirq"}));
}
TEST(ProcStat, EndsWithNewline) {
std::string proc_stat = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/stat"));
EXPECT_EQ(proc_stat.back(), '\n');
}
TEST(ProcStat, Fields) {
std::string proc_stat = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/stat"));
std::vector<std::string> names;
for (auto const& line : absl::StrSplit(proc_stat, '\n')) {
std::vector<std::string> fields =
absl::StrSplit(line, ' ', absl::SkipWhitespace());
if (fields.empty()) {
continue;
}
if (absl::StartsWith(fields[0], "cpu")) {
// As of Linux 3.11, each CPU entry has 10 fields, plus the name.
EXPECT_GE(fields.size(), 11) << proc_stat;
} else if (fields[0] == "ctxt") {
// Single field.
EXPECT_EQ(fields.size(), 2) << proc_stat;
} else if (fields[0] == "btime") {
// Single field.
EXPECT_EQ(fields.size(), 2) << proc_stat;
} else if (fields[0] == "itime") {
// Single field.
ASSERT_EQ(fields.size(), 2) << proc_stat;
// This is the only floating point field.
double val;
EXPECT_TRUE(absl::SimpleAtod(fields[1], &val)) << proc_stat;
continue;
} else if (fields[0] == "processes") {
// Single field.
EXPECT_EQ(fields.size(), 2) << proc_stat;
} else if (fields[0] == "procs_running") {
// Single field.
EXPECT_EQ(fields.size(), 2) << proc_stat;
} else if (fields[0] == "procs_blocked") {
// Single field.
EXPECT_EQ(fields.size(), 2) << proc_stat;
} else if (fields[0] == "softirq") {
// As of Linux 3.11, there are 10 softirqs. 12 fields for name + total.
EXPECT_GE(fields.size(), 12) << proc_stat;
}
// All fields besides itime are valid base 10 numbers.
for (size_t i = 1; i < fields.size(); i++) {
uint64_t val;
EXPECT_TRUE(absl::SimpleAtoi(fields[i], &val)) << proc_stat;
}
}
}
TEST(ProcLoadavg, EndsWithNewline) {
std::string proc_loadvg = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/loadavg"));
EXPECT_EQ(proc_loadvg.back(), '\n');
}
TEST(ProcLoadavg, Fields) {
std::string proc_loadvg = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/loadavg"));
std::vector<std::string> lines = absl::StrSplit(proc_loadvg, '\n');
// Single line.
EXPECT_EQ(lines.size(), 2) << proc_loadvg;
std::vector<std::string> fields =
absl::StrSplit(lines[0], absl::ByAnyChar(" /"), absl::SkipWhitespace());
// Six fields.
EXPECT_EQ(fields.size(), 6) << proc_loadvg;
double val;
uint64_t val2;
// First three fields are floating point numbers.
EXPECT_TRUE(absl::SimpleAtod(fields[0], &val)) << proc_loadvg;
EXPECT_TRUE(absl::SimpleAtod(fields[1], &val)) << proc_loadvg;
EXPECT_TRUE(absl::SimpleAtod(fields[2], &val)) << proc_loadvg;
// Rest of the fields are valid base 10 numbers.
EXPECT_TRUE(absl::SimpleAtoi(fields[3], &val2)) << proc_loadvg;
EXPECT_TRUE(absl::SimpleAtoi(fields[4], &val2)) << proc_loadvg;
EXPECT_TRUE(absl::SimpleAtoi(fields[5], &val2)) << proc_loadvg;
}
// NOTE: Tests in priority.cc also check certain priority related fields in
// /proc/self/stat.
class ProcPidStatTest : public ::testing::TestWithParam<std::string> {};
TEST_P(ProcPidStatTest, HasBasicFields) {
std::string proc_pid_stat = ASSERT_NO_ERRNO_AND_VALUE(
GetContents(absl::StrCat("/proc/", GetParam(), "/stat")));
ASSERT_FALSE(proc_pid_stat.empty());
std::vector<std::string> fields = absl::StrSplit(proc_pid_stat, ' ');
ASSERT_GE(fields.size(), 24);
EXPECT_EQ(absl::StrCat(getpid()), fields[0]);
// fields[1] is the thread name.
EXPECT_EQ("R", fields[2]); // task state
EXPECT_EQ(absl::StrCat(getppid()), fields[3]);
uint64_t vss;
ASSERT_TRUE(absl::SimpleAtoi(fields[22], &vss));
EXPECT_GT(vss, 0);
uint64_t rss;
ASSERT_TRUE(absl::SimpleAtoi(fields[23], &rss));
EXPECT_GT(rss, 0);
}
INSTANTIATE_TEST_CASE_P(SelfAndNumericPid, ProcPidStatTest,
::testing::Values("self", absl::StrCat(getpid())));
using ProcPidStatmTest = ::testing::TestWithParam<std::string>;
TEST_P(ProcPidStatmTest, HasBasicFields) {
std::string proc_pid_statm = ASSERT_NO_ERRNO_AND_VALUE(
GetContents(absl::StrCat("/proc/", GetParam(), "/statm")));
ASSERT_FALSE(proc_pid_statm.empty());
std::vector<std::string> fields = absl::StrSplit(proc_pid_statm, ' ');
ASSERT_GE(fields.size(), 7);
uint64_t vss;
ASSERT_TRUE(absl::SimpleAtoi(fields[0], &vss));
EXPECT_GT(vss, 0);
uint64_t rss;
ASSERT_TRUE(absl::SimpleAtoi(fields[1], &rss));
EXPECT_GT(rss, 0);
}
INSTANTIATE_TEST_CASE_P(SelfAndNumericPid, ProcPidStatmTest,
::testing::Values("self", absl::StrCat(getpid())));
PosixErrorOr<uint64_t> CurrentRSS() {
ASSIGN_OR_RETURN_ERRNO(auto proc_self_stat, GetContents("/proc/self/stat"));
if (proc_self_stat.empty()) {
return PosixError(EINVAL, "empty /proc/self/stat");
}
std::vector<std::string> fields = absl::StrSplit(proc_self_stat, ' ');
if (fields.size() < 24) {
return PosixError(
EINVAL,
absl::StrCat("/proc/self/stat has too few fields: ", proc_self_stat));
}
uint64_t rss;
if (!absl::SimpleAtoi(fields[23], &rss)) {
return PosixError(
EINVAL, absl::StrCat("/proc/self/stat RSS field is not a number: ",
fields[23]));
}
// RSS is given in number of pages.
return rss * kPageSize;
}
// The size of mapping created by MapPopulateRSS.
constexpr uint64_t kMappingSize = 100 << 20;
// Tolerance on RSS comparisons to account for background thread mappings,
// reclaimed pages, newly faulted pages, etc.
constexpr uint64_t kRSSTolerance = 5 << 20;
// Capture RSS before and after an anonymous mapping with passed prot.
void MapPopulateRSS(int prot, uint64_t* before, uint64_t* after) {
*before = ASSERT_NO_ERRNO_AND_VALUE(CurrentRSS());
// N.B. The kernel asynchronously accumulates per-task RSS counters into the
// mm RSS, which is exposed by /proc/PID/stat. Task exit is a synchronization
// point (kernel/exit.c:do_exit -> sync_mm_rss), so perform the mapping on
// another thread to ensure it is reflected in RSS after the thread exits.
Mapping mapping;
ScopedThread t([&mapping, prot] {
mapping = ASSERT_NO_ERRNO_AND_VALUE(
MmapAnon(kMappingSize, prot, MAP_PRIVATE | MAP_POPULATE));
});
t.Join();
*after = ASSERT_NO_ERRNO_AND_VALUE(CurrentRSS());
}
// TODO: Test for PROT_READ + MAP_POPULATE anonymous mappings. Their
// semantics are more subtle:
//
// Small pages -> Zero page mapped, not counted in RSS
// (mm/memory.c:do_anonymous_page).
//
// Huge pages (THP enabled, use_zero_page=0) -> Pages committed
// (mm/memory.c:__handle_mm_fault -> create_huge_pmd).
//
// Huge pages (THP enabled, use_zero_page=1) -> Zero page mapped, not counted in
// RSS (mm/huge_memory.c:do_huge_pmd_anonymous_page).
// PROT_WRITE + MAP_POPULATE anonymous mappings are always committed.
TEST(ProcSelfStat, PopulateWriteRSS) {
uint64_t before, after;
MapPopulateRSS(PROT_READ | PROT_WRITE, &before, &after);
// Mapping is committed.
EXPECT_NEAR(before + kMappingSize, after, kRSSTolerance);
}
// PROT_NONE + MAP_POPULATE anonymous mappings are never committed.
TEST(ProcSelfStat, PopulateNoneRSS) {
uint64_t before, after;
MapPopulateRSS(PROT_NONE, &before, &after);
// Mapping not committed.
EXPECT_NEAR(before, after, kRSSTolerance);
}
// Returns the calling thread's name.
PosixErrorOr<std::string> ThreadName() {
// "The buffer should allow space for up to 16 bytes; the returned std::string
// will be null-terminated if it is shorter than that." - prctl(2). But we
// always want the thread name to be null-terminated.
char thread_name[17];