ntdll: Do not report non-reserved memory areas as free since we don't know what's...
[wine/multimedia.git] / dlls / ntdll / virtual.c
blob1eb84b8f6332864f2ccec9beb213c50a7d8762ed
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 * const address_space_limit = 0; /* no limit needed on other platforms */
129 static void * const user_space_limit = 0; /* no limit needed on other platforms */
130 static void * const working_set_limit = 0; /* no limit needed on other platforms */
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 (limit && (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 *result;
629 /***********************************************************************
630 * alloc_reserved_area_callback
632 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
634 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
636 static void * const address_space_start = (void *)0x110000;
637 struct alloc_area *alloc = arg;
638 void *end = (char *)start + size;
640 if (start < address_space_start) start = address_space_start;
641 if (user_space_limit && end > user_space_limit) end = user_space_limit;
642 if (start >= end) return 0;
644 /* make sure we don't touch the preloader reserved range */
645 if (preload_reserve_end >= start)
647 if (preload_reserve_end >= end)
649 if (preload_reserve_start <= start) return 0; /* no space in that area */
650 if (preload_reserve_start < end) end = preload_reserve_start;
652 else if (preload_reserve_start <= start) start = preload_reserve_end;
653 else
655 /* range is split in two by the preloader reservation, try first part */
656 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
657 alloc->mask, alloc->top_down )))
658 return 1;
659 /* then fall through to try second part */
660 start = preload_reserve_end;
663 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
664 return 1;
666 return 0;
670 /***********************************************************************
671 * map_view
673 * Create a view and mmap the corresponding memory area.
674 * The csVirtual section must be held by caller.
676 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
677 int top_down, unsigned int vprot )
679 void *ptr;
680 NTSTATUS status;
682 if (base)
684 if (is_beyond_limit( base, size, address_space_limit ))
685 return STATUS_WORKING_SET_LIMIT_RANGE;
687 switch (wine_mmap_is_in_reserved_area( base, size ))
689 case -1: /* partially in a reserved area */
690 return STATUS_CONFLICTING_ADDRESSES;
692 case 0: /* not in a reserved area, do a normal allocation */
693 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
695 if (errno == ENOMEM) return STATUS_NO_MEMORY;
696 return STATUS_INVALID_PARAMETER;
698 if (ptr != base)
700 /* We couldn't get the address we wanted */
701 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
702 else munmap( ptr, size );
703 return STATUS_CONFLICTING_ADDRESSES;
705 break;
707 default:
708 case 1: /* in a reserved area, make sure the address is available */
709 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
710 /* replace the reserved area by our mapping */
711 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
712 return STATUS_INVALID_PARAMETER;
713 break;
715 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
717 else
719 size_t view_size = size + mask + 1;
720 struct alloc_area alloc;
722 alloc.size = size;
723 alloc.mask = mask;
724 alloc.top_down = top_down;
725 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
727 ptr = alloc.result;
728 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
729 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
730 return STATUS_INVALID_PARAMETER;
731 goto done;
734 for (;;)
736 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
738 if (errno == ENOMEM) return STATUS_NO_MEMORY;
739 return STATUS_INVALID_PARAMETER;
741 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
742 /* if we got something beyond the user limit, unmap it and retry */
743 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
744 else break;
746 ptr = unmap_extra_space( ptr, view_size, size, mask );
748 done:
749 status = create_view( view_ret, ptr, size, vprot );
750 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
751 return status;
755 /***********************************************************************
756 * unaligned_mmap
758 * Linux kernels before 2.4.x can support non page-aligned offsets, as
759 * long as the offset is aligned to the filesystem block size. This is
760 * a big performance gain so we want to take advantage of it.
762 * However, when we use 64-bit file support this doesn't work because
763 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
764 * in that it rounds unaligned offsets down to a page boundary. For
765 * these reasons we do a direct system call here.
767 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
768 unsigned int flags, int fd, off_t offset )
770 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
771 if (!(offset >> 32) && (offset & page_mask))
773 int ret;
775 struct
777 void *addr;
778 unsigned int length;
779 unsigned int prot;
780 unsigned int flags;
781 unsigned int fd;
782 unsigned int offset;
783 } args;
785 args.addr = addr;
786 args.length = length;
787 args.prot = prot;
788 args.flags = flags;
789 args.fd = fd;
790 args.offset = offset;
792 __asm__ __volatile__("push %%ebx\n\t"
793 "movl %2,%%ebx\n\t"
794 "int $0x80\n\t"
795 "popl %%ebx"
796 : "=a" (ret)
797 : "0" (90), /* SYS_mmap */
798 "q" (&args)
799 : "memory" );
800 if (ret < 0 && ret > -4096)
802 errno = -ret;
803 ret = -1;
805 return (void *)ret;
807 #endif
808 return mmap( addr, length, prot, flags, fd, offset );
812 /***********************************************************************
813 * map_file_into_view
815 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
816 * The csVirtual section must be held by caller.
818 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
819 off_t offset, unsigned int vprot, BOOL removable )
821 void *ptr;
822 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
823 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
825 assert( start < view->size );
826 assert( start + size <= view->size );
828 /* only try mmap if media is not removable (or if we require write access) */
829 if (!removable || shared_write)
831 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
833 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
834 goto done;
836 /* mmap() failed; if this is because the file offset is not */
837 /* page-aligned (EINVAL), or because the underlying filesystem */
838 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
839 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
840 if (shared_write) /* we cannot fake shared write mappings */
842 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
843 ERR( "shared writable mmap not supported, broken filesystem?\n" );
844 return STATUS_NOT_SUPPORTED;
848 /* Reserve the memory with an anonymous mmap */
849 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
850 if (ptr == (void *)-1) return FILE_GetNtStatus();
851 /* Now read in the file */
852 pread( fd, ptr, size, offset );
853 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
854 done:
855 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
856 return STATUS_SUCCESS;
860 /***********************************************************************
861 * get_committed_size
863 * Get the size of the committed range starting at base.
864 * Also return the protections for the first page.
866 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
868 SIZE_T i, start;
870 start = ((char *)base - (char *)view->base) >> page_shift;
871 *vprot = view->prot[start];
873 if (view->mapping && !(view->protect & VPROT_COMMITTED))
875 SIZE_T ret = 0;
876 SERVER_START_REQ( get_mapping_committed_range )
878 req->handle = view->mapping;
879 req->offset = start << page_shift;
880 if (!wine_server_call( req ))
882 ret = reply->size;
883 if (reply->committed)
885 *vprot |= VPROT_COMMITTED;
886 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
890 SERVER_END_REQ;
891 return ret;
893 for (i = start + 1; i < view->size >> page_shift; i++)
894 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
895 return (i - start) << page_shift;
899 /***********************************************************************
900 * decommit_view
902 * Decommit some pages of a given view.
903 * The csVirtual section must be held by caller.
905 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
907 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
909 BYTE *p = view->prot + (start >> page_shift);
910 size >>= page_shift;
911 while (size--) *p++ &= ~VPROT_COMMITTED;
912 return STATUS_SUCCESS;
914 return FILE_GetNtStatus();
918 /***********************************************************************
919 * map_image
921 * Map an executable (PE format) image into memory.
923 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
924 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
926 IMAGE_DOS_HEADER *dos;
927 IMAGE_NT_HEADERS *nt;
928 IMAGE_SECTION_HEADER *sec;
929 IMAGE_DATA_DIRECTORY *imports;
930 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
931 int i;
932 off_t pos;
933 sigset_t sigset;
934 struct stat st;
935 struct file_view *view = NULL;
936 char *ptr, *header_end;
937 int delta = 0;
939 /* zero-map the whole range */
941 server_enter_uninterrupted_section( &csVirtual, &sigset );
943 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
944 status = map_view( &view, base, total_size, mask, FALSE,
945 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
947 if (status == STATUS_CONFLICTING_ADDRESSES)
948 status = map_view( &view, NULL, total_size, mask, FALSE,
949 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
951 if (status != STATUS_SUCCESS) goto error;
953 ptr = view->base;
954 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
956 /* map the header */
958 if (fstat( fd, &st ) == -1)
960 status = FILE_GetNtStatus();
961 goto error;
963 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
964 if (!st.st_size) goto error;
965 header_size = min( header_size, st.st_size );
966 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
967 !dup_mapping ) != STATUS_SUCCESS) goto error;
968 dos = (IMAGE_DOS_HEADER *)ptr;
969 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
970 header_end = ptr + ROUND_SIZE( 0, header_size );
971 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
972 if ((char *)(nt + 1) > header_end) goto error;
973 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
974 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
976 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
977 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
979 /* check the architecture */
981 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
983 MESSAGE("Trying to load PE image for unsupported architecture (");
984 switch (nt->FileHeader.Machine)
986 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
987 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
988 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
989 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
990 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
991 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
992 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
993 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
994 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
995 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
996 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
997 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
999 MESSAGE(")\n");
1000 goto error;
1003 /* check for non page-aligned binary */
1005 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1007 /* unaligned sections, this happens for native subsystem binaries */
1008 /* in that case Windows simply maps in the whole file */
1010 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1011 !dup_mapping ) != STATUS_SUCCESS) goto error;
1013 /* check that all sections are loaded at the right offset */
1014 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1015 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1017 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1018 goto error; /* Windows refuses to load in that case too */
1021 /* set the image protections */
1022 VIRTUAL_SetProt( view, ptr, total_size,
1023 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1025 /* no relocations are performed on non page-aligned binaries */
1026 goto done;
1030 /* map all the sections */
1032 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1034 static const SIZE_T sector_align = 0x1ff;
1035 SIZE_T map_size, file_start, file_size, end;
1037 if (!sec->Misc.VirtualSize)
1038 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1039 else
1040 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1042 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1043 file_start = sec->PointerToRawData & ~sector_align;
1044 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1045 if (file_size > map_size) file_size = map_size;
1047 /* a few sanity checks */
1048 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1049 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1051 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1052 sec->Name, sec->VirtualAddress, map_size, total_size );
1053 goto error;
1056 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1057 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1059 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1060 sec->Name, ptr + sec->VirtualAddress,
1061 sec->PointerToRawData, (int)pos, file_size, map_size,
1062 sec->Characteristics );
1063 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1064 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1065 FALSE ) != STATUS_SUCCESS)
1067 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1068 goto error;
1071 /* check if the import directory falls inside this section */
1072 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1073 imports->VirtualAddress < sec->VirtualAddress + map_size)
1075 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1076 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1077 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1078 if (end > base)
1079 map_file_into_view( view, shared_fd, base, end - base,
1080 pos + (base - sec->VirtualAddress),
1081 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1082 FALSE );
1084 pos += map_size;
1085 continue;
1088 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1089 sec->Name, ptr + sec->VirtualAddress,
1090 sec->PointerToRawData, sec->SizeOfRawData,
1091 sec->Misc.VirtualSize, sec->Characteristics );
1093 if (!sec->PointerToRawData || !file_size) continue;
1095 /* Note: if the section is not aligned properly map_file_into_view will magically
1096 * fall back to read(), so we don't need to check anything here.
1098 end = file_start + file_size;
1099 if (sec->PointerToRawData >= st.st_size ||
1100 end > ((st.st_size + sector_align) & ~sector_align) ||
1101 end < file_start ||
1102 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1103 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1104 !dup_mapping ) != STATUS_SUCCESS)
1106 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1107 goto error;
1110 if (file_size & page_mask)
1112 end = ROUND_SIZE( 0, file_size );
1113 if (end > map_size) end = map_size;
1114 TRACE_(module)("clearing %p - %p\n",
1115 ptr + sec->VirtualAddress + file_size,
1116 ptr + sec->VirtualAddress + end );
1117 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1122 /* perform base relocation, if necessary */
1124 if (ptr != base &&
1125 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1126 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1128 IMAGE_BASE_RELOCATION *rel, *end;
1129 const IMAGE_DATA_DIRECTORY *relocs;
1131 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1133 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1134 base, ptr );
1135 status = STATUS_CONFLICTING_ADDRESSES;
1136 goto error;
1139 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1140 base, base + total_size, ptr, ptr + total_size );
1142 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1143 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1144 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1145 delta = ptr - base;
1147 while (rel < end - 1 && rel->SizeOfBlock)
1149 if (rel->VirtualAddress >= total_size)
1151 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1152 status = STATUS_ACCESS_VIOLATION;
1153 goto error;
1155 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1156 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1157 (USHORT *)(rel + 1), delta );
1158 if (!rel) goto error;
1162 /* set the image protections */
1164 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1166 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1167 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1169 SIZE_T size;
1170 BYTE vprot = VPROT_COMMITTED;
1172 if (sec->Misc.VirtualSize)
1173 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1174 else
1175 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1177 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1178 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1179 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1181 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1182 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1183 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1184 vprot |= VPROT_EXEC;
1186 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1189 done:
1190 view->mapping = dup_mapping;
1191 server_leave_uninterrupted_section( &csVirtual, &sigset );
1193 *addr_ptr = ptr;
1194 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1195 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1196 #endif
1197 return STATUS_SUCCESS;
1199 error:
1200 if (view) delete_view( view );
1201 server_leave_uninterrupted_section( &csVirtual, &sigset );
1202 if (dup_mapping) NtClose( dup_mapping );
1203 return status;
1207 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1208 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1210 void **heap_base = arg;
1212 if (address_space_limit) address_space_limit = max( (char *)address_space_limit, (char *)base + size );
1213 if (size < VIRTUAL_HEAP_SIZE) return 0;
1214 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1215 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1216 return (*heap_base != (void *)-1);
1219 /***********************************************************************
1220 * virtual_init
1222 void virtual_init(void)
1224 const char *preload;
1225 void *heap_base;
1226 struct file_view *heap_view;
1228 #ifndef page_mask
1229 page_size = getpagesize();
1230 page_mask = page_size - 1;
1231 /* Make sure we have a power of 2 */
1232 assert( !(page_size & page_mask) );
1233 page_shift = 0;
1234 while ((1 << page_shift) != page_size) page_shift++;
1235 #endif /* page_mask */
1236 if ((preload = getenv("WINEPRELOADRESERVE")))
1238 unsigned long start, end;
1239 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1241 preload_reserve_start = (void *)start;
1242 preload_reserve_end = (void *)end;
1246 /* try to find space in a reserved area for the virtual heap */
1247 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1248 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1250 assert( heap_base != (void *)-1 );
1251 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1252 VIRTUAL_HEAP_SIZE, NULL, NULL );
1253 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1257 /***********************************************************************
1258 * virtual_init_threading
1260 void virtual_init_threading(void)
1262 use_locks = 1;
1266 /***********************************************************************
1267 * virtual_get_system_info
1269 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1271 info->dwUnknown1 = 0;
1272 info->uKeMaximumIncrement = 0; /* FIXME */
1273 info->uPageSize = page_size;
1274 info->uMmLowestPhysicalPage = 1;
1275 info->uMmHighestPhysicalPage = 0x7fffffff / page_size;
1276 info->uMmNumberOfPhysicalPages = info->uMmHighestPhysicalPage - info->uMmLowestPhysicalPage;
1277 info->uAllocationGranularity = get_mask(0) + 1;
1278 info->pLowestUserAddress = (void *)0x10000;
1279 info->pMmHighestUserAddress = (char *)user_space_limit - 1;
1280 info->uKeActiveProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1281 info->bKeNumberProcessors = info->uKeActiveProcessors;
1285 /***********************************************************************
1286 * virtual_alloc_thread_stack
1288 NTSTATUS virtual_alloc_thread_stack( void *base, SIZE_T size )
1290 FILE_VIEW *view;
1291 NTSTATUS status;
1292 sigset_t sigset;
1294 server_enter_uninterrupted_section( &csVirtual, &sigset );
1296 if (base) /* already allocated, create a system view */
1298 size = ROUND_SIZE( base, size );
1299 base = ROUND_ADDR( base, page_mask );
1300 if ((status = create_view( &view, base, size,
1301 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC | VPROT_SYSTEM )) != STATUS_SUCCESS)
1302 goto done;
1304 else
1306 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1307 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1308 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1309 goto done;
1310 #ifdef VALGRIND_STACK_REGISTER
1311 /* no need to de-register the stack as it's the one of the main thread */
1312 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1313 #endif
1316 /* setup no access guard page */
1317 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1318 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1319 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1321 /* note: limit is lower than base since the stack grows down */
1322 NtCurrentTeb()->DeallocationStack = view->base;
1323 NtCurrentTeb()->Tib.StackBase = (char *)view->base + view->size;
1324 NtCurrentTeb()->Tib.StackLimit = (char *)view->base + 2 * page_size;
1326 done:
1327 server_leave_uninterrupted_section( &csVirtual, &sigset );
1328 return status;
1332 /***********************************************************************
1333 * virtual_clear_thread_stack
1335 * Clear the stack contents before calling the main entry point, some broken apps need that.
1337 void virtual_clear_thread_stack(void)
1339 void *stack = NtCurrentTeb()->Tib.StackLimit;
1340 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1342 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1343 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1347 /***********************************************************************
1348 * VIRTUAL_HandleFault
1350 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1352 FILE_VIEW *view;
1353 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1354 sigset_t sigset;
1356 server_enter_uninterrupted_section( &csVirtual, &sigset );
1357 if ((view = VIRTUAL_FindView( addr )))
1359 void *page = ROUND_ADDR( addr, page_mask );
1360 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1361 if (vprot & VPROT_GUARD)
1363 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1364 ret = STATUS_GUARD_PAGE_VIOLATION;
1367 server_leave_uninterrupted_section( &csVirtual, &sigset );
1368 return ret;
1373 /***********************************************************************
1374 * virtual_handle_stack_fault
1376 * Handle an access fault inside the current thread stack.
1377 * Called from inside a signal handler.
1379 BOOL virtual_handle_stack_fault( void *addr )
1381 FILE_VIEW *view;
1382 BOOL ret = FALSE;
1384 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1385 if ((view = VIRTUAL_FindView( addr )))
1387 void *page = ROUND_ADDR( addr, page_mask );
1388 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1389 if (vprot & VPROT_GUARD)
1391 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1392 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1393 NtCurrentTeb()->Tib.StackLimit = page;
1394 ret = TRUE;
1397 RtlLeaveCriticalSection( &csVirtual );
1398 return ret;
1402 /***********************************************************************
1403 * VIRTUAL_SetForceExec
1405 * Whether to force exec prot on all views.
1407 void VIRTUAL_SetForceExec( BOOL enable )
1409 struct file_view *view;
1410 sigset_t sigset;
1412 server_enter_uninterrupted_section( &csVirtual, &sigset );
1413 if (!force_exec_prot != !enable) /* change all existing views */
1415 force_exec_prot = enable;
1417 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1419 UINT i, count;
1420 char *addr = view->base;
1421 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1422 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1424 if (view->protect & VPROT_NOEXEC) continue;
1425 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1427 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1428 if (prot == unix_prot) continue;
1429 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1431 TRACE( "%s exec prot for %p-%p\n",
1432 force_exec_prot ? "enabling" : "disabling",
1433 addr, addr + (count << page_shift) - 1 );
1434 mprotect( addr, count << page_shift,
1435 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1437 addr += (count << page_shift);
1438 unix_prot = prot;
1439 count = 0;
1441 if (count)
1443 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1445 TRACE( "%s exec prot for %p-%p\n",
1446 force_exec_prot ? "enabling" : "disabling",
1447 addr, addr + (count << page_shift) - 1 );
1448 mprotect( addr, count << page_shift,
1449 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1454 server_leave_uninterrupted_section( &csVirtual, &sigset );
1458 /***********************************************************************
1459 * VIRTUAL_UseLargeAddressSpace
1461 * Increase the address space size for apps that support it.
1463 void VIRTUAL_UseLargeAddressSpace(void)
1465 /* no large address space on win9x */
1466 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1467 user_space_limit = working_set_limit = address_space_limit;
1471 /***********************************************************************
1472 * NtAllocateVirtualMemory (NTDLL.@)
1473 * ZwAllocateVirtualMemory (NTDLL.@)
1475 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1476 SIZE_T *size_ptr, ULONG type, ULONG protect )
1478 void *base;
1479 unsigned int vprot;
1480 SIZE_T size = *size_ptr;
1481 SIZE_T mask = get_mask( zero_bits );
1482 NTSTATUS status = STATUS_SUCCESS;
1483 struct file_view *view;
1484 sigset_t sigset;
1486 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1488 if (!size) return STATUS_INVALID_PARAMETER;
1490 if (process != NtCurrentProcess())
1492 apc_call_t call;
1493 apc_result_t result;
1495 memset( &call, 0, sizeof(call) );
1497 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1498 call.virtual_alloc.addr = *ret;
1499 call.virtual_alloc.size = *size_ptr;
1500 call.virtual_alloc.zero_bits = zero_bits;
1501 call.virtual_alloc.op_type = type;
1502 call.virtual_alloc.prot = protect;
1503 status = NTDLL_queue_process_apc( process, &call, &result );
1504 if (status != STATUS_SUCCESS) return status;
1506 if (result.virtual_alloc.status == STATUS_SUCCESS)
1508 *ret = result.virtual_alloc.addr;
1509 *size_ptr = result.virtual_alloc.size;
1511 return result.virtual_alloc.status;
1514 /* Round parameters to a page boundary */
1516 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1518 if (*ret)
1520 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1521 base = ROUND_ADDR( *ret, mask );
1522 else
1523 base = ROUND_ADDR( *ret, page_mask );
1524 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1526 /* disallow low 64k, wrap-around and kernel space */
1527 if (((char *)base < (char *)0x10000) ||
1528 ((char *)base + size < (char *)base) ||
1529 is_beyond_limit( base, size, address_space_limit ))
1530 return STATUS_INVALID_PARAMETER;
1532 else
1534 base = NULL;
1535 size = (size + page_mask) & ~page_mask;
1538 /* Compute the alloc type flags */
1540 if (!(type & MEM_SYSTEM))
1542 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1543 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1545 WARN("called with wrong alloc type flags (%08x) !\n", type);
1546 return STATUS_INVALID_PARAMETER;
1548 if (type & MEM_WRITE_WATCH)
1550 FIXME("MEM_WRITE_WATCH type not supported\n");
1551 return STATUS_NOT_SUPPORTED;
1554 vprot = VIRTUAL_GetProt( protect ) | VPROT_VALLOC;
1555 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1557 /* Reserve the memory */
1559 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1561 if (type & MEM_SYSTEM)
1563 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE | VPROT_NOEXEC;
1564 status = create_view( &view, base, size, vprot | VPROT_COMMITTED | VPROT_SYSTEM );
1565 if (status == STATUS_SUCCESS) base = view->base;
1567 else if ((type & MEM_RESERVE) || !base)
1569 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1570 if (status == STATUS_SUCCESS) base = view->base;
1572 else /* commit the pages */
1574 if (!(view = VIRTUAL_FindView( base )) ||
1575 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1576 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1577 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1579 SERVER_START_REQ( add_mapping_committed_range )
1581 req->handle = view->mapping;
1582 req->offset = (char *)base - (char *)view->base;
1583 req->size = size;
1584 wine_server_call( req );
1586 SERVER_END_REQ;
1590 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1592 if (status == STATUS_SUCCESS)
1594 *ret = base;
1595 *size_ptr = size;
1597 return status;
1601 /***********************************************************************
1602 * NtFreeVirtualMemory (NTDLL.@)
1603 * ZwFreeVirtualMemory (NTDLL.@)
1605 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1607 FILE_VIEW *view;
1608 char *base;
1609 sigset_t sigset;
1610 NTSTATUS status = STATUS_SUCCESS;
1611 LPVOID addr = *addr_ptr;
1612 SIZE_T size = *size_ptr;
1614 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1616 if (process != NtCurrentProcess())
1618 apc_call_t call;
1619 apc_result_t result;
1621 memset( &call, 0, sizeof(call) );
1623 call.virtual_free.type = APC_VIRTUAL_FREE;
1624 call.virtual_free.addr = addr;
1625 call.virtual_free.size = size;
1626 call.virtual_free.op_type = type;
1627 status = NTDLL_queue_process_apc( process, &call, &result );
1628 if (status != STATUS_SUCCESS) return status;
1630 if (result.virtual_free.status == STATUS_SUCCESS)
1632 *addr_ptr = result.virtual_free.addr;
1633 *size_ptr = result.virtual_free.size;
1635 return result.virtual_free.status;
1638 /* Fix the parameters */
1640 size = ROUND_SIZE( addr, size );
1641 base = ROUND_ADDR( addr, page_mask );
1643 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1644 if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;
1646 server_enter_uninterrupted_section( &csVirtual, &sigset );
1648 if (!(view = VIRTUAL_FindView( base )) ||
1649 (base + size > (char *)view->base + view->size) ||
1650 !(view->protect & VPROT_VALLOC))
1652 status = STATUS_INVALID_PARAMETER;
1654 else if (type & MEM_SYSTEM)
1656 /* return the values that the caller should use to unmap the area */
1657 *addr_ptr = view->base;
1658 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1659 else *size_ptr = 0; /* make sure we don't munmap anything from a reserved area */
1660 view->protect |= VPROT_SYSTEM;
1661 delete_view( view );
1663 else if (type == MEM_RELEASE)
1665 /* Free the pages */
1667 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1668 else
1670 delete_view( view );
1671 *addr_ptr = base;
1672 *size_ptr = size;
1675 else if (type == MEM_DECOMMIT)
1677 status = decommit_pages( view, base - (char *)view->base, size );
1678 if (status == STATUS_SUCCESS)
1680 *addr_ptr = base;
1681 *size_ptr = size;
1684 else
1686 WARN("called with wrong free type flags (%08x) !\n", type);
1687 status = STATUS_INVALID_PARAMETER;
1690 server_leave_uninterrupted_section( &csVirtual, &sigset );
1691 return status;
1695 /***********************************************************************
1696 * NtProtectVirtualMemory (NTDLL.@)
1697 * ZwProtectVirtualMemory (NTDLL.@)
1699 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1700 ULONG new_prot, ULONG *old_prot )
1702 FILE_VIEW *view;
1703 sigset_t sigset;
1704 NTSTATUS status = STATUS_SUCCESS;
1705 char *base;
1706 BYTE vprot;
1707 SIZE_T size = *size_ptr;
1708 LPVOID addr = *addr_ptr;
1710 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1712 if (process != NtCurrentProcess())
1714 apc_call_t call;
1715 apc_result_t result;
1717 memset( &call, 0, sizeof(call) );
1719 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1720 call.virtual_protect.addr = addr;
1721 call.virtual_protect.size = size;
1722 call.virtual_protect.prot = new_prot;
1723 status = NTDLL_queue_process_apc( process, &call, &result );
1724 if (status != STATUS_SUCCESS) return status;
1726 if (result.virtual_protect.status == STATUS_SUCCESS)
1728 *addr_ptr = result.virtual_protect.addr;
1729 *size_ptr = result.virtual_protect.size;
1730 if (old_prot) *old_prot = result.virtual_protect.prot;
1732 return result.virtual_protect.status;
1735 /* Fix the parameters */
1737 size = ROUND_SIZE( addr, size );
1738 base = ROUND_ADDR( addr, page_mask );
1740 server_enter_uninterrupted_section( &csVirtual, &sigset );
1742 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1744 status = STATUS_INVALID_PARAMETER;
1746 else
1748 /* Make sure all the pages are committed */
1749 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1751 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1752 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1753 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1755 else status = STATUS_NOT_COMMITTED;
1757 server_leave_uninterrupted_section( &csVirtual, &sigset );
1759 if (status == STATUS_SUCCESS)
1761 *addr_ptr = base;
1762 *size_ptr = size;
1764 return status;
1768 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
1769 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
1771 MEMORY_BASIC_INFORMATION *info = arg;
1772 void *end = (char *)start + size;
1774 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
1776 if (info->BaseAddress >= end)
1778 if (info->AllocationBase < end) info->AllocationBase = end;
1779 return 0;
1782 if (info->BaseAddress >= start)
1784 /* it's a real free area */
1785 info->State = MEM_FREE;
1786 info->Protect = PAGE_NOACCESS;
1787 info->AllocationBase = 0;
1788 info->AllocationProtect = 0;
1789 info->Type = 0;
1790 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
1791 info->RegionSize = (char *)end - (char *)info->BaseAddress;
1793 else /* outside of the reserved area, pretend it's allocated */
1795 info->RegionSize = (char *)start - (char *)info->BaseAddress;
1796 info->State = MEM_RESERVE;
1797 info->Protect = PAGE_NOACCESS;
1798 info->AllocationProtect = PAGE_NOACCESS;
1799 info->Type = MEM_PRIVATE;
1801 return 1;
1804 #define UNIMPLEMENTED_INFO_CLASS(c) \
1805 case c: \
1806 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1807 return STATUS_INVALID_INFO_CLASS
1809 /***********************************************************************
1810 * NtQueryVirtualMemory (NTDLL.@)
1811 * ZwQueryVirtualMemory (NTDLL.@)
1813 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1814 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1815 SIZE_T len, SIZE_T *res_len )
1817 FILE_VIEW *view;
1818 char *base, *alloc_base = 0;
1819 struct list *ptr;
1820 SIZE_T size = 0;
1821 MEMORY_BASIC_INFORMATION *info = buffer;
1822 sigset_t sigset;
1824 if (info_class != MemoryBasicInformation)
1826 switch(info_class)
1828 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1829 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1830 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1832 default:
1833 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1834 process, addr, info_class, buffer, len, res_len);
1835 return STATUS_INVALID_INFO_CLASS;
1839 if (process != NtCurrentProcess())
1841 NTSTATUS status;
1842 apc_call_t call;
1843 apc_result_t result;
1845 memset( &call, 0, sizeof(call) );
1847 call.virtual_query.type = APC_VIRTUAL_QUERY;
1848 call.virtual_query.addr = addr;
1849 status = NTDLL_queue_process_apc( process, &call, &result );
1850 if (status != STATUS_SUCCESS) return status;
1852 if (result.virtual_query.status == STATUS_SUCCESS)
1854 info->BaseAddress = result.virtual_query.base;
1855 info->AllocationBase = result.virtual_query.alloc_base;
1856 info->RegionSize = result.virtual_query.size;
1857 info->State = result.virtual_query.state;
1858 info->Protect = result.virtual_query.prot;
1859 info->AllocationProtect = result.virtual_query.alloc_prot;
1860 info->Type = result.virtual_query.alloc_type;
1861 if (res_len) *res_len = sizeof(*info);
1863 return result.virtual_query.status;
1866 base = ROUND_ADDR( addr, page_mask );
1868 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1870 /* Find the view containing the address */
1872 server_enter_uninterrupted_section( &csVirtual, &sigset );
1873 ptr = list_head( &views_list );
1874 for (;;)
1876 if (!ptr)
1878 size = (char *)working_set_limit - alloc_base;
1879 view = NULL;
1880 break;
1882 view = LIST_ENTRY( ptr, struct file_view, entry );
1883 if ((char *)view->base > base)
1885 size = (char *)view->base - alloc_base;
1886 view = NULL;
1887 break;
1889 if ((char *)view->base + view->size > base)
1891 alloc_base = view->base;
1892 size = view->size;
1893 break;
1895 alloc_base = (char *)view->base + view->size;
1896 ptr = list_next( &views_list, ptr );
1899 /* Fill the info structure */
1901 info->AllocationBase = alloc_base;
1902 info->BaseAddress = base;
1903 info->RegionSize = size - (base - alloc_base);
1905 if (!view)
1907 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
1909 /* not in a reserved area at all, pretend it's allocated */
1910 info->State = MEM_RESERVE;
1911 info->Protect = PAGE_NOACCESS;
1912 info->AllocationProtect = PAGE_NOACCESS;
1913 info->Type = MEM_PRIVATE;
1916 else
1918 BYTE vprot;
1919 SIZE_T range_size = get_committed_size( view, base, &vprot );
1921 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1922 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
1923 info->AllocationBase = alloc_base;
1924 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1925 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1926 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
1927 else info->Type = MEM_MAPPED;
1928 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
1929 if (view->prot[size >> page_shift] != vprot) break;
1930 info->RegionSize = size - (base - alloc_base);
1932 server_leave_uninterrupted_section( &csVirtual, &sigset );
1934 if (res_len) *res_len = sizeof(*info);
1935 return STATUS_SUCCESS;
1939 /***********************************************************************
1940 * NtLockVirtualMemory (NTDLL.@)
1941 * ZwLockVirtualMemory (NTDLL.@)
1943 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1945 NTSTATUS status = STATUS_SUCCESS;
1947 if (process != NtCurrentProcess())
1949 apc_call_t call;
1950 apc_result_t result;
1952 memset( &call, 0, sizeof(call) );
1954 call.virtual_lock.type = APC_VIRTUAL_LOCK;
1955 call.virtual_lock.addr = *addr;
1956 call.virtual_lock.size = *size;
1957 status = NTDLL_queue_process_apc( process, &call, &result );
1958 if (status != STATUS_SUCCESS) return status;
1960 if (result.virtual_lock.status == STATUS_SUCCESS)
1962 *addr = result.virtual_lock.addr;
1963 *size = result.virtual_lock.size;
1965 return result.virtual_lock.status;
1968 *size = ROUND_SIZE( *addr, *size );
1969 *addr = ROUND_ADDR( *addr, page_mask );
1971 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1972 return status;
1976 /***********************************************************************
1977 * NtUnlockVirtualMemory (NTDLL.@)
1978 * ZwUnlockVirtualMemory (NTDLL.@)
1980 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1982 NTSTATUS status = STATUS_SUCCESS;
1984 if (process != NtCurrentProcess())
1986 apc_call_t call;
1987 apc_result_t result;
1989 memset( &call, 0, sizeof(call) );
1991 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
1992 call.virtual_unlock.addr = *addr;
1993 call.virtual_unlock.size = *size;
1994 status = NTDLL_queue_process_apc( process, &call, &result );
1995 if (status != STATUS_SUCCESS) return status;
1997 if (result.virtual_unlock.status == STATUS_SUCCESS)
1999 *addr = result.virtual_unlock.addr;
2000 *size = result.virtual_unlock.size;
2002 return result.virtual_unlock.status;
2005 *size = ROUND_SIZE( *addr, *size );
2006 *addr = ROUND_ADDR( *addr, page_mask );
2008 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2009 return status;
2013 /***********************************************************************
2014 * NtCreateSection (NTDLL.@)
2015 * ZwCreateSection (NTDLL.@)
2017 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2018 const LARGE_INTEGER *size, ULONG protect,
2019 ULONG sec_flags, HANDLE file )
2021 NTSTATUS ret;
2022 unsigned int vprot;
2023 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2024 struct security_descriptor *sd = NULL;
2025 struct object_attributes objattr;
2027 /* Check parameters */
2029 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2031 objattr.rootdir = attr ? attr->RootDirectory : 0;
2032 objattr.sd_len = 0;
2033 objattr.name_len = len;
2034 if (attr)
2036 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2037 if (ret != STATUS_SUCCESS) return ret;
2040 vprot = VIRTUAL_GetProt( protect );
2041 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2042 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2043 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2045 /* Create the server object */
2047 SERVER_START_REQ( create_mapping )
2049 req->access = access;
2050 req->attributes = (attr) ? attr->Attributes : 0;
2051 req->file_handle = file;
2052 req->size = size ? size->QuadPart : 0;
2053 req->protect = vprot;
2054 wine_server_add_data( req, &objattr, sizeof(objattr) );
2055 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2056 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2057 ret = wine_server_call( req );
2058 *handle = reply->handle;
2060 SERVER_END_REQ;
2062 NTDLL_free_struct_sd( sd );
2064 return ret;
2068 /***********************************************************************
2069 * NtOpenSection (NTDLL.@)
2070 * ZwOpenSection (NTDLL.@)
2072 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2074 NTSTATUS ret;
2075 DWORD len = attr->ObjectName->Length;
2077 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2079 SERVER_START_REQ( open_mapping )
2081 req->access = access;
2082 req->attributes = attr->Attributes;
2083 req->rootdir = attr->RootDirectory;
2084 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2085 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
2087 SERVER_END_REQ;
2088 return ret;
2092 /***********************************************************************
2093 * NtMapViewOfSection (NTDLL.@)
2094 * ZwMapViewOfSection (NTDLL.@)
2096 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2097 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2098 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2100 NTSTATUS res;
2101 ULONGLONG full_size;
2102 ACCESS_MASK access;
2103 SIZE_T size = 0;
2104 SIZE_T mask = get_mask( zero_bits );
2105 int unix_handle = -1, needs_close;
2106 unsigned int map_vprot, vprot;
2107 void *base;
2108 struct file_view *view;
2109 DWORD header_size;
2110 HANDLE dup_mapping, shared_file;
2111 LARGE_INTEGER offset;
2112 sigset_t sigset;
2114 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2116 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2117 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2119 /* Check parameters */
2121 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2122 return STATUS_INVALID_PARAMETER;
2124 if (process != NtCurrentProcess())
2126 apc_call_t call;
2127 apc_result_t result;
2129 memset( &call, 0, sizeof(call) );
2131 call.map_view.type = APC_MAP_VIEW;
2132 call.map_view.handle = handle;
2133 call.map_view.addr = *addr_ptr;
2134 call.map_view.size = *size_ptr;
2135 call.map_view.offset = offset.QuadPart;
2136 call.map_view.zero_bits = zero_bits;
2137 call.map_view.alloc_type = alloc_type;
2138 call.map_view.prot = protect;
2139 res = NTDLL_queue_process_apc( process, &call, &result );
2140 if (res != STATUS_SUCCESS) return res;
2142 if (result.map_view.status == STATUS_SUCCESS)
2144 *addr_ptr = result.map_view.addr;
2145 *size_ptr = result.map_view.size;
2147 return result.map_view.status;
2150 switch(protect)
2152 case PAGE_NOACCESS:
2153 access = SECTION_QUERY;
2154 break;
2155 case PAGE_READWRITE:
2156 case PAGE_EXECUTE_READWRITE:
2157 access = SECTION_QUERY | SECTION_MAP_WRITE;
2158 break;
2159 case PAGE_READONLY:
2160 case PAGE_WRITECOPY:
2161 case PAGE_EXECUTE:
2162 case PAGE_EXECUTE_READ:
2163 case PAGE_EXECUTE_WRITECOPY:
2164 access = SECTION_QUERY | SECTION_MAP_READ;
2165 break;
2166 default:
2167 return STATUS_INVALID_PARAMETER;
2170 SERVER_START_REQ( get_mapping_info )
2172 req->handle = handle;
2173 req->access = access;
2174 res = wine_server_call( req );
2175 map_vprot = reply->protect;
2176 base = reply->base;
2177 full_size = reply->size;
2178 header_size = reply->header_size;
2179 dup_mapping = reply->mapping;
2180 shared_file = reply->shared_file;
2182 SERVER_END_REQ;
2183 if (res) return res;
2185 size = full_size;
2186 if (sizeof(size) < sizeof(full_size) && (size != full_size))
2187 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
2188 (DWORD)(full_size >> 32), (DWORD)full_size );
2190 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2192 if (map_vprot & VPROT_IMAGE)
2194 if (shared_file)
2196 int shared_fd, shared_needs_close;
2198 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2199 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2200 res = map_image( handle, unix_handle, base, size, mask, header_size,
2201 shared_fd, dup_mapping, addr_ptr );
2202 if (shared_needs_close) close( shared_fd );
2203 NtClose( shared_file );
2205 else
2207 res = map_image( handle, unix_handle, base, size, mask, header_size,
2208 -1, dup_mapping, addr_ptr );
2210 if (needs_close) close( unix_handle );
2211 if (!res) *size_ptr = size;
2212 return res;
2215 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2217 res = STATUS_INVALID_PARAMETER;
2218 goto done;
2220 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2221 else size = size - offset.QuadPart;
2223 /* Reserve a properly aligned area */
2225 server_enter_uninterrupted_section( &csVirtual, &sigset );
2227 vprot = VIRTUAL_GetProt( protect ) | (map_vprot & VPROT_COMMITTED);
2228 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2229 if (res)
2231 server_leave_uninterrupted_section( &csVirtual, &sigset );
2232 goto done;
2235 /* Map the file */
2237 TRACE("handle=%p size=%lx offset=%x%08x\n",
2238 handle, size, offset.u.HighPart, offset.u.LowPart );
2240 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2241 if (res == STATUS_SUCCESS)
2243 *addr_ptr = view->base;
2244 *size_ptr = size;
2245 view->mapping = dup_mapping;
2246 dup_mapping = 0; /* don't close it */
2248 else
2250 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2251 view->base, size, offset.u.HighPart, offset.u.LowPart );
2252 delete_view( view );
2255 server_leave_uninterrupted_section( &csVirtual, &sigset );
2257 done:
2258 if (dup_mapping) NtClose( dup_mapping );
2259 if (needs_close) close( unix_handle );
2260 return res;
2264 /***********************************************************************
2265 * NtUnmapViewOfSection (NTDLL.@)
2266 * ZwUnmapViewOfSection (NTDLL.@)
2268 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2270 FILE_VIEW *view;
2271 NTSTATUS status = STATUS_INVALID_PARAMETER;
2272 sigset_t sigset;
2273 void *base = ROUND_ADDR( addr, page_mask );
2275 if (process != NtCurrentProcess())
2277 apc_call_t call;
2278 apc_result_t result;
2280 memset( &call, 0, sizeof(call) );
2282 call.unmap_view.type = APC_UNMAP_VIEW;
2283 call.unmap_view.addr = addr;
2284 status = NTDLL_queue_process_apc( process, &call, &result );
2285 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2286 return status;
2289 server_enter_uninterrupted_section( &csVirtual, &sigset );
2290 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2292 delete_view( view );
2293 status = STATUS_SUCCESS;
2295 server_leave_uninterrupted_section( &csVirtual, &sigset );
2296 return status;
2300 /***********************************************************************
2301 * NtFlushVirtualMemory (NTDLL.@)
2302 * ZwFlushVirtualMemory (NTDLL.@)
2304 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2305 SIZE_T *size_ptr, ULONG unknown )
2307 FILE_VIEW *view;
2308 NTSTATUS status = STATUS_SUCCESS;
2309 sigset_t sigset;
2310 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2312 if (process != NtCurrentProcess())
2314 apc_call_t call;
2315 apc_result_t result;
2317 memset( &call, 0, sizeof(call) );
2319 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2320 call.virtual_flush.addr = addr;
2321 call.virtual_flush.size = *size_ptr;
2322 status = NTDLL_queue_process_apc( process, &call, &result );
2323 if (status != STATUS_SUCCESS) return status;
2325 if (result.virtual_flush.status == STATUS_SUCCESS)
2327 *addr_ptr = result.virtual_flush.addr;
2328 *size_ptr = result.virtual_flush.size;
2330 return result.virtual_flush.status;
2333 server_enter_uninterrupted_section( &csVirtual, &sigset );
2334 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2335 else
2337 if (!*size_ptr) *size_ptr = view->size;
2338 *addr_ptr = addr;
2339 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2341 server_leave_uninterrupted_section( &csVirtual, &sigset );
2342 return status;
2346 /***********************************************************************
2347 * NtReadVirtualMemory (NTDLL.@)
2348 * ZwReadVirtualMemory (NTDLL.@)
2350 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2351 SIZE_T size, SIZE_T *bytes_read )
2353 NTSTATUS status;
2355 SERVER_START_REQ( read_process_memory )
2357 req->handle = process;
2358 req->addr = (void *)addr;
2359 wine_server_set_reply( req, buffer, size );
2360 if ((status = wine_server_call( req ))) size = 0;
2362 SERVER_END_REQ;
2363 if (bytes_read) *bytes_read = size;
2364 return status;
2368 /***********************************************************************
2369 * NtWriteVirtualMemory (NTDLL.@)
2370 * ZwWriteVirtualMemory (NTDLL.@)
2372 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2373 SIZE_T size, SIZE_T *bytes_written )
2375 NTSTATUS status;
2377 SERVER_START_REQ( write_process_memory )
2379 req->handle = process;
2380 req->addr = addr;
2381 wine_server_add_data( req, buffer, size );
2382 if ((status = wine_server_call( req ))) size = 0;
2384 SERVER_END_REQ;
2385 if (bytes_written) *bytes_written = size;
2386 return status;
2390 /***********************************************************************
2391 * NtAreMappedFilesTheSame (NTDLL.@)
2392 * ZwAreMappedFilesTheSame (NTDLL.@)
2394 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2396 TRACE("%p %p\n", addr1, addr2);
2398 return STATUS_NOT_SAME_DEVICE;