xref: /aosp_15_r20/external/cronet/third_party/apache-portable-runtime/src/shmem/win32/shm.c (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "apr_general.h"
18 #include "apr_errno.h"
19 #include "apr_file_io.h"
20 #include "apr_shm.h"
21 #include "apr_strings.h"
22 #include "apr_arch_file_io.h"
23 #include "limits.h"
24 
25 typedef struct memblock_t {
26     apr_size_t size;
27     apr_size_t length;
28 } memblock_t;
29 
30 struct apr_shm_t {
31     apr_pool_t *pool;
32     memblock_t *memblk;
33     void       *usrmem;
34     apr_size_t  size;
35     apr_size_t  length;
36     HANDLE      hMap;
37     const char *filename;
38 };
39 
shm_cleanup(void * shm)40 static apr_status_t shm_cleanup(void* shm)
41 {
42     apr_status_t rv = APR_SUCCESS;
43     apr_shm_t *m = shm;
44 
45     if (!UnmapViewOfFile(m->memblk)) {
46         rv = apr_get_os_error();
47     }
48     if (!CloseHandle(m->hMap)) {
49         rv = rv != APR_SUCCESS ? rv : apr_get_os_error();
50     }
51     if (m->filename) {
52         /* Remove file if file backed */
53         apr_status_t rc = apr_file_remove(m->filename, m->pool);
54         rv = rv != APR_SUCCESS ? rv : rc;
55     }
56     return rv;
57 }
58 
59 /* See if the caller is able to create a map in the global namespace by
60  * checking if the SE_CREATE_GLOBAL_NAME privilege is enabled.
61  *
62  * Prior to APR 1.5.0, named shared memory segments were always created
63  * in the global segment.  However, with recent versions of Windows this
64  * fails for unprivileged processes.  Thus, with older APR, named shared
65  * memory segments can't be created by unprivileged processes on newer
66  * Windows.
67  *
68  * By checking if the caller has the privilege, shm APIs can decide
69  * whether to use the Global or Local namespace.
70  *
71  * If running on an SDK without the required API definitions *OR*
72  * some processing failure occurs trying to check the privilege, fall
73  * back to earlier behavior -- always try to use the Global namespace.
74  */
75 #ifdef SE_CREATE_GLOBAL_NAME
can_create_global_maps(void)76 static int can_create_global_maps(void)
77 {
78     BOOL ok, has_priv;
79     LUID priv_id;
80     PRIVILEGE_SET privs;
81     HANDLE hToken;
82 
83     ok = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken);
84     if (!ok && GetLastError() == ERROR_NO_TOKEN) {
85         /* no thread-specific access token, so try to get process access token
86          */
87         ok = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
88     }
89 
90     if (ok) {
91         ok = LookupPrivilegeValue(NULL, SE_CREATE_GLOBAL_NAME, &priv_id);
92     }
93 
94     if (ok) {
95         privs.PrivilegeCount = 1;
96         privs.Control = PRIVILEGE_SET_ALL_NECESSARY;
97         privs.Privilege[0].Luid = priv_id;
98         privs.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;
99         ok = PrivilegeCheck(hToken, &privs, &has_priv);
100     }
101 
102     if (ok && !has_priv) {
103         return 0;
104     }
105     else {
106         return 1;
107     }
108 }
109 #else /* SE_CREATE_GLOBAL_NAME */
110 /* SDK definitions missing */
can_create_global_maps(void)111 static int can_create_global_maps(void)
112 {
113     return 1;
114 }
115 #endif /* SE_CREATE_GLOBAL_NAME */
116 
apr_shm_create_ex(apr_shm_t ** m,apr_size_t reqsize,const char * file,apr_pool_t * pool,apr_int32_t flags)117 APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m,
118                                             apr_size_t reqsize,
119                                             const char *file,
120                                             apr_pool_t *pool,
121                                             apr_int32_t flags)
122 {
123     static apr_size_t memblock = 0;
124     HANDLE hMap, hFile;
125     apr_status_t rv;
126     apr_size_t size;
127     apr_file_t *f;
128     void *base;
129     void *mapkey;
130     DWORD err, sizelo, sizehi;
131 
132     reqsize += sizeof(memblock_t);
133 
134     if (!memblock)
135     {
136         SYSTEM_INFO si;
137         GetSystemInfo(&si);
138         memblock = si.dwAllocationGranularity;
139     }
140 
141     /* Compute the granualar multiple of the pagesize */
142     size = memblock * (1 + (reqsize - 1) / memblock);
143     sizelo = (DWORD)size;
144 #ifdef _WIN64
145     sizehi = (DWORD)(size >> 32);
146 #else
147     sizehi = 0;
148 #endif
149 
150     if (!file) {
151         /* Do Anonymous, which must be passed as a duplicated handle */
152 #ifndef _WIN32_WCE
153         hFile = INVALID_HANDLE_VALUE;
154 #endif
155         mapkey = NULL;
156     }
157     else {
158         int global;
159 
160         /* Do file backed, which is not an inherited handle
161          * While we could open APR_EXCL, it doesn't seem that Unix
162          * ever did.  Ignore that error here, but fail later when
163          * we discover we aren't the creator of the file map object.
164          */
165         rv = apr_file_open(&f, file,
166                            APR_READ | APR_WRITE | APR_BINARY | APR_CREATE,
167                            APR_UREAD | APR_UWRITE, pool);
168         if ((rv != APR_SUCCESS)
169                 || ((rv = apr_os_file_get(&hFile, f)) != APR_SUCCESS)) {
170             return rv;
171         }
172         rv = apr_file_trunc(f, size);
173 
174         /* res_name_from_filename turns file into a pseudo-name
175          * without slashes or backslashes, and prepends the \global
176          * or \local prefix on Win2K and later
177          */
178         if (flags & APR_SHM_NS_GLOBAL) {
179             global = 1;
180         }
181         else if (flags & APR_SHM_NS_LOCAL) {
182             global = 0;
183         }
184         else {
185             global = can_create_global_maps();
186         }
187         mapkey = res_name_from_filename(file, global, pool);
188     }
189 
190 #if APR_HAS_UNICODE_FS
191     IF_WIN_OS_IS_UNICODE
192     {
193         hMap = CreateFileMappingW(hFile, NULL, PAGE_READWRITE,
194                                   sizehi, sizelo, mapkey);
195     }
196 #endif
197 #if APR_HAS_ANSI_FS
198     ELSE_WIN_OS_IS_ANSI
199     {
200         hMap = CreateFileMappingA(hFile, NULL, PAGE_READWRITE,
201                                   sizehi, sizelo, mapkey);
202     }
203 #endif
204     err = apr_get_os_error();
205 
206     if (file) {
207         apr_file_close(f);
208     }
209 
210     if (hMap && APR_STATUS_IS_EEXIST(err)) {
211         CloseHandle(hMap);
212         return APR_EEXIST;
213     }
214     if (!hMap) {
215         return err;
216     }
217 
218     base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE,
219                          0, 0, size);
220     if (!base) {
221         CloseHandle(hMap);
222         return apr_get_os_error();
223     }
224 
225     *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t));
226     (*m)->pool = pool;
227     (*m)->hMap = hMap;
228     (*m)->memblk = base;
229     (*m)->size = size;
230 
231     (*m)->usrmem = (char*)base + sizeof(memblock_t);
232     (*m)->length = reqsize - sizeof(memblock_t);;
233 
234     (*m)->memblk->length = (*m)->length;
235     (*m)->memblk->size = (*m)->size;
236     (*m)->filename = file ? apr_pstrdup(pool, file) : NULL;
237 
238     apr_pool_cleanup_register((*m)->pool, *m,
239                               shm_cleanup, apr_pool_cleanup_null);
240     return APR_SUCCESS;
241 }
242 
apr_shm_create(apr_shm_t ** m,apr_size_t reqsize,const char * file,apr_pool_t * pool)243 APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m,
244                                          apr_size_t reqsize,
245                                          const char *file,
246                                          apr_pool_t *pool)
247 {
248     return apr_shm_create_ex(m, reqsize, file, pool, 0);
249 }
250 
apr_shm_destroy(apr_shm_t * m)251 APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m)
252 {
253     apr_status_t rv = shm_cleanup(m);
254     apr_pool_cleanup_kill(m->pool, m, shm_cleanup);
255     return rv;
256 }
257 
apr_shm_remove(const char * filename,apr_pool_t * pool)258 APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename,
259                                          apr_pool_t *pool)
260 {
261     return apr_file_remove(filename, pool);
262 }
263 
shm_attach_internal(apr_shm_t ** m,const char * file,apr_pool_t * pool,int global)264 static apr_status_t shm_attach_internal(apr_shm_t **m,
265                                         const char *file,
266                                         apr_pool_t *pool,
267                                         int global)
268 {
269     HANDLE hMap;
270     void *mapkey;
271     void *base;
272 
273     /* res_name_from_filename turns file into a pseudo-name
274      * without slashes or backslashes, and prepends the \global
275      * or local prefix on Win2K and later
276      */
277     mapkey = res_name_from_filename(file, global, pool);
278 
279 #if APR_HAS_UNICODE_FS
280     IF_WIN_OS_IS_UNICODE
281     {
282 #ifndef _WIN32_WCE
283         hMap = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mapkey);
284 #else
285         /* The WCE 3.0 lacks OpenFileMapping. So we emulate one with
286          * opening the existing shmem and reading its size from the header
287          */
288         hMap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
289                                   PAGE_READWRITE, 0, sizeof(apr_shm_t), mapkey);
290 #endif
291     }
292 #endif
293 #if APR_HAS_ANSI_FS
294     ELSE_WIN_OS_IS_ANSI
295     {
296         hMap = OpenFileMappingA(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mapkey);
297     }
298 #endif
299 
300     if (!hMap) {
301         return apr_get_os_error();
302     }
303 
304     base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
305     if (!base) {
306         CloseHandle(hMap);
307         return apr_get_os_error();
308     }
309 
310     *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t));
311     (*m)->pool = pool;
312     (*m)->memblk = base;
313     /* Real (*m)->mem->size could be recovered with VirtualQuery */
314     (*m)->size = (*m)->memblk->size;
315 #if _WIN32_WCE
316     /* Reopen with real size  */
317     UnmapViewOfFile(base);
318     CloseHandle(hMap);
319 
320     hMap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
321                               PAGE_READWRITE, 0, (*m)->size, mapkey);
322     if (!hMap) {
323         return apr_get_os_error();
324     }
325     base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
326     if (!base) {
327         CloseHandle(hMap);
328         return apr_get_os_error();
329     }
330 #endif
331     (*m)->hMap = hMap;
332     (*m)->length = (*m)->memblk->length;
333     (*m)->usrmem = (char*)base + sizeof(memblock_t);
334     (*m)->filename = NULL;
335 
336     apr_pool_cleanup_register((*m)->pool, *m,
337                               shm_cleanup, apr_pool_cleanup_null);
338     return APR_SUCCESS;
339 }
340 
apr_shm_attach_ex(apr_shm_t ** m,const char * file,apr_pool_t * pool,apr_int32_t flags)341 APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m,
342                                             const char *file,
343                                             apr_pool_t *pool,
344                                             apr_int32_t flags)
345 {
346     apr_status_t rv;
347     int can_create_global;
348     int try_global_local[3] = {-1, -1, -1};
349     int cur;
350 
351     if (!file) {
352         return APR_EINVAL;
353     }
354 
355     if (flags & APR_SHM_NS_LOCAL) {
356         try_global_local[0] = 0; /* only search local */
357     }
358     else if (flags & APR_SHM_NS_GLOBAL) {
359         try_global_local[0] = 1; /* only search global */
360     }
361     else {
362         can_create_global = can_create_global_maps();
363         if (!can_create_global) { /* unprivileged process */
364             try_global_local[0] = 0; /* search local before global */
365             try_global_local[1] = 1;
366         }
367         else {
368             try_global_local[0] = 1; /* search global before local */
369             try_global_local[1] = 0;
370         }
371     }
372 
373     for (cur = 0; try_global_local[cur] != -1; cur++) {
374         rv = shm_attach_internal(m, file, pool, try_global_local[cur]);
375         if (!APR_STATUS_IS_ENOENT(rv)) {
376             break;
377         }
378     }
379 
380     return rv;
381 }
382 
apr_shm_attach(apr_shm_t ** m,const char * file,apr_pool_t * pool)383 APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m,
384                                          const char *file,
385                                          apr_pool_t *pool)
386 {
387     return apr_shm_attach_ex(m, file, pool, 0);
388 }
389 
apr_shm_detach(apr_shm_t * m)390 APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m)
391 {
392     apr_status_t rv = shm_cleanup(m);
393     apr_pool_cleanup_kill(m->pool, m, shm_cleanup);
394     return rv;
395 }
396 
apr_shm_baseaddr_get(const apr_shm_t * m)397 APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m)
398 {
399     return m->usrmem;
400 }
401 
apr_shm_size_get(const apr_shm_t * m)402 APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m)
403 {
404     return m->length;
405 }
406 
407 APR_POOL_IMPLEMENT_ACCESSOR(shm)
408 
APR_DECLARE(apr_status_t)409 APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm,
410                                          apr_shm_t *shm)
411 {
412     *osshm = shm->hMap;
413     return APR_SUCCESS;
414 }
415 
apr_os_shm_put(apr_shm_t ** m,apr_os_shm_t * osshm,apr_pool_t * pool)416 APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **m,
417                                          apr_os_shm_t *osshm,
418                                          apr_pool_t *pool)
419 {
420     void* base;
421     base = MapViewOfFile(*osshm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
422     if (!base) {
423         return apr_get_os_error();
424     }
425 
426     *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t));
427     (*m)->pool = pool;
428     (*m)->hMap = *osshm;
429     (*m)->memblk = base;
430     (*m)->usrmem = (char*)base + sizeof(memblock_t);
431     /* Real (*m)->mem->size could be recovered with VirtualQuery */
432     (*m)->size = (*m)->memblk->size;
433     (*m)->length = (*m)->memblk->length;
434     (*m)->filename = NULL;
435 
436     apr_pool_cleanup_register((*m)->pool, *m,
437                               shm_cleanup, apr_pool_cleanup_null);
438     return APR_SUCCESS;
439 }
440 
441