ntdll: Use the copy of the section headers for applying memory protections as well...
[wine/multimedia.git] / dlls / ntdll / virtual.c
blob7c2b1a93368dfca65df3f313cbfc3de1ed742e0c
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 #include <fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #ifdef HAVE_SYS_MMAN_H
39 # include <sys/mman.h>
40 #endif
41 #ifdef HAVE_VALGRIND_VALGRIND_H
42 # include <valgrind/valgrind.h>
43 #endif
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "wine/library.h"
52 #include "wine/server.h"
53 #include "wine/exception.h"
54 #include "wine/list.h"
55 #include "wine/debug.h"
56 #include "ntdll_misc.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
61 #ifndef MS_SYNC
62 #define MS_SYNC 0
63 #endif
65 #ifndef MAP_NORESERVE
66 #define MAP_NORESERVE 0
67 #endif
69 /* File view */
70 struct file_view
72 struct list entry; /* Entry in global view list */
73 void *base; /* Base address */
74 size_t size; /* Size in bytes */
75 HANDLE mapping; /* Handle to the file mapping */
76 unsigned int map_protect; /* Mapping protection */
77 unsigned int protect; /* Protection for all pages at allocation time */
78 BYTE prot[1]; /* Protection byte for each page */
82 /* Conversion from VPROT_* to Win32 flags */
83 static const BYTE VIRTUAL_Win32Flags[16] =
85 PAGE_NOACCESS, /* 0 */
86 PAGE_READONLY, /* READ */
87 PAGE_READWRITE, /* WRITE */
88 PAGE_READWRITE, /* READ | WRITE */
89 PAGE_EXECUTE, /* EXEC */
90 PAGE_EXECUTE_READ, /* READ | EXEC */
91 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
92 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
93 PAGE_WRITECOPY, /* WRITECOPY */
94 PAGE_WRITECOPY, /* READ | WRITECOPY */
95 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
96 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
97 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
103 static struct list views_list = LIST_INIT(views_list);
105 static RTL_CRITICAL_SECTION csVirtual;
106 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
108 0, 0, &csVirtual,
109 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
110 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
112 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
114 #ifdef __i386__
115 /* These are always the same on an i386, and it will be faster this way */
116 # define page_mask 0xfff
117 # define page_shift 12
118 # define page_size 0x1000
119 /* Note: these are Windows limits, you cannot change them. */
120 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
121 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
122 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
123 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
124 #elif defined(__x86_64__)
125 # define page_mask 0xfff
126 # define page_shift 12
127 # define page_size 0x1000
128 static void *address_space_limit = (void *)0x7fffffff0000;
129 static void *user_space_limit = (void *)0x7fffffff0000;
130 static void *working_set_limit = (void *)0x7fffffff0000;
131 static void *address_space_start = (void *)0x10000;
132 #else
133 static UINT page_shift;
134 static UINT_PTR page_size;
135 static UINT_PTR page_mask;
136 static void *address_space_limit;
137 static void *user_space_limit;
138 static void *working_set_limit;
139 static void *address_space_start = (void *)0x10000;
140 #endif /* __i386__ */
141 static const int is_win64 = (sizeof(void *) > sizeof(int));
143 #define ROUND_ADDR(addr,mask) \
144 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
146 #define ROUND_SIZE(addr,size) \
147 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
149 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
150 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
152 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
154 static HANDLE virtual_heap;
155 static void *preload_reserve_start;
156 static void *preload_reserve_end;
157 static int use_locks;
158 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
161 /***********************************************************************
162 * VIRTUAL_GetProtStr
164 static const char *VIRTUAL_GetProtStr( BYTE prot )
166 static char buffer[6];
167 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
168 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
169 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
170 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
171 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
172 buffer[5] = 0;
173 return buffer;
177 /***********************************************************************
178 * VIRTUAL_GetUnixProt
180 * Convert page protections to protection for mmap/mprotect.
182 static int VIRTUAL_GetUnixProt( BYTE vprot )
184 int prot = 0;
185 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
187 if (vprot & VPROT_READ) prot |= PROT_READ;
188 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
189 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
190 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
191 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
193 if (!prot) prot = PROT_NONE;
194 return prot;
198 /***********************************************************************
199 * VIRTUAL_DumpView
201 static void VIRTUAL_DumpView( struct file_view *view )
203 UINT i, count;
204 char *addr = view->base;
205 BYTE prot = view->prot[0];
207 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
208 if (view->protect & VPROT_SYSTEM)
209 TRACE( " (system)\n" );
210 else if (view->protect & VPROT_VALLOC)
211 TRACE( " (valloc)\n" );
212 else if (view->mapping)
213 TRACE( " %p\n", view->mapping );
214 else
215 TRACE( " (anonymous)\n");
217 for (count = i = 1; i < view->size >> page_shift; i++, count++)
219 if (view->prot[i] == prot) continue;
220 TRACE( " %p - %p %s\n",
221 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
222 addr += (count << page_shift);
223 prot = view->prot[i];
224 count = 0;
226 if (count)
227 TRACE( " %p - %p %s\n",
228 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
232 /***********************************************************************
233 * VIRTUAL_Dump
235 #ifdef WINE_VM_DEBUG
236 static void VIRTUAL_Dump(void)
238 sigset_t sigset;
239 struct file_view *view;
241 TRACE( "Dump of all virtual memory views:\n" );
242 server_enter_uninterrupted_section( &csVirtual, &sigset );
243 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
245 VIRTUAL_DumpView( view );
247 server_leave_uninterrupted_section( &csVirtual, &sigset );
249 #endif
252 /***********************************************************************
253 * VIRTUAL_FindView
255 * Find the view containing a given address. The csVirtual section must be held by caller.
257 * PARAMS
258 * addr [I] Address
260 * RETURNS
261 * View: Success
262 * NULL: Failure
264 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
266 struct file_view *view;
268 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
270 if (view->base > addr) break; /* no matching view */
271 if ((const char *)view->base + view->size <= (const char *)addr) continue;
272 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
273 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
274 return view;
276 return NULL;
280 /***********************************************************************
281 * get_mask
283 static inline UINT_PTR get_mask( ULONG zero_bits )
285 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
286 if (zero_bits < page_shift) zero_bits = page_shift;
287 return (1 << zero_bits) - 1;
291 /***********************************************************************
292 * find_view_range
294 * Find the first view overlapping at least part of the specified range.
295 * The csVirtual section must be held by caller.
297 static struct file_view *find_view_range( const void *addr, size_t size )
299 struct file_view *view;
301 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
303 if ((const char *)view->base >= (const char *)addr + size) break;
304 if ((const char *)view->base + view->size > (const char *)addr) return view;
306 return NULL;
310 /***********************************************************************
311 * find_free_area
313 * Find a free area between views inside the specified range.
314 * The csVirtual section must be held by caller.
316 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
318 struct list *ptr;
319 void *start;
321 if (top_down)
323 start = ROUND_ADDR( (char *)end - size, mask );
324 if (start >= end || start < base) return NULL;
326 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
328 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
330 if ((char *)view->base + view->size <= (char *)start) break;
331 if ((char *)view->base >= (char *)start + size) continue;
332 start = ROUND_ADDR( (char *)view->base - size, mask );
333 /* stop if remaining space is not large enough */
334 if (!start || start >= end || start < base) return NULL;
337 else
339 start = ROUND_ADDR( (char *)base + mask, mask );
340 if (start >= end || (char *)end - (char *)start < size) return NULL;
342 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
344 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
346 if ((char *)view->base >= (char *)start + size) break;
347 if ((char *)view->base + view->size <= (char *)start) continue;
348 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
349 /* stop if remaining space is not large enough */
350 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
353 return start;
357 /***********************************************************************
358 * add_reserved_area
360 * Add a reserved area to the list maintained by libwine.
361 * The csVirtual section must be held by caller.
363 static void add_reserved_area( void *addr, size_t size )
365 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
367 if (addr < user_space_limit)
369 /* unmap the part of the area that is below the limit */
370 assert( (char *)addr + size > (char *)user_space_limit );
371 munmap( addr, (char *)user_space_limit - (char *)addr );
372 size -= (char *)user_space_limit - (char *)addr;
373 addr = user_space_limit;
375 /* blow away existing mappings */
376 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
377 wine_mmap_add_reserved_area( addr, size );
381 /***********************************************************************
382 * remove_reserved_area
384 * Remove a reserved area from the list maintained by libwine.
385 * The csVirtual section must be held by caller.
387 static void remove_reserved_area( void *addr, size_t size )
389 struct file_view *view;
391 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
392 wine_mmap_remove_reserved_area( addr, size, 0 );
394 /* unmap areas not covered by an existing view */
395 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
397 if ((char *)view->base >= (char *)addr + size)
399 munmap( addr, size );
400 break;
402 if ((char *)view->base + view->size <= (char *)addr) continue;
403 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
404 if ((char *)view->base + view->size > (char *)addr + size) break;
405 size = (char *)addr + size - ((char *)view->base + view->size);
406 addr = (char *)view->base + view->size;
411 /***********************************************************************
412 * is_beyond_limit
414 * Check if an address range goes beyond a given limit.
416 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
418 return (addr >= limit || (const char *)addr + size > (const char *)limit);
422 /***********************************************************************
423 * unmap_area
425 * Unmap an area, or simply replace it by an empty mapping if it is
426 * in a reserved area. The csVirtual section must be held by caller.
428 static inline void unmap_area( void *addr, size_t size )
430 if (wine_mmap_is_in_reserved_area( addr, size ))
431 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
432 else if (is_beyond_limit( addr, size, user_space_limit ))
433 add_reserved_area( addr, size );
434 else
435 munmap( addr, size );
439 /***********************************************************************
440 * delete_view
442 * Deletes a view. The csVirtual section must be held by caller.
444 static void delete_view( struct file_view *view ) /* [in] View */
446 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
447 list_remove( &view->entry );
448 if (view->mapping) close_handle( view->mapping );
449 RtlFreeHeap( virtual_heap, 0, view );
453 /***********************************************************************
454 * create_view
456 * Create a view. The csVirtual section must be held by caller.
458 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
460 struct file_view *view;
461 struct list *ptr;
462 int unix_prot = VIRTUAL_GetUnixProt( vprot );
464 assert( !((UINT_PTR)base & page_mask) );
465 assert( !(size & page_mask) );
467 /* Create the view structure */
469 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
471 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
472 return STATUS_NO_MEMORY;
475 view->base = base;
476 view->size = size;
477 view->mapping = 0;
478 view->map_protect = 0;
479 view->protect = vprot;
480 memset( view->prot, vprot, size >> page_shift );
482 /* Insert it in the linked list */
484 LIST_FOR_EACH( ptr, &views_list )
486 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
487 if (next->base > base) break;
489 list_add_before( ptr, &view->entry );
491 /* Check for overlapping views. This can happen if the previous view
492 * was a system view that got unmapped behind our back. In that case
493 * we recover by simply deleting it. */
495 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
497 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
498 if ((char *)prev->base + prev->size > (char *)base)
500 TRACE( "overlapping prev view %p-%p for %p-%p\n",
501 prev->base, (char *)prev->base + prev->size,
502 base, (char *)base + view->size );
503 assert( prev->protect & VPROT_SYSTEM );
504 delete_view( prev );
507 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
509 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
510 if ((char *)base + view->size > (char *)next->base)
512 TRACE( "overlapping next view %p-%p for %p-%p\n",
513 next->base, (char *)next->base + next->size,
514 base, (char *)base + view->size );
515 assert( next->protect & VPROT_SYSTEM );
516 delete_view( next );
520 *view_ret = view;
521 VIRTUAL_DEBUG_DUMP_VIEW( view );
523 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
525 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
526 mprotect( base, size, unix_prot | PROT_EXEC );
528 return STATUS_SUCCESS;
532 /***********************************************************************
533 * VIRTUAL_GetWin32Prot
535 * Convert page protections to Win32 flags.
537 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
539 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
540 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
541 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
542 return ret;
546 /***********************************************************************
547 * get_vprot_flags
549 * Build page protections from Win32 flags.
551 * PARAMS
552 * protect [I] Win32 protection flags
554 * RETURNS
555 * Value of page protection flags
557 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
559 switch(protect & 0xff)
561 case PAGE_READONLY:
562 *vprot = VPROT_READ;
563 break;
564 case PAGE_READWRITE:
565 if (image)
566 *vprot = VPROT_READ | VPROT_WRITECOPY;
567 else
568 *vprot = VPROT_READ | VPROT_WRITE;
569 break;
570 case PAGE_WRITECOPY:
571 *vprot = VPROT_READ | VPROT_WRITECOPY;
572 break;
573 case PAGE_EXECUTE:
574 *vprot = VPROT_EXEC;
575 break;
576 case PAGE_EXECUTE_READ:
577 *vprot = VPROT_EXEC | VPROT_READ;
578 break;
579 case PAGE_EXECUTE_READWRITE:
580 if (image)
581 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
582 else
583 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
584 break;
585 case PAGE_EXECUTE_WRITECOPY:
586 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
587 break;
588 case PAGE_NOACCESS:
589 *vprot = 0;
590 break;
591 default:
592 return STATUS_INVALID_PAGE_PROTECTION;
594 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
595 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
596 return STATUS_SUCCESS;
600 /***********************************************************************
601 * VIRTUAL_SetProt
603 * Change the protection of a range of pages.
605 * RETURNS
606 * TRUE: Success
607 * FALSE: Failure
609 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
610 void *base, /* [in] Starting address */
611 size_t size, /* [in] Size in bytes */
612 BYTE vprot ) /* [in] Protections to use */
614 int unix_prot = VIRTUAL_GetUnixProt(vprot);
615 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
617 TRACE("%p-%p %s\n",
618 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
620 if (view->protect & VPROT_WRITEWATCH)
622 /* each page may need different protections depending on write watch flag */
623 UINT i, count;
624 char *addr = base;
625 int prot;
627 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
628 unix_prot = VIRTUAL_GetUnixProt( p[0] );
629 for (count = i = 1; i < size >> page_shift; i++, count++)
631 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
632 prot = VIRTUAL_GetUnixProt( p[i] );
633 if (prot == unix_prot) continue;
634 mprotect( addr, count << page_shift, unix_prot );
635 addr += count << page_shift;
636 unix_prot = prot;
637 count = 0;
639 if (count) mprotect( addr, count << page_shift, unix_prot );
640 VIRTUAL_DEBUG_DUMP_VIEW( view );
641 return TRUE;
644 /* if setting stack guard pages, store the permissions first, as the guard may be
645 * triggered at any point after mprotect and change the permissions again */
646 if ((vprot & VPROT_GUARD) &&
647 (base >= NtCurrentTeb()->DeallocationStack) &&
648 (base < NtCurrentTeb()->Tib.StackBase))
650 memset( p, vprot, size >> page_shift );
651 mprotect( base, size, unix_prot );
652 VIRTUAL_DEBUG_DUMP_VIEW( view );
653 return TRUE;
656 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
657 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
659 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
660 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
661 /* exec + write may legitimately fail, in that case fall back to write only */
662 if (!(unix_prot & PROT_WRITE)) return FALSE;
665 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
667 done:
668 memset( p, vprot, size >> page_shift );
669 VIRTUAL_DEBUG_DUMP_VIEW( view );
670 return TRUE;
674 /***********************************************************************
675 * reset_write_watches
677 * Reset write watches in a memory range.
679 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
681 SIZE_T i, count;
682 int prot, unix_prot;
683 char *addr = base;
684 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
686 p[0] |= VPROT_WRITEWATCH;
687 unix_prot = VIRTUAL_GetUnixProt( p[0] );
688 for (count = i = 1; i < size >> page_shift; i++, count++)
690 p[i] |= VPROT_WRITEWATCH;
691 prot = VIRTUAL_GetUnixProt( p[i] );
692 if (prot == unix_prot) continue;
693 mprotect( addr, count << page_shift, unix_prot );
694 addr += count << page_shift;
695 unix_prot = prot;
696 count = 0;
698 if (count) mprotect( addr, count << page_shift, unix_prot );
702 /***********************************************************************
703 * unmap_extra_space
705 * Release the extra memory while keeping the range starting on the granularity boundary.
707 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
709 if ((ULONG_PTR)ptr & mask)
711 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
712 munmap( ptr, extra );
713 ptr = (char *)ptr + extra;
714 total_size -= extra;
716 if (total_size > wanted_size)
717 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
718 return ptr;
722 struct alloc_area
724 size_t size;
725 size_t mask;
726 int top_down;
727 void *limit;
728 void *result;
731 /***********************************************************************
732 * alloc_reserved_area_callback
734 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
736 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
738 struct alloc_area *alloc = arg;
739 void *end = (char *)start + size;
741 if (start < address_space_start) start = address_space_start;
742 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
743 if (start >= end) return 0;
745 /* make sure we don't touch the preloader reserved range */
746 if (preload_reserve_end >= start)
748 if (preload_reserve_end >= end)
750 if (preload_reserve_start <= start) return 0; /* no space in that area */
751 if (preload_reserve_start < end) end = preload_reserve_start;
753 else if (preload_reserve_start <= start) start = preload_reserve_end;
754 else
756 /* range is split in two by the preloader reservation, try first part */
757 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
758 alloc->mask, alloc->top_down )))
759 return 1;
760 /* then fall through to try second part */
761 start = preload_reserve_end;
764 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
765 return 1;
767 return 0;
771 /***********************************************************************
772 * map_view
774 * Create a view and mmap the corresponding memory area.
775 * The csVirtual section must be held by caller.
777 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
778 int top_down, unsigned int vprot )
780 void *ptr;
781 NTSTATUS status;
783 if (base)
785 if (is_beyond_limit( base, size, address_space_limit ))
786 return STATUS_WORKING_SET_LIMIT_RANGE;
788 switch (wine_mmap_is_in_reserved_area( base, size ))
790 case -1: /* partially in a reserved area */
791 return STATUS_CONFLICTING_ADDRESSES;
793 case 0: /* not in a reserved area, do a normal allocation */
794 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
796 if (errno == ENOMEM) return STATUS_NO_MEMORY;
797 return STATUS_INVALID_PARAMETER;
799 if (ptr != base)
801 /* We couldn't get the address we wanted */
802 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
803 else munmap( ptr, size );
804 return STATUS_CONFLICTING_ADDRESSES;
806 break;
808 default:
809 case 1: /* in a reserved area, make sure the address is available */
810 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
811 /* replace the reserved area by our mapping */
812 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
813 return STATUS_INVALID_PARAMETER;
814 break;
816 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
818 else
820 size_t view_size = size + mask + 1;
821 struct alloc_area alloc;
823 alloc.size = size;
824 alloc.mask = mask;
825 alloc.top_down = top_down;
826 alloc.limit = user_space_limit;
827 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
829 ptr = alloc.result;
830 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
831 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
832 return STATUS_INVALID_PARAMETER;
833 goto done;
836 for (;;)
838 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
840 if (errno == ENOMEM) return STATUS_NO_MEMORY;
841 return STATUS_INVALID_PARAMETER;
843 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
844 /* if we got something beyond the user limit, unmap it and retry */
845 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
846 else break;
848 ptr = unmap_extra_space( ptr, view_size, size, mask );
850 done:
851 status = create_view( view_ret, ptr, size, vprot );
852 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
853 return status;
857 /***********************************************************************
858 * map_file_into_view
860 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
861 * The csVirtual section must be held by caller.
863 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
864 off_t offset, unsigned int vprot, BOOL removable )
866 void *ptr;
867 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
868 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
870 assert( start < view->size );
871 assert( start + size <= view->size );
873 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
875 TRACE( "forcing exec permission on mapping %p-%p\n",
876 (char *)view->base + start, (char *)view->base + start + size - 1 );
877 prot |= PROT_EXEC;
880 /* only try mmap if media is not removable (or if we require write access) */
881 if (!removable || shared_write)
883 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
885 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
886 goto done;
888 if ((errno == EPERM) && (prot & PROT_EXEC))
889 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
891 /* mmap() failed; if this is because the file offset is not */
892 /* page-aligned (EINVAL), or because the underlying filesystem */
893 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
894 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
895 if (shared_write) /* we cannot fake shared write mappings */
897 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
898 ERR( "shared writable mmap not supported, broken filesystem?\n" );
899 return STATUS_NOT_SUPPORTED;
903 /* Reserve the memory with an anonymous mmap */
904 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
905 if (ptr == (void *)-1) return FILE_GetNtStatus();
906 /* Now read in the file */
907 pread( fd, ptr, size, offset );
908 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
909 done:
910 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
911 return STATUS_SUCCESS;
915 /***********************************************************************
916 * get_committed_size
918 * Get the size of the committed range starting at base.
919 * Also return the protections for the first page.
921 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
923 SIZE_T i, start;
925 start = ((char *)base - (char *)view->base) >> page_shift;
926 *vprot = view->prot[start];
928 if (view->mapping && !(view->protect & VPROT_COMMITTED))
930 SIZE_T ret = 0;
931 SERVER_START_REQ( get_mapping_committed_range )
933 req->handle = wine_server_obj_handle( view->mapping );
934 req->offset = start << page_shift;
935 if (!wine_server_call( req ))
937 ret = reply->size;
938 if (reply->committed)
940 *vprot |= VPROT_COMMITTED;
941 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
945 SERVER_END_REQ;
946 return ret;
948 for (i = start + 1; i < view->size >> page_shift; i++)
949 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
950 return (i - start) << page_shift;
954 /***********************************************************************
955 * decommit_view
957 * Decommit some pages of a given view.
958 * The csVirtual section must be held by caller.
960 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
962 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
964 BYTE *p = view->prot + (start >> page_shift);
965 size >>= page_shift;
966 while (size--) *p++ &= ~VPROT_COMMITTED;
967 return STATUS_SUCCESS;
969 return FILE_GetNtStatus();
973 /***********************************************************************
974 * allocate_dos_memory
976 * Allocate the DOS memory range.
978 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
980 size_t size;
981 void *addr = NULL;
982 void * const low_64k = (void *)0x10000;
983 const size_t dosmem_size = 0x110000;
984 int unix_prot = VIRTUAL_GetUnixProt( vprot );
985 struct list *ptr;
987 /* check for existing view */
989 if ((ptr = list_head( &views_list )))
991 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
992 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
995 /* check without the first 64K */
997 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
999 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1000 if (addr != low_64k)
1002 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1003 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1007 /* now try to allocate the low 64K too */
1009 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1011 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1012 if (addr == (void *)page_size)
1014 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1016 addr = NULL;
1017 TRACE( "successfully mapped low 64K range\n" );
1019 else TRACE( "failed to map page 0\n" );
1021 else
1023 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1024 addr = low_64k;
1025 TRACE( "failed to map low 64K range\n" );
1029 /* now reserve the whole range */
1031 size = (char *)dosmem_size - (char *)addr;
1032 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1033 return create_view( view, addr, size, vprot );
1037 /***********************************************************************
1038 * check_architecture
1040 * Check the architecture of a PE binary.
1042 static NTSTATUS check_architecture( const IMAGE_NT_HEADERS *nt )
1044 static const char *arch;
1046 #ifdef __i386__
1047 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_I386) return STATUS_SUCCESS;
1048 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
1050 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) /* don't warn for a 64-bit exe */
1051 WARN( "loading amd64 dll in 32-bit mode will fail\n" );
1052 return STATUS_INVALID_IMAGE_FORMAT;
1054 #elif defined(__x86_64__)
1055 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) return STATUS_SUCCESS;
1056 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
1058 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) /* don't warn for a 32-bit exe */
1059 WARN( "loading 32-bit dll in 64-bit mode will fail\n" );
1060 return STATUS_INVALID_IMAGE_FORMAT;
1062 #elif defined(__arm__) && !defined(__ARMEB__)
1063 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_ARM ||
1064 #if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__)
1065 nt->FileHeader.Machine == IMAGE_FILE_MACHINE_ARMV7 ||
1066 #endif
1067 nt->FileHeader.Machine == IMAGE_FILE_MACHINE_THUMB)
1068 return STATUS_SUCCESS;
1069 #endif
1071 switch (nt->FileHeader.Machine)
1073 case IMAGE_FILE_MACHINE_UNKNOWN: arch = "Unknown"; break;
1074 case IMAGE_FILE_MACHINE_I860: arch = "I860"; break;
1075 case IMAGE_FILE_MACHINE_I386: arch = "I386"; break;
1076 case IMAGE_FILE_MACHINE_R3000: arch = "R3000"; break;
1077 case IMAGE_FILE_MACHINE_R4000: arch = "R4000"; break;
1078 case IMAGE_FILE_MACHINE_R10000: arch = "R10000"; break;
1079 case IMAGE_FILE_MACHINE_ALPHA: arch = "Alpha"; break;
1080 case IMAGE_FILE_MACHINE_POWERPC: arch = "PowerPC"; break;
1081 case IMAGE_FILE_MACHINE_IA64: arch = "IA-64"; break;
1082 case IMAGE_FILE_MACHINE_ALPHA64: arch = "Alpha-64"; break;
1083 case IMAGE_FILE_MACHINE_AMD64: arch = "AMD-64"; break;
1084 case IMAGE_FILE_MACHINE_ARM: arch = "ARM"; break;
1085 case IMAGE_FILE_MACHINE_ARMV7: arch = "ARMv7"; break;
1086 case IMAGE_FILE_MACHINE_THUMB: arch = "ARM Thumb"; break;
1087 case IMAGE_FILE_MACHINE_SPARC: arch = "SPARC"; break;
1088 default: arch = wine_dbg_sprintf( "Unknown-%04x", nt->FileHeader.Machine ); break;
1090 ERR( "Trying to load PE image for unsupported architecture %s\n", arch );
1091 return STATUS_INVALID_IMAGE_FORMAT;
1095 /***********************************************************************
1096 * stat_mapping_file
1098 * Stat the underlying file for a memory view.
1100 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1102 NTSTATUS status;
1103 int unix_fd, needs_close;
1105 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1106 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1108 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1109 if (needs_close) close( unix_fd );
1111 return status;
1115 /***********************************************************************
1116 * map_image
1118 * Map an executable (PE format) image into memory.
1120 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1121 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1123 IMAGE_DOS_HEADER *dos;
1124 IMAGE_NT_HEADERS *nt;
1125 IMAGE_SECTION_HEADER *sec, *sections = NULL;
1126 IMAGE_DATA_DIRECTORY *imports;
1127 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1128 int i;
1129 off_t pos;
1130 sigset_t sigset;
1131 struct stat st;
1132 struct file_view *view = NULL;
1133 char *ptr, *header_end, *header_start;
1134 INT_PTR delta = 0;
1136 /* zero-map the whole range */
1138 server_enter_uninterrupted_section( &csVirtual, &sigset );
1140 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1141 status = map_view( &view, base, total_size, mask, FALSE,
1142 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1144 if (status != STATUS_SUCCESS)
1145 status = map_view( &view, NULL, total_size, mask, FALSE,
1146 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1148 if (status != STATUS_SUCCESS) goto error;
1150 ptr = view->base;
1151 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1153 /* map the header */
1155 if (fstat( fd, &st ) == -1)
1157 status = FILE_GetNtStatus();
1158 goto error;
1160 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1161 if (!st.st_size) goto error;
1162 header_size = min( header_size, st.st_size );
1163 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1164 !dup_mapping ) != STATUS_SUCCESS) goto error;
1165 dos = (IMAGE_DOS_HEADER *)ptr;
1166 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1167 header_end = ptr + ROUND_SIZE( 0, header_size );
1168 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1169 if ((char *)(nt + 1) > header_end) goto error;
1170 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1171 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1172 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1173 * copying the headers into local memory is necessary to properly load such applications. */
1174 sections = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1175 if (!sections)
1177 status = STATUS_NO_MEMORY;
1178 goto error;
1180 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1181 sec = sections;
1183 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1184 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1186 if (check_architecture( nt )) goto error;
1188 /* check for non page-aligned binary */
1190 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1192 /* unaligned sections, this happens for native subsystem binaries */
1193 /* in that case Windows simply maps in the whole file */
1195 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1196 !dup_mapping ) != STATUS_SUCCESS) goto error;
1198 /* check that all sections are loaded at the right offset */
1199 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1200 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1202 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1203 goto error; /* Windows refuses to load in that case too */
1206 /* set the image protections */
1207 VIRTUAL_SetProt( view, ptr, total_size,
1208 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1210 /* no relocations are performed on non page-aligned binaries */
1211 goto done;
1215 /* map all the sections */
1217 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1219 static const SIZE_T sector_align = 0x1ff;
1220 SIZE_T map_size, file_start, file_size, end;
1222 if (!sec->Misc.VirtualSize)
1223 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1224 else
1225 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1227 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1228 file_start = sec->PointerToRawData & ~sector_align;
1229 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1230 if (file_size > map_size) file_size = map_size;
1232 /* a few sanity checks */
1233 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1234 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1236 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1237 sec->Name, sec->VirtualAddress, map_size, total_size );
1238 goto error;
1241 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1242 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1244 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1245 sec->Name, ptr + sec->VirtualAddress,
1246 sec->PointerToRawData, (int)pos, file_size, map_size,
1247 sec->Characteristics );
1248 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1249 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1250 FALSE ) != STATUS_SUCCESS)
1252 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1253 goto error;
1256 /* check if the import directory falls inside this section */
1257 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1258 imports->VirtualAddress < sec->VirtualAddress + map_size)
1260 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1261 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1262 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1263 if (end > base)
1264 map_file_into_view( view, shared_fd, base, end - base,
1265 pos + (base - sec->VirtualAddress),
1266 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1267 FALSE );
1269 pos += map_size;
1270 continue;
1273 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1274 sec->Name, ptr + sec->VirtualAddress,
1275 sec->PointerToRawData, sec->SizeOfRawData,
1276 sec->Misc.VirtualSize, sec->Characteristics );
1278 if (!sec->PointerToRawData || !file_size) continue;
1280 /* Note: if the section is not aligned properly map_file_into_view will magically
1281 * fall back to read(), so we don't need to check anything here.
1283 end = file_start + file_size;
1284 if (sec->PointerToRawData >= st.st_size ||
1285 end > ((st.st_size + sector_align) & ~sector_align) ||
1286 end < file_start ||
1287 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1288 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1289 !dup_mapping ) != STATUS_SUCCESS)
1291 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1292 goto error;
1295 if (file_size & page_mask)
1297 end = ROUND_SIZE( 0, file_size );
1298 if (end > map_size) end = map_size;
1299 TRACE_(module)("clearing %p - %p\n",
1300 ptr + sec->VirtualAddress + file_size,
1301 ptr + sec->VirtualAddress + end );
1302 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1307 /* perform base relocation, if necessary */
1309 if (ptr != base &&
1310 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1311 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1313 IMAGE_BASE_RELOCATION *rel, *end;
1314 const IMAGE_DATA_DIRECTORY *relocs;
1316 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1318 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1319 base, ptr );
1320 status = STATUS_CONFLICTING_ADDRESSES;
1321 goto error;
1324 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1325 base, base + total_size, ptr, ptr + total_size );
1327 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1328 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1329 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1330 delta = ptr - base;
1332 while (rel < end - 1 && rel->SizeOfBlock)
1334 if (rel->VirtualAddress >= total_size)
1336 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1337 status = STATUS_ACCESS_VIOLATION;
1338 goto error;
1340 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1341 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1342 (USHORT *)(rel + 1), delta );
1343 if (!rel) goto error;
1347 /* set the image protections */
1349 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1351 sec = sections;
1352 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1354 SIZE_T size;
1355 BYTE vprot = VPROT_COMMITTED;
1357 if (sec->Misc.VirtualSize)
1358 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1359 else
1360 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1362 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1363 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1364 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1366 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1367 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1368 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1369 vprot |= VPROT_EXEC;
1371 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1372 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1373 sec->Characteristics, sec->Name );
1376 done:
1377 RtlFreeHeap( GetProcessHeap(), 0, sections );
1378 view->mapping = dup_mapping;
1379 view->map_protect = map_vprot;
1380 server_leave_uninterrupted_section( &csVirtual, &sigset );
1382 *addr_ptr = ptr;
1383 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1384 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1385 #endif
1386 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1387 return STATUS_SUCCESS;
1389 error:
1390 RtlFreeHeap( GetProcessHeap(), 0, sections );
1391 if (view) delete_view( view );
1392 server_leave_uninterrupted_section( &csVirtual, &sigset );
1393 if (dup_mapping) NtClose( dup_mapping );
1394 return status;
1398 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1399 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1401 void **heap_base = arg;
1403 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1404 if (size < VIRTUAL_HEAP_SIZE) return 0;
1405 if (is_win64 && base < (void *)0x80000000) return 0;
1406 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1407 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1408 return (*heap_base != (void *)-1);
1411 /***********************************************************************
1412 * virtual_init
1414 void virtual_init(void)
1416 const char *preload;
1417 void *heap_base;
1418 size_t size;
1419 struct file_view *heap_view;
1421 #ifndef page_mask
1422 page_size = getpagesize();
1423 page_mask = page_size - 1;
1424 /* Make sure we have a power of 2 */
1425 assert( !(page_size & page_mask) );
1426 page_shift = 0;
1427 while ((1 << page_shift) != page_size) page_shift++;
1428 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1429 #endif /* page_mask */
1430 if ((preload = getenv("WINEPRELOADRESERVE")))
1432 unsigned long start, end;
1433 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1435 preload_reserve_start = (void *)start;
1436 preload_reserve_end = (void *)end;
1440 /* try to find space in a reserved area for the virtual heap */
1441 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1442 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1444 assert( heap_base != (void *)-1 );
1445 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1446 VIRTUAL_HEAP_SIZE, NULL, NULL );
1447 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1449 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1450 size = (char *)address_space_start - (char *)0x10000;
1451 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1452 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1456 /***********************************************************************
1457 * virtual_init_threading
1459 void virtual_init_threading(void)
1461 use_locks = 1;
1465 /***********************************************************************
1466 * virtual_get_system_info
1468 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1470 info->unknown = 0;
1471 info->KeMaximumIncrement = 0; /* FIXME */
1472 info->PageSize = page_size;
1473 info->MmLowestPhysicalPage = 1;
1474 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1475 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1476 info->AllocationGranularity = get_mask(0) + 1;
1477 info->LowestUserAddress = (void *)0x10000;
1478 info->HighestUserAddress = (char *)user_space_limit - 1;
1479 info->ActiveProcessorsAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1480 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1484 /***********************************************************************
1485 * virtual_create_builtin_view
1487 NTSTATUS virtual_create_builtin_view( void *module )
1489 NTSTATUS status;
1490 sigset_t sigset;
1491 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1492 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1493 IMAGE_SECTION_HEADER *sec;
1494 struct file_view *view;
1495 void *base;
1496 int i;
1498 size = ROUND_SIZE( module, size );
1499 base = ROUND_ADDR( module, page_mask );
1500 server_enter_uninterrupted_section( &csVirtual, &sigset );
1501 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1502 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1503 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1504 server_leave_uninterrupted_section( &csVirtual, &sigset );
1506 if (status) return status;
1508 /* The PE header is always read-only, no write, no execute. */
1509 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1511 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1512 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1514 BYTE flags = VPROT_COMMITTED;
1516 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1517 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1518 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1519 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1520 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1523 return status;
1527 /***********************************************************************
1528 * virtual_alloc_thread_stack
1530 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1532 struct file_view *view;
1533 NTSTATUS status;
1534 sigset_t sigset;
1535 SIZE_T size;
1537 if (!reserve_size || !commit_size)
1539 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1540 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1541 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1544 size = max( reserve_size, commit_size );
1545 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1546 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1548 server_enter_uninterrupted_section( &csVirtual, &sigset );
1550 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1551 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1552 goto done;
1554 #ifdef VALGRIND_STACK_REGISTER
1555 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1556 #endif
1558 /* setup no access guard page */
1559 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1560 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1561 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1563 /* note: limit is lower than base since the stack grows down */
1564 teb->DeallocationStack = view->base;
1565 teb->Tib.StackBase = (char *)view->base + view->size;
1566 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1567 done:
1568 server_leave_uninterrupted_section( &csVirtual, &sigset );
1569 return status;
1573 /***********************************************************************
1574 * virtual_clear_thread_stack
1576 * Clear the stack contents before calling the main entry point, some broken apps need that.
1578 void virtual_clear_thread_stack(void)
1580 void *stack = NtCurrentTeb()->Tib.StackLimit;
1581 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1583 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1584 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1588 /***********************************************************************
1589 * virtual_handle_fault
1591 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1593 struct file_view *view;
1594 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1595 sigset_t sigset;
1597 server_enter_uninterrupted_section( &csVirtual, &sigset );
1598 if ((view = VIRTUAL_FindView( addr, 0 )))
1600 void *page = ROUND_ADDR( addr, page_mask );
1601 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1602 if (*vprot & VPROT_GUARD)
1604 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1605 ret = STATUS_GUARD_PAGE_VIOLATION;
1607 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1609 if (*vprot & VPROT_WRITEWATCH)
1611 *vprot &= ~VPROT_WRITEWATCH;
1612 VIRTUAL_SetProt( view, page, page_size, *vprot );
1614 /* ignore fault if page is writable now */
1615 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1618 server_leave_uninterrupted_section( &csVirtual, &sigset );
1619 return ret;
1624 /***********************************************************************
1625 * virtual_handle_stack_fault
1627 * Handle an access fault inside the current thread stack.
1628 * Called from inside a signal handler.
1630 BOOL virtual_handle_stack_fault( void *addr )
1632 struct file_view *view;
1633 BOOL ret = FALSE;
1635 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1636 if ((view = VIRTUAL_FindView( addr, 0 )))
1638 void *page = ROUND_ADDR( addr, page_mask );
1639 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1640 if (vprot & VPROT_GUARD)
1642 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1643 NtCurrentTeb()->Tib.StackLimit = page;
1644 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1646 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1647 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
1649 ret = TRUE;
1652 RtlLeaveCriticalSection( &csVirtual );
1653 return ret;
1657 /***********************************************************************
1658 * virtual_check_buffer_for_read
1660 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1662 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1664 if (!size) return TRUE;
1665 if (!ptr) return FALSE;
1667 __TRY
1669 volatile const char *p = ptr;
1670 char dummy __attribute__((unused));
1671 SIZE_T count = size;
1673 while (count > page_size)
1675 dummy = *p;
1676 p += page_size;
1677 count -= page_size;
1679 dummy = p[0];
1680 dummy = p[count - 1];
1682 __EXCEPT_PAGE_FAULT
1684 return FALSE;
1686 __ENDTRY
1687 return TRUE;
1691 /***********************************************************************
1692 * virtual_check_buffer_for_write
1694 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1696 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1698 if (!size) return TRUE;
1699 if (!ptr) return FALSE;
1701 __TRY
1703 volatile char *p = ptr;
1704 SIZE_T count = size;
1706 while (count > page_size)
1708 *p |= 0;
1709 p += page_size;
1710 count -= page_size;
1712 p[0] |= 0;
1713 p[count - 1] |= 0;
1715 __EXCEPT_PAGE_FAULT
1717 return FALSE;
1719 __ENDTRY
1720 return TRUE;
1724 /***********************************************************************
1725 * VIRTUAL_SetForceExec
1727 * Whether to force exec prot on all views.
1729 void VIRTUAL_SetForceExec( BOOL enable )
1731 struct file_view *view;
1732 sigset_t sigset;
1734 server_enter_uninterrupted_section( &csVirtual, &sigset );
1735 if (!force_exec_prot != !enable) /* change all existing views */
1737 force_exec_prot = enable;
1739 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1741 UINT i, count;
1742 char *addr = view->base;
1743 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1744 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1746 if (view->protect & VPROT_NOEXEC) continue;
1747 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1749 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1750 if (prot == unix_prot) continue;
1751 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1753 TRACE( "%s exec prot for %p-%p\n",
1754 force_exec_prot ? "enabling" : "disabling",
1755 addr, addr + (count << page_shift) - 1 );
1756 mprotect( addr, count << page_shift,
1757 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1759 addr += (count << page_shift);
1760 unix_prot = prot;
1761 count = 0;
1763 if (count)
1765 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1767 TRACE( "%s exec prot for %p-%p\n",
1768 force_exec_prot ? "enabling" : "disabling",
1769 addr, addr + (count << page_shift) - 1 );
1770 mprotect( addr, count << page_shift,
1771 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1776 server_leave_uninterrupted_section( &csVirtual, &sigset );
1779 struct free_range
1781 char *base;
1782 char *limit;
1785 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1786 static int free_reserved_memory( void *base, size_t size, void *arg )
1788 struct free_range *range = arg;
1790 if ((char *)base >= range->limit) return 0;
1791 if ((char *)base + size <= range->base) return 0;
1792 if ((char *)base < range->base)
1794 size -= range->base - (char *)base;
1795 base = range->base;
1797 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1798 remove_reserved_area( base, size );
1799 return 1; /* stop enumeration since the list has changed */
1802 /***********************************************************************
1803 * virtual_release_address_space
1805 * Release some address space once we have loaded and initialized the app.
1807 void virtual_release_address_space( BOOL free_high_mem )
1809 struct free_range range;
1810 sigset_t sigset;
1812 if (user_space_limit == address_space_limit) return; /* no need to free anything */
1814 server_enter_uninterrupted_section( &csVirtual, &sigset );
1816 /* no large address space on win9x */
1817 if (free_high_mem && NtCurrentTeb()->Peb->OSPlatformId == VER_PLATFORM_WIN32_NT)
1819 range.base = (char *)0x82000000;
1820 range.limit = address_space_limit;
1821 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1822 user_space_limit = working_set_limit = address_space_limit;
1824 else
1826 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1827 range.base = (char *)0x20000000;
1828 range.limit = (char *)0x7f000000;
1829 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1830 #endif
1833 server_leave_uninterrupted_section( &csVirtual, &sigset );
1837 /***********************************************************************
1838 * NtAllocateVirtualMemory (NTDLL.@)
1839 * ZwAllocateVirtualMemory (NTDLL.@)
1841 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1842 SIZE_T *size_ptr, ULONG type, ULONG protect )
1844 void *base;
1845 unsigned int vprot;
1846 SIZE_T size = *size_ptr;
1847 SIZE_T mask = get_mask( zero_bits );
1848 NTSTATUS status = STATUS_SUCCESS;
1849 struct file_view *view;
1850 sigset_t sigset;
1852 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1854 if (!size) return STATUS_INVALID_PARAMETER;
1856 if (process != NtCurrentProcess())
1858 apc_call_t call;
1859 apc_result_t result;
1861 memset( &call, 0, sizeof(call) );
1863 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1864 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1865 call.virtual_alloc.size = *size_ptr;
1866 call.virtual_alloc.zero_bits = zero_bits;
1867 call.virtual_alloc.op_type = type;
1868 call.virtual_alloc.prot = protect;
1869 status = NTDLL_queue_process_apc( process, &call, &result );
1870 if (status != STATUS_SUCCESS) return status;
1872 if (result.virtual_alloc.status == STATUS_SUCCESS)
1874 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1875 *size_ptr = result.virtual_alloc.size;
1877 return result.virtual_alloc.status;
1880 /* Round parameters to a page boundary */
1882 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1884 if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1885 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1886 vprot |= VPROT_VALLOC;
1887 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1889 if (*ret)
1891 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1892 base = ROUND_ADDR( *ret, mask );
1893 else
1894 base = ROUND_ADDR( *ret, page_mask );
1895 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1897 /* address 1 is magic to mean DOS area */
1898 if (!base && *ret == (void *)1 && size == 0x110000)
1900 server_enter_uninterrupted_section( &csVirtual, &sigset );
1901 status = allocate_dos_memory( &view, vprot );
1902 if (status == STATUS_SUCCESS)
1904 *ret = view->base;
1905 *size_ptr = view->size;
1907 server_leave_uninterrupted_section( &csVirtual, &sigset );
1908 return status;
1911 /* disallow low 64k, wrap-around and kernel space */
1912 if (((char *)base < (char *)0x10000) ||
1913 ((char *)base + size < (char *)base) ||
1914 is_beyond_limit( base, size, address_space_limit ))
1915 return STATUS_INVALID_PARAMETER;
1917 else
1919 base = NULL;
1920 size = (size + page_mask) & ~page_mask;
1923 /* Compute the alloc type flags */
1925 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1926 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1928 WARN("called with wrong alloc type flags (%08x) !\n", type);
1929 return STATUS_INVALID_PARAMETER;
1932 /* Reserve the memory */
1934 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1936 if ((type & MEM_RESERVE) || !base)
1938 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1939 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1940 if (status == STATUS_SUCCESS) base = view->base;
1942 else if (type & MEM_RESET)
1944 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1945 else madvise( base, size, MADV_DONTNEED );
1947 else /* commit the pages */
1949 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1950 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1951 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1953 SERVER_START_REQ( add_mapping_committed_range )
1955 req->handle = wine_server_obj_handle( view->mapping );
1956 req->offset = (char *)base - (char *)view->base;
1957 req->size = size;
1958 wine_server_call( req );
1960 SERVER_END_REQ;
1964 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1966 if (status == STATUS_SUCCESS)
1968 *ret = base;
1969 *size_ptr = size;
1971 return status;
1975 /***********************************************************************
1976 * NtFreeVirtualMemory (NTDLL.@)
1977 * ZwFreeVirtualMemory (NTDLL.@)
1979 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1981 struct file_view *view;
1982 char *base;
1983 sigset_t sigset;
1984 NTSTATUS status = STATUS_SUCCESS;
1985 LPVOID addr = *addr_ptr;
1986 SIZE_T size = *size_ptr;
1988 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1990 if (process != NtCurrentProcess())
1992 apc_call_t call;
1993 apc_result_t result;
1995 memset( &call, 0, sizeof(call) );
1997 call.virtual_free.type = APC_VIRTUAL_FREE;
1998 call.virtual_free.addr = wine_server_client_ptr( addr );
1999 call.virtual_free.size = size;
2000 call.virtual_free.op_type = type;
2001 status = NTDLL_queue_process_apc( process, &call, &result );
2002 if (status != STATUS_SUCCESS) return status;
2004 if (result.virtual_free.status == STATUS_SUCCESS)
2006 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2007 *size_ptr = result.virtual_free.size;
2009 return result.virtual_free.status;
2012 /* Fix the parameters */
2014 size = ROUND_SIZE( addr, size );
2015 base = ROUND_ADDR( addr, page_mask );
2017 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2018 if (!base) return STATUS_INVALID_PARAMETER;
2020 server_enter_uninterrupted_section( &csVirtual, &sigset );
2022 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2024 status = STATUS_INVALID_PARAMETER;
2026 else if (type == MEM_RELEASE)
2028 /* Free the pages */
2030 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2031 else
2033 delete_view( view );
2034 *addr_ptr = base;
2035 *size_ptr = size;
2038 else if (type == MEM_DECOMMIT)
2040 status = decommit_pages( view, base - (char *)view->base, size );
2041 if (status == STATUS_SUCCESS)
2043 *addr_ptr = base;
2044 *size_ptr = size;
2047 else
2049 WARN("called with wrong free type flags (%08x) !\n", type);
2050 status = STATUS_INVALID_PARAMETER;
2053 server_leave_uninterrupted_section( &csVirtual, &sigset );
2054 return status;
2057 static ULONG map_protection_to_access( ULONG vprot )
2059 vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2060 if (vprot & VPROT_EXEC)
2062 if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2064 else vprot &= ~VPROT_WRITECOPY;
2065 return vprot;
2068 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2070 ULONG view_prot, map_prot;
2072 view_prot = map_protection_to_access( view->protect );
2073 new_prot = map_protection_to_access( new_prot );
2075 if (view_prot == new_prot) return TRUE;
2076 if (!view_prot) return FALSE;
2078 if ((view_prot & new_prot) != new_prot) return FALSE;
2080 map_prot = map_protection_to_access( view->map_protect );
2081 if ((map_prot & new_prot) == new_prot) return TRUE;
2083 return FALSE;
2086 /***********************************************************************
2087 * NtProtectVirtualMemory (NTDLL.@)
2088 * ZwProtectVirtualMemory (NTDLL.@)
2090 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2091 ULONG new_prot, ULONG *old_prot )
2093 struct file_view *view;
2094 sigset_t sigset;
2095 NTSTATUS status = STATUS_SUCCESS;
2096 char *base;
2097 BYTE vprot;
2098 unsigned int new_vprot;
2099 SIZE_T size = *size_ptr;
2100 LPVOID addr = *addr_ptr;
2102 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2104 if (process != NtCurrentProcess())
2106 apc_call_t call;
2107 apc_result_t result;
2109 memset( &call, 0, sizeof(call) );
2111 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2112 call.virtual_protect.addr = wine_server_client_ptr( addr );
2113 call.virtual_protect.size = size;
2114 call.virtual_protect.prot = new_prot;
2115 status = NTDLL_queue_process_apc( process, &call, &result );
2116 if (status != STATUS_SUCCESS) return status;
2118 if (result.virtual_protect.status == STATUS_SUCCESS)
2120 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2121 *size_ptr = result.virtual_protect.size;
2122 if (old_prot) *old_prot = result.virtual_protect.prot;
2124 return result.virtual_protect.status;
2127 /* Fix the parameters */
2129 size = ROUND_SIZE( addr, size );
2130 base = ROUND_ADDR( addr, page_mask );
2132 server_enter_uninterrupted_section( &csVirtual, &sigset );
2134 if ((view = VIRTUAL_FindView( base, size )))
2136 /* Make sure all the pages are committed */
2137 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2139 if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2141 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2142 status = STATUS_INVALID_PAGE_PROTECTION;
2143 else
2145 if (!view->mapping || is_compatible_protection( view, new_vprot ))
2147 new_vprot |= VPROT_COMMITTED;
2148 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2149 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2151 else status = STATUS_INVALID_PAGE_PROTECTION;
2155 else status = STATUS_NOT_COMMITTED;
2157 else status = STATUS_INVALID_PARAMETER;
2159 server_leave_uninterrupted_section( &csVirtual, &sigset );
2161 if (status == STATUS_SUCCESS)
2163 *addr_ptr = base;
2164 *size_ptr = size;
2166 return status;
2170 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2171 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2173 MEMORY_BASIC_INFORMATION *info = arg;
2174 void *end = (char *)start + size;
2176 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2178 if (info->BaseAddress >= end)
2180 if (info->AllocationBase < end) info->AllocationBase = end;
2181 return 0;
2184 if (info->BaseAddress >= start || start <= address_space_start)
2186 /* it's a real free area */
2187 info->State = MEM_FREE;
2188 info->Protect = PAGE_NOACCESS;
2189 info->AllocationBase = 0;
2190 info->AllocationProtect = 0;
2191 info->Type = 0;
2192 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2193 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2195 else /* outside of the reserved area, pretend it's allocated */
2197 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2198 info->State = MEM_RESERVE;
2199 info->Protect = PAGE_NOACCESS;
2200 info->AllocationProtect = PAGE_NOACCESS;
2201 info->Type = MEM_PRIVATE;
2203 return 1;
2206 #define UNIMPLEMENTED_INFO_CLASS(c) \
2207 case c: \
2208 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2209 return STATUS_INVALID_INFO_CLASS
2211 /***********************************************************************
2212 * NtQueryVirtualMemory (NTDLL.@)
2213 * ZwQueryVirtualMemory (NTDLL.@)
2215 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2216 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2217 SIZE_T len, SIZE_T *res_len )
2219 struct file_view *view;
2220 char *base, *alloc_base = 0;
2221 struct list *ptr;
2222 SIZE_T size = 0;
2223 MEMORY_BASIC_INFORMATION *info = buffer;
2224 sigset_t sigset;
2226 if (info_class != MemoryBasicInformation)
2228 switch(info_class)
2230 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2231 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2232 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2234 default:
2235 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2236 process, addr, info_class, buffer, len, res_len);
2237 return STATUS_INVALID_INFO_CLASS;
2241 if (process != NtCurrentProcess())
2243 NTSTATUS status;
2244 apc_call_t call;
2245 apc_result_t result;
2247 memset( &call, 0, sizeof(call) );
2249 call.virtual_query.type = APC_VIRTUAL_QUERY;
2250 call.virtual_query.addr = wine_server_client_ptr( addr );
2251 status = NTDLL_queue_process_apc( process, &call, &result );
2252 if (status != STATUS_SUCCESS) return status;
2254 if (result.virtual_query.status == STATUS_SUCCESS)
2256 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2257 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2258 info->RegionSize = result.virtual_query.size;
2259 info->Protect = result.virtual_query.prot;
2260 info->AllocationProtect = result.virtual_query.alloc_prot;
2261 info->State = (DWORD)result.virtual_query.state << 12;
2262 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2263 if (info->RegionSize != result.virtual_query.size) /* truncated */
2264 return STATUS_INVALID_PARAMETER; /* FIXME */
2265 if (res_len) *res_len = sizeof(*info);
2267 return result.virtual_query.status;
2270 base = ROUND_ADDR( addr, page_mask );
2272 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2274 /* Find the view containing the address */
2276 server_enter_uninterrupted_section( &csVirtual, &sigset );
2277 ptr = list_head( &views_list );
2278 for (;;)
2280 if (!ptr)
2282 size = (char *)working_set_limit - alloc_base;
2283 view = NULL;
2284 break;
2286 view = LIST_ENTRY( ptr, struct file_view, entry );
2287 if ((char *)view->base > base)
2289 size = (char *)view->base - alloc_base;
2290 view = NULL;
2291 break;
2293 if ((char *)view->base + view->size > base)
2295 alloc_base = view->base;
2296 size = view->size;
2297 break;
2299 alloc_base = (char *)view->base + view->size;
2300 ptr = list_next( &views_list, ptr );
2303 /* Fill the info structure */
2305 info->AllocationBase = alloc_base;
2306 info->BaseAddress = base;
2307 info->RegionSize = size - (base - alloc_base);
2309 if (!view)
2311 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2313 /* not in a reserved area at all, pretend it's allocated */
2314 #ifdef __i386__
2315 if (base >= (char *)address_space_start)
2317 info->State = MEM_RESERVE;
2318 info->Protect = PAGE_NOACCESS;
2319 info->AllocationProtect = PAGE_NOACCESS;
2320 info->Type = MEM_PRIVATE;
2322 else
2323 #endif
2325 info->State = MEM_FREE;
2326 info->Protect = PAGE_NOACCESS;
2327 info->AllocationBase = 0;
2328 info->AllocationProtect = 0;
2329 info->Type = 0;
2333 else
2335 BYTE vprot;
2336 SIZE_T range_size = get_committed_size( view, base, &vprot );
2338 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2339 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2340 info->AllocationBase = alloc_base;
2341 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2342 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2343 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2344 else info->Type = MEM_MAPPED;
2345 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2346 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2347 info->RegionSize = size - (base - alloc_base);
2349 server_leave_uninterrupted_section( &csVirtual, &sigset );
2351 if (res_len) *res_len = sizeof(*info);
2352 return STATUS_SUCCESS;
2356 /***********************************************************************
2357 * NtLockVirtualMemory (NTDLL.@)
2358 * ZwLockVirtualMemory (NTDLL.@)
2360 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2362 NTSTATUS status = STATUS_SUCCESS;
2364 if (process != NtCurrentProcess())
2366 apc_call_t call;
2367 apc_result_t result;
2369 memset( &call, 0, sizeof(call) );
2371 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2372 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2373 call.virtual_lock.size = *size;
2374 status = NTDLL_queue_process_apc( process, &call, &result );
2375 if (status != STATUS_SUCCESS) return status;
2377 if (result.virtual_lock.status == STATUS_SUCCESS)
2379 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2380 *size = result.virtual_lock.size;
2382 return result.virtual_lock.status;
2385 *size = ROUND_SIZE( *addr, *size );
2386 *addr = ROUND_ADDR( *addr, page_mask );
2388 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2389 return status;
2393 /***********************************************************************
2394 * NtUnlockVirtualMemory (NTDLL.@)
2395 * ZwUnlockVirtualMemory (NTDLL.@)
2397 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2399 NTSTATUS status = STATUS_SUCCESS;
2401 if (process != NtCurrentProcess())
2403 apc_call_t call;
2404 apc_result_t result;
2406 memset( &call, 0, sizeof(call) );
2408 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2409 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2410 call.virtual_unlock.size = *size;
2411 status = NTDLL_queue_process_apc( process, &call, &result );
2412 if (status != STATUS_SUCCESS) return status;
2414 if (result.virtual_unlock.status == STATUS_SUCCESS)
2416 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2417 *size = result.virtual_unlock.size;
2419 return result.virtual_unlock.status;
2422 *size = ROUND_SIZE( *addr, *size );
2423 *addr = ROUND_ADDR( *addr, page_mask );
2425 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2426 return status;
2430 /***********************************************************************
2431 * NtCreateSection (NTDLL.@)
2432 * ZwCreateSection (NTDLL.@)
2434 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2435 const LARGE_INTEGER *size, ULONG protect,
2436 ULONG sec_flags, HANDLE file )
2438 NTSTATUS ret;
2439 unsigned int vprot;
2440 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2441 struct security_descriptor *sd = NULL;
2442 struct object_attributes objattr;
2444 /* Check parameters */
2446 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2448 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2450 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2451 objattr.sd_len = 0;
2452 objattr.name_len = len;
2453 if (attr)
2455 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2456 if (ret != STATUS_SUCCESS) return ret;
2459 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2460 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2461 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2463 /* Create the server object */
2465 SERVER_START_REQ( create_mapping )
2467 req->access = access;
2468 req->attributes = (attr) ? attr->Attributes : 0;
2469 req->file_handle = wine_server_obj_handle( file );
2470 req->size = size ? size->QuadPart : 0;
2471 req->protect = vprot;
2472 wine_server_add_data( req, &objattr, sizeof(objattr) );
2473 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2474 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2475 ret = wine_server_call( req );
2476 *handle = wine_server_ptr_handle( reply->handle );
2478 SERVER_END_REQ;
2480 NTDLL_free_struct_sd( sd );
2482 return ret;
2486 /***********************************************************************
2487 * NtOpenSection (NTDLL.@)
2488 * ZwOpenSection (NTDLL.@)
2490 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2492 NTSTATUS ret;
2493 DWORD len = attr->ObjectName->Length;
2495 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2497 SERVER_START_REQ( open_mapping )
2499 req->access = access;
2500 req->attributes = attr->Attributes;
2501 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2502 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2503 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2505 SERVER_END_REQ;
2506 return ret;
2510 /***********************************************************************
2511 * NtMapViewOfSection (NTDLL.@)
2512 * ZwMapViewOfSection (NTDLL.@)
2514 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2515 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2516 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2518 NTSTATUS res;
2519 mem_size_t full_size;
2520 ACCESS_MASK access;
2521 SIZE_T size, mask = get_mask( zero_bits );
2522 int unix_handle = -1, needs_close;
2523 unsigned int map_vprot, vprot;
2524 void *base;
2525 struct file_view *view;
2526 DWORD header_size;
2527 HANDLE dup_mapping, shared_file;
2528 LARGE_INTEGER offset;
2529 sigset_t sigset;
2531 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2533 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2534 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2536 /* Check parameters */
2538 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2539 return STATUS_INVALID_PARAMETER;
2541 switch(protect)
2543 case PAGE_NOACCESS:
2544 access = SECTION_MAP_READ;
2545 break;
2546 case PAGE_READWRITE:
2547 case PAGE_EXECUTE_READWRITE:
2548 access = SECTION_MAP_WRITE;
2549 break;
2550 case PAGE_READONLY:
2551 case PAGE_WRITECOPY:
2552 case PAGE_EXECUTE:
2553 case PAGE_EXECUTE_READ:
2554 case PAGE_EXECUTE_WRITECOPY:
2555 access = SECTION_MAP_READ;
2556 break;
2557 default:
2558 return STATUS_INVALID_PAGE_PROTECTION;
2561 if (process != NtCurrentProcess())
2563 apc_call_t call;
2564 apc_result_t result;
2566 memset( &call, 0, sizeof(call) );
2568 call.map_view.type = APC_MAP_VIEW;
2569 call.map_view.handle = wine_server_obj_handle( handle );
2570 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2571 call.map_view.size = *size_ptr;
2572 call.map_view.offset = offset.QuadPart;
2573 call.map_view.zero_bits = zero_bits;
2574 call.map_view.alloc_type = alloc_type;
2575 call.map_view.prot = protect;
2576 res = NTDLL_queue_process_apc( process, &call, &result );
2577 if (res != STATUS_SUCCESS) return res;
2579 if ((NTSTATUS)result.map_view.status >= 0)
2581 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2582 *size_ptr = result.map_view.size;
2584 return result.map_view.status;
2587 SERVER_START_REQ( get_mapping_info )
2589 req->handle = wine_server_obj_handle( handle );
2590 req->access = access;
2591 res = wine_server_call( req );
2592 map_vprot = reply->protect;
2593 base = wine_server_get_ptr( reply->base );
2594 full_size = reply->size;
2595 header_size = reply->header_size;
2596 dup_mapping = wine_server_ptr_handle( reply->mapping );
2597 shared_file = wine_server_ptr_handle( reply->shared_file );
2598 if ((ULONG_PTR)base != reply->base) base = NULL;
2600 SERVER_END_REQ;
2601 if (res) return res;
2603 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2605 if (map_vprot & VPROT_IMAGE)
2607 size = full_size;
2608 if (size != full_size) /* truncated */
2610 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2611 res = STATUS_INVALID_PARAMETER;
2612 goto done;
2614 if (shared_file)
2616 int shared_fd, shared_needs_close;
2618 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2619 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2620 res = map_image( handle, unix_handle, base, size, mask, header_size,
2621 shared_fd, dup_mapping, map_vprot, addr_ptr );
2622 if (shared_needs_close) close( shared_fd );
2623 NtClose( shared_file );
2625 else
2627 res = map_image( handle, unix_handle, base, size, mask, header_size,
2628 -1, dup_mapping, map_vprot, addr_ptr );
2630 if (needs_close) close( unix_handle );
2631 if (res >= 0) *size_ptr = size;
2632 return res;
2635 res = STATUS_INVALID_PARAMETER;
2636 if (offset.QuadPart >= full_size) goto done;
2637 if (*size_ptr)
2639 if (*size_ptr > full_size - offset.QuadPart) goto done;
2640 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2641 if (size < *size_ptr) goto done; /* wrap-around */
2643 else
2645 size = full_size - offset.QuadPart;
2646 if (size != full_size - offset.QuadPart) /* truncated */
2648 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2649 wine_dbgstr_longlong(full_size) );
2650 goto done;
2654 /* Reserve a properly aligned area */
2656 server_enter_uninterrupted_section( &csVirtual, &sigset );
2658 get_vprot_flags( protect, &vprot, map_vprot & VPROT_IMAGE );
2659 vprot |= (map_vprot & VPROT_COMMITTED);
2660 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2661 if (res)
2663 server_leave_uninterrupted_section( &csVirtual, &sigset );
2664 goto done;
2667 /* Map the file */
2669 TRACE("handle=%p size=%lx offset=%x%08x\n",
2670 handle, size, offset.u.HighPart, offset.u.LowPart );
2672 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2673 if (res == STATUS_SUCCESS)
2675 *addr_ptr = view->base;
2676 *size_ptr = size;
2677 view->mapping = dup_mapping;
2678 view->map_protect = map_vprot;
2679 dup_mapping = 0; /* don't close it */
2681 else
2683 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2684 view->base, size, offset.u.HighPart, offset.u.LowPart );
2685 delete_view( view );
2688 server_leave_uninterrupted_section( &csVirtual, &sigset );
2690 done:
2691 if (dup_mapping) NtClose( dup_mapping );
2692 if (needs_close) close( unix_handle );
2693 return res;
2697 /***********************************************************************
2698 * NtUnmapViewOfSection (NTDLL.@)
2699 * ZwUnmapViewOfSection (NTDLL.@)
2701 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2703 struct file_view *view;
2704 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2705 sigset_t sigset;
2706 void *base = ROUND_ADDR( addr, page_mask );
2708 if (process != NtCurrentProcess())
2710 apc_call_t call;
2711 apc_result_t result;
2713 memset( &call, 0, sizeof(call) );
2715 call.unmap_view.type = APC_UNMAP_VIEW;
2716 call.unmap_view.addr = wine_server_client_ptr( addr );
2717 status = NTDLL_queue_process_apc( process, &call, &result );
2718 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2719 return status;
2722 server_enter_uninterrupted_section( &csVirtual, &sigset );
2723 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2725 delete_view( view );
2726 status = STATUS_SUCCESS;
2728 server_leave_uninterrupted_section( &csVirtual, &sigset );
2729 return status;
2733 /***********************************************************************
2734 * NtFlushVirtualMemory (NTDLL.@)
2735 * ZwFlushVirtualMemory (NTDLL.@)
2737 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2738 SIZE_T *size_ptr, ULONG unknown )
2740 struct file_view *view;
2741 NTSTATUS status = STATUS_SUCCESS;
2742 sigset_t sigset;
2743 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2745 if (process != NtCurrentProcess())
2747 apc_call_t call;
2748 apc_result_t result;
2750 memset( &call, 0, sizeof(call) );
2752 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2753 call.virtual_flush.addr = wine_server_client_ptr( addr );
2754 call.virtual_flush.size = *size_ptr;
2755 status = NTDLL_queue_process_apc( process, &call, &result );
2756 if (status != STATUS_SUCCESS) return status;
2758 if (result.virtual_flush.status == STATUS_SUCCESS)
2760 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2761 *size_ptr = result.virtual_flush.size;
2763 return result.virtual_flush.status;
2766 server_enter_uninterrupted_section( &csVirtual, &sigset );
2767 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2768 else
2770 if (!*size_ptr) *size_ptr = view->size;
2771 *addr_ptr = addr;
2772 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2774 server_leave_uninterrupted_section( &csVirtual, &sigset );
2775 return status;
2779 /***********************************************************************
2780 * NtGetWriteWatch (NTDLL.@)
2781 * ZwGetWriteWatch (NTDLL.@)
2783 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2784 ULONG_PTR *count, ULONG *granularity )
2786 struct file_view *view;
2787 NTSTATUS status = STATUS_SUCCESS;
2788 sigset_t sigset;
2790 size = ROUND_SIZE( base, size );
2791 base = ROUND_ADDR( base, page_mask );
2793 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2794 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2795 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2797 if (!addresses) return STATUS_ACCESS_VIOLATION;
2799 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2800 addresses, *count );
2802 server_enter_uninterrupted_section( &csVirtual, &sigset );
2804 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2806 ULONG_PTR pos = 0;
2807 char *addr = base;
2808 char *end = addr + size;
2810 while (pos < *count && addr < end)
2812 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2813 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2814 addr += page_size;
2816 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2817 *count = pos;
2818 *granularity = page_size;
2820 else status = STATUS_INVALID_PARAMETER;
2822 server_leave_uninterrupted_section( &csVirtual, &sigset );
2823 return status;
2827 /***********************************************************************
2828 * NtResetWriteWatch (NTDLL.@)
2829 * ZwResetWriteWatch (NTDLL.@)
2831 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2833 struct file_view *view;
2834 NTSTATUS status = STATUS_SUCCESS;
2835 sigset_t sigset;
2837 size = ROUND_SIZE( base, size );
2838 base = ROUND_ADDR( base, page_mask );
2840 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2842 if (!size) return STATUS_INVALID_PARAMETER;
2844 server_enter_uninterrupted_section( &csVirtual, &sigset );
2846 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2847 reset_write_watches( view, base, size );
2848 else
2849 status = STATUS_INVALID_PARAMETER;
2851 server_leave_uninterrupted_section( &csVirtual, &sigset );
2852 return status;
2856 /***********************************************************************
2857 * NtReadVirtualMemory (NTDLL.@)
2858 * ZwReadVirtualMemory (NTDLL.@)
2860 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2861 SIZE_T size, SIZE_T *bytes_read )
2863 NTSTATUS status;
2865 if (virtual_check_buffer_for_write( buffer, size ))
2867 SERVER_START_REQ( read_process_memory )
2869 req->handle = wine_server_obj_handle( process );
2870 req->addr = wine_server_client_ptr( addr );
2871 wine_server_set_reply( req, buffer, size );
2872 if ((status = wine_server_call( req ))) size = 0;
2874 SERVER_END_REQ;
2876 else
2878 status = STATUS_ACCESS_VIOLATION;
2879 size = 0;
2881 if (bytes_read) *bytes_read = size;
2882 return status;
2886 /***********************************************************************
2887 * NtWriteVirtualMemory (NTDLL.@)
2888 * ZwWriteVirtualMemory (NTDLL.@)
2890 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2891 SIZE_T size, SIZE_T *bytes_written )
2893 NTSTATUS status;
2895 if (virtual_check_buffer_for_read( buffer, size ))
2897 SERVER_START_REQ( write_process_memory )
2899 req->handle = wine_server_obj_handle( process );
2900 req->addr = wine_server_client_ptr( addr );
2901 wine_server_add_data( req, buffer, size );
2902 if ((status = wine_server_call( req ))) size = 0;
2904 SERVER_END_REQ;
2906 else
2908 status = STATUS_PARTIAL_COPY;
2909 size = 0;
2911 if (bytes_written) *bytes_written = size;
2912 return status;
2916 /***********************************************************************
2917 * NtAreMappedFilesTheSame (NTDLL.@)
2918 * ZwAreMappedFilesTheSame (NTDLL.@)
2920 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2922 struct file_view *view1, *view2;
2923 struct stat st1, st2;
2924 NTSTATUS status;
2925 sigset_t sigset;
2927 TRACE("%p %p\n", addr1, addr2);
2929 server_enter_uninterrupted_section( &csVirtual, &sigset );
2931 view1 = VIRTUAL_FindView( addr1, 0 );
2932 view2 = VIRTUAL_FindView( addr2, 0 );
2934 if (!view1 || !view2)
2935 status = STATUS_INVALID_ADDRESS;
2936 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2937 status = STATUS_CONFLICTING_ADDRESSES;
2938 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2939 status = STATUS_NOT_SAME_DEVICE;
2940 else if (view1 == view2)
2941 status = STATUS_SUCCESS;
2942 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2943 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2944 status = STATUS_SUCCESS;
2945 else
2946 status = STATUS_NOT_SAME_DEVICE;
2948 server_leave_uninterrupted_section( &csVirtual, &sigset );
2949 return status;