• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 13665439908

04 Mar 2025 09:54PM UTC coverage: 71.855% (+0.04%) from 71.819%
13665439908

push

github

poettering
dirent-util: add several assertions in posix_getdents()

Follow-up for e86a492ff.

4 of 4 new or added lines in 1 file covered. (100.0%)

8029 existing lines in 84 files now uncovered.

294783 of 410245 relevant lines covered (71.86%)

717882.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.09
/src/basic/fd-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <errno.h>
4
#include <fcntl.h>
5
#include <linux/kcmp.h>
6
#include <linux/magic.h>
7
#include <sys/ioctl.h>
8
#include <sys/resource.h>
9
#include <sys/stat.h>
10
#include <unistd.h>
11

12
#include "alloc-util.h"
13
#include "dirent-util.h"
14
#include "fd-util.h"
15
#include "fileio.h"
16
#include "fs-util.h"
17
#include "io-util.h"
18
#include "macro.h"
19
#include "missing_fcntl.h"
20
#include "missing_fs.h"
21
#include "missing_syscall.h"
22
#include "mountpoint-util.h"
23
#include "parse-util.h"
24
#include "path-util.h"
25
#include "process-util.h"
26
#include "socket-util.h"
27
#include "sort-util.h"
28
#include "stat-util.h"
29
#include "stdio-util.h"
30
#include "tmpfile-util.h"
31

32
/* The maximum number of iterations in the loop to close descriptors in the fallback case
33
 * when /proc/self/fd/ is inaccessible. */
34
#define MAX_FD_LOOP_LIMIT (1024*1024)
35

36
int close_nointr(int fd) {
51,302,462✔
37
        assert(fd >= 0);
51,302,462✔
38

39
        if (close(fd) >= 0)
51,302,462✔
40
                return 0;
41

42
        /*
43
         * Just ignore EINTR; a retry loop is the wrong thing to do on
44
         * Linux.
45
         *
46
         * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
47
         * https://bugzilla.gnome.org/show_bug.cgi?id=682819
48
         * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
49
         * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
50
         */
51
        if (errno == EINTR)
16,303✔
52
                return 0;
53

54
        return -errno;
16,303✔
55
}
56

57
int safe_close(int fd) {
122,153,733✔
58
        /*
59
         * Like close_nointr() but cannot fail. Guarantees errno is unchanged. Is a noop for negative fds,
60
         * and returns -EBADF, so that it can be used in this syntax:
61
         *
62
         * fd = safe_close(fd);
63
         */
64

65
        if (fd >= 0) {
122,153,733✔
UNCOV
66
                PROTECT_ERRNO;
×
67

68
                /* The kernel might return pretty much any error code
69
                 * via close(), but the fd will be closed anyway. The
70
                 * only condition we want to check for here is whether
71
                 * the fd was invalid at all... */
72

73
                assert_se(close_nointr(fd) != -EBADF);
50,874,430✔
74
        }
75

76
        return -EBADF;
122,153,733✔
77
}
78

79
void safe_close_pair(int p[static 2]) {
524,105✔
80
        assert(p);
524,105✔
81

82
        if (p[0] == p[1]) {
524,105✔
83
                /* Special case pairs which use the same fd in both
84
                 * directions... */
85
                p[0] = p[1] = safe_close(p[0]);
492,623✔
86
                return;
492,623✔
87
        }
88

89
        p[0] = safe_close(p[0]);
31,482✔
90
        p[1] = safe_close(p[1]);
31,482✔
91
}
92

93
void close_many(const int fds[], size_t n_fds) {
2,818,265✔
94
        assert(fds || n_fds == 0);
2,818,265✔
95

96
        FOREACH_ARRAY(fd, fds, n_fds)
2,866,940✔
97
                safe_close(*fd);
48,675✔
98
}
2,818,265✔
99

100
void close_many_unset(int fds[], size_t n_fds) {
28✔
101
        assert(fds || n_fds == 0);
28✔
102

103
        FOREACH_ARRAY(fd, fds, n_fds)
29✔
104
                *fd = safe_close(*fd);
1✔
105
}
28✔
106

107
void close_many_and_free(int *fds, size_t n_fds) {
96✔
108
        assert(fds || n_fds == 0);
96✔
109

110
        close_many(fds, n_fds);
96✔
111
        free(fds);
96✔
112
}
96✔
113

114
int fclose_nointr(FILE *f) {
1,748,196✔
115
        assert(f);
1,748,196✔
116

117
        /* Same as close_nointr(), but for fclose() */
118

119
        errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
1,748,196✔
120
                    * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
121
                    * prior errno here */
122
        if (fclose(f) == 0)
1,748,196✔
123
                return 0;
124

UNCOV
125
        if (errno == EINTR)
×
126
                return 0;
127

128
        return errno_or_else(EIO);
×
129
}
130

131
FILE* safe_fclose(FILE *f) {
3,478,624✔
132

133
        /* Same as safe_close(), but for fclose() */
134

135
        if (f) {
3,478,624✔
UNCOV
136
                PROTECT_ERRNO;
×
137

138
                assert_se(fclose_nointr(f) != -EBADF);
1,748,196✔
139
        }
140

141
        return NULL;
3,478,624✔
142
}
143

UNCOV
144
DIR* safe_closedir(DIR *d) {
×
145

UNCOV
146
        if (d) {
×
147
                PROTECT_ERRNO;
×
148

149
                assert_se(closedir(d) >= 0 || errno != EBADF);
×
150
        }
151

152
        return NULL;
×
153
}
154

155
int fd_nonblock(int fd, bool nonblock) {
1,855,596✔
156
        int flags, nflags;
1,855,596✔
157

158
        assert(fd >= 0);
1,855,596✔
159

160
        flags = fcntl(fd, F_GETFL, 0);
1,855,596✔
161
        if (flags < 0)
1,855,596✔
UNCOV
162
                return -errno;
×
163

164
        nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock);
