push 9e645869891abdc47a8701768b7a401b196a1e38
[wine/hacks.git] / dlls / ntdll / virtual.c
blobf5bed62e17cf9aaf6fea5d8b1870768d4fe7979b
1 /*
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <errno.h>
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
28 #endif
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winternl.h"
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/list.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
61 WINE_DECLARE_DEBUG_CHANNEL(module);
63 #ifndef MS_SYNC
64 #define MS_SYNC 0
65 #endif
67 #ifndef MAP_NORESERVE
68 #define MAP_NORESERVE 0
69 #endif
71 /* File view */
72 typedef struct file_view
74 struct list entry; /* Entry in global view list */
75 void *base; /* Base address */
76 size_t size; /* Size in bytes */
77 HANDLE mapping; /* Handle to the file mapping */
78 unsigned int protect; /* Protection for all pages at allocation time */
79 BYTE prot[1]; /* Protection byte for each page */
80 } FILE_VIEW;
83 /* Conversion from VPROT_* to Win32 flags */
84 static const BYTE VIRTUAL_Win32Flags[16] =
86 PAGE_NOACCESS, /* 0 */
87 PAGE_READONLY, /* READ */
88 PAGE_READWRITE, /* WRITE */
89 PAGE_READWRITE, /* READ | WRITE */
90 PAGE_EXECUTE, /* EXEC */
91 PAGE_EXECUTE_READ, /* READ | EXEC */
92 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
93 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
94 PAGE_WRITECOPY, /* WRITECOPY */
95 PAGE_WRITECOPY, /* READ | WRITECOPY */
96 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
97 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
104 static struct list views_list = LIST_INIT(views_list);
106 static RTL_CRITICAL_SECTION csVirtual;
107 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
109 0, 0, &csVirtual,
110 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
111 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
113 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
115 #ifdef __i386__
116 /* These are always the same on an i386, and it will be faster this way */
117 # define page_mask 0xfff
118 # define page_shift 12
119 # define page_size 0x1000
120 /* Note: these are Windows limits, you cannot change them. */
121 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
122 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
123 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
124 #else
125 static UINT page_shift;
126 static UINT page_size;
127 static UINT_PTR page_mask;
128 static void *address_space_limit;
129 static void *user_space_limit;
130 static void *working_set_limit;
131 #endif /* __i386__ */
133 #define ROUND_ADDR(addr,mask) \
134 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
136 #define ROUND_SIZE(addr,size) \
137 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
139 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
140 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
142 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
144 static HANDLE virtual_heap;
145 static void *preload_reserve_start;
146 static void *preload_reserve_end;
147 static int use_locks;
148 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
151 /***********************************************************************
152 * VIRTUAL_GetProtStr
154 static const char *VIRTUAL_GetProtStr( BYTE prot )
156 static char buffer[6];
157 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
158 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
159 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
160 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
161 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
162 buffer[5] = 0;
163 return buffer;
167 /***********************************************************************
168 * VIRTUAL_GetUnixProt
170 * Convert page protections to protection for mmap/mprotect.
172 static int VIRTUAL_GetUnixProt( BYTE vprot )
174 int prot = 0;
175 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
177 if (vprot & VPROT_READ) prot |= PROT_READ;
178 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
179 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
180 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
182 if (!prot) prot = PROT_NONE;
183 return prot;
187 /***********************************************************************
188 * VIRTUAL_DumpView
190 static void VIRTUAL_DumpView( FILE_VIEW *view )
192 UINT i, count;
193 char *addr = view->base;
194 BYTE prot = view->prot[0];
196 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
197 if (view->protect & VPROT_SYSTEM)
198 TRACE( " (system)\n" );
199 else if (view->protect & VPROT_VALLOC)
200 TRACE( " (valloc)\n" );
201 else if (view->mapping)
202 TRACE( " %p\n", view->mapping );
203 else
204 TRACE( " (anonymous)\n");
206 for (count = i = 1; i < view->size >> page_shift; i++, count++)
208 if (view->prot[i] == prot) continue;
209 TRACE( " %p - %p %s\n",
210 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
211 addr += (count << page_shift);
212 prot = view->prot[i];
213 count = 0;
215 if (count)
216 TRACE( " %p - %p %s\n",
217 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
221 /***********************************************************************
222 * VIRTUAL_Dump
224 #if WINE_VM_DEBUG
225 static void VIRTUAL_Dump(void)
227 sigset_t sigset;
228 struct file_view *view;
230 TRACE( "Dump of all virtual memory views:\n" );
231 server_enter_uninterrupted_section( &csVirtual, &sigset );
232 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
234 VIRTUAL_DumpView( view );
236 server_leave_uninterrupted_section( &csVirtual, &sigset );
238 #endif
241 /***********************************************************************
242 * VIRTUAL_FindView
244 * Find the view containing a given address. The csVirtual section must be held by caller.
246 * PARAMS
247 * addr [I] Address
249 * RETURNS
250 * View: Success
251 * NULL: Failure
253 static struct file_view *VIRTUAL_FindView( const void *addr )
255 struct file_view *view;
257 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
259 if (view->base > addr) break;
260 if ((const char*)view->base + view->size > (const char*)addr) return view;
262 return NULL;
266 /***********************************************************************
267 * get_mask
269 static inline UINT_PTR get_mask( ULONG zero_bits )
271 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
272 if (zero_bits < page_shift) zero_bits = page_shift;
273 return (1 << zero_bits) - 1;
277 /***********************************************************************
278 * find_view_range
280 * Find the first view overlapping at least part of the specified range.
281 * The csVirtual section must be held by caller.
283 static struct file_view *find_view_range( const void *addr, size_t size )
285 struct file_view *view;
287 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
289 if ((const char *)view->base >= (const char *)addr + size) break;
290 if ((const char *)view->base + view->size > (const char *)addr) return view;
292 return NULL;
296 /***********************************************************************
297 * find_free_area
299 * Find a free area between views inside the specified range.
300 * The csVirtual section must be held by caller.
302 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
304 struct list *ptr;
305 void *start;
307 if (top_down)
309 start = ROUND_ADDR( (char *)end - size, mask );
310 if (start >= end || start < base) return NULL;
312 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
314 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
316 if ((char *)view->base + view->size <= (char *)start) break;
317 if ((char *)view->base >= (char *)start + size) continue;
318 start = ROUND_ADDR( (char *)view->base - size, mask );
319 /* stop if remaining space is not large enough */
320 if (!start || start >= end || start < base) return NULL;
323 else
325 start = ROUND_ADDR( (char *)base + mask, mask );
326 if (start >= end || (char *)end - (char *)start < size) return NULL;
328 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
330 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
332 if ((char *)view->base >= (char *)start + size) break;
333 if ((char *)view->base + view->size <= (char *)start) continue;
334 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
335 /* stop if remaining space is not large enough */
336 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
339 return start;
343 /***********************************************************************
344 * add_reserved_area
346 * Add a reserved area to the list maintained by libwine.
347 * The csVirtual section must be held by caller.
349 static void add_reserved_area( void *addr, size_t size )
351 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
353 if (addr < user_space_limit)
355 /* unmap the part of the area that is below the limit */
356 assert( (char *)addr + size > (char *)user_space_limit );
357 munmap( addr, (char *)user_space_limit - (char *)addr );
358 size -= (char *)user_space_limit - (char *)addr;
359 addr = user_space_limit;
361 /* blow away existing mappings */
362 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
363 wine_mmap_add_reserved_area( addr, size );
367 /***********************************************************************
368 * is_beyond_limit
370 * Check if an address range goes beyond a given limit.
372 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
374 return (addr >= limit || (const char *)addr + size > (const char *)limit);
378 /***********************************************************************
379 * unmap_area
381 * Unmap an area, or simply replace it by an empty mapping if it is
382 * in a reserved area. The csVirtual section must be held by caller.
384 static inline void unmap_area( void *addr, size_t size )
386 if (wine_mmap_is_in_reserved_area( addr, size ))
387 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
388 else if (is_beyond_limit( addr, size, user_space_limit ))
389 add_reserved_area( addr, size );
390 else
391 munmap( addr, size );
395 /***********************************************************************
396 * delete_view
398 * Deletes a view. The csVirtual section must be held by caller.
400 static void delete_view( struct file_view *view ) /* [in] View */
402 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
403 list_remove( &view->entry );
404 if (view->mapping) NtClose( view->mapping );
405 RtlFreeHeap( virtual_heap, 0, view );
409 /***********************************************************************
410 * create_view
412 * Create a view. The csVirtual section must be held by caller.
414 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
416 struct file_view *view;
417 struct list *ptr;
418 int unix_prot = VIRTUAL_GetUnixProt( vprot );
420 assert( !((UINT_PTR)base & page_mask) );
421 assert( !(size & page_mask) );
423 /* Create the view structure */
425 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
427 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
428 return STATUS_NO_MEMORY;
431 view->base = base;
432 view->size = size;
433 view->mapping = 0;
434 view->protect = vprot;
435 memset( view->prot, vprot, size >> page_shift );
437 /* Insert it in the linked list */
439 LIST_FOR_EACH( ptr, &views_list )
441 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
442 if (next->base > base) break;
444 list_add_before( ptr, &view->entry );
446 /* Check for overlapping views. This can happen if the previous view
447 * was a system view that got unmapped behind our back. In that case
448 * we recover by simply deleting it. */
450 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
452 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
453 if ((char *)prev->base + prev->size > (char *)base)
455 TRACE( "overlapping prev view %p-%p for %p-%p\n",
456 prev->base, (char *)prev->base + prev->size,
457 base, (char *)base + view->size );
458 assert( prev->protect & VPROT_SYSTEM );
459 delete_view( prev );
462 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
464 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
465 if ((char *)base + view->size > (char *)next->base)
467 TRACE( "overlapping next view %p-%p for %p-%p\n",
468 next->base, (char *)next->base + next->size,
469 base, (char *)base + view->size );
470 assert( next->protect & VPROT_SYSTEM );
471 delete_view( next );
475 *view_ret = view;
476 VIRTUAL_DEBUG_DUMP_VIEW( view );
478 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
480 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
481 mprotect( base, size, unix_prot | PROT_EXEC );
483 return STATUS_SUCCESS;
487 /***********************************************************************
488 * VIRTUAL_GetWin32Prot
490 * Convert page protections to Win32 flags.
492 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
494 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
495 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
496 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
497 return ret;
501 /***********************************************************************
502 * VIRTUAL_GetProt
504 * Build page protections from Win32 flags.
506 * PARAMS
507 * protect [I] Win32 protection flags
509 * RETURNS
510 * Value of page protection flags
512 static BYTE VIRTUAL_GetProt( DWORD protect )
514 BYTE vprot;
516 switch(protect & 0xff)
518 case PAGE_READONLY:
519 vprot = VPROT_READ;
520 break;
521 case PAGE_READWRITE:
522 vprot = VPROT_READ | VPROT_WRITE;
523 break;
524 case PAGE_WRITECOPY:
525 vprot = VPROT_READ | VPROT_WRITECOPY;
526 break;
527 case PAGE_EXECUTE:
528 vprot = VPROT_EXEC;
529 break;
530 case PAGE_EXECUTE_READ:
531 vprot = VPROT_EXEC | VPROT_READ;
532 break;
533 case PAGE_EXECUTE_READWRITE:
534 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
535 break;
536 case PAGE_EXECUTE_WRITECOPY:
537 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
538 break;
539 case PAGE_NOACCESS:
540 default:
541 vprot = 0;
542 break;
544 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
545 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
546 return vprot;
550 /***********************************************************************
551 * VIRTUAL_SetProt
553 * Change the protection of a range of pages.
555 * RETURNS
556 * TRUE: Success
557 * FALSE: Failure
559 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
560 void *base, /* [in] Starting address */
561 size_t size, /* [in] Size in bytes */
562 BYTE vprot ) /* [in] Protections to use */
564 int unix_prot = VIRTUAL_GetUnixProt(vprot);
566 TRACE("%p-%p %s\n",
567 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
569 /* if setting stack guard pages, store the permissions first, as the guard may be
570 * triggered at any point after mprotect and change the permissions again */
571 if ((vprot & VPROT_GUARD) &&
572 ((char *)base >= (char *)NtCurrentTeb()->DeallocationStack) &&
573 ((char *)base < (char *)NtCurrentTeb()->Tib.StackBase))
575 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
576 vprot, size >> page_shift );
577 mprotect( base, size, unix_prot );
578 VIRTUAL_DEBUG_DUMP_VIEW( view );
579 return TRUE;
582 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
583 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
585 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
586 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
587 /* exec + write may legitimately fail, in that case fall back to write only */
588 if (!(unix_prot & PROT_WRITE)) return FALSE;
591 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
593 done:
594 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
595 vprot, size >> page_shift );
596 VIRTUAL_DEBUG_DUMP_VIEW( view );
597 return TRUE;
601 /***********************************************************************
602 * unmap_extra_space
604 * Release the extra memory while keeping the range starting on the granularity boundary.
606 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
608 if ((ULONG_PTR)ptr & mask)
610 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
611 munmap( ptr, extra );
612 ptr = (char *)ptr + extra;
613 total_size -= extra;
615 if (total_size > wanted_size)
616 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
617 return ptr;
621 struct alloc_area
623 size_t size;
624 size_t mask;
625 int top_down;
626 void *limit;
627 void *result;
630 /***********************************************************************
631 * alloc_reserved_area_callback
633 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
635 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
637 static void * const address_space_start = (void *)0x110000;
638 struct alloc_area *alloc = arg;
639 void *end = (char *)start + size;
641 if (start < address_space_start) start = address_space_start;
642 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
643 if (start >= end) return 0;
645 /* make sure we don't touch the preloader reserved range */
646 if (preload_reserve_end >= start)
648 if (preload_reserve_end >= end)
650 if (preload_reserve_start <= start) return 0; /* no space in that area */
651 if (preload_reserve_start < end) end = preload_reserve_start;
653 else if (preload_reserve_start <= start) start = preload_reserve_end;
654 else
656 /* range is split in two by the preloader reservation, try first part */
657 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
658 alloc->mask, alloc->top_down )))
659 return 1;
660 /* then fall through to try second part */
661 start = preload_reserve_end;
664 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
665 return 1;
667 return 0;
671 /***********************************************************************
672 * map_view
674 * Create a view and mmap the corresponding memory area.
675 * The csVirtual section must be held by caller.
677 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
678 int top_down, unsigned int vprot )
680 void *ptr;
681 NTSTATUS status;
683 if (base)
685 if (is_beyond_limit( base, size, address_space_limit ))
686 return STATUS_WORKING_SET_LIMIT_RANGE;
688 switch (wine_mmap_is_in_reserved_area( base, size ))
690 case -1: /* partially in a reserved area */
691 return STATUS_CONFLICTING_ADDRESSES;
693 case 0: /* not in a reserved area, do a normal allocation */
694 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
696 if (errno == ENOMEM) return STATUS_NO_MEMORY;
697 return STATUS_INVALID_PARAMETER;
699 if (ptr != base)
701 /* We couldn't get the address we wanted */
702 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
703 else munmap( ptr, size );
704 return STATUS_CONFLICTING_ADDRESSES;
706 break;
708 default:
709 case 1: /* in a reserved area, make sure the address is available */
710 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
711 /* replace the reserved area by our mapping */
712 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
713 return STATUS_INVALID_PARAMETER;
714 break;
716 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
718 else
720 size_t view_size = size + mask + 1;
721 struct alloc_area alloc;
723 alloc.size = size;
724 alloc.mask = mask;
725 alloc.top_down = top_down;
726 alloc.limit = user_space_limit;
727 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
729 ptr = alloc.result;
730 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
731 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
732 return STATUS_INVALID_PARAMETER;
733 goto done;
736 for (;;)
738 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
740 if (errno == ENOMEM) return STATUS_NO_MEMORY;
741 return STATUS_INVALID_PARAMETER;
743 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
744 /* if we got something beyond the user limit, unmap it and retry */
745 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
746 else break;
748 ptr = unmap_extra_space( ptr, view_size, size, mask );
750 done:
751 status = create_view( view_ret, ptr, size, vprot );
752 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
753 return status;
757 /***********************************************************************
758 * map_file_into_view
760 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
761 * The csVirtual section must be held by caller.
763 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
764 off_t offset, unsigned int vprot, BOOL removable )
766 void *ptr;
767 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
768 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
770 assert( start < view->size );
771 assert( start + size <= view->size );
773 /* only try mmap if media is not removable (or if we require write access) */
774 if (!removable || shared_write)
776 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
778 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
779 goto done;
781 /* mmap() failed; if this is because the file offset is not */
782 /* page-aligned (EINVAL), or because the underlying filesystem */
783 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
784 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
785 if (shared_write) /* we cannot fake shared write mappings */
787 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
788 ERR( "shared writable mmap not supported, broken filesystem?\n" );
789 return STATUS_NOT_SUPPORTED;
793 /* Reserve the memory with an anonymous mmap */
794 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
795 if (ptr == (void *)-1) return FILE_GetNtStatus();
796 /* Now read in the file */
797 pread( fd, ptr, size, offset );
798 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
799 done:
800 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
801 return STATUS_SUCCESS;
805 /***********************************************************************
806 * get_committed_size
808 * Get the size of the committed range starting at base.
809 * Also return the protections for the first page.
811 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
813 SIZE_T i, start;
815 start = ((char *)base - (char *)view->base) >> page_shift;
816 *vprot = view->prot[start];
818 if (view->mapping && !(view->protect & VPROT_COMMITTED))
820 SIZE_T ret = 0;
821 SERVER_START_REQ( get_mapping_committed_range )
823 req->handle = view->mapping;
824 req->offset = start << page_shift;
825 if (!wine_server_call( req ))
827 ret = reply->size;
828 if (reply->committed)
830 *vprot |= VPROT_COMMITTED;
831 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
835 SERVER_END_REQ;
836 return ret;
838 for (i = start + 1; i < view->size >> page_shift; i++)
839 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
840 return (i - start) << page_shift;
844 /***********************************************************************
845 * decommit_view
847 * Decommit some pages of a given view.
848 * The csVirtual section must be held by caller.
850 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
852 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
854 BYTE *p = view->prot + (start >> page_shift);
855 size >>= page_shift;
856 while (size--) *p++ &= ~VPROT_COMMITTED;
857 return STATUS_SUCCESS;
859 return FILE_GetNtStatus();
863 /***********************************************************************
864 * allocate_dos_memory
866 * Allocate the DOS memory range.
868 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
870 size_t size;
871 void *addr = NULL;
872 void * const low_64k = (void *)0x10000;
873 const size_t dosmem_size = 0x110000;
874 int unix_prot = VIRTUAL_GetUnixProt( vprot );
875 struct list *ptr;
877 /* check for existing view */
879 if ((ptr = list_head( &views_list )))
881 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
882 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
885 /* check without the first 64K */
887 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
889 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
890 if (addr != low_64k)
892 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
893 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
897 /* now try to allocate the low 64K too */
899 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
901 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
902 if (addr == (void *)page_size)
904 addr = NULL;
905 TRACE( "successfully mapped low 64K range\n" );
907 else
909 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
910 addr = low_64k;
911 TRACE( "failed to map low 64K range\n" );
915 /* now reserve the whole range */
917 size = (char *)dosmem_size - (char *)addr;
918 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
919 return create_view( view, addr, size, vprot );
923 /***********************************************************************
924 * map_image
926 * Map an executable (PE format) image into memory.
928 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
929 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
931 IMAGE_DOS_HEADER *dos;
932 IMAGE_NT_HEADERS *nt;
933 IMAGE_SECTION_HEADER *sec;
934 IMAGE_DATA_DIRECTORY *imports;
935 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
936 int i;
937 off_t pos;
938 sigset_t sigset;
939 struct stat st;
940 struct file_view *view = NULL;
941 char *ptr, *header_end;
942 int delta = 0;
944 /* zero-map the whole range */
946 server_enter_uninterrupted_section( &csVirtual, &sigset );
948 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
949 status = map_view( &view, base, total_size, mask, FALSE,
950 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
952 if (status == STATUS_CONFLICTING_ADDRESSES)
953 status = map_view( &view, NULL, total_size, mask, FALSE,
954 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
956 if (status != STATUS_SUCCESS) goto error;
958 ptr = view->base;
959 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
961 /* map the header */
963 if (fstat( fd, &st ) == -1)
965 status = FILE_GetNtStatus();
966 goto error;
968 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
969 if (!st.st_size) goto error;
970 header_size = min( header_size, st.st_size );
971 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
972 !dup_mapping ) != STATUS_SUCCESS) goto error;
973 dos = (IMAGE_DOS_HEADER *)ptr;
974 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
975 header_end = ptr + ROUND_SIZE( 0, header_size );
976 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
977 if ((char *)(nt + 1) > header_end) goto error;
978 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
979 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
981 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
982 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
984 /* check the architecture */
986 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
988 MESSAGE("Trying to load PE image for unsupported architecture (");
989 switch (nt->FileHeader.Machine)
991 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
992 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
993 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
994 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
995 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
996 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
997 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
998 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
999 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
1000 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
1001 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
1002 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1004 MESSAGE(")\n");
1005 goto error;
1008 /* check for non page-aligned binary */
1010 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1012 /* unaligned sections, this happens for native subsystem binaries */
1013 /* in that case Windows simply maps in the whole file */
1015 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1016 !dup_mapping ) != STATUS_SUCCESS) goto error;
1018 /* check that all sections are loaded at the right offset */
1019 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1020 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1022 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1023 goto error; /* Windows refuses to load in that case too */
1026 /* set the image protections */
1027 VIRTUAL_SetProt( view, ptr, total_size,
1028 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1030 /* no relocations are performed on non page-aligned binaries */
1031 goto done;
1035 /* map all the sections */
1037 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1039 static const SIZE_T sector_align = 0x1ff;
1040 SIZE_T map_size, file_start, file_size, end;
1042 if (!sec->Misc.VirtualSize)
1043 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1044 else
1045 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1047 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1048 file_start = sec->PointerToRawData & ~sector_align;
1049 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1050 if (file_size > map_size) file_size = map_size;
1052 /* a few sanity checks */
1053 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1054 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1056 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1057 sec->Name, sec->VirtualAddress, map_size, total_size );
1058 goto error;
1061 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1062 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1064 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1065 sec->Name, ptr + sec->VirtualAddress,
1066 sec->PointerToRawData, (int)pos, file_size, map_size,
1067 sec->Characteristics );
1068 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1069 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1070 FALSE ) != STATUS_SUCCESS)
1072 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1073 goto error;
1076 /* check if the import directory falls inside this section */
1077 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1078 imports->VirtualAddress < sec->VirtualAddress + map_size)
1080 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1081 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1082 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1083 if (end > base)
1084 map_file_into_view( view, shared_fd, base, end - base,
1085 pos + (base - sec->VirtualAddress),
1086 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1087 FALSE );
1089 pos += map_size;
1090 continue;
1093 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1094 sec->Name, ptr + sec->VirtualAddress,
1095 sec->PointerToRawData, sec->SizeOfRawData,
1096 sec->Misc.VirtualSize, sec->Characteristics );
1098 if (!sec->PointerToRawData || !file_size) continue;
1100 /* Note: if the section is not aligned properly map_file_into_view will magically
1101 * fall back to read(), so we don't need to check anything here.
1103 end = file_start + file_size;
1104 if (sec->PointerToRawData >= st.st_size ||
1105 end > ((st.st_size + sector_align) & ~sector_align) ||
1106 end < file_start ||
1107 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1108 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1109 !dup_mapping ) != STATUS_SUCCESS)
1111 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1112 goto error;
1115 if (file_size & page_mask)
1117 end = ROUND_SIZE( 0, file_size );
1118 if (end > map_size) end = map_size;
1119 TRACE_(module)("clearing %p - %p\n",
1120 ptr + sec->VirtualAddress + file_size,
1121 ptr + sec->VirtualAddress + end );
1122 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1127 /* perform base relocation, if necessary */
1129 if (ptr != base &&
1130 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1131 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1133 IMAGE_BASE_RELOCATION *rel, *end;
1134 const IMAGE_DATA_DIRECTORY *relocs;
1136 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1138 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1139 base, ptr );
1140 status = STATUS_CONFLICTING_ADDRESSES;
1141 goto error;
1144 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1145 base, base + total_size, ptr, ptr + total_size );
1147 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1148 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1149 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1150 delta = ptr - base;
1152 while (rel < end - 1 && rel->SizeOfBlock)
1154 if (rel->VirtualAddress >= total_size)
1156 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1157 status = STATUS_ACCESS_VIOLATION;
1158 goto error;
1160 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1161 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1162 (USHORT *)(rel + 1), delta );
1163 if (!rel) goto error;
1167 /* set the image protections */
1169 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1171 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1172 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1174 SIZE_T size;
1175 BYTE vprot = VPROT_COMMITTED;
1177 if (sec->Misc.VirtualSize)
1178 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1179 else
1180 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1182 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1183 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1184 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1186 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1187 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1188 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1189 vprot |= VPROT_EXEC;
1191 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1194 done:
1195 view->mapping = dup_mapping;
1196 server_leave_uninterrupted_section( &csVirtual, &sigset );
1198 *addr_ptr = ptr;
1199 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1200 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1201 #endif
1202 return STATUS_SUCCESS;
1204 error:
1205 if (view) delete_view( view );
1206 server_leave_uninterrupted_section( &csVirtual, &sigset );
1207 if (dup_mapping) NtClose( dup_mapping );
1208 return status;
1212 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1213 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1215 void **heap_base = arg;
1217 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1218 if (size < VIRTUAL_HEAP_SIZE) return 0;
1219 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1220 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1221 return (*heap_base != (void *)-1);
1224 /***********************************************************************
1225 * virtual_init
1227 void virtual_init(void)
1229 const char *preload;
1230 void *heap_base;
1231 struct file_view *heap_view;
1233 #ifndef page_mask
1234 page_size = getpagesize();
1235 page_mask = page_size - 1;
1236 /* Make sure we have a power of 2 */
1237 assert( !(page_size & page_mask) );
1238 page_shift = 0;
1239 while ((1 << page_shift) != page_size) page_shift++;
1240 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1241 #endif /* page_mask */
1242 if ((preload = getenv("WINEPRELOADRESERVE")))
1244 unsigned long start, end;
1245 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1247 preload_reserve_start = (void *)start;
1248 preload_reserve_end = (void *)end;
1252 /* try to find space in a reserved area for the virtual heap */
1253 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1254 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1256 assert( heap_base != (void *)-1 );
1257 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1258 VIRTUAL_HEAP_SIZE, NULL, NULL );
1259 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1263 /***********************************************************************
1264 * virtual_init_threading
1266 void virtual_init_threading(void)
1268 use_locks = 1;
1272 /***********************************************************************
1273 * virtual_get_system_info
1275 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1277 info->dwUnknown1 = 0;
1278 info->uKeMaximumIncrement = 0; /* FIXME */
1279 info->uPageSize = page_size;
1280 info->uMmLowestPhysicalPage = 1;
1281 info->uMmHighestPhysicalPage = 0x7fffffff / page_size;
1282 info->uMmNumberOfPhysicalPages = info->uMmHighestPhysicalPage - info->uMmLowestPhysicalPage;
1283 info->uAllocationGranularity = get_mask(0) + 1;
1284 info->pLowestUserAddress = (void *)0x10000;
1285 info->pMmHighestUserAddress = (char *)user_space_limit - 1;
1286 info->uKeActiveProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1287 info->bKeNumberProcessors = info->uKeActiveProcessors;
1291 /***********************************************************************
1292 * virtual_create_system_view
1294 NTSTATUS virtual_create_system_view( void *base, SIZE_T size, DWORD vprot )
1296 FILE_VIEW *view;
1297 NTSTATUS status;
1298 sigset_t sigset;
1300 size = ROUND_SIZE( base, size );
1301 base = ROUND_ADDR( base, page_mask );
1302 server_enter_uninterrupted_section( &csVirtual, &sigset );
1303 status = create_view( &view, base, size, vprot );
1304 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1305 server_leave_uninterrupted_section( &csVirtual, &sigset );
1306 return status;
1310 /***********************************************************************
1311 * virtual_free_system_view
1313 SIZE_T virtual_free_system_view( PVOID *addr_ptr )
1315 FILE_VIEW *view;
1316 sigset_t sigset;
1317 SIZE_T size = 0;
1318 char *base = ROUND_ADDR( *addr_ptr, page_mask );
1320 server_enter_uninterrupted_section( &csVirtual, &sigset );
1321 if ((view = VIRTUAL_FindView( base )))
1323 TRACE( "freeing %p-%p\n", view->base, (char *)view->base + view->size );
1324 /* return the values that the caller should use to unmap the area */
1325 *addr_ptr = view->base;
1326 /* make sure we don't munmap anything from a reserved area */
1327 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) size = view->size;
1328 view->protect |= VPROT_SYSTEM;
1329 delete_view( view );
1331 server_leave_uninterrupted_section( &csVirtual, &sigset );
1332 return size;
1336 /***********************************************************************
1337 * virtual_alloc_thread_stack
1339 NTSTATUS virtual_alloc_thread_stack( void *base, SIZE_T size )
1341 FILE_VIEW *view;
1342 NTSTATUS status;
1343 sigset_t sigset;
1345 server_enter_uninterrupted_section( &csVirtual, &sigset );
1347 if (base) /* already allocated, create a system view */
1349 size = ROUND_SIZE( base, size );
1350 base = ROUND_ADDR( base, page_mask );
1351 if ((status = create_view( &view, base, size,
1352 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC | VPROT_SYSTEM )) != STATUS_SUCCESS)
1353 goto done;
1355 else
1357 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1358 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1359 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1360 goto done;
1361 #ifdef VALGRIND_STACK_REGISTER
1362 /* no need to de-register the stack as it's the one of the main thread */
1363 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1364 #endif
1367 /* setup no access guard page */
1368 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1369 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1370 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1372 /* note: limit is lower than base since the stack grows down */
1373 NtCurrentTeb()->DeallocationStack = view->base;
1374 NtCurrentTeb()->Tib.StackBase = (char *)view->base + view->size;
1375 NtCurrentTeb()->Tib.StackLimit = (char *)view->base + 2 * page_size;
1377 done:
1378 server_leave_uninterrupted_section( &csVirtual, &sigset );
1379 return status;
1383 /***********************************************************************
1384 * virtual_clear_thread_stack
1386 * Clear the stack contents before calling the main entry point, some broken apps need that.
1388 void virtual_clear_thread_stack(void)
1390 void *stack = NtCurrentTeb()->Tib.StackLimit;
1391 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1393 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1394 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1398 /***********************************************************************
1399 * VIRTUAL_HandleFault
1401 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1403 FILE_VIEW *view;
1404 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1405 sigset_t sigset;
1407 server_enter_uninterrupted_section( &csVirtual, &sigset );
1408 if ((view = VIRTUAL_FindView( addr )))
1410 void *page = ROUND_ADDR( addr, page_mask );
1411 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1412 if (vprot & VPROT_GUARD)
1414 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1415 ret = STATUS_GUARD_PAGE_VIOLATION;
1418 server_leave_uninterrupted_section( &csVirtual, &sigset );
1419 return ret;
1424 /***********************************************************************
1425 * virtual_handle_stack_fault
1427 * Handle an access fault inside the current thread stack.
1428 * Called from inside a signal handler.
1430 BOOL virtual_handle_stack_fault( void *addr )
1432 FILE_VIEW *view;
1433 BOOL ret = FALSE;
1435 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1436 if ((view = VIRTUAL_FindView( addr )))
1438 void *page = ROUND_ADDR( addr, page_mask );
1439 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1440 if (vprot & VPROT_GUARD)
1442 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1443 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1444 NtCurrentTeb()->Tib.StackLimit = page;
1445 ret = TRUE;
1448 RtlLeaveCriticalSection( &csVirtual );
1449 return ret;
1453 /***********************************************************************
1454 * VIRTUAL_SetForceExec
1456 * Whether to force exec prot on all views.
1458 void VIRTUAL_SetForceExec( BOOL enable )
1460 struct file_view *view;
1461 sigset_t sigset;
1463 server_enter_uninterrupted_section( &csVirtual, &sigset );
1464 if (!force_exec_prot != !enable) /* change all existing views */
1466 force_exec_prot = enable;
1468 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1470 UINT i, count;
1471 char *addr = view->base;
1472 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1473 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1475 if (view->protect & VPROT_NOEXEC) continue;
1476 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1478 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1479 if (prot == unix_prot) continue;
1480 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1482 TRACE( "%s exec prot for %p-%p\n",
1483 force_exec_prot ? "enabling" : "disabling",
1484 addr, addr + (count << page_shift) - 1 );
1485 mprotect( addr, count << page_shift,
1486 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1488 addr += (count << page_shift);
1489 unix_prot = prot;
1490 count = 0;
1492 if (count)
1494 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1496 TRACE( "%s exec prot for %p-%p\n",
1497 force_exec_prot ? "enabling" : "disabling",
1498 addr, addr + (count << page_shift) - 1 );
1499 mprotect( addr, count << page_shift,
1500 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1505 server_leave_uninterrupted_section( &csVirtual, &sigset );
1509 /***********************************************************************
1510 * VIRTUAL_UseLargeAddressSpace
1512 * Increase the address space size for apps that support it.
1514 void VIRTUAL_UseLargeAddressSpace(void)
1516 /* no large address space on win9x */
1517 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1518 user_space_limit = working_set_limit = address_space_limit;
1522 /***********************************************************************
1523 * NtAllocateVirtualMemory (NTDLL.@)
1524 * ZwAllocateVirtualMemory (NTDLL.@)
1526 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1527 SIZE_T *size_ptr, ULONG type, ULONG protect )
1529 void *base;
1530 unsigned int vprot;
1531 SIZE_T size = *size_ptr;
1532 SIZE_T mask = get_mask( zero_bits );
1533 NTSTATUS status = STATUS_SUCCESS;
1534 struct file_view *view;
1535 sigset_t sigset;
1537 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1539 if (!size) return STATUS_INVALID_PARAMETER;
1541 if (process != NtCurrentProcess())
1543 apc_call_t call;
1544 apc_result_t result;
1546 memset( &call, 0, sizeof(call) );
1548 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1549 call.virtual_alloc.addr = *ret;
1550 call.virtual_alloc.size = *size_ptr;
1551 call.virtual_alloc.zero_bits = zero_bits;
1552 call.virtual_alloc.op_type = type;
1553 call.virtual_alloc.prot = protect;
1554 status = NTDLL_queue_process_apc( process, &call, &result );
1555 if (status != STATUS_SUCCESS) return status;
1557 if (result.virtual_alloc.status == STATUS_SUCCESS)
1559 *ret = result.virtual_alloc.addr;
1560 *size_ptr = result.virtual_alloc.size;
1562 return result.virtual_alloc.status;
1565 /* Round parameters to a page boundary */
1567 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1569 vprot = VIRTUAL_GetProt( protect ) | VPROT_VALLOC;
1570 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1572 if (*ret)
1574 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1575 base = ROUND_ADDR( *ret, mask );
1576 else
1577 base = ROUND_ADDR( *ret, page_mask );
1578 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1580 /* address 1 is magic to mean DOS area */
1581 if (!base && *ret == (void *)1 && size == 0x110000)
1583 server_enter_uninterrupted_section( &csVirtual, &sigset );
1584 status = allocate_dos_memory( &view, vprot );
1585 if (status == STATUS_SUCCESS)
1587 *ret = view->base;
1588 *size_ptr = view->size;
1590 server_leave_uninterrupted_section( &csVirtual, &sigset );
1591 return status;
1594 /* disallow low 64k, wrap-around and kernel space */
1595 if (((char *)base < (char *)0x10000) ||
1596 ((char *)base + size < (char *)base) ||
1597 is_beyond_limit( base, size, address_space_limit ))
1598 return STATUS_INVALID_PARAMETER;
1600 else
1602 base = NULL;
1603 size = (size + page_mask) & ~page_mask;
1606 /* Compute the alloc type flags */
1608 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1609 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1611 WARN("called with wrong alloc type flags (%08x) !\n", type);
1612 return STATUS_INVALID_PARAMETER;
1614 if (type & MEM_WRITE_WATCH)
1616 FIXME("MEM_WRITE_WATCH type not supported\n");
1617 return STATUS_INVALID_PARAMETER;
1620 /* Reserve the memory */
1622 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1624 if ((type & MEM_RESERVE) || !base)
1626 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1627 if (status == STATUS_SUCCESS) base = view->base;
1629 else /* commit the pages */
1631 if (!(view = VIRTUAL_FindView( base )) ||
1632 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1633 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1634 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1636 SERVER_START_REQ( add_mapping_committed_range )
1638 req->handle = view->mapping;
1639 req->offset = (char *)base - (char *)view->base;
1640 req->size = size;
1641 wine_server_call( req );
1643 SERVER_END_REQ;
1647 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1649 if (status == STATUS_SUCCESS)
1651 *ret = base;
1652 *size_ptr = size;
1654 return status;
1658 /***********************************************************************
1659 * NtFreeVirtualMemory (NTDLL.@)
1660 * ZwFreeVirtualMemory (NTDLL.@)
1662 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1664 FILE_VIEW *view;
1665 char *base;
1666 sigset_t sigset;
1667 NTSTATUS status = STATUS_SUCCESS;
1668 LPVOID addr = *addr_ptr;
1669 SIZE_T size = *size_ptr;
1671 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1673 if (process != NtCurrentProcess())
1675 apc_call_t call;
1676 apc_result_t result;
1678 memset( &call, 0, sizeof(call) );
1680 call.virtual_free.type = APC_VIRTUAL_FREE;
1681 call.virtual_free.addr = addr;
1682 call.virtual_free.size = size;
1683 call.virtual_free.op_type = type;
1684 status = NTDLL_queue_process_apc( process, &call, &result );
1685 if (status != STATUS_SUCCESS) return status;
1687 if (result.virtual_free.status == STATUS_SUCCESS)
1689 *addr_ptr = result.virtual_free.addr;
1690 *size_ptr = result.virtual_free.size;
1692 return result.virtual_free.status;
1695 /* Fix the parameters */
1697 size = ROUND_SIZE( addr, size );
1698 base = ROUND_ADDR( addr, page_mask );
1700 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1701 if (!base) return STATUS_INVALID_PARAMETER;
1703 server_enter_uninterrupted_section( &csVirtual, &sigset );
1705 if (!(view = VIRTUAL_FindView( base )) ||
1706 (base + size > (char *)view->base + view->size) ||
1707 !(view->protect & VPROT_VALLOC))
1709 status = STATUS_INVALID_PARAMETER;
1711 else if (type == MEM_RELEASE)
1713 /* Free the pages */
1715 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1716 else
1718 delete_view( view );
1719 *addr_ptr = base;
1720 *size_ptr = size;
1723 else if (type == MEM_DECOMMIT)
1725 status = decommit_pages( view, base - (char *)view->base, size );
1726 if (status == STATUS_SUCCESS)
1728 *addr_ptr = base;
1729 *size_ptr = size;
1732 else
1734 WARN("called with wrong free type flags (%08x) !\n", type);
1735 status = STATUS_INVALID_PARAMETER;
1738 server_leave_uninterrupted_section( &csVirtual, &sigset );
1739 return status;
1743 /***********************************************************************
1744 * NtProtectVirtualMemory (NTDLL.@)
1745 * ZwProtectVirtualMemory (NTDLL.@)
1747 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1748 ULONG new_prot, ULONG *old_prot )
1750 FILE_VIEW *view;
1751 sigset_t sigset;
1752 NTSTATUS status = STATUS_SUCCESS;
1753 char *base;
1754 BYTE vprot;
1755 SIZE_T size = *size_ptr;
1756 LPVOID addr = *addr_ptr;
1758 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1760 if (process != NtCurrentProcess())
1762 apc_call_t call;
1763 apc_result_t result;
1765 memset( &call, 0, sizeof(call) );
1767 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1768 call.virtual_protect.addr = addr;
1769 call.virtual_protect.size = size;
1770 call.virtual_protect.prot = new_prot;
1771 status = NTDLL_queue_process_apc( process, &call, &result );
1772 if (status != STATUS_SUCCESS) return status;
1774 if (result.virtual_protect.status == STATUS_SUCCESS)
1776 *addr_ptr = result.virtual_protect.addr;
1777 *size_ptr = result.virtual_protect.size;
1778 if (old_prot) *old_prot = result.virtual_protect.prot;
1780 return result.virtual_protect.status;
1783 /* Fix the parameters */
1785 size = ROUND_SIZE( addr, size );
1786 base = ROUND_ADDR( addr, page_mask );
1788 server_enter_uninterrupted_section( &csVirtual, &sigset );
1790 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1792 status = STATUS_INVALID_PARAMETER;
1794 else
1796 /* Make sure all the pages are committed */
1797 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1799 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1800 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1801 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1803 else status = STATUS_NOT_COMMITTED;
1805 server_leave_uninterrupted_section( &csVirtual, &sigset );
1807 if (status == STATUS_SUCCESS)
1809 *addr_ptr = base;
1810 *size_ptr = size;
1812 return status;
1816 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
1817 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
1819 MEMORY_BASIC_INFORMATION *info = arg;
1820 void *end = (char *)start + size;
1822 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
1824 if (info->BaseAddress >= end)
1826 if (info->AllocationBase < end) info->AllocationBase = end;
1827 return 0;
1830 if (info->BaseAddress >= start)
1832 /* it's a real free area */
1833 info->State = MEM_FREE;
1834 info->Protect = PAGE_NOACCESS;
1835 info->AllocationBase = 0;
1836 info->AllocationProtect = 0;
1837 info->Type = 0;
1838 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
1839 info->RegionSize = (char *)end - (char *)info->BaseAddress;
1841 else /* outside of the reserved area, pretend it's allocated */
1843 info->RegionSize = (char *)start - (char *)info->BaseAddress;
1844 info->State = MEM_RESERVE;
1845 info->Protect = PAGE_NOACCESS;
1846 info->AllocationProtect = PAGE_NOACCESS;
1847 info->Type = MEM_PRIVATE;
1849 return 1;
1852 #define UNIMPLEMENTED_INFO_CLASS(c) \
1853 case c: \
1854 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1855 return STATUS_INVALID_INFO_CLASS
1857 /***********************************************************************
1858 * NtQueryVirtualMemory (NTDLL.@)
1859 * ZwQueryVirtualMemory (NTDLL.@)
1861 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1862 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1863 SIZE_T len, SIZE_T *res_len )
1865 FILE_VIEW *view;
1866 char *base, *alloc_base = 0;
1867 struct list *ptr;
1868 SIZE_T size = 0;
1869 MEMORY_BASIC_INFORMATION *info = buffer;
1870 sigset_t sigset;
1872 if (info_class != MemoryBasicInformation)
1874 switch(info_class)
1876 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1877 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1878 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1880 default:
1881 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1882 process, addr, info_class, buffer, len, res_len);
1883 return STATUS_INVALID_INFO_CLASS;
1887 if (process != NtCurrentProcess())
1889 NTSTATUS status;
1890 apc_call_t call;
1891 apc_result_t result;
1893 memset( &call, 0, sizeof(call) );
1895 call.virtual_query.type = APC_VIRTUAL_QUERY;
1896 call.virtual_query.addr = addr;
1897 status = NTDLL_queue_process_apc( process, &call, &result );
1898 if (status != STATUS_SUCCESS) return status;
1900 if (result.virtual_query.status == STATUS_SUCCESS)
1902 info->BaseAddress = result.virtual_query.base;
1903 info->AllocationBase = result.virtual_query.alloc_base;
1904 info->RegionSize = result.virtual_query.size;
1905 info->State = result.virtual_query.state;
1906 info->Protect = result.virtual_query.prot;
1907 info->AllocationProtect = result.virtual_query.alloc_prot;
1908 info->Type = result.virtual_query.alloc_type;
1909 if (res_len) *res_len = sizeof(*info);
1911 return result.virtual_query.status;
1914 base = ROUND_ADDR( addr, page_mask );
1916 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1918 /* Find the view containing the address */
1920 server_enter_uninterrupted_section( &csVirtual, &sigset );
1921 ptr = list_head( &views_list );
1922 for (;;)
1924 if (!ptr)
1926 size = (char *)working_set_limit - alloc_base;
1927 view = NULL;
1928 break;
1930 view = LIST_ENTRY( ptr, struct file_view, entry );
1931 if ((char *)view->base > base)
1933 size = (char *)view->base - alloc_base;
1934 view = NULL;
1935 break;
1937 if ((char *)view->base + view->size > base)
1939 alloc_base = view->base;
1940 size = view->size;
1941 break;
1943 alloc_base = (char *)view->base + view->size;
1944 ptr = list_next( &views_list, ptr );
1947 /* Fill the info structure */
1949 info->AllocationBase = alloc_base;
1950 info->BaseAddress = base;
1951 info->RegionSize = size - (base - alloc_base);
1953 if (!view)
1955 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
1957 /* not in a reserved area at all, pretend it's allocated */
1958 info->State = MEM_RESERVE;
1959 info->Protect = PAGE_NOACCESS;
1960 info->AllocationProtect = PAGE_NOACCESS;
1961 info->Type = MEM_PRIVATE;
1964 else
1966 BYTE vprot;
1967 SIZE_T range_size = get_committed_size( view, base, &vprot );
1969 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1970 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
1971 info->AllocationBase = alloc_base;
1972 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1973 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1974 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
1975 else info->Type = MEM_MAPPED;
1976 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
1977 if (view->prot[size >> page_shift] != vprot) break;
1978 info->RegionSize = size - (base - alloc_base);
1980 server_leave_uninterrupted_section( &csVirtual, &sigset );
1982 if (res_len) *res_len = sizeof(*info);
1983 return STATUS_SUCCESS;
1987 /***********************************************************************
1988 * NtLockVirtualMemory (NTDLL.@)
1989 * ZwLockVirtualMemory (NTDLL.@)
1991 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1993 NTSTATUS status = STATUS_SUCCESS;
1995 if (process != NtCurrentProcess())
1997 apc_call_t call;
1998 apc_result_t result;
2000 memset( &call, 0, sizeof(call) );
2002 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2003 call.virtual_lock.addr = *addr;
2004 call.virtual_lock.size = *size;
2005 status = NTDLL_queue_process_apc( process, &call, &result );
2006 if (status != STATUS_SUCCESS) return status;
2008 if (result.virtual_lock.status == STATUS_SUCCESS)
2010 *addr = result.virtual_lock.addr;
2011 *size = result.virtual_lock.size;
2013 return result.virtual_lock.status;
2016 *size = ROUND_SIZE( *addr, *size );
2017 *addr = ROUND_ADDR( *addr, page_mask );
2019 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2020 return status;
2024 /***********************************************************************
2025 * NtUnlockVirtualMemory (NTDLL.@)
2026 * ZwUnlockVirtualMemory (NTDLL.@)
2028 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2030 NTSTATUS status = STATUS_SUCCESS;
2032 if (process != NtCurrentProcess())
2034 apc_call_t call;
2035 apc_result_t result;
2037 memset( &call, 0, sizeof(call) );
2039 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2040 call.virtual_unlock.addr = *addr;
2041 call.virtual_unlock.size = *size;
2042 status = NTDLL_queue_process_apc( process, &call, &result );
2043 if (status != STATUS_SUCCESS) return status;
2045 if (result.virtual_unlock.status == STATUS_SUCCESS)
2047 *addr = result.virtual_unlock.addr;
2048 *size = result.virtual_unlock.size;
2050 return result.virtual_unlock.status;
2053 *size = ROUND_SIZE( *addr, *size );
2054 *addr = ROUND_ADDR( *addr, page_mask );
2056 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2057 return status;
2061 /***********************************************************************
2062 * NtCreateSection (NTDLL.@)
2063 * ZwCreateSection (NTDLL.@)
2065 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2066 const LARGE_INTEGER *size, ULONG protect,
2067 ULONG sec_flags, HANDLE file )
2069 NTSTATUS ret;
2070 unsigned int vprot;
2071 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2072 struct security_descriptor *sd = NULL;
2073 struct object_attributes objattr;
2075 /* Check parameters */
2077 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2079 objattr.rootdir = attr ? attr->RootDirectory : 0;
2080 objattr.sd_len = 0;
2081 objattr.name_len = len;
2082 if (attr)
2084 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2085 if (ret != STATUS_SUCCESS) return ret;
2088 vprot = VIRTUAL_GetProt( protect );
2089 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2090 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2091 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2093 /* Create the server object */
2095 SERVER_START_REQ( create_mapping )
2097 req->access = access;
2098 req->attributes = (attr) ? attr->Attributes : 0;
2099 req->file_handle = file;
2100 req->size = size ? size->QuadPart : 0;
2101 req->protect = vprot;
2102 wine_server_add_data( req, &objattr, sizeof(objattr) );
2103 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2104 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2105 ret = wine_server_call( req );
2106 *handle = reply->handle;
2108 SERVER_END_REQ;
2110 NTDLL_free_struct_sd( sd );
2112 return ret;
2116 /***********************************************************************
2117 * NtOpenSection (NTDLL.@)
2118 * ZwOpenSection (NTDLL.@)
2120 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2122 NTSTATUS ret;
2123 DWORD len = attr->ObjectName->Length;
2125 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2127 SERVER_START_REQ( open_mapping )
2129 req->access = access;
2130 req->attributes = attr->Attributes;
2131 req->rootdir = attr->RootDirectory;
2132 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2133 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
2135 SERVER_END_REQ;
2136 return ret;
2140 /***********************************************************************
2141 * NtMapViewOfSection (NTDLL.@)
2142 * ZwMapViewOfSection (NTDLL.@)
2144 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2145 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2146 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2148 NTSTATUS res;
2149 ULONGLONG full_size;
2150 ACCESS_MASK access;
2151 SIZE_T size = 0;
2152 SIZE_T mask = get_mask( zero_bits );
2153 int unix_handle = -1, needs_close;
2154 unsigned int map_vprot, vprot;
2155 void *base;
2156 struct file_view *view;
2157 DWORD header_size;
2158 HANDLE dup_mapping, shared_file;
2159 LARGE_INTEGER offset;
2160 sigset_t sigset;
2162 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2164 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2165 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2167 /* Check parameters */
2169 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2170 return STATUS_INVALID_PARAMETER;
2172 if (process != NtCurrentProcess())
2174 apc_call_t call;
2175 apc_result_t result;
2177 memset( &call, 0, sizeof(call) );
2179 call.map_view.type = APC_MAP_VIEW;
2180 call.map_view.handle = handle;
2181 call.map_view.addr = *addr_ptr;
2182 call.map_view.size = *size_ptr;
2183 call.map_view.offset = offset.QuadPart;
2184 call.map_view.zero_bits = zero_bits;
2185 call.map_view.alloc_type = alloc_type;
2186 call.map_view.prot = protect;
2187 res = NTDLL_queue_process_apc( process, &call, &result );
2188 if (res != STATUS_SUCCESS) return res;
2190 if (result.map_view.status == STATUS_SUCCESS)
2192 *addr_ptr = result.map_view.addr;
2193 *size_ptr = result.map_view.size;
2195 return result.map_view.status;
2198 switch(protect)
2200 case PAGE_NOACCESS:
2201 access = SECTION_QUERY;
2202 break;
2203 case PAGE_READWRITE:
2204 case PAGE_EXECUTE_READWRITE:
2205 access = SECTION_QUERY | SECTION_MAP_WRITE;
2206 break;
2207 case PAGE_READONLY:
2208 case PAGE_WRITECOPY:
2209 case PAGE_EXECUTE:
2210 case PAGE_EXECUTE_READ:
2211 case PAGE_EXECUTE_WRITECOPY:
2212 access = SECTION_QUERY | SECTION_MAP_READ;
2213 break;
2214 default:
2215 return STATUS_INVALID_PARAMETER;
2218 SERVER_START_REQ( get_mapping_info )
2220 req->handle = handle;
2221 req->access = access;
2222 res = wine_server_call( req );
2223 map_vprot = reply->protect;
2224 base = reply->base;
2225 full_size = reply->size;
2226 header_size = reply->header_size;
2227 dup_mapping = reply->mapping;
2228 shared_file = reply->shared_file;
2230 SERVER_END_REQ;
2231 if (res) return res;
2233 size = full_size;
2234 if (sizeof(size) < sizeof(full_size) && (size != full_size))
2235 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
2236 (DWORD)(full_size >> 32), (DWORD)full_size );
2238 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2240 if (map_vprot & VPROT_IMAGE)
2242 if (shared_file)
2244 int shared_fd, shared_needs_close;
2246 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2247 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2248 res = map_image( handle, unix_handle, base, size, mask, header_size,
2249 shared_fd, dup_mapping, addr_ptr );
2250 if (shared_needs_close) close( shared_fd );
2251 NtClose( shared_file );
2253 else
2255 res = map_image( handle, unix_handle, base, size, mask, header_size,
2256 -1, dup_mapping, addr_ptr );
2258 if (needs_close) close( unix_handle );
2259 if (!res) *size_ptr = size;
2260 return res;
2263 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2265 res = STATUS_INVALID_PARAMETER;
2266 goto done;
2268 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2269 else size = size - offset.QuadPart;
2271 /* Reserve a properly aligned area */
2273 server_enter_uninterrupted_section( &csVirtual, &sigset );
2275 vprot = VIRTUAL_GetProt( protect ) | (map_vprot & VPROT_COMMITTED);
2276 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2277 if (res)
2279 server_leave_uninterrupted_section( &csVirtual, &sigset );
2280 goto done;
2283 /* Map the file */
2285 TRACE("handle=%p size=%lx offset=%x%08x\n",
2286 handle, size, offset.u.HighPart, offset.u.LowPart );
2288 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2289 if (res == STATUS_SUCCESS)
2291 *addr_ptr = view->base;
2292 *size_ptr = size;
2293 view->mapping = dup_mapping;
2294 dup_mapping = 0; /* don't close it */
2296 else
2298 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2299 view->base, size, offset.u.HighPart, offset.u.LowPart );
2300 delete_view( view );
2303 server_leave_uninterrupted_section( &csVirtual, &sigset );
2305 done:
2306 if (dup_mapping) NtClose( dup_mapping );
2307 if (needs_close) close( unix_handle );
2308 return res;
2312 /***********************************************************************
2313 * NtUnmapViewOfSection (NTDLL.@)
2314 * ZwUnmapViewOfSection (NTDLL.@)
2316 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2318 FILE_VIEW *view;
2319 NTSTATUS status = STATUS_INVALID_PARAMETER;
2320 sigset_t sigset;
2321 void *base = ROUND_ADDR( addr, page_mask );
2323 if (process != NtCurrentProcess())
2325 apc_call_t call;
2326 apc_result_t result;
2328 memset( &call, 0, sizeof(call) );
2330 call.unmap_view.type = APC_UNMAP_VIEW;
2331 call.unmap_view.addr = addr;
2332 status = NTDLL_queue_process_apc( process, &call, &result );
2333 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2334 return status;
2337 server_enter_uninterrupted_section( &csVirtual, &sigset );
2338 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2340 delete_view( view );
2341 status = STATUS_SUCCESS;
2343 server_leave_uninterrupted_section( &csVirtual, &sigset );
2344 return status;
2348 /***********************************************************************
2349 * NtFlushVirtualMemory (NTDLL.@)
2350 * ZwFlushVirtualMemory (NTDLL.@)
2352 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2353 SIZE_T *size_ptr, ULONG unknown )
2355 FILE_VIEW *view;
2356 NTSTATUS status = STATUS_SUCCESS;
2357 sigset_t sigset;
2358 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2360 if (process != NtCurrentProcess())
2362 apc_call_t call;
2363 apc_result_t result;
2365 memset( &call, 0, sizeof(call) );
2367 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2368 call.virtual_flush.addr = addr;
2369 call.virtual_flush.size = *size_ptr;
2370 status = NTDLL_queue_process_apc( process, &call, &result );
2371 if (status != STATUS_SUCCESS) return status;
2373 if (result.virtual_flush.status == STATUS_SUCCESS)
2375 *addr_ptr = result.virtual_flush.addr;
2376 *size_ptr = result.virtual_flush.size;
2378 return result.virtual_flush.status;
2381 server_enter_uninterrupted_section( &csVirtual, &sigset );
2382 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2383 else
2385 if (!*size_ptr) *size_ptr = view->size;
2386 *addr_ptr = addr;
2387 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2389 server_leave_uninterrupted_section( &csVirtual, &sigset );
2390 return status;
2394 /***********************************************************************
2395 * NtGetWriteWatch (NTDLL.@)
2396 * ZwGetWriteWatch (NTDLL.@)
2398 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2399 ULONG_PTR *count, ULONG *granularity )
2401 FIXME( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size, addresses, *count );
2402 return STATUS_NOT_IMPLEMENTED;
2406 /***********************************************************************
2407 * NtResetWriteWatch (NTDLL.@)
2408 * ZwResetWriteWatch (NTDLL.@)
2410 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2412 FIXME( "%p %p-%p\n", process, base, (char *)base + size );
2413 return STATUS_NOT_IMPLEMENTED;
2417 /***********************************************************************
2418 * NtReadVirtualMemory (NTDLL.@)
2419 * ZwReadVirtualMemory (NTDLL.@)
2421 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2422 SIZE_T size, SIZE_T *bytes_read )
2424 NTSTATUS status;
2426 SERVER_START_REQ( read_process_memory )
2428 req->handle = process;
2429 req->addr = (void *)addr;
2430 wine_server_set_reply( req, buffer, size );
2431 if ((status = wine_server_call( req ))) size = 0;
2433 SERVER_END_REQ;
2434 if (bytes_read) *bytes_read = size;
2435 return status;
2439 /***********************************************************************
2440 * NtWriteVirtualMemory (NTDLL.@)
2441 * ZwWriteVirtualMemory (NTDLL.@)
2443 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2444 SIZE_T size, SIZE_T *bytes_written )
2446 NTSTATUS status;
2448 SERVER_START_REQ( write_process_memory )
2450 req->handle = process;
2451 req->addr = addr;
2452 wine_server_add_data( req, buffer, size );
2453 if ((status = wine_server_call( req ))) size = 0;
2455 SERVER_END_REQ;
2456 if (bytes_written) *bytes_written = size;
2457 return status;
2461 /***********************************************************************
2462 * NtAreMappedFilesTheSame (NTDLL.@)
2463 * ZwAreMappedFilesTheSame (NTDLL.@)
2465 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2467 TRACE("%p %p\n", addr1, addr2);
2469 return STATUS_NOT_SAME_DEVICE;