xref: /aosp_15_r20/external/virglrenderer/vtest/vtest_shm.c (revision bbecb9d118dfdb95f99bd754f8fa9be01f189df3)
1 /**************************************************************************
2  *
3  * Copyright (C) 2018 Chromium.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included
13  * in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  **************************************************************************/
24 
25 #include "util.h"
26 #include "vtest_shm.h"
27 
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 
33 #include <sys/syscall.h>
34 #include <unistd.h>
35 
memfd_create(const char * name,unsigned int flags)36 static int memfd_create(const char *name, unsigned int flags)
37 {
38 #ifdef __NR_memfd_create
39     return syscall(__NR_memfd_create, name, flags);
40 #else
41     (void)name;
42     (void)flags;
43     return -1;
44 #endif
45 }
46 
vtest_new_shm(uint32_t handle,size_t size)47 int vtest_new_shm(uint32_t handle, size_t size)
48 {
49    int fd, ret;
50    int length = snprintf(NULL, 0, "vtest-res-%u", handle);
51    char *str = malloc(length + 1);
52    snprintf(str, length + 1, "vtest-res-%u", handle);
53 
54    fd = memfd_create(str, MFD_ALLOW_SEALING);
55    free(str);
56    if (fd < 0) {
57       return report_failed_call("memfd_create", -errno);
58    }
59 
60    ret = ftruncate(fd, size);
61    if (ret < 0) {
62       close(fd);
63       return report_failed_call("ftruncate", -errno);
64    }
65 
66    return fd;
67 }
68 
vtest_shm_check(void)69 int vtest_shm_check(void)
70 {
71     int mfd = memfd_create("test", MFD_ALLOW_SEALING);
72 
73     if (mfd >= 0) {
74         close(mfd);
75         return 1;
76     }
77 
78     return 0;
79 }
80 
81