1,855,596✔
165
        if (nflags == flags)
1,855,596✔
166
                return 0;
167

168
        if (fcntl(fd, F_SETFL, nflags) < 0)
1,834,974✔
UNCOV
169
                return -errno;
×
170

171
        return 1;
172
}
173

174
int stdio_disable_nonblock(void) {
13,722✔
175
        int ret = 0;
13,722✔
176

177
        /* stdin/stdout/stderr really should have O_NONBLOCK, which would confuse apps if left on, as
178
         * write()s might unexpectedly fail with EAGAIN. */
179

180
        RET_GATHER(ret, fd_nonblock(STDIN_FILENO, false));
13,722✔
181
        RET_GATHER(ret, fd_nonblock(STDOUT_FILENO, false));
13,722✔
182
        RET_GATHER(ret, fd_nonblock(STDERR_FILENO, false));
13,722✔
183

184
        return ret;
13,722✔
185
}
186

187
int fd_cloexec(int fd, bool cloexec) {
95,029✔
188
        int flags, nflags;
95,029✔
189

190
        assert(fd >= 0);
95,029✔
191

192
        flags = fcntl(fd, F_GETFD, 0);
95,029✔
193
        if (flags < 0)
95,029✔
UNCOV
194
                return -errno;
×
195

196
        nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec);
95,029✔
197
        if (nflags == flags)
95,029✔
198
                return 0;
199

200
        return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
86,825✔
201
}
202

203
int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) {
71✔
204
        int r = 0;
71✔
205

206
        assert(fds || n_fds == 0);
71✔
207

208
        FOREACH_ARRAY(fd, fds, n_fds) {
93✔
209
                if (*fd < 0) /* Skip gracefully over already invalidated fds */
22✔
UNCOV
210
                        continue;
×
211

212
                RET_GATHER(r, fd_cloexec(*fd, cloexec));
22✔
213
        }
214

215
        return r;
71✔
216
}
217

218
static bool fd_in_set(int fd, const int fds[], size_t n_fds) {
33,623✔
219
        assert(fd >= 0);
33,623✔
220
        assert(fds || n_fds == 0);
33,623✔
221

222
        FOREACH_ARRAY(i, fds, n_fds) {
13,617,422✔
223
                if (*i < 0)
13,586,120✔
UNCOV
224
                        continue;
×
225

226
                if (*i == fd)
13,586,120✔
227
                        return true;
228
        }
229

230
        return false;
231
}
232

233
int get_max_fd(void) {
9✔
234
        struct rlimit rl;
9✔
235
        rlim_t m;
9✔
236

237
        /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
238
         * and INT_MAX as upper boundary. */
239

240
        if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
9✔
UNCOV
241
                return -errno;
×
242

243
        m = MAX(rl.rlim_cur, rl.rlim_max);
9✔
244
        if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
9✔
245
                return FD_SETSIZE-1;
246

247
        if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
9✔
248
                                                * never be above INT_MAX */
249
                return INT_MAX;
250

251
        return (int) (m - 1);
9✔
252
}
253

254
static int close_all_fds_frugal(const int except[], size_t n_except) {
4✔
255
        int max_fd, r = 0;
4✔
256

257
        assert(except || n_except == 0);
4✔
258

259
        /* This is the inner fallback core of close_all_fds(). This never calls malloc() or opendir() or so
260
         * and hence is safe to be called in signal handler context. Most users should call close_all_fds(),
261
         * but when we assume we are called from signal handler context, then use this simpler call
262
         * instead. */
263

264
        max_fd = get_max_fd();
4✔
265
        if (max_fd < 0)
4✔
266
                return max_fd;
4✔
267

268
        /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
269
         * spin the CPU for a long time. */
270
        if (max_fd > MAX_FD_LOOP_LIMIT)
4✔
UNCOV
271
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
×
272
                                       "Refusing to loop over %d potential fds.", max_fd);
273

274
        for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -EBADF) {
55,980✔
275
                int q;
27,988✔
276

277
                if (fd_in_set(fd, except, n_except))
27,988✔
278
                        continue;
1,686✔
279

280
                q = close_nointr(fd);
26,302✔
281
                if (q != -EBADF)
26,302✔
282
                        RET_GATHER(r, q);
10,000✔
283
        }
284

285
        return r;
286
}
287

288
static bool have_close_range = true; /* Assume we live in the future */
289

290
static int close_all_fds_special_case(const int except[], size_t n_except) {
44,656✔
291
        assert(n_except == 0 || except);
44,656✔
292

293
        /* Handles a few common special cases separately, since they are common and can be optimized really
294
         * nicely, since we won't need sorting for them. Returns > 0 if the special casing worked, 0
295
         * otherwise. */
296

297
        if (!have_close_range)
44,656✔
298
                return 0;
299

300
        if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid,
44,652✔
301
                                             * we got none */
302
                n_except = 0;
303

304
        switch (n_except) {
44,652✔
305

306
        case 0:
17,153✔
307
                /* Close everything. Yay! */
308

309
                if (close_range(3, INT_MAX, 0) >= 0)
17,153✔
310
                        return 1;
311

UNCOV
312
                if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
×
UNCOV
313
                        have_close_range = false;
×
UNCOV
314
                        return 0;
×
315
                }
316

317
                return -errno;
×
318

319
        case 1:
2,880✔
320
                /* Close all but exactly one, then we don't need no sorting. This is a pretty common
321
                 * case, hence let's handle it specially. */
322

323
                if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
2,880✔
324
                    (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
2,880✔
325
                        return 1;
2,880✔
326

UNCOV
327
                if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
×
UNCOV
328
                        have_close_range = false;
×
UNCOV
329
                        return 0;
×
330
                }
331

332
                return -errno;
×
333

334
        default:
335
                return 0;
336
        }
