1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2013 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include <sys/ioctl.h>
26 #include <sys/prctl.h>
29 #include "bus-label.h"
34 int memfd_new(const char *name) {
36 _cleanup_free_ char *g = NULL;
40 g = utf8_escape_invalid(name);
48 /* If no name is specified we generate one. We include
49 * a hint indicating our library implementation, and
50 * add the thread name to it */
52 assert_se(prctl(PR_GET_NAME, (unsigned long) pr) >= 0);
57 _cleanup_free_ char *e = NULL;
59 e = utf8_escape_invalid(pr);
63 g = strappend("sd-", e);
71 fd = memfd_create(name, MFD_ALLOW_SEALING);
78 int memfd_map(int fd, uint64_t offset, size_t size, void **p) {
86 sealed = memfd_get_sealed(fd);
91 q = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, offset);
93 q = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
102 int memfd_set_sealed(int fd) {
107 r = fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
114 int memfd_get_sealed(int fd) {
119 r = fcntl(fd, F_GET_SEALS);
123 return (r & (F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE)) ==
124 (F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
127 int memfd_get_size(int fd, uint64_t *sz) {
134 r = fstat(fd, &stat);
142 int memfd_set_size(int fd, uint64_t sz) {
147 r = ftruncate(fd, sz);
154 int memfd_new_and_map(const char *name, size_t sz, void **p) {
155 _cleanup_close_ int fd = -1;
161 fd = memfd_new(name);
165 r = memfd_set_size(fd, sz);
169 r = memfd_map(fd, 0, sz, p);
179 int memfd_get_name(int fd, char **name) {
180 char path[sizeof("/proc/self/fd/") + DECIMAL_STR_MAX(int)], buf[FILENAME_MAX+1], *e;
181 const char *delim, *end;
182 _cleanup_free_ char *n = NULL;
188 sprintf(path, "/proc/self/fd/%i", fd);
190 k = readlink(path, buf, sizeof(buf));
194 if ((size_t) k >= sizeof(buf))
199 delim = strstr(buf, ":[");
203 delim = strchr(delim + 2, ':');
209 end = strchr(delim, ']');
213 n = strndup(delim, end - delim);
217 e = utf8_escape_invalid(n);