1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gtest/gtest.h>
18
19 #include <dirent.h>
20 #include <err.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <netinet/in.h>
24 #include <stdlib.h>
25 #include <sys/epoll.h>
26 #include <sys/eventfd.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29
30 #if defined(__BIONIC__)
31 #include <sys/pidfd.h>
32
33 #include "platform/bionic/fdtrack.h"
34 #include "platform/bionic/reserved_signals.h"
35 #endif
36
37 #include <vector>
38
39 #include <android-base/cmsg.h>
40 #include <android-base/logging.h>
41 #include <android-base/unique_fd.h>
42
43 #include "utils.h"
44
45 using android::base::ReceiveFileDescriptors;
46 using android::base::SendFileDescriptors;
47 using android::base::unique_fd;
48
49 #if defined(__BIONIC__)
DumpEvent(std::vector<android_fdtrack_event> * events,size_t index)50 void DumpEvent(std::vector<android_fdtrack_event>* events, size_t index) {
51 auto& event = (*events)[index];
52 if (event.type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
53 fprintf(stderr, " event %zu: fd %d created by %s\n", index, event.fd,
54 event.data.create.function_name);
55 } else if (event.type == ANDROID_FDTRACK_EVENT_TYPE_CLOSE) {
56 fprintf(stderr, " event %zu: fd %d closed\n", index, event.fd);
57 } else {
58 errx(1, "unexpected fdtrack event type: %d", event.type);
59 }
60 }
61
FdtrackRun(void (* func)(),bool reenable=true)62 std::vector<android_fdtrack_event> FdtrackRun(void (*func)(), bool reenable = true) {
63 // Each bionic test is run in separate process, so we can safely use a static here.
64 // However, since they're all forked, we need to reenable fdtrack.
65 if (reenable) {
66 android_fdtrack_set_globally_enabled(true);
67 }
68
69 static std::vector<android_fdtrack_event> events;
70 events.clear();
71
72 android_fdtrack_hook_t previous = nullptr;
73 android_fdtrack_hook_t hook = [](android_fdtrack_event* event) { events.push_back(*event); };
74
75 if (!android_fdtrack_compare_exchange_hook(&previous, hook)) {
76 errx(1, "failed to exchange hook: previous hook was %p", previous);
77 }
78
79 if (previous) {
80 errx(1, "hook was already registered?");
81 abort();
82 }
83
84 func();
85
86 if (!android_fdtrack_compare_exchange_hook(&hook, nullptr)) {
87 errx(1, "failed to reset hook");
88 }
89
90 // Filter out temporary fds created and closed as a result of the call.
91 // (e.g. accept creating a socket to tell netd about the newly accepted socket)
92 size_t i = 0;
93 while (i + 1 < events.size()) {
94 auto& event = events[i];
95 if (event.type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
96 for (size_t j = i + 1; j < events.size(); ++j) {
97 if (event.fd == events[j].fd) {
98 if (events[j].type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
99 fprintf(stderr, "error: multiple create events for the same fd:\n");
100 DumpEvent(&events, i);
101 DumpEvent(&events, j);
102 exit(1);
103 }
104
105 events.erase(events.begin() + j);
106 events.erase(events.begin() + i);
107 continue;
108 }
109 }
110 }
111 ++i;
112 }
113
114 return std::move(events);
115 }
116
FdtrackEventTypeToName(android_fdtrack_event_type event_type)117 const char* FdtrackEventTypeToName(android_fdtrack_event_type event_type) {
118 switch (event_type) {
119 case ANDROID_FDTRACK_EVENT_TYPE_CREATE:
120 return "created";
121 case ANDROID_FDTRACK_EVENT_TYPE_CLOSE:
122 return "closed";
123 }
124 }
125 #endif
126
TEST(fdtrack,close)127 TEST(fdtrack, close) {
128 #if defined(__BIONIC__)
129 static int fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
130 ASSERT_NE(-1, fd);
131
132 auto events = FdtrackRun([]() { close(fd); });
133 ASSERT_EQ(1U, events.size());
134 ASSERT_EQ(fd, events[0].fd);
135 ASSERT_EQ(ANDROID_FDTRACK_EVENT_TYPE_CLOSE, events[0].type);
136 #endif
137 }
138
TEST(fdtrack,fork)139 TEST(fdtrack, fork) {
140 #if defined(__BIONIC__)
141 ASSERT_EXIT(
142 []() {
143 static int fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
144 ASSERT_NE(-1, fd);
145
146 auto events = FdtrackRun([]() { close(fd); }, false);
147 ASSERT_EQ(0U, events.size());
148 exit(0);
149 }(),
150 testing::ExitedWithCode(0), "");
151 #endif
152 }
153
TEST(fdtrack,enable_disable)154 TEST(fdtrack, enable_disable) {
155 #if defined(__BIONIC__)
156 static int fd1 = -1;
157 static int fd2 = -1;
158 static int fd3 = -1;
159
160 auto events = FdtrackRun([]() {
161 if (!android_fdtrack_get_enabled()) {
162 errx(1, "fdtrack is disabled");
163 }
164 fd1 = open("/dev/null", O_WRONLY | O_CLOEXEC);
165 android_fdtrack_set_enabled(false);
166 fd2 = open("/dev/null", O_WRONLY | O_CLOEXEC);
167 android_fdtrack_set_enabled(true);
168 fd3 = open("/dev/null", O_WRONLY | O_CLOEXEC);
169 });
170
171 if (fd1 == -1 || fd2 == -1 || fd3 == -1) {
172 errx(1, "failed to open /dev/null");
173 }
174
175 ASSERT_EQ(2U, events.size());
176
177 ASSERT_EQ(fd1, events[0].fd);
178 ASSERT_EQ(ANDROID_FDTRACK_EVENT_TYPE_CREATE, events[0].type);
179 ASSERT_STREQ("open", events[0].data.create.function_name);
180
181 ASSERT_EQ(fd3, events[1].fd);
182 ASSERT_EQ(ANDROID_FDTRACK_EVENT_TYPE_CREATE, events[1].type);
183 ASSERT_STREQ("open", events[1].data.create.function_name);
184 #endif
185 }
186
187 struct require_semicolon;
188
189 #if defined(__BIONIC__)
SetFdResult(std::vector<int> * output,int fd)190 void SetFdResult(std::vector<int>* output, int fd) {
191 output->push_back(fd);
192 }
193
SetFdResult(std::vector<int> * output,std::vector<int> fds)194 void SetFdResult(std::vector<int>* output, std::vector<int> fds) {
195 *output = fds;
196 }
197
198 #define FDTRACK_TEST_NAME(test_name, fdtrack_name, expression) \
199 TEST(fdtrack, test_name) { \
200 static std::vector<int> expected_fds; \
201 auto events = FdtrackRun([]() { SetFdResult(&expected_fds, expression); }); \
202 for (auto& fd : expected_fds) { \
203 ASSERT_NE(-1, fd) << strerror(errno); \
204 } \
205 if (events.size() != expected_fds.size()) { \
206 fprintf(stderr, "too many events received: expected %zu, got %zu:\n", expected_fds.size(), \
207 events.size()); \
208 for (size_t i = 0; i < events.size(); ++i) { \
209 DumpEvent(&events, i); \
210 } \
211 FAIL(); \
212 return; \
213 } \
214 for (auto& event : events) { \
215 ASSERT_NE(expected_fds.end(), \
216 std::find(expected_fds.begin(), expected_fds.end(), events[0].fd)); \
217 ASSERT_EQ(ANDROID_FDTRACK_EVENT_TYPE_CREATE, event.type); \
218 ASSERT_STREQ(fdtrack_name, event.data.create.function_name); \
219 } \
220 } \
221 struct require_semicolon
222 #else
223 #define FDTRACK_TEST_NAME(name, fdtrack_name, expression) \
224 TEST(fdtrack, name) {} \
225 struct require_semicolon
226 #endif
227
228 #define FDTRACK_TEST(name, expression) FDTRACK_TEST_NAME(name, #name, expression)
229
230 // clang-format misformats statement expressions pretty badly here:
231 // clang-format off
232 FDTRACK_TEST(open, open("/dev/null", O_WRONLY | O_CLOEXEC));
233 FDTRACK_TEST(openat, openat(AT_EMPTY_PATH, "/dev/null", O_WRONLY | O_CLOEXEC));
234 FDTRACK_TEST(socket, socket(AF_UNIX, SOCK_STREAM, 0));
235
236 FDTRACK_TEST(pidfd_open, ({
237 int rc = pidfd_open(getpid(), 0);
238 if (rc == -1 && errno == ENOSYS) GTEST_SKIP() << "no pidfd_open() in this kernel";
239 ASSERT_NE(-1, rc) << strerror(errno);
240 rc;
241 }));
242
243 FDTRACK_TEST(pidfd_getfd, ({
244 android_fdtrack_set_enabled(false);
245 int pidfd_self = pidfd_open(getpid(), 0);
246 if (pidfd_self == -1 && errno == ENOSYS) GTEST_SKIP() << "no pidfd_open() in this kernel";
247 ASSERT_NE(-1, pidfd_self) << strerror(errno);
248
249 android_fdtrack_set_enabled(true);
250
251 int rc = pidfd_getfd(pidfd_self, STDIN_FILENO, 0);
252 if (rc == -1 && errno == ENOSYS) GTEST_SKIP() << "no pidfd_getfd() in this kernel";
253 ASSERT_NE(-1, rc) << strerror(errno);
254
255 android_fdtrack_set_enabled(false);
256 close(pidfd_self);
257 android_fdtrack_set_enabled(true);
258
259 rc;
260 }));
261
262 FDTRACK_TEST(dup, dup(STDOUT_FILENO));
263 FDTRACK_TEST(dup2, dup2(STDOUT_FILENO, STDERR_FILENO));
264 FDTRACK_TEST(dup3, dup3(STDOUT_FILENO, STDERR_FILENO, 0));
265 FDTRACK_TEST_NAME(fcntl_F_DUPFD, "F_DUPFD", fcntl(STDOUT_FILENO, F_DUPFD, 0));
266 FDTRACK_TEST_NAME(fcntl_F_DUPFD_CLOEXEC, "F_DUPFD_CLOEXEC", fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 0));
267
268 FDTRACK_TEST(pipe, ({
269 std::vector<int> fds = { -1, -1};
270 if (pipe(fds.data()) != 0) {
271 err(1, "pipe failed");
272 }
273 fds;
274 }));
275
276 FDTRACK_TEST(pipe2, ({
277 std::vector<int> fds = { -1, -1};
278 if (pipe2(fds.data(), O_CLOEXEC) != 0) {
279 err(1, "pipe failed");
280 }
281 fds;
282 }));
283
284 FDTRACK_TEST(socketpair, ({
285 std::vector<int> fds = { -1, -1};
286 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds.data()) != 0) {
287 err(1, "socketpair failed");
288 }
289 fds;
290 }));
291
292 FDTRACK_TEST(epoll_create, epoll_create(1));
293 FDTRACK_TEST(epoll_create1, epoll_create1(0));
294
295 FDTRACK_TEST(eventfd, eventfd(0, 0));
296
297 #if defined(__BIONIC__)
CreateListener()298 static int CreateListener() {
299 android_fdtrack_set_enabled(false);
300 int listener = socket(AF_INET, SOCK_STREAM, 0);
301 CHECK_NE(-1, listener);
302
303 sockaddr_in addr = {
304 .sin_family = AF_INET,
305 .sin_port = 0,
306 .sin_addr = {htonl(INADDR_LOOPBACK)},
307 };
308 socklen_t addrlen = sizeof(addr);
309
310 CHECK_NE(-1, bind(listener, reinterpret_cast<sockaddr*>(&addr), addrlen)) << strerror(errno);
311 CHECK_NE(-1, getsockname(listener, reinterpret_cast<sockaddr*>(&addr), &addrlen));
312 CHECK_EQ(static_cast<size_t>(addrlen), sizeof(addr));
313 CHECK_NE(-1, listen(listener, 1));
314
315 int connector = socket(AF_INET, SOCK_STREAM, 0);
316 CHECK_NE(-1, connector);
317 CHECK_NE(-1, connect(connector, reinterpret_cast<sockaddr*>(&addr), addrlen));
318 android_fdtrack_set_enabled(true);
319
320 return listener;
321 }
322 #endif
323
324 FDTRACK_TEST_NAME(accept, "accept4", accept(CreateListener(), nullptr, nullptr));
325 FDTRACK_TEST(accept4, accept4(CreateListener(), nullptr, nullptr, 0));
326
327 FDTRACK_TEST(recvmsg, ({
328 android_fdtrack_set_enabled(false);
329 int sockets[2];
330 ASSERT_NE(-1, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets));
331 ASSERT_EQ(3, SendFileDescriptors(sockets[0], "foo", 3, STDIN_FILENO));
332 android_fdtrack_set_enabled(true);
333
334 char buf[4];
335 unique_fd received_fd;
336 ASSERT_EQ(3, ReceiveFileDescriptors(sockets[1], buf, sizeof(buf), &received_fd));
337 received_fd.release();
338 }));
339
340 FDTRACK_TEST_NAME(vfork, "open", ({
341 int fd = open("/dev/null", O_RDONLY);
342
343 pid_t rc = vfork();
344 ASSERT_NE(-1, rc);
345
346 if (rc == 0) {
347 close(fd);
348 _exit(0);
349 }
350
351 int status;
352 pid_t wait_result = waitpid(rc, &status, 0);
353 ASSERT_EQ(wait_result, rc);
354 ASSERT_TRUE(WIFEXITED(status));
355 ASSERT_EQ(0, WEXITSTATUS(status));
356
357 fd;
358 }));
359 // clang-format on
360