337
}
338

UNCOV
339
int close_all_fds_without_malloc(const int except[], size_t n_except) {
×
UNCOV
340
        int r;
×
341

342
        assert(n_except == 0 || except);
×
343

UNCOV
344
        r = close_all_fds_special_case(except, n_except);
×
345
        if (r < 0)
×
346
                return r;
347
        if (r > 0) /* special case worked! */
×
348
                return 0;
349

350
        return close_all_fds_frugal(except, n_except);
×
351
}
352

353
int close_all_fds(const int except[], size_t n_except) {
44,656✔
354
        _cleanup_closedir_ DIR *d = NULL;
44,656✔
355
        int r = 0;
44,656✔
356

357
        assert(n_except == 0 || except);
44,656✔
358

359
        r = close_all_fds_special_case(except, n_except);
44,656✔
360
        if (r < 0)
44,656✔
361
                return r;
362
        if (r > 0) /* special case worked! */
44,656✔
363
                return 0;
364

365
        if (have_close_range) {
24,623✔
366
                _cleanup_free_ int *sorted_malloc = NULL;
24,619✔
367
                size_t n_sorted;
24,619✔
368
                int *sorted;
24,619✔
369

370
                /* In the best case we have close_range() to close all fds between a start and an end fd,
371
                 * which we can use on the "inverted" exception array, i.e. all intervals between all
372
                 * adjacent pairs from the sorted exception array. This changes loop complexity from O(n)
373
                 * where n is number of open fds to O(mâ‹…log(m)) where m is the number of fds to keep
374
                 * open. Given that we assume n ≫ m that's preferable to us. */
375

376
                assert(n_except < SIZE_MAX);
24,619✔
377
                n_sorted = n_except + 1;
24,619✔
378

379
                if (n_sorted > 64) /* Use heap for large numbers of fds, stack otherwise */
24,619✔
380
                        sorted = sorted_malloc = new(int, n_sorted);
4✔
381
                else
382
                        sorted = newa(int, n_sorted);
24,615✔
383

384
                if (sorted) {
24,619✔
385
                        memcpy(sorted, except, n_except * sizeof(int));
24,619✔
386

387
                        /* Let's add fd 2 to the list of fds, to simplify the loop below, as this
388
                         * allows us to cover the head of the array the same way as the body */
389
                        sorted[n_sorted-1] = 2;
24,619✔
390

391
                        typesafe_qsort(sorted, n_sorted, cmp_int);
24,619✔
392

393
                        for (size_t i = 0; i < n_sorted-1; i++) {
110,571✔
394
                                int start, end;
85,954✔
395

396
                                start = MAX(sorted[i], 2); /* The first three fds shall always remain open */
85,954✔
397
                                end = MAX(sorted[i+1], 2);
85,954✔
398

399
                                assert(end >= start);
85,954✔
400

401
                                if (end - start <= 1)
85,954✔
402
                                        continue;
33,558✔
403

404
                                /* Close everything between the start and end fds (both of which shall stay open) */
405
                                if (close_range(start + 1, end - 1, 0) < 0) {
52,396✔
406
                                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
2✔
UNCOV
407
                                                return -errno;
×
408

409
                                        have_close_range = false;
2✔
410
                                        break;
2✔
411
                                }
412
                        }
413

414
                        if (have_close_range) {
24,619✔
415
                                /* The loop succeeded. Let's now close everything beyond the end */
416

417
                                if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */
24,617✔
418
                                        return 0;
419

420
                                if (close_range(sorted[n_sorted-1] + 1, INT_MAX, 0) >= 0)
24,617✔
421
                                        return 0;
422

UNCOV
423
                                if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
×
UNCOV
424
                                        return -errno;
×
425

426
                                have_close_range = false;
×
427
                        }
428
                }
429

430
                /* Fallback on OOM or if close_range() is not supported */
431
        }
432

433
        d = opendir("/proc/self/fd");
6✔
434
        if (!d)
6✔
435
                return close_all_fds_frugal(except, n_except); /* ultimate fallback if /proc/ is not available */
4✔
436

437
        FOREACH_DIRENT(de, d, return -errno) {
5,649✔
438
                int fd = -EBADF, q;
5,643✔
439

440
                if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
5,643✔
UNCOV
441
                        continue;
×
442

443
                fd = parse_fd(de->d_name);
5,643✔
444
                if (fd < 0)
5,643✔
445
                        /* Let's better ignore this, just in case */
UNCOV
446
                        continue;
×
447

448
                if (fd < 3)
5,643✔
449
                        continue;
6✔
450

451
                if (fd == dirfd(d))
5,637✔
452
                        continue;
2✔
453

454
                if (fd_in_set(fd, except, n_except))
5,635✔
455
                        continue;
635✔
456

457
                q = close_nointr(fd);
5,000✔
458
                if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
5,000✔
UNCOV
459
                        r = q;
×
460
        }
461

462
        return r;
463
}
464

