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"
33 int memfd_new(const char *name) {
35 _cleanup_free_ char *g = NULL;
41 /* The kernel side is pretty picky about the character
42 * set here, let's do the usual bus escaping to deal
45 g = bus_label_escape(name);
54 /* If no name is specified we generate one. We include
55 * a hint indicating our library implementation, and
56 * add the thread name to it */
58 assert_se(prctl(PR_GET_NAME, (unsigned long) pr) >= 0);
63 _cleanup_free_ char *e = NULL;
65 e = bus_label_escape(pr);
69 g = strappend("sd-", e);
77 fd = memfd_create(name, MFD_ALLOW_SEALING);
84 int memfd_map(int fd, uint64_t offset, size_t size, void **p) {
92 sealed = memfd_get_sealed(fd);
97 q = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, offset);
99 q = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
108 int memfd_set_sealed(int fd) {
113 r = fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
120 int memfd_get_sealed(int fd) {
125 r = fcntl(fd, F_GET_SEALS);
129 return (r & (F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE)) ==
130 (F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
133 int memfd_get_size(int fd, uint64_t *sz) {
140 r = fstat(fd, &stat);
148 int memfd_set_size(int fd, uint64_t sz) {
153 r = ftruncate(fd, sz);
160 int memfd_new_and_map(const char *name, size_t sz, void **p) {
161 _cleanup_close_ int fd = -1;
168 fd = memfd_new(name);
172 r = memfd_set_size(fd, sz);
176 r = memfd_map(fd, 0, sz, p);
186 int memfd_get_name(int fd, char **name) {
187 char path[sizeof("/proc/self/fd/") + DECIMAL_STR_MAX(int)], buf[FILENAME_MAX+1], *e;
188 const char *delim, *end;
189 _cleanup_free_ char *n = NULL;
195 sprintf(path, "/proc/self/fd/%i", fd);
197 k = readlink(path, buf, sizeof(buf));
201 if ((size_t) k >= sizeof(buf))
206 delim = strstr(buf, ":[");
210 delim = strchr(delim + 2, ':');
216 end = strchr(delim, ']');
220 n = strndup(delim, end - delim);
224 e = bus_label_unescape(n);