cmd: Move externals list at the same place as the builtins one so it's easier to...
[wine/multimedia.git] / dlls / ntdll / virtual.c
blob10fba17199267501a6b57499e3807a20be684409
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <errno.h>
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
28 #endif
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winternl.h"
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/list.h"
58 #include "wine/debug.h"
59 #include "ntdll_misc.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
62 WINE_DECLARE_DEBUG_CHANNEL(module);
64 #ifndef MS_SYNC
65 #define MS_SYNC 0
66 #endif
68 #ifndef MAP_NORESERVE
69 #define MAP_NORESERVE 0
70 #endif
72 /* File view */
73 struct file_view
75 struct list entry; /* Entry in global view list */
76 void *base; /* Base address */
77 size_t size; /* Size in bytes */
78 HANDLE mapping; /* Handle to the file mapping */
79 unsigned int protect; /* Protection for all pages at allocation time */
80 BYTE prot[1]; /* Protection byte for each page */
84 /* Conversion from VPROT_* to Win32 flags */
85 static const BYTE VIRTUAL_Win32Flags[16] =
87 PAGE_NOACCESS, /* 0 */
88 PAGE_READONLY, /* READ */
89 PAGE_READWRITE, /* WRITE */
90 PAGE_READWRITE, /* READ | WRITE */
91 PAGE_EXECUTE, /* EXEC */
92 PAGE_EXECUTE_READ, /* READ | EXEC */
93 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
94 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
95 PAGE_WRITECOPY, /* WRITECOPY */
96 PAGE_WRITECOPY, /* READ | WRITECOPY */
97 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
98 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
102 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
105 static struct list views_list = LIST_INIT(views_list);
107 static RTL_CRITICAL_SECTION csVirtual;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 0, 0, &csVirtual,
111 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
114 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
116 #ifdef __i386__
117 /* These are always the same on an i386, and it will be faster this way */
118 # define page_mask 0xfff
119 # define page_shift 12
120 # define page_size 0x1000
121 /* Note: these are Windows limits, you cannot change them. */
122 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
123 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
124 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
125 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
126 #elif defined(__x86_64__)
127 # define page_mask 0xfff
128 # define page_shift 12
129 # define page_size 0x1000
130 static void *address_space_limit = (void *)0x7fffffff0000;
131 static void *user_space_limit = (void *)0x7fffffff0000;
132 static void *working_set_limit = (void *)0x7fffffff0000;
133 static void *address_space_start = (void *)0x10000;
134 #else
135 static UINT page_shift;
136 static UINT_PTR page_size;
137 static UINT_PTR page_mask;
138 static void *address_space_limit;
139 static void *user_space_limit;
140 static void *working_set_limit;
141 static void *address_space_start = (void *)0x10000;
142 #endif /* __i386__ */
143 static const int is_win64 = (sizeof(void *) > sizeof(int));
145 #define ROUND_ADDR(addr,mask) \
146 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
148 #define ROUND_SIZE(addr,size) \
149 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
151 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
152 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
154 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
156 static HANDLE virtual_heap;
157 static void *preload_reserve_start;
158 static void *preload_reserve_end;
159 static int use_locks;
160 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
163 /***********************************************************************
164 * VIRTUAL_GetProtStr
166 static const char *VIRTUAL_GetProtStr( BYTE prot )
168 static char buffer[6];
169 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
170 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
171 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
172 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
173 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
174 buffer[5] = 0;
175 return buffer;
179 /***********************************************************************
180 * VIRTUAL_GetUnixProt
182 * Convert page protections to protection for mmap/mprotect.
184 static int VIRTUAL_GetUnixProt( BYTE vprot )
186 int prot = 0;
187 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
189 if (vprot & VPROT_READ) prot |= PROT_READ;
190 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
191 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
192 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
193 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
195 if (!prot) prot = PROT_NONE;
196 return prot;
200 /***********************************************************************
201 * VIRTUAL_DumpView
203 static void VIRTUAL_DumpView( struct file_view *view )
205 UINT i, count;
206 char *addr = view->base;
207 BYTE prot = view->prot[0];
209 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
210 if (view->protect & VPROT_SYSTEM)
211 TRACE( " (system)\n" );
212 else if (view->protect & VPROT_VALLOC)
213 TRACE( " (valloc)\n" );
214 else if (view->mapping)
215 TRACE( " %p\n", view->mapping );
216 else
217 TRACE( " (anonymous)\n");
219 for (count = i = 1; i < view->size >> page_shift; i++, count++)
221 if (view->prot[i] == prot) continue;
222 TRACE( " %p - %p %s\n",
223 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
224 addr += (count << page_shift);
225 prot = view->prot[i];
226 count = 0;
228 if (count)
229 TRACE( " %p - %p %s\n",
230 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
234 /***********************************************************************
235 * VIRTUAL_Dump
237 #ifdef WINE_VM_DEBUG
238 static void VIRTUAL_Dump(void)
240 sigset_t sigset;
241 struct file_view *view;
243 TRACE( "Dump of all virtual memory views:\n" );
244 server_enter_uninterrupted_section( &csVirtual, &sigset );
245 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
247 VIRTUAL_DumpView( view );
249 server_leave_uninterrupted_section( &csVirtual, &sigset );
251 #endif
254 /***********************************************************************
255 * VIRTUAL_FindView
257 * Find the view containing a given address. The csVirtual section must be held by caller.
259 * PARAMS
260 * addr [I] Address
262 * RETURNS
263 * View: Success
264 * NULL: Failure
266 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
268 struct file_view *view;
270 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
272 if (view->base > addr) break; /* no matching view */
273 if ((const char *)view->base + view->size <= (const char *)addr) continue;
274 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
275 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
276 return view;
278 return NULL;
282 /***********************************************************************
283 * get_mask
285 static inline UINT_PTR get_mask( ULONG zero_bits )
287 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
288 if (zero_bits < page_shift) zero_bits = page_shift;
289 return (1 << zero_bits) - 1;
293 /***********************************************************************
294 * find_view_range
296 * Find the first view overlapping at least part of the specified range.
297 * The csVirtual section must be held by caller.
299 static struct file_view *find_view_range( const void *addr, size_t size )
301 struct file_view *view;
303 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
305 if ((const char *)view->base >= (const char *)addr + size) break;
306 if ((const char *)view->base + view->size > (const char *)addr) return view;
308 return NULL;
312 /***********************************************************************
313 * find_free_area
315 * Find a free area between views inside the specified range.
316 * The csVirtual section must be held by caller.
318 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
320 struct list *ptr;
321 void *start;
323 if (top_down)
325 start = ROUND_ADDR( (char *)end - size, mask );
326 if (start >= end || start < base) return NULL;
328 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
330 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
332 if ((char *)view->base + view->size <= (char *)start) break;
333 if ((char *)view->base >= (char *)start + size) continue;
334 start = ROUND_ADDR( (char *)view->base - size, mask );
335 /* stop if remaining space is not large enough */
336 if (!start || start >= end || start < base) return NULL;
339 else
341 start = ROUND_ADDR( (char *)base + mask, mask );
342 if (start >= end || (char *)end - (char *)start < size) return NULL;
344 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
346 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
348 if ((char *)view->base >= (char *)start + size) break;
349 if ((char *)view->base + view->size <= (char *)start) continue;
350 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
351 /* stop if remaining space is not large enough */
352 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
355 return start;
359 /***********************************************************************
360 * add_reserved_area
362 * Add a reserved area to the list maintained by libwine.
363 * The csVirtual section must be held by caller.
365 static void add_reserved_area( void *addr, size_t size )
367 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
369 if (addr < user_space_limit)
371 /* unmap the part of the area that is below the limit */
372 assert( (char *)addr + size > (char *)user_space_limit );
373 munmap( addr, (char *)user_space_limit - (char *)addr );
374 size -= (char *)user_space_limit - (char *)addr;
375 addr = user_space_limit;
377 /* blow away existing mappings */
378 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
379 wine_mmap_add_reserved_area( addr, size );
383 /***********************************************************************
384 * remove_reserved_area
386 * Remove a reserved area from the list maintained by libwine.
387 * The csVirtual section must be held by caller.
389 static void remove_reserved_area( void *addr, size_t size )
391 struct file_view *view;
393 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
394 wine_mmap_remove_reserved_area( addr, size, 0 );
396 /* unmap areas not covered by an existing view */
397 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
399 if ((char *)view->base >= (char *)addr + size)
401 munmap( addr, size );
402 break;
404 if ((char *)view->base + view->size <= (char *)addr) continue;
405 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
406 if ((char *)view->base + view->size > (char *)addr + size) break;
407 size = (char *)addr + size - ((char *)view->base + view->size);
408 addr = (char *)view->base + view->size;
413 /***********************************************************************
414 * is_beyond_limit
416 * Check if an address range goes beyond a given limit.
418 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
420 return (addr >= limit || (const char *)addr + size > (const char *)limit);
424 /***********************************************************************
425 * unmap_area
427 * Unmap an area, or simply replace it by an empty mapping if it is
428 * in a reserved area. The csVirtual section must be held by caller.
430 static inline void unmap_area( void *addr, size_t size )
432 if (wine_mmap_is_in_reserved_area( addr, size ))
433 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
434 else if (is_beyond_limit( addr, size, user_space_limit ))
435 add_reserved_area( addr, size );
436 else
437 munmap( addr, size );
441 /***********************************************************************
442 * delete_view
444 * Deletes a view. The csVirtual section must be held by caller.
446 static void delete_view( struct file_view *view ) /* [in] View */
448 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
449 list_remove( &view->entry );
450 if (view->mapping) close_handle( view->mapping );
451 RtlFreeHeap( virtual_heap, 0, view );
455 /***********************************************************************
456 * create_view
458 * Create a view. The csVirtual section must be held by caller.
460 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
462 struct file_view *view;
463 struct list *ptr;
464 int unix_prot = VIRTUAL_GetUnixProt( vprot );
466 assert( !((UINT_PTR)base & page_mask) );
467 assert( !(size & page_mask) );
469 /* Create the view structure */
471 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
473 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
474 return STATUS_NO_MEMORY;
477 view->base = base;
478 view->size = size;
479 view->mapping = 0;
480 view->protect = vprot;
481 memset( view->prot, vprot, size >> page_shift );
483 /* Insert it in the linked list */
485 LIST_FOR_EACH( ptr, &views_list )
487 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
488 if (next->base > base) break;
490 list_add_before( ptr, &view->entry );
492 /* Check for overlapping views. This can happen if the previous view
493 * was a system view that got unmapped behind our back. In that case
494 * we recover by simply deleting it. */
496 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
498 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
499 if ((char *)prev->base + prev->size > (char *)base)
501 TRACE( "overlapping prev view %p-%p for %p-%p\n",
502 prev->base, (char *)prev->base + prev->size,
503 base, (char *)base + view->size );
504 assert( prev->protect & VPROT_SYSTEM );
505 delete_view( prev );
508 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
510 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
511 if ((char *)base + view->size > (char *)next->base)
513 TRACE( "overlapping next view %p-%p for %p-%p\n",
514 next->base, (char *)next->base + next->size,
515 base, (char *)base + view->size );
516 assert( next->protect & VPROT_SYSTEM );
517 delete_view( next );
521 *view_ret = view;
522 VIRTUAL_DEBUG_DUMP_VIEW( view );
524 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
526 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
527 mprotect( base, size, unix_prot | PROT_EXEC );
529 return STATUS_SUCCESS;
533 /***********************************************************************
534 * VIRTUAL_GetWin32Prot
536 * Convert page protections to Win32 flags.
538 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
540 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
541 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
542 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
543 return ret;
547 /***********************************************************************
548 * get_vprot_flags
550 * Build page protections from Win32 flags.
552 * PARAMS
553 * protect [I] Win32 protection flags
555 * RETURNS
556 * Value of page protection flags
558 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot )
560 switch(protect & 0xff)
562 case PAGE_READONLY:
563 *vprot = VPROT_READ;
564 break;
565 case PAGE_READWRITE:
566 *vprot = VPROT_READ | VPROT_WRITE;
567 break;
568 case PAGE_WRITECOPY:
569 *vprot = VPROT_READ | VPROT_WRITECOPY;
570 break;
571 case PAGE_EXECUTE:
572 *vprot = VPROT_EXEC;
573 break;
574 case PAGE_EXECUTE_READ:
575 *vprot = VPROT_EXEC | VPROT_READ;
576 break;
577 case PAGE_EXECUTE_READWRITE:
578 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
579 break;
580 case PAGE_EXECUTE_WRITECOPY:
581 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
582 break;
583 case PAGE_NOACCESS:
584 *vprot = 0;
585 break;
586 default:
587 return STATUS_INVALID_PARAMETER;
589 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
590 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
591 return STATUS_SUCCESS;
595 /***********************************************************************
596 * VIRTUAL_SetProt
598 * Change the protection of a range of pages.
600 * RETURNS
601 * TRUE: Success
602 * FALSE: Failure
604 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
605 void *base, /* [in] Starting address */
606 size_t size, /* [in] Size in bytes */
607 BYTE vprot ) /* [in] Protections to use */
609 int unix_prot = VIRTUAL_GetUnixProt(vprot);
610 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
612 TRACE("%p-%p %s\n",
613 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
615 if (view->protect & VPROT_WRITEWATCH)
617 /* each page may need different protections depending on write watch flag */
618 UINT i, count;
619 char *addr = base;
620 int prot;
622 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
623 unix_prot = VIRTUAL_GetUnixProt( p[0] );
624 for (count = i = 1; i < size >> page_shift; i++, count++)
626 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
627 prot = VIRTUAL_GetUnixProt( p[i] );
628 if (prot == unix_prot) continue;
629 mprotect( addr, count << page_shift, unix_prot );
630 addr += count << page_shift;
631 unix_prot = prot;
632 count = 0;
634 if (count) mprotect( addr, count << page_shift, unix_prot );
635 VIRTUAL_DEBUG_DUMP_VIEW( view );
636 return TRUE;
639 /* if setting stack guard pages, store the permissions first, as the guard may be
640 * triggered at any point after mprotect and change the permissions again */
641 if ((vprot & VPROT_GUARD) &&
642 (base >= NtCurrentTeb()->DeallocationStack) &&
643 (base < NtCurrentTeb()->Tib.StackBase))
645 memset( p, vprot, size >> page_shift );
646 mprotect( base, size, unix_prot );
647 VIRTUAL_DEBUG_DUMP_VIEW( view );
648 return TRUE;
651 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
652 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
654 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
655 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
656 /* exec + write may legitimately fail, in that case fall back to write only */
657 if (!(unix_prot & PROT_WRITE)) return FALSE;
660 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
662 done:
663 memset( p, vprot, size >> page_shift );
664 VIRTUAL_DEBUG_DUMP_VIEW( view );
665 return TRUE;
669 /***********************************************************************
670 * reset_write_watches
672 * Reset write watches in a memory range.
674 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
676 SIZE_T i, count;
677 int prot, unix_prot;
678 char *addr = base;
679 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
681 p[0] |= VPROT_WRITEWATCH;
682 unix_prot = VIRTUAL_GetUnixProt( p[0] );
683 for (count = i = 1; i < size >> page_shift; i++, count++)
685 p[i] |= VPROT_WRITEWATCH;
686 prot = VIRTUAL_GetUnixProt( p[i] );
687 if (prot == unix_prot) continue;
688 mprotect( addr, count << page_shift, unix_prot );
689 addr += count << page_shift;
690 unix_prot = prot;
691 count = 0;
693 if (count) mprotect( addr, count << page_shift, unix_prot );
697 /***********************************************************************
698 * unmap_extra_space
700 * Release the extra memory while keeping the range starting on the granularity boundary.
702 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
704 if ((ULONG_PTR)ptr & mask)
706 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
707 munmap( ptr, extra );
708 ptr = (char *)ptr + extra;
709 total_size -= extra;
711 if (total_size > wanted_size)
712 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
713 return ptr;
717 struct alloc_area
719 size_t size;
720 size_t mask;
721 int top_down;
722 void *limit;
723 void *result;
726 /***********************************************************************
727 * alloc_reserved_area_callback
729 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
731 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
733 struct alloc_area *alloc = arg;
734 void *end = (char *)start + size;
736 if (start < address_space_start) start = address_space_start;
737 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
738 if (start >= end) return 0;
740 /* make sure we don't touch the preloader reserved range */
741 if (preload_reserve_end >= start)
743 if (preload_reserve_end >= end)
745 if (preload_reserve_start <= start) return 0; /* no space in that area */
746 if (preload_reserve_start < end) end = preload_reserve_start;
748 else if (preload_reserve_start <= start) start = preload_reserve_end;
749 else
751 /* range is split in two by the preloader reservation, try first part */
752 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
753 alloc->mask, alloc->top_down )))
754 return 1;
755 /* then fall through to try second part */
756 start = preload_reserve_end;
759 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
760 return 1;
762 return 0;
766 /***********************************************************************
767 * map_view
769 * Create a view and mmap the corresponding memory area.
770 * The csVirtual section must be held by caller.
772 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
773 int top_down, unsigned int vprot )
775 void *ptr;
776 NTSTATUS status;
778 if (base)
780 if (is_beyond_limit( base, size, address_space_limit ))
781 return STATUS_WORKING_SET_LIMIT_RANGE;
783 switch (wine_mmap_is_in_reserved_area( base, size ))
785 case -1: /* partially in a reserved area */
786 return STATUS_CONFLICTING_ADDRESSES;
788 case 0: /* not in a reserved area, do a normal allocation */
789 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
791 if (errno == ENOMEM) return STATUS_NO_MEMORY;
792 return STATUS_INVALID_PARAMETER;
794 if (ptr != base)
796 /* We couldn't get the address we wanted */
797 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
798 else munmap( ptr, size );
799 return STATUS_CONFLICTING_ADDRESSES;
801 break;
803 default:
804 case 1: /* in a reserved area, make sure the address is available */
805 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
806 /* replace the reserved area by our mapping */
807 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
808 return STATUS_INVALID_PARAMETER;
809 break;
811 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
813 else
815 size_t view_size = size + mask + 1;
816 struct alloc_area alloc;
818 alloc.size = size;
819 alloc.mask = mask;
820 alloc.top_down = top_down;
821 alloc.limit = user_space_limit;
822 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
824 ptr = alloc.result;
825 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
826 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
827 return STATUS_INVALID_PARAMETER;
828 goto done;
831 for (;;)
833 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
835 if (errno == ENOMEM) return STATUS_NO_MEMORY;
836 return STATUS_INVALID_PARAMETER;
838 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
839 /* if we got something beyond the user limit, unmap it and retry */
840 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
841 else break;
843 ptr = unmap_extra_space( ptr, view_size, size, mask );
845 done:
846 status = create_view( view_ret, ptr, size, vprot );
847 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
848 return status;
852 /***********************************************************************
853 * map_file_into_view
855 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
856 * The csVirtual section must be held by caller.
858 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
859 off_t offset, unsigned int vprot, BOOL removable )
861 void *ptr;
862 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
863 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
865 assert( start < view->size );
866 assert( start + size <= view->size );
868 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
870 TRACE( "forcing exec permission on mapping %p-%p\n",
871 (char *)view->base + start, (char *)view->base + start + size - 1 );
872 prot |= PROT_EXEC;
875 /* only try mmap if media is not removable (or if we require write access) */
876 if (!removable || shared_write)
878 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
880 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
881 goto done;
883 if ((errno == EPERM) && (prot & PROT_EXEC))
884 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
886 /* mmap() failed; if this is because the file offset is not */
887 /* page-aligned (EINVAL), or because the underlying filesystem */
888 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
889 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
890 if (shared_write) /* we cannot fake shared write mappings */
892 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
893 ERR( "shared writable mmap not supported, broken filesystem?\n" );
894 return STATUS_NOT_SUPPORTED;
898 /* Reserve the memory with an anonymous mmap */
899 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
900 if (ptr == (void *)-1) return FILE_GetNtStatus();
901 /* Now read in the file */
902 pread( fd, ptr, size, offset );
903 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
904 done:
905 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
906 return STATUS_SUCCESS;
910 /***********************************************************************
911 * get_committed_size
913 * Get the size of the committed range starting at base.
914 * Also return the protections for the first page.
916 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
918 SIZE_T i, start;
920 start = ((char *)base - (char *)view->base) >> page_shift;
921 *vprot = view->prot[start];
923 if (view->mapping && !(view->protect & VPROT_COMMITTED))
925 SIZE_T ret = 0;
926 SERVER_START_REQ( get_mapping_committed_range )
928 req->handle = wine_server_obj_handle( view->mapping );
929 req->offset = start << page_shift;
930 if (!wine_server_call( req ))
932 ret = reply->size;
933 if (reply->committed)
935 *vprot |= VPROT_COMMITTED;
936 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
940 SERVER_END_REQ;
941 return ret;
943 for (i = start + 1; i < view->size >> page_shift; i++)
944 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
945 return (i - start) << page_shift;
949 /***********************************************************************
950 * decommit_view
952 * Decommit some pages of a given view.
953 * The csVirtual section must be held by caller.
955 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
957 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
959 BYTE *p = view->prot + (start >> page_shift);
960 size >>= page_shift;
961 while (size--) *p++ &= ~VPROT_COMMITTED;
962 return STATUS_SUCCESS;
964 return FILE_GetNtStatus();
968 /***********************************************************************
969 * allocate_dos_memory
971 * Allocate the DOS memory range.
973 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
975 size_t size;
976 void *addr = NULL;
977 void * const low_64k = (void *)0x10000;
978 const size_t dosmem_size = 0x110000;
979 int unix_prot = VIRTUAL_GetUnixProt( vprot );
980 struct list *ptr;
982 /* check for existing view */
984 if ((ptr = list_head( &views_list )))
986 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
987 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
990 /* check without the first 64K */
992 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
994 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
995 if (addr != low_64k)
997 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
998 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1002 /* now try to allocate the low 64K too */
1004 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1006 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1007 if (addr == (void *)page_size)
1009 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1011 addr = NULL;
1012 TRACE( "successfully mapped low 64K range\n" );
1014 else TRACE( "failed to map page 0\n" );
1016 else
1018 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1019 addr = low_64k;
1020 TRACE( "failed to map low 64K range\n" );
1024 /* now reserve the whole range */
1026 size = (char *)dosmem_size - (char *)addr;
1027 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1028 return create_view( view, addr, size, vprot );
1032 /***********************************************************************
1033 * check_architecture
1035 * Check the architecture of a PE binary.
1037 static NTSTATUS check_architecture( const IMAGE_NT_HEADERS *nt )
1039 static const char *arch;
1041 #ifdef __i386__
1042 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_I386) return STATUS_SUCCESS;
1043 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
1045 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) /* don't warn for a 64-bit exe */
1046 WARN( "loading amd64 dll in 32-bit mode will fail\n" );
1047 return STATUS_INVALID_IMAGE_FORMAT;
1049 #elif defined(__x86_64__)
1050 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) return STATUS_SUCCESS;
1051 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
1053 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) /* don't warn for a 32-bit exe */
1054 WARN( "loading 32-bit dll in 64-bit mode will fail\n" );
1055 return STATUS_INVALID_IMAGE_FORMAT;
1057 #elif defined(__arm__) && !defined(__ARMEB__)
1058 if (nt->FileHeader.Machine == IMAGE_FILE_MACHINE_ARM ||
1059 nt->FileHeader.Machine == IMAGE_FILE_MACHINE_THUMB)
1060 return STATUS_SUCCESS;
1061 #endif
1063 switch (nt->FileHeader.Machine)
1065 case IMAGE_FILE_MACHINE_UNKNOWN: arch = "Unknown"; break;
1066 case IMAGE_FILE_MACHINE_I860: arch = "I860"; break;
1067 case IMAGE_FILE_MACHINE_I386: arch = "I386"; break;
1068 case IMAGE_FILE_MACHINE_R3000: arch = "R3000"; break;
1069 case IMAGE_FILE_MACHINE_R4000: arch = "R4000"; break;
1070 case IMAGE_FILE_MACHINE_R10000: arch = "R10000"; break;
1071 case IMAGE_FILE_MACHINE_ALPHA: arch = "Alpha"; break;
1072 case IMAGE_FILE_MACHINE_POWERPC: arch = "PowerPC"; break;
1073 case IMAGE_FILE_MACHINE_IA64: arch = "IA-64"; break;
1074 case IMAGE_FILE_MACHINE_ALPHA64: arch = "Alpha-64"; break;
1075 case IMAGE_FILE_MACHINE_AMD64: arch = "AMD-64"; break;
1076 case IMAGE_FILE_MACHINE_ARM: arch = "ARM"; break;
1077 case IMAGE_FILE_MACHINE_THUMB: arch = "ARM Thumb"; break;
1078 case IMAGE_FILE_MACHINE_SPARC: arch = "SPARC"; break;
1079 default: arch = wine_dbg_sprintf( "Unknown-%04x", nt->FileHeader.Machine ); break;
1081 ERR( "Trying to load PE image for unsupported architecture %s\n", arch );
1082 return STATUS_INVALID_IMAGE_FORMAT;
1086 /***********************************************************************
1087 * stat_mapping_file
1089 * Stat the underlying file for a memory view.
1091 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1093 NTSTATUS status;
1094 int unix_fd, needs_close;
1096 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1097 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1099 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1100 if (needs_close) close( unix_fd );
1102 return status;
1106 /***********************************************************************
1107 * map_image
1109 * Map an executable (PE format) image into memory.
1111 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1112 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
1114 IMAGE_DOS_HEADER *dos;
1115 IMAGE_NT_HEADERS *nt;
1116 IMAGE_SECTION_HEADER *sec;
1117 IMAGE_DATA_DIRECTORY *imports;
1118 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1119 int i;
1120 off_t pos;
1121 sigset_t sigset;
1122 struct stat st;
1123 struct file_view *view = NULL;
1124 char *ptr, *header_end;
1125 INT_PTR delta = 0;
1127 /* zero-map the whole range */
1129 server_enter_uninterrupted_section( &csVirtual, &sigset );
1131 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1132 status = map_view( &view, base, total_size, mask, FALSE,
1133 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1135 if (status != STATUS_SUCCESS)
1136 status = map_view( &view, NULL, total_size, mask, FALSE,
1137 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1139 if (status != STATUS_SUCCESS) goto error;
1141 ptr = view->base;
1142 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1144 /* map the header */
1146 if (fstat( fd, &st ) == -1)
1148 status = FILE_GetNtStatus();
1149 goto error;
1151 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1152 if (!st.st_size) goto error;
1153 header_size = min( header_size, st.st_size );
1154 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1155 !dup_mapping ) != STATUS_SUCCESS) goto error;
1156 dos = (IMAGE_DOS_HEADER *)ptr;
1157 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1158 header_end = ptr + ROUND_SIZE( 0, header_size );
1159 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1160 if ((char *)(nt + 1) > header_end) goto error;
1161 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1162 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
1164 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1165 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1167 if (check_architecture( nt )) goto error;
1169 /* check for non page-aligned binary */
1171 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1173 /* unaligned sections, this happens for native subsystem binaries */
1174 /* in that case Windows simply maps in the whole file */
1176 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1177 !dup_mapping ) != STATUS_SUCCESS) goto error;
1179 /* check that all sections are loaded at the right offset */
1180 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1181 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1183 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1184 goto error; /* Windows refuses to load in that case too */
1187 /* set the image protections */
1188 VIRTUAL_SetProt( view, ptr, total_size,
1189 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1191 /* no relocations are performed on non page-aligned binaries */
1192 goto done;
1196 /* map all the sections */
1198 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1200 static const SIZE_T sector_align = 0x1ff;
1201 SIZE_T map_size, file_start, file_size, end;
1203 if (!sec->Misc.VirtualSize)
1204 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1205 else
1206 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1208 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1209 file_start = sec->PointerToRawData & ~sector_align;
1210 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1211 if (file_size > map_size) file_size = map_size;
1213 /* a few sanity checks */
1214 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1215 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1217 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1218 sec->Name, sec->VirtualAddress, map_size, total_size );
1219 goto error;
1222 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1223 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1225 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1226 sec->Name, ptr + sec->VirtualAddress,
1227 sec->PointerToRawData, (int)pos, file_size, map_size,
1228 sec->Characteristics );
1229 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1230 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1231 FALSE ) != STATUS_SUCCESS)
1233 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1234 goto error;
1237 /* check if the import directory falls inside this section */
1238 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1239 imports->VirtualAddress < sec->VirtualAddress + map_size)
1241 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1242 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1243 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1244 if (end > base)
1245 map_file_into_view( view, shared_fd, base, end - base,
1246 pos + (base - sec->VirtualAddress),
1247 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1248 FALSE );
1250 pos += map_size;
1251 continue;
1254 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1255 sec->Name, ptr + sec->VirtualAddress,
1256 sec->PointerToRawData, sec->SizeOfRawData,
1257 sec->Misc.VirtualSize, sec->Characteristics );
1259 if (!sec->PointerToRawData || !file_size) continue;
1261 /* Note: if the section is not aligned properly map_file_into_view will magically
1262 * fall back to read(), so we don't need to check anything here.
1264 end = file_start + file_size;
1265 if (sec->PointerToRawData >= st.st_size ||
1266 end > ((st.st_size + sector_align) & ~sector_align) ||
1267 end < file_start ||
1268 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1269 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1270 !dup_mapping ) != STATUS_SUCCESS)
1272 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1273 goto error;
1276 if (file_size & page_mask)
1278 end = ROUND_SIZE( 0, file_size );
1279 if (end > map_size) end = map_size;
1280 TRACE_(module)("clearing %p - %p\n",
1281 ptr + sec->VirtualAddress + file_size,
1282 ptr + sec->VirtualAddress + end );
1283 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1288 /* perform base relocation, if necessary */
1290 if (ptr != base &&
1291 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1292 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1294 IMAGE_BASE_RELOCATION *rel, *end;
1295 const IMAGE_DATA_DIRECTORY *relocs;
1297 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1299 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1300 base, ptr );
1301 status = STATUS_CONFLICTING_ADDRESSES;
1302 goto error;
1305 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1306 base, base + total_size, ptr, ptr + total_size );
1308 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1309 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1310 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1311 delta = ptr - base;
1313 while (rel < end - 1 && rel->SizeOfBlock)
1315 if (rel->VirtualAddress >= total_size)
1317 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1318 status = STATUS_ACCESS_VIOLATION;
1319 goto error;
1321 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1322 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1323 (USHORT *)(rel + 1), delta );
1324 if (!rel) goto error;
1328 /* set the image protections */
1330 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1332 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1333 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1335 SIZE_T size;
1336 BYTE vprot = VPROT_COMMITTED;
1338 if (sec->Misc.VirtualSize)
1339 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1340 else
1341 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1343 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1344 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1345 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE)
1347 if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
1348 vprot |= VPROT_READ | VPROT_WRITE;
1349 else
1350 vprot |= VPROT_READ | VPROT_WRITECOPY;
1353 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1354 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1355 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1356 vprot |= VPROT_EXEC;
1358 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1359 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1360 sec->Characteristics, sec->Name );
1363 done:
1364 view->mapping = dup_mapping;
1365 server_leave_uninterrupted_section( &csVirtual, &sigset );
1367 *addr_ptr = ptr;
1368 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1369 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1370 #endif
1371 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1372 return STATUS_SUCCESS;
1374 error:
1375 if (view) delete_view( view );
1376 server_leave_uninterrupted_section( &csVirtual, &sigset );
1377 if (dup_mapping) NtClose( dup_mapping );
1378 return status;
1382 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1383 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1385 void **heap_base = arg;
1387 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1388 if (size < VIRTUAL_HEAP_SIZE) return 0;
1389 if (is_win64 && base < (void *)0x80000000) return 0;
1390 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1391 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1392 return (*heap_base != (void *)-1);
1395 /***********************************************************************
1396 * virtual_init
1398 void virtual_init(void)
1400 const char *preload;
1401 void *heap_base;
1402 size_t size;
1403 struct file_view *heap_view;
1405 #ifndef page_mask
1406 page_size = getpagesize();
1407 page_mask = page_size - 1;
1408 /* Make sure we have a power of 2 */
1409 assert( !(page_size & page_mask) );
1410 page_shift = 0;
1411 while ((1 << page_shift) != page_size) page_shift++;
1412 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1413 #endif /* page_mask */
1414 if ((preload = getenv("WINEPRELOADRESERVE")))
1416 unsigned long start, end;
1417 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1419 preload_reserve_start = (void *)start;
1420 preload_reserve_end = (void *)end;
1424 /* try to find space in a reserved area for the virtual heap */
1425 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1426 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1428 assert( heap_base != (void *)-1 );
1429 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1430 VIRTUAL_HEAP_SIZE, NULL, NULL );
1431 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1433 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1434 size = (char *)address_space_start - (char *)0x10000;
1435 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1436 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1440 /***********************************************************************
1441 * virtual_init_threading
1443 void virtual_init_threading(void)
1445 use_locks = 1;
1449 /***********************************************************************
1450 * virtual_get_system_info
1452 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1454 info->unknown = 0;
1455 info->KeMaximumIncrement = 0; /* FIXME */
1456 info->PageSize = page_size;
1457 info->MmLowestPhysicalPage = 1;
1458 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1459 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1460 info->AllocationGranularity = get_mask(0) + 1;
1461 info->LowestUserAddress = (void *)0x10000;
1462 info->HighestUserAddress = (char *)user_space_limit - 1;
1463 info->ActiveProcessorsAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1464 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1468 /***********************************************************************
1469 * virtual_create_builtin_view
1471 NTSTATUS virtual_create_builtin_view( void *module )
1473 NTSTATUS status;
1474 sigset_t sigset;
1475 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1476 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1477 IMAGE_SECTION_HEADER *sec;
1478 struct file_view *view;
1479 void *base;
1480 int i;
1482 size = ROUND_SIZE( module, size );
1483 base = ROUND_ADDR( module, page_mask );
1484 server_enter_uninterrupted_section( &csVirtual, &sigset );
1485 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1486 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1487 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1488 server_leave_uninterrupted_section( &csVirtual, &sigset );
1490 if (status) return status;
1492 /* The PE header is always read-only, no write, no execute. */
1493 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1495 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1496 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1498 BYTE flags = VPROT_COMMITTED;
1500 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1501 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1502 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1503 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1504 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1507 return status;
1511 /***********************************************************************
1512 * virtual_alloc_thread_stack
1514 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1516 struct file_view *view;
1517 NTSTATUS status;
1518 sigset_t sigset;
1519 SIZE_T size;
1521 if (!reserve_size || !commit_size)
1523 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1524 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1525 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1528 size = max( reserve_size, commit_size );
1529 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1530 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1532 server_enter_uninterrupted_section( &csVirtual, &sigset );
1534 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1535 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1536 goto done;
1538 #ifdef VALGRIND_STACK_REGISTER
1539 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1540 #endif
1542 /* setup no access guard page */
1543 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1544 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1545 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1547 /* note: limit is lower than base since the stack grows down */
1548 teb->DeallocationStack = view->base;
1549 teb->Tib.StackBase = (char *)view->base + view->size;
1550 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1551 done:
1552 server_leave_uninterrupted_section( &csVirtual, &sigset );
1553 return status;
1557 /***********************************************************************
1558 * virtual_clear_thread_stack
1560 * Clear the stack contents before calling the main entry point, some broken apps need that.
1562 void virtual_clear_thread_stack(void)
1564 void *stack = NtCurrentTeb()->Tib.StackLimit;
1565 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1567 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1568 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1572 /***********************************************************************
1573 * virtual_handle_fault
1575 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err )
1577 struct file_view *view;
1578 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1579 sigset_t sigset;
1581 server_enter_uninterrupted_section( &csVirtual, &sigset );
1582 if ((view = VIRTUAL_FindView( addr, 0 )))
1584 void *page = ROUND_ADDR( addr, page_mask );
1585 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1586 if (*vprot & VPROT_GUARD)
1588 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1589 ret = STATUS_GUARD_PAGE_VIOLATION;
1591 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1593 if (*vprot & VPROT_WRITEWATCH)
1595 *vprot &= ~VPROT_WRITEWATCH;
1596 VIRTUAL_SetProt( view, page, page_size, *vprot );
1598 /* ignore fault if page is writable now */
1599 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1602 server_leave_uninterrupted_section( &csVirtual, &sigset );
1603 return ret;
1608 /***********************************************************************
1609 * virtual_handle_stack_fault
1611 * Handle an access fault inside the current thread stack.
1612 * Called from inside a signal handler.
1614 BOOL virtual_handle_stack_fault( void *addr )
1616 struct file_view *view;
1617 BOOL ret = FALSE;
1619 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1620 if ((view = VIRTUAL_FindView( addr, 0 )))
1622 void *page = ROUND_ADDR( addr, page_mask );
1623 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1624 if (vprot & VPROT_GUARD)
1626 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1627 NtCurrentTeb()->Tib.StackLimit = page;
1628 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1630 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1631 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_GUARD );
1633 ret = TRUE;
1636 RtlLeaveCriticalSection( &csVirtual );
1637 return ret;
1641 /***********************************************************************
1642 * virtual_check_buffer_for_read
1644 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1646 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1648 if (!size) return TRUE;
1649 if (!ptr) return FALSE;
1651 __TRY
1653 volatile const char *p = ptr;
1654 char dummy;
1655 SIZE_T count = size;
1657 while (count > page_size)
1659 dummy = *p;
1660 p += page_size;
1661 count -= page_size;
1663 dummy = p[0];
1664 dummy = p[count - 1];
1666 __EXCEPT_PAGE_FAULT
1668 return FALSE;
1670 __ENDTRY
1671 return TRUE;
1675 /***********************************************************************
1676 * virtual_check_buffer_for_write
1678 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1680 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1682 if (!size) return TRUE;
1683 if (!ptr) return FALSE;
1685 __TRY
1687 volatile char *p = ptr;
1688 SIZE_T count = size;
1690 while (count > page_size)
1692 *p |= 0;
1693 p += page_size;
1694 count -= page_size;
1696 p[0] |= 0;
1697 p[count - 1] |= 0;
1699 __EXCEPT_PAGE_FAULT
1701 return FALSE;
1703 __ENDTRY
1704 return TRUE;
1708 /***********************************************************************
1709 * VIRTUAL_SetForceExec
1711 * Whether to force exec prot on all views.
1713 void VIRTUAL_SetForceExec( BOOL enable )
1715 struct file_view *view;
1716 sigset_t sigset;
1718 server_enter_uninterrupted_section( &csVirtual, &sigset );
1719 if (!force_exec_prot != !enable) /* change all existing views */
1721 force_exec_prot = enable;
1723 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1725 UINT i, count;
1726 char *addr = view->base;
1727 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1728 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1730 if (view->protect & VPROT_NOEXEC) continue;
1731 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1733 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1734 if (prot == unix_prot) continue;
1735 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1737 TRACE( "%s exec prot for %p-%p\n",
1738 force_exec_prot ? "enabling" : "disabling",
1739 addr, addr + (count << page_shift) - 1 );
1740 mprotect( addr, count << page_shift,
1741 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1743 addr += (count << page_shift);
1744 unix_prot = prot;
1745 count = 0;
1747 if (count)
1749 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1751 TRACE( "%s exec prot for %p-%p\n",
1752 force_exec_prot ? "enabling" : "disabling",
1753 addr, addr + (count << page_shift) - 1 );
1754 mprotect( addr, count << page_shift,
1755 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1760 server_leave_uninterrupted_section( &csVirtual, &sigset );
1763 struct free_range
1765 char *base;
1766 char *limit;
1769 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1770 static int free_reserved_memory( void *base, size_t size, void *arg )
1772 struct free_range *range = arg;
1774 if ((char *)base >= range->limit) return 0;
1775 if ((char *)base + size <= range->base) return 0;
1776 if ((char *)base < range->base)
1778 size -= range->base - (char *)base;
1779 base = range->base;
1781 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1782 remove_reserved_area( base, size );
1783 return 1; /* stop enumeration since the list has changed */
1786 /***********************************************************************
1787 * virtual_release_address_space
1789 * Release some address space once we have loaded and initialized the app.
1791 void virtual_release_address_space( BOOL free_high_mem )
1793 struct free_range range;
1794 sigset_t sigset;
1796 if (user_space_limit == address_space_limit) return; /* no need to free anything */
1798 server_enter_uninterrupted_section( &csVirtual, &sigset );
1800 /* no large address space on win9x */
1801 if (free_high_mem && NtCurrentTeb()->Peb->OSPlatformId == VER_PLATFORM_WIN32_NT)
1803 range.base = (char *)0x82000000;
1804 range.limit = address_space_limit;
1805 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1806 user_space_limit = working_set_limit = address_space_limit;
1808 else
1810 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1811 range.base = (char *)0x20000000;
1812 range.limit = (char *)0x7f000000;
1813 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1814 #endif
1817 server_leave_uninterrupted_section( &csVirtual, &sigset );
1821 /***********************************************************************
1822 * NtAllocateVirtualMemory (NTDLL.@)
1823 * ZwAllocateVirtualMemory (NTDLL.@)
1825 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1826 SIZE_T *size_ptr, ULONG type, ULONG protect )
1828 void *base;
1829 unsigned int vprot;
1830 SIZE_T size = *size_ptr;
1831 SIZE_T mask = get_mask( zero_bits );
1832 NTSTATUS status = STATUS_SUCCESS;
1833 struct file_view *view;
1834 sigset_t sigset;
1836 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1838 if (!size) return STATUS_INVALID_PARAMETER;
1840 if (process != NtCurrentProcess())
1842 apc_call_t call;
1843 apc_result_t result;
1845 memset( &call, 0, sizeof(call) );
1847 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1848 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1849 call.virtual_alloc.size = *size_ptr;
1850 call.virtual_alloc.zero_bits = zero_bits;
1851 call.virtual_alloc.op_type = type;
1852 call.virtual_alloc.prot = protect;
1853 status = NTDLL_queue_process_apc( process, &call, &result );
1854 if (status != STATUS_SUCCESS) return status;
1856 if (result.virtual_alloc.status == STATUS_SUCCESS)
1858 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1859 *size_ptr = result.virtual_alloc.size;
1861 return result.virtual_alloc.status;
1864 /* Round parameters to a page boundary */
1866 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1868 if ((status = get_vprot_flags( protect, &vprot ))) return status;
1869 vprot |= VPROT_VALLOC;
1870 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1872 if (*ret)
1874 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1875 base = ROUND_ADDR( *ret, mask );
1876 else
1877 base = ROUND_ADDR( *ret, page_mask );
1878 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1880 /* address 1 is magic to mean DOS area */
1881 if (!base && *ret == (void *)1 && size == 0x110000)
1883 server_enter_uninterrupted_section( &csVirtual, &sigset );
1884 status = allocate_dos_memory( &view, vprot );
1885 if (status == STATUS_SUCCESS)
1887 *ret = view->base;
1888 *size_ptr = view->size;
1890 server_leave_uninterrupted_section( &csVirtual, &sigset );
1891 return status;
1894 /* disallow low 64k, wrap-around and kernel space */
1895 if (((char *)base < (char *)0x10000) ||
1896 ((char *)base + size < (char *)base) ||
1897 is_beyond_limit( base, size, address_space_limit ))
1898 return STATUS_INVALID_PARAMETER;
1900 else
1902 base = NULL;
1903 size = (size + page_mask) & ~page_mask;
1906 /* Compute the alloc type flags */
1908 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1909 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1911 WARN("called with wrong alloc type flags (%08x) !\n", type);
1912 return STATUS_INVALID_PARAMETER;
1915 /* Reserve the memory */
1917 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1919 if ((type & MEM_RESERVE) || !base)
1921 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1922 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1923 if (status == STATUS_SUCCESS) base = view->base;
1925 else if (type & MEM_RESET)
1927 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1928 else madvise( base, size, MADV_DONTNEED );
1930 else /* commit the pages */
1932 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1933 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1934 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1936 SERVER_START_REQ( add_mapping_committed_range )
1938 req->handle = wine_server_obj_handle( view->mapping );
1939 req->offset = (char *)base - (char *)view->base;
1940 req->size = size;
1941 wine_server_call( req );
1943 SERVER_END_REQ;
1947 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1949 if (status == STATUS_SUCCESS)
1951 *ret = base;
1952 *size_ptr = size;
1954 return status;
1958 /***********************************************************************
1959 * NtFreeVirtualMemory (NTDLL.@)
1960 * ZwFreeVirtualMemory (NTDLL.@)
1962 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1964 struct file_view *view;
1965 char *base;
1966 sigset_t sigset;
1967 NTSTATUS status = STATUS_SUCCESS;
1968 LPVOID addr = *addr_ptr;
1969 SIZE_T size = *size_ptr;
1971 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1973 if (process != NtCurrentProcess())
1975 apc_call_t call;
1976 apc_result_t result;
1978 memset( &call, 0, sizeof(call) );
1980 call.virtual_free.type = APC_VIRTUAL_FREE;
1981 call.virtual_free.addr = wine_server_client_ptr( addr );
1982 call.virtual_free.size = size;
1983 call.virtual_free.op_type = type;
1984 status = NTDLL_queue_process_apc( process, &call, &result );
1985 if (status != STATUS_SUCCESS) return status;
1987 if (result.virtual_free.status == STATUS_SUCCESS)
1989 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
1990 *size_ptr = result.virtual_free.size;
1992 return result.virtual_free.status;
1995 /* Fix the parameters */
1997 size = ROUND_SIZE( addr, size );
1998 base = ROUND_ADDR( addr, page_mask );
2000 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2001 if (!base) return STATUS_INVALID_PARAMETER;
2003 server_enter_uninterrupted_section( &csVirtual, &sigset );
2005 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2007 status = STATUS_INVALID_PARAMETER;
2009 else if (type == MEM_RELEASE)
2011 /* Free the pages */
2013 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2014 else
2016 delete_view( view );
2017 *addr_ptr = base;
2018 *size_ptr = size;
2021 else if (type == MEM_DECOMMIT)
2023 status = decommit_pages( view, base - (char *)view->base, size );
2024 if (status == STATUS_SUCCESS)
2026 *addr_ptr = base;
2027 *size_ptr = size;
2030 else
2032 WARN("called with wrong free type flags (%08x) !\n", type);
2033 status = STATUS_INVALID_PARAMETER;
2036 server_leave_uninterrupted_section( &csVirtual, &sigset );
2037 return status;
2041 /***********************************************************************
2042 * NtProtectVirtualMemory (NTDLL.@)
2043 * ZwProtectVirtualMemory (NTDLL.@)
2045 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2046 ULONG new_prot, ULONG *old_prot )
2048 struct file_view *view;
2049 sigset_t sigset;
2050 NTSTATUS status = STATUS_SUCCESS;
2051 char *base;
2052 BYTE vprot;
2053 unsigned int new_vprot;
2054 SIZE_T size = *size_ptr;
2055 LPVOID addr = *addr_ptr;
2057 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2059 if (process != NtCurrentProcess())
2061 apc_call_t call;
2062 apc_result_t result;
2064 memset( &call, 0, sizeof(call) );
2066 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2067 call.virtual_protect.addr = wine_server_client_ptr( addr );
2068 call.virtual_protect.size = size;
2069 call.virtual_protect.prot = new_prot;
2070 status = NTDLL_queue_process_apc( process, &call, &result );
2071 if (status != STATUS_SUCCESS) return status;
2073 if (result.virtual_protect.status == STATUS_SUCCESS)
2075 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2076 *size_ptr = result.virtual_protect.size;
2077 if (old_prot) *old_prot = result.virtual_protect.prot;
2079 return result.virtual_protect.status;
2082 /* Fix the parameters */
2084 size = ROUND_SIZE( addr, size );
2085 base = ROUND_ADDR( addr, page_mask );
2086 if ((status = get_vprot_flags( new_prot, &new_vprot ))) return status;
2087 new_vprot |= VPROT_COMMITTED;
2089 server_enter_uninterrupted_section( &csVirtual, &sigset );
2091 if (!(view = VIRTUAL_FindView( base, size )))
2093 status = STATUS_INVALID_PARAMETER;
2095 else
2097 /* Make sure all the pages are committed */
2098 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2100 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2101 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2103 else status = STATUS_NOT_COMMITTED;
2105 server_leave_uninterrupted_section( &csVirtual, &sigset );
2107 if (status == STATUS_SUCCESS)
2109 *addr_ptr = base;
2110 *size_ptr = size;
2112 return status;
2116 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2117 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2119 MEMORY_BASIC_INFORMATION *info = arg;
2120 void *end = (char *)start + size;
2122 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2124 if (info->BaseAddress >= end)
2126 if (info->AllocationBase < end) info->AllocationBase = end;
2127 return 0;
2130 if (info->BaseAddress >= start || start <= address_space_start)
2132 /* it's a real free area */
2133 info->State = MEM_FREE;
2134 info->Protect = PAGE_NOACCESS;
2135 info->AllocationBase = 0;
2136 info->AllocationProtect = 0;
2137 info->Type = 0;
2138 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2139 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2141 else /* outside of the reserved area, pretend it's allocated */
2143 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2144 info->State = MEM_RESERVE;
2145 info->Protect = PAGE_NOACCESS;
2146 info->AllocationProtect = PAGE_NOACCESS;
2147 info->Type = MEM_PRIVATE;
2149 return 1;
2152 #define UNIMPLEMENTED_INFO_CLASS(c) \
2153 case c: \
2154 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2155 return STATUS_INVALID_INFO_CLASS
2157 /***********************************************************************
2158 * NtQueryVirtualMemory (NTDLL.@)
2159 * ZwQueryVirtualMemory (NTDLL.@)
2161 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2162 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2163 SIZE_T len, SIZE_T *res_len )
2165 struct file_view *view;
2166 char *base, *alloc_base = 0;
2167 struct list *ptr;
2168 SIZE_T size = 0;
2169 MEMORY_BASIC_INFORMATION *info = buffer;
2170 sigset_t sigset;
2172 if (info_class != MemoryBasicInformation)
2174 switch(info_class)
2176 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2177 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2178 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2180 default:
2181 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2182 process, addr, info_class, buffer, len, res_len);
2183 return STATUS_INVALID_INFO_CLASS;
2187 if (process != NtCurrentProcess())
2189 NTSTATUS status;
2190 apc_call_t call;
2191 apc_result_t result;
2193 memset( &call, 0, sizeof(call) );
2195 call.virtual_query.type = APC_VIRTUAL_QUERY;
2196 call.virtual_query.addr = wine_server_client_ptr( addr );
2197 status = NTDLL_queue_process_apc( process, &call, &result );
2198 if (status != STATUS_SUCCESS) return status;
2200 if (result.virtual_query.status == STATUS_SUCCESS)
2202 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2203 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2204 info->RegionSize = result.virtual_query.size;
2205 info->Protect = result.virtual_query.prot;
2206 info->AllocationProtect = result.virtual_query.alloc_prot;
2207 info->State = (DWORD)result.virtual_query.state << 12;
2208 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2209 if (info->RegionSize != result.virtual_query.size) /* truncated */
2210 return STATUS_INVALID_PARAMETER; /* FIXME */
2211 if (res_len) *res_len = sizeof(*info);
2213 return result.virtual_query.status;
2216 base = ROUND_ADDR( addr, page_mask );
2218 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2220 /* Find the view containing the address */
2222 server_enter_uninterrupted_section( &csVirtual, &sigset );
2223 ptr = list_head( &views_list );
2224 for (;;)
2226 if (!ptr)
2228 size = (char *)working_set_limit - alloc_base;
2229 view = NULL;
2230 break;
2232 view = LIST_ENTRY( ptr, struct file_view, entry );
2233 if ((char *)view->base > base)
2235 size = (char *)view->base - alloc_base;
2236 view = NULL;
2237 break;
2239 if ((char *)view->base + view->size > base)
2241 alloc_base = view->base;
2242 size = view->size;
2243 break;
2245 alloc_base = (char *)view->base + view->size;
2246 ptr = list_next( &views_list, ptr );
2249 /* Fill the info structure */
2251 info->AllocationBase = alloc_base;
2252 info->BaseAddress = base;
2253 info->RegionSize = size - (base - alloc_base);
2255 if (!view)
2257 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2259 /* not in a reserved area at all, pretend it's allocated */
2260 #ifdef __i386__
2261 if (base >= (char *)address_space_start)
2263 info->State = MEM_RESERVE;
2264 info->Protect = PAGE_NOACCESS;
2265 info->AllocationProtect = PAGE_NOACCESS;
2266 info->Type = MEM_PRIVATE;
2268 else
2269 #endif
2271 info->State = MEM_FREE;
2272 info->Protect = PAGE_NOACCESS;
2273 info->AllocationBase = 0;
2274 info->AllocationProtect = 0;
2275 info->Type = 0;
2279 else
2281 BYTE vprot;
2282 SIZE_T range_size = get_committed_size( view, base, &vprot );
2284 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2285 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2286 info->AllocationBase = alloc_base;
2287 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2288 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2289 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2290 else info->Type = MEM_MAPPED;
2291 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2292 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2293 info->RegionSize = size - (base - alloc_base);
2295 server_leave_uninterrupted_section( &csVirtual, &sigset );
2297 if (res_len) *res_len = sizeof(*info);
2298 return STATUS_SUCCESS;
2302 /***********************************************************************
2303 * NtLockVirtualMemory (NTDLL.@)
2304 * ZwLockVirtualMemory (NTDLL.@)
2306 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2308 NTSTATUS status = STATUS_SUCCESS;
2310 if (process != NtCurrentProcess())
2312 apc_call_t call;
2313 apc_result_t result;
2315 memset( &call, 0, sizeof(call) );
2317 call.virtual_lock.type = APC_VIRTUAL_LOCK;
2318 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2319 call.virtual_lock.size = *size;
2320 status = NTDLL_queue_process_apc( process, &call, &result );
2321 if (status != STATUS_SUCCESS) return status;
2323 if (result.virtual_lock.status == STATUS_SUCCESS)
2325 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2326 *size = result.virtual_lock.size;
2328 return result.virtual_lock.status;
2331 *size = ROUND_SIZE( *addr, *size );
2332 *addr = ROUND_ADDR( *addr, page_mask );
2334 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2335 return status;
2339 /***********************************************************************
2340 * NtUnlockVirtualMemory (NTDLL.@)
2341 * ZwUnlockVirtualMemory (NTDLL.@)
2343 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2345 NTSTATUS status = STATUS_SUCCESS;
2347 if (process != NtCurrentProcess())
2349 apc_call_t call;
2350 apc_result_t result;
2352 memset( &call, 0, sizeof(call) );
2354 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2355 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2356 call.virtual_unlock.size = *size;
2357 status = NTDLL_queue_process_apc( process, &call, &result );
2358 if (status != STATUS_SUCCESS) return status;
2360 if (result.virtual_unlock.status == STATUS_SUCCESS)
2362 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2363 *size = result.virtual_unlock.size;
2365 return result.virtual_unlock.status;
2368 *size = ROUND_SIZE( *addr, *size );
2369 *addr = ROUND_ADDR( *addr, page_mask );
2371 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2372 return status;
2376 /***********************************************************************
2377 * NtCreateSection (NTDLL.@)
2378 * ZwCreateSection (NTDLL.@)
2380 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2381 const LARGE_INTEGER *size, ULONG protect,
2382 ULONG sec_flags, HANDLE file )
2384 NTSTATUS ret;
2385 unsigned int vprot;
2386 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
2387 struct security_descriptor *sd = NULL;
2388 struct object_attributes objattr;
2390 /* Check parameters */
2392 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2394 if ((ret = get_vprot_flags( protect, &vprot ))) return ret;
2396 objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
2397 objattr.sd_len = 0;
2398 objattr.name_len = len;
2399 if (attr)
2401 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2402 if (ret != STATUS_SUCCESS) return ret;
2405 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2406 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2407 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2409 /* Create the server object */
2411 SERVER_START_REQ( create_mapping )
2413 req->access = access;
2414 req->attributes = (attr) ? attr->Attributes : 0;
2415 req->file_handle = wine_server_obj_handle( file );
2416 req->size = size ? size->QuadPart : 0;
2417 req->protect = vprot;
2418 wine_server_add_data( req, &objattr, sizeof(objattr) );
2419 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2420 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2421 ret = wine_server_call( req );
2422 *handle = wine_server_ptr_handle( reply->handle );
2424 SERVER_END_REQ;
2426 NTDLL_free_struct_sd( sd );
2428 return ret;
2432 /***********************************************************************
2433 * NtOpenSection (NTDLL.@)
2434 * ZwOpenSection (NTDLL.@)
2436 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2438 NTSTATUS ret;
2439 DWORD len = attr->ObjectName->Length;
2441 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2443 SERVER_START_REQ( open_mapping )
2445 req->access = access;
2446 req->attributes = attr->Attributes;
2447 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2448 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2449 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
2451 SERVER_END_REQ;
2452 return ret;
2456 /***********************************************************************
2457 * NtMapViewOfSection (NTDLL.@)
2458 * ZwMapViewOfSection (NTDLL.@)
2460 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2461 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2462 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2464 NTSTATUS res;
2465 mem_size_t full_size;
2466 ACCESS_MASK access;
2467 SIZE_T size, mask = get_mask( zero_bits );
2468 int unix_handle = -1, needs_close;
2469 unsigned int map_vprot, vprot;
2470 void *base;
2471 struct file_view *view;
2472 DWORD header_size;
2473 HANDLE dup_mapping, shared_file;
2474 LARGE_INTEGER offset;
2475 sigset_t sigset;
2477 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2479 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2480 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2482 /* Check parameters */
2484 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2485 return STATUS_INVALID_PARAMETER;
2487 switch(protect)
2489 case PAGE_NOACCESS:
2490 access = 0;
2491 break;
2492 case PAGE_READWRITE:
2493 case PAGE_EXECUTE_READWRITE:
2494 access = SECTION_MAP_WRITE;
2495 break;
2496 case PAGE_READONLY:
2497 case PAGE_WRITECOPY:
2498 case PAGE_EXECUTE:
2499 case PAGE_EXECUTE_READ:
2500 case PAGE_EXECUTE_WRITECOPY:
2501 access = SECTION_MAP_READ;
2502 break;
2503 default:
2504 return STATUS_INVALID_PARAMETER;
2507 if (process != NtCurrentProcess())
2509 apc_call_t call;
2510 apc_result_t result;
2512 memset( &call, 0, sizeof(call) );
2514 call.map_view.type = APC_MAP_VIEW;
2515 call.map_view.handle = wine_server_obj_handle( handle );
2516 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2517 call.map_view.size = *size_ptr;
2518 call.map_view.offset = offset.QuadPart;
2519 call.map_view.zero_bits = zero_bits;
2520 call.map_view.alloc_type = alloc_type;
2521 call.map_view.prot = protect;
2522 res = NTDLL_queue_process_apc( process, &call, &result );
2523 if (res != STATUS_SUCCESS) return res;
2525 if ((NTSTATUS)result.map_view.status >= 0)
2527 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2528 *size_ptr = result.map_view.size;
2530 return result.map_view.status;
2533 SERVER_START_REQ( get_mapping_info )
2535 req->handle = wine_server_obj_handle( handle );
2536 req->access = access;
2537 res = wine_server_call( req );
2538 map_vprot = reply->protect;
2539 base = wine_server_get_ptr( reply->base );
2540 full_size = reply->size;
2541 header_size = reply->header_size;
2542 dup_mapping = wine_server_ptr_handle( reply->mapping );
2543 shared_file = wine_server_ptr_handle( reply->shared_file );
2544 if ((ULONG_PTR)base != reply->base) base = NULL;
2546 SERVER_END_REQ;
2547 if (res) return res;
2549 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2551 if (map_vprot & VPROT_IMAGE)
2553 size = full_size;
2554 if (size != full_size) /* truncated */
2556 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2557 res = STATUS_INVALID_PARAMETER;
2558 goto done;
2560 if (shared_file)
2562 int shared_fd, shared_needs_close;
2564 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2565 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2566 res = map_image( handle, unix_handle, base, size, mask, header_size,
2567 shared_fd, dup_mapping, addr_ptr );
2568 if (shared_needs_close) close( shared_fd );
2569 NtClose( shared_file );
2571 else
2573 res = map_image( handle, unix_handle, base, size, mask, header_size,
2574 -1, dup_mapping, addr_ptr );
2576 if (needs_close) close( unix_handle );
2577 if (res >= 0) *size_ptr = size;
2578 return res;
2581 res = STATUS_INVALID_PARAMETER;
2582 if (offset.QuadPart >= full_size) goto done;
2583 if (*size_ptr)
2585 if (*size_ptr > full_size - offset.QuadPart) goto done;
2586 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2587 if (size < *size_ptr) goto done; /* wrap-around */
2589 else
2591 size = full_size - offset.QuadPart;
2592 if (size != full_size - offset.QuadPart) /* truncated */
2594 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2595 wine_dbgstr_longlong(full_size) );
2596 goto done;
2600 /* Reserve a properly aligned area */
2602 server_enter_uninterrupted_section( &csVirtual, &sigset );
2604 get_vprot_flags( protect, &vprot );
2605 vprot |= (map_vprot & VPROT_COMMITTED);
2606 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2607 if (res)
2609 server_leave_uninterrupted_section( &csVirtual, &sigset );
2610 goto done;
2613 /* Map the file */
2615 TRACE("handle=%p size=%lx offset=%x%08x\n",
2616 handle, size, offset.u.HighPart, offset.u.LowPart );
2618 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2619 if (res == STATUS_SUCCESS)
2621 *addr_ptr = view->base;
2622 *size_ptr = size;
2623 view->mapping = dup_mapping;
2624 dup_mapping = 0; /* don't close it */
2626 else
2628 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2629 view->base, size, offset.u.HighPart, offset.u.LowPart );
2630 delete_view( view );
2633 server_leave_uninterrupted_section( &csVirtual, &sigset );
2635 done:
2636 if (dup_mapping) NtClose( dup_mapping );
2637 if (needs_close) close( unix_handle );
2638 return res;
2642 /***********************************************************************
2643 * NtUnmapViewOfSection (NTDLL.@)
2644 * ZwUnmapViewOfSection (NTDLL.@)
2646 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2648 struct file_view *view;
2649 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2650 sigset_t sigset;
2651 void *base = ROUND_ADDR( addr, page_mask );
2653 if (process != NtCurrentProcess())
2655 apc_call_t call;
2656 apc_result_t result;
2658 memset( &call, 0, sizeof(call) );
2660 call.unmap_view.type = APC_UNMAP_VIEW;
2661 call.unmap_view.addr = wine_server_client_ptr( addr );
2662 status = NTDLL_queue_process_apc( process, &call, &result );
2663 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2664 return status;
2667 server_enter_uninterrupted_section( &csVirtual, &sigset );
2668 if ((view = VIRTUAL_FindView( base, 0 )) && (base == view->base) && !(view->protect & VPROT_VALLOC))
2670 delete_view( view );
2671 status = STATUS_SUCCESS;
2673 server_leave_uninterrupted_section( &csVirtual, &sigset );
2674 return status;
2678 /***********************************************************************
2679 * NtFlushVirtualMemory (NTDLL.@)
2680 * ZwFlushVirtualMemory (NTDLL.@)
2682 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2683 SIZE_T *size_ptr, ULONG unknown )
2685 struct file_view *view;
2686 NTSTATUS status = STATUS_SUCCESS;
2687 sigset_t sigset;
2688 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2690 if (process != NtCurrentProcess())
2692 apc_call_t call;
2693 apc_result_t result;
2695 memset( &call, 0, sizeof(call) );
2697 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2698 call.virtual_flush.addr = wine_server_client_ptr( addr );
2699 call.virtual_flush.size = *size_ptr;
2700 status = NTDLL_queue_process_apc( process, &call, &result );
2701 if (status != STATUS_SUCCESS) return status;
2703 if (result.virtual_flush.status == STATUS_SUCCESS)
2705 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2706 *size_ptr = result.virtual_flush.size;
2708 return result.virtual_flush.status;
2711 server_enter_uninterrupted_section( &csVirtual, &sigset );
2712 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2713 else
2715 if (!*size_ptr) *size_ptr = view->size;
2716 *addr_ptr = addr;
2717 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2719 server_leave_uninterrupted_section( &csVirtual, &sigset );
2720 return status;
2724 /***********************************************************************
2725 * NtGetWriteWatch (NTDLL.@)
2726 * ZwGetWriteWatch (NTDLL.@)
2728 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2729 ULONG_PTR *count, ULONG *granularity )
2731 struct file_view *view;
2732 NTSTATUS status = STATUS_SUCCESS;
2733 sigset_t sigset;
2735 size = ROUND_SIZE( base, size );
2736 base = ROUND_ADDR( base, page_mask );
2738 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2739 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2740 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2742 if (!addresses) return STATUS_ACCESS_VIOLATION;
2744 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2745 addresses, *count );
2747 server_enter_uninterrupted_section( &csVirtual, &sigset );
2749 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2751 ULONG_PTR pos = 0;
2752 char *addr = base;
2753 char *end = addr + size;
2755 while (pos < *count && addr < end)
2757 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2758 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2759 addr += page_size;
2761 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2762 *count = pos;
2763 *granularity = page_size;
2765 else status = STATUS_INVALID_PARAMETER;
2767 server_leave_uninterrupted_section( &csVirtual, &sigset );
2768 return status;
2772 /***********************************************************************
2773 * NtResetWriteWatch (NTDLL.@)
2774 * ZwResetWriteWatch (NTDLL.@)
2776 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2778 struct file_view *view;
2779 NTSTATUS status = STATUS_SUCCESS;
2780 sigset_t sigset;
2782 size = ROUND_SIZE( base, size );
2783 base = ROUND_ADDR( base, page_mask );
2785 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2787 if (!size) return STATUS_INVALID_PARAMETER;
2789 server_enter_uninterrupted_section( &csVirtual, &sigset );
2791 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2792 reset_write_watches( view, base, size );
2793 else
2794 status = STATUS_INVALID_PARAMETER;
2796 server_leave_uninterrupted_section( &csVirtual, &sigset );
2797 return status;
2801 /***********************************************************************
2802 * NtReadVirtualMemory (NTDLL.@)
2803 * ZwReadVirtualMemory (NTDLL.@)
2805 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2806 SIZE_T size, SIZE_T *bytes_read )
2808 NTSTATUS status;
2810 if (virtual_check_buffer_for_write( buffer, size ))
2812 SERVER_START_REQ( read_process_memory )
2814 req->handle = wine_server_obj_handle( process );
2815 req->addr = wine_server_client_ptr( addr );
2816 wine_server_set_reply( req, buffer, size );
2817 if ((status = wine_server_call( req ))) size = 0;
2819 SERVER_END_REQ;
2821 else
2823 status = STATUS_ACCESS_VIOLATION;
2824 size = 0;
2826 if (bytes_read) *bytes_read = size;
2827 return status;
2831 /***********************************************************************
2832 * NtWriteVirtualMemory (NTDLL.@)
2833 * ZwWriteVirtualMemory (NTDLL.@)
2835 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2836 SIZE_T size, SIZE_T *bytes_written )
2838 NTSTATUS status;
2840 if (virtual_check_buffer_for_read( buffer, size ))
2842 SERVER_START_REQ( write_process_memory )
2844 req->handle = wine_server_obj_handle( process );
2845 req->addr = wine_server_client_ptr( addr );
2846 wine_server_add_data( req, buffer, size );
2847 if ((status = wine_server_call( req ))) size = 0;
2849 SERVER_END_REQ;
2851 else
2853 status = STATUS_PARTIAL_COPY;
2854 size = 0;
2856 if (bytes_written) *bytes_written = size;
2857 return status;
2861 /***********************************************************************
2862 * NtAreMappedFilesTheSame (NTDLL.@)
2863 * ZwAreMappedFilesTheSame (NTDLL.@)
2865 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2867 struct file_view *view1, *view2;
2868 struct stat st1, st2;
2869 NTSTATUS status;
2870 sigset_t sigset;
2872 TRACE("%p %p\n", addr1, addr2);
2874 server_enter_uninterrupted_section( &csVirtual, &sigset );
2876 view1 = VIRTUAL_FindView( addr1, 0 );
2877 view2 = VIRTUAL_FindView( addr2, 0 );
2879 if (!view1 || !view2)
2880 status = STATUS_INVALID_ADDRESS;
2881 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
2882 status = STATUS_CONFLICTING_ADDRESSES;
2883 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
2884 status = STATUS_NOT_SAME_DEVICE;
2885 else if (view1 == view2)
2886 status = STATUS_SUCCESS;
2887 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
2888 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2889 status = STATUS_SUCCESS;
2890 else
2891 status = STATUS_NOT_SAME_DEVICE;
2893 server_leave_uninterrupted_section( &csVirtual, &sigset );
2894 return status;