ntdll: Store correct values in the various limits on all platforms instead of using 0.
[wine/wine-kai.git] / dlls / ntdll / virtual.c
blob21da9afede801174f1fe00e30e03394f5cb61076
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 (((UINT)(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 * unaligned_mmap
760 * Linux kernels before 2.4.x can support non page-aligned offsets, as
761 * long as the offset is aligned to the filesystem block size. This is
762 * a big performance gain so we want to take advantage of it.
764 * However, when we use 64-bit file support this doesn't work because
765 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
766 * in that it rounds unaligned offsets down to a page boundary. For
767 * these reasons we do a direct system call here.
769 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
770 unsigned int flags, int fd, off_t offset )
772 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
773 if (!(offset >> 32) && (offset & page_mask))
775 int ret;
777 struct
779 void *addr;
780 unsigned int length;
781 unsigned int prot;
782 unsigned int flags;
783 unsigned int fd;
784 unsigned int offset;
785 } args;
787 args.addr = addr;
788 args.length = length;
789 args.prot = prot;
790 args.flags = flags;
791 args.fd = fd;
792 args.offset = offset;
794 __asm__ __volatile__("push %%ebx\n\t"
795 "movl %2,%%ebx\n\t"
796 "int $0x80\n\t"
797 "popl %%ebx"
798 : "=a" (ret)
799 : "0" (90), /* SYS_mmap */
800 "q" (&args)
801 : "memory" );
802 if (ret < 0 && ret > -4096)
804 errno = -ret;
805 ret = -1;
807 return (void *)ret;
809 #endif
810 return mmap( addr, length, prot, flags, fd, offset );
814 /***********************************************************************
815 * map_file_into_view
817 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
818 * The csVirtual section must be held by caller.
820 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
821 off_t offset, unsigned int vprot, BOOL removable )
823 void *ptr;
824 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
825 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
827 assert( start < view->size );
828 assert( start + size <= view->size );
830 /* only try mmap if media is not removable (or if we require write access) */
831 if (!removable || shared_write)
833 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
835 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
836 goto done;
838 /* mmap() failed; if this is because the file offset is not */
839 /* page-aligned (EINVAL), or because the underlying filesystem */
840 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
841 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
842 if (shared_write) /* we cannot fake shared write mappings */
844 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
845 ERR( "shared writable mmap not supported, broken filesystem?\n" );
846 return STATUS_NOT_SUPPORTED;
850 /* Reserve the memory with an anonymous mmap */
851 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
852 if (ptr == (void *)-1) return FILE_GetNtStatus();
853 /* Now read in the file */
854 pread( fd, ptr, size, offset );
855 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
856 done:
857 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
858 return STATUS_SUCCESS;
862 /***********************************************************************
863 * get_committed_size
865 * Get the size of the committed range starting at base.
866 * Also return the protections for the first page.
868 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
870 SIZE_T i, start;
872 start = ((char *)base - (char *)view->base) >> page_shift;
873 *vprot = view->prot[start];
875 if (view->mapping && !(view->protect & VPROT_COMMITTED))
877 SIZE_T ret = 0;
878 SERVER_START_REQ( get_mapping_committed_range )
880 req->handle = view->mapping;
881 req->offset = start << page_shift;
882 if (!wine_server_call( req ))
884 ret = reply->size;
885 if (reply->committed)
887 *vprot |= VPROT_COMMITTED;
888 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
892 SERVER_END_REQ;
893 return ret;
895 for (i = start + 1; i < view->size >> page_shift; i++)
896 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
897 return (i - start) << page_shift;
901 /***********************************************************************
902 * decommit_view
904 * Decommit some pages of a given view.
905 * The csVirtual section must be held by caller.
907 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
909 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
911 BYTE *p = view->prot + (start >> page_shift);
912 size >>= page_shift;
913 while (size--) *p++ &= ~VPROT_COMMITTED;
914 return STATUS_SUCCESS;
916 return FILE_GetNtStatus();
920 /***********************************************************************
921 * map_image
923 * Map an executable (PE format) image into memory.
925 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
926 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
928 IMAGE_DOS_HEADER *dos;
929 IMAGE_NT_HEADERS *nt;
930 IMAGE_SECTION_HEADER *sec;
931 IMAGE_DATA_DIRECTORY *imports;
932 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
933 int i;
934 off_t pos;
935 sigset_t sigset;
936 struct stat st;
937 struct file_view *view = NULL;
938 char *ptr, *header_end;
939 int delta = 0;
941 /* zero-map the whole range */
943 server_enter_uninterrupted_section( &csVirtual, &sigset );
945 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
946 status = map_view( &view, base, total_size, mask, FALSE,
947 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
949 if (status == STATUS_CONFLICTING_ADDRESSES)
950 status = map_view( &view, NULL, total_size, mask, FALSE,
951 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
953 if (status != STATUS_SUCCESS) goto error;
955 ptr = view->base;
956 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
958 /* map the header */
960 if (fstat( fd, &st ) == -1)
962 status = FILE_GetNtStatus();
963 goto error;
965 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
966 if (!st.st_size) goto error;
967 header_size = min( header_size, st.st_size );
968 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
969 !dup_mapping ) != STATUS_SUCCESS) goto error;
970 dos = (IMAGE_DOS_HEADER *)ptr;
971 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
972 header_end = ptr + ROUND_SIZE( 0, header_size );
973 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
974 if ((char *)(nt + 1) > header_end) goto error;
975 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
976 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
978 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
979 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
981 /* check the architecture */
983 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
985 MESSAGE("Trying to load PE image for unsupported architecture (");
986 switch (nt->FileHeader.Machine)
988 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
989 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
990 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
991 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
992 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
993 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
994 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
995 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
996 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
997 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
998 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
999 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1001 MESSAGE(")\n");
1002 goto error;
1005 /* check for non page-aligned binary */
1007 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1009 /* unaligned sections, this happens for native subsystem binaries */
1010 /* in that case Windows simply maps in the whole file */
1012 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1013 !dup_mapping ) != STATUS_SUCCESS) goto error;
1015 /* check that all sections are loaded at the right offset */
1016 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1017 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1019 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1020 goto error; /* Windows refuses to load in that case too */
1023 /* set the image protections */
1024 VIRTUAL_SetProt( view, ptr, total_size,
1025 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1027 /* no relocations are performed on non page-aligned binaries */
1028 goto done;
1032 /* map all the sections */
1034 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1036 static const SIZE_T sector_align = 0x1ff;
1037 SIZE_T map_size, file_start, file_size, end;
1039 if (!sec->Misc.VirtualSize)
1040 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1041 else
1042 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1044 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1045 file_start = sec->PointerToRawData & ~sector_align;
1046 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1047 if (file_size > map_size) file_size = map_size;
1049 /* a few sanity checks */
1050 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1051 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1053 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1054 sec->Name, sec->VirtualAddress, map_size, total_size );
1055 goto error;
1058 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1059 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1061 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1062 sec->Name, ptr + sec->VirtualAddress,
1063 sec->PointerToRawData, (int)pos, file_size, map_size,
1064 sec->Characteristics );
1065 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1066 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1067 FALSE ) != STATUS_SUCCESS)
1069 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1070 goto error;
1073 /* check if the import directory falls inside this section */
1074 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1075 imports->VirtualAddress < sec->VirtualAddress + map_size)
1077 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1078 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1079 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1080 if (end > base)
1081 map_file_into_view( view, shared_fd, base, end - base,
1082 pos + (base - sec->VirtualAddress),
1083 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1084 FALSE );
1086 pos += map_size;
1087 continue;
1090 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1091 sec->Name, ptr + sec->VirtualAddress,
1092 sec->PointerToRawData, sec->SizeOfRawData,
1093 sec->Misc.VirtualSize, sec->Characteristics );
1095 if (!sec->PointerToRawData || !file_size) continue;
1097 /* Note: if the section is not aligned properly map_file_into_view will magically
1098 * fall back to read(), so we don't need to check anything here.
1100 end = file_start + file_size;
1101 if (sec->PointerToRawData >= st.st_size ||
1102 end > ((st.st_size + sector_align) & ~sector_align) ||
1103 end < file_start ||
1104 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1105 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1106 !dup_mapping ) != STATUS_SUCCESS)
1108 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1109 goto error;
1112 if (file_size & page_mask)
1114 end = ROUND_SIZE( 0, file_size );
1115 if (end > map_size) end = map_size;
1116 TRACE_(module)("clearing %p - %p\n",
1117 ptr + sec->VirtualAddress + file_size,
1118 ptr + sec->VirtualAddress + end );
1119 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1124 /* perform base relocation, if necessary */
1126 if (ptr != base &&
1127 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1128 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1130 IMAGE_BASE_RELOCATION *rel, *end;
1131 const IMAGE_DATA_DIRECTORY *relocs;
1133 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1135 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1136 base, ptr );
1137 status = STATUS_CONFLICTING_ADDRESSES;
1138 goto error;
1141 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1142 base, base + total_size, ptr, ptr + total_size );
1144 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1145 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1146 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1147 delta = ptr - base;
1149 while (rel < end - 1 && rel->SizeOfBlock)
1151 if (rel->VirtualAddress >= total_size)
1153 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1154 status = STATUS_ACCESS_VIOLATION;
1155 goto error;
1157 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1158 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1159 (USHORT *)(rel + 1), delta );
1160 if (!rel) goto error;
1164 /* set the image protections */
1166 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1168 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1169 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1171 SIZE_T size;
1172 BYTE vprot = VPROT_COMMITTED;
1174 if (sec->Misc.VirtualSize)
1175 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1176 else
1177 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1179 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1180 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1181 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1183 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1184 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1185 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1186 vprot |= VPROT_EXEC;
1188 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1191 done:
1192 view->mapping = dup_mapping;
1193 server_leave_uninterrupted_section( &csVirtual, &sigset );
1195 *addr_ptr = ptr;
1196 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1197 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1198 #endif
1199 return STATUS_SUCCESS;
1201 error:
1202 if (view) delete_view( view );
1203 server_leave_uninterrupted_section( &csVirtual, &sigset );
1204 if (dup_mapping) NtClose( dup_mapping );
1205 return status;
1209 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1210 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1212 void **heap_base = arg;
1214 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1215 if (size < VIRTUAL_HEAP_SIZE) return 0;
1216 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1217 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1218 return (*heap_base != (void *)-1);
1221 /***********************************************************************
1222 * virtual_init
1224 void virtual_init(void)
1226 const char *preload;
1227 void *heap_base;
1228 struct file_view *heap_view;
1230 #ifndef page_mask
1231 page_size = getpagesize();
1232 page_mask = page_size - 1;
1233 /* Make sure we have a power of 2 */
1234 assert( !(page_size & page_mask) );
1235 page_shift = 0;
1236 while ((1 << page_shift) != page_size) page_shift++;
1237 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1238 #endif /* page_mask */
1239 if ((preload = getenv("WINEPRELOADRESERVE")))
1241 unsigned long start, end;
1242 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1244 preload_reserve_start = (void *)start;
1245 preload_reserve_end = (void *)end;
1249 /* try to find space in a reserved area for the virtual heap */
1250 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1251 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1253 assert( heap_base != (void *)-1 );
1254 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1255 VIRTUAL_HEAP_SIZE, NULL, NULL );
1256 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1260 /***********************************************************************
1261 * virtual_init_threading
1263 void virtual_init_threading(void)
1265 use_locks = 1;
1269 /***********************************************************************
1270 * virtual_get_system_info
1272 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1274 info->dwUnknown1 = 0;
1275 info->uKeMaximumIncrement = 0; /* FIXME */
1276 info->uPageSize = page_size;
1277 info->uMmLowestPhysicalPage = 1;
1278 info->uMmHighestPhysicalPage = 0x7fffffff / page_size;
1279 info->uMmNumberOfPhysicalPages = info->uMmHighestPhysicalPage - info->uMmLowestPhysicalPage;
1280 info->uAllocationGranularity = get_mask(0) + 1;
1281 info->pLowestUserAddress = (void *)0x10000;
1282 info->pMmHighestUserAddress = (char *)user_space_limit - 1;
1283 info->uKeActiveProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1284 info->bKeNumberProcessors = info->uKeActiveProcessors;
1288 /***********************************************************************
1289 * virtual_alloc_thread_stack
1291 NTSTATUS virtual_alloc_thread_stack( void *base, SIZE_T size )
1293 FILE_VIEW *view;
1294 NTSTATUS status;
1295 sigset_t sigset;
1297 server_enter_uninterrupted_section( &csVirtual, &sigset );
1299 if (base) /* already allocated, create a system view */
1301 size = ROUND_SIZE( base, size );
1302 base = ROUND_ADDR( base, page_mask );
1303 if ((status = create_view( &view, base, size,
1304 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC | VPROT_SYSTEM )) != STATUS_SUCCESS)
1305 goto done;
1307 else
1309 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1310 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1311 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1312 goto done;
1313 #ifdef VALGRIND_STACK_REGISTER
1314 /* no need to de-register the stack as it's the one of the main thread */
1315 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1316 #endif
1319 /* setup no access guard page */
1320 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1321 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1322 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1324 /* note: limit is lower than base since the stack grows down */
1325 NtCurrentTeb()->DeallocationStack = view->base;
1326 NtCurrentTeb()->Tib.StackBase = (char *)view->base + view->size;
1327 NtCurrentTeb()->Tib.StackLimit = (char *)view->base + 2 * page_size;
1329 done:
1330 server_leave_uninterrupted_section( &csVirtual, &sigset );
1331 return status;
1335 /***********************************************************************
1336 * virtual_clear_thread_stack
1338 * Clear the stack contents before calling the main entry point, some broken apps need that.
1340 void virtual_clear_thread_stack(void)
1342 void *stack = NtCurrentTeb()->Tib.StackLimit;
1343 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1345 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1346 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1350 /***********************************************************************
1351 * VIRTUAL_HandleFault
1353 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1355 FILE_VIEW *view;
1356 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1357 sigset_t sigset;
1359 server_enter_uninterrupted_section( &csVirtual, &sigset );
1360 if ((view = VIRTUAL_FindView( addr )))
1362 void *page = ROUND_ADDR( addr, page_mask );
1363 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1364 if (vprot & VPROT_GUARD)
1366 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1367 ret = STATUS_GUARD_PAGE_VIOLATION;
1370 server_leave_uninterrupted_section( &csVirtual, &sigset );
1371 return ret;
1376 /***********************************************************************
1377 * virtual_handle_stack_fault
1379 * Handle an access fault inside the current thread stack.
1380 * Called from inside a signal handler.
1382 BOOL virtual_handle_stack_fault( void *addr )
1384 FILE_VIEW *view;
1385 BOOL ret = FALSE;
1387 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1388 if ((view = VIRTUAL_FindView( addr )))
1390 void *page = ROUND_ADDR( addr, page_mask );
1391 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1392 if (vprot & VPROT_GUARD)
1394 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1395 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1396 NtCurrentTeb()->Tib.StackLimit = page;
1397 ret = TRUE;
1400 RtlLeaveCriticalSection( &csVirtual );
1401 return ret;
1405 /***********************************************************************
1406 * VIRTUAL_SetForceExec
1408 * Whether to force exec prot on all views.
1410 void VIRTUAL_SetForceExec( BOOL enable )
1412 struct file_view *view;
1413 sigset_t sigset;
1415 server_enter_uninterrupted_section( &csVirtual, &sigset );
1416 if (!force_exec_prot != !enable) /* change all existing views */
1418 force_exec_prot = enable;
1420 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1422 UINT i, count;
1423 char *addr = view->base;
1424 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1425 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1427 if (view->protect & VPROT_NOEXEC) continue;
1428 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1430 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1431 if (prot == unix_prot) continue;
1432 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1434 TRACE( "%s exec prot for %p-%p\n",
1435 force_exec_prot ? "enabling" : "disabling",
1436 addr, addr + (count << page_shift) - 1 );
1437 mprotect( addr, count << page_shift,
1438 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1440 addr += (count << page_shift);
1441 unix_prot = prot;
1442 count = 0;
1444 if (count)
1446 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1448 TRACE( "%s exec prot for %p-%p\n",
1449 force_exec_prot ? "enabling" : "disabling",
1450 addr, addr + (count << page_shift) - 1 );
1451 mprotect( addr, count << page_shift,
1452 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1457 server_leave_uninterrupted_section( &csVirtual, &sigset );
1461 /***********************************************************************
1462 * VIRTUAL_UseLargeAddressSpace
1464 * Increase the address space size for apps that support it.
1466 void VIRTUAL_UseLargeAddressSpace(void)
1468 /* no large address space on win9x */
1469 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1470 user_space_limit = working_set_limit = address_space_limit;
1474 /***********************************************************************
1475 * NtAllocateVirtualMemory (NTDLL.@)
1476 * ZwAllocateVirtualMemory (NTDLL.@)
1478 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1479 SIZE_T *size_ptr, ULONG type, ULONG protect )
1481 void *base;
1482 unsigned int vprot;
1483 SIZE_T size = *size_ptr;
1484 SIZE_T mask = get_mask( zero_bits );
1485 NTSTATUS status = STATUS_SUCCESS;
1486 struct file_view *view;
1487 sigset_t sigset;
1489 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1491 if (!size) return STATUS_INVALID_PARAMETER;
1493 if (process != NtCurrentProcess())
1495 apc_call_t call;
1496 apc_result_t result;
1498 memset( &call, 0, sizeof(call) );
1500 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1501 call.virtual_alloc.addr = *ret;
1502 call.virtual_alloc.size = *size_ptr;
1503 call.virtual_alloc.zero_bits = zero_bits;
1504 call.virtual_alloc.op_type = type;
1505 call.virtual_alloc.prot = protect;
1506 status = NTDLL_queue_process_apc( process, &call, &result );
1507 if (status != STATUS_SUCCESS) return status;
1509 if (result.virtual_alloc.status == STATUS_SUCCESS)
1511 *ret = result.virtual_alloc.addr;
1512 *size_ptr = result.virtual_alloc.size;
1514 return result.virtual_alloc.status;
1517 /* Round parameters to a page boundary */
1519 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1521 if (*ret)
1523 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1524 base = ROUND_ADDR( *ret, mask );
1525 else
1526 base = ROUND_ADDR( *ret, page_mask );
1527 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1529 /* disallow low 64k, wrap-around and kernel space */
1530 if (((char *)base < (char *)0x10000) ||
1531 ((char *)base + size < (char *)base) ||
1532 is_beyond_limit( base, size, address_space_limit ))
1533 return STATUS_INVALID_PARAMETER;
1535 else
1537 base = NULL;
1538 size = (size + page_mask) & ~page_mask;
1541 /* Compute the alloc type flags */
1543 if (!(type & MEM_SYSTEM))
1545 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1546 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1548 WARN("called with wrong alloc type flags (%08x) !\n", type);
1549 return STATUS_INVALID_PARAMETER;
1551 if (type & MEM_WRITE_WATCH)
1553 FIXME("MEM_WRITE_WATCH type not supported\n");
1554 return STATUS_NOT_SUPPORTED;
1557 vprot = VIRTUAL_GetProt( protect ) | VPROT_VALLOC;
1558 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1560 /* Reserve the memory */
1562 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1564 if (type & MEM_SYSTEM)
1566 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE | VPROT_NOEXEC;
1567 status = create_view( &view, base, size, vprot | VPROT_COMMITTED | VPROT_SYSTEM );
1568 if (status == STATUS_SUCCESS) base = view->base;
1570 else if ((type & MEM_RESERVE) || !base)
1572 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1573 if (status == STATUS_SUCCESS) base = view->base;
1575 else /* commit the pages */
1577 if (!(view = VIRTUAL_FindView( base )) ||
1578 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1579 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1580 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1582 SERVER_START_REQ( add_mapping_committed_range )
1584 req->handle = view->mapping;
1585 req->offset = (char *)base - (char *)view->base;
1586 req->size = size;
1587 wine_server_call( req );
1589 SERVER_END_REQ;
1593 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1595 if (status == STATUS_SUCCESS)
1597 *ret = base;
1598 *size_ptr = size;
1600 return status;
1604 /***********************************************************************
1605 * NtFreeVirtualMemory (NTDLL.@)
1606 * ZwFreeVirtualMemory (NTDLL.@)
1608 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1610 FILE_VIEW *view;
1611 char *base;
1612 sigset_t sigset;
1613 NTSTATUS status = STATUS_SUCCESS;
1614 LPVOID addr = *addr_ptr;
1615 SIZE_T size = *size_ptr;
1617 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1619 if (process != NtCurrentProcess())
1621 apc_call_t call;
1622 apc_result_t result;
1624 memset( &call, 0, sizeof(call) );
1626 call.virtual_free.type = APC_VIRTUAL_FREE;
1627 call.virtual_free.addr = addr;
1628 call.virtual_free.size = size;
1629 call.virtual_free.op_type = type;
1630 status = NTDLL_queue_process_apc( process, &call, &result );
1631 if (status != STATUS_SUCCESS) return status;
1633 if (result.virtual_free.status == STATUS_SUCCESS)
1635 *addr_ptr = result.virtual_free.addr;
1636 *size_ptr = result.virtual_free.size;
1638 return result.virtual_free.status;
1641 /* Fix the parameters */
1643 size = ROUND_SIZE( addr, size );
1644 base = ROUND_ADDR( addr, page_mask );
1646 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1647 if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;
1649 server_enter_uninterrupted_section( &csVirtual, &sigset );
1651 if (!(view = VIRTUAL_FindView( base )) ||
1652 (base + size > (char *)view->base + view->size) ||
1653 !(view->protect & VPROT_VALLOC))
1655 status = STATUS_INVALID_PARAMETER;
1657 else if (type & MEM_SYSTEM)
1659 /* return the values that the caller should use to unmap the area */
1660 *addr_ptr = view->base;
1661 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1662 else *size_ptr = 0; /* make sure we don't munmap anything from a reserved area */
1663 view->protect |= VPROT_SYSTEM;
1664 delete_view( view );
1666 else if (type == MEM_RELEASE)
1668 /* Free the pages */
1670 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1671 else
1673 delete_view( view );
1674 *addr_ptr = base;
1675 *size_ptr = size;
1678 else if (type == MEM_DECOMMIT)
1680 status = decommit_pages( view, base - (char *)view->base, size );
1681 if (status == STATUS_SUCCESS)
1683 *addr_ptr = base;
1684 *size_ptr = size;
1687 else
1689 WARN("called with wrong free type flags (%08x) !\n", type);
1690 status = STATUS_INVALID_PARAMETER;
1693 server_leave_uninterrupted_section( &csVirtual, &sigset );
1694 return status;
1698 /***********************************************************************
1699 * NtProtectVirtualMemory (NTDLL.@)
1700 * ZwProtectVirtualMemory (NTDLL.@)
1702 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1703 ULONG new_prot, ULONG *old_prot )
1705 FILE_VIEW *view;
1706 sigset_t sigset;
1707 NTSTATUS status = STATUS_SUCCESS;
1708 char *base;
1709 BYTE vprot;
1710 SIZE_T size = *size_ptr;
1711 LPVOID addr = *addr_ptr;
1713 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1715 if (process != NtCurrentProcess())
1717 apc_call_t call;
1718 apc_result_t result;
1720 memset( &call, 0, sizeof(call) );
1722 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1723 call.virtual_protect.addr = addr;
1724 call.virtual_protect.size = size;
1725 call.virtual_protect.prot = new_prot;
1726 status = NTDLL_queue_process_apc( process, &call, &result );
1727 if (status != STATUS_SUCCESS) return status;
1729 if (result.virtual_protect.status == STATUS_SUCCESS)
1731 *addr_ptr = result.virtual_protect.addr;
1732 *size_ptr = result.virtual_protect.size;
1733 if (old_prot) *old_prot = result.virtual_protect.prot;
1735 return result.virtual_protect.status;
1738 /* Fix the parameters */
1740 size = ROUND_SIZE( addr, size );
1741 base = ROUND_ADDR( addr, page_mask );
1743 server_enter_uninterrupted_section( &csVirtual, &sigset );
1745 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1747 status = STATUS_INVALID_PARAMETER;
1749 else
1751 /* Make sure all the pages are committed */
1752 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1754 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1755 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1756 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1758 else status = STATUS_NOT_COMMITTED;
1760 server_leave_uninterrupted_section( &csVirtual, &sigset );
1762 if (status == STATUS_SUCCESS)
1764 *addr_ptr = base;
1765 *size_ptr = size;
1767 return status;
1771 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
1772 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
1774 MEMORY_BASIC_INFORMATION *info = arg;
1775 void *end = (char *)start + size;
1777 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
1779 if (info->BaseAddress >= end)
1781 if (info->AllocationBase < end) info->AllocationBase = end;
1782 return 0;
1785 if (info->BaseAddress >= start)
1787 /* it's a real free area */
1788 info->State = MEM_FREE;
1789 info->Protect = PAGE_NOACCESS;
1790 info->AllocationBase = 0;
1791 info->AllocationProtect = 0;
1792 info->Type = 0;
1793 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
1794 info->RegionSize = (char *)end - (char *)info->BaseAddress;
1796 else /* outside of the reserved area, pretend it's allocated */
1798 info->RegionSize = (char *)start - (char *)info->BaseAddress;
1799 info->State = MEM_RESERVE;
1800 info->Protect = PAGE_NOACCESS;
1801 info->AllocationProtect = PAGE_NOACCESS;
1802 info->Type = MEM_PRIVATE;
1804 return 1;
1807 #define UNIMPLEMENTED_INFO_CLASS(c) \
1808 case c: \
1809 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1810 return STATUS_INVALID_INFO_CLASS
1812 /***********************************************************************
1813 * NtQueryVirtualMemory (NTDLL.@)
1814 * ZwQueryVirtualMemory (NTDLL.@)
1816 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1817 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1818 SIZE_T len, SIZE_T *res_len )
1820 FILE_VIEW *view;
1821 char *base, *alloc_base = 0;
1822 struct list *ptr;
1823 SIZE_T size = 0;
1824 MEMORY_BASIC_INFORMATION *info = buffer;
1825 sigset_t sigset;
1827 if (info_class != MemoryBasicInformation)
1829 switch(info_class)
1831 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1832 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1833 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1835 default:
1836 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1837 process, addr, info_class, buffer, len, res_len);
1838 return STATUS_INVALID_INFO_CLASS;
1842 if (process != NtCurrentProcess())
1844 NTSTATUS status;
1845 apc_call_t call;
1846 apc_result_t result;
1848 memset( &call, 0, sizeof(call) );
1850 call.virtual_query.type = APC_VIRTUAL_QUERY;
1851 call.virtual_query.addr = addr;
1852 status = NTDLL_queue_process_apc( process, &call, &result );
1853 if (status != STATUS_SUCCESS) return status;
1855 if (result.virtual_query.status == STATUS_SUCCESS)
1857 info->BaseAddress = result.virtual_query.base;
1858 info->AllocationBase = result.virtual_query.alloc_base;
1859 info->RegionSize = result.virtual_query.size;
1860 info->State = result.virtual_query.state;
1861 info->Protect = result.virtual_query.prot;
1862 info->AllocationProtect = result.virtual_query.alloc_prot;
1863 info->Type = result.virtual_query.alloc_type;
1864 if (res_len) *res_len = sizeof(*info);
1866 return result.virtual_query.status;
1869 base = ROUND_ADDR( addr, page_mask );
1871 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1873 /* Find the view containing the address */
1875 server_enter_uninterrupted_section( &csVirtual, &sigset );
1876 ptr = list_head( &views_list );
1877 for (;;)
1879 if (!ptr)
1881 size = (char *)working_set_limit - alloc_base;
1882 view = NULL;
1883 break;
1885 view = LIST_ENTRY( ptr, struct file_view, entry );
1886 if ((char *)view->base > base)
1888 size = (char *)view->base - alloc_base;
1889 view = NULL;
1890 break;
1892 if ((char *)view->base + view->size > base)
1894 alloc_base = view->base;
1895 size = view->size;
1896 break;
1898 alloc_base = (char *)view->base + view->size;
1899 ptr = list_next( &views_list, ptr );
1902 /* Fill the info structure */
1904 info->AllocationBase = alloc_base;
1905 info->BaseAddress = base;
1906 info->RegionSize = size - (base - alloc_base);
1908 if (!view)
1910 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
1912 /* not in a reserved area at all, pretend it's allocated */
1913 info->State = MEM_RESERVE;
1914 info->Protect = PAGE_NOACCESS;
1915 info->AllocationProtect = PAGE_NOACCESS;
1916 info->Type = MEM_PRIVATE;
1919 else
1921 BYTE vprot;
1922 SIZE_T range_size = get_committed_size( view, base, &vprot );
1924 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1925 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
1926 info->AllocationBase = alloc_base;
1927 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1928 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1929 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
1930 else info->Type = MEM_MAPPED;
1931 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
1932 if (view->prot[size >> page_shift] != vprot) break;
1933 info->RegionSize = size - (base - alloc_base);
1935 server_leave_uninterrupted_section( &csVirtual, &sigset );
1937 if (res_len) *res_len = sizeof(*info);
1938 return STATUS_SUCCESS;
1942 /***********************************************************************
1943 * NtLockVirtualMemory (NTDLL.@)
1944 * ZwLockVirtualMemory (NTDLL.@)
1946 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1948 NTSTATUS status = STATUS_SUCCESS;
1950 if (process != NtCurrentProcess())
1952 apc_call_t call;
1953 apc_result_t result;
1955 memset( &call, 0, sizeof(call) );
1957 call.virtual_lock.type = APC_VIRTUAL_LOCK;
1958 call.virtual_lock.addr = *addr;
1959 call.virtual_lock.size = *size;
1960 status = NTDLL_queue_process_apc( process, &call, &result );
1961 if (status != STATUS_SUCCESS) return status;
1963 if (result.virtual_lock.status == STATUS_SUCCESS)
1965 *addr = result.virtual_lock.addr;
1966 *size = result.virtual_lock.size;
1968 return result.virtual_lock.status;
1971 *size = ROUND_SIZE( *addr, *size );
1972 *addr = ROUND_ADDR( *addr, page_mask );
1974 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1975 return status;
1979 /***********************************************************************
1980 * NtUnlockVirtualMemory (NTDLL.@)
1981 * ZwUnlockVirtualMemory (NTDLL.@)
1983 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1985 NTSTATUS status = STATUS_SUCCESS;
1987 if (process != NtCurrentProcess())
1989 apc_call_t call;
1990 apc_result_t result;
1992 memset( &call, 0, sizeof(call) );
1994 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
1995 call.virtual_unlock.addr = *addr;
1996 call.virtual_unlock.size = *size;
1997 status = NTDLL_queue_process_apc( process, &call, &result );
1998 if (status != STATUS_SUCCESS) return status;
2000 if (result.virtual_unlock.status == STATUS_SUCCESS)
2002 *addr = result.virtual_unlock.addr;
2003 *size = result.virtual_unlock.size;
2005 return result.virtual_unlock.status;
2008 *size = ROUND_SIZE( *addr, *size );
2009 *addr = ROUND_ADDR( *addr, page_mask );
2011 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2012 return status;
2016 /***********************************************************************
2017 * NtCreateSection (NTDLL.@)
2018 * ZwCreateSection (NTDLL.@)
2020 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2021 const LARGE_INTEGER *size, ULONG protect,
2022 ULONG sec_flags, HANDLE file )
2024 NTSTATUS ret;
2025 unsigned int vprot;
2026 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2027 struct security_descriptor *sd = NULL;
2028 struct object_attributes objattr;
2030 /* Check parameters */
2032 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2034 objattr.rootdir = attr ? attr->RootDirectory : 0;
2035 objattr.sd_len = 0;
2036 objattr.name_len = len;
2037 if (attr)
2039 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2040 if (ret != STATUS_SUCCESS) return ret;
2043 vprot = VIRTUAL_GetProt( protect );
2044 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2045 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2046 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2048 /* Create the server object */
2050 SERVER_START_REQ( create_mapping )
2052 req->access = access;
2053 req->attributes = (attr) ? attr->Attributes : 0;
2054 req->file_handle = file;
2055 req->size = size ? size->QuadPart : 0;
2056 req->protect = vprot;
2057 wine_server_add_data( req, &objattr, sizeof(objattr) );
2058 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2059 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2060 ret = wine_server_call( req );
2061 *handle = reply->handle;
2063 SERVER_END_REQ;
2065 NTDLL_free_struct_sd( sd );
2067 return ret;
2071 /***********************************************************************
2072 * NtOpenSection (NTDLL.@)
2073 * ZwOpenSection (NTDLL.@)
2075 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2077 NTSTATUS ret;
2078 DWORD len = attr->ObjectName->Length;
2080 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2082 SERVER_START_REQ( open_mapping )
2084 req->access = access;
2085 req->attributes = attr->Attributes;
2086 req->rootdir = attr->RootDirectory;
2087 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2088 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
2090 SERVER_END_REQ;
2091 return ret;
2095 /***********************************************************************
2096 * NtMapViewOfSection (NTDLL.@)
2097 * ZwMapViewOfSection (NTDLL.@)
2099 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2100 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2101 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2103 NTSTATUS res;
2104 ULONGLONG full_size;
2105 ACCESS_MASK access;
2106 SIZE_T size = 0;
2107 SIZE_T mask = get_mask( zero_bits );
2108 int unix_handle = -1, needs_close;
2109 unsigned int map_vprot, vprot;
2110 void *base;
2111 struct file_view *view;
2112 DWORD header_size;
2113 HANDLE dup_mapping, shared_file;
2114 LARGE_INTEGER offset;
2115 sigset_t sigset;
2117 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2119 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2120 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2122 /* Check parameters */
2124 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2125 return STATUS_INVALID_PARAMETER;
2127 if (process != NtCurrentProcess())
2129 apc_call_t call;
2130 apc_result_t result;
2132 memset( &call, 0, sizeof(call) );
2134 call.map_view.type = APC_MAP_VIEW;
2135 call.map_view.handle = handle;
2136 call.map_view.addr = *addr_ptr;
2137 call.map_view.size = *size_ptr;
2138 call.map_view.offset = offset.QuadPart;
2139 call.map_view.zero_bits = zero_bits;
2140 call.map_view.alloc_type = alloc_type;
2141 call.map_view.prot = protect;
2142 res = NTDLL_queue_process_apc( process, &call, &result );
2143 if (res != STATUS_SUCCESS) return res;
2145 if (result.map_view.status == STATUS_SUCCESS)
2147 *addr_ptr = result.map_view.addr;
2148 *size_ptr = result.map_view.size;
2150 return result.map_view.status;
2153 switch(protect)
2155 case PAGE_NOACCESS:
2156 access = SECTION_QUERY;
2157 break;
2158 case PAGE_READWRITE:
2159 case PAGE_EXECUTE_READWRITE:
2160 access = SECTION_QUERY | SECTION_MAP_WRITE;
2161 break;
2162 case PAGE_READONLY:
2163 case PAGE_WRITECOPY:
2164 case PAGE_EXECUTE:
2165 case PAGE_EXECUTE_READ:
2166 case PAGE_EXECUTE_WRITECOPY:
2167 access = SECTION_QUERY | SECTION_MAP_READ;
2168 break;
2169 default:
2170 return STATUS_INVALID_PARAMETER;
2173 SERVER_START_REQ( get_mapping_info )
2175 req->handle = handle;
2176 req->access = access;
2177 res = wine_server_call( req );
2178 map_vprot = reply->protect;
2179 base = reply->base;
2180 full_size = reply->size;
2181 header_size = reply->header_size;
2182 dup_mapping = reply->mapping;
2183 shared_file = reply->shared_file;
2185 SERVER_END_REQ;
2186 if (res) return res;
2188 size = full_size;
2189 if (sizeof(size) < sizeof(full_size) && (size != full_size))
2190 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
2191 (DWORD)(full_size >> 32), (DWORD)full_size );
2193 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2195 if (map_vprot & VPROT_IMAGE)
2197 if (shared_file)
2199 int shared_fd, shared_needs_close;
2201 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2202 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2203 res = map_image( handle, unix_handle, base, size, mask, header_size,
2204 shared_fd, dup_mapping, addr_ptr );
2205 if (shared_needs_close) close( shared_fd );
2206 NtClose( shared_file );
2208 else
2210 res = map_image( handle, unix_handle, base, size, mask, header_size,
2211 -1, dup_mapping, addr_ptr );
2213 if (needs_close) close( unix_handle );
2214 if (!res) *size_ptr = size;
2215 return res;
2218 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2220 res = STATUS_INVALID_PARAMETER;
2221 goto done;
2223 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2224 else size = size - offset.QuadPart;
2226 /* Reserve a properly aligned area */
2228 server_enter_uninterrupted_section( &csVirtual, &sigset );
2230 vprot = VIRTUAL_GetProt( protect ) | (map_vprot & VPROT_COMMITTED);
2231 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2232 if (res)
2234 server_leave_uninterrupted_section( &csVirtual, &sigset );
2235 goto done;
2238 /* Map the file */
2240 TRACE("handle=%p size=%lx offset=%x%08x\n",
2241 handle, size, offset.u.HighPart, offset.u.LowPart );
2243 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2244 if (res == STATUS_SUCCESS)
2246 *addr_ptr = view->base;
2247 *size_ptr = size;
2248 view->mapping = dup_mapping;
2249 dup_mapping = 0; /* don't close it */
2251 else
2253 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2254 view->base, size, offset.u.HighPart, offset.u.LowPart );
2255 delete_view( view );
2258 server_leave_uninterrupted_section( &csVirtual, &sigset );
2260 done:
2261 if (dup_mapping) NtClose( dup_mapping );
2262 if (needs_close) close( unix_handle );
2263 return res;
2267 /***********************************************************************
2268 * NtUnmapViewOfSection (NTDLL.@)
2269 * ZwUnmapViewOfSection (NTDLL.@)
2271 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2273 FILE_VIEW *view;
2274 NTSTATUS status = STATUS_INVALID_PARAMETER;
2275 sigset_t sigset;
2276 void *base = ROUND_ADDR( addr, page_mask );
2278 if (process != NtCurrentProcess())
2280 apc_call_t call;
2281 apc_result_t result;
2283 memset( &call, 0, sizeof(call) );
2285 call.unmap_view.type = APC_UNMAP_VIEW;
2286 call.unmap_view.addr = addr;
2287 status = NTDLL_queue_process_apc( process, &call, &result );
2288 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2289 return status;
2292 server_enter_uninterrupted_section( &csVirtual, &sigset );
2293 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2295 delete_view( view );
2296 status = STATUS_SUCCESS;
2298 server_leave_uninterrupted_section( &csVirtual, &sigset );
2299 return status;
2303 /***********************************************************************
2304 * NtFlushVirtualMemory (NTDLL.@)
2305 * ZwFlushVirtualMemory (NTDLL.@)
2307 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2308 SIZE_T *size_ptr, ULONG unknown )
2310 FILE_VIEW *view;
2311 NTSTATUS status = STATUS_SUCCESS;
2312 sigset_t sigset;
2313 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2315 if (process != NtCurrentProcess())
2317 apc_call_t call;
2318 apc_result_t result;
2320 memset( &call, 0, sizeof(call) );
2322 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2323 call.virtual_flush.addr = addr;
2324 call.virtual_flush.size = *size_ptr;
2325 status = NTDLL_queue_process_apc( process, &call, &result );
2326 if (status != STATUS_SUCCESS) return status;
2328 if (result.virtual_flush.status == STATUS_SUCCESS)
2330 *addr_ptr = result.virtual_flush.addr;
2331 *size_ptr = result.virtual_flush.size;
2333 return result.virtual_flush.status;
2336 server_enter_uninterrupted_section( &csVirtual, &sigset );
2337 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2338 else
2340 if (!*size_ptr) *size_ptr = view->size;
2341 *addr_ptr = addr;
2342 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2344 server_leave_uninterrupted_section( &csVirtual, &sigset );
2345 return status;
2349 /***********************************************************************
2350 * NtReadVirtualMemory (NTDLL.@)
2351 * ZwReadVirtualMemory (NTDLL.@)
2353 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2354 SIZE_T size, SIZE_T *bytes_read )
2356 NTSTATUS status;
2358 SERVER_START_REQ( read_process_memory )
2360 req->handle = process;
2361 req->addr = (void *)addr;
2362 wine_server_set_reply( req, buffer, size );
2363 if ((status = wine_server_call( req ))) size = 0;
2365 SERVER_END_REQ;
2366 if (bytes_read) *bytes_read = size;
2367 return status;
2371 /***********************************************************************
2372 * NtWriteVirtualMemory (NTDLL.@)
2373 * ZwWriteVirtualMemory (NTDLL.@)
2375 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2376 SIZE_T size, SIZE_T *bytes_written )
2378 NTSTATUS status;
2380 SERVER_START_REQ( write_process_memory )
2382 req->handle = process;
2383 req->addr = addr;
2384 wine_server_add_data( req, buffer, size );
2385 if ((status = wine_server_call( req ))) size = 0;
2387 SERVER_END_REQ;
2388 if (bytes_written) *bytes_written = size;
2389 return status;
2393 /***********************************************************************
2394 * NtAreMappedFilesTheSame (NTDLL.@)
2395 * ZwAreMappedFilesTheSame (NTDLL.@)
2397 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2399 TRACE("%p %p\n", addr1, addr2);
2401 return STATUS_NOT_SAME_DEVICE;