]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/memfd-util.c
3257c1b9dd4b0c8fbdbf962fc183fb75b8c3dd0e
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "alloc-util.h"
10 #include "errno-util.h"
12 #include "memfd-util.h"
13 #include "string-util.h"
16 int memfd_create_wrapper(const char *name
, unsigned mode
) {
22 /* Wrapper around memfd_create() which adds compat with older kernels where memfd_create() didn't
23 * support MFD_EXEC/MFD_NOEXEC_SEAL. (kernel 6.3+) */
25 mfd
= RET_NERRNO(memfd_create(name
, mode
));
29 mode_compat
= mode
& ~(MFD_EXEC
| MFD_NOEXEC_SEAL
);
31 if (mode
== mode_compat
)
34 return RET_NERRNO(memfd_create(name
, mode_compat
));
37 int memfd_new_full(const char *name
, unsigned extra_flags
) {
38 _cleanup_free_
char *g
= NULL
;
41 char pr
[TASK_COMM_LEN
] = {};
43 /* If no name is specified we generate one. We include
44 * a hint indicating our library implementation, and
45 * add the thread name to it */
47 assert_se(prctl(PR_GET_NAME
, (unsigned long) pr
) >= 0);
52 _cleanup_free_
char *e
= NULL
;
54 e
= utf8_escape_invalid(pr
);
58 g
= strjoin("sd-", e
);
66 return memfd_create_wrapper(
68 MFD_CLOEXEC
| MFD_NOEXEC_SEAL
| extra_flags
);
71 static int memfd_add_seals(int fd
, unsigned seals
) {
74 return RET_NERRNO(fcntl(fd
, F_ADD_SEALS
, seals
));
77 static int memfd_get_seals(int fd
, unsigned *ret_seals
) {
82 r
= RET_NERRNO(fcntl(fd
, F_GET_SEALS
));
91 int memfd_set_sealed(int fd
) {
92 return memfd_add_seals(fd
, F_SEAL_SEAL
| F_SEAL_SHRINK
| F_SEAL_GROW
| F_SEAL_WRITE
);
95 int memfd_get_sealed(int fd
) {
99 r
= memfd_get_seals(fd
, &seals
);
103 /* We ignore F_SEAL_EXEC here to support older kernels. */
104 return FLAGS_SET(seals
, F_SEAL_SHRINK
| F_SEAL_GROW
| F_SEAL_WRITE
);
107 int memfd_get_size(int fd
, uint64_t *ret
) {
113 if (fstat(fd
, &stat
) < 0)
120 int memfd_set_size(int fd
, uint64_t sz
) {
123 return RET_NERRNO(ftruncate(fd
, sz
));
126 int memfd_new_and_seal(const char *name
, const void *data
, size_t sz
) {
127 _cleanup_close_
int fd
= -EBADF
;
130 assert(data
|| sz
== 0);
135 fd
= memfd_new_full(name
, MFD_ALLOW_SEALING
);
140 ssize_t n
= pwrite(fd
, data
, sz
, 0);
143 if ((size_t) n
!= sz
)
147 r
= memfd_set_sealed(fd
);