2 * Copyright © 2018 Alexey Dobriyan <adobriyan@gmail.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 // Test /proc/*/fd lookup.
26 #include <sys/types.h>
32 /* lstat(2) has more "coverage" in case non-symlink pops up somehow. */
33 static void test_lookup_pass(const char *pathname
)
38 memset(&st
, 0, sizeof(struct stat
));
39 rv
= lstat(pathname
, &st
);
41 assert(S_ISLNK(st
.st_mode
));
44 static void test_lookup_fail(const char *pathname
)
49 rv
= lstat(pathname
, &st
);
50 assert(rv
== -1 && errno
== ENOENT
);
53 static void test_lookup(unsigned int fd
)
60 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%u", fd
);
61 test_lookup_pass(buf
);
64 for (c
= 1; c
<= 255; c
++) {
67 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%c%u", c
, fd
);
68 test_lookup_fail(buf
);
72 for (c
= 1; c
<= 255; c
++) {
75 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%u%c", fd
, c
);
76 test_lookup_fail(buf
);
79 for (i
= INT_MIN
; i
< INT_MIN
+ 1024; i
++) {
80 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%d", i
);
81 test_lookup_fail(buf
);
83 for (i
= -1024; i
< 0; i
++) {
84 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%d", i
);
85 test_lookup_fail(buf
);
87 for (u
= INT_MAX
- 1024; u
<= (unsigned int)INT_MAX
+ 1024; u
++) {
88 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%u", u
);
89 test_lookup_fail(buf
);
91 for (u
= UINT_MAX
- 1024; u
!= 0; u
++) {
92 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%u", u
);
93 test_lookup_fail(buf
);
102 unsigned int fd
, target_fd
;
104 if (unshare(CLONE_FILES
) == -1)
111 d
= opendir("/proc/self/fd");
116 assert(de
->d_type
== DT_DIR
);
117 assert(streq(de
->d_name
, "."));
120 assert(de
->d_type
== DT_DIR
);
121 assert(streq(de
->d_name
, ".."));
125 unsigned long long fd_ull
;
129 assert(de
->d_type
== DT_LNK
);
131 fd_ull
= xstrtoull(de
->d_name
, &end
);
132 assert(*end
== '\0');
133 assert(fd_ull
== (unsigned int)fd_ull
);
144 /* Now fdtable is clean. */
146 fd
= open("/", O_PATH
|O_DIRECTORY
);
153 fd
= open("/", O_PATH
|O_DIRECTORY
);
155 /* Default RLIMIT_NOFILE-1 */
157 while (target_fd
> 0) {
158 if (dup2(fd
, target_fd
) == target_fd
)
162 assert(target_fd
> 0);
164 test_lookup(target_fd
);