1 /**************************************************************************
2  *
3  * Copyright 2021 Snap Inc.
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included
15  * in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  *
25  **************************************************************************/
26 
27 /*
28  * Memory fd wrappers.
29  */
30 
31 #include "detect_os.h"
32 
33 #if DETECT_OS_ANDROID
34 #include <linux/fcntl.h>
35 #endif
36 
37 #if DETECT_OS_UNIX
38 
39 #include <string.h>
40 #include <fcntl.h>
41 #include <unistd.h>
42 #include <sys/mman.h>
43 
44 #include "anon_file.h"
45 #include "mesa-sha1.h"
46 #include "u_math.h"
47 #include "os_memory.h"
48 
49 /* (Re)define UUID_SIZE to avoid including vulkan.h (or p_defines.h) here. */
50 #define UUID_SIZE 16
51 
52 struct memory_header {
53    size_t size;
54    size_t offset;
55    uint8_t uuid[UUID_SIZE];
56 };
57 
58 static void
get_driver_id_sha1_hash(uint8_t sha1[SHA1_DIGEST_LENGTH],const char * driver_id)59 get_driver_id_sha1_hash(uint8_t sha1[SHA1_DIGEST_LENGTH], const char *driver_id) {
60    struct mesa_sha1 sha1_ctx;
61    _mesa_sha1_init(&sha1_ctx);
62 
63    _mesa_sha1_update(&sha1_ctx, driver_id, strlen(driver_id));
64 
65    _mesa_sha1_final(&sha1_ctx, sha1);
66 }
67 
68 /**
69  * Imports memory from a file descriptor
70  */
71 bool
os_import_memory_fd(int fd,void ** ptr,uint64_t * size,char const * driver_id)72 os_import_memory_fd(int fd, void **ptr, uint64_t *size, char const *driver_id)
73 {
74    void *mapped_ptr;
75    struct memory_header header;
76 
77    lseek(fd, 0, SEEK_SET);
78    int bytes_read = read(fd, &header, sizeof(header));
79    if(bytes_read != sizeof(header))
80       return false;
81 
82    // Check the uuid we put after the sizes in order to verify that the fd
83    // is a memfd that we created and not some random fd.
84    uint8_t sha1[SHA1_DIGEST_LENGTH];
85    get_driver_id_sha1_hash(sha1, driver_id);
86 
87    assert(SHA1_DIGEST_LENGTH >= UUID_SIZE);
88    if (memcmp(header.uuid, sha1, UUID_SIZE)) {
89       return false;
90    }
91 
92    mapped_ptr = mmap(NULL, header.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
93    if (mapped_ptr == MAP_FAILED) {
94       return false;
95    }
96    *ptr = (void*)((uintptr_t)mapped_ptr + header.offset);
97    // the offset does not count as part of the size
98    *size = header.size - header.offset;
99    return true;
100 }
101 
102 /**
103  * Return memory on given byte alignment
104  */
105 void *
os_malloc_aligned_fd(size_t size,size_t alignment,int * fd,char const * fd_name,char const * driver_id)106 os_malloc_aligned_fd(size_t size, size_t alignment, int *fd, char const *fd_name, char const *driver_id)
107 {
108    void *ptr, *buf;
109    int mem_fd;
110    size_t alloc_size, offset;
111 
112    *fd = -1;
113 
114    /*
115     * Calculate
116     *
117     *   alloc_size = size + alignment + sizeof(struct memory_header) + sizeof(size_t)
118     *
119     * while checking for overflow.
120     */
121    const size_t header_size = sizeof(struct memory_header) + sizeof(size_t);
122    if (add_overflow_size_t(size, alignment, &alloc_size) ||
123        add_overflow_size_t(alloc_size, header_size, &alloc_size))
124       return NULL;
125 
126    mem_fd = os_create_anonymous_file(alloc_size, fd_name);
127 
128    if(mem_fd < 0)
129       return NULL;
130 
131 #if defined(HAVE_MEMFD_CREATE)
132    // Seal fd, so no one can grow or shrink the memory.
133    if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL) != 0)
134       goto fail;
135 #endif
136 
137    ptr = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd, 0);
138    if (ptr == MAP_FAILED)
139       goto fail;
140 
141    // Save the size and offset at the start, so we have all we need to unmap the memory
142    // and we are able to find the start of the actual data-section. Also save the
143    // offset directly before the data-section, so we can find the start of the mapped memory.
144    // |   size   |  offset  | ... padding ... |  offset  | ... data ... |
145    // ^                                                  ^              ^
146    // 0                                               offset          size
147    buf = (char *)(((uintptr_t)ptr + header_size + alignment - 1) & ~((uintptr_t)(alignment - 1)));
148    offset = (size_t)((uintptr_t)buf - (uintptr_t)ptr);
149    struct memory_header* header = (struct memory_header*)ptr;
150    header->size = alloc_size;
151    header->offset = offset;
152    ((size_t*)buf)[-1] = offset;
153 
154    // Add the hash of the driver_id as a uuid to the header in order to identify the memory
155    // when importing.
156    uint8_t sha1[SHA1_DIGEST_LENGTH];
157    get_driver_id_sha1_hash(sha1, driver_id);
158 
159    assert(SHA1_DIGEST_LENGTH >= UUID_SIZE);
160    memcpy(header->uuid, sha1, UUID_SIZE);
161 
162    *fd = mem_fd;
163    return buf;
164 
165 fail:
166    close(mem_fd);
167    return NULL;
168 }
169 
170 /**
171  * Free memory returned by os_malloc_aligned_fd().
172  */
173 void
os_free_fd(void * ptr)174 os_free_fd(void *ptr)
175 {
176    if (ptr) {
177       size_t offset = ((size_t*)ptr)[-1];
178       struct memory_header* header = (struct memory_header*)((uintptr_t)ptr - offset);
179       // check if the offset at the beginning of the memory
180       // is the same as the one we saved directly before the data.
181       assert(offset == header->offset);
182       munmap(header, header->size);
183    }
184 }
185 
186 #endif
187