Path: blob/master/tools/testing/selftests/efivarfs/open-unlink.c
25923 views
// SPDX-License-Identifier: GPL-2.01#include <errno.h>2#include <stdio.h>3#include <stdint.h>4#include <stdlib.h>5#include <unistd.h>6#include <sys/ioctl.h>7#include <sys/types.h>8#include <sys/stat.h>9#include <fcntl.h>10#include <linux/fs.h>1112static int set_immutable(const char *path, int immutable)13{14unsigned int flags;15int fd;16int rc;17int error;1819fd = open(path, O_RDONLY);20if (fd < 0)21return fd;2223rc = ioctl(fd, FS_IOC_GETFLAGS, &flags);24if (rc < 0) {25error = errno;26close(fd);27errno = error;28return rc;29}3031if (immutable)32flags |= FS_IMMUTABLE_FL;33else34flags &= ~FS_IMMUTABLE_FL;3536rc = ioctl(fd, FS_IOC_SETFLAGS, &flags);37error = errno;38close(fd);39errno = error;40return rc;41}4243static int get_immutable(const char *path)44{45unsigned int flags;46int fd;47int rc;48int error;4950fd = open(path, O_RDONLY);51if (fd < 0)52return fd;5354rc = ioctl(fd, FS_IOC_GETFLAGS, &flags);55if (rc < 0) {56error = errno;57close(fd);58errno = error;59return rc;60}61close(fd);62if (flags & FS_IMMUTABLE_FL)63return 1;64return 0;65}6667int main(int argc, char **argv)68{69const char *path;70char buf[5];71int fd, rc;7273if (argc < 2) {74fprintf(stderr, "usage: %s <path>\n", argv[0]);75return EXIT_FAILURE;76}7778path = argv[1];7980/* attributes: EFI_VARIABLE_NON_VOLATILE |81* EFI_VARIABLE_BOOTSERVICE_ACCESS |82* EFI_VARIABLE_RUNTIME_ACCESS83*/84*(uint32_t *)buf = 0x7;85buf[4] = 0;8687/* create a test variable */88fd = open(path, O_WRONLY | O_CREAT, 0600);89if (fd < 0) {90perror("open(O_WRONLY)");91return EXIT_FAILURE;92}9394rc = write(fd, buf, sizeof(buf));95if (rc != sizeof(buf)) {96perror("write");97return EXIT_FAILURE;98}99100close(fd);101102rc = get_immutable(path);103if (rc < 0) {104perror("ioctl(FS_IOC_GETFLAGS)");105return EXIT_FAILURE;106} else if (rc) {107rc = set_immutable(path, 0);108if (rc < 0) {109perror("ioctl(FS_IOC_SETFLAGS)");110return EXIT_FAILURE;111}112}113114fd = open(path, O_RDONLY);115if (fd < 0) {116perror("open");117return EXIT_FAILURE;118}119120if (unlink(path) < 0) {121perror("unlink");122return EXIT_FAILURE;123}124125rc = read(fd, buf, sizeof(buf));126if (rc > 0) {127fprintf(stderr, "reading from an unlinked variable "128"shouldn't be possible\n");129return EXIT_FAILURE;130}131132return EXIT_SUCCESS;133}134135136