465
int pack_fds(int fds[], size_t n_fds) {
11,128✔
466
        if (n_fds <= 0)
11,128✔
467
                return 0;
468

469
        /* Shifts around the fds in the provided array such that they
470
         * all end up packed next to each-other, in order, starting
471
         * from SD_LISTEN_FDS_START. This must be called after close_all_fds();
472
         * it is likely to freeze up otherwise. You should probably use safe_fork_full
473
         * with FORK_CLOSE_ALL_FDS|FORK_PACK_FDS set, to ensure that this is done correctly.
474
         * The fds array is modified in place with the new FD numbers. */
475

476
        assert(fds);
1,582✔
477

478
        for (int start = 0;;) {
479
                int restart_from = -1;
1,582✔
480

481
                for (int i = start; i < (int) n_fds; i++) {
4,166✔
482
                        int nfd;
2,584✔
483

484
                        /* Already at right index? */
485
                        if (fds[i] == i + 3)
2,584✔
UNCOV
486
                                continue;
×
487

488
                        nfd = fcntl(fds[i], F_DUPFD, i + 3);
2,584✔
489
                        if (nfd < 0)
2,584✔
UNCOV
490
                                return -errno;
×
491

492
                        safe_close(fds[i]);
2,584✔
493
                        fds[i] = nfd;
2,584✔
494

495
                        /* Hmm, the fd we wanted isn't free? Then
496
                         * let's remember that and try again from here */
497
                        if (nfd != i + 3 && restart_from < 0)
2,584✔
UNCOV
498
                                restart_from = i;
×
499
                }
500

501
                if (restart_from < 0)
1,582✔
502
                        break;
503

504
                start = restart_from;
505
        }
506

507
        assert(fds[0] == 3);
1,582✔
508

509
        return 0;
510
}
511

512
int fd_validate(int fd) {
113,966✔
513
        if (fd < 0)
113,966✔
514
                return -EBADF;
515

516
        if (fcntl(fd, F_GETFD) < 0)
113,964✔
517
                return -errno;
46,089✔
518

519
        return 0;
520
}
521

522
int same_fd(int a, int b) {
21,316✔
523
        struct stat sta, stb;
21,316✔
524
        pid_t pid;
21,316✔
525
        int r, fa, fb;
21,316✔
526

527
        assert(a >= 0);
21,316✔
528
        assert(b >= 0);
21,316✔
529

530
        /* Compares two file descriptors. Note that semantics are quite different depending on whether we
531
         * have F_DUPFD_QUERY/kcmp() or we don't. If we have F_DUPFD_QUERY/kcmp() this will only return true
532
         * for dup()ed file descriptors, but not otherwise. If we don't have F_DUPFD_QUERY/kcmp() this will
533
         * also return true for two fds of the same file, created by separate open() calls. Since we use this
534
         * call mostly for filtering out duplicates in the fd store this difference hopefully doesn't matter
535
         * too much.
536
         *
537
         * Guarantees that if either of the passed fds is not allocated we'll return -EBADF. */
538

539
        if (a == b) {
21,316✔
540
                /* Let's validate that the fd is valid */
541
                r = fd_validate(a);
7✔
542
                if (r < 0)
7✔
543
                        return r;
21,316✔
544

545
                return true;
6✔
546
        }
547

548
        /* Try to use F_DUPFD_QUERY if we have it first, as it is the nicest API */
549
        r = fcntl(a, F_DUPFD_QUERY, b);
21,309✔
550
        if (r > 0)
21,309✔
551
                return true;
552
        if (r == 0) {
21,309✔
553
                /* The kernel will return 0 in case the first fd is allocated, but the 2nd is not. (Which is different in the kcmp() case) Explicitly validate it hence. */
554
                r = fd_validate(b);
13,939✔
555
                if (r < 0)
13,939✔
556
                        return r;
557

558
                return false;
13,939✔
559
        }
560
        /* On old kernels (< 6.10) that do not support F_DUPFD_QUERY this will return EINVAL for regular fds, and EBADF on O_PATH fds. Confusing. */
561
        if (errno == EBADF) {
7,370✔
562
                /* EBADF could mean two things: the first fd is not valid, or it is valid and is O_PATH and
563
                 * F_DUPFD_QUERY is not supported. Let's validate the fd explicitly, to distinguish this
564
                 * case. */
565
                r = fd_validate(a);
5✔
566
                if (r < 0)
5✔
567
                        return r;
568

569
                /* If the fd is valid, but we got EBADF, then let's try kcmp(). */
570
        } else if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno) && errno != EINVAL)
7,365✔
UNCOV
571
                return -errno;
×
572

573
        /* Try to use kcmp() if we have it. */
574
        pid = getpid_cached();
7,369✔
575
        r = kcmp(pid, pid, KCMP_FILE, a, b);
7,369✔
576
        if (r >= 0)
7,369✔
577
                return !r;
7,368✔
578
        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
1✔
579
                return -errno;
1✔
580

581
        /* We have neither F_DUPFD_QUERY nor kcmp(), use fstat() instead. */
UNCOV
582
        if (fstat(a, &sta) < 0)
×
UNCOV
583
                return -errno;
×
584

585
        if (fstat(b, &stb) < 0)
×
586
                return -errno;
×
587

588
        if (!stat_inode_same(&sta, &stb))
×
589
                return false;
590

591
        /* We consider all device fds different, since two device fds might refer to quite different device
592
         * contexts even though they share the same inode and backing dev_t. */
593

UNCOV
594
        if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
×
595
                return false;
596

597
        /* The fds refer to the same inode on disk, let's also check if they have the same fd flags. This is
598
         * useful to distinguish the read and write side of a pipe created with pipe(). */
UNCOV
599
        fa = fcntl(a, F_GETFL);
×
UNCOV
600
        if (fa < 0)
×
UNCOV
601
                return -errno;
×
602

603
        fb = fcntl(b, F_GETFL);
×
604
        if (fb < 0)
×
UNCOV
605
                return -errno;
×
606

607
        return fa == fb;
×
608
}
609

