Debian Codegraph @

src/test/test-data-fd-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/socket.h>
5 #include <unistd.h>
6
7 #include "data-fd-util.h"
8 #include "fd-util.h"
9 #include "memfd-util.h"
10 #include "pidref.h"
11 #include "process-util.h"
12 #include "tests.h"
13
14 static void assert_equal_fd(int fd1, int fd2) {
15 for (;;) {
16 uint8_t a[4096], b[4096];
17 ssize_t x, y;
18
19 x = read(fd1, a, sizeof(a));
20 assert_se(x >= 0);
21
22 y = read(fd2, b, sizeof(b));
23 assert_se(y >= 0);
24
25 assert_se(x == y);
26
27 if (x == 0)
28 break;
29
30 assert_se(memcmp(a, b, x) == 0);
31 }
32 }
33
34 TEST(copy_data_fd) {
35 _cleanup_close_ int fd1 = -EBADF, fd2 = -EBADF;
36 _cleanup_close_pair_ int sfd[2] = EBADF_PAIR;
37 _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
38 int r;
39
40 fd1 = open("/etc/fstab", O_RDONLY|O_CLOEXEC);
41 if (fd1 >= 0) {
42
43 fd2 = copy_data_fd(fd1);
44 assert_se(fd2 >= 0);
45
46 assert_se(lseek(fd1, 0, SEEK_SET) == 0);
47 assert_equal_fd(fd1, fd2);
48 }
49
50 fd1 = safe_close(fd1);
51 fd2 = safe_close(fd2);
52
53 fd1 = memfd_new_and_seal_string("data", "hallo");
54 assert_se(fd1 >= 0);
55
56 fd2 = copy_data_fd(fd1);
57 assert_se(fd2 >= 0);
58
59 safe_close(fd1);
60 fd1 = memfd_new_and_seal_string("data", "hallo");
61 assert_se(fd1 >= 0);
62
63 assert_equal_fd(fd1, fd2);
64
65 fd1 = safe_close(fd1);
66 fd2 = safe_close(fd2);
67
68 assert_se(socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, sfd) >= 0);
69
70 r = pidref_safe_fork("(sd-pipe)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_LOG, &pidref);
71 assert_se(r >= 0);
72
73 if (r == 0) {
74 /* child */
75
76 sfd[0] = safe_close(sfd[0]);
77
78 for (uint64_t i = 0; i < 1536*1024 / sizeof(uint64_t); i++)
79 assert_se(write(sfd[1], &i, sizeof(i)) == sizeof(i));
80
81 sfd[1] = safe_close(sfd[1]);
82
83 _exit(EXIT_SUCCESS);
84 }
85
86 sfd[1] = safe_close(sfd[1]);
87
88 fd2 = copy_data_fd(sfd[0]);
89 assert_se(fd2 >= 0);
90
91 uint64_t j;
92 for (uint64_t i = 0; i < 1536*1024 / sizeof(uint64_t); i++) {
93 assert_se(read(fd2, &j, sizeof(j)) == sizeof(j));
94 assert_se(i == j);
95 }
96
97 assert_se(read(fd2, &j, sizeof(j)) == 0);
98 }
99
100 DEFINE_TEST_MAIN(LOG_DEBUG);