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
73 typedef struct file_view
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 #elif defined(__x86_64__)
126 # define page_mask 0xfff
127 # define page_shift 12
128 # define page_size 0x1000
129 static void *address_space_limit = (void *)0x7fffffff0000;
130 static void *user_space_limit = (void *)0x7fffffff0000;
131 static void *working_set_limit = (void *)0x7fffffff0000;
133 static UINT page_shift;
134 static UINT_PTR page_size;
135 static UINT_PTR page_mask;
136 static void *address_space_limit;
137 static void *user_space_limit;
138 static void *working_set_limit;
139 #endif /* __i386__ */
141 #define ROUND_ADDR(addr,mask) \
142 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
144 #define ROUND_SIZE(addr,size) \
145 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
147 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
148 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
150 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
152 static HANDLE virtual_heap;
153 static void *preload_reserve_start;
154 static void *preload_reserve_end;
155 static int use_locks;
156 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
159 /***********************************************************************
162 static const char *VIRTUAL_GetProtStr( BYTE prot )
164 static char buffer[6];
165 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
166 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
167 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
168 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
169 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
175 /***********************************************************************
176 * VIRTUAL_GetUnixProt
178 * Convert page protections to protection for mmap/mprotect.
180 static int VIRTUAL_GetUnixProt( BYTE vprot )
183 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
185 if (vprot & VPROT_READ) prot |= PROT_READ;
186 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
187 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
188 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
189 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
191 if (!prot) prot = PROT_NONE;
196 /***********************************************************************
199 static void VIRTUAL_DumpView( FILE_VIEW *view )
202 char *addr = view->base;
203 BYTE prot = view->prot[0];
205 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
206 if (view->protect & VPROT_SYSTEM)
207 TRACE( " (system)\n" );
208 else if (view->protect & VPROT_VALLOC)
209 TRACE( " (valloc)\n" );
210 else if (view->mapping)
211 TRACE( " %p\n", view->mapping );
213 TRACE( " (anonymous)\n");
215 for (count = i = 1; i < view->size >> page_shift; i++, count++)
217 if (view->prot[i] == prot) continue;
218 TRACE( " %p - %p %s\n",
219 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
220 addr += (count << page_shift);
221 prot = view->prot[i];
225 TRACE( " %p - %p %s\n",
226 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
230 /***********************************************************************
234 static void VIRTUAL_Dump(void)
237 struct file_view *view;
239 TRACE( "Dump of all virtual memory views:\n" );
240 server_enter_uninterrupted_section( &csVirtual, &sigset );
241 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
243 VIRTUAL_DumpView( view );
245 server_leave_uninterrupted_section( &csVirtual, &sigset );
250 /***********************************************************************
253 * Find the view containing a given address. The csVirtual section must be held by caller.
262 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
264 struct file_view *view;
266 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
268 if (view->base > addr) break; /* no matching view */
269 if ((const char *)view->base + view->size <= (const char *)addr) continue;
270 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
271 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
278 /***********************************************************************
281 static inline UINT_PTR get_mask( ULONG zero_bits )
283 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
284 if (zero_bits < page_shift) zero_bits = page_shift;
285 return (1 << zero_bits) - 1;
289 /***********************************************************************
292 * Find the first view overlapping at least part of the specified range.
293 * The csVirtual section must be held by caller.
295 static struct file_view *find_view_range( const void *addr, size_t size )
297 struct file_view *view;
299 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
301 if ((const char *)view->base >= (const char *)addr + size) break;
302 if ((const char *)view->base + view->size > (const char *)addr) return view;
308 /***********************************************************************
311 * Find a free area between views inside the specified range.
312 * The csVirtual section must be held by caller.
314 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
321 start = ROUND_ADDR( (char *)end - size, mask );
322 if (start >= end || start < base) return NULL;
324 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
326 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
328 if ((char *)view->base + view->size <= (char *)start) break;
329 if ((char *)view->base >= (char *)start + size) continue;
330 start = ROUND_ADDR( (char *)view->base - size, mask );
331 /* stop if remaining space is not large enough */
332 if (!start || start >= end || start < base) return NULL;
337 start = ROUND_ADDR( (char *)base + mask, mask );
338 if (start >= end || (char *)end - (char *)start < size) return NULL;
340 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
342 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
344 if ((char *)view->base >= (char *)start + size) break;
345 if ((char *)view->base + view->size <= (char *)start) continue;
346 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
347 /* stop if remaining space is not large enough */
348 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
355 /***********************************************************************
358 * Add a reserved area to the list maintained by libwine.
359 * The csVirtual section must be held by caller.
361 static void add_reserved_area( void *addr, size_t size )
363 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
365 if (addr < user_space_limit)
367 /* unmap the part of the area that is below the limit */
368 assert( (char *)addr + size > (char *)user_space_limit );
369 munmap( addr, (char *)user_space_limit - (char *)addr );
370 size -= (char *)user_space_limit - (char *)addr;
371 addr = user_space_limit;
373 /* blow away existing mappings */
374 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
375 wine_mmap_add_reserved_area( addr, size );
379 /***********************************************************************
380 * remove_reserved_area
382 * Remove a reserved area from the list maintained by libwine.
383 * The csVirtual section must be held by caller.
385 static void remove_reserved_area( void *addr, size_t size )
387 struct file_view *view;
389 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
390 wine_mmap_remove_reserved_area( addr, size, 0 );
392 /* unmap areas not covered by an existing view */
393 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
395 if ((char *)view->base >= (char *)addr + size)
397 munmap( addr, size );
400 if ((char *)view->base + view->size <= (char *)addr) continue;
401 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
402 if ((char *)view->base + view->size > (char *)addr + size) break;
403 size = (char *)addr + size - ((char *)view->base + view->size);
404 addr = (char *)view->base + view->size;
409 /***********************************************************************
412 * Check if an address range goes beyond a given limit.
414 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
416 return (addr >= limit || (const char *)addr + size > (const char *)limit);
420 /***********************************************************************
423 * Unmap an area, or simply replace it by an empty mapping if it is
424 * in a reserved area. The csVirtual section must be held by caller.
426 static inline void unmap_area( void *addr, size_t size )
428 if (wine_mmap_is_in_reserved_area( addr, size ))
429 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
430 else if (is_beyond_limit( addr, size, user_space_limit ))
431 add_reserved_area( addr, size );
433 munmap( addr, size );
437 /***********************************************************************
440 * Deletes a view. The csVirtual section must be held by caller.
442 static void delete_view( struct file_view *view ) /* [in] View */
444 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
445 list_remove( &view->entry );
446 if (view->mapping) NtClose( view->mapping );
447 RtlFreeHeap( virtual_heap, 0, view );
451 /***********************************************************************
454 * Create a view. The csVirtual section must be held by caller.
456 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
458 struct file_view *view;
460 int unix_prot = VIRTUAL_GetUnixProt( vprot );
462 assert( !((UINT_PTR)base & page_mask) );
463 assert( !(size & page_mask) );
465 /* Create the view structure */
467 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
469 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
470 return STATUS_NO_MEMORY;
476 view->protect = vprot;
477 memset( view->prot, vprot, size >> page_shift );
479 /* Insert it in the linked list */
481 LIST_FOR_EACH( ptr, &views_list )
483 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
484 if (next->base > base) break;
486 list_add_before( ptr, &view->entry );
488 /* Check for overlapping views. This can happen if the previous view
489 * was a system view that got unmapped behind our back. In that case
490 * we recover by simply deleting it. */
492 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
494 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
495 if ((char *)prev->base + prev->size > (char *)base)
497 TRACE( "overlapping prev view %p-%p for %p-%p\n",
498 prev->base, (char *)prev->base + prev->size,
499 base, (char *)base + view->size );
500 assert( prev->protect & VPROT_SYSTEM );
504 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
506 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
507 if ((char *)base + view->size > (char *)next->base)
509 TRACE( "overlapping next view %p-%p for %p-%p\n",
510 next->base, (char *)next->base + next->size,
511 base, (char *)base + view->size );
512 assert( next->protect & VPROT_SYSTEM );
518 VIRTUAL_DEBUG_DUMP_VIEW( view );
520 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
522 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
523 mprotect( base, size, unix_prot | PROT_EXEC );
525 return STATUS_SUCCESS;
529 /***********************************************************************
530 * VIRTUAL_GetWin32Prot
532 * Convert page protections to Win32 flags.
534 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
536 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
537 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
538 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
543 /***********************************************************************
546 * Build page protections from Win32 flags.
549 * protect [I] Win32 protection flags
552 * Value of page protection flags
554 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot )
556 switch(protect & 0xff)
562 *vprot = VPROT_READ | VPROT_WRITE;
565 *vprot = VPROT_READ | VPROT_WRITECOPY;
570 case PAGE_EXECUTE_READ:
571 *vprot = VPROT_EXEC | VPROT_READ;
573 case PAGE_EXECUTE_READWRITE:
574 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
576 case PAGE_EXECUTE_WRITECOPY:
577 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
583 return STATUS_INVALID_PARAMETER;
585 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
586 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
587 return STATUS_SUCCESS;
591 /***********************************************************************
594 * Change the protection of a range of pages.
600 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
601 void *base, /* [in] Starting address */
602 size_t size, /* [in] Size in bytes */
603 BYTE vprot ) /* [in] Protections to use */
605 int unix_prot = VIRTUAL_GetUnixProt(vprot);
606 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
609 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
611 if (view->protect & VPROT_WRITEWATCH)
613 /* each page may need different protections depending on write watch flag */
618 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
619 unix_prot = VIRTUAL_GetUnixProt( p[0] );
620 for (count = i = 1; i < size >> page_shift; i++, count++)
622 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
623 prot = VIRTUAL_GetUnixProt( p[i] );
624 if (prot == unix_prot) continue;
625 mprotect( addr, count << page_shift, unix_prot );
626 addr += count << page_shift;
630 if (count) mprotect( addr, count << page_shift, unix_prot );
631 VIRTUAL_DEBUG_DUMP_VIEW( view );
635 /* if setting stack guard pages, store the permissions first, as the guard may be
636 * triggered at any point after mprotect and change the permissions again */
637 if ((vprot & VPROT_GUARD) &&
638 (base >= NtCurrentTeb()->DeallocationStack) &&
639 (base < NtCurrentTeb()->Tib.StackBase))
641 memset( p, vprot, size >> page_shift );
642 mprotect( base, size, unix_prot );
643 VIRTUAL_DEBUG_DUMP_VIEW( view );
647 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
648 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
650 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
651 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
652 /* exec + write may legitimately fail, in that case fall back to write only */
653 if (!(unix_prot & PROT_WRITE)) return FALSE;
656 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
659 memset( p, vprot, size >> page_shift );
660 VIRTUAL_DEBUG_DUMP_VIEW( view );
665 /***********************************************************************
666 * reset_write_watches
668 * Reset write watches in a memory range.
670 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
675 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
677 p[0] |= VPROT_WRITEWATCH;
678 unix_prot = VIRTUAL_GetUnixProt( p[0] );
679 for (count = i = 1; i < size >> page_shift; i++, count++)
681 p[i] |= VPROT_WRITEWATCH;
682 prot = VIRTUAL_GetUnixProt( p[i] );
683 if (prot == unix_prot) continue;
684 mprotect( addr, count << page_shift, unix_prot );
685 addr += count << page_shift;
689 if (count) mprotect( addr, count << page_shift, unix_prot );
693 /***********************************************************************
696 * Release the extra memory while keeping the range starting on the granularity boundary.
698 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
700 if ((ULONG_PTR)ptr & mask)
702 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
703 munmap( ptr, extra );
704 ptr = (char *)ptr + extra;
707 if (total_size > wanted_size)
708 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
722 /***********************************************************************
723 * alloc_reserved_area_callback
725 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
727 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
729 static void * const address_space_start = (void *)0x110000;
730 struct alloc_area *alloc = arg;
731 void *end = (char *)start + size;
733 if (start < address_space_start) start = address_space_start;
734 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
735 if (start >= end) return 0;
737 /* make sure we don't touch the preloader reserved range */
738 if (preload_reserve_end >= start)
740 if (preload_reserve_end >= end)
742 if (preload_reserve_start <= start) return 0; /* no space in that area */
743 if (preload_reserve_start < end) end = preload_reserve_start;
745 else if (preload_reserve_start <= start) start = preload_reserve_end;
748 /* range is split in two by the preloader reservation, try first part */
749 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
750 alloc->mask, alloc->top_down )))
752 /* then fall through to try second part */
753 start = preload_reserve_end;
756 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
763 /***********************************************************************
766 * Create a view and mmap the corresponding memory area.
767 * The csVirtual section must be held by caller.
769 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
770 int top_down, unsigned int vprot )
777 if (is_beyond_limit( base, size, address_space_limit ))
778 return STATUS_WORKING_SET_LIMIT_RANGE;
780 switch (wine_mmap_is_in_reserved_area( base, size ))
782 case -1: /* partially in a reserved area */
783 return STATUS_CONFLICTING_ADDRESSES;
785 case 0: /* not in a reserved area, do a normal allocation */
786 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
788 if (errno == ENOMEM) return STATUS_NO_MEMORY;
789 return STATUS_INVALID_PARAMETER;
793 /* We couldn't get the address we wanted */
794 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
795 else munmap( ptr, size );
796 return STATUS_CONFLICTING_ADDRESSES;
801 case 1: /* in a reserved area, make sure the address is available */
802 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
803 /* replace the reserved area by our mapping */
804 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
805 return STATUS_INVALID_PARAMETER;
808 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
812 size_t view_size = size + mask + 1;
813 struct alloc_area alloc;
817 alloc.top_down = top_down;
818 alloc.limit = user_space_limit;
819 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
822 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
823 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
824 return STATUS_INVALID_PARAMETER;
830 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
832 if (errno == ENOMEM) return STATUS_NO_MEMORY;
833 return STATUS_INVALID_PARAMETER;
835 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
836 /* if we got something beyond the user limit, unmap it and retry */
837 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
840 ptr = unmap_extra_space( ptr, view_size, size, mask );
843 status = create_view( view_ret, ptr, size, vprot );
844 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
849 /***********************************************************************
852 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
853 * The csVirtual section must be held by caller.
855 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
856 off_t offset, unsigned int vprot, BOOL removable )
859 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
860 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
862 assert( start < view->size );
863 assert( start + size <= view->size );
865 /* only try mmap if media is not removable (or if we require write access) */
866 if (!removable || shared_write)
868 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
870 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
873 /* mmap() failed; if this is because the file offset is not */
874 /* page-aligned (EINVAL), or because the underlying filesystem */
875 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
876 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
877 if (shared_write) /* we cannot fake shared write mappings */
879 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
880 ERR( "shared writable mmap not supported, broken filesystem?\n" );
881 return STATUS_NOT_SUPPORTED;
885 /* Reserve the memory with an anonymous mmap */
886 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
887 if (ptr == (void *)-1) return FILE_GetNtStatus();
888 /* Now read in the file */
889 pread( fd, ptr, size, offset );
890 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
892 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
893 return STATUS_SUCCESS;
897 /***********************************************************************
900 * Get the size of the committed range starting at base.
901 * Also return the protections for the first page.
903 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
907 start = ((char *)base - (char *)view->base) >> page_shift;
908 *vprot = view->prot[start];
910 if (view->mapping && !(view->protect & VPROT_COMMITTED))
913 SERVER_START_REQ( get_mapping_committed_range )
915 req->handle = wine_server_obj_handle( view->mapping );
916 req->offset = start << page_shift;
917 if (!wine_server_call( req ))
920 if (reply->committed)
922 *vprot |= VPROT_COMMITTED;
923 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
930 for (i = start + 1; i < view->size >> page_shift; i++)
931 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
932 return (i - start) << page_shift;
936 /***********************************************************************
939 * Decommit some pages of a given view.
940 * The csVirtual section must be held by caller.
942 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
944 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
946 BYTE *p = view->prot + (start >> page_shift);
948 while (size--) *p++ &= ~VPROT_COMMITTED;
949 return STATUS_SUCCESS;
951 return FILE_GetNtStatus();
955 /***********************************************************************
956 * allocate_dos_memory
958 * Allocate the DOS memory range.
960 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
964 void * const low_64k = (void *)0x10000;
965 const size_t dosmem_size = 0x110000;
966 int unix_prot = VIRTUAL_GetUnixProt( vprot );
969 /* check for existing view */
971 if ((ptr = list_head( &views_list )))
973 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
974 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
977 /* check without the first 64K */
979 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
981 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
984 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
985 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
989 /* now try to allocate the low 64K too */
991 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
993 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
994 if (addr == (void *)page_size)
997 TRACE( "successfully mapped low 64K range\n" );
1001 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1003 TRACE( "failed to map low 64K range\n" );
1007 /* now reserve the whole range */
1009 size = (char *)dosmem_size - (char *)addr;
1010 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1011 return create_view( view, addr, size, vprot );
1015 /***********************************************************************
1018 * Map an executable (PE format) image into memory.
1020 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1021 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
1023 IMAGE_DOS_HEADER *dos;
1024 IMAGE_NT_HEADERS *nt;
1025 IMAGE_SECTION_HEADER *sec;
1026 IMAGE_DATA_DIRECTORY *imports;
1027 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1032 struct file_view *view = NULL;
1033 char *ptr, *header_end;
1036 /* zero-map the whole range */
1038 server_enter_uninterrupted_section( &csVirtual, &sigset );
1040 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
1041 status = map_view( &view, base, total_size, mask, FALSE,
1042 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1044 if (status != STATUS_SUCCESS)
1045 status = map_view( &view, NULL, total_size, mask, FALSE,
1046 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1048 if (status != STATUS_SUCCESS) goto error;
1051 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1053 /* map the header */
1055 if (fstat( fd, &st ) == -1)
1057 status = FILE_GetNtStatus();
1060 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1061 if (!st.st_size) goto error;
1062 header_size = min( header_size, st.st_size );
1063 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1064 !dup_mapping ) != STATUS_SUCCESS) goto error;
1065 dos = (IMAGE_DOS_HEADER *)ptr;
1066 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1067 header_end = ptr + ROUND_SIZE( 0, header_size );
1068 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1069 if ((char *)(nt + 1) > header_end) goto error;
1070 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1071 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
1073 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1074 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1076 /* check the architecture */
1079 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
1081 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
1084 MESSAGE("Trying to load PE image for unsupported architecture (");
1085 switch (nt->FileHeader.Machine)
1087 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
1088 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
1089 case IMAGE_FILE_MACHINE_I386: MESSAGE("I386"); break;
1090 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
1091 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
1092 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
1093 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
1094 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
1095 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
1096 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
1097 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
1098 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
1099 case IMAGE_FILE_MACHINE_SPARC: MESSAGE("SPARC"); break;
1100 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1106 /* check for non page-aligned binary */
1108 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1110 /* unaligned sections, this happens for native subsystem binaries */
1111 /* in that case Windows simply maps in the whole file */
1113 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1114 !dup_mapping ) != STATUS_SUCCESS) goto error;
1116 /* check that all sections are loaded at the right offset */
1117 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1118 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1120 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1121 goto error; /* Windows refuses to load in that case too */
1124 /* set the image protections */
1125 VIRTUAL_SetProt( view, ptr, total_size,
1126 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1128 /* no relocations are performed on non page-aligned binaries */
1133 /* map all the sections */
1135 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1137 static const SIZE_T sector_align = 0x1ff;
1138 SIZE_T map_size, file_start, file_size, end;
1140 if (!sec->Misc.VirtualSize)
1141 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1143 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1145 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1146 file_start = sec->PointerToRawData & ~sector_align;
1147 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1148 if (file_size > map_size) file_size = map_size;
1150 /* a few sanity checks */
1151 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1152 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1154 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1155 sec->Name, sec->VirtualAddress, map_size, total_size );
1159 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1160 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1162 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1163 sec->Name, ptr + sec->VirtualAddress,
1164 sec->PointerToRawData, (int)pos, file_size, map_size,
1165 sec->Characteristics );
1166 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1167 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1168 FALSE ) != STATUS_SUCCESS)
1170 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1174 /* check if the import directory falls inside this section */
1175 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1176 imports->VirtualAddress < sec->VirtualAddress + map_size)
1178 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1179 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1180 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1182 map_file_into_view( view, shared_fd, base, end - base,
1183 pos + (base - sec->VirtualAddress),
1184 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1191 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1192 sec->Name, ptr + sec->VirtualAddress,
1193 sec->PointerToRawData, sec->SizeOfRawData,
1194 sec->Misc.VirtualSize, sec->Characteristics );
1196 if (!sec->PointerToRawData || !file_size) continue;
1198 /* Note: if the section is not aligned properly map_file_into_view will magically
1199 * fall back to read(), so we don't need to check anything here.
1201 end = file_start + file_size;
1202 if (sec->PointerToRawData >= st.st_size ||
1203 end > ((st.st_size + sector_align) & ~sector_align) ||
1205 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1206 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1207 !dup_mapping ) != STATUS_SUCCESS)
1209 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1213 if (file_size & page_mask)
1215 end = ROUND_SIZE( 0, file_size );
1216 if (end > map_size) end = map_size;
1217 TRACE_(module)("clearing %p - %p\n",
1218 ptr + sec->VirtualAddress + file_size,
1219 ptr + sec->VirtualAddress + end );
1220 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1225 /* perform base relocation, if necessary */
1228 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1229 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1231 IMAGE_BASE_RELOCATION *rel, *end;
1232 const IMAGE_DATA_DIRECTORY *relocs;
1234 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1236 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1238 status = STATUS_CONFLICTING_ADDRESSES;
1242 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1243 base, base + total_size, ptr, ptr + total_size );
1245 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1246 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1247 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1250 while (rel < end - 1 && rel->SizeOfBlock)
1252 if (rel->VirtualAddress >= total_size)
1254 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1255 status = STATUS_ACCESS_VIOLATION;
1258 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1259 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1260 (USHORT *)(rel + 1), delta );
1261 if (!rel) goto error;
1265 /* set the image protections */
1267 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1269 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1270 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1273 BYTE vprot = VPROT_COMMITTED;
1275 if (sec->Misc.VirtualSize)
1276 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1278 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1280 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1281 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1282 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1284 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1285 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1286 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1287 vprot |= VPROT_EXEC;
1289 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1290 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1291 sec->Characteristics, sec->Name );
1295 view->mapping = dup_mapping;
1296 server_leave_uninterrupted_section( &csVirtual, &sigset );
1299 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1300 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1302 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1303 return STATUS_SUCCESS;
1306 if (view) delete_view( view );
1307 server_leave_uninterrupted_section( &csVirtual, &sigset );
1308 if (dup_mapping) NtClose( dup_mapping );
1313 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1314 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1316 void **heap_base = arg;
1318 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1319 if (size < VIRTUAL_HEAP_SIZE) return 0;
1320 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1321 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1322 return (*heap_base != (void *)-1);
1325 /***********************************************************************
1328 void virtual_init(void)
1330 const char *preload;
1332 struct file_view *heap_view;
1335 page_size = getpagesize();
1336 page_mask = page_size - 1;
1337 /* Make sure we have a power of 2 */
1338 assert( !(page_size & page_mask) );
1340 while ((1 << page_shift) != page_size) page_shift++;
1341 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1342 #endif /* page_mask */
1343 if ((preload = getenv("WINEPRELOADRESERVE")))
1345 unsigned long start, end;
1346 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1348 preload_reserve_start = (void *)start;
1349 preload_reserve_end = (void *)end;
1353 /* try to find space in a reserved area for the virtual heap */
1354 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1355 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1357 assert( heap_base != (void *)-1 );
1358 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1359 VIRTUAL_HEAP_SIZE, NULL, NULL );
1360 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1362 /* make the DOS area accessible to hide bugs in broken apps like Excel 2003 */
1363 if (wine_mmap_is_in_reserved_area( (void *)0x10000, 0x100000 ) == 1)
1364 wine_anon_mmap( (void *)0x10000, 0x100000, PROT_READ | PROT_WRITE, MAP_FIXED );
1368 /***********************************************************************
1369 * virtual_init_threading
1371 void virtual_init_threading(void)
1377 /***********************************************************************
1378 * virtual_get_system_info
1380 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1383 info->KeMaximumIncrement = 0; /* FIXME */
1384 info->PageSize = page_size;
1385 info->MmLowestPhysicalPage = 1;
1386 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1387 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1388 info->AllocationGranularity = get_mask(0) + 1;
1389 info->LowestUserAddress = (void *)0x10000;
1390 info->HighestUserAddress = (char *)user_space_limit - 1;
1391 info->ActiveProcessorsAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1392 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1396 /***********************************************************************
1397 * virtual_create_system_view
1399 NTSTATUS virtual_create_builtin_view( void *module )
1403 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1404 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1405 IMAGE_SECTION_HEADER *sec;
1410 size = ROUND_SIZE( module, size );
1411 base = ROUND_ADDR( module, page_mask );
1412 server_enter_uninterrupted_section( &csVirtual, &sigset );
1413 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1414 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1415 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1416 server_leave_uninterrupted_section( &csVirtual, &sigset );
1418 if (status) return status;
1420 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1421 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1423 DWORD flags = VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED;
1425 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1426 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1427 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1428 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1429 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1436 /***********************************************************************
1437 * virtual_alloc_thread_stack
1439 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1446 if (!reserve_size || !commit_size)
1448 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1449 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1450 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1453 size = max( reserve_size, commit_size );
1454 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1455 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1457 server_enter_uninterrupted_section( &csVirtual, &sigset );
1459 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1460 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1463 #ifdef VALGRIND_STACK_REGISTER
1464 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1467 /* setup no access guard page */
1468 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1469 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1470 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1472 /* note: limit is lower than base since the stack grows down */
1473 teb->DeallocationStack = view->base;
1474 teb->Tib.StackBase = (char *)view->base + view->size;
1475 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1477 server_leave_uninterrupted_section( &csVirtual, &sigset );
1482 /***********************************************************************
1483 * virtual_clear_thread_stack
1485 * Clear the stack contents before calling the main entry point, some broken apps need that.
1487 void virtual_clear_thread_stack(void)
1489 void *stack = NtCurrentTeb()->Tib.StackLimit;
1490 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1492 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1493 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1497 /***********************************************************************
1498 * virtual_handle_fault
1500 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1503 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1506 server_enter_uninterrupted_section( &csVirtual, &sigset );
1507 if ((view = VIRTUAL_FindView( addr, 0 )))
1509 void *page = ROUND_ADDR( addr, page_mask );
1510 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1511 if (*vprot & VPROT_GUARD)
1513 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1514 ret = STATUS_GUARD_PAGE_VIOLATION;
1516 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1518 if (*vprot & VPROT_WRITEWATCH)
1520 *vprot &= ~VPROT_WRITEWATCH;
1521 VIRTUAL_SetProt( view, page, page_size, *vprot );
1523 /* ignore fault if page is writable now */
1524 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1527 server_leave_uninterrupted_section( &csVirtual, &sigset );
1533 /***********************************************************************
1534 * virtual_handle_stack_fault
1536 * Handle an access fault inside the current thread stack.
1537 * Called from inside a signal handler.
1539 BOOL virtual_handle_stack_fault( void *addr )
1544 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1545 if ((view = VIRTUAL_FindView( addr, 0 )))
1547 void *page = ROUND_ADDR( addr, page_mask );
1548 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1549 if (vprot & VPROT_GUARD)
1551 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1552 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1553 NtCurrentTeb()->Tib.StackLimit = page;
1557 RtlLeaveCriticalSection( &csVirtual );
1562 /***********************************************************************
1563 * virtual_check_buffer_for_read
1565 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1567 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1569 if (!size) return TRUE;
1570 if (!ptr) return FALSE;
1574 volatile const char *p = ptr;
1576 SIZE_T count = size;
1578 while (count > page_size)
1585 dummy = p[count - 1];
1596 /***********************************************************************
1597 * virtual_check_buffer_for_write
1599 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1601 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1603 if (!size) return TRUE;
1604 if (!ptr) return FALSE;
1608 volatile char *p = ptr;
1609 SIZE_T count = size;
1611 while (count > page_size)
1629 /***********************************************************************
1630 * VIRTUAL_SetForceExec
1632 * Whether to force exec prot on all views.
1634 void VIRTUAL_SetForceExec( BOOL enable )
1636 struct file_view *view;
1639 server_enter_uninterrupted_section( &csVirtual, &sigset );
1640 if (!force_exec_prot != !enable) /* change all existing views */
1642 force_exec_prot = enable;
1644 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1647 char *addr = view->base;
1648 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1649 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1651 if (view->protect & VPROT_NOEXEC) continue;
1652 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1654 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1655 if (prot == unix_prot) continue;
1656 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1658 TRACE( "%s exec prot for %p-%p\n",
1659 force_exec_prot ? "enabling" : "disabling",
1660 addr, addr + (count << page_shift) - 1 );
1661 mprotect( addr, count << page_shift,
1662 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1664 addr += (count << page_shift);
1670 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1672 TRACE( "%s exec prot for %p-%p\n",
1673 force_exec_prot ? "enabling" : "disabling",
1674 addr, addr + (count << page_shift) - 1 );
1675 mprotect( addr, count << page_shift,
1676 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1681 server_leave_uninterrupted_section( &csVirtual, &sigset );
1690 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1691 static int free_reserved_memory( void *base, size_t size, void *arg )
1693 struct free_range *range = arg;
1695 if ((char *)base >= range->limit) return 0;
1696 if ((char *)base + size <= range->base) return 0;
1697 if ((char *)base < range->base)
1699 size -= range->base - (char *)base;
1702 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1703 remove_reserved_area( base, size );
1704 return 1; /* stop enumeration since the list has changed */
1707 /***********************************************************************
1708 * virtual_release_address_space
1710 * Release some address space once we have loaded and initialized the app.
1712 void virtual_release_address_space( BOOL free_high_mem )
1714 struct free_range range;
1717 if (user_space_limit == address_space_limit) return; /* no need to free anything */
1719 server_enter_uninterrupted_section( &csVirtual, &sigset );
1721 /* no large address space on win9x */
1722 if (free_high_mem && NtCurrentTeb()->Peb->OSPlatformId == VER_PLATFORM_WIN32_NT)
1724 range.base = (char *)0x82000000;
1725 range.limit = address_space_limit;
1726 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1727 user_space_limit = working_set_limit = address_space_limit;
1731 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1732 range.base = (char *)0x20000000;
1733 range.limit = (char *)0x7f000000;
1734 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1738 server_leave_uninterrupted_section( &csVirtual, &sigset );
1742 /***********************************************************************
1743 * NtAllocateVirtualMemory (NTDLL.@)
1744 * ZwAllocateVirtualMemory (NTDLL.@)
1746 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1747 SIZE_T *size_ptr, ULONG type, ULONG protect )
1751 SIZE_T size = *size_ptr;
1752 SIZE_T mask = get_mask( zero_bits );
1753 NTSTATUS status = STATUS_SUCCESS;
1754 struct file_view *view;
1757 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1759 if (!size) return STATUS_INVALID_PARAMETER;
1761 if (process != NtCurrentProcess())
1764 apc_result_t result;
1766 memset( &call, 0, sizeof(call) );
1768 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1769 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1770 call.virtual_alloc.size = *size_ptr;
1771 call.virtual_alloc.zero_bits = zero_bits;
1772 call.virtual_alloc.op_type = type;
1773 call.virtual_alloc.prot = protect;
1774 status = NTDLL_queue_process_apc( process, &call, &result );
1775 if (status != STATUS_SUCCESS) return status;
1777 if (result.virtual_alloc.status == STATUS_SUCCESS)
1779 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1780 *size_ptr = result.virtual_alloc.size;
1782 return result.virtual_alloc.status;
1785 /* Round parameters to a page boundary */
1787 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1789 if ((status = get_vprot_flags( protect, &vprot ))) return status;
1790 vprot |= VPROT_VALLOC;
1791 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1795 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1796 base = ROUND_ADDR( *ret, mask );
1798 base = ROUND_ADDR( *ret, page_mask );
1799 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1801 /* address 1 is magic to mean DOS area */
1802 if (!base && *ret == (void *)1 && size == 0x110000)
1804 server_enter_uninterrupted_section( &csVirtual, &sigset );
1805 status = allocate_dos_memory( &view, vprot );
1806 if (status == STATUS_SUCCESS)
1809 *size_ptr = view->size;
1811 server_leave_uninterrupted_section( &csVirtual, &sigset );
1815 /* disallow low 64k, wrap-around and kernel space */
1816 if (((char *)base < (char *)0x10000) ||
1817 ((char *)base + size < (char *)base) ||
1818 is_beyond_limit( base, size, address_space_limit ))
1819 return STATUS_INVALID_PARAMETER;
1824 size = (size + page_mask) & ~page_mask;
1827 /* Compute the alloc type flags */
1829 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1830 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1832 WARN("called with wrong alloc type flags (%08x) !\n", type);
1833 return STATUS_INVALID_PARAMETER;
1836 /* Reserve the memory */
1838 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1840 if ((type & MEM_RESERVE) || !base)
1842 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1843 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1844 if (status == STATUS_SUCCESS) base = view->base;
1846 else if (type & MEM_RESET)
1848 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1849 else madvise( base, size, MADV_DONTNEED );
1851 else /* commit the pages */
1853 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1854 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1855 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1857 SERVER_START_REQ( add_mapping_committed_range )
1859 req->handle = wine_server_obj_handle( view->mapping );
1860 req->offset = (char *)base - (char *)view->base;
1862 wine_server_call( req );
1868 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1870 if (status == STATUS_SUCCESS)
1879 /***********************************************************************
1880 * NtFreeVirtualMemory (NTDLL.@)
1881 * ZwFreeVirtualMemory (NTDLL.@)
1883 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1888 NTSTATUS status = STATUS_SUCCESS;
1889 LPVOID addr = *addr_ptr;
1890 SIZE_T size = *size_ptr;
1892 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1894 if (process != NtCurrentProcess())
1897 apc_result_t result;
1899 memset( &call, 0, sizeof(call) );
1901 call.virtual_free.type = APC_VIRTUAL_FREE;
1902 call.virtual_free.addr = wine_server_client_ptr( addr );
1903 call.virtual_free.size = size;
1904 call.virtual_free.op_type = type;
1905 status = NTDLL_queue_process_apc( process, &call, &result );
1906 if (status != STATUS_SUCCESS) return status;
1908 if (result.virtual_free.status == STATUS_SUCCESS)
1910 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
1911 *size_ptr = result.virtual_free.size;
1913 return result.virtual_free.status;
1916 /* Fix the parameters */
1918 size = ROUND_SIZE( addr, size );
1919 base = ROUND_ADDR( addr, page_mask );
1921 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1922 if (!base) return STATUS_INVALID_PARAMETER;
1924 server_enter_uninterrupted_section( &csVirtual, &sigset );
1926 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
1928 status = STATUS_INVALID_PARAMETER;
1930 else if (type == MEM_RELEASE)
1932 /* Free the pages */
1934 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1937 delete_view( view );
1942 else if (type == MEM_DECOMMIT)
1944 status = decommit_pages( view, base - (char *)view->base, size );
1945 if (status == STATUS_SUCCESS)
1953 WARN("called with wrong free type flags (%08x) !\n", type);
1954 status = STATUS_INVALID_PARAMETER;
1957 server_leave_uninterrupted_section( &csVirtual, &sigset );
1962 /***********************************************************************
1963 * NtProtectVirtualMemory (NTDLL.@)
1964 * ZwProtectVirtualMemory (NTDLL.@)
1966 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1967 ULONG new_prot, ULONG *old_prot )
1971 NTSTATUS status = STATUS_SUCCESS;
1974 unsigned int new_vprot;
1975 SIZE_T size = *size_ptr;
1976 LPVOID addr = *addr_ptr;
1978 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1980 if (process != NtCurrentProcess())
1983 apc_result_t result;
1985 memset( &call, 0, sizeof(call) );
1987 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1988 call.virtual_protect.addr = wine_server_client_ptr( addr );
1989 call.virtual_protect.size = size;
1990 call.virtual_protect.prot = new_prot;
1991 status = NTDLL_queue_process_apc( process, &call, &result );
1992 if (status != STATUS_SUCCESS) return status;
1994 if (result.virtual_protect.status == STATUS_SUCCESS)
1996 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
1997 *size_ptr = result.virtual_protect.size;
1998 if (old_prot) *old_prot = result.virtual_protect.prot;
2000 return result.virtual_protect.status;
2003 /* Fix the parameters */
2005 size = ROUND_SIZE( addr, size );
2006 base = ROUND_ADDR( addr, page_mask );
2007 if ((status = get_vprot_flags( new_prot, &new_vprot ))) return status;
2008 new_vprot |= VPROT_COMMITTED;
2010 server_enter_uninterrupted_section( &csVirtual, &sigset );
2012 if (!(view = VIRTUAL_FindView( base, size )))
2014 status = STATUS_INVALID_PARAMETER;
2018 /* Make sure all the pages are committed */
2019 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2021 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2022 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2024 else status = STATUS_NOT_COMMITTED;
2026 server_leave_uninterrupted_section( &csVirtual, &sigset );
2028 if (status == STATUS_SUCCESS)
2037 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2038 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2040 MEMORY_BASIC_INFORMATION *info = arg;
2041 void *end = (char *)start + size;
2043 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2045 if (info->BaseAddress >= end)
2047 if (info->AllocationBase < end) info->AllocationBase = end;
2051 if (info->BaseAddress >= start)
2053 /* it's a real free area */
2054 info->State = MEM_FREE;
2055 info->Protect = PAGE_NOACCESS;
2056 info->AllocationBase = 0;
2057 info->AllocationProtect = 0;
2059 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2060 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2062 else /* outside of the reserved area, pretend it's allocated */
2064 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2065 info->State = MEM_RESERVE;
2066 info->Protect = PAGE_NOACCESS;
2067 info->AllocationProtect = PAGE_NOACCESS;
2068 info->Type = MEM_PRIVATE;
2073 #define UNIMPLEMENTED_INFO_CLASS(c) \
2075 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2076 return STATUS_INVALID_INFO_CLASS
2078 /***********************************************************************
2079 * NtQueryVirtualMemory (NTDLL.@)
2080 * ZwQueryVirtualMemory (NTDLL.@)
2082 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2083 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2084 SIZE_T len, SIZE_T *res_len )
2087 char *base, *alloc_base = 0;
2090 MEMORY_BASIC_INFORMATION *info = buffer;
2093 if (info_class != MemoryBasicInformation)
2097 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2098 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2099 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2102 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2103 process, addr, info_class, buffer, len, res_len);
2104 return STATUS_INVALID_INFO_CLASS;
2108 if (process != NtCurrentProcess())
2112 apc_result_t result;
2114 memset( &call, 0, sizeof(call) );
2116 call.virtual_query.type = APC_VIRTUAL_QUERY;
2117 call.virtual_query.addr = wine_server_client_ptr( addr );
2118 status = NTDLL_queue_process_apc( process, &call, &result );
2119 if (status != STATUS_SUCCESS) return status;
2121 if (result.virtual_query.status == STATUS_SUCCESS)
2123 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2124 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2125 info->RegionSize = result.virtual_query.size;
2126 info->Protect = result.virtual_query.prot;
2127 info->AllocationProtect = result.virtual_query.alloc_prot;
2128 info->State = (DWORD)result.virtual_query.state << 12;
2129 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2130 if (info->RegionSize != result.virtual_query.size) /* truncated */
2131 return STATUS_INVALID_PARAMETER; /* FIXME */
2132 if (res_len) *res_len = sizeof(*info);
2134 return result.virtual_query.status;
2137 base = ROUND_ADDR( addr, page_mask );
2139 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2141 /* Find the view containing the address */
2143 server_enter_uninterrupted_section( &csVirtual, &sigset );
2144 ptr = list_head( &views_list );
2149 size = (char *)working_set_limit - alloc_base;
2153 view = LIST_ENTRY( ptr, struct file_view, entry );
2154 if ((char *)view->base > base)
2156 size = (char *)view->base - alloc_base;
2160 if ((char *)view->base + view->size > base)
2162 alloc_base = view->base;
2166 alloc_base = (char *)view->base + view->size;
2167 ptr = list_next( &views_list, ptr );
2170 /* Fill the info structure */
2172 info->AllocationBase = alloc_base;
2173 info->BaseAddress = base;
2174 info->RegionSize = size - (base - alloc_base);
2178 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2180 /* not in a reserved area at all, pretend it's allocated */
2182 info->State = MEM_RESERVE;
2183 info->Protect = PAGE_NOACCESS;
2184 info->AllocationProtect = PAGE_NOACCESS;
2185 info->Type = MEM_PRIVATE;
2187 info->State = MEM_FREE;
2188 info->Protect = PAGE_NOACCESS;
2189 info->AllocationBase = 0;
2190 info->AllocationProtect = 0;
2198 SIZE_T range_size = get_committed_size( view, base, &vprot );
2200 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2201 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2202 info->AllocationBase = alloc_base;
2203 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2204 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2205 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2206 else info->Type = MEM_MAPPED;
2207 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2208 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2209 info->RegionSize = size - (base - alloc_base);
2211 server_leave_uninterrupted_section( &csVirtual, &sigset );
2213 if (res_len) *res_len = sizeof(*info);
2214 return STATUS_SUCCESS;
2218 /***********************************************************************
2219 * NtLockVirtualMemory (NTDLL.@)
2220 * ZwLockVirtualMemory (NTDLL.@)
2222 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2224 NTSTATUS status = STATUS_SUCCESS;
2226 if (process != NtCurrentProcess())
2229 apc_result_t result;
2231 memset( &call, 0, sizeof(call) );
2233 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2234 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2235 call.virtual_lock.size = *size;
2236 status = NTDLL_queue_process_apc( process, &call, &result );
2237 if (status != STATUS_SUCCESS) return status;
2239 if (result.virtual_lock.status == STATUS_SUCCESS)
2241 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2242 *size = result.virtual_lock.size;
2244 return result.virtual_lock.status;
2247 *size = ROUND_SIZE( *addr, *size );
2248 *addr = ROUND_ADDR( *addr, page_mask );
2250 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2255 /***********************************************************************
2256 * NtUnlockVirtualMemory (NTDLL.@)
2257 * ZwUnlockVirtualMemory (NTDLL.@)
2259 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2261 NTSTATUS status = STATUS_SUCCESS;
2263 if (process != NtCurrentProcess())
2266 apc_result_t result;
2268 memset( &call, 0, sizeof(call) );
2270 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2271 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2272 call.virtual_unlock.size = *size;
2273 status = NTDLL_queue_process_apc( process, &call, &result );
2274 if (status != STATUS_SUCCESS) return status;
2276 if (result.virtual_unlock.status == STATUS_SUCCESS)
2278 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2279 *size = result.virtual_unlock.size;
2281 return result.virtual_unlock.status;
2284 *size = ROUND_SIZE( *addr, *size );
2285 *addr = ROUND_ADDR( *addr, page_mask );
2287 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2292 /***********************************************************************
2293 * NtCreateSection (NTDLL.@)
2294 * ZwCreateSection (NTDLL.@)
2296 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2297 const LARGE_INTEGER *size, ULONG protect,
2298 ULONG sec_flags, HANDLE file )
2302 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2303 struct security_descriptor *sd = NULL;
2304 struct object_attributes objattr;
2306 /* Check parameters */
2308 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2310 if ((ret = get_vprot_flags( protect, &vprot ))) return ret;
2312 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2314 objattr.name_len = len;
2317 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2318 if (ret != STATUS_SUCCESS) return ret;
2321 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2322 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2323 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2325 /* Create the server object */
2327 SERVER_START_REQ( create_mapping )
2329 req->access = access;
2330 req->attributes = (attr) ? attr->Attributes : 0;
2331 req->file_handle = wine_server_obj_handle( file );
2332 req->size = size ? size->QuadPart : 0;
2333 req->protect = vprot;
2334 wine_server_add_data( req, &objattr, sizeof(objattr) );
2335 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2336 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2337 ret = wine_server_call( req );
2338 *handle = wine_server_ptr_handle( reply->handle );
2342 NTDLL_free_struct_sd( sd );
2348 /***********************************************************************
2349 * NtOpenSection (NTDLL.@)
2350 * ZwOpenSection (NTDLL.@)
2352 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2355 DWORD len = attr->ObjectName->Length;
2357 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2359 SERVER_START_REQ( open_mapping )
2361 req->access = access;
2362 req->attributes = attr->Attributes;
2363 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2364 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2365 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2372 /***********************************************************************
2373 * NtMapViewOfSection (NTDLL.@)
2374 * ZwMapViewOfSection (NTDLL.@)
2376 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2377 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2378 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2381 mem_size_t full_size;
2383 SIZE_T size, mask = get_mask( zero_bits );
2384 int unix_handle = -1, needs_close;
2385 unsigned int map_vprot, vprot;
2387 struct file_view *view;
2389 HANDLE dup_mapping, shared_file;
2390 LARGE_INTEGER offset;
2393 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2395 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2396 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2398 /* Check parameters */
2400 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2401 return STATUS_INVALID_PARAMETER;
2408 case PAGE_READWRITE:
2409 case PAGE_EXECUTE_READWRITE:
2410 access = SECTION_MAP_WRITE;
2413 case PAGE_WRITECOPY:
2415 case PAGE_EXECUTE_READ:
2416 case PAGE_EXECUTE_WRITECOPY:
2417 access = SECTION_MAP_READ;
2420 return STATUS_INVALID_PARAMETER;
2423 if (process != NtCurrentProcess())
2426 apc_result_t result;
2428 memset( &call, 0, sizeof(call) );
2430 call.map_view.type = APC_MAP_VIEW;
2431 call.map_view.handle = wine_server_obj_handle( handle );
2432 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2433 call.map_view.size = *size_ptr;
2434 call.map_view.offset = offset.QuadPart;
2435 call.map_view.zero_bits = zero_bits;
2436 call.map_view.alloc_type = alloc_type;
2437 call.map_view.prot = protect;
2438 res = NTDLL_queue_process_apc( process, &call, &result );
2439 if (res != STATUS_SUCCESS) return res;
2441 if ((NTSTATUS)result.map_view.status >= 0)
2443 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2444 *size_ptr = result.map_view.size;
2446 return result.map_view.status;
2449 SERVER_START_REQ( get_mapping_info )
2451 req->handle = wine_server_obj_handle( handle );
2452 req->access = access;
2453 res = wine_server_call( req );
2454 map_vprot = reply->protect;
2455 base = wine_server_get_ptr( reply->base );
2456 full_size = reply->size;
2457 header_size = reply->header_size;
2458 dup_mapping = wine_server_ptr_handle( reply->mapping );
2459 shared_file = wine_server_ptr_handle( reply->shared_file );
2460 if ((ULONG_PTR)base != reply->base) base = NULL;
2463 if (res) return res;
2465 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2467 if (map_vprot & VPROT_IMAGE)
2470 if (size != full_size) /* truncated */
2472 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2473 res = STATUS_INVALID_PARAMETER;
2478 int shared_fd, shared_needs_close;
2480 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2481 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2482 res = map_image( handle, unix_handle, base, size, mask, header_size,
2483 shared_fd, dup_mapping, addr_ptr );
2484 if (shared_needs_close) close( shared_fd );
2485 NtClose( shared_file );
2489 res = map_image( handle, unix_handle, base, size, mask, header_size,
2490 -1, dup_mapping, addr_ptr );
2492 if (needs_close) close( unix_handle );
2493 if (res >= 0) *size_ptr = size;
2497 res = STATUS_INVALID_PARAMETER;
2498 if (offset.QuadPart >= full_size) goto done;
2501 if (*size_ptr > full_size - offset.QuadPart) goto done;
2502 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2503 if (size < *size_ptr) goto done; /* wrap-around */
2507 size = full_size - offset.QuadPart;
2508 if (size != full_size - offset.QuadPart) /* truncated */
2510 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2511 wine_dbgstr_longlong(full_size) );
2516 /* Reserve a properly aligned area */
2518 server_enter_uninterrupted_section( &csVirtual, &sigset );
2520 get_vprot_flags( protect, &vprot );
2521 vprot |= (map_vprot & VPROT_COMMITTED);
2522 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2525 server_leave_uninterrupted_section( &csVirtual, &sigset );
2531 TRACE("handle=%p size=%lx offset=%x%08x\n",
2532 handle, size, offset.u.HighPart, offset.u.LowPart );
2534 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2535 if (res == STATUS_SUCCESS)
2537 *addr_ptr = view->base;
2539 view->mapping = dup_mapping;
2540 dup_mapping = 0; /* don't close it */
2544 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2545 view->base, size, offset.u.HighPart, offset.u.LowPart );
2546 delete_view( view );
2549 server_leave_uninterrupted_section( &csVirtual, &sigset );
2552 if (dup_mapping) NtClose( dup_mapping );
2553 if (needs_close) close( unix_handle );
2558 /***********************************************************************
2559 * NtUnmapViewOfSection (NTDLL.@)
2560 * ZwUnmapViewOfSection (NTDLL.@)
2562 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2565 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2567 void *base = ROUND_ADDR( addr, page_mask );
2569 if (process != NtCurrentProcess())
2572 apc_result_t result;
2574 memset( &call, 0, sizeof(call) );
2576 call.unmap_view.type = APC_UNMAP_VIEW;
2577 call.unmap_view.addr = wine_server_client_ptr( addr );
2578 status = NTDLL_queue_process_apc( process, &call, &result );
2579 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2583 server_enter_uninterrupted_section( &csVirtual, &sigset );
2584 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2586 delete_view( view );
2587 status = STATUS_SUCCESS;
2589 server_leave_uninterrupted_section( &csVirtual, &sigset );
2594 /***********************************************************************
2595 * NtFlushVirtualMemory (NTDLL.@)
2596 * ZwFlushVirtualMemory (NTDLL.@)
2598 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2599 SIZE_T *size_ptr, ULONG unknown )
2602 NTSTATUS status = STATUS_SUCCESS;
2604 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2606 if (process != NtCurrentProcess())
2609 apc_result_t result;
2611 memset( &call, 0, sizeof(call) );
2613 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2614 call.virtual_flush.addr = wine_server_client_ptr( addr );
2615 call.virtual_flush.size = *size_ptr;
2616 status = NTDLL_queue_process_apc( process, &call, &result );
2617 if (status != STATUS_SUCCESS) return status;
2619 if (result.virtual_flush.status == STATUS_SUCCESS)
2621 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2622 *size_ptr = result.virtual_flush.size;
2624 return result.virtual_flush.status;
2627 server_enter_uninterrupted_section( &csVirtual, &sigset );
2628 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2631 if (!*size_ptr) *size_ptr = view->size;
2633 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2635 server_leave_uninterrupted_section( &csVirtual, &sigset );
2640 /***********************************************************************
2641 * NtGetWriteWatch (NTDLL.@)
2642 * ZwGetWriteWatch (NTDLL.@)
2644 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2645 ULONG_PTR *count, ULONG *granularity )
2647 struct file_view *view;
2648 NTSTATUS status = STATUS_SUCCESS;
2651 size = ROUND_SIZE( base, size );
2652 base = ROUND_ADDR( base, page_mask );
2654 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2655 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2656 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2658 if (!addresses) return STATUS_ACCESS_VIOLATION;
2660 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2661 addresses, *count );
2663 server_enter_uninterrupted_section( &csVirtual, &sigset );
2665 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2669 char *end = addr + size;
2671 while (pos < *count && addr < end)
2673 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2674 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2677 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2679 *granularity = page_size;
2681 else status = STATUS_INVALID_PARAMETER;
2683 server_leave_uninterrupted_section( &csVirtual, &sigset );
2688 /***********************************************************************
2689 * NtResetWriteWatch (NTDLL.@)
2690 * ZwResetWriteWatch (NTDLL.@)
2692 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2694 struct file_view *view;
2695 NTSTATUS status = STATUS_SUCCESS;
2698 size = ROUND_SIZE( base, size );
2699 base = ROUND_ADDR( base, page_mask );
2701 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2703 if (!size) return STATUS_INVALID_PARAMETER;
2705 server_enter_uninterrupted_section( &csVirtual, &sigset );
2707 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2708 reset_write_watches( view, base, size );
2710 status = STATUS_INVALID_PARAMETER;
2712 server_leave_uninterrupted_section( &csVirtual, &sigset );
2717 /***********************************************************************
2718 * NtReadVirtualMemory (NTDLL.@)
2719 * ZwReadVirtualMemory (NTDLL.@)
2721 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2722 SIZE_T size, SIZE_T *bytes_read )
2726 if (virtual_check_buffer_for_write( buffer, size ))
2728 SERVER_START_REQ( read_process_memory )
2730 req->handle = wine_server_obj_handle( process );
2731 req->addr = wine_server_client_ptr( addr );
2732 wine_server_set_reply( req, buffer, size );
2733 if ((status = wine_server_call( req ))) size = 0;
2739 status = STATUS_ACCESS_VIOLATION;
2742 if (bytes_read) *bytes_read = size;
2747 /***********************************************************************
2748 * NtWriteVirtualMemory (NTDLL.@)
2749 * ZwWriteVirtualMemory (NTDLL.@)
2751 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2752 SIZE_T size, SIZE_T *bytes_written )
2756 if (virtual_check_buffer_for_read( buffer, size ))
2758 SERVER_START_REQ( write_process_memory )
2760 req->handle = wine_server_obj_handle( process );
2761 req->addr = wine_server_client_ptr( addr );
2762 wine_server_add_data( req, buffer, size );
2763 if ((status = wine_server_call( req ))) size = 0;
2769 status = STATUS_PARTIAL_COPY;
2772 if (bytes_written) *bytes_written = size;
2777 /***********************************************************************
2778 * NtAreMappedFilesTheSame (NTDLL.@)
2779 * ZwAreMappedFilesTheSame (NTDLL.@)
2781 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2783 TRACE("%p %p\n", addr1, addr2);
2785 return STATUS_NOT_SAME_DEVICE;