610
void cmsg_close_all(struct msghdr *mh) {
143,713✔
611
        assert(mh);
143,713✔
612

613
        struct cmsghdr *cmsg;
143,713✔
614
        CMSG_FOREACH(cmsg, mh) {
537,908✔
615
                if (cmsg->cmsg_level != SOL_SOCKET)
125,241✔
UNCOV
616
                        continue;
×
617

618
                if (cmsg->cmsg_type == SCM_RIGHTS)
125,241✔
619
                        close_many(CMSG_TYPED_DATA(cmsg, int),
×
UNCOV
620
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
×
621
                else if (cmsg->cmsg_type == SCM_PIDFD) {
125,241✔
622
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
×
623
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
×
624
                }
625
        }
626
}
143,713✔
627

628
bool fdname_is_valid(const char *s) {
16,169✔
629
        const char *p;
16,169✔
630

631
        /* Validates a name for $LISTEN_FDNAMES. We basically allow
632
         * everything ASCII that's not a control character. Also, as
633
         * special exception the ":" character is not allowed, as we
634
         * use that as field separator in $LISTEN_FDNAMES.
635
         *
636
         * Note that the empty string is explicitly allowed
637
         * here. However, we limit the length of the names to 255
638
         * characters. */
639

640
        if (!s)
16,169✔
641
                return false;
642

643
        for (p = s; *p; p++) {
262,311✔
644
                if (*p < ' ')
246,147✔
645
                        return false;
646
                if (*p >= 127)
246,147✔
647
                        return false;
648
                if (*p == ':')
246,147✔
649
                        return false;
650
        }
651

652
        return p - s <= FDNAME_MAX;
16,164✔
653
}
654

655
int fd_get_path(int fd, char **ret) {
1,821,379✔
656
        int r;
1,821,379✔
657

658
        assert(fd >= 0 || fd == AT_FDCWD);
1,821,379✔
659

660
        if (fd == AT_FDCWD)
1,821,379✔
661
                return safe_getcwd(ret);
5,107✔
662

663
        r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret);
1,816,272✔
664
        if (r == -ENOENT)
1,816,272✔
665
                return proc_fd_enoent_errno();
4✔
666
        return r;
667
}
668

669
int move_fd(int from, int to, int cloexec) {
25,673✔
670
        int r;
25,673✔
671

672
        /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
673
         * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
674
         * off, if it is > 0 it is turned on. */
675

676
        if (from < 0)
25,673✔
677
                return -EBADF;
678
        if (to < 0)
25,673✔
679
                return -EBADF;
680

681
        if (from == to) {
25,673✔
682

UNCOV
683
                if (cloexec >= 0) {
×
UNCOV
684
                        r = fd_cloexec(to, cloexec);
×
UNCOV
685
                        if (r < 0)
×
686
                                return r;
687
                }
688

UNCOV
689
                return to;
×
690
        }
691

692
        if (cloexec < 0) {
25,673✔
UNCOV
693
                int fl;
×
694

UNCOV
695
                fl = fcntl(from, F_GETFD, 0);
×
696
                if (fl < 0)
×
UNCOV
697
                        return -errno;
×
698

699
                cloexec = FLAGS_SET(fl, FD_CLOEXEC);
×
700
        }
701

702
        r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
51,346✔
703
        if (r < 0)
25,673✔
UNCOV
704
                return -errno;
×
705

706
        assert(r == to);
25,673✔
707

708
        safe_close(from);
25,673✔
709

710
        return to;
25,673✔
711
}
712

713
int fd_move_above_stdio(int fd) {
660,410✔
714
        int flags, copy;
660,410✔
715
        PROTECT_ERRNO;
660,410✔
716

717
        /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
718
         * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
719
         * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
720
         * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
721
         * stdin/stdout/stderr of unrelated code.
722
         *
723
         * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
724
         * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
725
         * been closed before.
726
         *
727
         * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
728
         * error we simply return the original file descriptor, and we do not touch errno. */
729

730
        if (fd < 0 || fd > 2)
660,410✔
731
                return fd;
732

733
        flags = fcntl(fd, F_GETFD, 0);
103✔
734
        if (flags < 0)
103✔
735
                return fd;
736

737
        if (flags & FD_CLOEXEC)
103✔
738
                copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
101✔
739
        else
740
                copy = fcntl(fd, F_DUPFD, 3);
2✔
741
        if (copy < 0)
103✔
742
                return fd;
743

744
        assert(copy > 2);
103✔
745

746
        (void) close(fd);
103✔
747
        return copy;
748
}
749

750
int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
14,096✔
751
        int fd[3] = { original_input_fd,             /* Put together an array of fds we work on */
14,096✔
752
                      original_output_fd,
753
                      original_error_fd },
754
            null_fd = -EBADF,                        /* If we open /dev/null, we store the fd to it here */
14,096✔
755
            copy_fd[3] = EBADF_TRIPLET,              /* This contains all fds we duplicate here
14,096✔
756
                                                      * temporarily, and hence need to close at the end. */
757
            r;
758
        bool null_readable, null_writable;
14,096✔
759

760
        /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors
761
         * is specified as -EBADF it will be connected with /dev/null instead. If any of the file descriptors
762
         * is passed as itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is
763
         * turned off should it be on.
764
         *
765
         * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and
766
         * on failure! Thus, callers should assume that when this function returns the input fds are
767
         * invalidated.
768
         *
769
         * Note that when this function fails stdin/stdout/stderr might remain half set up!
770
         *
771
         * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
772
         * stdin/stdout/stderr). */
773

774
        null_readable = original_input_fd < 0;
14,096✔
775
        null_writable = original_output_fd < 0 || original_error_fd < 0;
14,096✔
776

777
        /* First step, open /dev/null once, if we need it */
778
        if (null_readable || null_writable) {
14,096✔
779

780
                /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
781
                null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
23,429✔
782
                                             null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
11,646✔
783
                if (null_fd < 0) {
11,783✔
UNCOV
784
                        r = -errno;
×
UNCOV
785
                        goto finish;
×
786
                }
787

788
                /* If this fd is in the 0…2 range, let's move it out of it */
789
                if (null_fd < 3) {
11,783✔
790
                        int copy;
75✔
791

792
                        copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
75✔
793
                        if (copy < 0) {
75✔
UNCOV
794
                                r = -errno;
×
UNCOV
795
                                goto finish;
×
796
                        }
797

798
                        close_and_replace(null_fd, copy);
75✔
799
                }
800
        }
