ntdll: Implement the SectionBasicInformation class of NtQuerySection.
[wine.git] / dlls / ntdll / virtual.c
blob818e2641d86da534486dbf2c293f78194fc00a22
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_SYS_SYSINFO_H
42 # include <sys/sysinfo.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #include "ntstatus.h"
49 #define WIN32_NO_STATUS
50 #define NONAMELESSUNION
51 #include "windef.h"
52 #include "winternl.h"
53 #include "wine/library.h"
54 #include "wine/server.h"
55 #include "wine/exception.h"
56 #include "wine/list.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
61 WINE_DECLARE_DEBUG_CHANNEL(module);
63 #ifndef MAP_NORESERVE
64 #define MAP_NORESERVE 0
65 #endif
67 /* File view */
68 struct file_view
70 struct list entry; /* Entry in global view list */
71 void *base; /* Base address */
72 size_t size; /* Size in bytes */
73 HANDLE mapping; /* Handle to the file mapping */
74 unsigned int map_protect; /* Mapping protection */
75 unsigned int protect; /* Protection for all pages at allocation time */
76 BYTE prot[1]; /* Protection byte for each page */
80 /* Conversion from VPROT_* to Win32 flags */
81 static const BYTE VIRTUAL_Win32Flags[16] =
83 PAGE_NOACCESS, /* 0 */
84 PAGE_READONLY, /* READ */
85 PAGE_READWRITE, /* WRITE */
86 PAGE_READWRITE, /* READ | WRITE */
87 PAGE_EXECUTE, /* EXEC */
88 PAGE_EXECUTE_READ, /* READ | EXEC */
89 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
90 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
91 PAGE_WRITECOPY, /* WRITECOPY */
92 PAGE_WRITECOPY, /* READ | WRITECOPY */
93 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
94 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
95 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
96 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
97 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
101 static struct list views_list = LIST_INIT(views_list);
103 static RTL_CRITICAL_SECTION csVirtual;
104 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
106 0, 0, &csVirtual,
107 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
108 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
110 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
112 #ifdef __i386__
113 static const UINT page_shift = 12;
114 static const UINT_PTR page_mask = 0xfff;
115 /* Note: these are Windows limits, you cannot change them. */
116 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
117 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
118 static void *working_set_limit = (void *)0x7fff0000; /* top of the current working set */
119 static void *address_space_start = (void *)0x110000; /* keep DOS area clear */
120 #elif defined(__x86_64__)
121 static const UINT page_shift = 12;
122 static const UINT_PTR page_mask = 0xfff;
123 static void *address_space_limit = (void *)0x7fffffff0000;
124 static void *user_space_limit = (void *)0x7fffffff0000;
125 static void *working_set_limit = (void *)0x7fffffff0000;
126 static void *address_space_start = (void *)0x10000;
127 #else
128 UINT_PTR page_size = 0;
129 static UINT page_shift;
130 static UINT_PTR page_mask;
131 static void *address_space_limit;
132 static void *user_space_limit;
133 static void *working_set_limit;
134 static void *address_space_start = (void *)0x10000;
135 #endif /* __i386__ */
136 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
138 #define ROUND_ADDR(addr,mask) \
139 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
141 #define ROUND_SIZE(addr,size) \
142 (((SIZE_T)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
144 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
145 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
147 #define VIRTUAL_HEAP_SIZE (sizeof(void*)*1024*1024)
149 static HANDLE virtual_heap;
150 static void *preload_reserve_start;
151 static void *preload_reserve_end;
152 static BOOL use_locks;
153 static BOOL force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
156 /***********************************************************************
157 * VIRTUAL_GetProtStr
159 static const char *VIRTUAL_GetProtStr( BYTE prot )
161 static char buffer[6];
162 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
163 buffer[1] = (prot & VPROT_GUARD) ? 'g' : ((prot & VPROT_WRITEWATCH) ? 'H' : '-');
164 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
165 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
166 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
167 buffer[5] = 0;
168 return buffer;
172 /***********************************************************************
173 * VIRTUAL_GetUnixProt
175 * Convert page protections to protection for mmap/mprotect.
177 static int VIRTUAL_GetUnixProt( BYTE vprot )
179 int prot = 0;
180 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
182 if (vprot & VPROT_READ) prot |= PROT_READ;
183 if (vprot & VPROT_WRITE) prot |= PROT_WRITE | PROT_READ;
184 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE | PROT_READ;
185 if (vprot & VPROT_EXEC) prot |= PROT_EXEC | PROT_READ;
186 if (vprot & VPROT_WRITEWATCH) prot &= ~PROT_WRITE;
188 if (!prot) prot = PROT_NONE;
189 return prot;
193 /***********************************************************************
194 * VIRTUAL_DumpView
196 static void VIRTUAL_DumpView( struct file_view *view )
198 UINT i, count;
199 char *addr = view->base;
200 BYTE prot = view->prot[0];
202 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
203 if (view->protect & VPROT_SYSTEM)
204 TRACE( " (system)\n" );
205 else if (view->protect & VPROT_VALLOC)
206 TRACE( " (valloc)\n" );
207 else if (view->mapping)
208 TRACE( " %p\n", view->mapping );
209 else
210 TRACE( " (anonymous)\n");
212 for (count = i = 1; i < view->size >> page_shift; i++, count++)
214 if (view->prot[i] == prot) continue;
215 TRACE( " %p - %p %s\n",
216 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
217 addr += (count << page_shift);
218 prot = view->prot[i];
219 count = 0;
221 if (count)
222 TRACE( " %p - %p %s\n",
223 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
227 /***********************************************************************
228 * VIRTUAL_Dump
230 #ifdef WINE_VM_DEBUG
231 static void VIRTUAL_Dump(void)
233 sigset_t sigset;
234 struct file_view *view;
236 TRACE( "Dump of all virtual memory views:\n" );
237 server_enter_uninterrupted_section( &csVirtual, &sigset );
238 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
240 VIRTUAL_DumpView( view );
242 server_leave_uninterrupted_section( &csVirtual, &sigset );
244 #endif
247 /***********************************************************************
248 * VIRTUAL_FindView
250 * Find the view containing a given address. The csVirtual section must be held by caller.
252 * PARAMS
253 * addr [I] Address
255 * RETURNS
256 * View: Success
257 * NULL: Failure
259 static struct file_view *VIRTUAL_FindView( const void *addr, size_t size )
261 struct file_view *view;
263 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
265 if (view->base > addr) break; /* no matching view */
266 if ((const char *)view->base + view->size <= (const char *)addr) continue;
267 if ((const char *)view->base + view->size < (const char *)addr + size) break; /* size too large */
268 if ((const char *)addr + size < (const char *)addr) break; /* overflow */
269 return view;
271 return NULL;
275 /***********************************************************************
276 * get_mask
278 static inline UINT_PTR get_mask( ULONG zero_bits )
280 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
281 if (zero_bits < page_shift) zero_bits = page_shift;
282 return (1 << zero_bits) - 1;
286 /***********************************************************************
287 * find_view_range
289 * Find the first view overlapping at least part of the specified range.
290 * The csVirtual section must be held by caller.
292 static struct file_view *find_view_range( const void *addr, size_t size )
294 struct file_view *view;
296 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
298 if ((const char *)view->base >= (const char *)addr + size) break;
299 if ((const char *)view->base + view->size > (const char *)addr) return view;
301 return NULL;
305 /***********************************************************************
306 * find_free_area
308 * Find a free area between views inside the specified range.
309 * The csVirtual section must be held by caller.
311 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
313 struct list *ptr;
314 void *start;
316 if (top_down)
318 start = ROUND_ADDR( (char *)end - size, mask );
319 if (start >= end || start < base) return NULL;
321 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
323 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
325 if ((char *)view->base + view->size <= (char *)start) break;
326 if ((char *)view->base >= (char *)start + size) continue;
327 start = ROUND_ADDR( (char *)view->base - size, mask );
328 /* stop if remaining space is not large enough */
329 if (!start || start >= end || start < base) return NULL;
332 else
334 start = ROUND_ADDR( (char *)base + mask, mask );
335 if (start >= end || (char *)end - (char *)start < size) return NULL;
337 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
339 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
341 if ((char *)view->base >= (char *)start + size) break;
342 if ((char *)view->base + view->size <= (char *)start) continue;
343 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
344 /* stop if remaining space is not large enough */
345 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
348 return start;
352 /***********************************************************************
353 * add_reserved_area
355 * Add a reserved area to the list maintained by libwine.
356 * The csVirtual section must be held by caller.
358 static void add_reserved_area( void *addr, size_t size )
360 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
362 if (addr < user_space_limit)
364 /* unmap the part of the area that is below the limit */
365 assert( (char *)addr + size > (char *)user_space_limit );
366 munmap( addr, (char *)user_space_limit - (char *)addr );
367 size -= (char *)user_space_limit - (char *)addr;
368 addr = user_space_limit;
370 /* blow away existing mappings */
371 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
372 wine_mmap_add_reserved_area( addr, size );
376 /***********************************************************************
377 * remove_reserved_area
379 * Remove a reserved area from the list maintained by libwine.
380 * The csVirtual section must be held by caller.
382 static void remove_reserved_area( void *addr, size_t size )
384 struct file_view *view;
386 TRACE( "removing %p-%p\n", addr, (char *)addr + size );
387 wine_mmap_remove_reserved_area( addr, size, 0 );
389 /* unmap areas not covered by an existing view */
390 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
392 if ((char *)view->base >= (char *)addr + size)
394 munmap( addr, size );
395 break;
397 if ((char *)view->base + view->size <= (char *)addr) continue;
398 if (view->base > addr) munmap( addr, (char *)view->base - (char *)addr );
399 if ((char *)view->base + view->size > (char *)addr + size) break;
400 size = (char *)addr + size - ((char *)view->base + view->size);
401 addr = (char *)view->base + view->size;
406 /***********************************************************************
407 * is_beyond_limit
409 * Check if an address range goes beyond a given limit.
411 static inline BOOL is_beyond_limit( const void *addr, size_t size, const void *limit )
413 return (addr >= limit || (const char *)addr + size > (const char *)limit);
417 /***********************************************************************
418 * unmap_area
420 * Unmap an area, or simply replace it by an empty mapping if it is
421 * in a reserved area. The csVirtual section must be held by caller.
423 static inline void unmap_area( void *addr, size_t size )
425 if (wine_mmap_is_in_reserved_area( addr, size ))
426 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
427 else if (is_beyond_limit( addr, size, user_space_limit ))
428 add_reserved_area( addr, size );
429 else
430 munmap( addr, size );
434 /***********************************************************************
435 * delete_view
437 * Deletes a view. The csVirtual section must be held by caller.
439 static void delete_view( struct file_view *view ) /* [in] View */
441 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
442 list_remove( &view->entry );
443 if (view->mapping) close_handle( view->mapping );
444 RtlFreeHeap( virtual_heap, 0, view );
448 /***********************************************************************
449 * create_view
451 * Create a view. The csVirtual section must be held by caller.
453 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
455 struct file_view *view;
456 struct list *ptr;
457 int unix_prot = VIRTUAL_GetUnixProt( vprot );
459 assert( !((UINT_PTR)base & page_mask) );
460 assert( !(size & page_mask) );
462 /* Create the view structure */
464 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
466 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
467 return STATUS_NO_MEMORY;
470 view->base = base;
471 view->size = size;
472 view->mapping = 0;
473 view->map_protect = 0;
474 view->protect = vprot;
475 memset( view->prot, vprot, size >> page_shift );
477 /* Insert it in the linked list */
479 LIST_FOR_EACH( ptr, &views_list )
481 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
482 if (next->base > base) break;
484 list_add_before( ptr, &view->entry );
486 /* Check for overlapping views. This can happen if the previous view
487 * was a system view that got unmapped behind our back. In that case
488 * we recover by simply deleting it. */
490 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
492 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
493 if ((char *)prev->base + prev->size > (char *)base)
495 TRACE( "overlapping prev view %p-%p for %p-%p\n",
496 prev->base, (char *)prev->base + prev->size,
497 base, (char *)base + view->size );
498 assert( prev->protect & VPROT_SYSTEM );
499 delete_view( prev );
502 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
504 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
505 if ((char *)base + view->size > (char *)next->base)
507 TRACE( "overlapping next view %p-%p for %p-%p\n",
508 next->base, (char *)next->base + next->size,
509 base, (char *)base + view->size );
510 assert( next->protect & VPROT_SYSTEM );
511 delete_view( next );
515 *view_ret = view;
516 VIRTUAL_DEBUG_DUMP_VIEW( view );
518 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
520 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
521 mprotect( base, size, unix_prot | PROT_EXEC );
523 return STATUS_SUCCESS;
527 /***********************************************************************
528 * VIRTUAL_GetWin32Prot
530 * Convert page protections to Win32 flags.
532 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
534 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
535 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
536 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
537 return ret;
541 /***********************************************************************
542 * get_vprot_flags
544 * Build page protections from Win32 flags.
546 * PARAMS
547 * protect [I] Win32 protection flags
549 * RETURNS
550 * Value of page protection flags
552 static NTSTATUS get_vprot_flags( DWORD protect, unsigned int *vprot, BOOL image )
554 switch(protect & 0xff)
556 case PAGE_READONLY:
557 *vprot = VPROT_READ;
558 break;
559 case PAGE_READWRITE:
560 if (image)
561 *vprot = VPROT_READ | VPROT_WRITECOPY;
562 else
563 *vprot = VPROT_READ | VPROT_WRITE;
564 break;
565 case PAGE_WRITECOPY:
566 *vprot = VPROT_READ | VPROT_WRITECOPY;
567 break;
568 case PAGE_EXECUTE:
569 *vprot = VPROT_EXEC;
570 break;
571 case PAGE_EXECUTE_READ:
572 *vprot = VPROT_EXEC | VPROT_READ;
573 break;
574 case PAGE_EXECUTE_READWRITE:
575 if (image)
576 *vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
577 else
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_PAGE_PROTECTION;
589 if (protect & PAGE_GUARD) *vprot |= VPROT_GUARD;
590 if (protect & PAGE_NOCACHE) *vprot |= VPROT_NOCACHE;
591 return STATUS_SUCCESS;
595 /***********************************************************************
596 * mprotect_exec
598 * Wrapper for mprotect, adds PROT_EXEC if forced by force_exec_prot
600 static inline int mprotect_exec( void *base, size_t size, int unix_prot, unsigned int view_protect )
602 if (force_exec_prot && !(view_protect & VPROT_NOEXEC) &&
603 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
605 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
606 if (!mprotect( base, size, unix_prot | PROT_EXEC )) return 0;
607 /* exec + write may legitimately fail, in that case fall back to write only */
608 if (!(unix_prot & PROT_WRITE)) return -1;
611 return mprotect( base, size, unix_prot );
614 /***********************************************************************
615 * VIRTUAL_SetProt
617 * Change the protection of a range of pages.
619 * RETURNS
620 * TRUE: Success
621 * FALSE: Failure
623 static BOOL VIRTUAL_SetProt( struct file_view *view, /* [in] Pointer to view */
624 void *base, /* [in] Starting address */
625 size_t size, /* [in] Size in bytes */
626 BYTE vprot ) /* [in] Protections to use */
628 int unix_prot = VIRTUAL_GetUnixProt(vprot);
629 BYTE *p = view->prot + (((char *)base - (char *)view->base) >> page_shift);
631 TRACE("%p-%p %s\n",
632 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
634 if (view->protect & VPROT_WRITEWATCH)
636 /* each page may need different protections depending on write watch flag */
637 UINT i, count;
638 char *addr = base;
639 int prot;
641 p[0] = vprot | (p[0] & VPROT_WRITEWATCH);
642 unix_prot = VIRTUAL_GetUnixProt( p[0] );
643 for (count = i = 1; i < size >> page_shift; i++, count++)
645 p[i] = vprot | (p[i] & VPROT_WRITEWATCH);
646 prot = VIRTUAL_GetUnixProt( p[i] );
647 if (prot == unix_prot) continue;
648 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
649 addr += count << page_shift;
650 unix_prot = prot;
651 count = 0;
653 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
654 VIRTUAL_DEBUG_DUMP_VIEW( view );
655 return TRUE;
658 /* if setting stack guard pages, store the permissions first, as the guard may be
659 * triggered at any point after mprotect and change the permissions again */
660 if ((vprot & VPROT_GUARD) &&
661 (base >= NtCurrentTeb()->DeallocationStack) &&
662 (base < NtCurrentTeb()->Tib.StackBase))
664 memset( p, vprot, size >> page_shift );
665 mprotect( base, size, unix_prot );
666 VIRTUAL_DEBUG_DUMP_VIEW( view );
667 return TRUE;
670 if (mprotect_exec( base, size, unix_prot, view->protect )) /* FIXME: last error */
671 return FALSE;
673 memset( p, vprot, size >> page_shift );
674 VIRTUAL_DEBUG_DUMP_VIEW( view );
675 return TRUE;
679 /***********************************************************************
680 * reset_write_watches
682 * Reset write watches in a memory range.
684 static void reset_write_watches( struct file_view *view, void *base, SIZE_T size )
686 SIZE_T i, count;
687 int prot, unix_prot;
688 char *addr = base;
689 BYTE *p = view->prot + ((addr - (char *)view->base) >> page_shift);
691 p[0] |= VPROT_WRITEWATCH;
692 unix_prot = VIRTUAL_GetUnixProt( p[0] );
693 for (count = i = 1; i < size >> page_shift; i++, count++)
695 p[i] |= VPROT_WRITEWATCH;
696 prot = VIRTUAL_GetUnixProt( p[i] );
697 if (prot == unix_prot) continue;
698 mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
699 addr += count << page_shift;
700 unix_prot = prot;
701 count = 0;
703 if (count) mprotect_exec( addr, count << page_shift, unix_prot, view->protect );
707 /***********************************************************************
708 * unmap_extra_space
710 * Release the extra memory while keeping the range starting on the granularity boundary.
712 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
714 if ((ULONG_PTR)ptr & mask)
716 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
717 munmap( ptr, extra );
718 ptr = (char *)ptr + extra;
719 total_size -= extra;
721 if (total_size > wanted_size)
722 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
723 return ptr;
727 struct alloc_area
729 size_t size;
730 size_t mask;
731 int top_down;
732 void *limit;
733 void *result;
736 /***********************************************************************
737 * alloc_reserved_area_callback
739 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
741 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
743 struct alloc_area *alloc = arg;
744 void *end = (char *)start + size;
746 if (start < address_space_start) start = address_space_start;
747 if (is_beyond_limit( start, size, alloc->limit )) end = alloc->limit;
748 if (start >= end) return 0;
750 /* make sure we don't touch the preloader reserved range */
751 if (preload_reserve_end >= start)
753 if (preload_reserve_end >= end)
755 if (preload_reserve_start <= start) return 0; /* no space in that area */
756 if (preload_reserve_start < end) end = preload_reserve_start;
758 else if (preload_reserve_start <= start) start = preload_reserve_end;
759 else
761 /* range is split in two by the preloader reservation, try first part */
762 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
763 alloc->mask, alloc->top_down )))
764 return 1;
765 /* then fall through to try second part */
766 start = preload_reserve_end;
769 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
770 return 1;
772 return 0;
776 /***********************************************************************
777 * map_view
779 * Create a view and mmap the corresponding memory area.
780 * The csVirtual section must be held by caller.
782 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
783 int top_down, unsigned int vprot )
785 void *ptr;
786 NTSTATUS status;
788 if (base)
790 if (is_beyond_limit( base, size, address_space_limit ))
791 return STATUS_WORKING_SET_LIMIT_RANGE;
793 switch (wine_mmap_is_in_reserved_area( base, size ))
795 case -1: /* partially in a reserved area */
796 return STATUS_CONFLICTING_ADDRESSES;
798 case 0: /* not in a reserved area, do a normal allocation */
799 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
801 if (errno == ENOMEM) return STATUS_NO_MEMORY;
802 return STATUS_INVALID_PARAMETER;
804 if (ptr != base)
806 /* We couldn't get the address we wanted */
807 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
808 else munmap( ptr, size );
809 return STATUS_CONFLICTING_ADDRESSES;
811 break;
813 default:
814 case 1: /* in a reserved area, make sure the address is available */
815 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
816 /* replace the reserved area by our mapping */
817 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
818 return STATUS_INVALID_PARAMETER;
819 break;
821 if (is_beyond_limit( ptr, size, working_set_limit )) working_set_limit = address_space_limit;
823 else
825 size_t view_size = size + mask + 1;
826 struct alloc_area alloc;
828 alloc.size = size;
829 alloc.mask = mask;
830 alloc.top_down = top_down;
831 alloc.limit = user_space_limit;
832 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
834 ptr = alloc.result;
835 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
836 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
837 return STATUS_INVALID_PARAMETER;
838 goto done;
841 for (;;)
843 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
845 if (errno == ENOMEM) return STATUS_NO_MEMORY;
846 return STATUS_INVALID_PARAMETER;
848 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
849 /* if we got something beyond the user limit, unmap it and retry */
850 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
851 else break;
853 ptr = unmap_extra_space( ptr, view_size, size, mask );
855 done:
856 status = create_view( view_ret, ptr, size, vprot );
857 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
858 return status;
862 /***********************************************************************
863 * map_file_into_view
865 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
866 * The csVirtual section must be held by caller.
868 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
869 off_t offset, unsigned int vprot, BOOL removable )
871 void *ptr;
872 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
873 unsigned int flags = MAP_FIXED | ((vprot & VPROT_WRITECOPY) ? MAP_PRIVATE : MAP_SHARED);
875 assert( start < view->size );
876 assert( start + size <= view->size );
878 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (vprot & VPROT_READ))
880 TRACE( "forcing exec permission on mapping %p-%p\n",
881 (char *)view->base + start, (char *)view->base + start + size - 1 );
882 prot |= PROT_EXEC;
885 /* only try mmap if media is not removable (or if we require write access) */
886 if (!removable || (flags & MAP_SHARED))
888 if (mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
889 goto done;
891 if ((errno == EPERM) && (prot & PROT_EXEC))
892 ERR( "failed to set %08x protection on file map, noexec filesystem?\n", prot );
894 /* mmap() failed; if this is because the file offset is not */
895 /* page-aligned (EINVAL), or because the underlying filesystem */
896 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
897 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
898 if (flags & MAP_SHARED) /* we cannot fake shared mappings */
900 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
901 ERR( "shared writable mmap not supported, broken filesystem?\n" );
902 return STATUS_NOT_SUPPORTED;
906 /* Reserve the memory with an anonymous mmap */
907 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
908 if (ptr == (void *)-1) return FILE_GetNtStatus();
909 /* Now read in the file */
910 pread( fd, ptr, size, offset );
911 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
912 done:
913 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
914 return STATUS_SUCCESS;
918 /***********************************************************************
919 * get_committed_size
921 * Get the size of the committed range starting at base.
922 * Also return the protections for the first page.
924 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
926 SIZE_T i, start;
928 start = ((char *)base - (char *)view->base) >> page_shift;
929 *vprot = view->prot[start];
931 if (view->mapping && !(view->protect & VPROT_COMMITTED))
933 SIZE_T ret = 0;
934 SERVER_START_REQ( get_mapping_committed_range )
936 req->handle = wine_server_obj_handle( view->mapping );
937 req->offset = start << page_shift;
938 if (!wine_server_call( req ))
940 ret = reply->size;
941 if (reply->committed)
943 *vprot |= VPROT_COMMITTED;
944 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
948 SERVER_END_REQ;
949 return ret;
951 for (i = start + 1; i < view->size >> page_shift; i++)
952 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
953 return (i - start) << page_shift;
957 /***********************************************************************
958 * decommit_view
960 * Decommit some pages of a given view.
961 * The csVirtual section must be held by caller.
963 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
965 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
967 BYTE *p = view->prot + (start >> page_shift);
968 size >>= page_shift;
969 while (size--) *p++ &= ~VPROT_COMMITTED;
970 return STATUS_SUCCESS;
972 return FILE_GetNtStatus();
976 /***********************************************************************
977 * allocate_dos_memory
979 * Allocate the DOS memory range.
981 static NTSTATUS allocate_dos_memory( struct file_view **view, unsigned int vprot )
983 size_t size;
984 void *addr = NULL;
985 void * const low_64k = (void *)0x10000;
986 const size_t dosmem_size = 0x110000;
987 int unix_prot = VIRTUAL_GetUnixProt( vprot );
988 struct list *ptr;
990 /* check for existing view */
992 if ((ptr = list_head( &views_list )))
994 struct file_view *first_view = LIST_ENTRY( ptr, struct file_view, entry );
995 if (first_view->base < (void *)dosmem_size) return STATUS_CONFLICTING_ADDRESSES;
998 /* check without the first 64K */
1000 if (wine_mmap_is_in_reserved_area( low_64k, dosmem_size - 0x10000 ) != 1)
1002 addr = wine_anon_mmap( low_64k, dosmem_size - 0x10000, unix_prot, 0 );
1003 if (addr != low_64k)
1005 if (addr != (void *)-1) munmap( addr, dosmem_size - 0x10000 );
1006 return map_view( view, NULL, dosmem_size, 0xffff, 0, vprot );
1010 /* now try to allocate the low 64K too */
1012 if (wine_mmap_is_in_reserved_area( NULL, 0x10000 ) != 1)
1014 addr = wine_anon_mmap( (void *)page_size, 0x10000 - page_size, unix_prot, 0 );
1015 if (addr == (void *)page_size)
1017 if (!wine_anon_mmap( NULL, page_size, unix_prot, MAP_FIXED ))
1019 addr = NULL;
1020 TRACE( "successfully mapped low 64K range\n" );
1022 else TRACE( "failed to map page 0\n" );
1024 else
1026 if (addr != (void *)-1) munmap( addr, 0x10000 - page_size );
1027 addr = low_64k;
1028 TRACE( "failed to map low 64K range\n" );
1032 /* now reserve the whole range */
1034 size = (char *)dosmem_size - (char *)addr;
1035 wine_anon_mmap( addr, size, unix_prot, MAP_FIXED );
1036 return create_view( view, addr, size, vprot );
1040 /***********************************************************************
1041 * stat_mapping_file
1043 * Stat the underlying file for a memory view.
1045 static NTSTATUS stat_mapping_file( struct file_view *view, struct stat *st )
1047 NTSTATUS status;
1048 int unix_fd, needs_close;
1050 if (!view->mapping) return STATUS_NOT_MAPPED_VIEW;
1051 if (!(status = server_get_unix_fd( view->mapping, 0, &unix_fd, &needs_close, NULL, NULL )))
1053 if (fstat( unix_fd, st ) == -1) status = FILE_GetNtStatus();
1054 if (needs_close) close( unix_fd );
1056 return status;
1059 /***********************************************************************
1060 * map_image
1062 * Map an executable (PE format) image into memory.
1064 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
1065 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, unsigned int map_vprot, PVOID *addr_ptr )
1067 IMAGE_DOS_HEADER *dos;
1068 IMAGE_NT_HEADERS *nt;
1069 IMAGE_SECTION_HEADER sections[96];
1070 IMAGE_SECTION_HEADER *sec;
1071 IMAGE_DATA_DIRECTORY *imports;
1072 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
1073 int i;
1074 off_t pos;
1075 sigset_t sigset;
1076 struct stat st;
1077 struct file_view *view = NULL;
1078 char *ptr, *header_end, *header_start;
1080 /* zero-map the whole range */
1082 server_enter_uninterrupted_section( &csVirtual, &sigset );
1084 if (base >= (char *)address_space_start) /* make sure the DOS area remains free */
1085 status = map_view( &view, base, total_size, mask, FALSE,
1086 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1088 if (status != STATUS_SUCCESS)
1089 status = map_view( &view, NULL, total_size, mask, FALSE,
1090 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1092 if (status != STATUS_SUCCESS) goto error;
1094 ptr = view->base;
1095 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1097 /* map the header */
1099 if (fstat( fd, &st ) == -1)
1101 status = FILE_GetNtStatus();
1102 goto error;
1104 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1105 if (!st.st_size) goto error;
1106 header_size = min( header_size, st.st_size );
1107 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1108 !dup_mapping ) != STATUS_SUCCESS) goto error;
1109 dos = (IMAGE_DOS_HEADER *)ptr;
1110 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1111 header_end = ptr + ROUND_SIZE( 0, header_size );
1112 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1113 if ((char *)(nt + 1) > header_end) goto error;
1114 header_start = (char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader;
1115 if (nt->FileHeader.NumberOfSections > sizeof(sections)/sizeof(*sections)) goto error;
1116 if (header_start + sizeof(*sections) * nt->FileHeader.NumberOfSections > header_end) goto error;
1117 /* Some applications (e.g. the Steam version of Borderlands) map over the top of the section headers,
1118 * copying the headers into local memory is necessary to properly load such applications. */
1119 memcpy(sections, header_start, sizeof(*sections) * nt->FileHeader.NumberOfSections);
1120 sec = sections;
1122 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1123 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1125 /* check for non page-aligned binary */
1127 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1129 /* unaligned sections, this happens for native subsystem binaries */
1130 /* in that case Windows simply maps in the whole file */
1132 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1133 !dup_mapping ) != STATUS_SUCCESS) goto error;
1135 /* check that all sections are loaded at the right offset */
1136 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1137 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1139 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1140 goto error; /* Windows refuses to load in that case too */
1143 /* set the image protections */
1144 VIRTUAL_SetProt( view, ptr, total_size,
1145 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1147 /* no relocations are performed on non page-aligned binaries */
1148 goto done;
1152 /* map all the sections */
1154 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1156 static const SIZE_T sector_align = 0x1ff;
1157 SIZE_T map_size, file_start, file_size, end;
1159 if (!sec->Misc.VirtualSize)
1160 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1161 else
1162 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1164 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1165 file_start = sec->PointerToRawData & ~sector_align;
1166 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1167 if (file_size > map_size) file_size = map_size;
1169 /* a few sanity checks */
1170 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1171 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1173 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1174 sec->Name, sec->VirtualAddress, map_size, total_size );
1175 goto error;
1178 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1179 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1181 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1182 sec->Name, ptr + sec->VirtualAddress,
1183 sec->PointerToRawData, (int)pos, file_size, map_size,
1184 sec->Characteristics );
1185 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1186 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE, FALSE ) != STATUS_SUCCESS)
1188 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1189 goto error;
1192 /* check if the import directory falls inside this section */
1193 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1194 imports->VirtualAddress < sec->VirtualAddress + map_size)
1196 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1197 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1198 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1199 if (end > base)
1200 map_file_into_view( view, shared_fd, base, end - base,
1201 pos + (base - sec->VirtualAddress),
1202 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY, FALSE );
1204 pos += map_size;
1205 continue;
1208 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1209 sec->Name, ptr + sec->VirtualAddress,
1210 sec->PointerToRawData, sec->SizeOfRawData,
1211 sec->Misc.VirtualSize, sec->Characteristics );
1213 if (!sec->PointerToRawData || !file_size) continue;
1215 /* Note: if the section is not aligned properly map_file_into_view will magically
1216 * fall back to read(), so we don't need to check anything here.
1218 end = file_start + file_size;
1219 if (sec->PointerToRawData >= st.st_size ||
1220 end > ((st.st_size + sector_align) & ~sector_align) ||
1221 end < file_start ||
1222 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1223 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1224 !dup_mapping ) != STATUS_SUCCESS)
1226 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1227 goto error;
1230 if (file_size & page_mask)
1232 end = ROUND_SIZE( 0, file_size );
1233 if (end > map_size) end = map_size;
1234 TRACE_(module)("clearing %p - %p\n",
1235 ptr + sec->VirtualAddress + file_size,
1236 ptr + sec->VirtualAddress + end );
1237 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1241 /* set the image protections */
1243 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1245 sec = sections;
1246 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1248 SIZE_T size;
1249 BYTE vprot = VPROT_COMMITTED;
1251 if (sec->Misc.VirtualSize)
1252 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1253 else
1254 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1256 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1257 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITECOPY;
1258 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1260 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1261 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1262 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1263 vprot |= VPROT_EXEC;
1265 if (!VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot ) && (vprot & VPROT_EXEC))
1266 ERR( "failed to set %08x protection on section %.8s, noexec filesystem?\n",
1267 sec->Characteristics, sec->Name );
1270 done:
1271 view->mapping = dup_mapping;
1272 view->map_protect = map_vprot;
1273 server_leave_uninterrupted_section( &csVirtual, &sigset );
1275 *addr_ptr = ptr;
1276 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1277 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, ptr - base);
1278 #endif
1279 if (ptr != base) return STATUS_IMAGE_NOT_AT_BASE;
1280 return STATUS_SUCCESS;
1282 error:
1283 if (view) delete_view( view );
1284 server_leave_uninterrupted_section( &csVirtual, &sigset );
1285 if (dup_mapping) close_handle( dup_mapping );
1286 return status;
1290 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1291 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1293 void **heap_base = arg;
1295 if (is_beyond_limit( base, size, address_space_limit )) address_space_limit = (char *)base + size;
1296 if (size < VIRTUAL_HEAP_SIZE) return 0;
1297 if (is_win64 && base < (void *)0x80000000) return 0;
1298 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1299 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1300 return (*heap_base != (void *)-1);
1303 /***********************************************************************
1304 * virtual_init
1306 void virtual_init(void)
1308 const char *preload;
1309 void *heap_base;
1310 size_t size;
1311 struct file_view *heap_view;
1313 #if !defined(__i386__) && !defined(__x86_64__)
1314 page_size = sysconf( _SC_PAGESIZE );
1315 page_mask = page_size - 1;
1316 /* Make sure we have a power of 2 */
1317 assert( !(page_size & page_mask) );
1318 page_shift = 0;
1319 while ((1 << page_shift) != page_size) page_shift++;
1320 user_space_limit = working_set_limit = address_space_limit = (void *)~page_mask;
1321 #endif /* page_mask */
1322 if ((preload = getenv("WINEPRELOADRESERVE")))
1324 unsigned long start, end;
1325 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1327 preload_reserve_start = (void *)start;
1328 preload_reserve_end = (void *)end;
1332 /* try to find space in a reserved area for the virtual heap */
1333 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1334 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1336 assert( heap_base != (void *)-1 );
1337 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1338 VIRTUAL_HEAP_SIZE, NULL, NULL );
1339 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1341 /* make the DOS area accessible (except the low 64K) to hide bugs in broken apps like Excel 2003 */
1342 size = (char *)address_space_start - (char *)0x10000;
1343 if (size && wine_mmap_is_in_reserved_area( (void*)0x10000, size ) == 1)
1344 wine_anon_mmap( (void *)0x10000, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1348 /***********************************************************************
1349 * virtual_init_threading
1351 void virtual_init_threading(void)
1353 use_locks = TRUE;
1357 /***********************************************************************
1358 * virtual_get_system_info
1360 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1362 #ifdef HAVE_SYS_SYSINFO_H
1363 struct sysinfo sinfo;
1364 #endif
1366 info->unknown = 0;
1367 info->KeMaximumIncrement = 0; /* FIXME */
1368 info->PageSize = page_size;
1369 info->MmLowestPhysicalPage = 1;
1370 info->MmHighestPhysicalPage = 0x7fffffff / page_size;
1371 #ifdef HAVE_SYS_SYSINFO_H
1372 if (!sysinfo(&sinfo))
1374 ULONG64 total = (ULONG64)sinfo.totalram * sinfo.mem_unit;
1375 info->MmHighestPhysicalPage = max(1, total / page_size);
1377 #endif
1378 info->MmNumberOfPhysicalPages = info->MmHighestPhysicalPage - info->MmLowestPhysicalPage;
1379 info->AllocationGranularity = get_mask(0) + 1;
1380 info->LowestUserAddress = (void *)0x10000;
1381 info->HighestUserAddress = (char *)user_space_limit - 1;
1382 info->ActiveProcessorsAffinityMask = get_system_affinity_mask();
1383 info->NumberOfProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1387 /***********************************************************************
1388 * virtual_create_builtin_view
1390 NTSTATUS virtual_create_builtin_view( void *module )
1392 NTSTATUS status;
1393 sigset_t sigset;
1394 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1395 SIZE_T size = nt->OptionalHeader.SizeOfImage;
1396 IMAGE_SECTION_HEADER *sec;
1397 struct file_view *view;
1398 void *base;
1399 int i;
1401 size = ROUND_SIZE( module, size );
1402 base = ROUND_ADDR( module, page_mask );
1403 server_enter_uninterrupted_section( &csVirtual, &sigset );
1404 status = create_view( &view, base, size, VPROT_SYSTEM | VPROT_IMAGE |
1405 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1406 if (!status) TRACE( "created %p-%p\n", base, (char *)base + size );
1407 server_leave_uninterrupted_section( &csVirtual, &sigset );
1409 if (status) return status;
1411 /* The PE header is always read-only, no write, no execute. */
1412 view->prot[0] = VPROT_COMMITTED | VPROT_READ;
1414 sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
1415 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1417 BYTE flags = VPROT_COMMITTED;
1419 if (sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) flags |= VPROT_EXEC;
1420 if (sec[i].Characteristics & IMAGE_SCN_MEM_READ) flags |= VPROT_READ;
1421 if (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE) flags |= VPROT_WRITE;
1422 memset (view->prot + (sec[i].VirtualAddress >> page_shift), flags,
1423 ROUND_SIZE( sec[i].VirtualAddress, sec[i].Misc.VirtualSize ) >> page_shift );
1426 return status;
1430 /***********************************************************************
1431 * virtual_alloc_thread_stack
1433 NTSTATUS virtual_alloc_thread_stack( TEB *teb, SIZE_T reserve_size, SIZE_T commit_size )
1435 struct file_view *view;
1436 NTSTATUS status;
1437 sigset_t sigset;
1438 SIZE_T size;
1440 if (!reserve_size || !commit_size)
1442 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1443 if (!reserve_size) reserve_size = nt->OptionalHeader.SizeOfStackReserve;
1444 if (!commit_size) commit_size = nt->OptionalHeader.SizeOfStackCommit;
1447 size = max( reserve_size, commit_size );
1448 if (size < 1024 * 1024) size = 1024 * 1024; /* Xlib needs a large stack */
1449 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1451 server_enter_uninterrupted_section( &csVirtual, &sigset );
1453 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1454 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1455 goto done;
1457 #ifdef VALGRIND_STACK_REGISTER
1458 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1459 #endif
1461 /* setup no access guard page */
1462 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1463 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1464 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1466 /* note: limit is lower than base since the stack grows down */
1467 teb->DeallocationStack = view->base;
1468 teb->Tib.StackBase = (char *)view->base + view->size;
1469 teb->Tib.StackLimit = (char *)view->base + 2 * page_size;
1470 done:
1471 server_leave_uninterrupted_section( &csVirtual, &sigset );
1472 return status;
1476 /***********************************************************************
1477 * virtual_clear_thread_stack
1479 * Clear the stack contents before calling the main entry point, some broken apps need that.
1481 void virtual_clear_thread_stack(void)
1483 void *stack = NtCurrentTeb()->Tib.StackLimit;
1484 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1486 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1487 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1491 /***********************************************************************
1492 * virtual_handle_fault
1494 NTSTATUS virtual_handle_fault( LPCVOID addr, DWORD err, BOOL on_signal_stack )
1496 struct file_view *view;
1497 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1498 sigset_t sigset;
1500 server_enter_uninterrupted_section( &csVirtual, &sigset );
1501 if ((view = VIRTUAL_FindView( addr, 0 )))
1503 void *page = ROUND_ADDR( addr, page_mask );
1504 BYTE *vprot = &view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1505 if ((err & EXCEPTION_WRITE_FAULT) && (view->protect & VPROT_WRITEWATCH))
1507 if (*vprot & VPROT_WRITEWATCH)
1509 *vprot &= ~VPROT_WRITEWATCH;
1510 VIRTUAL_SetProt( view, page, page_size, *vprot );
1512 /* ignore fault if page is writable now */
1513 if (VIRTUAL_GetUnixProt( *vprot ) & PROT_WRITE) ret = STATUS_SUCCESS;
1515 if (!on_signal_stack && (*vprot & VPROT_GUARD))
1517 VIRTUAL_SetProt( view, page, page_size, *vprot & ~VPROT_GUARD );
1518 ret = STATUS_GUARD_PAGE_VIOLATION;
1521 server_leave_uninterrupted_section( &csVirtual, &sigset );
1522 return ret;
1527 /***********************************************************************
1528 * virtual_is_valid_code_address
1530 BOOL virtual_is_valid_code_address( const void *addr, SIZE_T size )
1532 struct file_view *view;
1533 BOOL ret = FALSE;
1534 sigset_t sigset;
1536 server_enter_uninterrupted_section( &csVirtual, &sigset );
1537 if ((view = VIRTUAL_FindView( addr, size )))
1538 ret = !(view->protect & VPROT_SYSTEM); /* system views are not visible to the app */
1539 server_leave_uninterrupted_section( &csVirtual, &sigset );
1540 return ret;
1544 /***********************************************************************
1545 * virtual_handle_stack_fault
1547 * Handle an access fault inside the current thread stack.
1548 * Called from inside a signal handler.
1550 BOOL virtual_handle_stack_fault( void *addr )
1552 struct file_view *view;
1553 BOOL ret = FALSE;
1555 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1556 if ((view = VIRTUAL_FindView( addr, 0 )))
1558 void *page = ROUND_ADDR( addr, page_mask );
1559 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1560 if (vprot & VPROT_GUARD)
1562 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1563 NtCurrentTeb()->Tib.StackLimit = page;
1564 if ((char *)page >= (char *)NtCurrentTeb()->DeallocationStack + 2*page_size)
1566 vprot = view->prot[((char *)page - page_size - (char *)view->base) >> page_shift];
1567 VIRTUAL_SetProt( view, (char *)page - page_size, page_size, vprot | VPROT_COMMITTED | VPROT_GUARD );
1569 ret = TRUE;
1572 RtlLeaveCriticalSection( &csVirtual );
1573 return ret;
1577 /***********************************************************************
1578 * virtual_check_buffer_for_read
1580 * Check if a memory buffer can be read, triggering page faults if needed for DIB section access.
1582 BOOL virtual_check_buffer_for_read( const void *ptr, SIZE_T size )
1584 if (!size) return TRUE;
1585 if (!ptr) return FALSE;
1587 __TRY
1589 volatile const char *p = ptr;
1590 char dummy __attribute__((unused));
1591 SIZE_T count = size;
1593 while (count > page_size)
1595 dummy = *p;
1596 p += page_size;
1597 count -= page_size;
1599 dummy = p[0];
1600 dummy = p[count - 1];
1602 __EXCEPT_PAGE_FAULT
1604 return FALSE;
1606 __ENDTRY
1607 return TRUE;
1611 /***********************************************************************
1612 * virtual_check_buffer_for_write
1614 * Check if a memory buffer can be written to, triggering page faults if needed for write watches.
1616 BOOL virtual_check_buffer_for_write( void *ptr, SIZE_T size )
1618 if (!size) return TRUE;
1619 if (!ptr) return FALSE;
1621 __TRY
1623 volatile char *p = ptr;
1624 SIZE_T count = size;
1626 while (count > page_size)
1628 *p |= 0;
1629 p += page_size;
1630 count -= page_size;
1632 p[0] |= 0;
1633 p[count - 1] |= 0;
1635 __EXCEPT_PAGE_FAULT
1637 return FALSE;
1639 __ENDTRY
1640 return TRUE;
1644 /***********************************************************************
1645 * virtual_uninterrupted_read_memory
1647 * Similar to NtReadVirtualMemory, but without wineserver calls. Moreover
1648 * permissions are checked before accessing each page, to ensure that no
1649 * exceptions can happen.
1651 SIZE_T virtual_uninterrupted_read_memory( const void *addr, void *buffer, SIZE_T size )
1653 struct file_view *view;
1654 sigset_t sigset;
1655 SIZE_T bytes_read = 0;
1657 if (!size) return 0;
1659 server_enter_uninterrupted_section( &csVirtual, &sigset );
1660 if ((view = VIRTUAL_FindView( addr, size )))
1662 if (!(view->protect & VPROT_SYSTEM))
1664 void *page = ROUND_ADDR( addr, page_mask );
1665 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1667 while (bytes_read < size && (VIRTUAL_GetUnixProt( *p++ ) & PROT_READ))
1669 SIZE_T block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1670 memcpy( buffer, addr, block_size );
1672 addr = (const void *)((const char *)addr + block_size);
1673 buffer = (void *)((char *)buffer + block_size);
1674 bytes_read += block_size;
1678 server_leave_uninterrupted_section( &csVirtual, &sigset );
1679 return bytes_read;
1683 /***********************************************************************
1684 * virtual_uninterrupted_write_memory
1686 * Similar to NtWriteVirtualMemory, but without wineserver calls. Moreover
1687 * permissions are checked before accessing each page, to ensure that no
1688 * exceptions can happen.
1690 SIZE_T virtual_uninterrupted_write_memory( void *addr, const void *buffer, SIZE_T size )
1692 struct file_view *view;
1693 sigset_t sigset;
1694 SIZE_T bytes_written = 0;
1696 if (!size) return 0;
1698 server_enter_uninterrupted_section( &csVirtual, &sigset );
1699 if ((view = VIRTUAL_FindView( addr, size )))
1701 if (!(view->protect & VPROT_SYSTEM))
1703 while (bytes_written < size)
1705 void *page = ROUND_ADDR( addr, page_mask );
1706 BYTE *p = view->prot + (((const char *)page - (const char *)view->base) >> page_shift);
1707 SIZE_T block_size;
1709 /* If the page is not writable then check for write watches
1710 * before giving up. This can be done without raising a real
1711 * exception. Similar to virtual_handle_fault. */
1712 if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
1714 if (!(view->protect & VPROT_WRITEWATCH))
1715 break;
1717 if (*p & VPROT_WRITEWATCH)
1719 *p &= ~VPROT_WRITEWATCH;
1720 VIRTUAL_SetProt( view, page, page_size, *p );
1722 /* ignore fault if page is writable now */
1723 if (!(VIRTUAL_GetUnixProt( *p ) & PROT_WRITE))
1724 break;
1727 block_size = min( size, page_size - ((UINT_PTR)addr & page_mask) );
1728 memcpy( addr, buffer, block_size );
1730 addr = (void *)((char *)addr + block_size);
1731 buffer = (const void *)((const char *)buffer + block_size);
1732 bytes_written += block_size;
1736 server_leave_uninterrupted_section( &csVirtual, &sigset );
1737 return bytes_written;
1741 /***********************************************************************
1742 * VIRTUAL_SetForceExec
1744 * Whether to force exec prot on all views.
1746 void VIRTUAL_SetForceExec( BOOL enable )
1748 struct file_view *view;
1749 sigset_t sigset;
1751 server_enter_uninterrupted_section( &csVirtual, &sigset );
1752 if (!force_exec_prot != !enable) /* change all existing views */
1754 force_exec_prot = enable;
1756 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1758 UINT i, count;
1759 char *addr = view->base;
1760 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1761 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1763 if (view->protect & VPROT_NOEXEC) continue;
1764 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1766 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1767 if (prot == unix_prot) continue;
1768 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1770 TRACE( "%s exec prot for %p-%p\n",
1771 force_exec_prot ? "enabling" : "disabling",
1772 addr, addr + (count << page_shift) - 1 );
1773 mprotect( addr, count << page_shift,
1774 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1776 addr += (count << page_shift);
1777 unix_prot = prot;
1778 count = 0;
1780 if (count)
1782 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1784 TRACE( "%s exec prot for %p-%p\n",
1785 force_exec_prot ? "enabling" : "disabling",
1786 addr, addr + (count << page_shift) - 1 );
1787 mprotect( addr, count << page_shift,
1788 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1793 server_leave_uninterrupted_section( &csVirtual, &sigset );
1796 struct free_range
1798 char *base;
1799 char *limit;
1802 /* free reserved areas above the limit; callback for wine_mmap_enum_reserved_areas */
1803 static int free_reserved_memory( void *base, size_t size, void *arg )
1805 struct free_range *range = arg;
1807 if ((char *)base >= range->limit) return 0;
1808 if ((char *)base + size <= range->base) return 0;
1809 if ((char *)base < range->base)
1811 size -= range->base - (char *)base;
1812 base = range->base;
1814 if ((char *)base + size > range->limit) size = range->limit - (char *)base;
1815 remove_reserved_area( base, size );
1816 return 1; /* stop enumeration since the list has changed */
1819 /***********************************************************************
1820 * virtual_release_address_space
1822 * Release some address space once we have loaded and initialized the app.
1824 void virtual_release_address_space(void)
1826 struct free_range range;
1827 sigset_t sigset;
1829 if (is_win64) return;
1831 server_enter_uninterrupted_section( &csVirtual, &sigset );
1833 range.base = (char *)0x82000000;
1834 range.limit = user_space_limit;
1836 if (range.limit > range.base)
1838 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 1 )) /* nothing */;
1840 else
1842 #ifndef __APPLE__ /* dyld doesn't support parts of the WINE_DOS segment being unmapped */
1843 range.base = (char *)0x20000000;
1844 range.limit = (char *)0x7f000000;
1845 while (wine_mmap_enum_reserved_areas( free_reserved_memory, &range, 0 )) /* nothing */;
1846 #endif
1849 server_leave_uninterrupted_section( &csVirtual, &sigset );
1853 /***********************************************************************
1854 * virtual_set_large_address_space
1856 * Enable use of a large address space when allowed by the application.
1858 void virtual_set_large_address_space(void)
1860 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
1862 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)) return;
1863 /* no large address space on win9x */
1864 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1866 user_space_limit = working_set_limit = address_space_limit;
1870 /***********************************************************************
1871 * NtAllocateVirtualMemory (NTDLL.@)
1872 * ZwAllocateVirtualMemory (NTDLL.@)
1874 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1875 SIZE_T *size_ptr, ULONG type, ULONG protect )
1877 void *base;
1878 unsigned int vprot;
1879 SIZE_T size = *size_ptr;
1880 SIZE_T mask = get_mask( zero_bits );
1881 NTSTATUS status = STATUS_SUCCESS;
1882 struct file_view *view;
1883 sigset_t sigset;
1885 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1887 if (!size) return STATUS_INVALID_PARAMETER;
1889 if (process != NtCurrentProcess())
1891 apc_call_t call;
1892 apc_result_t result;
1894 memset( &call, 0, sizeof(call) );
1896 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1897 call.virtual_alloc.addr = wine_server_client_ptr( *ret );
1898 call.virtual_alloc.size = *size_ptr;
1899 call.virtual_alloc.zero_bits = zero_bits;
1900 call.virtual_alloc.op_type = type;
1901 call.virtual_alloc.prot = protect;
1902 status = server_queue_process_apc( process, &call, &result );
1903 if (status != STATUS_SUCCESS) return status;
1905 if (result.virtual_alloc.status == STATUS_SUCCESS)
1907 *ret = wine_server_get_ptr( result.virtual_alloc.addr );
1908 *size_ptr = result.virtual_alloc.size;
1910 return result.virtual_alloc.status;
1913 /* Round parameters to a page boundary */
1915 if (is_beyond_limit( 0, size, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
1917 if ((status = get_vprot_flags( protect, &vprot, FALSE ))) return status;
1918 if (vprot & VPROT_WRITECOPY) return STATUS_INVALID_PAGE_PROTECTION;
1919 vprot |= VPROT_VALLOC;
1920 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1922 if (*ret)
1924 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1925 base = ROUND_ADDR( *ret, mask );
1926 else
1927 base = ROUND_ADDR( *ret, page_mask );
1928 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1930 /* address 1 is magic to mean DOS area */
1931 if (!base && *ret == (void *)1 && size == 0x110000)
1933 server_enter_uninterrupted_section( &csVirtual, &sigset );
1934 status = allocate_dos_memory( &view, vprot );
1935 if (status == STATUS_SUCCESS)
1937 *ret = view->base;
1938 *size_ptr = view->size;
1940 server_leave_uninterrupted_section( &csVirtual, &sigset );
1941 return status;
1944 /* disallow low 64k, wrap-around and kernel space */
1945 if (((char *)base < (char *)0x10000) ||
1946 ((char *)base + size < (char *)base) ||
1947 is_beyond_limit( base, size, address_space_limit ))
1948 return STATUS_INVALID_PARAMETER;
1950 else
1952 base = NULL;
1953 size = (size + page_mask) & ~page_mask;
1956 /* Compute the alloc type flags */
1958 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) ||
1959 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1961 WARN("called with wrong alloc type flags (%08x) !\n", type);
1962 return STATUS_INVALID_PARAMETER;
1965 /* Reserve the memory */
1967 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1969 if ((type & MEM_RESERVE) || !base)
1971 if (type & MEM_WRITE_WATCH) vprot |= VPROT_WRITEWATCH;
1972 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1973 if (status == STATUS_SUCCESS) base = view->base;
1975 else if (type & MEM_RESET)
1977 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1978 else madvise( base, size, MADV_DONTNEED );
1980 else /* commit the pages */
1982 if (!(view = VIRTUAL_FindView( base, size ))) status = STATUS_NOT_MAPPED_VIEW;
1983 else if (view->mapping && (view->protect & VPROT_COMMITTED)) status = STATUS_ALREADY_COMMITTED;
1984 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1985 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1987 SERVER_START_REQ( add_mapping_committed_range )
1989 req->handle = wine_server_obj_handle( view->mapping );
1990 req->offset = (char *)base - (char *)view->base;
1991 req->size = size;
1992 wine_server_call( req );
1994 SERVER_END_REQ;
1998 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
2000 if (status == STATUS_SUCCESS)
2002 *ret = base;
2003 *size_ptr = size;
2005 return status;
2009 /***********************************************************************
2010 * NtFreeVirtualMemory (NTDLL.@)
2011 * ZwFreeVirtualMemory (NTDLL.@)
2013 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
2015 struct file_view *view;
2016 char *base;
2017 sigset_t sigset;
2018 NTSTATUS status = STATUS_SUCCESS;
2019 LPVOID addr = *addr_ptr;
2020 SIZE_T size = *size_ptr;
2022 TRACE("%p %p %08lx %x\n", process, addr, size, type );
2024 if (process != NtCurrentProcess())
2026 apc_call_t call;
2027 apc_result_t result;
2029 memset( &call, 0, sizeof(call) );
2031 call.virtual_free.type = APC_VIRTUAL_FREE;
2032 call.virtual_free.addr = wine_server_client_ptr( addr );
2033 call.virtual_free.size = size;
2034 call.virtual_free.op_type = type;
2035 status = server_queue_process_apc( process, &call, &result );
2036 if (status != STATUS_SUCCESS) return status;
2038 if (result.virtual_free.status == STATUS_SUCCESS)
2040 *addr_ptr = wine_server_get_ptr( result.virtual_free.addr );
2041 *size_ptr = result.virtual_free.size;
2043 return result.virtual_free.status;
2046 /* Fix the parameters */
2048 size = ROUND_SIZE( addr, size );
2049 base = ROUND_ADDR( addr, page_mask );
2051 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
2052 if (!base) return STATUS_INVALID_PARAMETER;
2054 server_enter_uninterrupted_section( &csVirtual, &sigset );
2056 if (!(view = VIRTUAL_FindView( base, size )) || !(view->protect & VPROT_VALLOC))
2058 status = STATUS_INVALID_PARAMETER;
2060 else if (type == MEM_RELEASE)
2062 /* Free the pages */
2064 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
2065 else
2067 delete_view( view );
2068 *addr_ptr = base;
2069 *size_ptr = size;
2072 else if (type == MEM_DECOMMIT)
2074 status = decommit_pages( view, base - (char *)view->base, size );
2075 if (status == STATUS_SUCCESS)
2077 *addr_ptr = base;
2078 *size_ptr = size;
2081 else
2083 WARN("called with wrong free type flags (%08x) !\n", type);
2084 status = STATUS_INVALID_PARAMETER;
2087 server_leave_uninterrupted_section( &csVirtual, &sigset );
2088 return status;
2091 static ULONG map_protection_to_access( ULONG vprot )
2093 vprot &= VPROT_READ | VPROT_WRITE | VPROT_EXEC | VPROT_WRITECOPY;
2094 if (vprot & VPROT_EXEC)
2096 if (vprot & VPROT_WRITE) vprot |= VPROT_WRITECOPY;
2098 else vprot &= ~VPROT_WRITECOPY;
2099 return vprot;
2102 static BOOL is_compatible_protection( const struct file_view *view, ULONG new_prot )
2104 ULONG view_prot, map_prot;
2106 view_prot = map_protection_to_access( view->protect );
2107 new_prot = map_protection_to_access( new_prot );
2109 if (view_prot == new_prot) return TRUE;
2110 if (!view_prot) return FALSE;
2112 if ((view_prot & new_prot) != new_prot) return FALSE;
2114 map_prot = map_protection_to_access( view->map_protect );
2115 if ((map_prot & new_prot) == new_prot) return TRUE;
2117 return FALSE;
2120 /***********************************************************************
2121 * NtProtectVirtualMemory (NTDLL.@)
2122 * ZwProtectVirtualMemory (NTDLL.@)
2124 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
2125 ULONG new_prot, ULONG *old_prot )
2127 struct file_view *view;
2128 sigset_t sigset;
2129 NTSTATUS status = STATUS_SUCCESS;
2130 char *base;
2131 BYTE vprot;
2132 unsigned int new_vprot;
2133 SIZE_T size = *size_ptr;
2134 LPVOID addr = *addr_ptr;
2136 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
2138 if (!old_prot)
2139 return STATUS_ACCESS_VIOLATION;
2141 if (process != NtCurrentProcess())
2143 apc_call_t call;
2144 apc_result_t result;
2146 memset( &call, 0, sizeof(call) );
2148 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
2149 call.virtual_protect.addr = wine_server_client_ptr( addr );
2150 call.virtual_protect.size = size;
2151 call.virtual_protect.prot = new_prot;
2152 status = server_queue_process_apc( process, &call, &result );
2153 if (status != STATUS_SUCCESS) return status;
2155 if (result.virtual_protect.status == STATUS_SUCCESS)
2157 *addr_ptr = wine_server_get_ptr( result.virtual_protect.addr );
2158 *size_ptr = result.virtual_protect.size;
2159 if (old_prot) *old_prot = result.virtual_protect.prot;
2161 return result.virtual_protect.status;
2164 /* Fix the parameters */
2166 size = ROUND_SIZE( addr, size );
2167 base = ROUND_ADDR( addr, page_mask );
2169 server_enter_uninterrupted_section( &csVirtual, &sigset );
2171 if ((view = VIRTUAL_FindView( base, size )))
2173 /* Make sure all the pages are committed */
2174 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
2176 if (!(status = get_vprot_flags( new_prot, &new_vprot, view->protect & VPROT_IMAGE )))
2178 if ((new_vprot & VPROT_WRITECOPY) && (view->protect & VPROT_VALLOC))
2179 status = STATUS_INVALID_PAGE_PROTECTION;
2180 else
2182 if (!view->mapping || is_compatible_protection( view, new_vprot ))
2184 new_vprot |= VPROT_COMMITTED;
2185 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
2186 if (!VIRTUAL_SetProt( view, base, size, new_vprot )) status = STATUS_ACCESS_DENIED;
2188 else status = STATUS_INVALID_PAGE_PROTECTION;
2192 else status = STATUS_NOT_COMMITTED;
2194 else status = STATUS_INVALID_PARAMETER;
2196 server_leave_uninterrupted_section( &csVirtual, &sigset );
2198 if (status == STATUS_SUCCESS)
2200 *addr_ptr = base;
2201 *size_ptr = size;
2203 return status;
2207 /* retrieve state for a free memory area; callback for wine_mmap_enum_reserved_areas */
2208 static int get_free_mem_state_callback( void *start, size_t size, void *arg )
2210 MEMORY_BASIC_INFORMATION *info = arg;
2211 void *end = (char *)start + size;
2213 if ((char *)info->BaseAddress + info->RegionSize < (char *)start) return 0;
2215 if (info->BaseAddress >= end)
2217 if (info->AllocationBase < end) info->AllocationBase = end;
2218 return 0;
2221 if (info->BaseAddress >= start || start <= address_space_start)
2223 /* it's a real free area */
2224 info->State = MEM_FREE;
2225 info->Protect = PAGE_NOACCESS;
2226 info->AllocationBase = 0;
2227 info->AllocationProtect = 0;
2228 info->Type = 0;
2229 if ((char *)info->BaseAddress + info->RegionSize > (char *)end)
2230 info->RegionSize = (char *)end - (char *)info->BaseAddress;
2232 else /* outside of the reserved area, pretend it's allocated */
2234 info->RegionSize = (char *)start - (char *)info->BaseAddress;
2235 info->State = MEM_RESERVE;
2236 info->Protect = PAGE_NOACCESS;
2237 info->AllocationProtect = PAGE_NOACCESS;
2238 info->Type = MEM_PRIVATE;
2240 return 1;
2243 #define UNIMPLEMENTED_INFO_CLASS(c) \
2244 case c: \
2245 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
2246 return STATUS_INVALID_INFO_CLASS
2248 /***********************************************************************
2249 * NtQueryVirtualMemory (NTDLL.@)
2250 * ZwQueryVirtualMemory (NTDLL.@)
2252 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
2253 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
2254 SIZE_T len, SIZE_T *res_len )
2256 struct file_view *view;
2257 char *base, *alloc_base = 0;
2258 struct list *ptr;
2259 SIZE_T size = 0;
2260 MEMORY_BASIC_INFORMATION *info = buffer;
2261 sigset_t sigset;
2263 if (info_class != MemoryBasicInformation)
2265 switch(info_class)
2267 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
2268 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
2269 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
2271 default:
2272 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
2273 process, addr, info_class, buffer, len, res_len);
2274 return STATUS_INVALID_INFO_CLASS;
2278 if (process != NtCurrentProcess())
2280 NTSTATUS status;
2281 apc_call_t call;
2282 apc_result_t result;
2284 memset( &call, 0, sizeof(call) );
2286 call.virtual_query.type = APC_VIRTUAL_QUERY;
2287 call.virtual_query.addr = wine_server_client_ptr( addr );
2288 status = server_queue_process_apc( process, &call, &result );
2289 if (status != STATUS_SUCCESS) return status;
2291 if (result.virtual_query.status == STATUS_SUCCESS)
2293 info->BaseAddress = wine_server_get_ptr( result.virtual_query.base );
2294 info->AllocationBase = wine_server_get_ptr( result.virtual_query.alloc_base );
2295 info->RegionSize = result.virtual_query.size;
2296 info->Protect = result.virtual_query.prot;
2297 info->AllocationProtect = result.virtual_query.alloc_prot;
2298 info->State = (DWORD)result.virtual_query.state << 12;
2299 info->Type = (DWORD)result.virtual_query.alloc_type << 16;
2300 if (info->RegionSize != result.virtual_query.size) /* truncated */
2301 return STATUS_INVALID_PARAMETER; /* FIXME */
2302 if (res_len) *res_len = sizeof(*info);
2304 return result.virtual_query.status;
2307 base = ROUND_ADDR( addr, page_mask );
2309 if (is_beyond_limit( base, 1, working_set_limit )) return STATUS_WORKING_SET_LIMIT_RANGE;
2311 /* Find the view containing the address */
2313 server_enter_uninterrupted_section( &csVirtual, &sigset );
2314 ptr = list_head( &views_list );
2315 for (;;)
2317 if (!ptr)
2319 size = (char *)working_set_limit - alloc_base;
2320 view = NULL;
2321 break;
2323 view = LIST_ENTRY( ptr, struct file_view, entry );
2324 if ((char *)view->base > base)
2326 size = (char *)view->base - alloc_base;
2327 view = NULL;
2328 break;
2330 if ((char *)view->base + view->size > base)
2332 alloc_base = view->base;
2333 size = view->size;
2334 break;
2336 alloc_base = (char *)view->base + view->size;
2337 ptr = list_next( &views_list, ptr );
2340 /* Fill the info structure */
2342 info->AllocationBase = alloc_base;
2343 info->BaseAddress = base;
2344 info->RegionSize = size - (base - alloc_base);
2346 if (!view)
2348 if (!wine_mmap_enum_reserved_areas( get_free_mem_state_callback, info, 0 ))
2350 /* not in a reserved area at all, pretend it's allocated */
2351 #ifdef __i386__
2352 if (base >= (char *)address_space_start)
2354 info->State = MEM_RESERVE;
2355 info->Protect = PAGE_NOACCESS;
2356 info->AllocationProtect = PAGE_NOACCESS;
2357 info->Type = MEM_PRIVATE;
2359 else
2360 #endif
2362 info->State = MEM_FREE;
2363 info->Protect = PAGE_NOACCESS;
2364 info->AllocationBase = 0;
2365 info->AllocationProtect = 0;
2366 info->Type = 0;
2370 else
2372 BYTE vprot;
2373 SIZE_T range_size = get_committed_size( view, base, &vprot );
2375 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
2376 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
2377 info->AllocationBase = alloc_base;
2378 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
2379 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
2380 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
2381 else info->Type = MEM_MAPPED;
2382 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
2383 if ((view->prot[size >> page_shift] ^ vprot) & ~VPROT_WRITEWATCH) break;
2384 info->RegionSize = size - (base - alloc_base);
2386 server_leave_uninterrupted_section( &csVirtual, &sigset );
2388 if (res_len) *res_len = sizeof(*info);
2389 return STATUS_SUCCESS;
2393 /***********************************************************************
2394 * NtLockVirtualMemory (NTDLL.@)
2395 * ZwLockVirtualMemory (NTDLL.@)
2397 NTSTATUS WINAPI NtLockVirtualMemory( 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_lock.type = APC_VIRTUAL_LOCK;
2409 call.virtual_lock.addr = wine_server_client_ptr( *addr );
2410 call.virtual_lock.size = *size;
2411 status = server_queue_process_apc( process, &call, &result );
2412 if (status != STATUS_SUCCESS) return status;
2414 if (result.virtual_lock.status == STATUS_SUCCESS)
2416 *addr = wine_server_get_ptr( result.virtual_lock.addr );
2417 *size = result.virtual_lock.size;
2419 return result.virtual_lock.status;
2422 *size = ROUND_SIZE( *addr, *size );
2423 *addr = ROUND_ADDR( *addr, page_mask );
2425 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2426 return status;
2430 /***********************************************************************
2431 * NtUnlockVirtualMemory (NTDLL.@)
2432 * ZwUnlockVirtualMemory (NTDLL.@)
2434 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
2436 NTSTATUS status = STATUS_SUCCESS;
2438 if (process != NtCurrentProcess())
2440 apc_call_t call;
2441 apc_result_t result;
2443 memset( &call, 0, sizeof(call) );
2445 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
2446 call.virtual_unlock.addr = wine_server_client_ptr( *addr );
2447 call.virtual_unlock.size = *size;
2448 status = server_queue_process_apc( process, &call, &result );
2449 if (status != STATUS_SUCCESS) return status;
2451 if (result.virtual_unlock.status == STATUS_SUCCESS)
2453 *addr = wine_server_get_ptr( result.virtual_unlock.addr );
2454 *size = result.virtual_unlock.size;
2456 return result.virtual_unlock.status;
2459 *size = ROUND_SIZE( *addr, *size );
2460 *addr = ROUND_ADDR( *addr, page_mask );
2462 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
2463 return status;
2467 /***********************************************************************
2468 * NtCreateSection (NTDLL.@)
2469 * ZwCreateSection (NTDLL.@)
2471 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
2472 const LARGE_INTEGER *size, ULONG protect,
2473 ULONG sec_flags, HANDLE file )
2475 NTSTATUS ret;
2476 unsigned int vprot;
2477 data_size_t len;
2478 struct object_attributes *objattr;
2480 if ((ret = get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE ))) return ret;
2481 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
2483 SERVER_START_REQ( create_mapping )
2485 req->access = access;
2486 req->flags = sec_flags;
2487 req->file_handle = wine_server_obj_handle( file );
2488 req->size = size ? size->QuadPart : 0;
2489 req->protect = vprot;
2490 wine_server_add_data( req, objattr, len );
2491 ret = wine_server_call( req );
2492 *handle = wine_server_ptr_handle( reply->handle );
2494 SERVER_END_REQ;
2496 RtlFreeHeap( GetProcessHeap(), 0, objattr );
2497 return ret;
2501 /***********************************************************************
2502 * NtOpenSection (NTDLL.@)
2503 * ZwOpenSection (NTDLL.@)
2505 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2507 NTSTATUS ret;
2509 if ((ret = validate_open_object_attributes( attr ))) return ret;
2511 SERVER_START_REQ( open_mapping )
2513 req->access = access;
2514 req->attributes = attr->Attributes;
2515 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2516 if (attr->ObjectName)
2517 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
2518 ret = wine_server_call( req );
2519 *handle = wine_server_ptr_handle( reply->handle );
2521 SERVER_END_REQ;
2522 return ret;
2526 /***********************************************************************
2527 * NtMapViewOfSection (NTDLL.@)
2528 * ZwMapViewOfSection (NTDLL.@)
2530 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2531 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2532 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2534 NTSTATUS res;
2535 mem_size_t full_size;
2536 ACCESS_MASK access;
2537 SIZE_T size, mask = get_mask( zero_bits );
2538 int unix_handle = -1, needs_close;
2539 unsigned int map_vprot, vprot, sec_flags;
2540 void *base;
2541 struct file_view *view;
2542 DWORD header_size;
2543 HANDLE dup_mapping, shared_file;
2544 LARGE_INTEGER offset;
2545 sigset_t sigset;
2547 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2549 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2550 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, *size_ptr, protect );
2552 /* Check parameters */
2554 if (*addr_ptr && zero_bits)
2555 return STATUS_INVALID_PARAMETER_4;
2557 #ifndef _WIN64
2558 if (!is_wow64 && (alloc_type & AT_ROUND_TO_PAGE))
2560 *addr_ptr = ROUND_ADDR( *addr_ptr, page_mask );
2561 mask = page_mask;
2563 #endif
2565 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2566 return STATUS_MAPPED_ALIGNMENT;
2568 switch(protect)
2570 case PAGE_NOACCESS:
2571 access = SECTION_MAP_READ;
2572 break;
2573 case PAGE_READWRITE:
2574 case PAGE_EXECUTE_READWRITE:
2575 access = SECTION_MAP_WRITE;
2576 break;
2577 case PAGE_READONLY:
2578 case PAGE_WRITECOPY:
2579 case PAGE_EXECUTE:
2580 case PAGE_EXECUTE_READ:
2581 case PAGE_EXECUTE_WRITECOPY:
2582 access = SECTION_MAP_READ;
2583 break;
2584 default:
2585 return STATUS_INVALID_PAGE_PROTECTION;
2588 if (process != NtCurrentProcess())
2590 apc_call_t call;
2591 apc_result_t result;
2593 memset( &call, 0, sizeof(call) );
2595 call.map_view.type = APC_MAP_VIEW;
2596 call.map_view.handle = wine_server_obj_handle( handle );
2597 call.map_view.addr = wine_server_client_ptr( *addr_ptr );
2598 call.map_view.size = *size_ptr;
2599 call.map_view.offset = offset.QuadPart;
2600 call.map_view.zero_bits = zero_bits;
2601 call.map_view.alloc_type = alloc_type;
2602 call.map_view.prot = protect;
2603 res = server_queue_process_apc( process, &call, &result );
2604 if (res != STATUS_SUCCESS) return res;
2606 if ((NTSTATUS)result.map_view.status >= 0)
2608 *addr_ptr = wine_server_get_ptr( result.map_view.addr );
2609 *size_ptr = result.map_view.size;
2611 return result.map_view.status;
2614 SERVER_START_REQ( get_mapping_info )
2616 req->handle = wine_server_obj_handle( handle );
2617 req->access = access;
2618 res = wine_server_call( req );
2619 map_vprot = reply->protect;
2620 sec_flags = reply->flags;
2621 base = wine_server_get_ptr( reply->base );
2622 full_size = reply->size;
2623 header_size = reply->header_size;
2624 dup_mapping = wine_server_ptr_handle( reply->mapping );
2625 shared_file = wine_server_ptr_handle( reply->shared_file );
2626 if ((ULONG_PTR)base != reply->base) base = NULL;
2628 SERVER_END_REQ;
2629 if (res) return res;
2631 if (!(sec_flags & SEC_RESERVE)) map_vprot |= VPROT_COMMITTED;
2632 if (sec_flags & SEC_NOCACHE) map_vprot |= VPROT_NOCACHE;
2633 if (sec_flags & SEC_IMAGE) map_vprot |= VPROT_IMAGE;
2635 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2637 if (sec_flags & SEC_IMAGE)
2639 size = full_size;
2640 if (size != full_size) /* truncated */
2642 WARN( "Modules larger than 4Gb (%s) not supported\n", wine_dbgstr_longlong(full_size) );
2643 res = STATUS_INVALID_PARAMETER;
2644 goto done;
2646 if (shared_file)
2648 int shared_fd, shared_needs_close;
2650 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2651 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2652 res = map_image( handle, unix_handle, base, size, mask, header_size,
2653 shared_fd, dup_mapping, map_vprot, addr_ptr );
2654 if (shared_needs_close) close( shared_fd );
2655 close_handle( shared_file );
2657 else
2659 res = map_image( handle, unix_handle, base, size, mask, header_size,
2660 -1, dup_mapping, map_vprot, addr_ptr );
2662 if (needs_close) close( unix_handle );
2663 if (res >= 0) *size_ptr = size;
2664 return res;
2667 res = STATUS_INVALID_PARAMETER;
2668 if (offset.QuadPart >= full_size) goto done;
2669 if (*size_ptr)
2671 if (*size_ptr > full_size - offset.QuadPart) goto done;
2672 size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2673 if (size < *size_ptr) goto done; /* wrap-around */
2675 else
2677 size = full_size - offset.QuadPart;
2678 if (size != full_size - offset.QuadPart) /* truncated */
2680 WARN( "Files larger than 4Gb (%s) not supported on this platform\n",
2681 wine_dbgstr_longlong(full_size) );
2682 goto done;
2686 /* Reserve a properly aligned area */
2688 server_enter_uninterrupted_section( &csVirtual, &sigset );
2690 get_vprot_flags( protect, &vprot, sec_flags & SEC_IMAGE );
2691 vprot |= (map_vprot & VPROT_COMMITTED);
2692 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2693 if (res)
2695 server_leave_uninterrupted_section( &csVirtual, &sigset );
2696 goto done;
2699 /* Map the file */
2701 TRACE("handle=%p size=%lx offset=%x%08x\n",
2702 handle, size, offset.u.HighPart, offset.u.LowPart );
2704 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2705 if (res == STATUS_SUCCESS)
2707 *addr_ptr = view->base;
2708 *size_ptr = size;
2709 view->mapping = dup_mapping;
2710 view->map_protect = map_vprot;
2711 dup_mapping = 0; /* don't close it */
2713 else
2715 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2716 view->base, size, offset.u.HighPart, offset.u.LowPart );
2717 delete_view( view );
2720 server_leave_uninterrupted_section( &csVirtual, &sigset );
2722 done:
2723 if (dup_mapping) close_handle( dup_mapping );
2724 if (needs_close) close( unix_handle );
2725 return res;
2729 /***********************************************************************
2730 * NtUnmapViewOfSection (NTDLL.@)
2731 * ZwUnmapViewOfSection (NTDLL.@)
2733 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2735 struct file_view *view;
2736 NTSTATUS status = STATUS_NOT_MAPPED_VIEW;
2737 sigset_t sigset;
2739 if (process != NtCurrentProcess())
2741 apc_call_t call;
2742 apc_result_t result;
2744 memset( &call, 0, sizeof(call) );
2746 call.unmap_view.type = APC_UNMAP_VIEW;
2747 call.unmap_view.addr = wine_server_client_ptr( addr );
2748 status = server_queue_process_apc( process, &call, &result );
2749 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2750 return status;
2753 server_enter_uninterrupted_section( &csVirtual, &sigset );
2754 if ((view = VIRTUAL_FindView( addr, 0 )) && !(view->protect & VPROT_VALLOC))
2756 delete_view( view );
2757 status = STATUS_SUCCESS;
2759 server_leave_uninterrupted_section( &csVirtual, &sigset );
2760 return status;
2764 /******************************************************************************
2765 * NtQuerySection (NTDLL.@)
2766 * ZwQuerySection (NTDLL.@)
2768 NTSTATUS WINAPI NtQuerySection( HANDLE handle, SECTION_INFORMATION_CLASS class, void *ptr,
2769 ULONG size, ULONG *ret_size )
2771 NTSTATUS status;
2772 SECTION_BASIC_INFORMATION *basic_info = ptr;
2774 if (class != SectionBasicInformation)
2776 FIXME( "class %u not implemented\n", class );
2777 return STATUS_NOT_IMPLEMENTED;
2779 if (size < sizeof(*basic_info)) return STATUS_INFO_LENGTH_MISMATCH;
2781 SERVER_START_REQ( get_mapping_info )
2783 req->handle = wine_server_obj_handle( handle );
2784 req->access = SECTION_QUERY;
2785 if (!(status = wine_server_call( req )))
2787 basic_info->Attributes = reply->flags;
2788 basic_info->BaseAddress = NULL;
2789 basic_info->Size.QuadPart = reply->size;
2790 if (ret_size) *ret_size = sizeof(*basic_info);
2793 SERVER_END_REQ;
2795 return status;
2799 /***********************************************************************
2800 * NtFlushVirtualMemory (NTDLL.@)
2801 * ZwFlushVirtualMemory (NTDLL.@)
2803 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2804 SIZE_T *size_ptr, ULONG unknown )
2806 struct file_view *view;
2807 NTSTATUS status = STATUS_SUCCESS;
2808 sigset_t sigset;
2809 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2811 if (process != NtCurrentProcess())
2813 apc_call_t call;
2814 apc_result_t result;
2816 memset( &call, 0, sizeof(call) );
2818 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2819 call.virtual_flush.addr = wine_server_client_ptr( addr );
2820 call.virtual_flush.size = *size_ptr;
2821 status = server_queue_process_apc( process, &call, &result );
2822 if (status != STATUS_SUCCESS) return status;
2824 if (result.virtual_flush.status == STATUS_SUCCESS)
2826 *addr_ptr = wine_server_get_ptr( result.virtual_flush.addr );
2827 *size_ptr = result.virtual_flush.size;
2829 return result.virtual_flush.status;
2832 server_enter_uninterrupted_section( &csVirtual, &sigset );
2833 if (!(view = VIRTUAL_FindView( addr, *size_ptr ))) status = STATUS_INVALID_PARAMETER;
2834 else
2836 if (!*size_ptr) *size_ptr = view->size;
2837 *addr_ptr = addr;
2838 #ifdef MS_ASYNC
2839 if (msync( addr, *size_ptr, MS_ASYNC )) status = STATUS_NOT_MAPPED_DATA;
2840 #endif
2842 server_leave_uninterrupted_section( &csVirtual, &sigset );
2843 return status;
2847 /***********************************************************************
2848 * NtGetWriteWatch (NTDLL.@)
2849 * ZwGetWriteWatch (NTDLL.@)
2851 NTSTATUS WINAPI NtGetWriteWatch( HANDLE process, ULONG flags, PVOID base, SIZE_T size, PVOID *addresses,
2852 ULONG_PTR *count, ULONG *granularity )
2854 struct file_view *view;
2855 NTSTATUS status = STATUS_SUCCESS;
2856 sigset_t sigset;
2858 size = ROUND_SIZE( base, size );
2859 base = ROUND_ADDR( base, page_mask );
2861 if (!count || !granularity) return STATUS_ACCESS_VIOLATION;
2862 if (!*count || !size) return STATUS_INVALID_PARAMETER;
2863 if (flags & ~WRITE_WATCH_FLAG_RESET) return STATUS_INVALID_PARAMETER;
2865 if (!addresses) return STATUS_ACCESS_VIOLATION;
2867 TRACE( "%p %x %p-%p %p %lu\n", process, flags, base, (char *)base + size,
2868 addresses, *count );
2870 server_enter_uninterrupted_section( &csVirtual, &sigset );
2872 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2874 ULONG_PTR pos = 0;
2875 char *addr = base;
2876 char *end = addr + size;
2878 while (pos < *count && addr < end)
2880 BYTE prot = view->prot[(addr - (char *)view->base) >> page_shift];
2881 if (!(prot & VPROT_WRITEWATCH)) addresses[pos++] = addr;
2882 addr += page_size;
2884 if (flags & WRITE_WATCH_FLAG_RESET) reset_write_watches( view, base, addr - (char *)base );
2885 *count = pos;
2886 *granularity = page_size;
2888 else status = STATUS_INVALID_PARAMETER;
2890 server_leave_uninterrupted_section( &csVirtual, &sigset );
2891 return status;
2895 /***********************************************************************
2896 * NtResetWriteWatch (NTDLL.@)
2897 * ZwResetWriteWatch (NTDLL.@)
2899 NTSTATUS WINAPI NtResetWriteWatch( HANDLE process, PVOID base, SIZE_T size )
2901 struct file_view *view;
2902 NTSTATUS status = STATUS_SUCCESS;
2903 sigset_t sigset;
2905 size = ROUND_SIZE( base, size );
2906 base = ROUND_ADDR( base, page_mask );
2908 TRACE( "%p %p-%p\n", process, base, (char *)base + size );
2910 if (!size) return STATUS_INVALID_PARAMETER;
2912 server_enter_uninterrupted_section( &csVirtual, &sigset );
2914 if ((view = VIRTUAL_FindView( base, size )) && (view->protect & VPROT_WRITEWATCH))
2915 reset_write_watches( view, base, size );
2916 else
2917 status = STATUS_INVALID_PARAMETER;
2919 server_leave_uninterrupted_section( &csVirtual, &sigset );
2920 return status;
2924 /***********************************************************************
2925 * NtReadVirtualMemory (NTDLL.@)
2926 * ZwReadVirtualMemory (NTDLL.@)
2928 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2929 SIZE_T size, SIZE_T *bytes_read )
2931 NTSTATUS status;
2933 if (virtual_check_buffer_for_write( buffer, size ))
2935 SERVER_START_REQ( read_process_memory )
2937 req->handle = wine_server_obj_handle( process );
2938 req->addr = wine_server_client_ptr( addr );
2939 wine_server_set_reply( req, buffer, size );
2940 if ((status = wine_server_call( req ))) size = 0;
2942 SERVER_END_REQ;
2944 else
2946 status = STATUS_ACCESS_VIOLATION;
2947 size = 0;
2949 if (bytes_read) *bytes_read = size;
2950 return status;
2954 /***********************************************************************
2955 * NtWriteVirtualMemory (NTDLL.@)
2956 * ZwWriteVirtualMemory (NTDLL.@)
2958 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2959 SIZE_T size, SIZE_T *bytes_written )
2961 NTSTATUS status;
2963 if (virtual_check_buffer_for_read( buffer, size ))
2965 SERVER_START_REQ( write_process_memory )
2967 req->handle = wine_server_obj_handle( process );
2968 req->addr = wine_server_client_ptr( addr );
2969 wine_server_add_data( req, buffer, size );
2970 if ((status = wine_server_call( req ))) size = 0;
2972 SERVER_END_REQ;
2974 else
2976 status = STATUS_PARTIAL_COPY;
2977 size = 0;
2979 if (bytes_written) *bytes_written = size;
2980 return status;
2984 /***********************************************************************
2985 * NtAreMappedFilesTheSame (NTDLL.@)
2986 * ZwAreMappedFilesTheSame (NTDLL.@)
2988 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2990 struct file_view *view1, *view2;
2991 struct stat st1, st2;
2992 NTSTATUS status;
2993 sigset_t sigset;
2995 TRACE("%p %p\n", addr1, addr2);
2997 server_enter_uninterrupted_section( &csVirtual, &sigset );
2999 view1 = VIRTUAL_FindView( addr1, 0 );
3000 view2 = VIRTUAL_FindView( addr2, 0 );
3002 if (!view1 || !view2)
3003 status = STATUS_INVALID_ADDRESS;
3004 else if ((view1->protect & VPROT_VALLOC) || (view2->protect & VPROT_VALLOC))
3005 status = STATUS_CONFLICTING_ADDRESSES;
3006 else if (view1 == view2)
3007 status = STATUS_SUCCESS;
3008 else if (!(view1->protect & VPROT_IMAGE) || !(view2->protect & VPROT_IMAGE))
3009 status = STATUS_NOT_SAME_DEVICE;
3010 else if (!stat_mapping_file( view1, &st1 ) && !stat_mapping_file( view2, &st2 ) &&
3011 st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
3012 status = STATUS_SUCCESS;
3013 else
3014 status = STATUS_NOT_SAME_DEVICE;
3016 server_leave_uninterrupted_section( &csVirtual, &sigset );
3017 return status;