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 struct kdbus_cmd_memfd_make cmd = {
39 .size = sizeof(struct kdbus_cmd_memfd_make),
41 _cleanup_close_ int kdbus = -1;
44 assert_return(m, -EINVAL);
46 kdbus = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
50 if (ioctl(kdbus, KDBUS_CMD_MEMFD_NEW, &cmd) < 0)
53 n = new0(struct sd_memfd, 1);
55 close_nointr_nofail(cmd.fd);
64 _public_ int sd_memfd_make(int fd, sd_memfd **m) {
68 assert_return(m, -EINVAL);
69 assert_return(fd >= 0, -EINVAL);
71 /* Check if this is a valid memfd */
72 if (ioctl(fd, KDBUS_CMD_MEMFD_SIZE_GET, &sz) < 0)
75 n = new0(struct sd_memfd, 1);
85 _public_ void sd_memfd_free(sd_memfd *m) {
92 close_nointr_nofail(m->fd);
97 _public_ int sd_memfd_get_fd(sd_memfd *m) {
98 assert_return(m, -EINVAL);
103 _public_ int sd_memfd_get_file(sd_memfd *m, FILE **f) {
104 assert_return(m, -EINVAL);
105 assert_return(f, -EINVAL);
108 m->f = fdopen(m->fd, "r+");
117 _public_ int sd_memfd_dup_fd(sd_memfd *m) {
120 assert_return(m, -EINVAL);
122 fd = fcntl(m->fd, F_DUPFD_CLOEXEC, 3);
129 _public_ int sd_memfd_map(sd_memfd *m, uint64_t offset, size_t size, void **p) {
133 assert_return(m, -EINVAL);
134 assert_return(size > 0, -EINVAL);
135 assert_return(p, -EINVAL);
137 sealed = sd_memfd_get_sealed(m);
141 q = mmap(NULL, size, sealed ? PROT_READ : PROT_READ|PROT_WRITE, MAP_SHARED, m->fd, offset);
149 _public_ int sd_memfd_set_sealed(sd_memfd *m, int b) {
152 assert_return(m, -EINVAL);
154 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SEAL_SET, b);
161 _public_ int sd_memfd_get_sealed(sd_memfd *m) {
164 assert_return(m, -EINVAL);
166 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SEAL_GET, &b);
173 _public_ int sd_memfd_get_size(sd_memfd *m, uint64_t *sz) {
176 assert_return(m, -EINVAL);
177 assert_return(sz, -EINVAL);
179 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SIZE_GET, sz);
186 _public_ int sd_memfd_set_size(sd_memfd *m, uint64_t sz) {
189 assert_return(m, -EINVAL);
191 r = ioctl(m->fd, KDBUS_CMD_MEMFD_SIZE_SET, &sz);
198 _public_ int sd_memfd_new_and_map(sd_memfd **m, size_t sz, void **p) {
202 r = sd_memfd_new(&n);
206 r = sd_memfd_set_size(n, sz);
212 r = sd_memfd_map(n, 0, sz, p);