801

802
        /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
803
        for (int i = 0; i < 3; i++)
56,384✔
804
                if (fd[i] < 0)
42,288✔
805
                        fd[i] = null_fd;        /* A negative parameter means: connect this one to /dev/null */
12,053✔
806
                else if (fd[i] != i && fd[i] < 3) {
30,235✔
807
                        /* This fd is in the 0…2 territory, but not at its intended place, move it out of there, so that we can work there. */
808
                        copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
77✔
809
                        if (copy_fd[i] < 0) {
77✔
UNCOV
810
                                r = -errno;
×
UNCOV
811
                                goto finish;
×
812
                        }
813

814
                        fd[i] = copy_fd[i];
77✔
815
                }
816

817
        /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that
818
         * we have freedom to move them around. If the fds already were at the right places then the specific
819
         * fds are -EBADF. Let's now move them to the right places. This is the point of no return. */
820
        for (int i = 0; i < 3; i++)
56,384✔
821
                if (fd[i] == i) {
42,288✔
822
                        /* fd is already in place, but let's make sure O_CLOEXEC is off */
823
                        r = fd_cloexec(i, false);
4,420✔
824
                        if (r < 0)
4,420✔
UNCOV
825
                                goto finish;
×
826
                } else {
827
                        assert(fd[i] > 2);
37,868✔
828

829
                        if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
37,868✔
UNCOV
830
                                r = -errno;
×
UNCOV
831
                                goto finish;
×
832
                        }
833
                }
834

835
        r = 0;
836

837
finish:
14,096✔
838
        /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
839
         * fd passed in multiple times. */
840
        safe_close_above_stdio(original_input_fd);
14,096✔
841
        if (original_output_fd != original_input_fd)
14,096✔
842
                safe_close_above_stdio(original_output_fd);
13,793✔
843
        if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
14,096✔
844
                safe_close_above_stdio(original_error_fd);
13,614✔
845

846
        /* Close the copies we moved > 2 */
847
        close_many(copy_fd, 3);
14,096✔
848

849
        /* Close our null fd, if it's > 2 */
850
        safe_close_above_stdio(null_fd);
14,096✔
851

852
        return r;
14,096✔
853
}
854

855
int fd_reopen(int fd, int flags) {
10,722,147✔
856
        assert(fd >= 0 || fd == AT_FDCWD);
10,722,147✔
857
        assert(!FLAGS_SET(flags, O_CREAT));
10,722,147✔
858

859
        /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
860
         * turn O_RDWR fds into O_RDONLY fds.
861
         *
862
         * This doesn't work on sockets (since they cannot be open()ed, ever).
863
         *
864
         * This implicitly resets the file read index to 0.
865
         *
866
         * If AT_FDCWD is specified as file descriptor gets an fd to the current cwd.
867
         *
868
         * If the specified file descriptor refers to a symlink via O_PATH, then this function cannot be used
869
         * to follow that symlink. Because we cannot have non-O_PATH fds to symlinks reopening it without
870
         * O_PATH will always result in -ELOOP. Or in other words: if you have an O_PATH fd to a symlink you
871
         * can reopen it only if you pass O_PATH again. */
872

873
        if (FLAGS_SET(flags, O_NOFOLLOW))
10,722,147✔
874
                /* O_NOFOLLOW is not allowed in fd_reopen(), because after all this is primarily implemented
875
                 * via a symlink-based interface in /proc/self/fd. Let's refuse this here early. Note that
876
                 * the kernel would generate ELOOP here too, hence this manual check is mostly redundant –
877
                 * the only reason we add it here is so that the O_DIRECTORY special case (see below) behaves
878
                 * the same way as the non-O_DIRECTORY case. */
879
                return -ELOOP;
10,722,147✔
880

881
        if (FLAGS_SET(flags, O_DIRECTORY) || fd == AT_FDCWD)
10,722,141✔
882
                /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole
883
                 * magic /proc/ directory, and make ourselves independent of that being mounted. */
884
                return RET_NERRNO(openat(fd, ".", flags | O_DIRECTORY));
238,871✔
885

886
        int new_fd = open(FORMAT_PROC_FD_PATH(fd), flags);
10,483,276✔
887
        if (new_fd < 0) {
10,483,276✔
888
                if (errno != ENOENT)
94,502✔
889
                        return -errno;
94,499✔
890

891
                return proc_fd_enoent_errno();
3✔
892
        }
893

894
        return new_fd;
895
}
896

