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>
37 _public_ int sd_memfd_new(sd_memfd **m) {
38 _cleanup_close_ int kdbus = -1;
42 assert_return(m, -EINVAL);
44 kdbus = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
48 if (ioctl(kdbus, KDBUS_CMD_MEMFD_NEW, &fd) < 0)
51 n = new0(struct sd_memfd, 1);
60 _public_ int sd_memfd_make(int fd, sd_memfd **m) {
64 assert_return(m, -EINVAL);
65 assert_return(fd >= 0, -EINVAL);
67 /* Check if this is a valid memfd */
68 if (ioctl(fd, KDBUS_CMD_MEMFD_SIZE_GET, &sz) < 0)
71 n = new0(struct sd_memfd, 1);
81 _public_ void sd_memfd_free(sd_memfd *m) {
88 close_nointr_nofail(m->fd);
93 _public_ int sd_memfd_get_fd(sd_memfd *m) {
94 assert_return(m, -EINVAL);
99 _public_ int sd_memfd_get_file(sd_memfd *m, FILE **f) {
100 assert_return(m, -EINVAL);
101 assert_return(f, -EINVAL);
104 m->f = fdopen(m->fd, "r+");
113 _public_ int sd_memfd_dup_fd(sd_memfd *m) {
116 assert_return(m, -EINVAL);
118 fd = fcntl(m->fd, F_DUPFD_CLOEXEC, 3);
125 _public_ int sd_memfd_map(sd_memfd *m, uint64_t offset, size_t size, void **p) {
129 assert_return(m, -EINVAL);
130 assert_return(size > 0, -EINVAL);
131 assert_return(p, -EINVAL);
133 sealed = sd_memfd_get_sealed(m);
137 q = mmap(NULL, size, sealed ? PROT_READ : PROT_READ|PROT_WRITE, MAP_SHARED, m->fd, offset);
145 _public_ int sd_memfd_set_sealed(sd_memfd *m, int b) {
148 assert_return(m, -EINVAL);
150 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SEAL_SET, b);
157 _public_ int sd_memfd_get_sealed(sd_memfd *m) {
160 assert_return(m, -EINVAL);
162 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SEAL_GET, &b);
169 _public_ int sd_memfd_get_size(sd_memfd *m, uint64_t *sz) {
172 assert_return(m, -EINVAL);
173 assert_return(sz, -EINVAL);
175 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SIZE_GET, sz);
182 _public_ int sd_memfd_set_size(sd_memfd *m, uint64_t sz) {
185 assert_return(m, -EINVAL);
187 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SIZE_SET, &sz);
194 _public_ int sd_memfd_new_and_map(sd_memfd **m, size_t sz, void **p) {
198 r = sd_memfd_new(&n);
202 r = sd_memfd_set_size(n, sz);
208 r = sd_memfd_map(n, 0, sz, p);