]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/memfd-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #if HAVE_LINUX_MEMFD_H
26 #include <linux/memfd.h>
30 #include <sys/prctl.h>
32 #include "alloc-util.h"
35 #include "memfd-util.h"
37 #include "string-util.h"
40 int memfd_new(const char *name
) {
41 _cleanup_free_
char *g
= NULL
;
47 /* If no name is specified we generate one. We include
48 * a hint indicating our library implementation, and
49 * add the thread name to it */
51 assert_se(prctl(PR_GET_NAME
, (unsigned long) pr
) >= 0);
56 _cleanup_free_
char *e
= NULL
;
58 e
= utf8_escape_invalid(pr
);
62 g
= strappend("sd-", e
);
70 fd
= memfd_create(name
, MFD_ALLOW_SEALING
| MFD_CLOEXEC
);
77 int memfd_map(int fd
, uint64_t offset
, size_t size
, void **p
) {
85 sealed
= memfd_get_sealed(fd
);
90 q
= mmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, offset
);
92 q
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, offset
);
101 int memfd_set_sealed(int fd
) {
106 r
= fcntl(fd
, F_ADD_SEALS
, F_SEAL_SHRINK
| F_SEAL_GROW
| F_SEAL_WRITE
| F_SEAL_SEAL
);
113 int memfd_get_sealed(int fd
) {
118 r
= fcntl(fd
, F_GET_SEALS
);
122 return r
== (F_SEAL_SHRINK
| F_SEAL_GROW
| F_SEAL_WRITE
| F_SEAL_SEAL
);
125 int memfd_get_size(int fd
, uint64_t *sz
) {
132 r
= fstat(fd
, &stat
);
140 int memfd_set_size(int fd
, uint64_t sz
) {
145 r
= ftruncate(fd
, sz
);
152 int memfd_new_and_map(const char *name
, size_t sz
, void **p
) {
153 _cleanup_close_
int fd
= -1;
159 fd
= memfd_new(name
);
163 r
= memfd_set_size(fd
, sz
);
167 r
= memfd_map(fd
, 0, sz
, p
);