2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 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
22 #include "wine/port.h"
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
51 #define WIN32_NO_STATUS
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/list.h"
58 #include "wine/debug.h"
59 #include "ntdll_misc.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
62 WINE_DECLARE_DEBUG_CHANNEL(module);
69 #define MAP_NORESERVE 0
75 struct list entry; /* Entry in global view list */
76 void *base; /* Base address */
77 size_t size; /* Size in bytes */
78 HANDLE mapping; /* Handle to the file mapping */
79 unsigned int protect; /* Protection for all pages at allocation time */
80 BYTE prot[1]; /* Protection byte for each page */
84 /* Conversion from VPROT_* to Win32 flags */
85 static const BYTE VIRTUAL_Win32Flags[16] =
87 PAGE_NOACCESS, /* 0 */
88 PAGE_READONLY, /* READ */
89 PAGE_READWRITE, /* WRITE */
90 PAGE_READWRITE, /* READ | WRITE */
91 PAGE_EXECUTE, /* EXEC */
92 PAGE_EXECUTE_READ, /* READ | EXEC */
93 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
94 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
95 PAGE_WRITECOPY, /* WRITECOPY */
96 PAGE_WRITECOPY, /* READ | WRITECOPY */
97 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
98 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
102 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
105 static struct list views_list = LIST_INIT(views_list);
107 static RTL_CRITICAL_SECTION csVirtual;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
111 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
114 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
117 /* These are always the same on an i386, and it will be faster this way */
118 # define page_mask 0xfff
119 # define page_shift 12
120 # define page_size 0x1000
121 /* Note: these are Windows limits, you cannot change them. */
122 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
123 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
124 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
125 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
126 #elif defined(__x86_64__)
127 # define page_mask 0xfff
128 # define page_shift 12
129 # define page_size 0x1000
130 static void *address_space_limit = (void *)0x7fffffff0000;
131 static void *user_space_limit = (void *)0x7fffffff0000;
132 static void *working_set_limit = (void *)0x7fffffff0000;
133 static void *address_space_start = (void *)0x10000;
135 static UINT page_shift;
136 static UINT_PTR page_size;
137 static UINT_PTR page_mask;
138 static void *address_space_limit;
139 static void *user_space_limit;
140 static void *working_set_limit;
141 static void *address_space_start = (void *)0x10000;
142 #endif /* __i386__ */
143 static const int is_win64 = (sizeof(void *) > sizeof(int));
145 #define ROUND_ADDR(addr,mask) \
146 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
148 #define ROUND_SIZE(addr,size) \
149 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
151 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
152 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
154 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
156 static HANDLE virtual_heap;
157 static void *preload_reserve_start;
158 static void *preload_reserve_end;
159 static int use_locks;
160 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
163 /***********************************************************************
166 static const char *VIRTUAL_GetProtStr( BYTE prot )
168 static char buffer[6];
169 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
170 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
171 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
172 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
173 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
179 /***********************************************************************
180 * VIRTUAL_GetUnixProt
182 * Convert page protections to protection for mmap/mprotect.
184 static int VIRTUAL_GetUnixProt( BYTE vprot )
187 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
189 if (vprot & VPROT_READ) prot |= PROT_READ;
190 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
191 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
192 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
193 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
195 if (!prot) prot = PROT_NONE;
200 /***********************************************************************
203 static void VIRTUAL_DumpView( struct file_view *view )
206 char *addr = view->base;
207 BYTE prot = view->prot[0];
209 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
210 if (view->protect & VPROT_SYSTEM)
211 TRACE( " (system)\n" );
212 else if (view->protect & VPROT_VALLOC)
213 TRACE( " (valloc)\n" );
214 else if (view->mapping)
215 TRACE( " %p\n", view->mapping );
217 TRACE( " (anonymous)\n");
219 for (count = i = 1; i < view->size >> page_shift; i++, count++)
221 if (view->prot[i] == prot) continue;
222 TRACE( " %p - %p %s\n",
223 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
224 addr += (count << page_shift);
225 prot = view->prot[i];
229 TRACE( " %p - %p %s\n",
230 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
234 /***********************************************************************
238 static void VIRTUAL_Dump(void)
241 struct file_view *view;
243 TRACE( "Dump of all virtual memory views:\n" );
244 server_enter_uninterrupted_section( &csVirtual, &sigset );
245 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
247 VIRTUAL_DumpView( view );
249 server_leave_uninterrupted_section( &csVirtual, &sigset );
254 /***********************************************************************
257 * Find the view containing a given address. The csVirtual section must be held by caller.
266 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
268 struct file_view *view;
270 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
272 if (view->base > addr) break; /* no matching view */
273 if ((const char *)view->base + view->size <= (const char *)addr) continue;
274 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
275 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
282 /***********************************************************************
285 static inline UINT_PTR get_mask( ULONG zero_bits )
287 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
288 if (zero_bits < page_shift) zero_bits = page_shift;
289 return (1 << zero_bits) - 1;
293 /***********************************************************************
296 * Find the first view overlapping at least part of the specified range.
297 * The csVirtual section must be held by caller.
299 static struct file_view *find_view_range( const void *addr, size_t size )
301 struct file_view *view;
303 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
305 if ((const char *)view->base >= (const char *)addr + size) break;
306 if ((const char *)view->base + view->size > (const char *)addr) return view;
312 /***********************************************************************
315 * Find a free area between views inside the specified range.
316 * The csVirtual section must be held by caller.
318 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
325 start = ROUND_ADDR( (char *)end - size, mask );
326 if (start >= end || start < base) return NULL;
328 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
330 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
332 if ((char *)view->base + view->size <= (char *)start) break;
333 if ((char *)view->base >= (char *)start + size) continue;
334 start = ROUND_ADDR( (char *)view->base - size, mask );
335 /* stop if remaining space is not large enough */
336 if (!start || start >= end || start < base) return NULL;
341 start = ROUND_ADDR( (char *)base + mask, mask );
342 if (start >= end || (char *)end - (char *)start < size) return NULL;
344 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
346 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
348 if ((char *)view->base >= (char *)start + size) break;
349 if ((char *)view->base + view->size <= (char *)start) continue;
350 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
351 /* stop if remaining space is not large enough */
352 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
359 /***********************************************************************
362 * Add a reserved area to the list maintained by libwine.
363 * The csVirtual section must be held by caller.
365 static void add_reserved_area( void *addr, size_t size )
367 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
369 if (addr < user_space_limit)
371 /* unmap the part of the area that is below the limit */
372 assert( (char *)addr + size > (char *)user_space_limit );
373 munmap( addr, (char *)user_space_limit - (char *)addr );
374 size -= (char *)user_space_limit - (char *)addr;
375 addr = user_space_limit;
377 /* blow away existing mappings */
378 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
379 wine_mmap_add_reserved_area( addr, size );
383 /***********************************************************************
384 * remove_reserved_area
386 * Remove a reserved area from the list maintained by libwine.
387 * The csVirtual section must be held by caller.
389 static void remove_reserved_area( void *addr, size_t size )
391 struct file_view *view;
393 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
394 wine_mmap_remove_reserved_area( addr, size, 0 );
396 /* unmap areas not covered by an existing view */
397 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
399 if ((char *)view->base >= (char *)addr + size)
401 munmap( addr, size );
404 if ((char *)view->base + view->size <= (char *)addr) continue;
405 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
406 if ((char *)view->base + view->size > (char *)addr + size) break;
407 size = (char *)addr + size - ((char *)view->base + view->size);
408 addr = (char *)view->base + view->size;
413 /***********************************************************************
416 * Check if an address range goes beyond a given limit.
418 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
420 return (addr >= limit || (const char *)addr + size > (const char *)limit);
424 /***********************************************************************
427 * Unmap an area, or simply replace it by an empty mapping if it is
428 * in a reserved area. The csVirtual section must be held by caller.
430 static inline void unmap_area( void *addr, size_t size )
432 if (wine_mmap_is_in_reserved_area( addr, size ))
433 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
434 else if (is_beyond_limit( addr, size, user_space_limit ))
435 add_reserved_area( addr, size );
437 munmap( addr, size );
441 /***********************************************************************
444 * Deletes a view. The csVirtual section must be held by caller.
446 static void delete_view( struct file_view *view ) /* [in] View */
448 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
449 list_remove( &view->entry );
450 if (view->mapping) close_handle( view->mapping );
451 RtlFreeHeap( virtual_heap, 0, view );
455 /***********************************************************************
458 * Create a view. The csVirtual section must be held by caller.
460 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
462 struct file_view *view;
464 int unix_prot = VIRTUAL_GetUnixProt( vprot );
466 assert( !((UINT_PTR)base & page_mask) );
467 assert( !(size & page_mask) );
469 /* Create the view structure */
471 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
473 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
474 return STATUS_NO_MEMORY;
480 view->protect = vprot;
481 memset( view->prot, vprot, size >> page_shift );
483 /* Insert it in the linked list */
485 LIST_FOR_EACH( ptr, &views_list )
487 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
488 if (next->base > base) break;
490 list_add_before( ptr, &view->entry );
492 /* Check for overlapping views. This can happen if the previous view
493 * was a system view that got unmapped behind our back. In that case
494 * we recover by simply deleting it. */
496 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
498 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
499 if ((char *)prev->base + prev->size > (char *)base)
501 TRACE( "overlapping prev view %p-%p for %p-%p\n",
502 prev->base, (char *)prev->base + prev->size,
503 base, (char *)base + view->size );
504 assert( prev->protect & VPROT_SYSTEM );
508 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
510 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
511 if ((char *)base + view->size > (char *)next->base)
513 TRACE( "overlapping next view %p-%p for %p-%p\n",
514 next->base, (char *)next->base + next->size,
515 base, (char *)base + view->size );
516 assert( next->protect & VPROT_SYSTEM );
522 VIRTUAL_DEBUG_DUMP_VIEW( view );
524 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
526 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
527 mprotect( base, size, unix_prot | PROT_EXEC );
529 return STATUS_SUCCESS;
533 /***********************************************************************
534 * VIRTUAL_GetWin32Prot
536 * Convert page protections to Win32 flags.
538 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
540 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
541 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
542 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
547 /***********************************************************************
550 * Build page protections from Win32 flags.
553 * protect [I] Win32 protection flags
556 * Value of page protection flags
558 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot )
560 switch(protect & 0xff)
566 *vprot = VPROT_READ | VPROT_WRITE;
569 *vprot = VPROT_READ | VPROT_WRITECOPY;
574 case PAGE_EXECUTE_READ:
575 *vprot = VPROT_EXEC | VPROT_READ;
577 case PAGE_EXECUTE_READWRITE:
578 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
580 case PAGE_EXECUTE_WRITECOPY:
581 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
587 return STATUS_INVALID_PARAMETER;
589 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
590 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
591 return STATUS_SUCCESS;
595 /***********************************************************************
598 * Change the protection of a range of pages.
604 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
605 void *base, /* [in] Starting address */
606 size_t size, /* [in] Size in bytes */
607 BYTE vprot ) /* [in] Protections to use */
609 int unix_prot = VIRTUAL_GetUnixProt(vprot);
610 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
613 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
615 if (view->protect & VPROT_WRITEWATCH)
617 /* each page may need different protections depending on write watch flag */
622 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
623 unix_prot = VIRTUAL_GetUnixProt( p[0] );
624 for (count = i = 1; i < size >> page_shift; i++, count++)
626 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
627 prot = VIRTUAL_GetUnixProt( p[i] );
628 if (prot == unix_prot) continue;
629 mprotect( addr, count << page_shift, unix_prot );
630 addr += count << page_shift;
634 if (count) mprotect( addr, count << page_shift, unix_prot );
635 VIRTUAL_DEBUG_DUMP_VIEW( view );
639 /* if setting stack guard pages, store the permissions first, as the guard may be
640 * triggered at any point after mprotect and change the permissions again */
641 if ((vprot & VPROT_GUARD) &&
642 (base >= NtCurrentTeb()->DeallocationStack) &&
643 (base < NtCurrentTeb()->Tib.StackBase))
645 memset( p, vprot, size >> page_shift );
646 mprotect( base, size, unix_prot );
647 VIRTUAL_DEBUG_DUMP_VIEW( view );
651 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
652 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
654 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
655 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
656 /* exec + write may legitimately fail, in that case fall back to write only */
657 if (!(unix_prot & PROT_WRITE)) return FALSE;
660 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
663 memset( p, vprot, size >> page_shift );
664 VIRTUAL_DEBUG_DUMP_VIEW( view );
669 /***********************************************************************
670 * reset_write_watches
672 * Reset write watches in a memory range.
674 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
679 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
681 p[0] |= VPROT_WRITEWATCH;
682 unix_prot = VIRTUAL_GetUnixProt( p[0] );
683 for (count = i = 1; i < size >> page_shift; i++, count++)
685 p[i] |= VPROT_WRITEWATCH;
686 prot = VIRTUAL_GetUnixProt( p[i] );
687 if (prot == unix_prot) continue;
688 mprotect( addr, count << page_shift, unix_prot );
689 addr += count << page_shift;
693 if (count) mprotect( addr, count << page_shift, unix_prot );
697 /***********************************************************************
700 * Release the extra memory while keeping the range starting on the granularity boundary.
702 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
704 if ((ULONG_PTR)ptr & mask)
706 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
707 munmap( ptr, extra );
708 ptr = (char *)ptr + extra;
711 if (total_size > wanted_size)
712 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
726 /***********************************************************************
727 * alloc_reserved_area_callback
729 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
731 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
733 struct alloc_area *alloc = arg;
734 void *end = (char *)start + size;
736 if (start < address_space_start) start = address_space_start;
737 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
738 if (start >= end) return 0;
740 /* make sure we don't touch the preloader reserved range */
741 if (preload_reserve_end >= start)
743 if (preload_reserve_end >= end)
745 if (preload_reserve_start <= start) return 0; /* no space in that area */
746 if (preload_reserve_start < end) end = preload_reserve_start;
748 else if (preload_reserve_start <= start) start = preload_reserve_end;
751 /* range is split in two by the preloader reservation, try first part */
752 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
753 alloc->mask, alloc->top_down )))
755 /* then fall through to try second part */
756 start = preload_reserve_end;
759 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
766 /***********************************************************************
769 * Create a view and mmap the corresponding memory area.
770 * The csVirtual section must be held by caller.
772 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
773 int top_down, unsigned int vprot )
780 if (is_beyond_limit( base, size, address_space_limit ))
781 return STATUS_WORKING_SET_LIMIT_RANGE;
783 switch (wine_mmap_is_in_reserved_area( base, size ))
785 case -1: /* partially in a reserved area */
786 return STATUS_CONFLICTING_ADDRESSES;
788 case 0: /* not in a reserved area, do a normal allocation */
789 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
791 if (errno == ENOMEM) return STATUS_NO_MEMORY;
792 return STATUS_INVALID_PARAMETER;
796 /* We couldn't get the address we wanted */
797 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
798 else munmap( ptr, size );
799 return STATUS_CONFLICTING_ADDRESSES;
804 case 1: /* in a reserved area, make sure the address is available */
805 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
806 /* replace the reserved area by our mapping */
807 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
808 return STATUS_INVALID_PARAMETER;
811 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
815 size_t view_size = size + mask + 1;
816 struct alloc_area alloc;
820 alloc.top_down = top_down;
821 alloc.limit = user_space_limit;
822 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
825 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
826 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
827 return STATUS_INVALID_PARAMETER;
833 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
835 if (errno == ENOMEM) return STATUS_NO_MEMORY;
836 return STATUS_INVALID_PARAMETER;
838 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
839 /* if we got something beyond the user limit, unmap it and retry */
840 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
843 ptr = unmap_extra_space( ptr, view_size, size, mask );
846 status = create_view( view_ret, ptr, size, vprot );
847 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
852 /***********************************************************************
855 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
856 * The csVirtual section must be held by caller.
858 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
859 off_t offset, unsigned int vprot, BOOL removable )
862 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
863 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
865 assert( start < view->size );
866 assert( start + size <= view->size );
868 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
870 TRACE( "forcing exec permission on mapping %p-%p\n",
871 (char *)view->base + start, (char *)view->base + start + size - 1 );
875 /* only try mmap if media is not removable (or if we require write access) */
876 if (!removable || shared_write)
878 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
880 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
883 if ((errno == EPERM) && (prot & PROT_EXEC))
884 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
886 /* mmap() failed; if this is because the file offset is not */
887 /* page-aligned (EINVAL), or because the underlying filesystem */
888 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
889 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
890 if (shared_write) /* we cannot fake shared write mappings */
892 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
893 ERR( "shared writable mmap not supported, broken filesystem?\n" );
894 return STATUS_NOT_SUPPORTED;
898 /* Reserve the memory with an anonymous mmap */
899 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
900 if (ptr == (void *)-1) return FILE_GetNtStatus();
901 /* Now read in the file */
902 pread( fd, ptr, size, offset );
903 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
905 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
906 return STATUS_SUCCESS;
910 /***********************************************************************
913 * Get the size of the committed range starting at base.
914 * Also return the protections for the first page.
916 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
920 start = ((char *)base - (char *)view->base) >> page_shift;
921 *vprot = view->prot[start];
923 if (view->mapping && !(view->protect & VPROT_COMMITTED))
926 SERVER_START_REQ( get_mapping_committed_range )
928 req->handle = wine_server_obj_handle( view->mapping );
929 req->offset = start << page_shift;
930 if (!wine_server_call( req ))
933 if (reply->committed)
935 *vprot |= VPROT_COMMITTED;
936 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
943 for (i = start + 1; i < view->size >> page_shift; i++)
944 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
945 return (i - start) << page_shift;
949 /***********************************************************************
952 * Decommit some pages of a given view.
953 * The csVirtual section must be held by caller.
955 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
957 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
959 BYTE *p = view->prot + (start >> page_shift);
961 while (size--) *p++ &= ~VPROT_COMMITTED;
962 return STATUS_SUCCESS;
964 return FILE_GetNtStatus();
968 /***********************************************************************
969 * allocate_dos_memory
971 * Allocate the DOS memory range.
973 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
977 void * const low_64k = (void *)0x10000;
978 const size_t dosmem_size = 0x110000;
979 int unix_prot = VIRTUAL_GetUnixProt( vprot );
982 /* check for existing view */
984 if ((ptr = list_head( &views_list )))
986 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
987 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
990 /* check without the first 64K */
992 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
994 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
997 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
998 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1002 /* now try to allocate the low 64K too */
1004 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1006 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1007 if (addr == (void *)page_size)
1009 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1012 TRACE( "successfully mapped low 64K range\n" );
1014 else TRACE( "failed to map page 0\n" );
1018 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1020 TRACE( "failed to map low 64K range\n" );
1024 /* now reserve the whole range */
1026 size = (char *)dosmem_size - (char *)addr;
1027 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1028 return create_view( view, addr, size, vprot );
1032 /***********************************************************************
1035 * Stat the underlying file for a memory view.
1037 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1040 int unix_fd, needs_close;
1042 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1043 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1045 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1046 if (needs_close) close( unix_fd );
1052 /***********************************************************************
1055 * Map an executable (PE format) image into memory.
1057 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1058 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
1060 IMAGE_DOS_HEADER *dos;
1061 IMAGE_NT_HEADERS *nt;
1062 IMAGE_SECTION_HEADER *sec;
1063 IMAGE_DATA_DIRECTORY *imports;
1064 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1069 struct file_view *view = NULL;
1070 char *ptr, *header_end;
1073 /* zero-map the whole range */
1075 server_enter_uninterrupted_section( &csVirtual, &sigset );
1077 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1078 status = map_view( &view, base, total_size, mask, FALSE,
1079 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1081 if (status != STATUS_SUCCESS)
1082 status = map_view( &view, NULL, total_size, mask, FALSE,
1083 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1085 if (status != STATUS_SUCCESS) goto error;
1088 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1090 /* map the header */
1092 if (fstat( fd, &st ) == -1)
1094 status = FILE_GetNtStatus();
1097 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1098 if (!st.st_size) goto error;
1099 header_size = min( header_size, st.st_size );
1100 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1101 !dup_mapping ) != STATUS_SUCCESS) goto error;
1102 dos = (IMAGE_DOS_HEADER *)ptr;
1103 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1104 header_end = ptr + ROUND_SIZE( 0, header_size );
1105 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1106 if ((char *)(nt + 1) > header_end) goto error;
1107 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1108 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
1110 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1111 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1113 /* check the architecture */
1116 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
1117 #elif defined(__ARMEL__)
1118 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_ARM &&
1119 nt->FileHeader.Machine != IMAGE_FILE_MACHINE_THUMB)
1121 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
1124 MESSAGE("Trying to load PE image for unsupported architecture (");
1125 switch (nt->FileHeader.Machine)
1127 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
1128 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
1129 case IMAGE_FILE_MACHINE_I386: MESSAGE("I386"); break;
1130 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
1131 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
1132 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
1133 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
1134 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
1135 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
1136 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
1137 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
1138 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
1139 case IMAGE_FILE_MACHINE_THUMB: MESSAGE("ARM Thumb"); break;
1140 case IMAGE_FILE_MACHINE_SPARC: MESSAGE("SPARC"); break;
1141 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1147 /* check for non page-aligned binary */
1149 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1151 /* unaligned sections, this happens for native subsystem binaries */
1152 /* in that case Windows simply maps in the whole file */
1154 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1155 !dup_mapping ) != STATUS_SUCCESS) goto error;
1157 /* check that all sections are loaded at the right offset */
1158 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1159 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1161 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1162 goto error; /* Windows refuses to load in that case too */
1165 /* set the image protections */
1166 VIRTUAL_SetProt( view, ptr, total_size,
1167 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1169 /* no relocations are performed on non page-aligned binaries */
1174 /* map all the sections */
1176 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1178 static const SIZE_T sector_align = 0x1ff;
1179 SIZE_T map_size, file_start, file_size, end;
1181 if (!sec->Misc.VirtualSize)
1182 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1184 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1186 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1187 file_start = sec->PointerToRawData & ~sector_align;
1188 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1189 if (file_size > map_size) file_size = map_size;
1191 /* a few sanity checks */
1192 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1193 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1195 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1196 sec->Name, sec->VirtualAddress, map_size, total_size );
1200 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1201 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1203 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1204 sec->Name, ptr + sec->VirtualAddress,
1205 sec->PointerToRawData, (int)pos, file_size, map_size,
1206 sec->Characteristics );
1207 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1208 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1209 FALSE ) != STATUS_SUCCESS)
1211 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1215 /* check if the import directory falls inside this section */
1216 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1217 imports->VirtualAddress < sec->VirtualAddress + map_size)
1219 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1220 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1221 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1223 map_file_into_view( view, shared_fd, base, end - base,
1224 pos + (base - sec->VirtualAddress),
1225 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1232 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1233 sec->Name, ptr + sec->VirtualAddress,
1234 sec->PointerToRawData, sec->SizeOfRawData,
1235 sec->Misc.VirtualSize, sec->Characteristics );
1237 if (!sec->PointerToRawData || !file_size) continue;
1239 /* Note: if the section is not aligned properly map_file_into_view will magically
1240 * fall back to read(), so we don't need to check anything here.
1242 end = file_start + file_size;
1243 if (sec->PointerToRawData >= st.st_size ||
1244 end > ((st.st_size + sector_align) & ~sector_align) ||
1246 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1247 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1248 !dup_mapping ) != STATUS_SUCCESS)
1250 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1254 if (file_size & page_mask)
1256 end = ROUND_SIZE( 0, file_size );
1257 if (end > map_size) end = map_size;
1258 TRACE_(module)("clearing %p - %p\n",
1259 ptr + sec->VirtualAddress + file_size,
1260 ptr + sec->VirtualAddress + end );
1261 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1266 /* perform base relocation, if necessary */
1269 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1270 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1272 IMAGE_BASE_RELOCATION *rel, *end;
1273 const IMAGE_DATA_DIRECTORY *relocs;
1275 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1277 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1279 status = STATUS_CONFLICTING_ADDRESSES;
1283 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1284 base, base + total_size, ptr, ptr + total_size );
1286 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1287 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1288 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1291 while (rel < end - 1 && rel->SizeOfBlock)
1293 if (rel->VirtualAddress >= total_size)
1295 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1296 status = STATUS_ACCESS_VIOLATION;
1299 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1300 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1301 (USHORT *)(rel + 1), delta );
1302 if (!rel) goto error;
1306 /* set the image protections */
1308 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1310 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1311 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1314 BYTE vprot = VPROT_COMMITTED;
1316 if (sec->Misc.VirtualSize)
1317 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1319 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1321 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1322 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITE;
1323 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1325 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1326 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1327 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1328 vprot |= VPROT_EXEC;
1330 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1331 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1332 sec->Characteristics, sec->Name );
1336 view->mapping = dup_mapping;
1337 server_leave_uninterrupted_section( &csVirtual, &sigset );
1340 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1341 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1343 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1344 return STATUS_SUCCESS;
1347 if (view) delete_view( view );
1348 server_leave_uninterrupted_section( &csVirtual, &sigset );
1349 if (dup_mapping) NtClose( dup_mapping );
1354 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1355 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1357 void **heap_base = arg;
1359 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1360 if (size < VIRTUAL_HEAP_SIZE) return 0;
1361 if (is_win64 && base < (void *)0x80000000) return 0;
1362 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1363 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1364 return (*heap_base != (void *)-1);
1367 /***********************************************************************
1370 void virtual_init(void)
1372 const char *preload;
1375 struct file_view *heap_view;
1378 page_size = getpagesize();
1379 page_mask = page_size - 1;
1380 /* Make sure we have a power of 2 */
1381 assert( !(page_size & page_mask) );
1383 while ((1 << page_shift) != page_size) page_shift++;
1384 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1385 #endif /* page_mask */
1386 if ((preload = getenv("WINEPRELOADRESERVE")))
1388 unsigned long start, end;
1389 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1391 preload_reserve_start = (void *)start;
1392 preload_reserve_end = (void *)end;
1396 /* try to find space in a reserved area for the virtual heap */
1397 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1398 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1400 assert( heap_base != (void *)-1 );
1401 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1402 VIRTUAL_HEAP_SIZE, NULL, NULL );
1403 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1405 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1406 size = (char *)address_space_start - (char *)0x10000;
1407 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1408 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1412 /***********************************************************************
1413 * virtual_init_threading
1415 void virtual_init_threading(void)
1421 /***********************************************************************
1422 * virtual_get_system_info
1424 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1427 info->KeMaximumIncrement = 0; /* FIXME */
1428 info->PageSize = page_size;
1429 info->MmLowestPhysicalPage = 1;
1430 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1431 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1432 info->AllocationGranularity = get_mask(0) + 1;
1433 info->LowestUserAddress = (void *)0x10000;
1434 info->HighestUserAddress = (char *)user_space_limit - 1;
1435 info->ActiveProcessorsAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1436 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1440 /***********************************************************************
1441 * virtual_create_system_view
1443 NTSTATUS virtual_create_builtin_view( void *module )
1447 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1448 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1449 IMAGE_SECTION_HEADER *sec;
1450 struct file_view *view;
1454 size = ROUND_SIZE( module, size );
1455 base = ROUND_ADDR( module, page_mask );
1456 server_enter_uninterrupted_section( &csVirtual, &sigset );
1457 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1458 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1459 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1460 server_leave_uninterrupted_section( &csVirtual, &sigset );
1462 if (status) return status;
1464 /* The PE header is always read-only, no write, no execute. */
1465 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1467 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1468 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1470 BYTE flags = VPROT_COMMITTED;
1472 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1473 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1474 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1475 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1476 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1483 /***********************************************************************
1484 * virtual_alloc_thread_stack
1486 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1488 struct file_view *view;
1493 if (!reserve_size || !commit_size)
1495 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1496 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1497 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1500 size = max( reserve_size, commit_size );
1501 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1502 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1504 server_enter_uninterrupted_section( &csVirtual, &sigset );
1506 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1507 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1510 #ifdef VALGRIND_STACK_REGISTER
1511 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1514 /* setup no access guard page */
1515 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1516 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1517 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1519 /* note: limit is lower than base since the stack grows down */
1520 teb->DeallocationStack = view->base;
1521 teb->Tib.StackBase = (char *)view->base + view->size;
1522 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1524 server_leave_uninterrupted_section( &csVirtual, &sigset );
1529 /***********************************************************************
1530 * virtual_clear_thread_stack
1532 * Clear the stack contents before calling the main entry point, some broken apps need that.
1534 void virtual_clear_thread_stack(void)
1536 void *stack = NtCurrentTeb()->Tib.StackLimit;
1537 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1539 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1540 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1544 /***********************************************************************
1545 * virtual_handle_fault
1547 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1549 struct file_view *view;
1550 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1553 server_enter_uninterrupted_section( &csVirtual, &sigset );
1554 if ((view = VIRTUAL_FindView( addr, 0 )))
1556 void *page = ROUND_ADDR( addr, page_mask );
1557 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1558 if (*vprot & VPROT_GUARD)
1560 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1561 ret = STATUS_GUARD_PAGE_VIOLATION;
1563 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1565 if (*vprot & VPROT_WRITEWATCH)
1567 *vprot &= ~VPROT_WRITEWATCH;
1568 VIRTUAL_SetProt( view, page, page_size, *vprot );
1570 /* ignore fault if page is writable now */
1571 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1574 server_leave_uninterrupted_section( &csVirtual, &sigset );
1580 /***********************************************************************
1581 * virtual_handle_stack_fault
1583 * Handle an access fault inside the current thread stack.
1584 * Called from inside a signal handler.
1586 BOOL virtual_handle_stack_fault( void *addr )
1588 struct file_view *view;
1591 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1592 if ((view = VIRTUAL_FindView( addr, 0 )))
1594 void *page = ROUND_ADDR( addr, page_mask );
1595 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1596 if (vprot & VPROT_GUARD)
1598 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1599 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1600 NtCurrentTeb()->Tib.StackLimit = page;
1604 RtlLeaveCriticalSection( &csVirtual );
1609 /***********************************************************************
1610 * virtual_check_buffer_for_read
1612 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1614 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1616 if (!size) return TRUE;
1617 if (!ptr) return FALSE;
1621 volatile const char *p = ptr;
1623 SIZE_T count = size;
1625 while (count > page_size)
1632 dummy = p[count - 1];
1643 /***********************************************************************
1644 * virtual_check_buffer_for_write
1646 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1648 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1650 if (!size) return TRUE;
1651 if (!ptr) return FALSE;
1655 volatile char *p = ptr;
1656 SIZE_T count = size;
1658 while (count > page_size)
1676 /***********************************************************************
1677 * VIRTUAL_SetForceExec
1679 * Whether to force exec prot on all views.
1681 void VIRTUAL_SetForceExec( BOOL enable )
1683 struct file_view *view;
1686 server_enter_uninterrupted_section( &csVirtual, &sigset );
1687 if (!force_exec_prot != !enable) /* change all existing views */
1689 force_exec_prot = enable;
1691 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1694 char *addr = view->base;
1695 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1696 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1698 if (view->protect & VPROT_NOEXEC) continue;
1699 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1701 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1702 if (prot == unix_prot) continue;
1703 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1705 TRACE( "%s exec prot for %p-%p\n",
1706 force_exec_prot ? "enabling" : "disabling",
1707 addr, addr + (count << page_shift) - 1 );
1708 mprotect( addr, count << page_shift,
1709 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1711 addr += (count << page_shift);
1717 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1719 TRACE( "%s exec prot for %p-%p\n",
1720 force_exec_prot ? "enabling" : "disabling",
1721 addr, addr + (count << page_shift) - 1 );
1722 mprotect( addr, count << page_shift,
1723 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1728 server_leave_uninterrupted_section( &csVirtual, &sigset );
1737 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1738 static int free_reserved_memory( void *base, size_t size, void *arg )
1740 struct free_range *range = arg;
1742 if ((char *)base >= range->limit) return 0;
1743 if ((char *)base + size <= range->base) return 0;
1744 if ((char *)base < range->base)
1746 size -= range->base - (char *)base;
1749 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1750 remove_reserved_area( base, size );
1751 return 1; /* stop enumeration since the list has changed */
1754 /***********************************************************************
1755 * virtual_release_address_space
1757 * Release some address space once we have loaded and initialized the app.
1759 void virtual_release_address_space( BOOL free_high_mem )
1761 struct free_range range;
1764 if (user_space_limit == address_space_limit) return; /* no need to free anything */
1766 server_enter_uninterrupted_section( &csVirtual, &sigset );
1768 /* no large address space on win9x */
1769 if (free_high_mem && NtCurrentTeb()->Peb->OSPlatformId == VER_PLATFORM_WIN32_NT)
1771 range.base = (char *)0x82000000;
1772 range.limit = address_space_limit;
1773 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1774 user_space_limit = working_set_limit = address_space_limit;
1778 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1779 range.base = (char *)0x20000000;
1780 range.limit = (char *)0x7f000000;
1781 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1785 server_leave_uninterrupted_section( &csVirtual, &sigset );
1789 /***********************************************************************
1790 * NtAllocateVirtualMemory (NTDLL.@)
1791 * ZwAllocateVirtualMemory (NTDLL.@)
1793 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1794 SIZE_T *size_ptr, ULONG type, ULONG protect )
1798 SIZE_T size = *size_ptr;
1799 SIZE_T mask = get_mask( zero_bits );
1800 NTSTATUS status = STATUS_SUCCESS;
1801 struct file_view *view;
1804 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1806 if (!size) return STATUS_INVALID_PARAMETER;
1808 if (process != NtCurrentProcess())
1811 apc_result_t result;
1813 memset( &call, 0, sizeof(call) );
1815 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1816 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1817 call.virtual_alloc.size = *size_ptr;
1818 call.virtual_alloc.zero_bits = zero_bits;
1819 call.virtual_alloc.op_type = type;
1820 call.virtual_alloc.prot = protect;
1821 status = NTDLL_queue_process_apc( process, &call, &result );
1822 if (status != STATUS_SUCCESS) return status;
1824 if (result.virtual_alloc.status == STATUS_SUCCESS)
1826 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1827 *size_ptr = result.virtual_alloc.size;
1829 return result.virtual_alloc.status;
1832 /* Round parameters to a page boundary */
1834 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1836 if ((status = get_vprot_flags( protect, &vprot ))) return status;
1837 vprot |= VPROT_VALLOC;
1838 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1842 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1843 base = ROUND_ADDR( *ret, mask );
1845 base = ROUND_ADDR( *ret, page_mask );
1846 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1848 /* address 1 is magic to mean DOS area */
1849 if (!base && *ret == (void *)1 && size == 0x110000)
1851 server_enter_uninterrupted_section( &csVirtual, &sigset );
1852 status = allocate_dos_memory( &view, vprot );
1853 if (status == STATUS_SUCCESS)
1856 *size_ptr = view->size;
1858 server_leave_uninterrupted_section( &csVirtual, &sigset );
1862 /* disallow low 64k, wrap-around and kernel space */
1863 if (((char *)base < (char *)0x10000) ||
1864 ((char *)base + size < (char *)base) ||
1865 is_beyond_limit( base, size, address_space_limit ))
1866 return STATUS_INVALID_PARAMETER;
1871 size = (size + page_mask) & ~page_mask;
1874 /* Compute the alloc type flags */
1876 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1877 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1879 WARN("called with wrong alloc type flags (%08x) !\n", type);
1880 return STATUS_INVALID_PARAMETER;
1883 /* Reserve the memory */
1885 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1887 if ((type & MEM_RESERVE) || !base)
1889 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1890 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1891 if (status == STATUS_SUCCESS) base = view->base;
1893 else if (type & MEM_RESET)
1895 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1896 else madvise( base, size, MADV_DONTNEED );
1898 else /* commit the pages */
1900 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1901 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1902 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1904 SERVER_START_REQ( add_mapping_committed_range )
1906 req->handle = wine_server_obj_handle( view->mapping );
1907 req->offset = (char *)base - (char *)view->base;
1909 wine_server_call( req );
1915 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1917 if (status == STATUS_SUCCESS)
1926 /***********************************************************************
1927 * NtFreeVirtualMemory (NTDLL.@)
1928 * ZwFreeVirtualMemory (NTDLL.@)
1930 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1932 struct file_view *view;
1935 NTSTATUS status = STATUS_SUCCESS;
1936 LPVOID addr = *addr_ptr;
1937 SIZE_T size = *size_ptr;
1939 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1941 if (process != NtCurrentProcess())
1944 apc_result_t result;
1946 memset( &call, 0, sizeof(call) );
1948 call.virtual_free.type = APC_VIRTUAL_FREE;
1949 call.virtual_free.addr = wine_server_client_ptr( addr );
1950 call.virtual_free.size = size;
1951 call.virtual_free.op_type = type;
1952 status = NTDLL_queue_process_apc( process, &call, &result );
1953 if (status != STATUS_SUCCESS) return status;
1955 if (result.virtual_free.status == STATUS_SUCCESS)
1957 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
1958 *size_ptr = result.virtual_free.size;
1960 return result.virtual_free.status;
1963 /* Fix the parameters */
1965 size = ROUND_SIZE( addr, size );
1966 base = ROUND_ADDR( addr, page_mask );
1968 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1969 if (!base) return STATUS_INVALID_PARAMETER;
1971 server_enter_uninterrupted_section( &csVirtual, &sigset );
1973 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
1975 status = STATUS_INVALID_PARAMETER;
1977 else if (type == MEM_RELEASE)
1979 /* Free the pages */
1981 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1984 delete_view( view );
1989 else if (type == MEM_DECOMMIT)
1991 status = decommit_pages( view, base - (char *)view->base, size );
1992 if (status == STATUS_SUCCESS)
2000 WARN("called with wrong free type flags (%08x) !\n", type);
2001 status = STATUS_INVALID_PARAMETER;
2004 server_leave_uninterrupted_section( &csVirtual, &sigset );
2009 /***********************************************************************
2010 * NtProtectVirtualMemory (NTDLL.@)
2011 * ZwProtectVirtualMemory (NTDLL.@)
2013 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2014 ULONG new_prot, ULONG *old_prot )
2016 struct file_view *view;
2018 NTSTATUS status = STATUS_SUCCESS;
2021 unsigned int new_vprot;
2022 SIZE_T size = *size_ptr;
2023 LPVOID addr = *addr_ptr;
2025 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2027 if (process != NtCurrentProcess())
2030 apc_result_t result;
2032 memset( &call, 0, sizeof(call) );
2034 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2035 call.virtual_protect.addr = wine_server_client_ptr( addr );
2036 call.virtual_protect.size = size;
2037 call.virtual_protect.prot = new_prot;
2038 status = NTDLL_queue_process_apc( process, &call, &result );
2039 if (status != STATUS_SUCCESS) return status;
2041 if (result.virtual_protect.status == STATUS_SUCCESS)
2043 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2044 *size_ptr = result.virtual_protect.size;
2045 if (old_prot) *old_prot = result.virtual_protect.prot;
2047 return result.virtual_protect.status;
2050 /* Fix the parameters */
2052 size = ROUND_SIZE( addr, size );
2053 base = ROUND_ADDR( addr, page_mask );
2054 if ((status = get_vprot_flags( new_prot, &new_vprot ))) return status;
2055 new_vprot |= VPROT_COMMITTED;
2057 server_enter_uninterrupted_section( &csVirtual, &sigset );
2059 if (!(view = VIRTUAL_FindView( base, size )))
2061 status = STATUS_INVALID_PARAMETER;
2065 /* Make sure all the pages are committed */
2066 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2068 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2069 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2071 else status = STATUS_NOT_COMMITTED;
2073 server_leave_uninterrupted_section( &csVirtual, &sigset );
2075 if (status == STATUS_SUCCESS)
2084 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2085 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2087 MEMORY_BASIC_INFORMATION *info = arg;
2088 void *end = (char *)start + size;
2090 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2092 if (info->BaseAddress >= end)
2094 if (info->AllocationBase < end) info->AllocationBase = end;
2098 if (info->BaseAddress >= start || start <= address_space_start)
2100 /* it's a real free area */
2101 info->State = MEM_FREE;
2102 info->Protect = PAGE_NOACCESS;
2103 info->AllocationBase = 0;
2104 info->AllocationProtect = 0;
2106 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2107 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2109 else /* outside of the reserved area, pretend it's allocated */
2111 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2112 info->State = MEM_RESERVE;
2113 info->Protect = PAGE_NOACCESS;
2114 info->AllocationProtect = PAGE_NOACCESS;
2115 info->Type = MEM_PRIVATE;
2120 #define UNIMPLEMENTED_INFO_CLASS(c) \
2122 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2123 return STATUS_INVALID_INFO_CLASS
2125 /***********************************************************************
2126 * NtQueryVirtualMemory (NTDLL.@)
2127 * ZwQueryVirtualMemory (NTDLL.@)
2129 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2130 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2131 SIZE_T len, SIZE_T *res_len )
2133 struct file_view *view;
2134 char *base, *alloc_base = 0;
2137 MEMORY_BASIC_INFORMATION *info = buffer;
2140 if (info_class != MemoryBasicInformation)
2144 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2145 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2146 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2149 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2150 process, addr, info_class, buffer, len, res_len);
2151 return STATUS_INVALID_INFO_CLASS;
2155 if (process != NtCurrentProcess())
2159 apc_result_t result;
2161 memset( &call, 0, sizeof(call) );
2163 call.virtual_query.type = APC_VIRTUAL_QUERY;
2164 call.virtual_query.addr = wine_server_client_ptr( addr );
2165 status = NTDLL_queue_process_apc( process, &call, &result );
2166 if (status != STATUS_SUCCESS) return status;
2168 if (result.virtual_query.status == STATUS_SUCCESS)
2170 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2171 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2172 info->RegionSize = result.virtual_query.size;
2173 info->Protect = result.virtual_query.prot;
2174 info->AllocationProtect = result.virtual_query.alloc_prot;
2175 info->State = (DWORD)result.virtual_query.state << 12;
2176 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2177 if (info->RegionSize != result.virtual_query.size) /* truncated */
2178 return STATUS_INVALID_PARAMETER; /* FIXME */
2179 if (res_len) *res_len = sizeof(*info);
2181 return result.virtual_query.status;
2184 base = ROUND_ADDR( addr, page_mask );
2186 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2188 /* Find the view containing the address */
2190 server_enter_uninterrupted_section( &csVirtual, &sigset );
2191 ptr = list_head( &views_list );
2196 size = (char *)working_set_limit - alloc_base;
2200 view = LIST_ENTRY( ptr, struct file_view, entry );
2201 if ((char *)view->base > base)
2203 size = (char *)view->base - alloc_base;
2207 if ((char *)view->base + view->size > base)
2209 alloc_base = view->base;
2213 alloc_base = (char *)view->base + view->size;
2214 ptr = list_next( &views_list, ptr );
2217 /* Fill the info structure */
2219 info->AllocationBase = alloc_base;
2220 info->BaseAddress = base;
2221 info->RegionSize = size - (base - alloc_base);
2225 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2227 /* not in a reserved area at all, pretend it's allocated */
2229 if (base >= (char *)address_space_start)
2231 info->State = MEM_RESERVE;
2232 info->Protect = PAGE_NOACCESS;
2233 info->AllocationProtect = PAGE_NOACCESS;
2234 info->Type = MEM_PRIVATE;
2239 info->State = MEM_FREE;
2240 info->Protect = PAGE_NOACCESS;
2241 info->AllocationBase = 0;
2242 info->AllocationProtect = 0;
2250 SIZE_T range_size = get_committed_size( view, base, &vprot );
2252 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2253 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2254 info->AllocationBase = alloc_base;
2255 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2256 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2257 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2258 else info->Type = MEM_MAPPED;
2259 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2260 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2261 info->RegionSize = size - (base - alloc_base);
2263 server_leave_uninterrupted_section( &csVirtual, &sigset );
2265 if (res_len) *res_len = sizeof(*info);
2266 return STATUS_SUCCESS;
2270 /***********************************************************************
2271 * NtLockVirtualMemory (NTDLL.@)
2272 * ZwLockVirtualMemory (NTDLL.@)
2274 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2276 NTSTATUS status = STATUS_SUCCESS;
2278 if (process != NtCurrentProcess())
2281 apc_result_t result;
2283 memset( &call, 0, sizeof(call) );
2285 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2286 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2287 call.virtual_lock.size = *size;
2288 status = NTDLL_queue_process_apc( process, &call, &result );
2289 if (status != STATUS_SUCCESS) return status;
2291 if (result.virtual_lock.status == STATUS_SUCCESS)
2293 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2294 *size = result.virtual_lock.size;
2296 return result.virtual_lock.status;
2299 *size = ROUND_SIZE( *addr, *size );
2300 *addr = ROUND_ADDR( *addr, page_mask );
2302 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2307 /***********************************************************************
2308 * NtUnlockVirtualMemory (NTDLL.@)
2309 * ZwUnlockVirtualMemory (NTDLL.@)
2311 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2313 NTSTATUS status = STATUS_SUCCESS;
2315 if (process != NtCurrentProcess())
2318 apc_result_t result;
2320 memset( &call, 0, sizeof(call) );
2322 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2323 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2324 call.virtual_unlock.size = *size;
2325 status = NTDLL_queue_process_apc( process, &call, &result );
2326 if (status != STATUS_SUCCESS) return status;
2328 if (result.virtual_unlock.status == STATUS_SUCCESS)
2330 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2331 *size = result.virtual_unlock.size;
2333 return result.virtual_unlock.status;
2336 *size = ROUND_SIZE( *addr, *size );
2337 *addr = ROUND_ADDR( *addr, page_mask );
2339 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2344 /***********************************************************************
2345 * NtCreateSection (NTDLL.@)
2346 * ZwCreateSection (NTDLL.@)
2348 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2349 const LARGE_INTEGER *size, ULONG protect,
2350 ULONG sec_flags, HANDLE file )
2354 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2355 struct security_descriptor *sd = NULL;
2356 struct object_attributes objattr;
2358 /* Check parameters */
2360 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2362 if ((ret = get_vprot_flags( protect, &vprot ))) return ret;
2364 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2366 objattr.name_len = len;
2369 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2370 if (ret != STATUS_SUCCESS) return ret;
2373 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2374 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2375 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2377 /* Create the server object */
2379 SERVER_START_REQ( create_mapping )
2381 req->access = access;
2382 req->attributes = (attr) ? attr->Attributes : 0;
2383 req->file_handle = wine_server_obj_handle( file );
2384 req->size = size ? size->QuadPart : 0;
2385 req->protect = vprot;
2386 wine_server_add_data( req, &objattr, sizeof(objattr) );
2387 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2388 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2389 ret = wine_server_call( req );
2390 *handle = wine_server_ptr_handle( reply->handle );
2394 NTDLL_free_struct_sd( sd );
2400 /***********************************************************************
2401 * NtOpenSection (NTDLL.@)
2402 * ZwOpenSection (NTDLL.@)
2404 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2407 DWORD len = attr->ObjectName->Length;
2409 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2411 SERVER_START_REQ( open_mapping )
2413 req->access = access;
2414 req->attributes = attr->Attributes;
2415 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2416 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2417 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2424 /***********************************************************************
2425 * NtMapViewOfSection (NTDLL.@)
2426 * ZwMapViewOfSection (NTDLL.@)
2428 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2429 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2430 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2433 mem_size_t full_size;
2435 SIZE_T size, mask = get_mask( zero_bits );
2436 int unix_handle = -1, needs_close;
2437 unsigned int map_vprot, vprot;
2439 struct file_view *view;
2441 HANDLE dup_mapping, shared_file;
2442 LARGE_INTEGER offset;
2445 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2447 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2448 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2450 /* Check parameters */
2452 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2453 return STATUS_INVALID_PARAMETER;
2460 case PAGE_READWRITE:
2461 case PAGE_EXECUTE_READWRITE:
2462 access = SECTION_MAP_WRITE;
2465 case PAGE_WRITECOPY:
2467 case PAGE_EXECUTE_READ:
2468 case PAGE_EXECUTE_WRITECOPY:
2469 access = SECTION_MAP_READ;
2472 return STATUS_INVALID_PARAMETER;
2475 if (process != NtCurrentProcess())
2478 apc_result_t result;
2480 memset( &call, 0, sizeof(call) );
2482 call.map_view.type = APC_MAP_VIEW;
2483 call.map_view.handle = wine_server_obj_handle( handle );
2484 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2485 call.map_view.size = *size_ptr;
2486 call.map_view.offset = offset.QuadPart;
2487 call.map_view.zero_bits = zero_bits;
2488 call.map_view.alloc_type = alloc_type;
2489 call.map_view.prot = protect;
2490 res = NTDLL_queue_process_apc( process, &call, &result );
2491 if (res != STATUS_SUCCESS) return res;
2493 if ((NTSTATUS)result.map_view.status >= 0)
2495 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2496 *size_ptr = result.map_view.size;
2498 return result.map_view.status;
2501 SERVER_START_REQ( get_mapping_info )
2503 req->handle = wine_server_obj_handle( handle );
2504 req->access = access;
2505 res = wine_server_call( req );
2506 map_vprot = reply->protect;
2507 base = wine_server_get_ptr( reply->base );
2508 full_size = reply->size;
2509 header_size = reply->header_size;
2510 dup_mapping = wine_server_ptr_handle( reply->mapping );
2511 shared_file = wine_server_ptr_handle( reply->shared_file );
2512 if ((ULONG_PTR)base != reply->base) base = NULL;
2515 if (res) return res;
2517 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2519 if (map_vprot & VPROT_IMAGE)
2522 if (size != full_size) /* truncated */
2524 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2525 res = STATUS_INVALID_PARAMETER;
2530 int shared_fd, shared_needs_close;
2532 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2533 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2534 res = map_image( handle, unix_handle, base, size, mask, header_size,
2535 shared_fd, dup_mapping, addr_ptr );
2536 if (shared_needs_close) close( shared_fd );
2537 NtClose( shared_file );
2541 res = map_image( handle, unix_handle, base, size, mask, header_size,
2542 -1, dup_mapping, addr_ptr );
2544 if (needs_close) close( unix_handle );
2545 if (res >= 0) *size_ptr = size;
2549 res = STATUS_INVALID_PARAMETER;
2550 if (offset.QuadPart >= full_size) goto done;
2553 if (*size_ptr > full_size - offset.QuadPart) goto done;
2554 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2555 if (size < *size_ptr) goto done; /* wrap-around */
2559 size = full_size - offset.QuadPart;
2560 if (size != full_size - offset.QuadPart) /* truncated */
2562 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2563 wine_dbgstr_longlong(full_size) );
2568 /* Reserve a properly aligned area */
2570 server_enter_uninterrupted_section( &csVirtual, &sigset );
2572 get_vprot_flags( protect, &vprot );
2573 vprot |= (map_vprot & VPROT_COMMITTED);
2574 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2577 server_leave_uninterrupted_section( &csVirtual, &sigset );
2583 TRACE("handle=%p size=%lx offset=%x%08x\n",
2584 handle, size, offset.u.HighPart, offset.u.LowPart );
2586 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2587 if (res == STATUS_SUCCESS)
2589 *addr_ptr = view->base;
2591 view->mapping = dup_mapping;
2592 dup_mapping = 0; /* don't close it */
2596 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2597 view->base, size, offset.u.HighPart, offset.u.LowPart );
2598 delete_view( view );
2601 server_leave_uninterrupted_section( &csVirtual, &sigset );
2604 if (dup_mapping) NtClose( dup_mapping );
2605 if (needs_close) close( unix_handle );
2610 /***********************************************************************
2611 * NtUnmapViewOfSection (NTDLL.@)
2612 * ZwUnmapViewOfSection (NTDLL.@)
2614 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2616 struct file_view *view;
2617 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2619 void *base = ROUND_ADDR( addr, page_mask );
2621 if (process != NtCurrentProcess())
2624 apc_result_t result;
2626 memset( &call, 0, sizeof(call) );
2628 call.unmap_view.type = APC_UNMAP_VIEW;
2629 call.unmap_view.addr = wine_server_client_ptr( addr );
2630 status = NTDLL_queue_process_apc( process, &call, &result );
2631 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2635 server_enter_uninterrupted_section( &csVirtual, &sigset );
2636 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2638 delete_view( view );
2639 status = STATUS_SUCCESS;
2641 server_leave_uninterrupted_section( &csVirtual, &sigset );
2646 /***********************************************************************
2647 * NtFlushVirtualMemory (NTDLL.@)
2648 * ZwFlushVirtualMemory (NTDLL.@)
2650 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2651 SIZE_T *size_ptr, ULONG unknown )
2653 struct file_view *view;
2654 NTSTATUS status = STATUS_SUCCESS;
2656 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2658 if (process != NtCurrentProcess())
2661 apc_result_t result;
2663 memset( &call, 0, sizeof(call) );
2665 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2666 call.virtual_flush.addr = wine_server_client_ptr( addr );
2667 call.virtual_flush.size = *size_ptr;
2668 status = NTDLL_queue_process_apc( process, &call, &result );
2669 if (status != STATUS_SUCCESS) return status;
2671 if (result.virtual_flush.status == STATUS_SUCCESS)
2673 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2674 *size_ptr = result.virtual_flush.size;
2676 return result.virtual_flush.status;
2679 server_enter_uninterrupted_section( &csVirtual, &sigset );
2680 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2683 if (!*size_ptr) *size_ptr = view->size;
2685 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2687 server_leave_uninterrupted_section( &csVirtual, &sigset );
2692 /***********************************************************************
2693 * NtGetWriteWatch (NTDLL.@)
2694 * ZwGetWriteWatch (NTDLL.@)
2696 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2697 ULONG_PTR *count, ULONG *granularity )
2699 struct file_view *view;
2700 NTSTATUS status = STATUS_SUCCESS;
2703 size = ROUND_SIZE( base, size );
2704 base = ROUND_ADDR( base, page_mask );
2706 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2707 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2708 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2710 if (!addresses) return STATUS_ACCESS_VIOLATION;
2712 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2713 addresses, *count );
2715 server_enter_uninterrupted_section( &csVirtual, &sigset );
2717 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2721 char *end = addr + size;
2723 while (pos < *count && addr < end)
2725 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2726 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2729 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2731 *granularity = page_size;
2733 else status = STATUS_INVALID_PARAMETER;
2735 server_leave_uninterrupted_section( &csVirtual, &sigset );
2740 /***********************************************************************
2741 * NtResetWriteWatch (NTDLL.@)
2742 * ZwResetWriteWatch (NTDLL.@)
2744 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2746 struct file_view *view;
2747 NTSTATUS status = STATUS_SUCCESS;
2750 size = ROUND_SIZE( base, size );
2751 base = ROUND_ADDR( base, page_mask );
2753 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2755 if (!size) return STATUS_INVALID_PARAMETER;
2757 server_enter_uninterrupted_section( &csVirtual, &sigset );
2759 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2760 reset_write_watches( view, base, size );
2762 status = STATUS_INVALID_PARAMETER;
2764 server_leave_uninterrupted_section( &csVirtual, &sigset );
2769 /***********************************************************************
2770 * NtReadVirtualMemory (NTDLL.@)
2771 * ZwReadVirtualMemory (NTDLL.@)
2773 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2774 SIZE_T size, SIZE_T *bytes_read )
2778 if (virtual_check_buffer_for_write( buffer, size ))
2780 SERVER_START_REQ( read_process_memory )
2782 req->handle = wine_server_obj_handle( process );
2783 req->addr = wine_server_client_ptr( addr );
2784 wine_server_set_reply( req, buffer, size );
2785 if ((status = wine_server_call( req ))) size = 0;
2791 status = STATUS_ACCESS_VIOLATION;
2794 if (bytes_read) *bytes_read = size;
2799 /***********************************************************************
2800 * NtWriteVirtualMemory (NTDLL.@)
2801 * ZwWriteVirtualMemory (NTDLL.@)
2803 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2804 SIZE_T size, SIZE_T *bytes_written )
2808 if (virtual_check_buffer_for_read( buffer, size ))
2810 SERVER_START_REQ( write_process_memory )
2812 req->handle = wine_server_obj_handle( process );
2813 req->addr = wine_server_client_ptr( addr );
2814 wine_server_add_data( req, buffer, size );
2815 if ((status = wine_server_call( req ))) size = 0;
2821 status = STATUS_PARTIAL_COPY;
2824 if (bytes_written) *bytes_written = size;
2829 /***********************************************************************
2830 * NtAreMappedFilesTheSame (NTDLL.@)
2831 * ZwAreMappedFilesTheSame (NTDLL.@)
2833 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2835 struct file_view *view1, *view2;
2836 struct stat st1, st2;
2840 TRACE("%p %p\n", addr1, addr2);
2842 server_enter_uninterrupted_section( &csVirtual, &sigset );
2844 view1 = VIRTUAL_FindView( addr1, 0 );
2845 view2 = VIRTUAL_FindView( addr2, 0 );
2847 if (!view1 || !view2)
2848 status = STATUS_INVALID_ADDRESS;
2849 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2850 status = STATUS_CONFLICTING_ADDRESSES;
2851 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2852 status = STATUS_NOT_SAME_DEVICE;
2853 else if (view1 == view2)
2854 status = STATUS_SUCCESS;
2855 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2856 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2857 status = STATUS_SUCCESS;
2859 status = STATUS_NOT_SAME_DEVICE;
2861 server_leave_uninterrupted_section( &csVirtual, &sigset );