// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#define __EXPORTED_HEADERS__
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <linux/falloc.h>
#include <linux/fcntl.h>
#include <linux/memfd.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#include "common.h"
#define MEMFD_STR "memfd:"
#define MEMFD_HUGE_STR "memfd-hugetlb:"
#define SHARED_FT_STR "(shared file-table)"
#define MFD_DEF_SIZE 8192
#define STACK_SIZE 65536
/*
* Default is not to test hugetlbfs
*/
static size_t mfd_def_size = MFD_DEF_SIZE;
static const char *memfd_str = MEMFD_STR;
static int mfd_assert_new(const char *name, loff_t sz, unsigned int flags)
{
int r, fd;
fd = sys_memfd_create(name, flags);
if (fd < 0) {
printf("memfd_create(\"%s\", %u) failed: %m\n",
name, flags);
abort();
}
r = ftruncate(fd, sz);
if (r < 0) {
printf("ftruncate(%llu) failed: %m\n", (unsigned long long)sz);
abort();
}
return fd;
}
static int mfd_assert_reopen_fd(int fd_in)
{
int r, fd;
char path[100];
sprintf(path, "/proc/self/fd/%d", fd_in);
fd = open(path, O_RDWR);
if (fd < 0) {
printf("re-open of existing fd %d failed\n", fd_in);
abort();
}
return fd;
}
static void mfd_fail_new(const char *name, unsigned int flags)
{
int r;
r = sys_memfd_create(name, flags);
if (r >= 0) {
printf("memfd_create(\"%s\", %u) succeeded, but failure expected\n",
name, flags);
close(r);
abort();
}
}
static unsigned int mfd_assert_get_seals(int fd)
{
int r;
r = fcntl(fd, F_GET_SEALS);
if (r < 0) {
printf("GET_SEALS(%d) failed: %m\n", fd);
abort();
}
return (unsigned int)r;
}
static void mfd_assert_has_seals(int fd, unsigned int seals)
{
unsigned int s;
s = mfd_assert_get_seals(fd);
if (s != seals) {
printf("%u != %u = GET_SEALS(%d)\n", seals, s, fd);
abort();
}
}
static void mfd_assert_add_seals(int fd, unsigned int seals)
{
int r;
unsigned int s;
s = mfd_assert_get_seals(fd);
r = fcntl(fd, F_ADD_SEALS, seals);
if (r < 0) {
printf("ADD_SEALS(%d, %u -> %u) failed: %m\n", fd, s, seals);
abort();
}
}
static void mfd_fail_add_seals(int fd, unsigned int seals)
{
int r;
unsigned int s;
r = fcntl(fd, F_GET_SEALS);
if (r < 0)
s = 0;
else
s = (unsigned int)r;
r = fcntl(fd, F_ADD_SEALS, seals);
if (r >= 0) {
printf("ADD_SEALS(%d, %u -> %u) didn't fail as expected\n",
fd, s, seals);
abort();
}
}
static void