]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/memfd-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2013 Lennart Poettering
10 #if HAVE_LINUX_MEMFD_H
11 #include <linux/memfd.h>
15 #include <sys/prctl.h>
17 #include "alloc-util.h"
20 #include "memfd-util.h"
22 #include "string-util.h"
25 int memfd_new(const char *name
) {
26 _cleanup_free_
char *g
= NULL
;
32 /* If no name is specified we generate one. We include
33 * a hint indicating our library implementation, and
34 * add the thread name to it */
36 assert_se(prctl(PR_GET_NAME
, (unsigned long) pr
) >= 0);
41 _cleanup_free_
char *e
= NULL
;
43 e
= utf8_escape_invalid(pr
);
47 g
= strappend("sd-", e
);
55 fd
= memfd_create(name
, MFD_ALLOW_SEALING
| MFD_CLOEXEC
);
62 int memfd_map(int fd
, uint64_t offset
, size_t size
, void **p
) {
70 sealed
= memfd_get_sealed(fd
);
75 q
= mmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, offset
);
77 q
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, offset
);
86 int memfd_set_sealed(int fd
) {
91 r
= fcntl(fd
, F_ADD_SEALS
, F_SEAL_SHRINK
| F_SEAL_GROW
| F_SEAL_WRITE
| F_SEAL_SEAL
);
98 int memfd_get_sealed(int fd
) {
103 r
= fcntl(fd
, F_GET_SEALS
);
107 return r
== (F_SEAL_SHRINK
| F_SEAL_GROW
| F_SEAL_WRITE
| F_SEAL_SEAL
);
110 int memfd_get_size(int fd
, uint64_t *sz
) {
117 r
= fstat(fd
, &stat
);
125 int memfd_set_size(int fd
, uint64_t sz
) {
130 r
= ftruncate(fd
, sz
);
137 int memfd_new_and_map(const char *name
, size_t sz
, void **p
) {
138 _cleanup_close_
int fd
= -1;
144 fd
= memfd_new(name
);
148 r
= memfd_set_size(fd
, sz
);
152 r
= memfd_map(fd
, 0, sz
, p
);