897
int fd_reopen_propagate_append_and_position(int fd, int flags) {
28✔
898
        /* Invokes fd_reopen(fd, flags), but propagates O_APPEND if set on original fd, and also tries to
899
         * keep current file position.
900
         *
901
         * You should use this if the original fd potentially is O_APPEND, otherwise we get rather
902
         * "unexpected" behavior. Unless you intentionally want to overwrite pre-existing data, and have
903
         * your output overwritten by the next user.
904
         *
905
         * Use case: "systemd-run --pty >> some-log".
906
         *
907
         * The "keep position" part is obviously nonsense for the O_APPEND case, but should reduce surprises
908
         * if someone carefully pre-positioned the passed in original input or non-append output FDs. */
909

910
        assert(fd >= 0);
28✔
911
        assert(!(flags & (O_APPEND|O_DIRECTORY)));
28✔
912

913
        int existing_flags = fcntl(fd, F_GETFL);
28✔
914
        if (existing_flags < 0)
28✔
UNCOV
915
                return -errno;
×
916

917
        int new_fd = fd_reopen(fd, flags | (existing_flags & O_APPEND));
28✔
918
        if (new_fd < 0)
28✔
919
                return new_fd;
920

921
        /* Try to adjust the offset, but ignore errors. */
922
        off_t p = lseek(fd, 0, SEEK_CUR);
19✔
923
        if (p > 0) {
19✔
UNCOV
924
                off_t new_p = lseek(new_fd, p, SEEK_SET);
×
UNCOV
925
                if (new_p < 0)
×
UNCOV
926
                        log_debug_errno(errno,
×
927
                                        "Failed to propagate file position for re-opened fd %d, ignoring: %m",
928
                                        fd);
929
                else if (new_p != p)
×
UNCOV
930
                        log_debug("Failed to propagate file position for re-opened fd %d (%lld != %lld), ignoring.",
×
931
                                  fd, (long long) new_p, (long long) p);
932
        }
933

934
        return new_fd;
935
}
936

937
int fd_reopen_condition(
1,197,391✔
938
                int fd,
939
                int flags,
940
                int mask,
941
                int *ret_new_fd) {
942

943
        int r, new_fd;
1,197,391✔
944

945
        assert(fd >= 0);
1,197,391✔
946
        assert(!FLAGS_SET(flags, O_CREAT));
1,197,391✔
947

948
        /* Invokes fd_reopen(fd, flags), but only if the existing F_GETFL flags don't match the specified
949
         * flags (masked by the specified mask). This is useful for converting O_PATH fds into real fds if
950
         * needed, but only then. */
951

952
        r = fcntl(fd, F_GETFL);
1,197,391✔
953
        if (r < 0)
1,197,391✔
UNCOV
954
                return -errno;
×
955

956
        if ((r & mask) == (flags & mask)) {
1,197,391✔
957
                *ret_new_fd = -EBADF;
1,193,386✔
958
                return fd;
1,193,386✔
959
        }
960

961
        new_fd = fd_reopen(fd, flags);
4,005✔
962
        if (new_fd < 0)
4,005✔
963
                return new_fd;
964

965
        *ret_new_fd = new_fd;
4,005✔
966
        return new_fd;
4,005✔
967
}
968

969
int fd_is_opath(int fd) {
444,171✔
970
        int r;
444,171✔
971

972
        assert(fd >= 0);
444,171✔
973

974
        r = fcntl(fd, F_GETFL);
444,171✔
975
        if (r < 0)
444,171✔
UNCOV
976
                return -errno;
×
977

978
        return FLAGS_SET(r, O_PATH);
444,171✔
979
}
980

981
int fd_verify_safe_flags_full(int fd, int extra_flags) {
466✔
982
        int flags, unexpected_flags;
466✔
983

984
        /* Check if an extrinsic fd is safe to work on (by a privileged service). This ensures that clients
985
         * can't trick a privileged service into giving access to a file the client doesn't already have
986
         * access to (especially via something like O_PATH).
987
         *
988
         * O_NOFOLLOW: For some reason the kernel will return this flag from fcntl(); it doesn't go away
989
         *             immediately after open(). It should have no effect whatsoever to an already-opened FD,
990
         *             and since we refuse O_PATH it should be safe.
991
         *
992
         * RAW_O_LARGEFILE: glibc secretly sets this and neglects to hide it from us if we call fcntl.
993
         *                  See comment in missing_fcntl.h for more details about this.
994
         *
995
         * If 'extra_flags' is specified as non-zero the included flags are also allowed.
996
         */
997

998
        assert(fd >= 0);
466✔
999

1000
        flags = fcntl(fd, F_GETFL);
466✔
1001
        if (flags < 0)
466✔
UNCOV
1002
                return -errno;
×
1003

1004
        unexpected_flags = flags & ~(O_ACCMODE|O_NOFOLLOW|RAW_O_LARGEFILE|extra_flags);
466✔
1005
        if (unexpected_flags != 0)
466✔
UNCOV
1006
                return log_debug_errno(SYNTHETIC_ERRNO(EREMOTEIO),
×
1007
                                       "Unexpected flags set for extrinsic fd: 0%o",
1008
                                       (unsigned) unexpected_flags);
1009

1010
        return flags & (O_ACCMODE | extra_flags); /* return the flags variable, but remove the noise */
466✔
1011
}
1012

1013
int read_nr_open(void) {
27,821✔
1014
        _cleanup_free_ char *nr_open = NULL;
27,821✔
1015
        int r;
27,821✔
1016

1017
        /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the
1018
         * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */
1019

1020
        r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
27,821✔
1021
        if (r < 0)
27,821✔
1022
                log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
27,821✔
1023
        else {
1024
                int v;
27,818✔
1025

1026
                r = safe_atoi(nr_open, &v);
27,818✔
1027
                if (r < 0)
27,818✔
UNCOV
1028
                        log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
×
1029
                else
1030
                        return v;
27,818✔
1031
        }
1032

1033
        /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */
1034
        return 1024 * 1024;
1035
}
1036

1037
int fd_get_diskseq(int fd, uint64_t *ret) {
56,311✔
1038
        uint64_t diskseq;
56,311✔
1039

1040
        assert(fd >= 0);
56,311✔
1041
        assert(ret);
56,311✔
1042

1043
        if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) {
56,311✔
1044
                /* Note that the kernel is weird: non-existing ioctls currently return EINVAL
1045
                 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
1046
                 * but in the meantime we accept both here. */
UNCOV
1047
                if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
×
UNCOV
1048
                        return -errno;
×
1049

1050
                return -EOPNOTSUPP;
1051
        }
1052

1053
        *ret = diskseq;
56,311✔
1054

1055
        return 0;
