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     return -1;
42 #endif
43 }
44 
vtest_new_shm(uint32_t handle,size_t size)45 int vtest_new_shm(uint32_t handle, size_t size)
46 {
47    int fd, ret;
48    int length = snprintf(NULL, 0, "vtest-res-%u", handle);
49    char *str = malloc(length + 1);
50    snprintf(str, length + 1, "vtest-res-%u", handle);
51 
52    fd = memfd_create(str, MFD_ALLOW_SEALING);
53    free(str);
54    if (fd < 0) {
55       return report_failed_call("memfd_create", -errno);
56    }
57 
58    ret = ftruncate(fd, size);
59    if (ret < 0) {
60       close(fd);
61       return report_failed_call("ftruncate", -errno);
62    }
63 
64    return fd;
65 }
66 
vtest_shm_check(void)67 int vtest_shm_check(void)
68 {
69     int mfd = memfd_create("test", MFD_ALLOW_SEALING);
70 
71     if (mfd >= 0) {
72         close(mfd);
73         return 1;
74     }
75 
76     return 0;
77 }
78 
79