#include <sys/mman.h>
#include <sys/prctl.h>
+#ifdef HAVE_LINUX_MEMFD_H
+# include <linux/memfd.h>
+#endif
+
#include "util.h"
#include "bus-label.h"
-#include "missing.h"
#include "memfd.h"
+#include "utf8.h"
+#include "missing.h"
-#include "sd-bus.h"
-
-int memfd_new(int *fd, const char *name) {
-
+int memfd_new(const char *name) {
_cleanup_free_ char *g = NULL;
- int n;
-
- assert_return(fd, -EINVAL);
+ int fd;
- if (name) {
- /* The kernel side is pretty picky about the character
- * set here, let's do the usual bus escaping to deal
- * with that. */
-
- g = bus_label_escape(name);
- if (!g)
- return -ENOMEM;
-
- name = g;
-
- } else {
+ if (!name) {
char pr[17] = {};
/* If no name is specified we generate one. We include
else {
_cleanup_free_ char *e = NULL;
- e = bus_label_escape(pr);
+ e = utf8_escape_invalid(pr);
if (!e)
return -ENOMEM;
}
}
- n = memfd_create(name, MFD_ALLOW_SEALING);
- if (n < 0)
+ fd = memfd_create(name, MFD_ALLOW_SEALING);
+ if (fd < 0)
return -errno;
- *fd = n;
- return 0;
+ return fd;
}
int memfd_map(int fd, uint64_t offset, size_t size, void **p) {
void *q;
int sealed;
- assert_return(fd >= 0, -EINVAL);
- assert_return(size > 0, -EINVAL);
- assert_return(p, -EINVAL);
+ assert(fd >= 0);
+ assert(size > 0);
+ assert(p);
sealed = memfd_get_sealed(fd);
if (sealed < 0)
int memfd_set_sealed(int fd) {
int r;
- assert_return(fd >= 0, -EINVAL);
+ assert(fd >= 0);
r = fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
if (r < 0)
int memfd_get_sealed(int fd) {
int r;
- assert_return(fd >= 0, -EINVAL);
+ assert(fd >= 0);
r = fcntl(fd, F_GET_SEALS);
if (r < 0)
}
int memfd_get_size(int fd, uint64_t *sz) {
- int r;
struct stat stat;
+ int r;
- assert_return(fd >= 0, -EINVAL);
- assert_return(sz, -EINVAL);
+ assert(fd >= 0);
+ assert(sz);
r = fstat(fd, &stat);
if (r < 0)
return -errno;
*sz = stat.st_size;
- return r;
+ return 0;
}
int memfd_set_size(int fd, uint64_t sz) {
int r;
- assert_return(fd >= 0, -EINVAL);
+ assert(fd >= 0);
r = ftruncate(fd, sz);
if (r < 0)
return -errno;
- return r;
+ return 0;
}
-int memfd_new_and_map(int *fd, const char *name, size_t sz, void **p) {
- _cleanup_close_ int n = -1;
+int memfd_new_and_map(const char *name, size_t sz, void **p) {
+ _cleanup_close_ int fd = -1;
int r;
- r = memfd_new(&n, name);
- if (r < 0)
- return r;
+ assert(sz > 0);
+ assert(p);
+
+ fd = memfd_new(name);
+ if (fd < 0)
+ return fd;
- r = memfd_set_size(n, sz);
+ r = memfd_set_size(fd, sz);
if (r < 0)
return r;
- r = memfd_map(n, 0, sz, p);
+ r = memfd_map(fd, 0, sz, p);
if (r < 0)
return r;
- *fd = n;
- n = -1;
- return 0;
+ r = fd;
+ fd = -1;
+
+ return r;
}
int memfd_get_name(int fd, char **name) {
_cleanup_free_ char *n = NULL;
ssize_t k;
- assert_return(fd >= 0, -EINVAL);
- assert_return(name, -EINVAL);
+ assert(fd >= 0);
+ assert(name);
sprintf(path, "/proc/self/fd/%i", fd);
if (!n)
return -ENOMEM;
- e = bus_label_unescape(n);
+ e = utf8_escape_invalid(n);
if (!e)
return -ENOMEM;