ntdll: Add logging for free ranges.
[wine.git] / dlls / ntdll / unix / virtual.c
blob0841fb466aa15b30d37a00163a4c7f59ee4acefa
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997, 2002, 2020 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #if 0
22 #pragma makedep unix
23 #endif
25 #include "config.h"
27 #include <assert.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <signal.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/mman.h>
39 #ifdef HAVE_SYS_SYSINFO_H
40 # include <sys/sysinfo.h>
41 #endif
42 #ifdef HAVE_SYS_SYSCTL_H
43 # include <sys/sysctl.h>
44 #endif
45 #ifdef HAVE_SYS_PARAM_H
46 # include <sys/param.h>
47 #endif
48 #ifdef HAVE_SYS_QUEUE_H
49 # include <sys/queue.h>
50 #endif
51 #ifdef HAVE_SYS_USER_H
52 # include <sys/user.h>
53 #endif
54 #ifdef HAVE_LIBPROCSTAT_H
55 # include <libprocstat.h>
56 #endif
57 #include <unistd.h>
58 #include <dlfcn.h>
59 #ifdef HAVE_VALGRIND_VALGRIND_H
60 # include <valgrind/valgrind.h>
61 #endif
62 #if defined(__APPLE__)
63 # include <mach/mach_init.h>
64 # include <mach/mach_vm.h>
65 #endif
67 #include "ntstatus.h"
68 #define WIN32_NO_STATUS
69 #include "windef.h"
70 #include "winnt.h"
71 #include "winternl.h"
72 #include "ddk/wdm.h"
73 #include "wine/list.h"
74 #include "wine/rbtree.h"
75 #include "unix_private.h"
76 #include "wine/debug.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
79 WINE_DECLARE_DEBUG_CHANNEL(module);
80 WINE_DECLARE_DEBUG_CHANNEL(virtual_ranges);
82 struct preload_info
84 void *addr;
85 size_t size;
88 struct reserved_area
90 struct list entry;
91 void *base;
92 size_t size;
95 static struct list reserved_areas = LIST_INIT(reserved_areas);
97 struct builtin_module
99 struct list entry;
100 unsigned int refcount;
101 void *handle;
102 void *module;
103 char *unix_path;
104 void *unix_handle;
107 static struct list builtin_modules = LIST_INIT( builtin_modules );
109 struct file_view
111 struct wine_rb_entry entry; /* entry in global view tree */
112 void *base; /* base address */
113 size_t size; /* size in bytes */
114 unsigned int protect; /* protection for all pages at allocation time and SEC_* flags */
117 /* per-page protection flags */
118 #define VPROT_READ 0x01
119 #define VPROT_WRITE 0x02
120 #define VPROT_EXEC 0x04
121 #define VPROT_WRITECOPY 0x08
122 #define VPROT_GUARD 0x10
123 #define VPROT_COMMITTED 0x20
124 #define VPROT_WRITEWATCH 0x40
125 /* per-mapping protection flags */
126 #define VPROT_SYSTEM 0x0200 /* system view (underlying mmap not under our control) */
128 /* Conversion from VPROT_* to Win32 flags */
129 static const BYTE VIRTUAL_Win32Flags[16] =
131 PAGE_NOACCESS, /* 0 */
132 PAGE_READONLY, /* READ */
133 PAGE_READWRITE, /* WRITE */
134 PAGE_READWRITE, /* READ | WRITE */
135 PAGE_EXECUTE, /* EXEC */
136 PAGE_EXECUTE_READ, /* READ | EXEC */
137 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
138 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
139 PAGE_WRITECOPY, /* WRITECOPY */
140 PAGE_WRITECOPY, /* READ | WRITECOPY */
141 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
142 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
143 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
144 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
145 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
146 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
149 static struct wine_rb_tree views_tree;
150 static pthread_mutex_t virtual_mutex;
152 static const UINT page_shift = 12;
153 static const UINT_PTR page_mask = 0xfff;
154 static const UINT_PTR granularity_mask = 0xffff;
156 /* Note: these are Windows limits, you cannot change them. */
157 #ifdef __i386__
158 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
159 #else
160 static void *address_space_start = (void *)0x10000;
161 #endif
163 #ifdef __aarch64__
164 static void *address_space_limit = (void *)0xffffffff0000; /* top of the total available address space */
165 #elif defined(_WIN64)
166 static void *address_space_limit = (void *)0x7fffffff0000;
167 #else
168 static void *address_space_limit = (void *)0xc0000000;
169 #endif
171 #ifdef _WIN64
172 static void *user_space_limit = (void *)0x7fffffff0000; /* top of the user address space */
173 static void *working_set_limit = (void *)0x7fffffff0000; /* top of the current working set */
174 #else
175 static void *user_space_limit = (void *)0x7fff0000;
176 static void *working_set_limit = (void *)0x7fff0000;
177 #endif
179 static UINT64 *arm64ec_map;
181 struct _KUSER_SHARED_DATA *user_shared_data = (void *)0x7ffe0000;
183 /* TEB allocation blocks */
184 static void *teb_block;
185 static void **next_free_teb;
186 static int teb_block_pos;
187 static struct list teb_list = LIST_INIT( teb_list );
189 #define ROUND_ADDR(addr,mask) ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
190 #define ROUND_SIZE(addr,size) (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
192 #define VIRTUAL_DEBUG_DUMP_VIEW(view) do { if (TRACE_ON(virtual)) dump_view(view); } while (0)
193 #define VIRTUAL_DEBUG_DUMP_RANGES() do { if (TRACE_ON(virtual_ranges)) dump_free_ranges(); } while (0)
195 #ifndef MAP_NORESERVE
196 #define MAP_NORESERVE 0
197 #endif
199 #ifdef _WIN64 /* on 64-bit the page protection bytes use a 2-level table */
200 static const size_t pages_vprot_shift = 20;
201 static const size_t pages_vprot_mask = (1 << 20) - 1;
202 static size_t pages_vprot_size;
203 static BYTE **pages_vprot;
204 #else /* on 32-bit we use a simple array with one byte per page */
205 static BYTE *pages_vprot;
206 #endif
208 static struct file_view *view_block_start, *view_block_end, *next_free_view;
209 static const size_t view_block_size = 0x100000;
210 static void *preload_reserve_start;
211 static void *preload_reserve_end;
212 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
214 struct range_entry
216 void *base;
217 void *end;
220 static struct range_entry *free_ranges;
221 static struct range_entry *free_ranges_end;
224 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
226 return (addr >= limit || (const char *)addr + size > (const char *)limit);
229 /* mmap() anonymous memory at a fixed address */
230 void *anon_mmap_fixed( void *start, size_t size, int prot, int flags )
232 return mmap( start, size, prot, MAP_PRIVATE | MAP_ANON | MAP_FIXED | flags, -1, 0 );
235 /* allocate anonymous mmap() memory at any address */
236 void *anon_mmap_alloc( size_t size, int prot )
238 return mmap( NULL, size, prot, MAP_PRIVATE | MAP_ANON, -1, 0 );
242 static void mmap_add_reserved_area( void *addr, SIZE_T size )
244 struct reserved_area *area;
245 struct list *ptr;
247 if (!((intptr_t)addr + size)) size--; /* avoid wrap-around */
249 LIST_FOR_EACH( ptr, &reserved_areas )
251 area = LIST_ENTRY( ptr, struct reserved_area, entry );
252 if (area->base > addr)
254 /* try to merge with the next one */
255 if ((char *)addr + size == (char *)area->base)
257 area->base = addr;
258 area->size += size;
259 return;
261 break;
263 else if ((char *)area->base + area->size == (char *)addr)
265 /* merge with the previous one */
266 area->size += size;
268 /* try to merge with the next one too */
269 if ((ptr = list_next( &reserved_areas, ptr )))
271 struct reserved_area *next = LIST_ENTRY( ptr, struct reserved_area, entry );
272 if ((char *)addr + size == (char *)next->base)
274 area->size += next->size;
275 list_remove( &next->entry );
276 free( next );
279 return;
283 if ((area = malloc( sizeof(*area) )))
285 area->base = addr;
286 area->size = size;
287 list_add_before( ptr, &area->entry );
291 static void mmap_remove_reserved_area( void *addr, SIZE_T size )
293 struct reserved_area *area;
294 struct list *ptr;
296 if (!((intptr_t)addr + size)) size--; /* avoid wrap-around */
298 ptr = list_head( &reserved_areas );
299 /* find the first area covering address */
300 while (ptr)
302 area = LIST_ENTRY( ptr, struct reserved_area, entry );
303 if ((char *)area->base >= (char *)addr + size) break; /* outside the range */
304 if ((char *)area->base + area->size > (char *)addr) /* overlaps range */
306 if (area->base >= addr)
308 if ((char *)area->base + area->size > (char *)addr + size)
310 /* range overlaps beginning of area only -> shrink area */
311 area->size -= (char *)addr + size - (char *)area->base;
312 area->base = (char *)addr + size;
313 break;
315 else
317 /* range contains the whole area -> remove area completely */
318 ptr = list_next( &reserved_areas, ptr );
319 list_remove( &area->entry );
320 free( area );
321 continue;
324 else
326 if ((char *)area->base + area->size > (char *)addr + size)
328 /* range is in the middle of area -> split area in two */
329 struct reserved_area *new_area = malloc( sizeof(*new_area) );
330 if (new_area)
332 new_area->base = (char *)addr + size;
333 new_area->size = (char *)area->base + area->size - (char *)new_area->base;
334 list_add_after( ptr, &new_area->entry );
336 else size = (char *)area->base + area->size - (char *)addr;
337 area->size = (char *)addr - (char *)area->base;
338 break;
340 else
342 /* range overlaps end of area only -> shrink area */
343 area->size = (char *)addr - (char *)area->base;
347 ptr = list_next( &reserved_areas, ptr );
351 static int mmap_is_in_reserved_area( void *addr, SIZE_T size )
353 struct reserved_area *area;
354 struct list *ptr;
356 LIST_FOR_EACH( ptr, &reserved_areas )
358 area = LIST_ENTRY( ptr, struct reserved_area, entry );
359 if (area->base > addr) break;
360 if ((char *)area->base + area->size <= (char *)addr) continue;
361 /* area must contain block completely */
362 if ((char *)area->base + area->size < (char *)addr + size) return -1;
363 return 1;
365 return 0;
368 static int mmap_enum_reserved_areas( int (*enum_func)(void *base, SIZE_T size, void *arg),
369 void *arg, int top_down )
371 int ret = 0;
372 struct list *ptr;
374 if (top_down)
376 for (ptr = reserved_areas.prev; ptr != &reserved_areas; ptr = ptr->prev)
378 struct reserved_area *area = LIST_ENTRY( ptr, struct reserved_area, entry );
379 if ((ret = enum_func( area->base, area->size, arg ))) break;
382 else
384 for (ptr = reserved_areas.next; ptr != &reserved_areas; ptr = ptr->next)
386 struct reserved_area *area = LIST_ENTRY( ptr, struct reserved_area, entry );
387 if ((ret = enum_func( area->base, area->size, arg ))) break;
390 return ret;
393 static void *anon_mmap_tryfixed( void *start, size_t size, int prot, int flags )
395 void *ptr;
397 #ifdef MAP_FIXED_NOREPLACE
398 ptr = mmap( start, size, prot, MAP_FIXED_NOREPLACE | MAP_PRIVATE | MAP_ANON | flags, -1, 0 );
399 #elif defined(MAP_TRYFIXED)
400 ptr = mmap( start, size, prot, MAP_TRYFIXED | MAP_PRIVATE | MAP_ANON | flags, -1, 0 );
401 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
402 ptr = mmap( start, size, prot, MAP_FIXED | MAP_EXCL | MAP_PRIVATE | MAP_ANON | flags, -1, 0 );
403 if (ptr == MAP_FAILED && errno == EINVAL) errno = EEXIST;
404 #elif defined(__APPLE__)
405 mach_vm_address_t result = (mach_vm_address_t)start;
406 kern_return_t ret = mach_vm_map( mach_task_self(), &result, size, 0, VM_FLAGS_FIXED,
407 MEMORY_OBJECT_NULL, 0, 0, prot, VM_PROT_ALL, VM_INHERIT_COPY );
409 if (!ret)
411 if ((ptr = anon_mmap_fixed( start, size, prot, flags )) == MAP_FAILED)
412 mach_vm_deallocate( mach_task_self(), result, size );
414 else
416 errno = (ret == KERN_NO_SPACE ? EEXIST : ENOMEM);
417 ptr = MAP_FAILED;
419 #else
420 ptr = mmap( start, size, prot, MAP_PRIVATE | MAP_ANON | flags, -1, 0 );
421 #endif
422 if (ptr != MAP_FAILED && ptr != start)
424 if (is_beyond_limit( ptr, size, user_space_limit ))
426 anon_mmap_fixed( ptr, size, PROT_NONE, MAP_NORESERVE );
427 mmap_add_reserved_area( ptr, size );
429 else munmap( ptr, size );
430 ptr = MAP_FAILED;
431 errno = EEXIST;
433 return ptr;
436 static void reserve_area( void *addr, void *end )
438 #ifdef __APPLE__
440 #ifdef __i386__
441 static const mach_vm_address_t max_address = VM_MAX_ADDRESS;
442 #else
443 static const mach_vm_address_t max_address = MACH_VM_MAX_ADDRESS;
444 #endif
445 mach_vm_address_t address = (mach_vm_address_t)addr;
446 mach_vm_address_t end_address = (mach_vm_address_t)end;
448 if (!end_address || max_address < end_address)
449 end_address = max_address;
451 while (address < end_address)
453 mach_vm_address_t hole_address = address;
454 kern_return_t ret;
455 mach_vm_size_t size;
456 vm_region_basic_info_data_64_t info;
457 mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
458 mach_port_t dummy_object_name = MACH_PORT_NULL;
460 /* find the mapped region at or above the current address. */
461 ret = mach_vm_region(mach_task_self(), &address, &size, VM_REGION_BASIC_INFO_64,
462 (vm_region_info_t)&info, &count, &dummy_object_name);
463 if (ret != KERN_SUCCESS)
465 address = max_address;
466 size = 0;
469 if (end_address < address)
470 address = end_address;
471 if (hole_address < address)
473 /* found a hole, attempt to reserve it. */
474 size_t hole_size = address - hole_address;
475 mach_vm_address_t alloc_address = hole_address;
477 ret = mach_vm_map( mach_task_self(), &alloc_address, hole_size, 0, VM_FLAGS_FIXED,
478 MEMORY_OBJECT_NULL, 0, 0, PROT_NONE, VM_PROT_ALL, VM_INHERIT_COPY );
479 if (!ret) mmap_add_reserved_area( (void*)hole_address, hole_size );
480 else if (ret == KERN_NO_SPACE)
482 /* something filled (part of) the hole before we could.
483 go back and look again. */
484 address = hole_address;
485 continue;
488 address += size;
490 #else
491 void *ptr;
492 size_t size = (char *)end - (char *)addr;
494 if (!size) return;
496 if ((ptr = anon_mmap_tryfixed( addr, size, PROT_NONE, MAP_NORESERVE )) != MAP_FAILED)
498 mmap_add_reserved_area( addr, size );
499 return;
501 size = (size / 2) & ~granularity_mask;
502 if (size)
504 reserve_area( addr, (char *)addr + size );
505 reserve_area( (char *)addr + size, end );
507 #endif /* __APPLE__ */
511 static void mmap_init( const struct preload_info *preload_info )
513 #ifndef _WIN64
514 #ifndef __APPLE__
515 char stack;
516 char * const stack_ptr = &stack;
517 #endif
518 char *user_space_limit = (char *)0x7ffe0000;
519 int i;
521 if (preload_info)
523 /* check for a reserved area starting at the user space limit */
524 /* to avoid wasting time trying to allocate it again */
525 for (i = 0; preload_info[i].size; i++)
527 if ((char *)preload_info[i].addr > user_space_limit) break;
528 if ((char *)preload_info[i].addr + preload_info[i].size > user_space_limit)
530 user_space_limit = (char *)preload_info[i].addr + preload_info[i].size;
531 break;
535 else reserve_area( (void *)0x00010000, (void *)0x40000000 );
538 #ifndef __APPLE__
539 if (stack_ptr >= user_space_limit)
541 char *end = 0;
542 char *base = stack_ptr - ((unsigned int)stack_ptr & granularity_mask) - (granularity_mask + 1);
543 if (base > user_space_limit) reserve_area( user_space_limit, base );
544 base = stack_ptr - ((unsigned int)stack_ptr & granularity_mask) + (granularity_mask + 1);
545 #if defined(linux) || defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
546 /* Heuristic: assume the stack is near the end of the address */
547 /* space, this avoids a lot of futile allocation attempts */
548 end = (char *)(((unsigned long)base + 0x0fffffff) & 0xf0000000);
549 #endif
550 reserve_area( base, end );
552 else
553 #endif
554 reserve_area( user_space_limit, 0 );
556 #else
558 if (preload_info) return;
559 /* if we don't have a preloader, try to reserve the space now */
560 reserve_area( (void *)0x000000010000, (void *)0x000068000000 );
561 reserve_area( (void *)0x00007ff00000, (void *)0x00007fff0000 );
562 reserve_area( (void *)0x7ffffe000000, (void *)0x7fffffff0000 );
564 #endif
568 /***********************************************************************
569 * get_wow_user_space_limit
571 static void *get_wow_user_space_limit(void)
573 #ifdef _WIN64
574 if (main_image_info.ImageCharacteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) return (void *)0xc0000000;
575 return (void *)0x7fff0000;
576 #endif
577 return user_space_limit;
581 /***********************************************************************
582 * add_builtin_module
584 static void add_builtin_module( void *module, void *handle )
586 struct builtin_module *builtin;
588 if (!(builtin = malloc( sizeof(*builtin) ))) return;
589 builtin->handle = handle;
590 builtin->module = module;
591 builtin->refcount = 1;
592 builtin->unix_path = NULL;
593 builtin->unix_handle = NULL;
594 list_add_tail( &builtin_modules, &builtin->entry );
598 /***********************************************************************
599 * release_builtin_module
601 static void release_builtin_module( void *module )
603 struct builtin_module *builtin;
605 LIST_FOR_EACH_ENTRY( builtin, &builtin_modules, struct builtin_module, entry )
607 if (builtin->module != module) continue;
608 if (!--builtin->refcount)
610 list_remove( &builtin->entry );
611 if (builtin->handle) dlclose( builtin->handle );
612 if (builtin->unix_handle) dlclose( builtin->unix_handle );
613 free( builtin->unix_path );
614 free( builtin );
616 break;
621 /***********************************************************************
622 * get_builtin_so_handle
624 void *get_builtin_so_handle( void *module )
626 sigset_t sigset;
627 void *ret = NULL;
628 struct builtin_module *builtin;
630 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
631 LIST_FOR_EACH_ENTRY( builtin, &builtin_modules, struct builtin_module, entry )
633 if (builtin->module != module) continue;
634 ret = builtin->handle;
635 if (ret) builtin->refcount++;
636 break;
638 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
639 return ret;
643 /***********************************************************************
644 * get_builtin_unix_funcs
646 static NTSTATUS get_builtin_unix_funcs( void *module, BOOL wow, const void **funcs )
648 const char *ptr_name = wow ? "__wine_unix_call_wow64_funcs" : "__wine_unix_call_funcs";
649 sigset_t sigset;
650 NTSTATUS status = STATUS_DLL_NOT_FOUND;
651 struct builtin_module *builtin;
653 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
654 LIST_FOR_EACH_ENTRY( builtin, &builtin_modules, struct builtin_module, entry )
656 if (builtin->module != module) continue;
657 if (builtin->unix_path && !builtin->unix_handle)
658 builtin->unix_handle = dlopen( builtin->unix_path, RTLD_NOW );
659 if (builtin->unix_handle)
661 *funcs = dlsym( builtin->unix_handle, ptr_name );
662 status = *funcs ? STATUS_SUCCESS : STATUS_ENTRYPOINT_NOT_FOUND;
664 break;
666 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
667 return status;
671 /***********************************************************************
672 * load_builtin_unixlib
674 NTSTATUS load_builtin_unixlib( void *module, const char *name )
676 sigset_t sigset;
677 NTSTATUS status = STATUS_SUCCESS;
678 struct builtin_module *builtin;
680 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
681 LIST_FOR_EACH_ENTRY( builtin, &builtin_modules, struct builtin_module, entry )
683 if (builtin->module != module) continue;
684 if (!builtin->unix_path) builtin->unix_path = strdup( name );
685 else status = STATUS_IMAGE_ALREADY_LOADED;
686 break;
688 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
689 return status;
693 /***********************************************************************
694 * free_ranges_lower_bound
696 * Returns the first range whose end is not less than addr, or end if there's none.
698 static struct range_entry *free_ranges_lower_bound( void *addr )
700 struct range_entry *begin = free_ranges;
701 struct range_entry *end = free_ranges_end;
702 struct range_entry *mid;
704 while (begin < end)
706 mid = begin + (end - begin) / 2;
707 if (mid->end < addr)
708 begin = mid + 1;
709 else
710 end = mid;
713 return begin;
716 static void dump_free_ranges(void)
718 struct range_entry *r;
719 for (r = free_ranges; r != free_ranges_end; ++r)
720 TRACE_(virtual_ranges)("%p - %p.\n", r->base, r->end);
723 /***********************************************************************
724 * free_ranges_insert_view
726 * Updates the free_ranges after a new view has been created.
728 static void free_ranges_insert_view( struct file_view *view )
730 void *view_base = ROUND_ADDR( view->base, granularity_mask );
731 void *view_end = ROUND_ADDR( (char *)view->base + view->size + granularity_mask, granularity_mask );
732 struct range_entry *range = free_ranges_lower_bound( view_base );
733 struct range_entry *next = range + 1;
735 /* free_ranges initial value is such that the view is either inside range or before another one. */
736 assert( range != free_ranges_end );
737 assert( range->end > view_base || next != free_ranges_end );
739 /* Free ranges addresses are aligned at granularity_mask while the views may be not. */
741 if (range->base > view_base)
742 view_base = range->base;
743 if (range->end < view_end)
744 view_end = range->end;
745 if (range->end == view_base && next->base >= view_end)
746 view_end = view_base;
748 TRACE_(virtual_ranges)( "%p - %p, aligned %p - %p.\n",
749 view->base, (char *)view->base + view->size, view_base, view_end );
751 if (view_end <= view_base)
753 VIRTUAL_DEBUG_DUMP_RANGES();
754 return;
757 /* this should never happen */
758 if (range->base > view_base || range->end < view_end)
759 ERR( "range %p - %p is already partially mapped\n", view_base, view_end );
760 assert( range->base <= view_base && range->end >= view_end );
762 /* need to split the range in two */
763 if (range->base < view_base && range->end > view_end)
765 memmove( next + 1, next, (free_ranges_end - next) * sizeof(struct range_entry) );
766 free_ranges_end += 1;
767 if ((char *)free_ranges_end - (char *)free_ranges > view_block_size)
768 ERR( "Free range sequence is full, trouble ahead!\n" );
769 assert( (char *)free_ranges_end - (char *)free_ranges <= view_block_size );
771 next->base = view_end;
772 next->end = range->end;
773 range->end = view_base;
775 else
777 /* otherwise we just have to shrink it */
778 if (range->base < view_base)
779 range->end = view_base;
780 else
781 range->base = view_end;
783 if (range->base < range->end)
785 VIRTUAL_DEBUG_DUMP_RANGES();
786 return;
788 /* and possibly remove it if it's now empty */
789 memmove( range, next, (free_ranges_end - next) * sizeof(struct range_entry) );
790 free_ranges_end -= 1;
791 assert( free_ranges_end - free_ranges > 0 );
793 VIRTUAL_DEBUG_DUMP_RANGES();
796 /***********************************************************************
797 * free_ranges_remove_view
799 * Updates the free_ranges after a view has been destroyed.
801 static void free_ranges_remove_view( struct file_view *view )
803 void *view_base = ROUND_ADDR( view->base, granularity_mask );
804 void *view_end = ROUND_ADDR( (char *)view->base + view->size + granularity_mask, granularity_mask );
805 struct range_entry *range = free_ranges_lower_bound( view_base );
806 struct range_entry *next = range + 1;
808 /* Free ranges addresses are aligned at granularity_mask while the views may be not. */
809 struct file_view *prev_view = RB_ENTRY_VALUE( rb_prev( &view->entry ), struct file_view, entry );
810 struct file_view *next_view = RB_ENTRY_VALUE( rb_next( &view->entry ), struct file_view, entry );
811 void *prev_view_base = prev_view ? ROUND_ADDR( prev_view->base, granularity_mask ) : NULL;
812 void *prev_view_end = prev_view ? ROUND_ADDR( (char *)prev_view->base + prev_view->size + granularity_mask, granularity_mask ) : NULL;
813 void *next_view_base = next_view ? ROUND_ADDR( next_view->base, granularity_mask ) : NULL;
814 void *next_view_end = next_view ? ROUND_ADDR( (char *)next_view->base + next_view->size + granularity_mask, granularity_mask ) : NULL;
816 if (prev_view_end && prev_view_end > view_base && prev_view_base < view_end)
817 view_base = prev_view_end;
818 if (next_view_base && next_view_base < view_end && next_view_end > view_base)
819 view_end = next_view_base;
821 TRACE_(virtual_ranges)( "%p - %p, aligned %p - %p.\n",
822 view->base, (char *)view->base + view->size, view_base, view_end );
824 if (view_end <= view_base)
826 VIRTUAL_DEBUG_DUMP_RANGES();
827 return;
829 /* free_ranges initial value is such that the view is either inside range or before another one. */
830 assert( range != free_ranges_end );
831 assert( range->end > view_base || next != free_ranges_end );
833 /* this should never happen, but we can safely ignore it */
834 if (range->base <= view_base && range->end >= view_end)
836 WARN( "range %p - %p is already unmapped\n", view_base, view_end );
837 return;
840 /* this should never happen */
841 if (range->base < view_end && range->end > view_base)
842 ERR( "range %p - %p is already partially unmapped\n", view_base, view_end );
843 assert( range->end <= view_base || range->base >= view_end );
845 /* merge with next if possible */
846 if (range->end == view_base && next->base == view_end)
848 range->end = next->end;
849 memmove( next, next + 1, (free_ranges_end - next - 1) * sizeof(struct range_entry) );
850 free_ranges_end -= 1;
851 assert( free_ranges_end - free_ranges > 0 );
853 /* or try growing the range */
854 else if (range->end == view_base)
855 range->end = view_end;
856 else if (range->base == view_end)
857 range->base = view_base;
858 /* otherwise create a new one */
859 else
861 memmove( range + 1, range, (free_ranges_end - range) * sizeof(struct range_entry) );
862 free_ranges_end += 1;
863 if ((char *)free_ranges_end - (char *)free_ranges > view_block_size)
864 ERR( "Free range sequence is full, trouble ahead!\n" );
865 assert( (char *)free_ranges_end - (char *)free_ranges <= view_block_size );
867 range->base = view_base;
868 range->end = view_end;
870 VIRTUAL_DEBUG_DUMP_RANGES();
874 static inline int is_view_valloc( const struct file_view *view )
876 return !(view->protect & (SEC_FILE | SEC_RESERVE | SEC_COMMIT));
879 /***********************************************************************
880 * get_page_vprot
882 * Return the page protection byte.
884 static BYTE get_page_vprot( const void *addr )
886 size_t idx = (size_t)addr >> page_shift;
888 #ifdef _WIN64
889 if ((idx >> pages_vprot_shift) >= pages_vprot_size) return 0;
890 if (!pages_vprot[idx >> pages_vprot_shift]) return 0;
891 return pages_vprot[idx >> pages_vprot_shift][idx & pages_vprot_mask];
892 #else
893 return pages_vprot[idx];
894 #endif
898 /***********************************************************************
899 * get_vprot_range_size
901 * Return the size of the region with equal masked vprot byte.
902 * Also return the protections for the first page.
903 * The function assumes that base and size are page aligned,
904 * base + size does not wrap around and the range is within view so
905 * vprot bytes are allocated for the range. */
906 static SIZE_T get_vprot_range_size( char *base, SIZE_T size, BYTE mask, BYTE *vprot )
908 static const UINT_PTR word_from_byte = (UINT_PTR)0x101010101010101;
909 static const UINT_PTR index_align_mask = sizeof(UINT_PTR) - 1;
910 SIZE_T curr_idx, start_idx, end_idx, aligned_start_idx;
911 UINT_PTR vprot_word, mask_word;
912 const BYTE *vprot_ptr;
914 TRACE("base %p, size %p, mask %#x.\n", base, (void *)size, mask);
916 curr_idx = start_idx = (size_t)base >> page_shift;
917 end_idx = start_idx + (size >> page_shift);
919 aligned_start_idx = (start_idx + index_align_mask) & ~index_align_mask;
920 if (aligned_start_idx > end_idx) aligned_start_idx = end_idx;
922 #ifdef _WIN64
923 vprot_ptr = pages_vprot[curr_idx >> pages_vprot_shift] + (curr_idx & pages_vprot_mask);
924 #else
925 vprot_ptr = pages_vprot + curr_idx;
926 #endif
927 *vprot = *vprot_ptr;
929 /* Page count page table is at least the multiples of sizeof(UINT_PTR)
930 * so we don't have to worry about crossing the boundary on unaligned idx values. */
932 for (; curr_idx < aligned_start_idx; ++curr_idx, ++vprot_ptr)
933 if ((*vprot ^ *vprot_ptr) & mask) return (curr_idx - start_idx) << page_shift;
935 vprot_word = word_from_byte * *vprot;
936 mask_word = word_from_byte * mask;
937 for (; curr_idx < end_idx; curr_idx += sizeof(UINT_PTR), vprot_ptr += sizeof(UINT_PTR))
939 #ifdef _WIN64
940 if (!(curr_idx & pages_vprot_mask)) vprot_ptr = pages_vprot[curr_idx >> pages_vprot_shift];
941 #endif
942 if ((vprot_word ^ *(UINT_PTR *)vprot_ptr) & mask_word)
944 for (; curr_idx < end_idx; ++curr_idx, ++vprot_ptr)
945 if ((*vprot ^ *vprot_ptr) & mask) break;
946 return (curr_idx - start_idx) << page_shift;
949 return size;
952 /***********************************************************************
953 * set_page_vprot
955 * Set a range of page protection bytes.
957 static void set_page_vprot( const void *addr, size_t size, BYTE vprot )
959 size_t idx = (size_t)addr >> page_shift;
960 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
962 #ifdef _WIN64
963 while (idx >> pages_vprot_shift != end >> pages_vprot_shift)
965 size_t dir_size = pages_vprot_mask + 1 - (idx & pages_vprot_mask);
966 memset( pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask), vprot, dir_size );
967 idx += dir_size;
969 memset( pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask), vprot, end - idx );
970 #else
971 memset( pages_vprot + idx, vprot, end - idx );
972 #endif
976 /***********************************************************************
977 * set_page_vprot_bits
979 * Set or clear bits in a range of page protection bytes.
981 static void set_page_vprot_bits( const void *addr, size_t size, BYTE set, BYTE clear )
983 size_t idx = (size_t)addr >> page_shift;
984 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
986 #ifdef _WIN64
987 for ( ; idx < end; idx++)
989 BYTE *ptr = pages_vprot[idx >> pages_vprot_shift] + (idx & pages_vprot_mask);
990 *ptr = (*ptr & ~clear) | set;
992 #else
993 for ( ; idx < end; idx++) pages_vprot[idx] = (pages_vprot[idx] & ~clear) | set;
994 #endif
998 /***********************************************************************
999 * alloc_pages_vprot
1001 * Allocate the page protection bytes for a given range.
1003 static BOOL alloc_pages_vprot( const void *addr, size_t size )
1005 #ifdef _WIN64
1006 size_t idx = (size_t)addr >> page_shift;
1007 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
1008 size_t i;
1009 void *ptr;
1011 assert( end <= pages_vprot_size << pages_vprot_shift );
1012 for (i = idx >> pages_vprot_shift; i < (end + pages_vprot_mask) >> pages_vprot_shift; i++)
1014 if (pages_vprot[i]) continue;
1015 if ((ptr = anon_mmap_alloc( pages_vprot_mask + 1, PROT_READ | PROT_WRITE )) == MAP_FAILED)
1016 return FALSE;
1017 pages_vprot[i] = ptr;
1019 #endif
1020 return TRUE;
1024 static inline UINT64 maskbits( size_t idx )
1026 return ~(UINT64)0 << (idx & 63);
1029 /***********************************************************************
1030 * set_arm64ec_range
1032 static void set_arm64ec_range( const void *addr, size_t size )
1034 size_t idx = (size_t)addr >> page_shift;
1035 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
1036 size_t pos = idx / 64;
1037 size_t end_pos = end / 64;
1039 if (end_pos > pos)
1041 arm64ec_map[pos++] |= maskbits( idx );
1042 while (pos < end_pos) arm64ec_map[pos++] = ~(UINT64)0;
1043 if (end & 63) arm64ec_map[pos] |= ~maskbits( end );
1045 else arm64ec_map[pos] |= maskbits( idx ) & ~maskbits( end );
1049 /***********************************************************************
1050 * clear_arm64ec_range
1052 static void clear_arm64ec_range( const void *addr, size_t size )
1054 size_t idx = (size_t)addr >> page_shift;
1055 size_t end = ((size_t)addr + size + page_mask) >> page_shift;
1056 size_t pos = idx / 64;
1057 size_t end_pos = end / 64;
1059 if (end_pos > pos)
1061 arm64ec_map[pos++] &= ~maskbits( idx );
1062 while (pos < end_pos) arm64ec_map[pos++] = 0;
1063 if (end & 63) arm64ec_map[pos] &= maskbits( end );
1065 else arm64ec_map[pos] &= ~maskbits( idx ) | maskbits( end );
1069 /***********************************************************************
1070 * compare_view
1072 * View comparison function used for the rb tree.
1074 static int compare_view( const void *addr, const struct wine_rb_entry *entry )
1076 struct file_view *view = WINE_RB_ENTRY_VALUE( entry, struct file_view, entry );
1078 if (addr < view->base) return -1;
1079 if (addr > view->base) return 1;
1080 return 0;
1084 /***********************************************************************
1085 * get_prot_str
1087 static const char *get_prot_str( BYTE prot )
1089 static char buffer[6];
1090 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
1091 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
1092 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
1093 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
1094 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
1095 buffer[5] = 0;
1096 return buffer;
1100 /***********************************************************************
1101 * get_unix_prot
1103 * Convert page protections to protection for mmap/mprotect.
1105 static int get_unix_prot( BYTE vprot )
1107 int prot = 0;
1108 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
1110 if (vprot & VPROT_READ) prot |= PROT_READ;
1111 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
1112 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
1113 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
1114 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
1116 if (!prot) prot = PROT_NONE;
1117 return prot;
1121 /***********************************************************************
1122 * dump_view
1124 static void dump_view( struct file_view *view )
1126 UINT i, count;
1127 char *addr = view->base;
1128 BYTE prot = get_page_vprot( addr );
1130 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
1131 if (view->protect & VPROT_SYSTEM)
1132 TRACE( " (builtin image)\n" );
1133 else if (view->protect & SEC_IMAGE)
1134 TRACE( " (image)\n" );
1135 else if (view->protect & SEC_FILE)
1136 TRACE( " (file)\n" );
1137 else if (view->protect & (SEC_RESERVE | SEC_COMMIT))
1138 TRACE( " (anonymous)\n" );
1139 else
1140 TRACE( " (valloc)\n");
1142 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1144 BYTE next = get_page_vprot( addr + (count << page_shift) );
1145 if (next == prot) continue;
1146 TRACE( " %p - %p %s\n",
1147 addr, addr + (count << page_shift) - 1, get_prot_str(prot) );
1148 addr += (count << page_shift);
1149 prot = next;
1150 count = 0;
1152 if (count)
1153 TRACE( " %p - %p %s\n",
1154 addr, addr + (count << page_shift) - 1, get_prot_str(prot) );
1158 /***********************************************************************
1159 * VIRTUAL_Dump
1161 #ifdef WINE_VM_DEBUG
1162 static void VIRTUAL_Dump(void)
1164 sigset_t sigset;
1165 struct file_view *view;
1167 TRACE( "Dump of all virtual memory views:\n" );
1168 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
1169 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
1171 dump_view( view );
1173 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
1175 #endif
1178 /***********************************************************************
1179 * find_view
1181 * Find the view containing a given address. virtual_mutex must be held by caller.
1183 * PARAMS
1184 * addr [I] Address
1186 * RETURNS
1187 * View: Success
1188 * NULL: Failure
1190 static struct file_view *find_view( const void *addr, size_t size )
1192 struct wine_rb_entry *ptr = views_tree.root;
1194 if ((const char *)addr + size < (const char *)addr) return NULL; /* overflow */
1196 while (ptr)
1198 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
1200 if (view->base > addr) ptr = ptr->left;
1201 else if ((const char *)view->base + view->size <= (const char *)addr) ptr = ptr->right;
1202 else if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
1203 else return view;
1205 return NULL;
1209 /***********************************************************************
1210 * is_write_watch_range
1212 static inline BOOL is_write_watch_range( const void *addr, size_t size )
1214 struct file_view *view = find_view( addr, size );
1215 return view && (view->protect & VPROT_WRITEWATCH);
1219 /***********************************************************************
1220 * find_view_range
1222 * Find the first view overlapping at least part of the specified range.
1223 * virtual_mutex must be held by caller.
1225 static struct file_view *find_view_range( const void *addr, size_t size )
1227 struct wine_rb_entry *ptr = views_tree.root;
1229 while (ptr)
1231 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
1233 if ((const char *)view->base >= (const char *)addr + size) ptr = ptr->left;
1234 else if ((const char *)view->base + view->size <= (const char *)addr) ptr = ptr->right;
1235 else return view;
1237 return NULL;
1241 /***********************************************************************
1242 * find_view_inside_range
1244 * Find first (resp. last, if top_down) view inside a range.
1245 * virtual_mutex must be held by caller.
1247 static struct wine_rb_entry *find_view_inside_range( void **base_ptr, void **end_ptr, int top_down )
1249 struct wine_rb_entry *first = NULL, *ptr = views_tree.root;
1250 void *base = *base_ptr, *end = *end_ptr;
1252 /* find the first (resp. last) view inside the range */
1253 while (ptr)
1255 struct file_view *view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
1256 if ((char *)view->base + view->size >= (char *)end)
1258 end = min( end, view->base );
1259 ptr = ptr->left;
1261 else if (view->base <= base)
1263 base = max( (char *)base, (char *)view->base + view->size );
1264 ptr = ptr->right;
1266 else
1268 first = ptr;
1269 ptr = top_down ? ptr->right : ptr->left;
1273 *base_ptr = base;
1274 *end_ptr = end;
1275 return first;
1279 /***********************************************************************
1280 * try_map_free_area
1282 * Try mmaping some expected free memory region, eventually stepping and
1283 * retrying inside it, and return where it actually succeeded, or NULL.
1285 static void* try_map_free_area( void *base, void *end, ptrdiff_t step,
1286 void *start, size_t size, int unix_prot )
1288 void *ptr;
1290 while (start && base <= start && (char*)start + size <= (char*)end)
1292 if ((ptr = anon_mmap_tryfixed( start, size, unix_prot, 0 )) != MAP_FAILED) return start;
1293 TRACE( "Found free area is already mapped, start %p.\n", start );
1294 if (errno != EEXIST)
1296 ERR( "mmap() error %s, range %p-%p, unix_prot %#x.\n",
1297 strerror(errno), start, (char *)start + size, unix_prot );
1298 return NULL;
1300 if ((step > 0 && (char *)end - (char *)start < step) ||
1301 (step < 0 && (char *)start - (char *)base < -step) ||
1302 step == 0)
1303 break;
1304 start = (char *)start + step;
1307 return NULL;
1311 /***********************************************************************
1312 * map_free_area
1314 * Find a free area between views inside the specified range and map it.
1315 * virtual_mutex must be held by caller.
1317 static void *map_free_area( void *base, void *end, size_t size, int top_down, int unix_prot, size_t align_mask )
1319 struct wine_rb_entry *first = find_view_inside_range( &base, &end, top_down );
1320 ptrdiff_t step = top_down ? -(align_mask + 1) : (align_mask + 1);
1321 void *start;
1323 if (top_down)
1325 start = ROUND_ADDR( (char *)end - size, align_mask );
1326 if (start >= end || start < base) return NULL;
1328 while (first)
1330 struct file_view *view = WINE_RB_ENTRY_VALUE( first, struct file_view, entry );
1331 if ((start = try_map_free_area( (char *)view->base + view->size, (char *)start + size, step,
1332 start, size, unix_prot ))) break;
1333 start = ROUND_ADDR( (char *)view->base - size, align_mask );
1334 /* stop if remaining space is not large enough */
1335 if (!start || start >= end || start < base) return NULL;
1336 first = rb_prev( first );
1339 else
1341 start = ROUND_ADDR( (char *)base + align_mask, align_mask );
1342 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
1344 while (first)
1346 struct file_view *view = WINE_RB_ENTRY_VALUE( first, struct file_view, entry );
1347 if ((start = try_map_free_area( start, view->base, step,
1348 start, size, unix_prot ))) break;
1349 start = ROUND_ADDR( (char *)view->base + view->size + align_mask, align_mask );
1350 /* stop if remaining space is not large enough */
1351 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
1352 first = rb_next( first );
1356 if (!first)
1357 return try_map_free_area( base, end, step, start, size, unix_prot );
1359 return start;
1363 /***********************************************************************
1364 * find_reserved_free_area
1366 * Find a free area between views inside the specified range.
1367 * virtual_mutex must be held by caller.
1368 * The range must be inside the preloader reserved range.
1370 static void *find_reserved_free_area( void *base, void *end, size_t size, int top_down, size_t align_mask )
1372 struct range_entry *range;
1373 void *start;
1375 base = ROUND_ADDR( (char *)base + align_mask, align_mask );
1376 end = (char *)ROUND_ADDR( (char *)end - size, align_mask ) + size;
1378 if (top_down)
1380 start = (char *)end - size;
1381 range = free_ranges_lower_bound( start );
1382 assert(range != free_ranges_end && range->end >= start);
1384 if ((char *)range->end - (char *)start < size) start = ROUND_ADDR( (char *)range->end - size, align_mask );
1387 if (start >= end || start < base || (char *)end - (char *)start < size) return NULL;
1388 if (start < range->end && start >= range->base && (char *)range->end - (char *)start >= size) break;
1389 if (--range < free_ranges) return NULL;
1390 start = ROUND_ADDR( (char *)range->end - size, align_mask );
1392 while (1);
1394 else
1396 start = base;
1397 range = free_ranges_lower_bound( start );
1398 assert(range != free_ranges_end && range->end >= start);
1400 if (start < range->base) start = ROUND_ADDR( (char *)range->base + align_mask, align_mask );
1403 if (start >= end || start < base || (char *)end - (char *)start < size) return NULL;
1404 if (start < range->end && start >= range->base && (char *)range->end - (char *)start >= size) break;
1405 if (++range == free_ranges_end) return NULL;
1406 start = ROUND_ADDR( (char *)range->base + align_mask, align_mask );
1408 while (1);
1410 return start;
1414 /***********************************************************************
1415 * add_reserved_area
1417 * Add a reserved area to the list maintained by libwine.
1418 * virtual_mutex must be held by caller.
1420 static void add_reserved_area( void *addr, size_t size )
1422 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
1424 if (addr < user_space_limit)
1426 /* unmap the part of the area that is below the limit */
1427 assert( (char *)addr + size > (char *)user_space_limit );
1428 munmap( addr, (char *)user_space_limit - (char *)addr );
1429 size -= (char *)user_space_limit - (char *)addr;
1430 addr = user_space_limit;
1432 /* blow away existing mappings */
1433 anon_mmap_fixed( addr, size, PROT_NONE, MAP_NORESERVE );
1434 mmap_add_reserved_area( addr, size );
1438 /***********************************************************************
1439 * remove_reserved_area
1441 * Remove a reserved area from the list maintained by libwine.
1442 * virtual_mutex must be held by caller.
1444 static void remove_reserved_area( void *addr, size_t size )
1446 struct file_view *view;
1448 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
1449 mmap_remove_reserved_area( addr, size );
1451 /* unmap areas not covered by an existing view */
1452 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
1454 if ((char *)view->base >= (char *)addr + size) break;
1455 if ((char *)view->base + view->size <= (char *)addr) continue;
1456 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
1457 if ((char *)view->base + view->size > (char *)addr + size) return;
1458 size = (char *)addr + size - ((char *)view->base + view->size);
1459 addr = (char *)view->base + view->size;
1461 munmap( addr, size );
1465 struct area_boundary
1467 void *base;
1468 size_t size;
1469 void *boundary;
1472 /***********************************************************************
1473 * get_area_boundary_callback
1475 * Get lowest boundary address between reserved area and non-reserved area
1476 * in the specified region. If no boundaries are found, result is NULL.
1477 * virtual_mutex must be held by caller.
1479 static int get_area_boundary_callback( void *start, SIZE_T size, void *arg )
1481 struct area_boundary *area = arg;
1482 void *end = (char *)start + size;
1484 area->boundary = NULL;
1485 if (area->base >= end) return 0;
1486 if ((char *)start >= (char *)area->base + area->size) return 1;
1487 if (area->base >= start)
1489 if ((char *)area->base + area->size > (char *)end)
1491 area->boundary = end;
1492 return 1;
1494 return 0;
1496 area->boundary = start;
1497 return 1;
1501 /***********************************************************************
1502 * unmap_area
1504 * Unmap an area, or simply replace it by an empty mapping if it is
1505 * in a reserved area. virtual_mutex must be held by caller.
1507 static inline void unmap_area( void *addr, size_t size )
1509 switch (mmap_is_in_reserved_area( addr, size ))
1511 case -1: /* partially in a reserved area */
1513 struct area_boundary area;
1514 size_t lower_size;
1515 area.base = addr;
1516 area.size = size;
1517 mmap_enum_reserved_areas( get_area_boundary_callback, &area, 0 );
1518 assert( area.boundary );
1519 lower_size = (char *)area.boundary - (char *)addr;
1520 unmap_area( addr, lower_size );
1521 unmap_area( area.boundary, size - lower_size );
1522 break;
1524 case 1: /* in a reserved area */
1525 anon_mmap_fixed( addr, size, PROT_NONE, MAP_NORESERVE );
1526 break;
1527 default:
1528 case 0: /* not in a reserved area */
1529 if (is_beyond_limit( addr, size, user_space_limit ))
1530 add_reserved_area( addr, size );
1531 else
1532 munmap( addr, size );
1533 break;
1538 /***********************************************************************
1539 * alloc_view
1541 * Allocate a new view. virtual_mutex must be held by caller.
1543 static struct file_view *alloc_view(void)
1545 if (next_free_view)
1547 struct file_view *ret = next_free_view;
1548 next_free_view = *(struct file_view **)ret;
1549 return ret;
1551 if (view_block_start == view_block_end)
1553 void *ptr = anon_mmap_alloc( view_block_size, PROT_READ | PROT_WRITE );
1554 if (ptr == MAP_FAILED) return NULL;
1555 view_block_start = ptr;
1556 view_block_end = view_block_start + view_block_size / sizeof(*view_block_start);
1558 return view_block_start++;
1562 /***********************************************************************
1563 * free_view
1565 * Free memory for view structure. virtual_mutex must be held by caller.
1567 static void free_view( struct file_view *view )
1569 *(struct file_view **)view = next_free_view;
1570 next_free_view = view;
1574 /***********************************************************************
1575 * unregister_view
1577 * Remove view from the tree and update free ranges. virtual_mutex must be held by caller.
1579 static void unregister_view( struct file_view *view )
1581 if (mmap_is_in_reserved_area( view->base, view->size ))
1582 free_ranges_remove_view( view );
1583 wine_rb_remove( &views_tree, &view->entry );
1587 /***********************************************************************
1588 * delete_view
1590 * Deletes a view. virtual_mutex must be held by caller.
1592 static void delete_view( struct file_view *view ) /* [in] View */
1594 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
1595 set_page_vprot( view->base, view->size, 0 );
1596 if (arm64ec_map) clear_arm64ec_range( view->base, view->size );
1597 unregister_view( view );
1598 free_view( view );
1602 /***********************************************************************
1603 * register_view
1605 * Add view to the tree and update free ranges. virtual_mutex must be held by caller.
1607 static void register_view( struct file_view *view )
1609 wine_rb_put( &views_tree, view->base, &view->entry );
1610 if (mmap_is_in_reserved_area( view->base, view->size ))
1611 free_ranges_insert_view( view );
1615 /***********************************************************************
1616 * create_view
1618 * Create a view. virtual_mutex must be held by caller.
1620 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
1622 struct file_view *view;
1623 int unix_prot = get_unix_prot( vprot );
1625 assert( !((UINT_PTR)base & page_mask) );
1626 assert( !(size & page_mask) );
1628 /* Check for overlapping views. This can happen if the previous view
1629 * was a system view that got unmapped behind our back. In that case
1630 * we recover by simply deleting it. */
1632 while ((view = find_view_range( base, size )))
1634 TRACE( "overlapping view %p-%p for %p-%p\n",
1635 view->base, (char *)view->base + view->size, base, (char *)base + size );
1636 assert( view->protect & VPROT_SYSTEM );
1637 delete_view( view );
1640 if (!alloc_pages_vprot( base, size )) return STATUS_NO_MEMORY;
1642 /* Create the view structure */
1644 if (!(view = alloc_view()))
1646 FIXME( "out of memory for %p-%p\n", base, (char *)base + size );
1647 return STATUS_NO_MEMORY;
1650 view->base = base;
1651 view->size = size;
1652 view->protect = vprot;
1653 set_page_vprot( base, size, vprot );
1655 register_view( view );
1657 *view_ret = view;
1659 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1661 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
1662 mprotect( base, size, unix_prot | PROT_EXEC );
1664 return STATUS_SUCCESS;
1668 /***********************************************************************
1669 * get_win32_prot
1671 * Convert page protections to Win32 flags.
1673 static DWORD get_win32_prot( BYTE vprot, unsigned int map_prot )
1675 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
1676 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
1677 if (map_prot & SEC_NOCACHE) ret |= PAGE_NOCACHE;
1678 return ret;
1682 /***********************************************************************
1683 * get_vprot_flags
1685 * Build page protections from Win32 flags.
1687 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
1689 switch(protect & 0xff)
1691 case PAGE_READONLY:
1692 *vprot = VPROT_READ;
1693 break;
1694 case PAGE_READWRITE:
1695 if (image)
1696 *vprot = VPROT_READ | VPROT_WRITECOPY;
1697 else
1698 *vprot = VPROT_READ | VPROT_WRITE;
1699 break;
1700 case PAGE_WRITECOPY:
1701 *vprot = VPROT_READ | VPROT_WRITECOPY;
1702 break;
1703 case PAGE_EXECUTE:
1704 *vprot = VPROT_EXEC;
1705 break;
1706 case PAGE_EXECUTE_READ:
1707 *vprot = VPROT_EXEC | VPROT_READ;
1708 break;
1709 case PAGE_EXECUTE_READWRITE:
1710 if (image)
1711 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
1712 else
1713 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
1714 break;
1715 case PAGE_EXECUTE_WRITECOPY:
1716 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
1717 break;
1718 case PAGE_NOACCESS:
1719 *vprot = 0;
1720 break;
1721 default:
1722 return STATUS_INVALID_PAGE_PROTECTION;
1724 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
1725 return STATUS_SUCCESS;
1729 /***********************************************************************
1730 * mprotect_exec
1732 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
1734 static inline int mprotect_exec( void *base, size_t size, int unix_prot )
1736 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1738 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
1739 if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
1740 /* exec + write may legitimately fail, in that case fall back to write only */
1741 if (!(unix_prot & PROT_WRITE)) return -1;
1744 return mprotect( base, size, unix_prot );
1748 /***********************************************************************
1749 * mprotect_range
1751 * Call mprotect on a page range, applying the protections from the per-page byte.
1753 static void mprotect_range( void *base, size_t size, BYTE set, BYTE clear )
1755 size_t i, count;
1756 char *addr = ROUND_ADDR( base, page_mask );
1757 int prot, next;
1759 size = ROUND_SIZE( base, size );
1760 prot = get_unix_prot( (get_page_vprot( addr ) & ~clear ) | set );
1761 for (count = i = 1; i < size >> page_shift; i++, count++)
1763 next = get_unix_prot( (get_page_vprot( addr + (count << page_shift) ) & ~clear) | set );
1764 if (next == prot) continue;
1765 mprotect_exec( addr, count << page_shift, prot );
1766 addr += count << page_shift;
1767 prot = next;
1768 count = 0;
1770 if (count) mprotect_exec( addr, count << page_shift, prot );
1774 /***********************************************************************
1775 * set_vprot
1777 * Change the protection of a range of pages.
1779 static BOOL set_vprot( struct file_view *view, void *base, size_t size, BYTE vprot )
1781 int unix_prot = get_unix_prot(vprot);
1783 if (view->protect & VPROT_WRITEWATCH)
1785 /* each page may need different protections depending on write watch flag */
1786 set_page_vprot_bits( base, size, vprot & ~VPROT_WRITEWATCH, ~vprot & ~VPROT_WRITEWATCH );
1787 mprotect_range( base, size, 0, 0 );
1788 return TRUE;
1790 if (mprotect_exec( base, size, unix_prot )) return FALSE;
1791 set_page_vprot( base, size, vprot );
1792 return TRUE;
1796 /***********************************************************************
1797 * set_protection
1799 * Set page protections on a range of pages
1801 static NTSTATUS set_protection( struct file_view *view, void *base, SIZE_T size, ULONG protect )
1803 unsigned int vprot;
1804 NTSTATUS status;
1806 if ((status = get_vprot_flags( protect, &vprot, view->protect & SEC_IMAGE ))) return status;
1807 if (is_view_valloc( view ))
1809 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1811 else
1813 BYTE access = vprot & (VPROT_READ | VPROT_WRITE | VPROT_EXEC);
1814 if ((view->protect & access) != access) return STATUS_INVALID_PAGE_PROTECTION;
1817 if (!set_vprot( view, base, size, vprot | VPROT_COMMITTED )) return STATUS_ACCESS_DENIED;
1818 return STATUS_SUCCESS;
1822 /***********************************************************************
1823 * update_write_watches
1825 static void update_write_watches( void *base, size_t size, size_t accessed_size )
1827 TRACE( "updating watch %p-%p-%p\n", base, (char *)base + accessed_size, (char *)base + size );
1828 /* clear write watch flag on accessed pages */
1829 set_page_vprot_bits( base, accessed_size, 0, VPROT_WRITEWATCH );
1830 /* restore page protections on the entire range */
1831 mprotect_range( base, size, 0, 0 );
1835 /***********************************************************************
1836 * reset_write_watches
1838 * Reset write watches in a memory range.
1840 static void reset_write_watches( void *base, SIZE_T size )
1842 set_page_vprot_bits( base, size, VPROT_WRITEWATCH, 0 );
1843 mprotect_range( base, size, 0, 0 );
1847 /***********************************************************************
1848 * unmap_extra_space
1850 * Release the extra memory while keeping the range starting on the alignment boundary.
1852 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t align_mask )
1854 if ((ULONG_PTR)ptr & align_mask)
1856 size_t extra = align_mask + 1 - ((ULONG_PTR)ptr & align_mask);
1857 munmap( ptr, extra );
1858 ptr = (char *)ptr + extra;
1859 total_size -= extra;
1861 if (total_size > wanted_size)
1862 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
1863 return ptr;
1867 struct alloc_area
1869 size_t size;
1870 int top_down;
1871 void *limit;
1872 void *result;
1873 size_t align_mask;
1876 /***********************************************************************
1877 * alloc_reserved_area_callback
1879 * Try to map some space inside a reserved area. Callback for mmap_enum_reserved_areas.
1881 static int alloc_reserved_area_callback( void *start, SIZE_T size, void *arg )
1883 struct alloc_area *alloc = arg;
1884 void *end = (char *)start + size;
1886 if (start < address_space_start) start = address_space_start;
1887 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
1888 if (start >= end) return 0;
1890 /* make sure we don't touch the preloader reserved range */
1891 if (preload_reserve_end >= start)
1893 if (preload_reserve_end >= end)
1895 if (preload_reserve_start <= start) return 0; /* no space in that area */
1896 if (preload_reserve_start < end) end = preload_reserve_start;
1898 else if (preload_reserve_start <= start) start = preload_reserve_end;
1899 else
1901 /* range is split in two by the preloader reservation, try first part */
1902 if ((alloc->result = find_reserved_free_area( start, preload_reserve_start, alloc->size,
1903 alloc->top_down, alloc->align_mask )))
1904 return 1;
1905 /* then fall through to try second part */
1906 start = preload_reserve_end;
1909 if ((alloc->result = find_reserved_free_area( start, end, alloc->size, alloc->top_down, alloc->align_mask )))
1910 return 1;
1912 return 0;
1915 /***********************************************************************
1916 * map_fixed_area
1918 * mmap the fixed memory area.
1919 * virtual_mutex must be held by caller.
1921 static NTSTATUS map_fixed_area( void *base, size_t size, unsigned int vprot )
1923 void *ptr;
1925 switch (mmap_is_in_reserved_area( base, size ))
1927 case -1: /* partially in a reserved area */
1929 NTSTATUS status;
1930 struct area_boundary area;
1931 size_t lower_size;
1932 area.base = base;
1933 area.size = size;
1934 mmap_enum_reserved_areas( get_area_boundary_callback, &area, 0 );
1935 assert( area.boundary );
1936 lower_size = (char *)area.boundary - (char *)base;
1937 status = map_fixed_area( base, lower_size, vprot );
1938 if (status == STATUS_SUCCESS)
1940 status = map_fixed_area( area.boundary, size - lower_size, vprot);
1941 if (status != STATUS_SUCCESS) unmap_area( base, lower_size );
1943 return status;
1945 case 0: /* not in a reserved area, do a normal allocation */
1946 if ((ptr = anon_mmap_tryfixed( base, size, get_unix_prot(vprot), 0 )) == MAP_FAILED)
1948 if (errno == ENOMEM) return STATUS_NO_MEMORY;
1949 if (errno == EEXIST) return STATUS_CONFLICTING_ADDRESSES;
1950 return STATUS_INVALID_PARAMETER;
1952 break;
1954 default:
1955 case 1: /* in a reserved area, make sure the address is available */
1956 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
1957 /* replace the reserved area by our mapping */
1958 if ((ptr = anon_mmap_fixed( base, size, get_unix_prot(vprot), 0 )) != base)
1959 return STATUS_INVALID_PARAMETER;
1960 break;
1962 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
1963 return STATUS_SUCCESS;
1966 /***********************************************************************
1967 * map_view
1969 * Create a view and mmap the corresponding memory area.
1970 * virtual_mutex must be held by caller.
1972 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size,
1973 int top_down, unsigned int vprot, ULONG_PTR limit, size_t align_mask )
1975 void *ptr;
1976 NTSTATUS status;
1978 if (base)
1980 if (is_beyond_limit( base, size, address_space_limit ))
1981 return STATUS_WORKING_SET_LIMIT_RANGE;
1982 if (limit && is_beyond_limit( base, size, (void *)limit ))
1983 return STATUS_CONFLICTING_ADDRESSES;
1984 status = map_fixed_area( base, size, vprot );
1985 if (status != STATUS_SUCCESS) return status;
1986 ptr = base;
1988 else
1990 struct alloc_area alloc;
1991 size_t view_size;
1993 if (!align_mask) align_mask = granularity_mask;
1994 view_size = size + align_mask + 1;
1996 alloc.size = size;
1997 alloc.top_down = top_down;
1998 alloc.limit = limit ? min( (void *)(limit + 1), user_space_limit ) : user_space_limit;
1999 alloc.align_mask = align_mask;
2001 if (mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
2003 ptr = alloc.result;
2004 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
2005 if (anon_mmap_fixed( ptr, size, get_unix_prot(vprot), 0 ) != ptr)
2006 return STATUS_INVALID_PARAMETER;
2007 goto done;
2010 if (limit)
2012 if (!(ptr = map_free_area( address_space_start, alloc.limit, size,
2013 top_down, get_unix_prot(vprot), align_mask )))
2014 return STATUS_NO_MEMORY;
2015 TRACE( "got mem with map_free_area %p-%p\n", ptr, (char *)ptr + size );
2016 goto done;
2019 for (;;)
2021 if ((ptr = anon_mmap_alloc( view_size, get_unix_prot(vprot) )) == MAP_FAILED)
2023 if (errno == ENOMEM) return STATUS_NO_MEMORY;
2024 return STATUS_INVALID_PARAMETER;
2026 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
2027 /* if we got something beyond the user limit, unmap it and retry */
2028 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
2029 else break;
2031 ptr = unmap_extra_space( ptr, view_size, size, align_mask );
2033 done:
2034 status = create_view( view_ret, ptr, size, vprot );
2035 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
2036 return status;
2040 /***********************************************************************
2041 * map_file_into_view
2043 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
2044 * virtual_mutex must be held by caller.
2046 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
2047 off_t offset, unsigned int vprot, BOOL removable )
2049 void *ptr;
2050 int prot = get_unix_prot( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
2051 unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
2053 assert( start < view->size );
2054 assert( start + size <= view->size );
2056 if (force_exec_prot && (vprot & VPROT_READ))
2058 TRACE( "forcing exec permission on mapping %p-%p\n",
2059 (char *)view->base + start, (char *)view->base + start + size - 1 );
2060 prot |= PROT_EXEC;
2063 /* only try mmap if media is not removable (or if we require write access) */
2064 if (!removable || (flags & MAP_SHARED))
2066 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != MAP_FAILED)
2067 goto done;
2069 switch (errno)
2071 case EINVAL: /* file offset is not page-aligned, fall back to read() */
2072 if (flags & MAP_SHARED) return STATUS_INVALID_PARAMETER;
2073 break;
2074 case ENOEXEC:
2075 case ENODEV: /* filesystem doesn't support mmap(), fall back to read() */
2076 if (vprot & VPROT_WRITE)
2078 ERR( "shared writable mmap not supported, broken filesystem?\n" );
2079 return STATUS_NOT_SUPPORTED;
2081 break;
2082 case EACCES:
2083 case EPERM: /* noexec filesystem, fall back to read() */
2084 if (flags & MAP_SHARED)
2086 if (prot & PROT_EXEC) ERR( "failed to set PROT_EXEC on file map, noexec filesystem?\n" );
2087 return STATUS_ACCESS_DENIED;
2089 if (prot & PROT_EXEC) WARN( "failed to set PROT_EXEC on file map, noexec filesystem?\n" );
2090 break;
2091 default:
2092 return STATUS_NO_MEMORY;
2096 /* Reserve the memory with an anonymous mmap */
2097 ptr = anon_mmap_fixed( (char *)view->base + start, size, PROT_READ | PROT_WRITE, 0 );
2098 if (ptr == MAP_FAILED) return STATUS_NO_MEMORY;
2099 /* Now read in the file */
2100 pread( fd, ptr, size, offset );
2101 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
2102 done:
2103 set_page_vprot( (char *)view->base + start, size, vprot );
2104 return STATUS_SUCCESS;
2108 /***********************************************************************
2109 * get_committed_size
2111 * Get the size of the committed range with equal masked vprot bytes starting at base.
2112 * Also return the protections for the first page.
2114 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot, BYTE vprot_mask )
2116 SIZE_T offset, size;
2118 base = ROUND_ADDR( base, page_mask );
2119 offset = (char *)base - (char *)view->base;
2121 if (view->protect & SEC_RESERVE)
2123 size = 0;
2125 *vprot = get_page_vprot( base );
2127 SERVER_START_REQ( get_mapping_committed_range )
2129 req->base = wine_server_client_ptr( view->base );
2130 req->offset = offset;
2131 if (!wine_server_call( req ))
2133 size = reply->size;
2134 if (reply->committed)
2136 *vprot |= VPROT_COMMITTED;
2137 set_page_vprot_bits( base, size, VPROT_COMMITTED, 0 );
2141 SERVER_END_REQ;
2143 if (!size || !(vprot_mask & ~VPROT_COMMITTED)) return size;
2145 else size = view->size - offset;
2147 return get_vprot_range_size( base, size, vprot_mask, vprot );
2151 /***********************************************************************
2152 * decommit_pages
2154 * Decommit some pages of a given view.
2155 * virtual_mutex must be held by caller.
2157 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
2159 if (!size) size = view->size;
2160 if (anon_mmap_fixed( (char *)view->base + start, size, PROT_NONE, 0 ) != MAP_FAILED)
2162 set_page_vprot_bits( (char *)view->base + start, size, 0, VPROT_COMMITTED );
2163 return STATUS_SUCCESS;
2165 return STATUS_NO_MEMORY;
2169 /***********************************************************************
2170 * allocate_dos_memory
2172 * Allocate the DOS memory range.
2174 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
2176 size_t size;
2177 void *addr = NULL;
2178 void * const low_64k = (void *)0x10000;
2179 const size_t dosmem_size = 0x110000;
2180 int unix_prot = get_unix_prot( vprot );
2182 /* check for existing view */
2184 if (find_view_range( 0, dosmem_size )) return STATUS_CONFLICTING_ADDRESSES;
2186 /* check without the first 64K */
2188 if (mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
2190 addr = anon_mmap_tryfixed( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
2191 if (addr == MAP_FAILED) return map_view( view, NULL, dosmem_size, FALSE, vprot, 0, 0 );
2194 /* now try to allocate the low 64K too */
2196 if (mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
2198 addr = anon_mmap_tryfixed( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
2199 if (addr != MAP_FAILED)
2201 if (!anon_mmap_fixed( NULL, page_size, unix_prot, 0 ))
2203 addr = NULL;
2204 TRACE( "successfully mapped low 64K range\n" );
2206 else TRACE( "failed to map page 0\n" );
2208 else
2210 addr = low_64k;
2211 TRACE( "failed to map low 64K range\n" );
2215 /* now reserve the whole range */
2217 size = (char *)dosmem_size - (char *)addr;
2218 anon_mmap_fixed( addr, size, unix_prot, 0 );
2219 return create_view( view, addr, size, vprot );
2223 /***********************************************************************
2224 * map_pe_header
2226 * Map the header of a PE file into memory.
2228 static NTSTATUS map_pe_header( void *ptr, size_t size, int fd, BOOL *removable )
2230 if (!size) return STATUS_INVALID_IMAGE_FORMAT;
2232 if (!*removable)
2234 if (mmap( ptr, size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_FIXED|MAP_PRIVATE, fd, 0 ) != MAP_FAILED)
2235 return STATUS_SUCCESS;
2237 switch (errno)
2239 case EPERM:
2240 case EACCES:
2241 WARN( "noexec file system, falling back to read\n" );
2242 break;
2243 case ENOEXEC:
2244 case ENODEV:
2245 WARN( "file system doesn't support mmap, falling back to read\n" );
2246 break;
2247 default:
2248 return STATUS_NO_MEMORY;
2250 *removable = TRUE;
2252 pread( fd, ptr, size, 0 );
2253 return STATUS_SUCCESS; /* page protections will be updated later */
2256 #ifdef __aarch64__
2258 /***********************************************************************
2259 * apply_arm64x_relocations
2261 static void apply_arm64x_relocations( char *base, const IMAGE_BASE_RELOCATION *reloc, size_t size )
2263 const IMAGE_BASE_RELOCATION *reloc_end = (const IMAGE_BASE_RELOCATION *)((const char *)reloc + size);
2265 while (reloc < reloc_end - 1 && reloc->SizeOfBlock)
2267 const USHORT *rel = (const USHORT *)(reloc + 1);
2268 const USHORT *rel_end = (const USHORT *)reloc + reloc->SizeOfBlock / sizeof(USHORT);
2269 char *page = base + reloc->VirtualAddress;
2271 while (rel < rel_end && *rel)
2273 USHORT offset = *rel & 0xfff;
2274 USHORT type = (*rel >> 12) & 3;
2275 USHORT arg = *rel >> 14;
2276 int val;
2277 rel++;
2278 switch (type)
2280 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
2281 memset( page + offset, 0, 1 << arg );
2282 break;
2283 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
2284 memcpy( page + offset, rel, 1 << arg );
2285 rel += (1 << arg) / sizeof(USHORT);
2286 break;
2287 case IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
2288 val = (unsigned int)*rel++ * ((arg & 2) ? 8 : 4);
2289 if (arg & 1) val = -val;
2290 *(int *)(page + offset) += val;
2291 break;
2294 reloc = (const IMAGE_BASE_RELOCATION *)rel_end;
2299 /***********************************************************************
2300 * update_arm64x_mapping
2302 static void update_arm64x_mapping( char *base, IMAGE_NT_HEADERS *nt, IMAGE_SECTION_HEADER *sections )
2304 ULONG i, size, sec, offset;
2305 const IMAGE_DATA_DIRECTORY *dir;
2306 const IMAGE_LOAD_CONFIG_DIRECTORY *cfg;
2307 const IMAGE_ARM64EC_METADATA *metadata;
2308 const IMAGE_DYNAMIC_RELOCATION_TABLE *table;
2309 const char *ptr, *end;
2311 /* retrieve config directory */
2313 if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return;
2314 dir = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
2315 if (!dir->VirtualAddress || !dir->Size) return;
2316 cfg = (void *)(base + dir->VirtualAddress);
2317 size = min( dir->Size, cfg->Size );
2319 /* update code ranges */
2321 if (size <= offsetof( IMAGE_LOAD_CONFIG_DIRECTORY, CHPEMetadataPointer )) return;
2322 metadata = (void *)(base + (cfg->CHPEMetadataPointer - nt->OptionalHeader.ImageBase));
2323 if (metadata->CodeMap && arm64ec_map)
2325 const IMAGE_CHPE_RANGE_ENTRY *map = (void *)(base + metadata->CodeMap);
2327 for (i = 0; i < metadata->CodeMapCount; i++)
2329 if ((map[i].StartOffset & 0x3) != 1 /* arm64ec */) continue;
2330 set_arm64ec_range( base + (map[i].StartOffset & ~3), map[i].Length );
2334 /* apply dynamic relocations */
2336 if (size <= offsetof( IMAGE_LOAD_CONFIG_DIRECTORY, DynamicValueRelocTableSection )) return;
2337 offset = cfg->DynamicValueRelocTableOffset;
2338 sec = cfg->DynamicValueRelocTableSection;
2339 if (!sec || sec > nt->FileHeader.NumberOfSections) return;
2340 if (offset >= sections[sec - 1].Misc.VirtualSize) return;
2341 table = (const IMAGE_DYNAMIC_RELOCATION_TABLE *)(base + sections[sec - 1].VirtualAddress + offset);
2342 ptr = (const char *)(table + 1);
2343 end = ptr + table->Size;
2344 switch (table->Version)
2346 case 1:
2347 while (ptr < end)
2349 const IMAGE_DYNAMIC_RELOCATION64 *dyn = (const IMAGE_DYNAMIC_RELOCATION64 *)ptr;
2350 if (dyn->Symbol == IMAGE_DYNAMIC_RELOCATION_ARM64X)
2352 apply_arm64x_relocations( base, (const IMAGE_BASE_RELOCATION *)(dyn + 1),
2353 dyn->BaseRelocSize );
2354 break;
2356 ptr += sizeof(*dyn) + dyn->BaseRelocSize;
2358 break;
2359 case 2:
2360 while (ptr < end)
2362 const IMAGE_DYNAMIC_RELOCATION64_V2 *dyn = (const IMAGE_DYNAMIC_RELOCATION64_V2 *)ptr;
2363 if (dyn->Symbol == IMAGE_DYNAMIC_RELOCATION_ARM64X)
2365 apply_arm64x_relocations( base, (const IMAGE_BASE_RELOCATION *)(dyn + 1),
2366 dyn->FixupInfoSize );
2367 break;
2369 ptr += dyn->HeaderSize + dyn->FixupInfoSize;
2371 break;
2372 default:
2373 FIXME( "unsupported version %u\n", table->Version );
2374 break;
2378 #endif /* __aarch64__ */
2380 /***********************************************************************
2381 * map_image_into_view
2383 * Map an executable (PE format) image into an existing view.
2384 * virtual_mutex must be held by caller.
2386 static NTSTATUS map_image_into_view( struct file_view *view, const WCHAR *filename, int fd, void *orig_base,
2387 SIZE_T header_size, ULONG image_flags, int shared_fd, BOOL removable )
2389 IMAGE_DOS_HEADER *dos;
2390 IMAGE_NT_HEADERS *nt;
2391 IMAGE_SECTION_HEADER sections[96];
2392 IMAGE_SECTION_HEADER *sec;
2393 IMAGE_DATA_DIRECTORY *imports;
2394 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
2395 int i;
2396 off_t pos;
2397 struct stat st;
2398 char *header_end, *header_start;
2399 char *ptr = view->base;
2400 SIZE_T total_size = view->size;
2402 TRACE_(module)( "mapping PE file %s at %p-%p\n", debugstr_w(filename), ptr, ptr + total_size );
2404 /* map the header */
2406 fstat( fd, &st );
2407 header_size = min( header_size, st.st_size );
2408 if ((status = map_pe_header( view->base, header_size, fd, &removable ))) return status;
2410 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
2411 dos = (IMAGE_DOS_HEADER *)ptr;
2412 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
2413 header_end = ptr + ROUND_SIZE( 0, header_size );
2414 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
2415 if ((char *)(nt + 1) > header_end) return status;
2416 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
2417 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( sections )) return status;
2418 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) return status;
2419 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
2420 * copying the headers into local memory is necessary to properly load such applications. */
2421 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
2422 sec = sections;
2424 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
2425 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
2427 /* check for non page-aligned binary */
2429 if (image_flags & IMAGE_FLAGS_ImageMappedFlat)
2431 /* unaligned sections, this happens for native subsystem binaries */
2432 /* in that case Windows simply maps in the whole file */
2434 total_size = min( total_size, ROUND_SIZE( 0, st.st_size ));
2435 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
2436 removable ) != STATUS_SUCCESS) return status;
2438 /* check that all sections are loaded at the right offset */
2439 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) return status;
2440 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
2442 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
2443 return status; /* Windows refuses to load in that case too */
2446 /* set the image protections */
2447 set_vprot( view, ptr, total_size, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
2449 /* no relocations are performed on non page-aligned binaries */
2450 return STATUS_SUCCESS;
2454 /* map all the sections */
2456 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2458 static const SIZE_T sector_align = 0x1ff;
2459 SIZE_T map_size, file_start, file_size, end;
2461 if (!sec->Misc.VirtualSize)
2462 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
2463 else
2464 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
2466 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
2467 file_start = sec->PointerToRawData & ~sector_align;
2468 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
2469 if (file_size > map_size) file_size = map_size;
2471 /* a few sanity checks */
2472 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
2473 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
2475 WARN_(module)( "%s section %.8s too large (%x+%lx/%lx)\n",
2476 debugstr_w(filename), sec->Name, (int)sec->VirtualAddress, map_size, total_size );
2477 return status;
2480 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
2481 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
2483 TRACE_(module)( "%s mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
2484 debugstr_w(filename), sec->Name, ptr + sec->VirtualAddress,
2485 (int)sec->PointerToRawData, (int)pos, file_size, map_size,
2486 (int)sec->Characteristics );
2487 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
2488 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
2490 ERR_(module)( "Could not map %s shared section %.8s\n", debugstr_w(filename), sec->Name );
2491 return status;
2494 /* check if the import directory falls inside this section */
2495 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
2496 imports->VirtualAddress < sec->VirtualAddress + map_size)
2498 UINT_PTR base = imports->VirtualAddress & ~page_mask;
2499 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
2500 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
2501 if (end > base)
2502 map_file_into_view( view, shared_fd, base, end - base,
2503 pos + (base - sec->VirtualAddress),
2504 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
2506 pos += map_size;
2507 continue;
2510 TRACE_(module)( "mapping %s section %.8s at %p off %x size %x virt %x flags %x\n",
2511 debugstr_w(filename), sec->Name, ptr + sec->VirtualAddress,
2512 (int)sec->PointerToRawData, (int)sec->SizeOfRawData,
2513 (int)sec->Misc.VirtualSize, (int)sec->Characteristics );
2515 if (!sec->PointerToRawData || !file_size) continue;
2517 /* Note: if the section is not aligned properly map_file_into_view will magically
2518 * fall back to read(), so we don't need to check anything here.
2520 end = file_start + file_size;
2521 if (sec->PointerToRawData >= st.st_size ||
2522 end > ((st.st_size + sector_align) & ~sector_align) ||
2523 end < file_start ||
2524 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
2525 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
2526 removable ) != STATUS_SUCCESS)
2528 ERR_(module)( "Could not map %s section %.8s, file probably truncated\n",
2529 debugstr_w(filename), sec->Name );
2530 return status;
2533 if (file_size & page_mask)
2535 end = ROUND_SIZE( 0, file_size );
2536 if (end > map_size) end = map_size;
2537 TRACE_(module)("clearing %p - %p\n",
2538 ptr + sec->VirtualAddress + file_size,
2539 ptr + sec->VirtualAddress + end );
2540 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
2544 #ifdef __aarch64__
2545 if (main_image_info.Machine == IMAGE_FILE_MACHINE_AMD64 &&
2546 nt->FileHeader.Machine == IMAGE_FILE_MACHINE_ARM64)
2547 update_arm64x_mapping( ptr, nt, sections );
2548 #endif
2550 /* set the image protections */
2552 set_vprot( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
2554 sec = sections;
2555 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2557 SIZE_T size;
2558 BYTE vprot = VPROT_COMMITTED;
2560 if (sec->Misc.VirtualSize)
2561 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
2562 else
2563 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
2565 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
2566 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
2567 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
2569 if (!set_vprot( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
2570 ERR( "failed to set %08x protection on %s section %.8s, noexec filesystem?\n",
2571 (int)sec->Characteristics, debugstr_w(filename), sec->Name );
2574 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
2575 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, ptr - (char *)orig_base);
2576 #endif
2577 return STATUS_SUCCESS;
2581 /***********************************************************************
2582 * get_mapping_info
2584 static unsigned int get_mapping_info( HANDLE handle, ACCESS_MASK access, unsigned int *sec_flags,
2585 mem_size_t *full_size, HANDLE *shared_file, pe_image_info_t **info )
2587 pe_image_info_t *image_info;
2588 SIZE_T total, size = 1024;
2589 unsigned int status;
2591 for (;;)
2593 if (!(image_info = malloc( size ))) return STATUS_NO_MEMORY;
2595 SERVER_START_REQ( get_mapping_info )
2597 req->handle = wine_server_obj_handle( handle );
2598 req->access = access;
2599 wine_server_set_reply( req, image_info, size );
2600 status = wine_server_call( req );
2601 *sec_flags = reply->flags;
2602 *full_size = reply->size;
2603 total = reply->total;
2604 *shared_file = wine_server_ptr_handle( reply->shared_file );
2606 SERVER_END_REQ;
2607 if (!status && total <= size - sizeof(WCHAR)) break;
2608 free( image_info );
2609 if (status) return status;
2610 if (*shared_file) NtClose( *shared_file );
2611 size = total + sizeof(WCHAR);
2614 if (total)
2616 WCHAR *filename = (WCHAR *)(image_info + 1);
2618 assert( total >= sizeof(*image_info) );
2619 total -= sizeof(*image_info);
2620 filename[total / sizeof(WCHAR)] = 0;
2621 *info = image_info;
2623 else free( image_info );
2625 return STATUS_SUCCESS;
2629 /***********************************************************************
2630 * virtual_map_image
2632 * Map a PE image section into memory.
2634 static NTSTATUS virtual_map_image( HANDLE mapping, ACCESS_MASK access, void **addr_ptr, SIZE_T *size_ptr,
2635 ULONG_PTR limit, HANDLE shared_file, ULONG alloc_type,
2636 pe_image_info_t *image_info, WCHAR *filename, BOOL is_builtin )
2638 unsigned int vprot = SEC_IMAGE | SEC_FILE | VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY;
2639 int unix_fd = -1, needs_close;
2640 int shared_fd = -1, shared_needs_close = 0;
2641 SIZE_T size = image_info->map_size;
2642 struct file_view *view;
2643 unsigned int status;
2644 sigset_t sigset;
2645 void *base;
2647 if ((status = server_get_unix_fd( mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
2648 return status;
2650 if (shared_file && ((status = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2651 &shared_fd, &shared_needs_close, NULL, NULL ))))
2653 if (needs_close) close( unix_fd );
2654 return status;
2657 status = STATUS_INVALID_PARAMETER;
2658 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
2660 base = wine_server_get_ptr( image_info->base );
2661 if ((ULONG_PTR)base != image_info->base) base = NULL;
2663 if ((char *)base >= (char *)address_space_start) /* make sure the DOS area remains free */
2664 status = map_view( &view, base, size, alloc_type & MEM_TOP_DOWN, vprot, limit, 0 );
2666 if (status) status = map_view( &view, NULL, size, alloc_type & MEM_TOP_DOWN, vprot, limit, 0 );
2667 if (status) goto done;
2669 status = map_image_into_view( view, filename, unix_fd, base, image_info->header_size,
2670 image_info->image_flags, shared_fd, needs_close );
2671 if (status == STATUS_SUCCESS)
2673 SERVER_START_REQ( map_view )
2675 req->mapping = wine_server_obj_handle( mapping );
2676 req->access = access;
2677 req->base = wine_server_client_ptr( view->base );
2678 req->size = size;
2679 status = wine_server_call( req );
2681 SERVER_END_REQ;
2683 if (NT_SUCCESS(status))
2685 if (is_builtin) add_builtin_module( view->base, NULL );
2686 *addr_ptr = view->base;
2687 *size_ptr = size;
2688 VIRTUAL_DEBUG_DUMP_VIEW( view );
2690 else delete_view( view );
2692 done:
2693 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
2694 if (needs_close) close( unix_fd );
2695 if (shared_needs_close) close( shared_fd );
2696 return status;
2700 /***********************************************************************
2701 * virtual_map_section
2703 * Map a file section into memory.
2705 static unsigned int virtual_map_section( HANDLE handle, PVOID *addr_ptr, ULONG_PTR limit,
2706 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2707 ULONG alloc_type, ULONG protect )
2709 unsigned int res;
2710 mem_size_t full_size;
2711 ACCESS_MASK access;
2712 SIZE_T size;
2713 pe_image_info_t *image_info = NULL;
2714 WCHAR *filename;
2715 void *base;
2716 int unix_handle = -1, needs_close;
2717 unsigned int vprot, sec_flags;
2718 struct file_view *view;
2719 HANDLE shared_file;
2720 LARGE_INTEGER offset;
2721 sigset_t sigset;
2723 switch(protect)
2725 case PAGE_NOACCESS:
2726 case PAGE_READONLY:
2727 case PAGE_WRITECOPY:
2728 access = SECTION_MAP_READ;
2729 break;
2730 case PAGE_READWRITE:
2731 access = SECTION_MAP_WRITE;
2732 break;
2733 case PAGE_EXECUTE:
2734 case PAGE_EXECUTE_READ:
2735 case PAGE_EXECUTE_WRITECOPY:
2736 access = SECTION_MAP_READ | SECTION_MAP_EXECUTE;
2737 break;
2738 case PAGE_EXECUTE_READWRITE:
2739 access = SECTION_MAP_WRITE | SECTION_MAP_EXECUTE;
2740 break;
2741 default:
2742 return STATUS_INVALID_PAGE_PROTECTION;
2745 res = get_mapping_info( handle, access, &sec_flags, &full_size, &shared_file, &image_info );
2746 if (res) return res;
2748 if (image_info)
2750 filename = (WCHAR *)(image_info + 1);
2751 /* check if we can replace that mapping with the builtin */
2752 res = load_builtin( image_info, filename, addr_ptr, size_ptr, limit );
2753 if (res == STATUS_IMAGE_ALREADY_LOADED)
2754 res = virtual_map_image( handle, access, addr_ptr, size_ptr, limit, shared_file,
2755 alloc_type, image_info, filename, FALSE );
2756 if (shared_file) NtClose( shared_file );
2757 free( image_info );
2758 return res;
2761 base = *addr_ptr;
2762 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2763 if (offset.QuadPart >= full_size) return STATUS_INVALID_PARAMETER;
2764 if (*size_ptr)
2766 size = *size_ptr;
2767 if (size > full_size - offset.QuadPart) return STATUS_INVALID_VIEW_SIZE;
2769 else
2771 size = full_size - offset.QuadPart;
2772 if (size != full_size - offset.QuadPart) /* truncated */
2774 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2775 wine_dbgstr_longlong(full_size) );
2776 return STATUS_INVALID_PARAMETER;
2779 if (!(size = ROUND_SIZE( 0, size ))) return STATUS_INVALID_PARAMETER; /* wrap-around */
2781 get_vprot_flags( protect, &vprot, FALSE );
2782 vprot |= sec_flags;
2783 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2785 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) return res;
2787 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
2789 res = map_view( &view, base, size, alloc_type & MEM_TOP_DOWN, vprot, limit, 0 );
2790 if (res) goto done;
2792 TRACE( "handle=%p size=%lx offset=%s\n", handle, size, wine_dbgstr_longlong(offset.QuadPart) );
2793 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, needs_close );
2794 if (res == STATUS_SUCCESS)
2796 SERVER_START_REQ( map_view )
2798 req->mapping = wine_server_obj_handle( handle );
2799 req->access = access;
2800 req->base = wine_server_client_ptr( view->base );
2801 req->size = size;
2802 req->start = offset.QuadPart;
2803 res = wine_server_call( req );
2805 SERVER_END_REQ;
2807 else ERR( "mapping %p %lx %s failed\n", view->base, size, wine_dbgstr_longlong(offset.QuadPart) );
2809 if (NT_SUCCESS(res))
2811 *addr_ptr = view->base;
2812 *size_ptr = size;
2813 VIRTUAL_DEBUG_DUMP_VIEW( view );
2815 else delete_view( view );
2817 done:
2818 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
2819 if (needs_close) close( unix_handle );
2820 return res;
2824 struct alloc_virtual_heap
2826 void *base;
2827 size_t size;
2830 /* callback for mmap_enum_reserved_areas to allocate space for the virtual heap */
2831 static int alloc_virtual_heap( void *base, SIZE_T size, void *arg )
2833 struct alloc_virtual_heap *alloc = arg;
2834 void *end = (char *)base + size;
2836 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
2837 if (is_win64 && base < (void *)0x80000000) return 0;
2838 if (preload_reserve_end >= end)
2840 if (preload_reserve_start <= base) return 0; /* no space in that area */
2841 if (preload_reserve_start < end) end = preload_reserve_start;
2843 else if (preload_reserve_end > base)
2845 if (preload_reserve_start <= base) base = preload_reserve_end;
2846 else if ((char *)end - (char *)preload_reserve_end >= alloc->size) base = preload_reserve_end;
2847 else end = preload_reserve_start;
2849 if ((char *)end - (char *)base < alloc->size) return 0;
2850 alloc->base = anon_mmap_fixed( (char *)end - alloc->size, alloc->size, PROT_READ|PROT_WRITE, 0 );
2851 return (alloc->base != MAP_FAILED);
2854 /***********************************************************************
2855 * virtual_init
2857 void virtual_init(void)
2859 const struct preload_info **preload_info = dlsym( RTLD_DEFAULT, "wine_main_preload_info" );
2860 const char *preload = getenv( "WINEPRELOADRESERVE" );
2861 struct alloc_virtual_heap alloc_views;
2862 size_t size;
2863 int i;
2864 pthread_mutexattr_t attr;
2866 pthread_mutexattr_init( &attr );
2867 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
2868 pthread_mutex_init( &virtual_mutex, &attr );
2869 pthread_mutexattr_destroy( &attr );
2871 if (preload_info && *preload_info)
2872 for (i = 0; (*preload_info)[i].size; i++)
2873 mmap_add_reserved_area( (*preload_info)[i].addr, (*preload_info)[i].size );
2875 mmap_init( preload_info ? *preload_info : NULL );
2877 if ((preload = getenv("WINEPRELOADRESERVE")))
2879 unsigned long start, end;
2880 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
2882 preload_reserve_start = (void *)start;
2883 preload_reserve_end = (void *)end;
2884 /* some apps start inside the DOS area */
2885 if (preload_reserve_start)
2886 address_space_start = min( address_space_start, preload_reserve_start );
2890 /* try to find space in a reserved area for the views and pages protection table */
2891 #ifdef _WIN64
2892 pages_vprot_size = ((size_t)address_space_limit >> page_shift >> pages_vprot_shift) + 1;
2893 alloc_views.size = 2 * view_block_size + pages_vprot_size * sizeof(*pages_vprot);
2894 #else
2895 alloc_views.size = 2 * view_block_size + (1U << (32 - page_shift));
2896 #endif
2897 if (mmap_enum_reserved_areas( alloc_virtual_heap, &alloc_views, 1 ))
2898 mmap_remove_reserved_area( alloc_views.base, alloc_views.size );
2899 else
2900 alloc_views.base = anon_mmap_alloc( alloc_views.size, PROT_READ | PROT_WRITE );
2902 assert( alloc_views.base != MAP_FAILED );
2903 view_block_start = alloc_views.base;
2904 view_block_end = view_block_start + view_block_size / sizeof(*view_block_start);
2905 free_ranges = (void *)((char *)alloc_views.base + view_block_size);
2906 pages_vprot = (void *)((char *)alloc_views.base + 2 * view_block_size);
2907 wine_rb_init( &views_tree, compare_view );
2909 free_ranges[0].base = (void *)0;
2910 free_ranges[0].end = (void *)~0;
2911 free_ranges_end = free_ranges + 1;
2913 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
2914 size = (char *)address_space_start - (char *)0x10000;
2915 if (size && mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
2916 anon_mmap_fixed( (void *)0x10000, size, PROT_READ | PROT_WRITE, 0 );
2920 /***********************************************************************
2921 * get_system_affinity_mask
2923 ULONG_PTR get_system_affinity_mask(void)
2925 ULONG num_cpus = peb->NumberOfProcessors;
2926 if (num_cpus >= sizeof(ULONG_PTR) * 8) return ~(ULONG_PTR)0;
2927 return ((ULONG_PTR)1 << num_cpus) - 1;
2930 /***********************************************************************
2931 * virtual_get_system_info
2933 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info, BOOL wow64 )
2935 #if defined(HAVE_SYSINFO) \
2936 && defined(HAVE_STRUCT_SYSINFO_TOTALRAM) && defined(HAVE_STRUCT_SYSINFO_MEM_UNIT)
2937 struct sysinfo sinfo;
2939 if (!sysinfo(&sinfo))
2941 ULONG64 total = (ULONG64)sinfo.totalram * sinfo.mem_unit;
2942 info->MmHighestPhysicalPage = max(1, total / page_size);
2944 #elif defined(_SC_PHYS_PAGES)
2945 LONG64 phys_pages = sysconf( _SC_PHYS_PAGES );
2947 info->MmHighestPhysicalPage = max(1, phys_pages);
2948 #else
2949 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
2950 #endif
2952 info->unknown = 0;
2953 info->KeMaximumIncrement = 0; /* FIXME */
2954 info->PageSize = page_size;
2955 info->MmLowestPhysicalPage = 1;
2956 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
2957 info->AllocationGranularity = granularity_mask + 1;
2958 info->LowestUserAddress = (void *)0x10000;
2959 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
2960 info->NumberOfProcessors = peb->NumberOfProcessors;
2961 if (wow64) info->HighestUserAddress = (char *)get_wow_user_space_limit() - 1;
2962 else info->HighestUserAddress = (char *)user_space_limit - 1;
2966 /***********************************************************************
2967 * virtual_map_builtin_module
2969 NTSTATUS virtual_map_builtin_module( HANDLE mapping, void **module, SIZE_T *size, SECTION_IMAGE_INFORMATION *info,
2970 ULONG_PTR limit, WORD machine, BOOL prefer_native )
2972 mem_size_t full_size;
2973 unsigned int sec_flags;
2974 HANDLE shared_file;
2975 pe_image_info_t *image_info = NULL;
2976 ACCESS_MASK access = SECTION_MAP_READ | SECTION_MAP_EXECUTE;
2977 NTSTATUS status;
2978 WCHAR *filename;
2980 if ((status = get_mapping_info( mapping, access, &sec_flags, &full_size, &shared_file, &image_info )))
2981 return status;
2983 if (!image_info) return STATUS_INVALID_PARAMETER;
2985 *module = NULL;
2986 *size = 0;
2987 filename = (WCHAR *)(image_info + 1);
2989 if (!(image_info->image_flags & IMAGE_FLAGS_WineBuiltin)) /* ignore non-builtins */
2991 WARN( "%s found in WINEDLLPATH but not a builtin, ignoring\n", debugstr_w(filename) );
2992 status = STATUS_DLL_NOT_FOUND;
2994 else if (machine && image_info->machine != machine)
2996 TRACE( "%s is for arch %04x, continuing search\n", debugstr_w(filename), image_info->machine );
2997 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2999 else if (prefer_native && (image_info->dll_charact & IMAGE_DLLCHARACTERISTICS_PREFER_NATIVE))
3001 TRACE( "%s has prefer-native flag, ignoring builtin\n", debugstr_w(filename) );
3002 status = STATUS_IMAGE_ALREADY_LOADED;
3004 else
3006 status = virtual_map_image( mapping, SECTION_MAP_READ | SECTION_MAP_EXECUTE,
3007 module, size, limit, shared_file, 0, image_info, filename, TRUE );
3008 virtual_fill_image_information( image_info, info );
3011 if (shared_file) NtClose( shared_file );
3012 free( image_info );
3013 return status;
3017 /***********************************************************************
3018 * virtual_create_builtin_view
3020 NTSTATUS virtual_create_builtin_view( void *module, const UNICODE_STRING *nt_name,
3021 pe_image_info_t *info, void *so_handle )
3023 NTSTATUS status;
3024 sigset_t sigset;
3025 IMAGE_DOS_HEADER *dos = module;
3026 IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3027 SIZE_T size = info->map_size;
3028 IMAGE_SECTION_HEADER *sec;
3029 struct file_view *view;
3030 void *base = wine_server_get_ptr( info->base );
3031 int i;
3033 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3034 status = create_view( &view, base, size, SEC_IMAGE | SEC_FILE | VPROT_SYSTEM |
3035 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
3036 if (!status)
3038 TRACE( "created %p-%p for %s\n", base, (char *)base + size, debugstr_us(nt_name) );
3040 /* The PE header is always read-only, no write, no execute. */
3041 set_page_vprot( base, page_size, VPROT_COMMITTED | VPROT_READ );
3043 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
3044 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
3046 BYTE flags = VPROT_COMMITTED;
3048 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
3049 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
3050 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
3051 set_page_vprot( (char *)base + sec[i].VirtualAddress, sec[i].Misc.VirtualSize, flags );
3054 SERVER_START_REQ( map_view )
3056 req->base = wine_server_client_ptr( view->base );
3057 req->size = size;
3058 wine_server_add_data( req, info, sizeof(*info) );
3059 wine_server_add_data( req, nt_name->Buffer, nt_name->Length );
3060 status = wine_server_call( req );
3062 SERVER_END_REQ;
3064 if (status >= 0)
3066 add_builtin_module( view->base, so_handle );
3067 VIRTUAL_DEBUG_DUMP_VIEW( view );
3068 if (is_beyond_limit( base, size, working_set_limit )) working_set_limit = address_space_limit;
3070 else delete_view( view );
3072 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3074 return status;
3078 /* set some initial values in a new TEB */
3079 static TEB *init_teb( void *ptr, BOOL is_wow )
3081 struct ntdll_thread_data *thread_data;
3082 TEB *teb;
3083 TEB64 *teb64 = ptr;
3084 TEB32 *teb32 = (TEB32 *)((char *)ptr + teb_offset);
3086 #ifdef _WIN64
3087 teb = (TEB *)teb64;
3088 teb32->Peb = PtrToUlong( (char *)peb + page_size );
3089 teb32->Tib.Self = PtrToUlong( teb32 );
3090 teb32->Tib.ExceptionList = ~0u;
3091 teb32->ActivationContextStackPointer = PtrToUlong( &teb32->ActivationContextStack );
3092 teb32->ActivationContextStack.FrameListCache.Flink =
3093 teb32->ActivationContextStack.FrameListCache.Blink =
3094 PtrToUlong( &teb32->ActivationContextStack.FrameListCache );
3095 teb32->StaticUnicodeString.Buffer = PtrToUlong( teb32->StaticUnicodeBuffer );
3096 teb32->StaticUnicodeString.MaximumLength = sizeof( teb32->StaticUnicodeBuffer );
3097 teb32->GdiBatchCount = PtrToUlong( teb64 );
3098 teb32->WowTebOffset = -teb_offset;
3099 if (is_wow) teb64->WowTebOffset = teb_offset;
3100 #else
3101 teb = (TEB *)teb32;
3102 teb64->Peb = PtrToUlong( (char *)peb - page_size );
3103 teb64->Tib.Self = PtrToUlong( teb64 );
3104 teb64->Tib.ExceptionList = PtrToUlong( teb32 );
3105 teb64->ActivationContextStackPointer = PtrToUlong( &teb64->ActivationContextStack );
3106 teb64->ActivationContextStack.FrameListCache.Flink =
3107 teb64->ActivationContextStack.FrameListCache.Blink =
3108 PtrToUlong( &teb64->ActivationContextStack.FrameListCache );
3109 teb64->StaticUnicodeString.Buffer = PtrToUlong( teb64->StaticUnicodeBuffer );
3110 teb64->StaticUnicodeString.MaximumLength = sizeof( teb64->StaticUnicodeBuffer );
3111 teb64->WowTebOffset = teb_offset;
3112 if (is_wow)
3114 teb32->GdiBatchCount = PtrToUlong( teb64 );
3115 teb32->WowTebOffset = -teb_offset;
3117 #endif
3118 teb->Peb = peb;
3119 teb->Tib.Self = &teb->Tib;
3120 teb->Tib.ExceptionList = (void *)~0ul;
3121 teb->Tib.StackBase = (void *)~0ul;
3122 teb->ActivationContextStackPointer = &teb->ActivationContextStack;
3123 InitializeListHead( &teb->ActivationContextStack.FrameListCache );
3124 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
3125 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
3126 thread_data = (struct ntdll_thread_data *)&teb->GdiTebBatch;
3127 thread_data->request_fd = -1;
3128 thread_data->reply_fd = -1;
3129 thread_data->wait_fd[0] = -1;
3130 thread_data->wait_fd[1] = -1;
3131 list_add_head( &teb_list, &thread_data->entry );
3132 return teb;
3136 /***********************************************************************
3137 * virtual_alloc_first_teb
3139 TEB *virtual_alloc_first_teb(void)
3141 void *ptr;
3142 TEB *teb;
3143 unsigned int status;
3144 SIZE_T data_size = page_size;
3145 SIZE_T block_size = signal_stack_mask + 1;
3146 SIZE_T total = 32 * block_size;
3148 /* reserve space for shared user data */
3149 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&user_shared_data, 0, &data_size,
3150 MEM_RESERVE | MEM_COMMIT, PAGE_READONLY );
3151 if (status)
3153 ERR( "wine: failed to map the shared user data: %08x\n", status );
3154 exit(1);
3157 NtAllocateVirtualMemory( NtCurrentProcess(), &teb_block, is_win64 ? 0x7fffffff : 0, &total,
3158 MEM_RESERVE | MEM_TOP_DOWN, PAGE_READWRITE );
3159 teb_block_pos = 30;
3160 ptr = (char *)teb_block + 30 * block_size;
3161 data_size = 2 * block_size;
3162 NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&ptr, 0, &data_size, MEM_COMMIT, PAGE_READWRITE );
3163 peb = (PEB *)((char *)teb_block + 31 * block_size + (is_win64 ? 0 : page_size));
3164 teb = init_teb( ptr, FALSE );
3165 pthread_key_create( &teb_key, NULL );
3166 pthread_setspecific( teb_key, teb );
3167 return teb;
3171 /***********************************************************************
3172 * virtual_alloc_teb
3174 NTSTATUS virtual_alloc_teb( TEB **ret_teb )
3176 sigset_t sigset;
3177 TEB *teb;
3178 void *ptr = NULL;
3179 NTSTATUS status = STATUS_SUCCESS;
3180 SIZE_T block_size = signal_stack_mask + 1;
3182 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3183 if (next_free_teb)
3185 ptr = next_free_teb;
3186 next_free_teb = *(void **)ptr;
3187 memset( ptr, 0, teb_size );
3189 else
3191 if (!teb_block_pos)
3193 SIZE_T total = 32 * block_size;
3195 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, is_win64 && is_wow64() ? 0x7fffffff : 0,
3196 &total, MEM_RESERVE, PAGE_READWRITE )))
3198 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3199 return status;
3201 teb_block = ptr;
3202 teb_block_pos = 32;
3204 ptr = ((char *)teb_block + --teb_block_pos * block_size);
3205 NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&ptr, 0, &block_size,
3206 MEM_COMMIT, PAGE_READWRITE );
3208 *ret_teb = teb = init_teb( ptr, is_wow64() );
3209 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3211 if ((status = signal_alloc_thread( teb )))
3213 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3214 *(void **)ptr = next_free_teb;
3215 next_free_teb = ptr;
3216 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3218 return status;
3222 /***********************************************************************
3223 * virtual_free_teb
3225 void virtual_free_teb( TEB *teb )
3227 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)&teb->GdiTebBatch;
3228 void *ptr;
3229 SIZE_T size;
3230 sigset_t sigset;
3231 WOW_TEB *wow_teb = get_wow_teb( teb );
3233 signal_free_thread( teb );
3234 if (teb->DeallocationStack)
3236 size = 0;
3237 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
3239 if (thread_data->kernel_stack)
3241 size = 0;
3242 NtFreeVirtualMemory( GetCurrentProcess(), &thread_data->kernel_stack, &size, MEM_RELEASE );
3244 if (wow_teb && (ptr = ULongToPtr( wow_teb->DeallocationStack )))
3246 size = 0;
3247 NtFreeVirtualMemory( GetCurrentProcess(), &ptr, &size, MEM_RELEASE );
3250 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3251 list_remove( &thread_data->entry );
3252 ptr = teb;
3253 if (!is_win64) ptr = (char *)ptr - teb_offset;
3254 *(void **)ptr = next_free_teb;
3255 next_free_teb = ptr;
3256 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3260 /***********************************************************************
3261 * virtual_clear_tls_index
3263 NTSTATUS virtual_clear_tls_index( ULONG index )
3265 struct ntdll_thread_data *thread_data;
3266 sigset_t sigset;
3268 if (index < TLS_MINIMUM_AVAILABLE)
3270 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3271 LIST_FOR_EACH_ENTRY( thread_data, &teb_list, struct ntdll_thread_data, entry )
3273 TEB *teb = CONTAINING_RECORD( thread_data, TEB, GdiTebBatch );
3274 #ifdef _WIN64
3275 WOW_TEB *wow_teb = get_wow_teb( teb );
3276 if (wow_teb) wow_teb->TlsSlots[index] = 0;
3277 else
3278 #endif
3279 teb->TlsSlots[index] = 0;
3281 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3283 else
3285 index -= TLS_MINIMUM_AVAILABLE;
3286 if (index >= 8 * sizeof(peb->TlsExpansionBitmapBits)) return STATUS_INVALID_PARAMETER;
3288 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3289 LIST_FOR_EACH_ENTRY( thread_data, &teb_list, struct ntdll_thread_data, entry )
3291 TEB *teb = CONTAINING_RECORD( thread_data, TEB, GdiTebBatch );
3292 #ifdef _WIN64
3293 WOW_TEB *wow_teb = get_wow_teb( teb );
3294 if (wow_teb)
3296 if (wow_teb->TlsExpansionSlots)
3297 ((ULONG *)ULongToPtr( wow_teb->TlsExpansionSlots ))[index] = 0;
3299 else
3300 #endif
3301 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
3303 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3305 return STATUS_SUCCESS;
3309 /***********************************************************************
3310 * virtual_alloc_thread_stack
3312 NTSTATUS virtual_alloc_thread_stack( INITIAL_TEB *stack, ULONG_PTR limit, SIZE_T reserve_size,
3313 SIZE_T commit_size, BOOL guard_page )
3315 struct file_view *view;
3316 NTSTATUS status;
3317 sigset_t sigset;
3318 SIZE_T size;
3320 if (!reserve_size) reserve_size = main_image_info.MaximumStackSize;
3321 if (!commit_size) commit_size = main_image_info.CommittedStackSize;
3323 size = max( reserve_size, commit_size );
3324 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
3325 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
3327 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3329 status = map_view( &view, NULL, size, FALSE, VPROT_READ | VPROT_WRITE | VPROT_COMMITTED, limit, 0 );
3330 if (status != STATUS_SUCCESS) goto done;
3332 #ifdef VALGRIND_STACK_REGISTER
3333 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
3334 #endif
3336 /* setup no access guard page */
3337 if (guard_page)
3339 set_page_vprot( view->base, page_size, VPROT_COMMITTED );
3340 set_page_vprot( (char *)view->base + page_size, page_size,
3341 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
3342 mprotect_range( view->base, 2 * page_size , 0, 0 );
3344 VIRTUAL_DEBUG_DUMP_VIEW( view );
3346 /* note: limit is lower than base since the stack grows down */
3347 stack->OldStackBase = 0;
3348 stack->OldStackLimit = 0;
3349 stack->DeallocationStack = view->base;
3350 stack->StackBase = (char *)view->base + view->size;
3351 stack->StackLimit = (char *)view->base + (guard_page ? 2 * page_size : 0);
3352 done:
3353 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3354 return status;
3358 /***********************************************************************
3359 * virtual_alloc_arm64ec_map
3361 void *virtual_alloc_arm64ec_map(void)
3363 #ifdef __aarch64__
3364 SIZE_T size = ((ULONG_PTR)user_space_limit + page_size) >> (page_shift + 3); /* one bit per page */
3365 unsigned int status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&arm64ec_map, 0, &size,
3366 MEM_COMMIT, PAGE_READWRITE );
3367 if (status)
3369 ERR( "failed to allocate ARM64EC map: %08x\n", status );
3370 exit(1);
3372 #endif
3373 return arm64ec_map;
3377 /***********************************************************************
3378 * virtual_map_user_shared_data
3380 void virtual_map_user_shared_data(void)
3382 static const WCHAR nameW[] = {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
3383 '\\','_','_','w','i','n','e','_','u','s','e','r','_','s','h','a','r','e','d','_','d','a','t','a',0};
3384 UNICODE_STRING name_str = RTL_CONSTANT_STRING( nameW );
3385 OBJECT_ATTRIBUTES attr = { sizeof(attr), 0, &name_str };
3386 unsigned int status;
3387 HANDLE section;
3388 int res, fd, needs_close;
3390 if ((status = NtOpenSection( &section, SECTION_ALL_ACCESS, &attr )))
3392 ERR( "failed to open the USD section: %08x\n", status );
3393 exit(1);
3395 if ((res = server_get_unix_fd( section, 0, &fd, &needs_close, NULL, NULL )) ||
3396 (user_shared_data != mmap( user_shared_data, page_size, PROT_READ, MAP_SHARED|MAP_FIXED, fd, 0 )))
3398 ERR( "failed to remap the process USD: %d\n", res );
3399 exit(1);
3401 if (needs_close) close( fd );
3402 NtClose( section );
3406 struct thread_stack_info
3408 char *start;
3409 char *limit;
3410 char *end;
3411 SIZE_T guaranteed;
3412 BOOL is_wow;
3415 /***********************************************************************
3416 * is_inside_thread_stack
3418 static BOOL is_inside_thread_stack( void *ptr, struct thread_stack_info *stack )
3420 TEB *teb = NtCurrentTeb();
3421 WOW_TEB *wow_teb = get_wow_teb( teb );
3423 stack->start = teb->DeallocationStack;
3424 stack->limit = teb->Tib.StackLimit;
3425 stack->end = teb->Tib.StackBase;
3426 stack->guaranteed = max( teb->GuaranteedStackBytes, page_size * (is_win64 ? 2 : 1) );
3427 stack->is_wow = FALSE;
3428 if ((char *)ptr > stack->start && (char *)ptr <= stack->end) return TRUE;
3430 if (!wow_teb) return FALSE;
3431 stack->start = ULongToPtr( wow_teb->DeallocationStack );
3432 stack->limit = ULongToPtr( wow_teb->Tib.StackLimit );
3433 stack->end = ULongToPtr( wow_teb->Tib.StackBase );
3434 stack->guaranteed = max( wow_teb->GuaranteedStackBytes, page_size * (is_win64 ? 1 : 2) );
3435 stack->is_wow = TRUE;
3436 return ((char *)ptr > stack->start && (char *)ptr <= stack->end);
3440 /***********************************************************************
3441 * grow_thread_stack
3443 static NTSTATUS grow_thread_stack( char *page, struct thread_stack_info *stack_info )
3445 NTSTATUS ret = 0;
3447 set_page_vprot_bits( page, page_size, 0, VPROT_GUARD );
3448 mprotect_range( page, page_size, 0, 0 );
3449 if (page >= stack_info->start + page_size + stack_info->guaranteed)
3451 set_page_vprot_bits( page - page_size, page_size, VPROT_COMMITTED | VPROT_GUARD, 0 );
3452 mprotect_range( page - page_size, page_size, 0, 0 );
3454 else /* inside guaranteed space -> overflow exception */
3456 page = stack_info->start + page_size;
3457 set_page_vprot_bits( page, stack_info->guaranteed, VPROT_COMMITTED, VPROT_GUARD );
3458 mprotect_range( page, stack_info->guaranteed, 0, 0 );
3459 ret = STATUS_STACK_OVERFLOW;
3461 if (stack_info->is_wow)
3463 WOW_TEB *wow_teb = get_wow_teb( NtCurrentTeb() );
3464 wow_teb->Tib.StackLimit = PtrToUlong( page );
3466 else NtCurrentTeb()->Tib.StackLimit = page;
3467 return ret;
3471 /***********************************************************************
3472 * virtual_handle_fault
3474 NTSTATUS virtual_handle_fault( void *addr, DWORD err, void *stack )
3476 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
3477 char *page = ROUND_ADDR( addr, page_mask );
3478 BYTE vprot;
3480 mutex_lock( &virtual_mutex ); /* no need for signal masking inside signal handler */
3481 vprot = get_page_vprot( page );
3482 if (!is_inside_signal_stack( stack ) && (vprot & VPROT_GUARD))
3484 struct thread_stack_info stack_info;
3485 if (!is_inside_thread_stack( page, &stack_info ))
3487 set_page_vprot_bits( page, page_size, 0, VPROT_GUARD );
3488 mprotect_range( page, page_size, 0, 0 );
3489 ret = STATUS_GUARD_PAGE_VIOLATION;
3491 else ret = grow_thread_stack( page, &stack_info );
3493 else if (err & EXCEPTION_WRITE_FAULT)
3495 if (vprot & VPROT_WRITEWATCH)
3497 set_page_vprot_bits( page, page_size, 0, VPROT_WRITEWATCH );
3498 mprotect_range( page, page_size, 0, 0 );
3500 /* ignore fault if page is writable now */
3501 if (get_unix_prot( get_page_vprot( page )) & PROT_WRITE)
3503 if ((vprot & VPROT_WRITEWATCH) || is_write_watch_range( page, page_size ))
3504 ret = STATUS_SUCCESS;
3507 mutex_unlock( &virtual_mutex );
3508 return ret;
3512 /***********************************************************************
3513 * virtual_setup_exception
3515 void *virtual_setup_exception( void *stack_ptr, size_t size, EXCEPTION_RECORD *rec )
3517 char *stack = stack_ptr;
3518 struct thread_stack_info stack_info;
3520 if (!is_inside_thread_stack( stack, &stack_info ))
3522 if (is_inside_signal_stack( stack ))
3524 ERR( "nested exception on signal stack addr %p stack %p\n", rec->ExceptionAddress, stack );
3525 abort_thread(1);
3527 WARN( "exception outside of stack limits addr %p stack %p (%p-%p-%p)\n",
3528 rec->ExceptionAddress, stack, NtCurrentTeb()->DeallocationStack,
3529 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
3530 return stack - size;
3533 stack -= size;
3535 if (stack < stack_info.start + 4096)
3537 /* stack overflow on last page, unrecoverable */
3538 UINT diff = stack_info.start + 4096 - stack;
3539 ERR( "stack overflow %u bytes addr %p stack %p (%p-%p-%p)\n",
3540 diff, rec->ExceptionAddress, stack, stack_info.start, stack_info.limit, stack_info.end );
3541 abort_thread(1);
3543 else if (stack < stack_info.limit)
3545 mutex_lock( &virtual_mutex ); /* no need for signal masking inside signal handler */
3546 if ((get_page_vprot( stack ) & VPROT_GUARD) &&
3547 grow_thread_stack( ROUND_ADDR( stack, page_mask ), &stack_info ))
3549 rec->ExceptionCode = STATUS_STACK_OVERFLOW;
3550 rec->NumberParameters = 0;
3552 mutex_unlock( &virtual_mutex );
3554 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
3555 VALGRIND_MAKE_MEM_UNDEFINED( stack, size );
3556 #elif defined(VALGRIND_MAKE_WRITABLE)
3557 VALGRIND_MAKE_WRITABLE( stack, size );
3558 #endif
3559 return stack;
3563 /***********************************************************************
3564 * check_write_access
3566 * Check if the memory range is writable, temporarily disabling write watches if necessary.
3568 static NTSTATUS check_write_access( void *base, size_t size, BOOL *has_write_watch )
3570 size_t i;
3571 char *addr = ROUND_ADDR( base, page_mask );
3573 size = ROUND_SIZE( base, size );
3574 for (i = 0; i < size; i += page_size)
3576 BYTE vprot = get_page_vprot( addr + i );
3577 if (vprot & VPROT_WRITEWATCH) *has_write_watch = TRUE;
3578 if (!(get_unix_prot( vprot & ~VPROT_WRITEWATCH ) & PROT_WRITE))
3579 return STATUS_INVALID_USER_BUFFER;
3581 if (*has_write_watch)
3582 mprotect_range( addr, size, 0, VPROT_WRITEWATCH ); /* temporarily enable write access */
3583 return STATUS_SUCCESS;
3587 /***********************************************************************
3588 * virtual_locked_server_call
3590 unsigned int virtual_locked_server_call( void *req_ptr )
3592 struct __server_request_info * const req = req_ptr;
3593 sigset_t sigset;
3594 void *addr = req->reply_data;
3595 data_size_t size = req->u.req.request_header.reply_size;
3596 BOOL has_write_watch = FALSE;
3597 unsigned int ret = STATUS_ACCESS_VIOLATION;
3599 if (!size) return wine_server_call( req_ptr );
3601 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3602 if (!(ret = check_write_access( addr, size, &has_write_watch )))
3604 ret = server_call_unlocked( req );
3605 if (has_write_watch) update_write_watches( addr, size, wine_server_reply_size( req ));
3607 else memset( &req->u.reply, 0, sizeof(req->u.reply) );
3608 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3609 return ret;
3613 /***********************************************************************
3614 * virtual_locked_read
3616 ssize_t virtual_locked_read( int fd, void *addr, size_t size )
3618 sigset_t sigset;
3619 BOOL has_write_watch = FALSE;
3620 int err = EFAULT;
3622 ssize_t ret = read( fd, addr, size );
3623 if (ret != -1 || errno != EFAULT) return ret;
3625 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3626 if (!check_write_access( addr, size, &has_write_watch ))
3628 ret = read( fd, addr, size );
3629 err = errno;
3630 if (has_write_watch) update_write_watches( addr, size, max( 0, ret ));
3632 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3633 errno = err;
3634 return ret;
3638 /***********************************************************************
3639 * virtual_locked_pread
3641 ssize_t virtual_locked_pread( int fd, void *addr, size_t size, off_t offset )
3643 sigset_t sigset;
3644 BOOL has_write_watch = FALSE;
3645 int err = EFAULT;
3647 ssize_t ret = pread( fd, addr, size, offset );
3648 if (ret != -1 || errno != EFAULT) return ret;
3650 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3651 if (!check_write_access( addr, size, &has_write_watch ))
3653 ret = pread( fd, addr, size, offset );
3654 err = errno;
3655 if (has_write_watch) update_write_watches( addr, size, max( 0, ret ));
3657 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3658 errno = err;
3659 return ret;
3663 /***********************************************************************
3664 * virtual_locked_recvmsg
3666 ssize_t virtual_locked_recvmsg( int fd, struct msghdr *hdr, int flags )
3668 sigset_t sigset;
3669 size_t i;
3670 BOOL has_write_watch = FALSE;
3671 int err = EFAULT;
3673 ssize_t ret = recvmsg( fd, hdr, flags );
3674 if (ret != -1 || errno != EFAULT) return ret;
3676 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3677 for (i = 0; i < hdr->msg_iovlen; i++)
3678 if (check_write_access( hdr->msg_iov[i].iov_base, hdr->msg_iov[i].iov_len, &has_write_watch ))
3679 break;
3680 if (i == hdr->msg_iovlen)
3682 ret = recvmsg( fd, hdr, flags );
3683 err = errno;
3685 if (has_write_watch)
3686 while (i--) update_write_watches( hdr->msg_iov[i].iov_base, hdr->msg_iov[i].iov_len, 0 );
3688 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3689 errno = err;
3690 return ret;
3694 /***********************************************************************
3695 * virtual_is_valid_code_address
3697 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
3699 struct file_view *view;
3700 BOOL ret = FALSE;
3701 sigset_t sigset;
3703 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3704 if ((view = find_view( addr, size )))
3705 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
3706 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3707 return ret;
3711 /***********************************************************************
3712 * virtual_check_buffer_for_read
3714 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
3716 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
3718 if (!size) return TRUE;
3719 if (!ptr) return FALSE;
3721 __TRY
3723 volatile const char *p = ptr;
3724 char dummy __attribute__((unused));
3725 SIZE_T count = size;
3727 while (count > page_size)
3729 dummy = *p;
3730 p += page_size;
3731 count -= page_size;
3733 dummy = p[0];
3734 dummy = p[count - 1];
3736 __EXCEPT
3738 return FALSE;
3740 __ENDTRY
3741 return TRUE;
3745 /***********************************************************************
3746 * virtual_check_buffer_for_write
3748 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
3750 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
3752 if (!size) return TRUE;
3753 if (!ptr) return FALSE;
3755 __TRY
3757 volatile char *p = ptr;
3758 SIZE_T count = size;
3760 while (count > page_size)
3762 *p |= 0;
3763 p += page_size;
3764 count -= page_size;
3766 p[0] |= 0;
3767 p[count - 1] |= 0;
3769 __EXCEPT
3771 return FALSE;
3773 __ENDTRY
3774 return TRUE;
3778 /***********************************************************************
3779 * virtual_uninterrupted_read_memory
3781 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
3782 * permissions are checked before accessing each page, to ensure that no
3783 * exceptions can happen.
3785 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
3787 struct file_view *view;
3788 sigset_t sigset;
3789 SIZE_T bytes_read = 0;
3791 if (!size) return 0;
3793 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3794 if ((view = find_view( addr, size )))
3796 if (!(view->protect & VPROT_SYSTEM))
3798 while (bytes_read < size && (get_unix_prot( get_page_vprot( addr )) & PROT_READ))
3800 SIZE_T block_size = min( size - bytes_read, page_size - ((UINT_PTR)addr & page_mask) );
3801 memcpy( buffer, addr, block_size );
3803 addr = (const void *)((const char *)addr + block_size);
3804 buffer = (void *)((char *)buffer + block_size);
3805 bytes_read += block_size;
3809 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3810 return bytes_read;
3814 /***********************************************************************
3815 * virtual_uninterrupted_write_memory
3817 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
3818 * permissions are checked before accessing each page, to ensure that no
3819 * exceptions can happen.
3821 NTSTATUS virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
3823 BOOL has_write_watch = FALSE;
3824 sigset_t sigset;
3825 NTSTATUS ret;
3827 if (!size) return STATUS_SUCCESS;
3829 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3830 if (!(ret = check_write_access( addr, size, &has_write_watch )))
3832 memcpy( addr, buffer, size );
3833 if (has_write_watch) update_write_watches( addr, size, size );
3835 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3836 return ret;
3840 /***********************************************************************
3841 * virtual_set_force_exec
3843 * Whether to force exec prot on all views.
3845 void virtual_set_force_exec( BOOL enable )
3847 struct file_view *view;
3848 sigset_t sigset;
3850 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3851 if (!force_exec_prot != !enable) /* change all existing views */
3853 force_exec_prot = enable;
3855 WINE_RB_FOR_EACH_ENTRY( view, &views_tree, struct file_view, entry )
3857 /* file mappings are always accessible */
3858 BYTE commit = is_view_valloc( view ) ? 0 : VPROT_COMMITTED;
3860 mprotect_range( view->base, view->size, commit, 0 );
3863 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
3866 struct free_range
3868 char *base;
3869 char *limit;
3872 /* free reserved areas above the limit; callback for mmap_enum_reserved_areas */
3873 static int free_reserved_memory( void *base, SIZE_T size, void *arg )
3875 struct free_range *range = arg;
3877 if ((char *)base >= range->limit) return 0;
3878 if ((char *)base + size <= range->base) return 0;
3879 if ((char *)base < range->base)
3881 size -= range->base - (char *)base;
3882 base = range->base;
3884 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
3885 remove_reserved_area( base, size );
3886 return 1; /* stop enumeration since the list has changed */
3889 /***********************************************************************
3890 * virtual_release_address_space
3892 * Release some address space once we have loaded and initialized the app.
3894 static void virtual_release_address_space(void)
3896 struct free_range range;
3898 range.base = (char *)0x82000000;
3899 range.limit = get_wow_user_space_limit();
3901 if (range.limit > (char *)0xfffff000) return; /* 64-bit limit, nothing to do */
3903 if (range.limit > range.base)
3905 while (mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
3906 #ifdef __APPLE__
3907 /* On macOS, we still want to free some of low memory, for OpenGL resources */
3908 range.base = (char *)0x40000000;
3909 #else
3910 return;
3911 #endif
3913 else range.base = (char *)0x20000000;
3915 range.limit = (char *)0x7f000000;
3916 while (mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
3920 /***********************************************************************
3921 * virtual_set_large_address_space
3923 * Enable use of a large address space when allowed by the application.
3925 void virtual_set_large_address_space(void)
3927 /* no large address space on win9x */
3928 if (peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
3930 user_space_limit = working_set_limit = address_space_limit;
3934 /***********************************************************************
3935 * allocate_virtual_memory
3937 * NtAllocateVirtualMemory[Ex] implementation.
3939 static NTSTATUS allocate_virtual_memory( void **ret, SIZE_T *size_ptr, ULONG type, ULONG protect,
3940 ULONG_PTR limit, ULONG_PTR align, ULONG attributes )
3942 void *base;
3943 unsigned int vprot;
3944 BOOL is_dos_memory = FALSE;
3945 struct file_view *view;
3946 sigset_t sigset;
3947 SIZE_T size = *size_ptr;
3948 NTSTATUS status = STATUS_SUCCESS;
3950 /* Round parameters to a page boundary */
3952 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
3954 if (*ret)
3956 if (type & MEM_RESERVE) /* Round down to 64k boundary */
3957 base = ROUND_ADDR( *ret, granularity_mask );
3958 else
3959 base = ROUND_ADDR( *ret, page_mask );
3960 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
3962 /* disallow low 64k, wrap-around and kernel space */
3963 if (((char *)base < (char *)0x10000) ||
3964 ((char *)base + size < (char *)base) ||
3965 is_beyond_limit( base, size, address_space_limit ))
3967 /* address 1 is magic to mean DOS area */
3968 if (!base && *ret == (void *)1 && size == 0x110000) is_dos_memory = TRUE;
3969 else return STATUS_INVALID_PARAMETER;
3972 else
3974 base = NULL;
3975 size = (size + page_mask) & ~page_mask;
3978 /* Compute the alloc type flags */
3980 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
3981 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
3983 WARN("called with wrong alloc type flags (%08x) !\n", (int)type);
3984 return STATUS_INVALID_PARAMETER;
3987 if (!arm64ec_map && (attributes & MEM_EXTENDED_PARAMETER_EC_CODE)) return STATUS_INVALID_PARAMETER;
3989 /* Reserve the memory */
3991 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
3993 if ((type & MEM_RESERVE) || !base)
3995 if (!(status = get_vprot_flags( protect, &vprot, FALSE )))
3997 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
3998 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
3999 if (protect & PAGE_NOCACHE) vprot |= SEC_NOCACHE;
4001 if (vprot & VPROT_WRITECOPY) status = STATUS_INVALID_PAGE_PROTECTION;
4002 else if (is_dos_memory) status = allocate_dos_memory( &view, vprot );
4003 else status = map_view( &view, base, size, type & MEM_TOP_DOWN, vprot, limit,
4004 align ? align - 1 : granularity_mask );
4006 if (status == STATUS_SUCCESS) base = view->base;
4009 else if (type & MEM_RESET)
4011 if (!(view = find_view( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
4012 else madvise( base, size, MADV_DONTNEED );
4014 else /* commit the pages */
4016 if (!(view = find_view( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
4017 else if (view->protect & SEC_FILE) status = STATUS_ALREADY_COMMITTED;
4018 else if (!(status = set_protection( view, base, size, protect )) && (view->protect & SEC_RESERVE))
4020 SERVER_START_REQ( add_mapping_committed_range )
4022 req->base = wine_server_client_ptr( view->base );
4023 req->offset = (char *)base - (char *)view->base;
4024 req->size = size;
4025 wine_server_call( req );
4027 SERVER_END_REQ;
4031 if (!status && (attributes & MEM_EXTENDED_PARAMETER_EC_CODE)) set_arm64ec_range( base, size );
4033 if (!status) VIRTUAL_DEBUG_DUMP_VIEW( view );
4035 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
4037 if (status == STATUS_SUCCESS)
4039 *ret = base;
4040 *size_ptr = size;
4042 return status;
4046 /***********************************************************************
4047 * NtAllocateVirtualMemory (NTDLL.@)
4048 * ZwAllocateVirtualMemory (NTDLL.@)
4050 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG_PTR zero_bits,
4051 SIZE_T *size_ptr, ULONG type, ULONG protect )
4053 ULONG_PTR limit;
4055 TRACE("%p %p %08lx %x %08x\n", process, *ret, *size_ptr, (int)type, (int)protect );
4057 if (!*size_ptr) return STATUS_INVALID_PARAMETER;
4058 if (zero_bits > 21 && zero_bits < 32) return STATUS_INVALID_PARAMETER_3;
4059 if (zero_bits > 32 && zero_bits < granularity_mask) return STATUS_INVALID_PARAMETER_3;
4060 #ifndef _WIN64
4061 if (!is_old_wow64() && zero_bits >= 32) return STATUS_INVALID_PARAMETER_3;
4062 #endif
4064 if (process != NtCurrentProcess())
4066 apc_call_t call;
4067 apc_result_t result;
4068 unsigned int status;
4070 memset( &call, 0, sizeof(call) );
4072 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
4073 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
4074 call.virtual_alloc.size = *size_ptr;
4075 call.virtual_alloc.zero_bits = zero_bits;
4076 call.virtual_alloc.op_type = type;
4077 call.virtual_alloc.prot = protect;
4078 status = server_queue_process_apc( process, &call, &result );
4079 if (status != STATUS_SUCCESS) return status;
4081 if (result.virtual_alloc.status == STATUS_SUCCESS)
4083 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
4084 *size_ptr = result.virtual_alloc.size;
4086 return result.virtual_alloc.status;
4089 if (!*ret)
4090 limit = get_zero_bits_limit( zero_bits );
4091 else
4092 limit = 0;
4094 return allocate_virtual_memory( ret, size_ptr, type, protect, limit, 0, 0 );
4098 static NTSTATUS get_extended_params( const MEM_EXTENDED_PARAMETER *parameters, ULONG count,
4099 ULONG_PTR *limit, ULONG_PTR *align, ULONG *attributes )
4101 MEM_ADDRESS_REQUIREMENTS *r = NULL;
4102 ULONG i;
4104 if (count && !parameters) return STATUS_INVALID_PARAMETER;
4106 for (i = 0; i < count; ++i)
4108 switch (parameters[i].Type)
4110 case MemExtendedParameterAddressRequirements:
4111 if (r) return STATUS_INVALID_PARAMETER;
4112 r = parameters[i].Pointer;
4114 if (r->LowestStartingAddress)
4115 FIXME( "Not supported requirements LowestStartingAddress %p, Alignment %p.\n",
4116 r->LowestStartingAddress, (void *)r->Alignment );
4118 if (r->Alignment)
4120 if ((r->Alignment & (r->Alignment - 1)) || r->Alignment - 1 < granularity_mask)
4122 WARN( "Invalid alignment %lu.\n", r->Alignment );
4123 return STATUS_INVALID_PARAMETER;
4125 *align = r->Alignment;
4127 if (r->HighestEndingAddress)
4129 *limit = (ULONG_PTR)r->HighestEndingAddress;
4130 if (*limit > (ULONG_PTR)user_space_limit || ((*limit + 1) & (page_mask - 1)))
4132 WARN( "Invalid limit %p.\n", r->HighestEndingAddress );
4133 return STATUS_INVALID_PARAMETER;
4136 break;
4138 case MemExtendedParameterAttributeFlags:
4139 *attributes = parameters[i].ULong;
4140 break;
4142 case MemExtendedParameterNumaNode:
4143 case MemExtendedParameterPartitionHandle:
4144 case MemExtendedParameterUserPhysicalHandle:
4145 case MemExtendedParameterImageMachine:
4146 FIXME( "Parameter type %d is not supported.\n", parameters[i].Type );
4147 break;
4149 default:
4150 WARN( "Invalid parameter type %u\n", parameters[i].Type );
4151 return STATUS_INVALID_PARAMETER;
4154 return STATUS_SUCCESS;
4158 /***********************************************************************
4159 * NtAllocateVirtualMemoryEx (NTDLL.@)
4160 * ZwAllocateVirtualMemoryEx (NTDLL.@)
4162 NTSTATUS WINAPI NtAllocateVirtualMemoryEx( HANDLE process, PVOID *ret, SIZE_T *size_ptr, ULONG type,
4163 ULONG protect, MEM_EXTENDED_PARAMETER *parameters,
4164 ULONG count )
4166 ULONG_PTR limit = 0;
4167 ULONG_PTR align = 0;
4168 ULONG attributes = 0;
4169 unsigned int status;
4171 TRACE( "%p %p %08lx %x %08x %p %u\n",
4172 process, *ret, *size_ptr, (int)type, (int)protect, parameters, (int)count );
4174 status = get_extended_params( parameters, count, &limit, &align, &attributes );
4175 if (status) return status;
4177 if (*ret && (align || limit)) return STATUS_INVALID_PARAMETER;
4178 if (!*size_ptr) return STATUS_INVALID_PARAMETER;
4180 if (process != NtCurrentProcess())
4182 apc_call_t call;
4183 apc_result_t result;
4185 memset( &call, 0, sizeof(call) );
4187 call.virtual_alloc_ex.type = APC_VIRTUAL_ALLOC_EX;
4188 call.virtual_alloc_ex.addr = wine_server_client_ptr( *ret );
4189 call.virtual_alloc_ex.size = *size_ptr;
4190 call.virtual_alloc_ex.limit = limit;
4191 call.virtual_alloc_ex.align = align;
4192 call.virtual_alloc_ex.op_type = type;
4193 call.virtual_alloc_ex.prot = protect;
4194 call.virtual_alloc_ex.attributes = attributes;
4195 status = server_queue_process_apc( process, &call, &result );
4196 if (status != STATUS_SUCCESS) return status;
4198 if (result.virtual_alloc_ex.status == STATUS_SUCCESS)
4200 *ret = wine_server_get_ptr( result.virtual_alloc_ex.addr );
4201 *size_ptr = result.virtual_alloc_ex.size;
4203 return result.virtual_alloc_ex.status;
4206 return allocate_virtual_memory( ret, size_ptr, type, protect, limit, align, attributes );
4210 /***********************************************************************
4211 * NtFreeVirtualMemory (NTDLL.@)
4212 * ZwFreeVirtualMemory (NTDLL.@)
4214 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
4216 struct file_view *view;
4217 char *base;
4218 sigset_t sigset;
4219 unsigned int status = STATUS_SUCCESS;
4220 LPVOID addr = *addr_ptr;
4221 SIZE_T size = *size_ptr;
4223 TRACE("%p %p %08lx %x\n", process, addr, size, (int)type );
4225 if (process != NtCurrentProcess())
4227 apc_call_t call;
4228 apc_result_t result;
4230 memset( &call, 0, sizeof(call) );
4232 call.virtual_free.type = APC_VIRTUAL_FREE;
4233 call.virtual_free.addr = wine_server_client_ptr( addr );
4234 call.virtual_free.size = size;
4235 call.virtual_free.op_type = type;
4236 status = server_queue_process_apc( process, &call, &result );
4237 if (status != STATUS_SUCCESS) return status;
4239 if (result.virtual_free.status == STATUS_SUCCESS)
4241 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
4242 *size_ptr = result.virtual_free.size;
4244 return result.virtual_free.status;
4247 /* Fix the parameters */
4249 if (size) size = ROUND_SIZE( addr, size );
4250 base = ROUND_ADDR( addr, page_mask );
4252 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
4254 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
4255 if (!base)
4257 /* address 1 is magic to mean release reserved space */
4258 if (addr == (void *)1 && !size && type == MEM_RELEASE) virtual_release_address_space();
4259 else status = STATUS_INVALID_PARAMETER;
4261 else if (!(view = find_view( base, 0 ))) status = STATUS_MEMORY_NOT_ALLOCATED;
4262 else if (!is_view_valloc( view )) status = STATUS_INVALID_PARAMETER;
4263 else if (type == MEM_RELEASE)
4265 /* Free the pages */
4267 if (size && (char *)view->base + view->size - base < size) status = STATUS_UNABLE_TO_FREE_VM;
4268 else if (!size && base != view->base) status = STATUS_FREE_VM_NOT_AT_BASE;
4269 else
4271 if (!size) size = view->size;
4273 if (size == view->size)
4275 assert( base == view->base );
4276 delete_view( view );
4278 else
4280 struct file_view *new_view = NULL;
4282 if (view->base != base && base + size != (char *)view->base + view->size
4283 && !(new_view = alloc_view()))
4285 ERR( "out of memory for %p-%p\n", base, (char *)base + size );
4286 return STATUS_NO_MEMORY;
4288 unregister_view( view );
4290 if (new_view)
4292 new_view->base = base + size;
4293 new_view->size = (char *)view->base + view->size - (char *)new_view->base;
4294 new_view->protect = view->protect;
4296 view->size = base - (char *)view->base;
4297 register_view( view );
4298 register_view( new_view );
4300 VIRTUAL_DEBUG_DUMP_VIEW( view );
4301 VIRTUAL_DEBUG_DUMP_VIEW( new_view );
4303 else
4305 if (view->base == base)
4307 view->base = base + size;
4308 view->size -= size;
4310 else
4312 view->size = base - (char *)view->base;
4314 register_view( view );
4315 VIRTUAL_DEBUG_DUMP_VIEW( view );
4318 set_page_vprot( base, size, 0 );
4319 unmap_area( base, size );
4321 *addr_ptr = base;
4322 *size_ptr = size;
4325 else if (type == MEM_DECOMMIT)
4327 if (!size && base != view->base) status = STATUS_FREE_VM_NOT_AT_BASE;
4328 else if (base - (char *)view->base + size > view->size) status = STATUS_UNABLE_TO_FREE_VM;
4329 else status = decommit_pages( view, base - (char *)view->base, size );
4330 if (status == STATUS_SUCCESS)
4332 *addr_ptr = base;
4333 *size_ptr = size;
4336 else
4338 WARN("called with wrong free type flags (%08x) !\n", (int)type);
4339 status = STATUS_INVALID_PARAMETER;
4342 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
4343 return status;
4347 /***********************************************************************
4348 * NtProtectVirtualMemory (NTDLL.@)
4349 * ZwProtectVirtualMemory (NTDLL.@)
4351 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
4352 ULONG new_prot, ULONG *old_prot )
4354 struct file_view *view;
4355 sigset_t sigset;
4356 unsigned int status = STATUS_SUCCESS;
4357 char *base;
4358 BYTE vprot;
4359 SIZE_T size = *size_ptr;
4360 LPVOID addr = *addr_ptr;
4361 DWORD old;
4363 TRACE("%p %p %08lx %08x\n", process, addr, size, (int)new_prot );
4365 if (!old_prot)
4366 return STATUS_ACCESS_VIOLATION;
4368 if (process != NtCurrentProcess())
4370 apc_call_t call;
4371 apc_result_t result;
4373 memset( &call, 0, sizeof(call) );
4375 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
4376 call.virtual_protect.addr = wine_server_client_ptr( addr );
4377 call.virtual_protect.size = size;
4378 call.virtual_protect.prot = new_prot;
4379 status = server_queue_process_apc( process, &call, &result );
4380 if (status != STATUS_SUCCESS) return status;
4382 if (result.virtual_protect.status == STATUS_SUCCESS)
4384 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
4385 *size_ptr = result.virtual_protect.size;
4386 *old_prot = result.virtual_protect.prot;
4388 return result.virtual_protect.status;
4391 /* Fix the parameters */
4393 size = ROUND_SIZE( addr, size );
4394 base = ROUND_ADDR( addr, page_mask );
4396 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
4398 if ((view = find_view( base, size )))
4400 /* Make sure all the pages are committed */
4401 if (get_committed_size( view, base, &vprot, VPROT_COMMITTED ) >= size && (vprot & VPROT_COMMITTED))
4403 old = get_win32_prot( vprot, view->protect );
4404 status = set_protection( view, base, size, new_prot );
4406 else status = STATUS_NOT_COMMITTED;
4408 else status = STATUS_INVALID_PARAMETER;
4410 if (!status) VIRTUAL_DEBUG_DUMP_VIEW( view );
4412 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
4414 if (status == STATUS_SUCCESS)
4416 *addr_ptr = base;
4417 *size_ptr = size;
4418 *old_prot = old;
4420 return status;
4424 /* retrieve state for a free memory area; callback for mmap_enum_reserved_areas */
4425 static int get_free_mem_state_callback( void *start, SIZE_T size, void *arg )
4427 MEMORY_BASIC_INFORMATION *info = arg;
4428 void *end = (char *)start + size;
4430 if ((char *)info->BaseAddress + info->RegionSize <= (char *)start) return 0;
4432 if (info->BaseAddress >= end)
4434 if (info->AllocationBase < end) info->AllocationBase = end;
4435 return 0;
4438 if (info->BaseAddress >= start || start <= address_space_start)
4440 /* it's a real free area */
4441 info->State = MEM_FREE;
4442 info->Protect = PAGE_NOACCESS;
4443 info->AllocationBase = 0;
4444 info->AllocationProtect = 0;
4445 info->Type = 0;
4446 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
4447 info->RegionSize = (char *)end - (char *)info->BaseAddress;
4449 else /* outside of the reserved area, pretend it's allocated */
4451 info->RegionSize = (char *)start - (char *)info->BaseAddress;
4452 #ifdef __i386__
4453 info->State = MEM_RESERVE;
4454 info->Protect = PAGE_NOACCESS;
4455 info->AllocationProtect = PAGE_NOACCESS;
4456 info->Type = MEM_PRIVATE;
4457 #else
4458 info->State = MEM_FREE;
4459 info->Protect = PAGE_NOACCESS;
4460 info->AllocationBase = 0;
4461 info->AllocationProtect = 0;
4462 info->Type = 0;
4463 #endif
4465 return 1;
4468 static unsigned int fill_basic_memory_info( const void *addr, MEMORY_BASIC_INFORMATION *info )
4470 char *base, *alloc_base = 0, *alloc_end = working_set_limit;
4471 struct wine_rb_entry *ptr;
4472 struct file_view *view;
4473 sigset_t sigset;
4475 base = ROUND_ADDR( addr, page_mask );
4477 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_INVALID_PARAMETER;
4479 /* Find the view containing the address */
4481 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
4482 ptr = views_tree.root;
4483 while (ptr)
4485 view = WINE_RB_ENTRY_VALUE( ptr, struct file_view, entry );
4486 if ((char *)view->base > base)
4488 alloc_end = view->base;
4489 ptr = ptr->left;
4491 else if ((char *)view->base + view->size <= base)
4493 alloc_base = (char *)view->base + view->size;
4494 ptr = ptr->right;
4496 else
4498 alloc_base = view->base;
4499 alloc_end = (char *)view->base + view->size;
4500 break;
4504 /* Fill the info structure */
4506 info->AllocationBase = alloc_base;
4507 info->BaseAddress = base;
4508 info->RegionSize = alloc_end - base;
4510 if (!ptr)
4512 if (!mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
4514 /* not in a reserved area at all, pretend it's allocated */
4515 #ifdef __i386__
4516 if (base >= (char *)address_space_start)
4518 info->State = MEM_RESERVE;
4519 info->Protect = PAGE_NOACCESS;
4520 info->AllocationProtect = PAGE_NOACCESS;
4521 info->Type = MEM_PRIVATE;
4523 else
4524 #endif
4526 info->State = MEM_FREE;
4527 info->Protect = PAGE_NOACCESS;
4528 info->AllocationBase = 0;
4529 info->AllocationProtect = 0;
4530 info->Type = 0;
4534 else
4536 BYTE vprot;
4538 info->RegionSize = get_committed_size( view, base, &vprot, ~VPROT_WRITEWATCH );
4539 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
4540 info->Protect = (vprot & VPROT_COMMITTED) ? get_win32_prot( vprot, view->protect ) : 0;
4541 info->AllocationProtect = get_win32_prot( view->protect, view->protect );
4542 if (view->protect & SEC_IMAGE) info->Type = MEM_IMAGE;
4543 else if (view->protect & (SEC_FILE | SEC_RESERVE | SEC_COMMIT)) info->Type = MEM_MAPPED;
4544 else info->Type = MEM_PRIVATE;
4546 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
4548 return STATUS_SUCCESS;
4551 /* get basic information about a memory block */
4552 static unsigned int get_basic_memory_info( HANDLE process, LPCVOID addr,
4553 MEMORY_BASIC_INFORMATION *info,
4554 SIZE_T len, SIZE_T *res_len )
4556 unsigned int status;
4558 if (len < sizeof(*info))
4559 return STATUS_INFO_LENGTH_MISMATCH;
4561 if (process != NtCurrentProcess())
4563 apc_call_t call;
4564 apc_result_t result;
4566 memset( &call, 0, sizeof(call) );
4568 call.virtual_query.type = APC_VIRTUAL_QUERY;
4569 call.virtual_query.addr = wine_server_client_ptr( addr );
4570 status = server_queue_process_apc( process, &call, &result );
4571 if (status != STATUS_SUCCESS) return status;
4573 if (result.virtual_query.status == STATUS_SUCCESS)
4575 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
4576 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
4577 info->RegionSize = result.virtual_query.size;
4578 info->Protect = result.virtual_query.prot;
4579 info->AllocationProtect = result.virtual_query.alloc_prot;
4580 info->State = (DWORD)result.virtual_query.state << 12;
4581 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
4582 if (info->RegionSize != result.virtual_query.size) /* truncated */
4583 return STATUS_INVALID_PARAMETER; /* FIXME */
4584 if (res_len) *res_len = sizeof(*info);
4586 return result.virtual_query.status;
4589 if ((status = fill_basic_memory_info( addr, info ))) return status;
4591 if (res_len) *res_len = sizeof(*info);
4592 return STATUS_SUCCESS;
4595 static unsigned int get_memory_region_info( HANDLE process, LPCVOID addr, MEMORY_REGION_INFORMATION *info,
4596 SIZE_T len, SIZE_T *res_len )
4598 MEMORY_BASIC_INFORMATION basic_info;
4599 unsigned int status;
4601 if (len < FIELD_OFFSET(MEMORY_REGION_INFORMATION, CommitSize))
4602 return STATUS_INFO_LENGTH_MISMATCH;
4604 if (process != NtCurrentProcess())
4606 FIXME("Unimplemented for other processes.\n");
4607 return STATUS_NOT_IMPLEMENTED;
4610 if ((status = fill_basic_memory_info( addr, &basic_info ))) return status;
4612 info->AllocationBase = basic_info.AllocationBase;
4613 info->AllocationProtect = basic_info.AllocationProtect;
4614 info->RegionType = 0; /* FIXME */
4615 if (len >= FIELD_OFFSET(MEMORY_REGION_INFORMATION, CommitSize))
4616 info->RegionSize = basic_info.RegionSize;
4617 if (len >= FIELD_OFFSET(MEMORY_REGION_INFORMATION, PartitionId))
4618 info->CommitSize = basic_info.State == MEM_COMMIT ? basic_info.RegionSize : 0;
4620 if (res_len) *res_len = sizeof(*info);
4621 return STATUS_SUCCESS;
4624 static NTSTATUS get_working_set_ex( HANDLE process, LPCVOID addr,
4625 MEMORY_WORKING_SET_EX_INFORMATION *info,
4626 SIZE_T len, SIZE_T *res_len )
4628 #if !defined(HAVE_LIBPROCSTAT)
4629 static int pagemap_fd = -2;
4630 #endif
4631 MEMORY_WORKING_SET_EX_INFORMATION *p;
4632 sigset_t sigset;
4634 if (process != NtCurrentProcess())
4636 FIXME( "(process=%p,addr=%p) Unimplemented information class: MemoryWorkingSetExInformation\n", process, addr );
4637 return STATUS_INVALID_INFO_CLASS;
4640 #if defined(HAVE_LIBPROCSTAT)
4642 struct procstat *pstat;
4643 unsigned int proc_count;
4644 struct kinfo_proc *kip = NULL;
4645 unsigned int vmentry_count = 0;
4646 struct kinfo_vmentry *vmentries = NULL;
4648 pstat = procstat_open_sysctl();
4649 if (pstat)
4650 kip = procstat_getprocs( pstat, KERN_PROC_PID, getpid(), &proc_count );
4651 if (kip)
4652 vmentries = procstat_getvmmap( pstat, kip, &vmentry_count );
4653 if (vmentries == NULL)
4654 WARN( "couldn't get process vmmap, errno %d\n", errno );
4656 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
4657 for (p = info; (UINT_PTR)(p + 1) <= (UINT_PTR)info + len; p++)
4659 int i;
4660 struct kinfo_vmentry *entry = NULL;
4661 BYTE vprot;
4662 struct file_view *view;
4664 memset( &p->VirtualAttributes, 0, sizeof(p->VirtualAttributes) );
4665 if ((view = find_view( p->VirtualAddress, 0 )) &&
4666 get_committed_size( view, p->VirtualAddress, &vprot, VPROT_COMMITTED ) &&
4667 (vprot & VPROT_COMMITTED))
4669 for (i = 0; i < vmentry_count && entry == NULL; i++)
4671 if (vmentries[i].kve_start <= (ULONG_PTR)p->VirtualAddress && (ULONG_PTR)p->VirtualAddress <= vmentries[i].kve_end)
4672 entry = &vmentries[i];
4675 p->VirtualAttributes.Valid = !(vprot & VPROT_GUARD) && (vprot & 0x0f) && entry && entry->kve_type != KVME_TYPE_SWAP;
4676 p->VirtualAttributes.Shared = !is_view_valloc( view );
4677 if (p->VirtualAttributes.Shared && p->VirtualAttributes.Valid)
4678 p->VirtualAttributes.ShareCount = 1; /* FIXME */
4679 if (p->VirtualAttributes.Valid)
4680 p->VirtualAttributes.Win32Protection = get_win32_prot( vprot, view->protect );
4683 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
4685 if (vmentries)
4686 procstat_freevmmap( pstat, vmentries );
4687 if (kip)
4688 procstat_freeprocs( pstat, kip );
4689 if (pstat)
4690 procstat_close( pstat );
4692 #else
4693 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
4694 if (pagemap_fd == -2)
4696 #ifdef O_CLOEXEC
4697 if ((pagemap_fd = open( "/proc/self/pagemap", O_RDONLY | O_CLOEXEC, 0 )) == -1 && errno == EINVAL)
4698 #endif
4699 pagemap_fd = open( "/proc/self/pagemap", O_RDONLY, 0 );
4701 if (pagemap_fd == -1) WARN( "unable to open /proc/self/pagemap\n" );
4702 else fcntl(pagemap_fd, F_SETFD, FD_CLOEXEC); /* in case O_CLOEXEC isn't supported */
4705 for (p = info; (UINT_PTR)(p + 1) <= (UINT_PTR)info + len; p++)
4707 BYTE vprot;
4708 UINT64 pagemap;
4709 struct file_view *view;
4711 memset( &p->VirtualAttributes, 0, sizeof(p->VirtualAttributes) );
4713 if ((view = find_view( p->VirtualAddress, 0 )) &&
4714 get_committed_size( view, p->VirtualAddress, &vprot, VPROT_COMMITTED ) &&
4715 (vprot & VPROT_COMMITTED))
4717 if (pagemap_fd == -1 ||
4718 pread( pagemap_fd, &pagemap, sizeof(pagemap), ((UINT_PTR)p->VirtualAddress >> page_shift) * sizeof(pagemap) ) != sizeof(pagemap))
4720 /* If we don't have pagemap information, default to invalid. */
4721 pagemap = 0;
4724 p->VirtualAttributes.Valid = !(vprot & VPROT_GUARD) && (vprot & 0x0f) && (pagemap >> 63);
4725 p->VirtualAttributes.Shared = !is_view_valloc( view ) && ((pagemap >> 61) & 1);
4726 if (p->VirtualAttributes.Shared && p->VirtualAttributes.Valid)
4727 p->VirtualAttributes.ShareCount = 1; /* FIXME */
4728 if (p->VirtualAttributes.Valid)
4729 p->VirtualAttributes.Win32Protection = get_win32_prot( vprot, view->protect );
4732 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
4733 #endif
4735 if (res_len)
4736 *res_len = (UINT_PTR)p - (UINT_PTR)info;
4737 return STATUS_SUCCESS;
4740 static unsigned int get_memory_section_name( HANDLE process, LPCVOID addr,
4741 MEMORY_SECTION_NAME *info, SIZE_T len, SIZE_T *ret_len )
4743 unsigned int status;
4745 if (!info) return STATUS_ACCESS_VIOLATION;
4747 SERVER_START_REQ( get_mapping_filename )
4749 req->process = wine_server_obj_handle( process );
4750 req->addr = wine_server_client_ptr( addr );
4751 if (len > sizeof(*info) + sizeof(WCHAR))
4752 wine_server_set_reply( req, info + 1, len - sizeof(*info) - sizeof(WCHAR) );
4753 status = wine_server_call( req );
4754 if (!status || status == STATUS_BUFFER_OVERFLOW)
4756 if (ret_len) *ret_len = sizeof(*info) + reply->len + sizeof(WCHAR);
4757 if (len < sizeof(*info)) status = STATUS_INFO_LENGTH_MISMATCH;
4758 if (!status)
4760 info->SectionFileName.Buffer = (WCHAR *)(info + 1);
4761 info->SectionFileName.Length = reply->len;
4762 info->SectionFileName.MaximumLength = reply->len + sizeof(WCHAR);
4763 info->SectionFileName.Buffer[reply->len / sizeof(WCHAR)] = 0;
4767 SERVER_END_REQ;
4768 return status;
4772 /***********************************************************************
4773 * NtQueryVirtualMemory (NTDLL.@)
4774 * ZwQueryVirtualMemory (NTDLL.@)
4776 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
4777 MEMORY_INFORMATION_CLASS info_class,
4778 PVOID buffer, SIZE_T len, SIZE_T *res_len )
4780 NTSTATUS status;
4782 TRACE("(%p, %p, info_class=%d, %p, %ld, %p)\n",
4783 process, addr, info_class, buffer, len, res_len);
4785 switch(info_class)
4787 case MemoryBasicInformation:
4788 return get_basic_memory_info( process, addr, buffer, len, res_len );
4790 case MemoryWorkingSetExInformation:
4791 return get_working_set_ex( process, addr, buffer, len, res_len );
4793 case MemoryMappedFilenameInformation:
4794 return get_memory_section_name( process, addr, buffer, len, res_len );
4796 case MemoryRegionInformation:
4797 return get_memory_region_info( process, addr, buffer, len, res_len );
4799 case MemoryWineUnixFuncs:
4800 case MemoryWineUnixWow64Funcs:
4801 if (len != sizeof(unixlib_handle_t)) return STATUS_INFO_LENGTH_MISMATCH;
4802 if (process == GetCurrentProcess())
4804 void *module = (void *)addr;
4805 const void *funcs = NULL;
4807 status = get_builtin_unix_funcs( module, info_class == MemoryWineUnixWow64Funcs, &funcs );
4808 if (!status) *(unixlib_handle_t *)buffer = (UINT_PTR)funcs;
4809 return status;
4811 return STATUS_INVALID_HANDLE;
4813 default:
4814 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
4815 process, addr, info_class, buffer, len, res_len);
4816 return STATUS_INVALID_INFO_CLASS;
4821 /***********************************************************************
4822 * NtLockVirtualMemory (NTDLL.@)
4823 * ZwLockVirtualMemory (NTDLL.@)
4825 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
4827 unsigned int status = STATUS_SUCCESS;
4829 if (process != NtCurrentProcess())
4831 apc_call_t call;
4832 apc_result_t result;
4834 memset( &call, 0, sizeof(call) );
4836 call.virtual_lock.type = APC_VIRTUAL_LOCK;
4837 call.virtual_lock.addr = wine_server_client_ptr( *addr );
4838 call.virtual_lock.size = *size;
4839 status = server_queue_process_apc( process, &call, &result );
4840 if (status != STATUS_SUCCESS) return status;
4842 if (result.virtual_lock.status == STATUS_SUCCESS)
4844 *addr = wine_server_get_ptr( result.virtual_lock.addr );
4845 *size = result.virtual_lock.size;
4847 return result.virtual_lock.status;
4850 *size = ROUND_SIZE( *addr, *size );
4851 *addr = ROUND_ADDR( *addr, page_mask );
4853 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
4854 return status;
4858 /***********************************************************************
4859 * NtUnlockVirtualMemory (NTDLL.@)
4860 * ZwUnlockVirtualMemory (NTDLL.@)
4862 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
4864 unsigned int status = STATUS_SUCCESS;
4866 if (process != NtCurrentProcess())
4868 apc_call_t call;
4869 apc_result_t result;
4871 memset( &call, 0, sizeof(call) );
4873 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
4874 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
4875 call.virtual_unlock.size = *size;
4876 status = server_queue_process_apc( process, &call, &result );
4877 if (status != STATUS_SUCCESS) return status;
4879 if (result.virtual_unlock.status == STATUS_SUCCESS)
4881 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
4882 *size = result.virtual_unlock.size;
4884 return result.virtual_unlock.status;
4887 *size = ROUND_SIZE( *addr, *size );
4888 *addr = ROUND_ADDR( *addr, page_mask );
4890 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
4891 return status;
4895 /***********************************************************************
4896 * NtMapViewOfSection (NTDLL.@)
4897 * ZwMapViewOfSection (NTDLL.@)
4899 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG_PTR zero_bits,
4900 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
4901 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
4903 unsigned int res;
4904 SIZE_T mask = granularity_mask;
4905 LARGE_INTEGER offset;
4907 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
4909 TRACE("handle=%p process=%p addr=%p off=%s size=%lx access=%x\n",
4910 handle, process, *addr_ptr, wine_dbgstr_longlong(offset.QuadPart), *size_ptr, (int)protect );
4912 /* Check parameters */
4913 if (zero_bits > 21 && zero_bits < 32)
4914 return STATUS_INVALID_PARAMETER_4;
4916 /* If both addr_ptr and zero_bits are passed, they have match */
4917 if (*addr_ptr && zero_bits && zero_bits < 32 &&
4918 (((UINT_PTR)*addr_ptr) >> (32 - zero_bits)))
4919 return STATUS_INVALID_PARAMETER_4;
4920 if (*addr_ptr && zero_bits >= 32 &&
4921 (((UINT_PTR)*addr_ptr) & ~zero_bits))
4922 return STATUS_INVALID_PARAMETER_4;
4924 #ifndef _WIN64
4925 if (!is_old_wow64())
4927 if (zero_bits >= 32) return STATUS_INVALID_PARAMETER_4;
4928 if (alloc_type & AT_ROUND_TO_PAGE)
4930 *addr_ptr = ROUND_ADDR( *addr_ptr, page_mask );
4931 mask = page_mask;
4934 #endif
4936 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
4937 return STATUS_MAPPED_ALIGNMENT;
4939 if (process != NtCurrentProcess())
4941 apc_call_t call;
4942 apc_result_t result;
4944 memset( &call, 0, sizeof(call) );
4946 call.map_view.type = APC_MAP_VIEW;
4947 call.map_view.handle = wine_server_obj_handle( handle );
4948 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
4949 call.map_view.size = *size_ptr;
4950 call.map_view.offset = offset.QuadPart;
4951 call.map_view.zero_bits = zero_bits;
4952 call.map_view.alloc_type = alloc_type;
4953 call.map_view.prot = protect;
4954 res = server_queue_process_apc( process, &call, &result );
4955 if (res != STATUS_SUCCESS) return res;
4957 if (NT_SUCCESS(result.map_view.status))
4959 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
4960 *size_ptr = result.map_view.size;
4962 return result.map_view.status;
4965 return virtual_map_section( handle, addr_ptr, get_zero_bits_limit( zero_bits ), commit_size,
4966 offset_ptr, size_ptr, alloc_type, protect );
4969 /***********************************************************************
4970 * NtMapViewOfSectionEx (NTDLL.@)
4971 * ZwMapViewOfSectionEx (NTDLL.@)
4973 NTSTATUS WINAPI NtMapViewOfSectionEx( HANDLE handle, HANDLE process, PVOID *addr_ptr,
4974 const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
4975 ULONG alloc_type, ULONG protect,
4976 MEM_EXTENDED_PARAMETER *parameters, ULONG count )
4978 ULONG_PTR limit = 0, align = 0;
4979 ULONG attributes = 0;
4980 unsigned int status;
4981 SIZE_T mask = granularity_mask;
4982 LARGE_INTEGER offset;
4984 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
4986 TRACE( "handle=%p process=%p addr=%p off=%s size=%lx access=%x\n",
4987 handle, process, *addr_ptr, wine_dbgstr_longlong(offset.QuadPart), *size_ptr, (int)protect );
4989 status = get_extended_params( parameters, count, &limit, &align, &attributes );
4990 if (status) return status;
4992 if (align) return STATUS_INVALID_PARAMETER;
4993 if (*addr_ptr && limit) return STATUS_INVALID_PARAMETER;
4995 #ifndef _WIN64
4996 if (!is_old_wow64() && (alloc_type & AT_ROUND_TO_PAGE))
4998 *addr_ptr = ROUND_ADDR( *addr_ptr, page_mask );
4999 mask = page_mask;
5001 #endif
5003 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
5004 return STATUS_MAPPED_ALIGNMENT;
5006 if (process != NtCurrentProcess())
5008 apc_call_t call;
5009 apc_result_t result;
5011 memset( &call, 0, sizeof(call) );
5013 call.map_view_ex.type = APC_MAP_VIEW_EX;
5014 call.map_view_ex.handle = wine_server_obj_handle( handle );
5015 call.map_view_ex.addr = wine_server_client_ptr( *addr_ptr );
5016 call.map_view_ex.size = *size_ptr;
5017 call.map_view_ex.offset = offset.QuadPart;
5018 call.map_view_ex.limit = limit;
5019 call.map_view_ex.alloc_type = alloc_type;
5020 call.map_view_ex.prot = protect;
5021 status = server_queue_process_apc( process, &call, &result );
5022 if (status != STATUS_SUCCESS) return status;
5024 if (NT_SUCCESS(result.map_view_ex.status))
5026 *addr_ptr = wine_server_get_ptr( result.map_view_ex.addr );
5027 *size_ptr = result.map_view_ex.size;
5029 return result.map_view_ex.status;
5032 return virtual_map_section( handle, addr_ptr, limit, 0, offset_ptr, size_ptr, alloc_type, protect );
5035 /***********************************************************************
5036 * NtUnmapViewOfSection (NTDLL.@)
5037 * ZwUnmapViewOfSection (NTDLL.@)
5039 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
5041 struct file_view *view;
5042 unsigned int status = STATUS_NOT_MAPPED_VIEW;
5043 sigset_t sigset;
5045 if (process != NtCurrentProcess())
5047 apc_call_t call;
5048 apc_result_t result;
5050 memset( &call, 0, sizeof(call) );
5052 call.unmap_view.type = APC_UNMAP_VIEW;
5053 call.unmap_view.addr = wine_server_client_ptr( addr );
5054 status = server_queue_process_apc( process, &call, &result );
5055 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
5056 return status;
5059 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
5060 if ((view = find_view( addr, 0 )) && !is_view_valloc( view ))
5062 if (view->protect & VPROT_SYSTEM)
5064 struct builtin_module *builtin;
5066 LIST_FOR_EACH_ENTRY( builtin, &builtin_modules, struct builtin_module, entry )
5068 if (builtin->module != view->base) continue;
5069 if (builtin->refcount > 1)
5071 TRACE( "not freeing in-use builtin %p\n", view->base );
5072 builtin->refcount--;
5073 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
5074 return STATUS_SUCCESS;
5079 SERVER_START_REQ( unmap_view )
5081 req->base = wine_server_client_ptr( view->base );
5082 status = wine_server_call( req );
5084 SERVER_END_REQ;
5085 if (!status)
5087 if (view->protect & SEC_IMAGE) release_builtin_module( view->base );
5088 delete_view( view );
5090 else FIXME( "failed to unmap %p %x\n", view->base, status );
5092 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
5093 return status;
5096 /***********************************************************************
5097 * NtUnmapViewOfSectionEx (NTDLL.@)
5098 * ZwUnmapViewOfSectionEx (NTDLL.@)
5100 NTSTATUS WINAPI NtUnmapViewOfSectionEx( HANDLE process, PVOID addr, ULONG flags )
5102 if (flags) FIXME("Ignoring flags %#x.\n", (int)flags);
5103 return NtUnmapViewOfSection( process, addr );
5106 /******************************************************************************
5107 * virtual_fill_image_information
5109 * Helper for NtQuerySection.
5111 void virtual_fill_image_information( const pe_image_info_t *pe_info, SECTION_IMAGE_INFORMATION *info )
5113 info->TransferAddress = wine_server_get_ptr( pe_info->base + pe_info->entry_point );
5114 info->ZeroBits = pe_info->zerobits;
5115 info->MaximumStackSize = pe_info->stack_size;
5116 info->CommittedStackSize = pe_info->stack_commit;
5117 info->SubSystemType = pe_info->subsystem;
5118 info->MinorSubsystemVersion = pe_info->subsystem_minor;
5119 info->MajorSubsystemVersion = pe_info->subsystem_major;
5120 info->MajorOperatingSystemVersion = pe_info->osversion_major;
5121 info->MinorOperatingSystemVersion = pe_info->osversion_minor;
5122 info->ImageCharacteristics = pe_info->image_charact;
5123 info->DllCharacteristics = pe_info->dll_charact;
5124 info->Machine = pe_info->machine;
5125 info->ImageContainsCode = pe_info->contains_code;
5126 info->ImageFlags = pe_info->image_flags;
5127 info->LoaderFlags = pe_info->loader_flags;
5128 info->ImageFileSize = pe_info->file_size;
5129 info->CheckSum = pe_info->checksum;
5130 #ifndef _WIN64 /* don't return 64-bit values to 32-bit processes */
5131 if (is_machine_64bit( pe_info->machine ))
5133 info->TransferAddress = (void *)0x81231234; /* sic */
5134 info->MaximumStackSize = 0x100000;
5135 info->CommittedStackSize = 0x10000;
5137 #endif
5140 /******************************************************************************
5141 * NtQuerySection (NTDLL.@)
5142 * ZwQuerySection (NTDLL.@)
5144 NTSTATUS WINAPI NtQuerySection( HANDLE handle, SECTION_INFORMATION_CLASS class, void *ptr,
5145 SIZE_T size, SIZE_T *ret_size )
5147 unsigned int status;
5148 pe_image_info_t image_info;
5150 switch (class)
5152 case SectionBasicInformation:
5153 if (size < sizeof(SECTION_BASIC_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
5154 break;
5155 case SectionImageInformation:
5156 if (size < sizeof(SECTION_IMAGE_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
5157 break;
5158 default:
5159 FIXME( "class %u not implemented\n", class );
5160 return STATUS_NOT_IMPLEMENTED;
5162 if (!ptr) return STATUS_ACCESS_VIOLATION;
5164 SERVER_START_REQ( get_mapping_info )
5166 req->handle = wine_server_obj_handle( handle );
5167 req->access = SECTION_QUERY;
5168 wine_server_set_reply( req, &image_info, sizeof(image_info) );
5169 if (!(status = wine_server_call( req )))
5171 if (class == SectionBasicInformation)
5173 SECTION_BASIC_INFORMATION *info = ptr;
5174 info->Attributes = reply->flags;
5175 info->BaseAddress = NULL;
5176 info->Size.QuadPart = reply->size;
5177 if (ret_size) *ret_size = sizeof(*info);
5179 else if (reply->flags & SEC_IMAGE)
5181 SECTION_IMAGE_INFORMATION *info = ptr;
5182 virtual_fill_image_information( &image_info, info );
5183 if (ret_size) *ret_size = sizeof(*info);
5185 else status = STATUS_SECTION_NOT_IMAGE;
5188 SERVER_END_REQ;
5190 return status;
5194 /***********************************************************************
5195 * NtFlushVirtualMemory (NTDLL.@)
5196 * ZwFlushVirtualMemory (NTDLL.@)
5198 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
5199 SIZE_T *size_ptr, ULONG unknown )
5201 struct file_view *view;
5202 unsigned int status = STATUS_SUCCESS;
5203 sigset_t sigset;
5204 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
5206 if (process != NtCurrentProcess())
5208 apc_call_t call;
5209 apc_result_t result;
5211 memset( &call, 0, sizeof(call) );
5213 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
5214 call.virtual_flush.addr = wine_server_client_ptr( addr );
5215 call.virtual_flush.size = *size_ptr;
5216 status = server_queue_process_apc( process, &call, &result );
5217 if (status != STATUS_SUCCESS) return status;
5219 if (result.virtual_flush.status == STATUS_SUCCESS)
5221 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
5222 *size_ptr = result.virtual_flush.size;
5224 return result.virtual_flush.status;
5227 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
5228 if (!(view = find_view( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
5229 else
5231 if (!*size_ptr) *size_ptr = view->size;
5232 *addr_ptr = addr;
5233 #ifdef MS_ASYNC
5234 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
5235 #endif
5237 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
5238 return status;
5242 /***********************************************************************
5243 * NtGetWriteWatch (NTDLL.@)
5244 * ZwGetWriteWatch (NTDLL.@)
5246 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
5247 ULONG_PTR *count, ULONG *granularity )
5249 NTSTATUS status = STATUS_SUCCESS;
5250 sigset_t sigset;
5252 size = ROUND_SIZE( base, size );
5253 base = ROUND_ADDR( base, page_mask );
5255 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
5256 if (!*count || !size) return STATUS_INVALID_PARAMETER;
5257 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
5259 if (!addresses) return STATUS_ACCESS_VIOLATION;
5261 TRACE( "%p %x %p-%p %p %lu\n", process, (int)flags, base, (char *)base + size,
5262 addresses, *count );
5264 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
5266 if (is_write_watch_range( base, size ))
5268 ULONG_PTR pos = 0;
5269 char *addr = base;
5270 char *end = addr + size;
5272 while (pos < *count && addr < end)
5274 if (!(get_page_vprot( addr ) & VPROT_WRITEWATCH)) addresses[pos++] = addr;
5275 addr += page_size;
5277 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( base, addr - (char *)base );
5278 *count = pos;
5279 *granularity = page_size;
5281 else status = STATUS_INVALID_PARAMETER;
5283 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
5284 return status;
5288 /***********************************************************************
5289 * NtResetWriteWatch (NTDLL.@)
5290 * ZwResetWriteWatch (NTDLL.@)
5292 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
5294 NTSTATUS status = STATUS_SUCCESS;
5295 sigset_t sigset;
5297 size = ROUND_SIZE( base, size );
5298 base = ROUND_ADDR( base, page_mask );
5300 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
5302 if (!size) return STATUS_INVALID_PARAMETER;
5304 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
5306 if (is_write_watch_range( base, size ))
5307 reset_write_watches( base, size );
5308 else
5309 status = STATUS_INVALID_PARAMETER;
5311 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
5312 return status;
5316 /***********************************************************************
5317 * NtReadVirtualMemory (NTDLL.@)
5318 * ZwReadVirtualMemory (NTDLL.@)
5320 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
5321 SIZE_T size, SIZE_T *bytes_read )
5323 unsigned int status;
5325 if (virtual_check_buffer_for_write( buffer, size ))
5327 SERVER_START_REQ( read_process_memory )
5329 req->handle = wine_server_obj_handle( process );
5330 req->addr = wine_server_client_ptr( addr );
5331 wine_server_set_reply( req, buffer, size );
5332 if ((status = wine_server_call( req ))) size = 0;
5334 SERVER_END_REQ;
5336 else
5338 status = STATUS_ACCESS_VIOLATION;
5339 size = 0;
5341 if (bytes_read) *bytes_read = size;
5342 return status;
5346 /***********************************************************************
5347 * NtWriteVirtualMemory (NTDLL.@)
5348 * ZwWriteVirtualMemory (NTDLL.@)
5350 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
5351 SIZE_T size, SIZE_T *bytes_written )
5353 unsigned int status;
5355 if (virtual_check_buffer_for_read( buffer, size ))
5357 SERVER_START_REQ( write_process_memory )
5359 req->handle = wine_server_obj_handle( process );
5360 req->addr = wine_server_client_ptr( addr );
5361 wine_server_add_data( req, buffer, size );
5362 if ((status = wine_server_call( req ))) size = 0;
5364 SERVER_END_REQ;
5366 else
5368 status = STATUS_PARTIAL_COPY;
5369 size = 0;
5371 if (bytes_written) *bytes_written = size;
5372 return status;
5376 /***********************************************************************
5377 * NtAreMappedFilesTheSame (NTDLL.@)
5378 * ZwAreMappedFilesTheSame (NTDLL.@)
5380 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
5382 struct file_view *view1, *view2;
5383 unsigned int status;
5384 sigset_t sigset;
5386 TRACE("%p %p\n", addr1, addr2);
5388 server_enter_uninterrupted_section( &virtual_mutex, &sigset );
5390 view1 = find_view( addr1, 0 );
5391 view2 = find_view( addr2, 0 );
5393 if (!view1 || !view2)
5394 status = STATUS_INVALID_ADDRESS;
5395 else if (is_view_valloc( view1 ) || is_view_valloc( view2 ))
5396 status = STATUS_CONFLICTING_ADDRESSES;
5397 else if (view1 == view2)
5398 status = STATUS_SUCCESS;
5399 else if ((view1->protect & VPROT_SYSTEM) || (view2->protect & VPROT_SYSTEM))
5400 status = STATUS_NOT_SAME_DEVICE;
5401 else
5403 SERVER_START_REQ( is_same_mapping )
5405 req->base1 = wine_server_client_ptr( view1->base );
5406 req->base2 = wine_server_client_ptr( view2->base );
5407 status = wine_server_call( req );
5409 SERVER_END_REQ;
5412 server_leave_uninterrupted_section( &virtual_mutex, &sigset );
5413 return status;
5417 static NTSTATUS prefetch_memory( HANDLE process, ULONG_PTR count,
5418 PMEMORY_RANGE_ENTRY addresses, ULONG flags )
5420 ULONG_PTR i;
5421 PVOID base;
5422 SIZE_T size;
5423 static unsigned int once;
5425 if (!once++)
5427 FIXME( "(process=%p,flags=%u) NtSetInformationVirtualMemory(VmPrefetchInformation) partial stub\n",
5428 process, (int)flags );
5431 for (i = 0; i < count; i++)
5433 if (!addresses[i].NumberOfBytes) return STATUS_INVALID_PARAMETER_4;
5436 if (process != NtCurrentProcess()) return STATUS_SUCCESS;
5438 for (i = 0; i < count; i++)
5440 base = ROUND_ADDR( addresses[i].VirtualAddress, page_mask );
5441 size = ROUND_SIZE( addresses[i].VirtualAddress, addresses[i].NumberOfBytes );
5442 madvise( base, size, MADV_WILLNEED );
5445 return STATUS_SUCCESS;
5448 /***********************************************************************
5449 * NtSetInformationVirtualMemory (NTDLL.@)
5450 * ZwSetInformationVirtualMemory (NTDLL.@)
5452 NTSTATUS WINAPI NtSetInformationVirtualMemory( HANDLE process,
5453 VIRTUAL_MEMORY_INFORMATION_CLASS info_class,
5454 ULONG_PTR count, PMEMORY_RANGE_ENTRY addresses,
5455 PVOID ptr, ULONG size )
5457 TRACE("(%p, info_class=%d, %lu, %p, %p, %u)\n",
5458 process, info_class, count, addresses, ptr, (int)size);
5460 switch (info_class)
5462 case VmPrefetchInformation:
5463 if (!ptr) return STATUS_INVALID_PARAMETER_5;
5464 if (size != sizeof(ULONG)) return STATUS_INVALID_PARAMETER_6;
5465 if (!count) return STATUS_INVALID_PARAMETER_3;
5466 return prefetch_memory( process, count, addresses, *(ULONG *)ptr );
5468 default:
5469 FIXME("(%p,info_class=%d,%lu,%p,%p,%u) Unknown information class\n",
5470 process, info_class, count, addresses, ptr, (int)size);
5471 return STATUS_INVALID_PARAMETER_2;
5476 /**********************************************************************
5477 * NtFlushInstructionCache (NTDLL.@)
5479 NTSTATUS WINAPI NtFlushInstructionCache( HANDLE handle, const void *addr, SIZE_T size )
5481 #if defined(__x86_64__) || defined(__i386__)
5482 /* no-op */
5483 #elif defined(HAVE___CLEAR_CACHE)
5484 if (handle == GetCurrentProcess())
5486 __clear_cache( (char *)addr, (char *)addr + size );
5488 else
5490 static int once;
5491 if (!once++) FIXME( "%p %p %ld other process not supported\n", handle, addr, size );
5493 #else
5494 static int once;
5495 if (!once++) FIXME( "%p %p %ld\n", handle, addr, size );
5496 #endif
5497 return STATUS_SUCCESS;
5501 /**********************************************************************
5502 * NtFlushProcessWriteBuffers (NTDLL.@)
5504 void WINAPI NtFlushProcessWriteBuffers(void)
5506 static int once = 0;
5507 if (!once++) FIXME( "stub\n" );
5511 /**********************************************************************
5512 * NtCreatePagingFile (NTDLL.@)
5514 NTSTATUS WINAPI NtCreatePagingFile( UNICODE_STRING *name, LARGE_INTEGER *min_size,
5515 LARGE_INTEGER *max_size, LARGE_INTEGER *actual_size )
5517 FIXME( "(%s %p %p %p) stub\n", debugstr_us(name), min_size, max_size, actual_size );
5518 return STATUS_SUCCESS;
5521 #ifndef _WIN64
5523 /***********************************************************************
5524 * NtWow64AllocateVirtualMemory64 (NTDLL.@)
5525 * ZwWow64AllocateVirtualMemory64 (NTDLL.@)
5527 NTSTATUS WINAPI NtWow64AllocateVirtualMemory64( HANDLE process, ULONG64 *ret, ULONG64 zero_bits,
5528 ULONG64 *size_ptr, ULONG type, ULONG protect )
5530 void *base;
5531 SIZE_T size;
5532 unsigned int status;
5534 TRACE("%p %s %s %x %08x\n", process,
5535 wine_dbgstr_longlong(*ret), wine_dbgstr_longlong(*size_ptr), (int)type, (int)protect );
5537 if (!*size_ptr) return STATUS_INVALID_PARAMETER_4;
5538 if (zero_bits > 21 && zero_bits < 32) return STATUS_INVALID_PARAMETER_3;
5540 if (process != NtCurrentProcess())
5542 apc_call_t call;
5543 apc_result_t result;
5545 memset( &call, 0, sizeof(call) );
5547 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
5548 call.virtual_alloc.addr = *ret;
5549 call.virtual_alloc.size = *size_ptr;
5550 call.virtual_alloc.zero_bits = zero_bits;
5551 call.virtual_alloc.op_type = type;
5552 call.virtual_alloc.prot = protect;
5553 status = server_queue_process_apc( process, &call, &result );
5554 if (status != STATUS_SUCCESS) return status;
5556 if (result.virtual_alloc.status == STATUS_SUCCESS)
5558 *ret = result.virtual_alloc.addr;
5559 *size_ptr = result.virtual_alloc.size;
5561 return result.virtual_alloc.status;
5564 base = (void *)(ULONG_PTR)*ret;
5565 size = *size_ptr;
5566 if ((ULONG_PTR)base != *ret) return STATUS_CONFLICTING_ADDRESSES;
5567 if (size != *size_ptr) return STATUS_WORKING_SET_LIMIT_RANGE;
5569 status = NtAllocateVirtualMemory( process, &base, zero_bits, &size, type, protect );
5570 if (!status)
5572 *ret = (ULONG_PTR)base;
5573 *size_ptr = size;
5575 return status;
5579 /***********************************************************************
5580 * NtWow64ReadVirtualMemory64 (NTDLL.@)
5581 * ZwWow64ReadVirtualMemory64 (NTDLL.@)
5583 NTSTATUS WINAPI NtWow64ReadVirtualMemory64( HANDLE process, ULONG64 addr, void *buffer,
5584 ULONG64 size, ULONG64 *bytes_read )
5586 unsigned int status;
5588 if (size > MAXLONG) size = MAXLONG;
5590 if (virtual_check_buffer_for_write( buffer, size ))
5592 SERVER_START_REQ( read_process_memory )
5594 req->handle = wine_server_obj_handle( process );
5595 req->addr = addr;
5596 wine_server_set_reply( req, buffer, size );
5597 if ((status = wine_server_call( req ))) size = 0;
5599 SERVER_END_REQ;
5601 else
5603 status = STATUS_ACCESS_VIOLATION;
5604 size = 0;
5606 if (bytes_read) *bytes_read = size;
5607 return status;
5611 /***********************************************************************
5612 * NtWow64WriteVirtualMemory64 (NTDLL.@)
5613 * ZwWow64WriteVirtualMemory64 (NTDLL.@)
5615 NTSTATUS WINAPI NtWow64WriteVirtualMemory64( HANDLE process, ULONG64 addr, const void *buffer,
5616 ULONG64 size, ULONG64 *bytes_written )
5618 unsigned int status;
5620 if (size > MAXLONG) size = MAXLONG;
5622 if (virtual_check_buffer_for_read( buffer, size ))
5624 SERVER_START_REQ( write_process_memory )
5626 req->handle = wine_server_obj_handle( process );
5627 req->addr = addr;
5628 wine_server_add_data( req, buffer, size );
5629 if ((status = wine_server_call( req ))) size = 0;
5631 SERVER_END_REQ;
5633 else
5635 status = STATUS_PARTIAL_COPY;
5636 size = 0;
5638 if (bytes_written) *bytes_written = size;
5639 return status;
5643 /***********************************************************************
5644 * NtWow64GetNativeSystemInformation (NTDLL.@)
5645 * ZwWow64GetNativeSystemInformation (NTDLL.@)
5647 NTSTATUS WINAPI NtWow64GetNativeSystemInformation( SYSTEM_INFORMATION_CLASS class, void *info,
5648 ULONG len, ULONG *retlen )
5650 NTSTATUS status;
5652 switch (class)
5654 case SystemCpuInformation:
5655 status = NtQuerySystemInformation( class, info, len, retlen );
5656 if (!status && is_old_wow64())
5658 SYSTEM_CPU_INFORMATION *cpu = info;
5660 if (cpu->ProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
5661 cpu->ProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64;
5663 return status;
5664 case SystemBasicInformation:
5665 case SystemEmulationBasicInformation:
5666 case SystemEmulationProcessorInformation:
5667 return NtQuerySystemInformation( class, info, len, retlen );
5668 case SystemNativeBasicInformation:
5669 return NtQuerySystemInformation( SystemBasicInformation, info, len, retlen );
5670 default:
5671 if (is_old_wow64()) return STATUS_INVALID_INFO_CLASS;
5672 return NtQuerySystemInformation( class, info, len, retlen );
5676 /***********************************************************************
5677 * NtWow64IsProcessorFeaturePresent (NTDLL.@)
5678 * ZwWow64IsProcessorFeaturePresent (NTDLL.@)
5680 NTSTATUS WINAPI NtWow64IsProcessorFeaturePresent( UINT feature )
5682 return feature < PROCESSOR_FEATURE_MAX && user_shared_data->ProcessorFeatures[feature];
5685 #endif /* _WIN64 */