56,311✔
1056
}
1057

1058
int path_is_root_at(int dir_fd, const char *path) {
3,631,900✔
1059
        _cleanup_close_ int fd = -EBADF, pfd = -EBADF;
3,631,900✔
1060

1061
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
3,631,900✔
1062

1063
        if (!isempty(path)) {
3,631,900✔
1064
                fd = openat(dir_fd, path, O_PATH|O_DIRECTORY|O_CLOEXEC);
124,918✔
1065
                if (fd < 0)
124,918✔
1066
                        return errno == ENOTDIR ? false : -errno;
14,213✔
1067

1068
                dir_fd = fd;
1069
        }
1070

1071
        pfd = openat(dir_fd, "..", O_PATH|O_DIRECTORY|O_CLOEXEC);
3,617,687✔
1072
        if (pfd < 0)
3,617,687✔
1073
                return errno == ENOTDIR ? false : -errno;
2✔
1074

1075
        /* Even if the parent directory has the same inode, the fd may not point to the root directory "/",
1076
         * and we also need to check that the mount ids are the same. Otherwise, a construct like the
1077
         * following could be used to trick us:
1078
         *
1079
         * $ mkdir /tmp/x /tmp/x/y
1080
         * $ mount --bind /tmp/x /tmp/x/y
1081
         */
1082

1083
        return fds_are_same_mount(dir_fd, pfd);
3,617,685✔
1084
}
1085

1086
int fds_are_same_mount(int fd1, int fd2) {
3,617,755✔
1087
        struct statx sx1 = {}, sx2 = {}; /* explicitly initialize the struct to make msan silent. */
3,617,755✔
1088
        int r;
3,617,755✔
1089

1090
        assert(fd1 >= 0);
3,617,755✔
1091
        assert(fd2 >= 0);
3,617,755✔
1092

1093
        if (statx(fd1, "", AT_EMPTY_PATH, STATX_TYPE|STATX_INO|STATX_MNT_ID, &sx1) < 0)
3,617,755✔
UNCOV
1094
                return -errno;
×
1095

1096
        if (statx(fd2, "", AT_EMPTY_PATH, STATX_TYPE|STATX_INO|STATX_MNT_ID, &sx2) < 0)
3,617,755✔
1097
                return -errno;
×
1098

1099
        /* First, compare inode. If these are different, the fd does not point to the root directory "/". */
1100
        if (!statx_inode_same(&sx1, &sx2))
3,617,755✔
1101
                return false;
1102

1103
        /* Note, statx() does not provide the mount ID and path_get_mnt_id_at() does not work when an old
1104
         * kernel is used. In that case, let's assume that we do not have such spurious mount points in an
1105
         * early boot stage, and silently skip the following check. */
1106

1107
        if (!FLAGS_SET(sx1.stx_mask, STATX_MNT_ID)) {
3,290,899✔
UNCOV
1108
                int mntid;
×
1109

UNCOV
1110
                r = path_get_mnt_id_at_fallback(fd1, "", &mntid);
×
1111
                if (r < 0)
×
UNCOV
1112
                        return r;
×
1113
                assert(mntid >= 0);
×
1114

1115
                sx1.stx_mnt_id = mntid;
×
1116
                sx1.stx_mask |= STATX_MNT_ID;
×
1117
        }
1118

1119
        if (!FLAGS_SET(sx2.stx_mask, STATX_MNT_ID)) {
3,290,899✔
UNCOV
1120
                int mntid;
×
1121

UNCOV
1122
                r = path_get_mnt_id_at_fallback(fd2, "", &mntid);
×
1123
                if (r < 0)
×
UNCOV
1124
                        return r;
×
1125
                assert(mntid >= 0);
×
1126

1127
                sx2.stx_mnt_id = mntid;
×
1128
                sx2.stx_mask |= STATX_MNT_ID;
×
1129
        }
1130

1131
        return statx_mount_same(&sx1, &sx2);
3,290,899✔
1132
}
1133

1134
const char* accmode_to_string(int flags) {
176✔
1135
        switch (flags & O_ACCMODE) {
176✔
1136
        case O_RDONLY:
1137
                return "ro";
1138
        case O_WRONLY:
3✔
1139
                return "wo";
3✔
1140
        case O_RDWR:
170✔
1141
                return "rw";
170✔
UNCOV
1142
        default:
×
UNCOV
1143
                return NULL;
×
1144
        }
1145
}
1146

1147
char* format_proc_pid_fd_path(char buf[static PROC_PID_FD_PATH_MAX], pid_t pid, int fd) {
1✔
1148
        assert(buf);
1✔
1149
        assert(fd >= 0);
1✔
1150
        assert(pid >= 0);
1✔
1151
        assert_se(snprintf_ok(buf, PROC_PID_FD_PATH_MAX, "/proc/" PID_FMT "/fd/%i", pid == 0 ? getpid_cached() : pid, fd));
1✔
1152
        return buf;
1✔
1153
}
1154

1155
int proc_fd_enoent_errno(void) {
7✔
1156
        int r;
7✔
1157

1158
        /* When ENOENT is returned during the use of FORMAT_PROC_FD_PATH, it can mean two things:
1159
         * that the fd does not exist or that /proc/ is not mounted.
1160
         * Let's make things debuggable and figure out the most appropriate errno. */
1161

1162
        r = proc_mounted();
7✔
1163
        if (r == 0)
7✔
1164
                return -ENOSYS;  /* /proc/ is not available or not set up properly, we're most likely
1165
                                    in some chroot environment. */
1166
        if (r > 0)
7✔
1167
                return -EBADF;   /* If /proc/ is definitely around then this means the fd is not valid. */
7✔
1168

1169
        return -ENOENT;          /* Otherwise let's propagate the original ENOENT. */
1170
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc