ntdll,server: Fixed access checks for OpenFileMapping and MapViewOfFile.
[wine/multimedia.git] / dlls / ntdll / virtual.c
blob6fd86317246eececf068e35840897f41cd93dcf2
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997, 2002 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <errno.h>
26 #ifdef HAVE_SYS_ERRNO_H
27 #include <sys/errno.h>
28 #endif
29 #include <fcntl.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 # include <sys/mman.h>
43 #endif
44 #ifdef HAVE_VALGRIND_VALGRIND_H
45 # include <valgrind/valgrind.h>
46 #endif
48 #define NONAMELESSUNION
49 #define NONAMELESSSTRUCT
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winternl.h"
54 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/list.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
61 WINE_DECLARE_DEBUG_CHANNEL(module);
63 #ifndef MS_SYNC
64 #define MS_SYNC 0
65 #endif
67 #ifndef MAP_NORESERVE
68 #define MAP_NORESERVE 0
69 #endif
71 /* File view */
72 typedef struct file_view
74 struct list entry; /* Entry in global view list */
75 void *base; /* Base address */
76 size_t size; /* Size in bytes */
77 HANDLE mapping; /* Handle to the file mapping */
78 unsigned int protect; /* Protection for all pages at allocation time */
79 BYTE prot[1]; /* Protection byte for each page */
80 } FILE_VIEW;
83 /* Conversion from VPROT_* to Win32 flags */
84 static const BYTE VIRTUAL_Win32Flags[16] =
86 PAGE_NOACCESS, /* 0 */
87 PAGE_READONLY, /* READ */
88 PAGE_READWRITE, /* WRITE */
89 PAGE_READWRITE, /* READ | WRITE */
90 PAGE_EXECUTE, /* EXEC */
91 PAGE_EXECUTE_READ, /* READ | EXEC */
92 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
93 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
94 PAGE_WRITECOPY, /* WRITECOPY */
95 PAGE_WRITECOPY, /* READ | WRITECOPY */
96 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
97 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
98 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
99 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
100 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
101 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
104 static struct list views_list = LIST_INIT(views_list);
106 static RTL_CRITICAL_SECTION csVirtual;
107 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
109 0, 0, &csVirtual,
110 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
111 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
113 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
115 #ifdef __i386__
116 /* These are always the same on an i386, and it will be faster this way */
117 # define page_mask 0xfff
118 # define page_shift 12
119 # define page_size 0x1000
120 /* Note: these are Windows limits, you cannot change them. */
121 static void *address_space_limit = (void *)0xc0000000; /* top of the total available address space */
122 static void *user_space_limit = (void *)0x7fff0000; /* top of the user address space */
123 #else
124 static UINT page_shift;
125 static UINT page_size;
126 static UINT_PTR page_mask;
127 static void * const address_space_limit = 0; /* no limit needed on other platforms */
128 static void * const user_space_limit = 0; /* no limit needed on other platforms */
129 #endif /* __i386__ */
131 #define ROUND_ADDR(addr,mask) \
132 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
134 #define ROUND_SIZE(addr,size) \
135 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
137 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
138 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
140 #define VIRTUAL_HEAP_SIZE (4*1024*1024)
142 static HANDLE virtual_heap;
143 static void *preload_reserve_start;
144 static void *preload_reserve_end;
145 static int use_locks;
146 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
149 /***********************************************************************
150 * VIRTUAL_GetProtStr
152 static const char *VIRTUAL_GetProtStr( BYTE prot )
154 static char buffer[6];
155 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
156 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
157 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
158 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
159 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
160 buffer[5] = 0;
161 return buffer;
165 /***********************************************************************
166 * VIRTUAL_GetUnixProt
168 * Convert page protections to protection for mmap/mprotect.
170 static int VIRTUAL_GetUnixProt( BYTE vprot )
172 int prot = 0;
173 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
175 if (vprot & VPROT_READ) prot |= PROT_READ;
176 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
177 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
178 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
180 if (!prot) prot = PROT_NONE;
181 return prot;
185 /***********************************************************************
186 * VIRTUAL_DumpView
188 static void VIRTUAL_DumpView( FILE_VIEW *view )
190 UINT i, count;
191 char *addr = view->base;
192 BYTE prot = view->prot[0];
194 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
195 if (view->protect & VPROT_SYSTEM)
196 TRACE( " (system)\n" );
197 else if (view->protect & VPROT_VALLOC)
198 TRACE( " (valloc)\n" );
199 else if (view->mapping)
200 TRACE( " %p\n", view->mapping );
201 else
202 TRACE( " (anonymous)\n");
204 for (count = i = 1; i < view->size >> page_shift; i++, count++)
206 if (view->prot[i] == prot) continue;
207 TRACE( " %p - %p %s\n",
208 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
209 addr += (count << page_shift);
210 prot = view->prot[i];
211 count = 0;
213 if (count)
214 TRACE( " %p - %p %s\n",
215 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
219 /***********************************************************************
220 * VIRTUAL_Dump
222 #if WINE_VM_DEBUG
223 static void VIRTUAL_Dump(void)
225 sigset_t sigset;
226 struct file_view *view;
228 TRACE( "Dump of all virtual memory views:\n" );
229 server_enter_uninterrupted_section( &csVirtual, &sigset );
230 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
232 VIRTUAL_DumpView( view );
234 server_leave_uninterrupted_section( &csVirtual, &sigset );
236 #endif
239 /***********************************************************************
240 * VIRTUAL_FindView
242 * Find the view containing a given address. The csVirtual section must be held by caller.
244 * PARAMS
245 * addr [I] Address
247 * RETURNS
248 * View: Success
249 * NULL: Failure
251 static struct file_view *VIRTUAL_FindView( const void *addr )
253 struct file_view *view;
255 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
257 if (view->base > addr) break;
258 if ((const char*)view->base + view->size > (const char*)addr) return view;
260 return NULL;
264 /***********************************************************************
265 * get_mask
267 static inline UINT_PTR get_mask( ULONG zero_bits )
269 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
270 if (zero_bits < page_shift) zero_bits = page_shift;
271 return (1 << zero_bits) - 1;
275 /***********************************************************************
276 * find_view_range
278 * Find the first view overlapping at least part of the specified range.
279 * The csVirtual section must be held by caller.
281 static struct file_view *find_view_range( const void *addr, size_t size )
283 struct file_view *view;
285 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
287 if ((const char *)view->base >= (const char *)addr + size) break;
288 if ((const char *)view->base + view->size > (const char *)addr) return view;
290 return NULL;
294 /***********************************************************************
295 * find_free_area
297 * Find a free area between views inside the specified range.
298 * The csVirtual section must be held by caller.
300 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
302 struct list *ptr;
303 void *start;
305 if (top_down)
307 start = ROUND_ADDR( (char *)end - size, mask );
308 if (start >= end || start < base) return NULL;
310 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
312 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
314 if ((char *)view->base + view->size <= (char *)start) break;
315 if ((char *)view->base >= (char *)start + size) continue;
316 start = ROUND_ADDR( (char *)view->base - size, mask );
317 /* stop if remaining space is not large enough */
318 if (!start || start >= end || start < base) return NULL;
321 else
323 start = ROUND_ADDR( (char *)base + mask, mask );
324 if (start >= end || (char *)end - (char *)start < size) return NULL;
326 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
328 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
330 if ((char *)view->base >= (char *)start + size) break;
331 if ((char *)view->base + view->size <= (char *)start) continue;
332 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
333 /* stop if remaining space is not large enough */
334 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
337 return start;
341 /***********************************************************************
342 * add_reserved_area
344 * Add a reserved area to the list maintained by libwine.
345 * The csVirtual section must be held by caller.
347 static void add_reserved_area( void *addr, size_t size )
349 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
351 if (addr < user_space_limit)
353 /* unmap the part of the area that is below the limit */
354 assert( (char *)addr + size > (char *)user_space_limit );
355 munmap( addr, (char *)user_space_limit - (char *)addr );
356 size -= (char *)user_space_limit - (char *)addr;
357 addr = user_space_limit;
359 /* blow away existing mappings */
360 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
361 wine_mmap_add_reserved_area( addr, size );
365 /***********************************************************************
366 * is_beyond_limit
368 * Check if an address range goes beyond a given limit.
370 static inline int is_beyond_limit( const void *addr, size_t size, const void *limit )
372 return (limit && (addr >= limit || (const char *)addr + size > (const char *)limit));
376 /***********************************************************************
377 * unmap_area
379 * Unmap an area, or simply replace it by an empty mapping if it is
380 * in a reserved area. The csVirtual section must be held by caller.
382 static inline void unmap_area( void *addr, size_t size )
384 if (wine_mmap_is_in_reserved_area( addr, size ))
385 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
386 else if (is_beyond_limit( addr, size, user_space_limit ))
387 add_reserved_area( addr, size );
388 else
389 munmap( addr, size );
393 /***********************************************************************
394 * delete_view
396 * Deletes a view. The csVirtual section must be held by caller.
398 static void delete_view( struct file_view *view ) /* [in] View */
400 if (!(view->protect & VPROT_SYSTEM)) unmap_area( view->base, view->size );
401 list_remove( &view->entry );
402 if (view->mapping) NtClose( view->mapping );
403 RtlFreeHeap( virtual_heap, 0, view );
407 /***********************************************************************
408 * create_view
410 * Create a view. The csVirtual section must be held by caller.
412 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, unsigned int vprot )
414 struct file_view *view;
415 struct list *ptr;
416 int unix_prot = VIRTUAL_GetUnixProt( vprot );
418 assert( !((UINT_PTR)base & page_mask) );
419 assert( !(size & page_mask) );
421 /* Create the view structure */
423 if (!(view = RtlAllocateHeap( virtual_heap, 0, sizeof(*view) + (size >> page_shift) - 1 )))
425 FIXME( "out of memory in virtual heap for %p-%p\n", base, (char *)base + size );
426 return STATUS_NO_MEMORY;
429 view->base = base;
430 view->size = size;
431 view->mapping = 0;
432 view->protect = vprot;
433 memset( view->prot, vprot, size >> page_shift );
435 /* Insert it in the linked list */
437 LIST_FOR_EACH( ptr, &views_list )
439 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
440 if (next->base > base) break;
442 list_add_before( ptr, &view->entry );
444 /* Check for overlapping views. This can happen if the previous view
445 * was a system view that got unmapped behind our back. In that case
446 * we recover by simply deleting it. */
448 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
450 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
451 if ((char *)prev->base + prev->size > (char *)base)
453 TRACE( "overlapping prev view %p-%p for %p-%p\n",
454 prev->base, (char *)prev->base + prev->size,
455 base, (char *)base + view->size );
456 assert( prev->protect & VPROT_SYSTEM );
457 delete_view( prev );
460 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
462 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
463 if ((char *)base + view->size > (char *)next->base)
465 TRACE( "overlapping next view %p-%p for %p-%p\n",
466 next->base, (char *)next->base + next->size,
467 base, (char *)base + view->size );
468 assert( next->protect & VPROT_SYSTEM );
469 delete_view( next );
473 *view_ret = view;
474 VIRTUAL_DEBUG_DUMP_VIEW( view );
476 if (force_exec_prot && !(vprot & VPROT_NOEXEC) && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
478 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
479 mprotect( base, size, unix_prot | PROT_EXEC );
481 return STATUS_SUCCESS;
485 /***********************************************************************
486 * VIRTUAL_GetWin32Prot
488 * Convert page protections to Win32 flags.
490 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
492 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
493 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
494 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
495 return ret;
499 /***********************************************************************
500 * VIRTUAL_GetProt
502 * Build page protections from Win32 flags.
504 * PARAMS
505 * protect [I] Win32 protection flags
507 * RETURNS
508 * Value of page protection flags
510 static BYTE VIRTUAL_GetProt( DWORD protect )
512 BYTE vprot;
514 switch(protect & 0xff)
516 case PAGE_READONLY:
517 vprot = VPROT_READ;
518 break;
519 case PAGE_READWRITE:
520 vprot = VPROT_READ | VPROT_WRITE;
521 break;
522 case PAGE_WRITECOPY:
523 vprot = VPROT_READ | VPROT_WRITECOPY;
524 break;
525 case PAGE_EXECUTE:
526 vprot = VPROT_EXEC;
527 break;
528 case PAGE_EXECUTE_READ:
529 vprot = VPROT_EXEC | VPROT_READ;
530 break;
531 case PAGE_EXECUTE_READWRITE:
532 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
533 break;
534 case PAGE_EXECUTE_WRITECOPY:
535 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
536 break;
537 case PAGE_NOACCESS:
538 default:
539 vprot = 0;
540 break;
542 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
543 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
544 return vprot;
548 /***********************************************************************
549 * VIRTUAL_SetProt
551 * Change the protection of a range of pages.
553 * RETURNS
554 * TRUE: Success
555 * FALSE: Failure
557 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
558 void *base, /* [in] Starting address */
559 size_t size, /* [in] Size in bytes */
560 BYTE vprot ) /* [in] Protections to use */
562 int unix_prot = VIRTUAL_GetUnixProt(vprot);
564 TRACE("%p-%p %s\n",
565 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
567 /* if setting stack guard pages, store the permissions first, as the guard may be
568 * triggered at any point after mprotect and change the permissions again */
569 if ((vprot & VPROT_GUARD) &&
570 ((char *)base >= (char *)NtCurrentTeb()->DeallocationStack) &&
571 ((char *)base < (char *)NtCurrentTeb()->Tib.StackBase))
573 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
574 vprot, size >> page_shift );
575 mprotect( base, size, unix_prot );
576 VIRTUAL_DEBUG_DUMP_VIEW( view );
577 return TRUE;
580 if (force_exec_prot && !(view->protect & VPROT_NOEXEC) &&
581 (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
583 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
584 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
585 /* exec + write may legitimately fail, in that case fall back to write only */
586 if (!(unix_prot & PROT_WRITE)) return FALSE;
589 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
591 done:
592 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
593 vprot, size >> page_shift );
594 VIRTUAL_DEBUG_DUMP_VIEW( view );
595 return TRUE;
599 /***********************************************************************
600 * unmap_extra_space
602 * Release the extra memory while keeping the range starting on the granularity boundary.
604 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
606 if ((ULONG_PTR)ptr & mask)
608 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
609 munmap( ptr, extra );
610 ptr = (char *)ptr + extra;
611 total_size -= extra;
613 if (total_size > wanted_size)
614 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
615 return ptr;
619 struct alloc_area
621 size_t size;
622 size_t mask;
623 int top_down;
624 void *result;
627 /***********************************************************************
628 * alloc_reserved_area_callback
630 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
632 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
634 static void * const address_space_start = (void *)0x110000;
635 struct alloc_area *alloc = arg;
636 void *end = (char *)start + size;
638 if (start < address_space_start) start = address_space_start;
639 if (user_space_limit && end > user_space_limit) end = user_space_limit;
640 if (start >= end) return 0;
642 /* make sure we don't touch the preloader reserved range */
643 if (preload_reserve_end >= start)
645 if (preload_reserve_end >= end)
647 if (preload_reserve_start <= start) return 0; /* no space in that area */
648 if (preload_reserve_start < end) end = preload_reserve_start;
650 else if (preload_reserve_start <= start) start = preload_reserve_end;
651 else
653 /* range is split in two by the preloader reservation, try first part */
654 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
655 alloc->mask, alloc->top_down )))
656 return 1;
657 /* then fall through to try second part */
658 start = preload_reserve_end;
661 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
662 return 1;
664 return 0;
668 /***********************************************************************
669 * map_view
671 * Create a view and mmap the corresponding memory area.
672 * The csVirtual section must be held by caller.
674 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
675 int top_down, unsigned int vprot )
677 void *ptr;
678 NTSTATUS status;
680 if (base)
682 if (is_beyond_limit( base, size, address_space_limit ))
683 return STATUS_WORKING_SET_LIMIT_RANGE;
685 switch (wine_mmap_is_in_reserved_area( base, size ))
687 case -1: /* partially in a reserved area */
688 return STATUS_CONFLICTING_ADDRESSES;
690 case 0: /* not in a reserved area, do a normal allocation */
691 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
693 if (errno == ENOMEM) return STATUS_NO_MEMORY;
694 return STATUS_INVALID_PARAMETER;
696 if (ptr != base)
698 /* We couldn't get the address we wanted */
699 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
700 else munmap( ptr, size );
701 return STATUS_CONFLICTING_ADDRESSES;
703 break;
705 default:
706 case 1: /* in a reserved area, make sure the address is available */
707 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
708 /* replace the reserved area by our mapping */
709 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
710 return STATUS_INVALID_PARAMETER;
711 break;
714 else
716 size_t view_size = size + mask + 1;
717 struct alloc_area alloc;
719 alloc.size = size;
720 alloc.mask = mask;
721 alloc.top_down = top_down;
722 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
724 ptr = alloc.result;
725 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
726 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
727 return STATUS_INVALID_PARAMETER;
728 goto done;
731 for (;;)
733 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
735 if (errno == ENOMEM) return STATUS_NO_MEMORY;
736 return STATUS_INVALID_PARAMETER;
738 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
739 /* if we got something beyond the user limit, unmap it and retry */
740 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
741 else break;
743 ptr = unmap_extra_space( ptr, view_size, size, mask );
745 done:
746 status = create_view( view_ret, ptr, size, vprot );
747 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
748 return status;
752 /***********************************************************************
753 * unaligned_mmap
755 * Linux kernels before 2.4.x can support non page-aligned offsets, as
756 * long as the offset is aligned to the filesystem block size. This is
757 * a big performance gain so we want to take advantage of it.
759 * However, when we use 64-bit file support this doesn't work because
760 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
761 * in that it rounds unaligned offsets down to a page boundary. For
762 * these reasons we do a direct system call here.
764 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
765 unsigned int flags, int fd, off_t offset )
767 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
768 if (!(offset >> 32) && (offset & page_mask))
770 int ret;
772 struct
774 void *addr;
775 unsigned int length;
776 unsigned int prot;
777 unsigned int flags;
778 unsigned int fd;
779 unsigned int offset;
780 } args;
782 args.addr = addr;
783 args.length = length;
784 args.prot = prot;
785 args.flags = flags;
786 args.fd = fd;
787 args.offset = offset;
789 __asm__ __volatile__("push %%ebx\n\t"
790 "movl %2,%%ebx\n\t"
791 "int $0x80\n\t"
792 "popl %%ebx"
793 : "=a" (ret)
794 : "0" (90), /* SYS_mmap */
795 "q" (&args)
796 : "memory" );
797 if (ret < 0 && ret > -4096)
799 errno = -ret;
800 ret = -1;
802 return (void *)ret;
804 #endif
805 return mmap( addr, length, prot, flags, fd, offset );
809 /***********************************************************************
810 * map_file_into_view
812 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
813 * The csVirtual section must be held by caller.
815 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
816 off_t offset, unsigned int vprot, BOOL removable )
818 void *ptr;
819 int prot = VIRTUAL_GetUnixProt( vprot | VPROT_COMMITTED /* make sure it is accessible */ );
820 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
822 assert( start < view->size );
823 assert( start + size <= view->size );
825 /* only try mmap if media is not removable (or if we require write access) */
826 if (!removable || shared_write)
828 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
830 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
831 goto done;
833 /* mmap() failed; if this is because the file offset is not */
834 /* page-aligned (EINVAL), or because the underlying filesystem */
835 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
836 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
837 if (shared_write) /* we cannot fake shared write mappings */
839 if (errno == EINVAL) return STATUS_INVALID_PARAMETER;
840 ERR( "shared writable mmap not supported, broken filesystem?\n" );
841 return STATUS_NOT_SUPPORTED;
845 /* Reserve the memory with an anonymous mmap */
846 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
847 if (ptr == (void *)-1) return FILE_GetNtStatus();
848 /* Now read in the file */
849 pread( fd, ptr, size, offset );
850 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
851 done:
852 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
853 return STATUS_SUCCESS;
857 /***********************************************************************
858 * get_committed_size
860 * Get the size of the committed range starting at base.
861 * Also return the protections for the first page.
863 static SIZE_T get_committed_size( struct file_view *view, void *base, BYTE *vprot )
865 SIZE_T i, start;
867 start = ((char *)base - (char *)view->base) >> page_shift;
868 *vprot = view->prot[start];
870 if (view->mapping && !(view->protect & VPROT_COMMITTED))
872 SIZE_T ret = 0;
873 SERVER_START_REQ( get_mapping_committed_range )
875 req->handle = view->mapping;
876 req->offset = start << page_shift;
877 if (!wine_server_call( req ))
879 ret = reply->size;
880 if (reply->committed)
882 *vprot |= VPROT_COMMITTED;
883 for (i = 0; i < ret >> page_shift; i++) view->prot[start+i] |= VPROT_COMMITTED;
887 SERVER_END_REQ;
888 return ret;
890 for (i = start + 1; i < view->size >> page_shift; i++)
891 if ((*vprot ^ view->prot[i]) & VPROT_COMMITTED) break;
892 return (i - start) << page_shift;
896 /***********************************************************************
897 * decommit_view
899 * Decommit some pages of a given view.
900 * The csVirtual section must be held by caller.
902 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
904 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
906 BYTE *p = view->prot + (start >> page_shift);
907 size >>= page_shift;
908 while (size--) *p++ &= ~VPROT_COMMITTED;
909 return STATUS_SUCCESS;
911 return FILE_GetNtStatus();
915 /***********************************************************************
916 * map_image
918 * Map an executable (PE format) image into memory.
920 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
921 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
923 IMAGE_DOS_HEADER *dos;
924 IMAGE_NT_HEADERS *nt;
925 IMAGE_SECTION_HEADER *sec;
926 IMAGE_DATA_DIRECTORY *imports;
927 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
928 int i;
929 off_t pos;
930 sigset_t sigset;
931 struct stat st;
932 struct file_view *view = NULL;
933 char *ptr, *header_end;
934 int delta = 0;
936 /* zero-map the whole range */
938 server_enter_uninterrupted_section( &csVirtual, &sigset );
940 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
941 status = map_view( &view, base, total_size, mask, FALSE,
942 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
944 if (status == STATUS_CONFLICTING_ADDRESSES)
945 status = map_view( &view, NULL, total_size, mask, FALSE,
946 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
948 if (status != STATUS_SUCCESS) goto error;
950 ptr = view->base;
951 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
953 /* map the header */
955 if (fstat( fd, &st ) == -1)
957 status = FILE_GetNtStatus();
958 goto error;
960 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
961 if (!st.st_size) goto error;
962 header_size = min( header_size, st.st_size );
963 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
964 !dup_mapping ) != STATUS_SUCCESS) goto error;
965 dos = (IMAGE_DOS_HEADER *)ptr;
966 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
967 header_end = ptr + ROUND_SIZE( 0, header_size );
968 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
969 if ((char *)(nt + 1) > header_end) goto error;
970 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
971 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
973 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
974 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
976 /* check the architecture */
978 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
980 MESSAGE("Trying to load PE image for unsupported architecture (");
981 switch (nt->FileHeader.Machine)
983 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
984 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
985 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
986 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
987 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
988 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
989 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
990 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
991 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
992 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
993 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
994 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
996 MESSAGE(")\n");
997 goto error;
1000 /* check for non page-aligned binary */
1002 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1004 /* unaligned sections, this happens for native subsystem binaries */
1005 /* in that case Windows simply maps in the whole file */
1007 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1008 !dup_mapping ) != STATUS_SUCCESS) goto error;
1010 /* check that all sections are loaded at the right offset */
1011 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1012 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1014 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1015 goto error; /* Windows refuses to load in that case too */
1018 /* set the image protections */
1019 VIRTUAL_SetProt( view, ptr, total_size,
1020 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1022 /* no relocations are performed on non page-aligned binaries */
1023 goto done;
1027 /* map all the sections */
1029 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1031 static const SIZE_T sector_align = 0x1ff;
1032 SIZE_T map_size, file_start, file_size, end;
1034 if (!sec->Misc.VirtualSize)
1035 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1036 else
1037 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1039 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1040 file_start = sec->PointerToRawData & ~sector_align;
1041 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1042 if (file_size > map_size) file_size = map_size;
1044 /* a few sanity checks */
1045 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1046 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1048 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1049 sec->Name, sec->VirtualAddress, map_size, total_size );
1050 goto error;
1053 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1054 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1056 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1057 sec->Name, ptr + sec->VirtualAddress,
1058 sec->PointerToRawData, (int)pos, file_size, map_size,
1059 sec->Characteristics );
1060 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1061 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1062 FALSE ) != STATUS_SUCCESS)
1064 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1065 goto error;
1068 /* check if the import directory falls inside this section */
1069 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1070 imports->VirtualAddress < sec->VirtualAddress + map_size)
1072 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1073 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1074 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1075 if (end > base)
1076 map_file_into_view( view, shared_fd, base, end - base,
1077 pos + (base - sec->VirtualAddress),
1078 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1079 FALSE );
1081 pos += map_size;
1082 continue;
1085 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1086 sec->Name, ptr + sec->VirtualAddress,
1087 sec->PointerToRawData, sec->SizeOfRawData,
1088 sec->Misc.VirtualSize, sec->Characteristics );
1090 if (!sec->PointerToRawData || !file_size) continue;
1092 /* Note: if the section is not aligned properly map_file_into_view will magically
1093 * fall back to read(), so we don't need to check anything here.
1095 end = file_start + file_size;
1096 if (sec->PointerToRawData >= st.st_size ||
1097 end > ((st.st_size + sector_align) & ~sector_align) ||
1098 end < file_start ||
1099 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1100 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1101 !dup_mapping ) != STATUS_SUCCESS)
1103 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1104 goto error;
1107 if (file_size & page_mask)
1109 end = ROUND_SIZE( 0, file_size );
1110 if (end > map_size) end = map_size;
1111 TRACE_(module)("clearing %p - %p\n",
1112 ptr + sec->VirtualAddress + file_size,
1113 ptr + sec->VirtualAddress + end );
1114 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1119 /* perform base relocation, if necessary */
1121 if (ptr != base &&
1122 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1123 !NtCurrentTeb()->Peb->ImageBaseAddress) )
1125 IMAGE_BASE_RELOCATION *rel, *end;
1126 const IMAGE_DATA_DIRECTORY *relocs;
1128 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1130 WARN_(module)( "Need to relocate module from %p to %p, but there are no relocation records\n",
1131 base, ptr );
1132 status = STATUS_CONFLICTING_ADDRESSES;
1133 goto error;
1136 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
1137 base, base + total_size, ptr, ptr + total_size );
1139 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1140 rel = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress);
1141 end = (IMAGE_BASE_RELOCATION *)(ptr + relocs->VirtualAddress + relocs->Size);
1142 delta = ptr - base;
1144 while (rel < end - 1 && rel->SizeOfBlock)
1146 if (rel->VirtualAddress >= total_size)
1148 WARN_(module)( "invalid address %p in relocation %p\n", ptr + rel->VirtualAddress, rel );
1149 status = STATUS_ACCESS_VIOLATION;
1150 goto error;
1152 rel = LdrProcessRelocationBlock( ptr + rel->VirtualAddress,
1153 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1154 (USHORT *)(rel + 1), delta );
1155 if (!rel) goto error;
1159 /* set the image protections */
1161 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1163 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1164 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1166 SIZE_T size;
1167 BYTE vprot = VPROT_COMMITTED;
1169 if (sec->Misc.VirtualSize)
1170 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1171 else
1172 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1174 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1175 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1176 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1178 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1179 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1180 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1181 vprot |= VPROT_EXEC;
1183 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1186 done:
1187 view->mapping = dup_mapping;
1188 server_leave_uninterrupted_section( &csVirtual, &sigset );
1190 *addr_ptr = ptr;
1191 #ifdef VALGRIND_LOAD_PDB_DEBUGINFO
1192 VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta);
1193 #endif
1194 return STATUS_SUCCESS;
1196 error:
1197 if (view) delete_view( view );
1198 server_leave_uninterrupted_section( &csVirtual, &sigset );
1199 if (dup_mapping) NtClose( dup_mapping );
1200 return status;
1204 /* callback for wine_mmap_enum_reserved_areas to allocate space for the virtual heap */
1205 static int alloc_virtual_heap( void *base, size_t size, void *arg )
1207 void **heap_base = arg;
1209 if (address_space_limit) address_space_limit = max( (char *)address_space_limit, (char *)base + size );
1210 if (size < VIRTUAL_HEAP_SIZE) return 0;
1211 *heap_base = wine_anon_mmap( (char *)base + size - VIRTUAL_HEAP_SIZE,
1212 VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED );
1213 return (*heap_base != (void *)-1);
1216 /***********************************************************************
1217 * virtual_init
1219 void virtual_init(void)
1221 const char *preload;
1222 void *heap_base;
1223 struct file_view *heap_view;
1225 #ifndef page_mask
1226 page_size = getpagesize();
1227 page_mask = page_size - 1;
1228 /* Make sure we have a power of 2 */
1229 assert( !(page_size & page_mask) );
1230 page_shift = 0;
1231 while ((1 << page_shift) != page_size) page_shift++;
1232 #endif /* page_mask */
1233 if ((preload = getenv("WINEPRELOADRESERVE")))
1235 unsigned long start, end;
1236 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1238 preload_reserve_start = (void *)start;
1239 preload_reserve_end = (void *)end;
1243 /* try to find space in a reserved area for the virtual heap */
1244 if (!wine_mmap_enum_reserved_areas( alloc_virtual_heap, &heap_base, 1 ))
1245 heap_base = wine_anon_mmap( NULL, VIRTUAL_HEAP_SIZE, PROT_READ|PROT_WRITE, 0 );
1247 assert( heap_base != (void *)-1 );
1248 virtual_heap = RtlCreateHeap( HEAP_NO_SERIALIZE, heap_base, VIRTUAL_HEAP_SIZE,
1249 VIRTUAL_HEAP_SIZE, NULL, NULL );
1250 create_view( &heap_view, heap_base, VIRTUAL_HEAP_SIZE, VPROT_COMMITTED | VPROT_READ | VPROT_WRITE );
1254 /***********************************************************************
1255 * virtual_init_threading
1257 void virtual_init_threading(void)
1259 use_locks = 1;
1263 /***********************************************************************
1264 * virtual_get_system_info
1266 void virtual_get_system_info( SYSTEM_BASIC_INFORMATION *info )
1268 info->dwUnknown1 = 0;
1269 info->uKeMaximumIncrement = 0; /* FIXME */
1270 info->uPageSize = page_size;
1271 info->uMmLowestPhysicalPage = 1;
1272 info->uMmHighestPhysicalPage = 0x7fffffff / page_size;
1273 info->uMmNumberOfPhysicalPages = info->uMmHighestPhysicalPage - info->uMmLowestPhysicalPage;
1274 info->uAllocationGranularity = get_mask(0) + 1;
1275 info->pLowestUserAddress = (void *)0x10000;
1276 info->pMmHighestUserAddress = (char *)user_space_limit - 1;
1277 info->uKeActiveProcessors = NtCurrentTeb()->Peb->NumberOfProcessors;
1278 info->bKeNumberProcessors = info->uKeActiveProcessors;
1282 /***********************************************************************
1283 * virtual_alloc_thread_stack
1285 NTSTATUS virtual_alloc_thread_stack( void *base, SIZE_T size )
1287 FILE_VIEW *view;
1288 NTSTATUS status;
1289 sigset_t sigset;
1291 server_enter_uninterrupted_section( &csVirtual, &sigset );
1293 if (base) /* already allocated, create a system view */
1295 size = ROUND_SIZE( base, size );
1296 base = ROUND_ADDR( base, page_mask );
1297 if ((status = create_view( &view, base, size,
1298 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC | VPROT_SYSTEM )) != STATUS_SUCCESS)
1299 goto done;
1301 else
1303 size = (size + 0xffff) & ~0xffff; /* round to 64K boundary */
1304 if ((status = map_view( &view, NULL, size, 0xffff, 0,
1305 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_VALLOC )) != STATUS_SUCCESS)
1306 goto done;
1307 #ifdef VALGRIND_STACK_REGISTER
1308 /* no need to de-register the stack as it's the one of the main thread */
1309 VALGRIND_STACK_REGISTER( view->base, (char *)view->base + view->size );
1310 #endif
1313 /* setup no access guard page */
1314 VIRTUAL_SetProt( view, view->base, page_size, VPROT_COMMITTED );
1315 VIRTUAL_SetProt( view, (char *)view->base + page_size, page_size,
1316 VPROT_READ | VPROT_WRITE | VPROT_COMMITTED | VPROT_GUARD );
1318 /* note: limit is lower than base since the stack grows down */
1319 NtCurrentTeb()->DeallocationStack = view->base;
1320 NtCurrentTeb()->Tib.StackBase = (char *)view->base + view->size;
1321 NtCurrentTeb()->Tib.StackLimit = (char *)view->base + 2 * page_size;
1323 done:
1324 server_leave_uninterrupted_section( &csVirtual, &sigset );
1325 return status;
1329 /***********************************************************************
1330 * virtual_clear_thread_stack
1332 * Clear the stack contents before calling the main entry point, some broken apps need that.
1334 void virtual_clear_thread_stack(void)
1336 void *stack = NtCurrentTeb()->Tib.StackLimit;
1337 size_t size = (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit;
1339 wine_anon_mmap( stack, size, PROT_READ | PROT_WRITE, MAP_FIXED );
1340 if (force_exec_prot) mprotect( stack, size, PROT_READ | PROT_WRITE | PROT_EXEC );
1344 /***********************************************************************
1345 * VIRTUAL_HandleFault
1347 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1349 FILE_VIEW *view;
1350 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1351 sigset_t sigset;
1353 server_enter_uninterrupted_section( &csVirtual, &sigset );
1354 if ((view = VIRTUAL_FindView( addr )))
1356 void *page = ROUND_ADDR( addr, page_mask );
1357 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1358 if (vprot & VPROT_GUARD)
1360 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1361 ret = STATUS_GUARD_PAGE_VIOLATION;
1364 server_leave_uninterrupted_section( &csVirtual, &sigset );
1365 return ret;
1370 /***********************************************************************
1371 * virtual_handle_stack_fault
1373 * Handle an access fault inside the current thread stack.
1374 * Called from inside a signal handler.
1376 BOOL virtual_handle_stack_fault( void *addr )
1378 FILE_VIEW *view;
1379 BOOL ret = FALSE;
1381 RtlEnterCriticalSection( &csVirtual ); /* no need for signal masking inside signal handler */
1382 if ((view = VIRTUAL_FindView( addr )))
1384 void *page = ROUND_ADDR( addr, page_mask );
1385 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1386 if (vprot & VPROT_GUARD)
1388 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1389 if ((char *)page + page_size == NtCurrentTeb()->Tib.StackLimit)
1390 NtCurrentTeb()->Tib.StackLimit = page;
1391 ret = TRUE;
1394 RtlLeaveCriticalSection( &csVirtual );
1395 return ret;
1399 /***********************************************************************
1400 * VIRTUAL_SetForceExec
1402 * Whether to force exec prot on all views.
1404 void VIRTUAL_SetForceExec( BOOL enable )
1406 struct file_view *view;
1407 sigset_t sigset;
1409 server_enter_uninterrupted_section( &csVirtual, &sigset );
1410 if (!force_exec_prot != !enable) /* change all existing views */
1412 force_exec_prot = enable;
1414 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1416 UINT i, count;
1417 char *addr = view->base;
1418 BYTE commit = view->mapping ? VPROT_COMMITTED : 0; /* file mappings are always accessible */
1419 int unix_prot = VIRTUAL_GetUnixProt( view->prot[0] | commit );
1421 if (view->protect & VPROT_NOEXEC) continue;
1422 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1424 int prot = VIRTUAL_GetUnixProt( view->prot[i] | commit );
1425 if (prot == unix_prot) continue;
1426 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1428 TRACE( "%s exec prot for %p-%p\n",
1429 force_exec_prot ? "enabling" : "disabling",
1430 addr, addr + (count << page_shift) - 1 );
1431 mprotect( addr, count << page_shift,
1432 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1434 addr += (count << page_shift);
1435 unix_prot = prot;
1436 count = 0;
1438 if (count)
1440 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1442 TRACE( "%s exec prot for %p-%p\n",
1443 force_exec_prot ? "enabling" : "disabling",
1444 addr, addr + (count << page_shift) - 1 );
1445 mprotect( addr, count << page_shift,
1446 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1451 server_leave_uninterrupted_section( &csVirtual, &sigset );
1455 /***********************************************************************
1456 * VIRTUAL_UseLargeAddressSpace
1458 * Increase the address space size for apps that support it.
1460 void VIRTUAL_UseLargeAddressSpace(void)
1462 /* no large address space on win9x */
1463 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1464 user_space_limit = address_space_limit;
1468 /***********************************************************************
1469 * NtAllocateVirtualMemory (NTDLL.@)
1470 * ZwAllocateVirtualMemory (NTDLL.@)
1472 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1473 SIZE_T *size_ptr, ULONG type, ULONG protect )
1475 void *base;
1476 unsigned int vprot;
1477 SIZE_T size = *size_ptr;
1478 SIZE_T mask = get_mask( zero_bits );
1479 NTSTATUS status = STATUS_SUCCESS;
1480 struct file_view *view;
1481 sigset_t sigset;
1483 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1485 if (!size) return STATUS_INVALID_PARAMETER;
1487 if (process != NtCurrentProcess())
1489 apc_call_t call;
1490 apc_result_t result;
1492 memset( &call, 0, sizeof(call) );
1494 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1495 call.virtual_alloc.addr = *ret;
1496 call.virtual_alloc.size = *size_ptr;
1497 call.virtual_alloc.zero_bits = zero_bits;
1498 call.virtual_alloc.op_type = type;
1499 call.virtual_alloc.prot = protect;
1500 status = NTDLL_queue_process_apc( process, &call, &result );
1501 if (status != STATUS_SUCCESS) return status;
1503 if (result.virtual_alloc.status == STATUS_SUCCESS)
1505 *ret = result.virtual_alloc.addr;
1506 *size_ptr = result.virtual_alloc.size;
1508 return result.virtual_alloc.status;
1511 /* Round parameters to a page boundary */
1513 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1515 if (*ret)
1517 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1518 base = ROUND_ADDR( *ret, mask );
1519 else
1520 base = ROUND_ADDR( *ret, page_mask );
1521 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1523 /* disallow low 64k, wrap-around and kernel space */
1524 if (((char *)base < (char *)0x10000) ||
1525 ((char *)base + size < (char *)base) ||
1526 is_beyond_limit( base, size, address_space_limit ))
1527 return STATUS_INVALID_PARAMETER;
1529 else
1531 base = NULL;
1532 size = (size + page_mask) & ~page_mask;
1535 /* Compute the alloc type flags */
1537 if (!(type & MEM_SYSTEM))
1539 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1540 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1542 WARN("called with wrong alloc type flags (%08x) !\n", type);
1543 return STATUS_INVALID_PARAMETER;
1545 if (type & MEM_WRITE_WATCH)
1547 FIXME("MEM_WRITE_WATCH type not supported\n");
1548 return STATUS_NOT_SUPPORTED;
1551 vprot = VIRTUAL_GetProt( protect ) | VPROT_VALLOC;
1552 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1554 /* Reserve the memory */
1556 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1558 if (type & MEM_SYSTEM)
1560 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE | VPROT_NOEXEC;
1561 status = create_view( &view, base, size, vprot | VPROT_COMMITTED | VPROT_SYSTEM );
1562 if (status == STATUS_SUCCESS) base = view->base;
1564 else if ((type & MEM_RESERVE) || !base)
1566 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1567 if (status == STATUS_SUCCESS) base = view->base;
1569 else /* commit the pages */
1571 if (!(view = VIRTUAL_FindView( base )) ||
1572 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1573 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1574 else if (view->mapping && !(view->protect & VPROT_COMMITTED))
1576 SERVER_START_REQ( add_mapping_committed_range )
1578 req->handle = view->mapping;
1579 req->offset = (char *)base - (char *)view->base;
1580 req->size = size;
1581 wine_server_call( req );
1583 SERVER_END_REQ;
1587 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1589 if (status == STATUS_SUCCESS)
1591 *ret = base;
1592 *size_ptr = size;
1594 return status;
1598 /***********************************************************************
1599 * NtFreeVirtualMemory (NTDLL.@)
1600 * ZwFreeVirtualMemory (NTDLL.@)
1602 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1604 FILE_VIEW *view;
1605 char *base;
1606 sigset_t sigset;
1607 NTSTATUS status = STATUS_SUCCESS;
1608 LPVOID addr = *addr_ptr;
1609 SIZE_T size = *size_ptr;
1611 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1613 if (process != NtCurrentProcess())
1615 apc_call_t call;
1616 apc_result_t result;
1618 memset( &call, 0, sizeof(call) );
1620 call.virtual_free.type = APC_VIRTUAL_FREE;
1621 call.virtual_free.addr = addr;
1622 call.virtual_free.size = size;
1623 call.virtual_free.op_type = type;
1624 status = NTDLL_queue_process_apc( process, &call, &result );
1625 if (status != STATUS_SUCCESS) return status;
1627 if (result.virtual_free.status == STATUS_SUCCESS)
1629 *addr_ptr = result.virtual_free.addr;
1630 *size_ptr = result.virtual_free.size;
1632 return result.virtual_free.status;
1635 /* Fix the parameters */
1637 size = ROUND_SIZE( addr, size );
1638 base = ROUND_ADDR( addr, page_mask );
1640 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1641 if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;
1643 server_enter_uninterrupted_section( &csVirtual, &sigset );
1645 if (!(view = VIRTUAL_FindView( base )) ||
1646 (base + size > (char *)view->base + view->size) ||
1647 !(view->protect & VPROT_VALLOC))
1649 status = STATUS_INVALID_PARAMETER;
1651 else if (type & MEM_SYSTEM)
1653 /* return the values that the caller should use to unmap the area */
1654 *addr_ptr = view->base;
1655 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1656 else *size_ptr = 0; /* make sure we don't munmap anything from a reserved area */
1657 view->protect |= VPROT_SYSTEM;
1658 delete_view( view );
1660 else if (type == MEM_RELEASE)
1662 /* Free the pages */
1664 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1665 else
1667 delete_view( view );
1668 *addr_ptr = base;
1669 *size_ptr = size;
1672 else if (type == MEM_DECOMMIT)
1674 status = decommit_pages( view, base - (char *)view->base, size );
1675 if (status == STATUS_SUCCESS)
1677 *addr_ptr = base;
1678 *size_ptr = size;
1681 else
1683 WARN("called with wrong free type flags (%08x) !\n", type);
1684 status = STATUS_INVALID_PARAMETER;
1687 server_leave_uninterrupted_section( &csVirtual, &sigset );
1688 return status;
1692 /***********************************************************************
1693 * NtProtectVirtualMemory (NTDLL.@)
1694 * ZwProtectVirtualMemory (NTDLL.@)
1696 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1697 ULONG new_prot, ULONG *old_prot )
1699 FILE_VIEW *view;
1700 sigset_t sigset;
1701 NTSTATUS status = STATUS_SUCCESS;
1702 char *base;
1703 BYTE vprot;
1704 SIZE_T size = *size_ptr;
1705 LPVOID addr = *addr_ptr;
1707 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1709 if (process != NtCurrentProcess())
1711 apc_call_t call;
1712 apc_result_t result;
1714 memset( &call, 0, sizeof(call) );
1716 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1717 call.virtual_protect.addr = addr;
1718 call.virtual_protect.size = size;
1719 call.virtual_protect.prot = new_prot;
1720 status = NTDLL_queue_process_apc( process, &call, &result );
1721 if (status != STATUS_SUCCESS) return status;
1723 if (result.virtual_protect.status == STATUS_SUCCESS)
1725 *addr_ptr = result.virtual_protect.addr;
1726 *size_ptr = result.virtual_protect.size;
1727 if (old_prot) *old_prot = result.virtual_protect.prot;
1729 return result.virtual_protect.status;
1732 /* Fix the parameters */
1734 size = ROUND_SIZE( addr, size );
1735 base = ROUND_ADDR( addr, page_mask );
1737 server_enter_uninterrupted_section( &csVirtual, &sigset );
1739 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1741 status = STATUS_INVALID_PARAMETER;
1743 else
1745 /* Make sure all the pages are committed */
1746 if (get_committed_size( view, base, &vprot ) >= size && (vprot & VPROT_COMMITTED))
1748 if (old_prot) *old_prot = VIRTUAL_GetWin32Prot( vprot );
1749 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1750 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1752 else status = STATUS_NOT_COMMITTED;
1754 server_leave_uninterrupted_section( &csVirtual, &sigset );
1756 if (status == STATUS_SUCCESS)
1758 *addr_ptr = base;
1759 *size_ptr = size;
1761 return status;
1764 #define UNIMPLEMENTED_INFO_CLASS(c) \
1765 case c: \
1766 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1767 return STATUS_INVALID_INFO_CLASS
1769 /***********************************************************************
1770 * NtQueryVirtualMemory (NTDLL.@)
1771 * ZwQueryVirtualMemory (NTDLL.@)
1773 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1774 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1775 SIZE_T len, SIZE_T *res_len )
1777 FILE_VIEW *view;
1778 char *base, *alloc_base = 0;
1779 struct list *ptr;
1780 SIZE_T size = 0;
1781 MEMORY_BASIC_INFORMATION *info = buffer;
1782 sigset_t sigset;
1784 if (info_class != MemoryBasicInformation)
1786 switch(info_class)
1788 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1789 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1790 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1792 default:
1793 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1794 process, addr, info_class, buffer, len, res_len);
1795 return STATUS_INVALID_INFO_CLASS;
1798 if (address_space_limit && addr >= address_space_limit)
1799 return STATUS_WORKING_SET_LIMIT_RANGE;
1801 if (process != NtCurrentProcess())
1803 NTSTATUS status;
1804 apc_call_t call;
1805 apc_result_t result;
1807 memset( &call, 0, sizeof(call) );
1809 call.virtual_query.type = APC_VIRTUAL_QUERY;
1810 call.virtual_query.addr = addr;
1811 status = NTDLL_queue_process_apc( process, &call, &result );
1812 if (status != STATUS_SUCCESS) return status;
1814 if (result.virtual_query.status == STATUS_SUCCESS)
1816 info->BaseAddress = result.virtual_query.base;
1817 info->AllocationBase = result.virtual_query.alloc_base;
1818 info->RegionSize = result.virtual_query.size;
1819 info->State = result.virtual_query.state;
1820 info->Protect = result.virtual_query.prot;
1821 info->AllocationProtect = result.virtual_query.alloc_prot;
1822 info->Type = result.virtual_query.alloc_type;
1823 if (res_len) *res_len = sizeof(*info);
1825 return result.virtual_query.status;
1828 base = ROUND_ADDR( addr, page_mask );
1830 /* Find the view containing the address */
1832 server_enter_uninterrupted_section( &csVirtual, &sigset );
1833 ptr = list_head( &views_list );
1834 for (;;)
1836 if (!ptr)
1838 /* make the address space end at the user limit, except if
1839 * the last view was mapped beyond that */
1840 if (alloc_base <= (char *)user_space_limit)
1842 if (user_space_limit && base >= (char *)user_space_limit)
1844 server_leave_uninterrupted_section( &csVirtual, &sigset );
1845 return STATUS_WORKING_SET_LIMIT_RANGE;
1847 size = (char *)user_space_limit - alloc_base;
1849 else size = (char *)address_space_limit - alloc_base;
1850 view = NULL;
1851 break;
1853 view = LIST_ENTRY( ptr, struct file_view, entry );
1854 if ((char *)view->base > base)
1856 size = (char *)view->base - alloc_base;
1857 view = NULL;
1858 break;
1860 if ((char *)view->base + view->size > base)
1862 alloc_base = view->base;
1863 size = view->size;
1864 break;
1866 alloc_base = (char *)view->base + view->size;
1867 ptr = list_next( &views_list, ptr );
1870 /* Fill the info structure */
1872 if (!view)
1874 info->State = MEM_FREE;
1875 info->Protect = PAGE_NOACCESS;
1876 info->AllocationBase = 0;
1877 info->AllocationProtect = 0;
1878 info->Type = 0;
1880 else
1882 BYTE vprot;
1883 SIZE_T range_size = get_committed_size( view, base, &vprot );
1885 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1886 info->Protect = (vprot & VPROT_COMMITTED) ? VIRTUAL_GetWin32Prot( vprot ) : 0;
1887 info->AllocationBase = alloc_base;
1888 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1889 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1890 else if (view->protect & VPROT_VALLOC) info->Type = MEM_PRIVATE;
1891 else info->Type = MEM_MAPPED;
1892 for (size = base - alloc_base; size < base + range_size - alloc_base; size += page_size)
1893 if (view->prot[size >> page_shift] != vprot) break;
1895 server_leave_uninterrupted_section( &csVirtual, &sigset );
1897 info->BaseAddress = base;
1898 info->RegionSize = size - (base - alloc_base);
1899 if (res_len) *res_len = sizeof(*info);
1900 return STATUS_SUCCESS;
1904 /***********************************************************************
1905 * NtLockVirtualMemory (NTDLL.@)
1906 * ZwLockVirtualMemory (NTDLL.@)
1908 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1910 NTSTATUS status = STATUS_SUCCESS;
1912 if (process != NtCurrentProcess())
1914 apc_call_t call;
1915 apc_result_t result;
1917 memset( &call, 0, sizeof(call) );
1919 call.virtual_lock.type = APC_VIRTUAL_LOCK;
1920 call.virtual_lock.addr = *addr;
1921 call.virtual_lock.size = *size;
1922 status = NTDLL_queue_process_apc( process, &call, &result );
1923 if (status != STATUS_SUCCESS) return status;
1925 if (result.virtual_lock.status == STATUS_SUCCESS)
1927 *addr = result.virtual_lock.addr;
1928 *size = result.virtual_lock.size;
1930 return result.virtual_lock.status;
1933 *size = ROUND_SIZE( *addr, *size );
1934 *addr = ROUND_ADDR( *addr, page_mask );
1936 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1937 return status;
1941 /***********************************************************************
1942 * NtUnlockVirtualMemory (NTDLL.@)
1943 * ZwUnlockVirtualMemory (NTDLL.@)
1945 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1947 NTSTATUS status = STATUS_SUCCESS;
1949 if (process != NtCurrentProcess())
1951 apc_call_t call;
1952 apc_result_t result;
1954 memset( &call, 0, sizeof(call) );
1956 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
1957 call.virtual_unlock.addr = *addr;
1958 call.virtual_unlock.size = *size;
1959 status = NTDLL_queue_process_apc( process, &call, &result );
1960 if (status != STATUS_SUCCESS) return status;
1962 if (result.virtual_unlock.status == STATUS_SUCCESS)
1964 *addr = result.virtual_unlock.addr;
1965 *size = result.virtual_unlock.size;
1967 return result.virtual_unlock.status;
1970 *size = ROUND_SIZE( *addr, *size );
1971 *addr = ROUND_ADDR( *addr, page_mask );
1973 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1974 return status;
1978 /***********************************************************************
1979 * NtCreateSection (NTDLL.@)
1980 * ZwCreateSection (NTDLL.@)
1982 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1983 const LARGE_INTEGER *size, ULONG protect,
1984 ULONG sec_flags, HANDLE file )
1986 NTSTATUS ret;
1987 unsigned int vprot;
1988 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1989 struct security_descriptor *sd = NULL;
1990 struct object_attributes objattr;
1992 /* Check parameters */
1994 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1996 objattr.rootdir = attr ? attr->RootDirectory : 0;
1997 objattr.sd_len = 0;
1998 objattr.name_len = len;
1999 if (attr)
2001 ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
2002 if (ret != STATUS_SUCCESS) return ret;
2005 vprot = VIRTUAL_GetProt( protect );
2006 if (!(sec_flags & SEC_RESERVE)) vprot |= VPROT_COMMITTED;
2007 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
2008 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
2010 /* Create the server object */
2012 SERVER_START_REQ( create_mapping )
2014 req->access = access;
2015 req->attributes = (attr) ? attr->Attributes : 0;
2016 req->file_handle = file;
2017 req->size = size ? size->QuadPart : 0;
2018 req->protect = vprot;
2019 wine_server_add_data( req, &objattr, sizeof(objattr) );
2020 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
2021 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
2022 ret = wine_server_call( req );
2023 *handle = reply->handle;
2025 SERVER_END_REQ;
2027 NTDLL_free_struct_sd( sd );
2029 return ret;
2033 /***********************************************************************
2034 * NtOpenSection (NTDLL.@)
2035 * ZwOpenSection (NTDLL.@)
2037 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
2039 NTSTATUS ret;
2040 DWORD len = attr->ObjectName->Length;
2042 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2044 SERVER_START_REQ( open_mapping )
2046 req->access = access;
2047 req->attributes = attr->Attributes;
2048 req->rootdir = attr->RootDirectory;
2049 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2050 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
2052 SERVER_END_REQ;
2053 return ret;
2057 /***********************************************************************
2058 * NtMapViewOfSection (NTDLL.@)
2059 * ZwMapViewOfSection (NTDLL.@)
2061 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2062 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2063 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2065 NTSTATUS res;
2066 ULONGLONG full_size;
2067 ACCESS_MASK access;
2068 SIZE_T size = 0;
2069 SIZE_T mask = get_mask( zero_bits );
2070 int unix_handle = -1, needs_close;
2071 unsigned int map_vprot, vprot;
2072 void *base;
2073 struct file_view *view;
2074 DWORD header_size;
2075 HANDLE dup_mapping, shared_file;
2076 LARGE_INTEGER offset;
2077 sigset_t sigset;
2079 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2081 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2082 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2084 /* Check parameters */
2086 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2087 return STATUS_INVALID_PARAMETER;
2089 if (process != NtCurrentProcess())
2091 apc_call_t call;
2092 apc_result_t result;
2094 memset( &call, 0, sizeof(call) );
2096 call.map_view.type = APC_MAP_VIEW;
2097 call.map_view.handle = handle;
2098 call.map_view.addr = *addr_ptr;
2099 call.map_view.size = *size_ptr;
2100 call.map_view.offset = offset.QuadPart;
2101 call.map_view.zero_bits = zero_bits;
2102 call.map_view.alloc_type = alloc_type;
2103 call.map_view.prot = protect;
2104 res = NTDLL_queue_process_apc( process, &call, &result );
2105 if (res != STATUS_SUCCESS) return res;
2107 if (result.map_view.status == STATUS_SUCCESS)
2109 *addr_ptr = result.map_view.addr;
2110 *size_ptr = result.map_view.size;
2112 return result.map_view.status;
2115 switch(protect)
2117 case PAGE_NOACCESS:
2118 access = SECTION_QUERY;
2119 break;
2120 case PAGE_READWRITE:
2121 case PAGE_EXECUTE_READWRITE:
2122 access = SECTION_QUERY | SECTION_MAP_WRITE;
2123 break;
2124 case PAGE_READONLY:
2125 case PAGE_WRITECOPY:
2126 case PAGE_EXECUTE:
2127 case PAGE_EXECUTE_READ:
2128 case PAGE_EXECUTE_WRITECOPY:
2129 access = SECTION_QUERY | SECTION_MAP_READ;
2130 break;
2131 default:
2132 return STATUS_INVALID_PARAMETER;
2135 SERVER_START_REQ( get_mapping_info )
2137 req->handle = handle;
2138 req->access = access;
2139 res = wine_server_call( req );
2140 map_vprot = reply->protect;
2141 base = reply->base;
2142 full_size = reply->size;
2143 header_size = reply->header_size;
2144 dup_mapping = reply->mapping;
2145 shared_file = reply->shared_file;
2147 SERVER_END_REQ;
2148 if (res) return res;
2150 size = full_size;
2151 if (sizeof(size) < sizeof(full_size) && (size != full_size))
2152 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n",
2153 (DWORD)(full_size >> 32), (DWORD)full_size );
2155 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2157 if (map_vprot & VPROT_IMAGE)
2159 if (shared_file)
2161 int shared_fd, shared_needs_close;
2163 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2164 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2165 res = map_image( handle, unix_handle, base, size, mask, header_size,
2166 shared_fd, dup_mapping, addr_ptr );
2167 if (shared_needs_close) close( shared_fd );
2168 NtClose( shared_file );
2170 else
2172 res = map_image( handle, unix_handle, base, size, mask, header_size,
2173 -1, dup_mapping, addr_ptr );
2175 if (needs_close) close( unix_handle );
2176 if (!res) *size_ptr = size;
2177 return res;
2180 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2182 res = STATUS_INVALID_PARAMETER;
2183 goto done;
2185 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2186 else size = size - offset.QuadPart;
2188 /* Reserve a properly aligned area */
2190 server_enter_uninterrupted_section( &csVirtual, &sigset );
2192 vprot = VIRTUAL_GetProt( protect ) | (map_vprot & VPROT_COMMITTED);
2193 res = map_view( &view, *addr_ptr, size, mask, FALSE, vprot );
2194 if (res)
2196 server_leave_uninterrupted_section( &csVirtual, &sigset );
2197 goto done;
2200 /* Map the file */
2202 TRACE("handle=%p size=%lx offset=%x%08x\n",
2203 handle, size, offset.u.HighPart, offset.u.LowPart );
2205 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, vprot, !dup_mapping );
2206 if (res == STATUS_SUCCESS)
2208 *addr_ptr = view->base;
2209 *size_ptr = size;
2210 view->mapping = dup_mapping;
2211 dup_mapping = 0; /* don't close it */
2213 else
2215 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2216 view->base, size, offset.u.HighPart, offset.u.LowPart );
2217 delete_view( view );
2220 server_leave_uninterrupted_section( &csVirtual, &sigset );
2222 done:
2223 if (dup_mapping) NtClose( dup_mapping );
2224 if (needs_close) close( unix_handle );
2225 return res;
2229 /***********************************************************************
2230 * NtUnmapViewOfSection (NTDLL.@)
2231 * ZwUnmapViewOfSection (NTDLL.@)
2233 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2235 FILE_VIEW *view;
2236 NTSTATUS status = STATUS_INVALID_PARAMETER;
2237 sigset_t sigset;
2238 void *base = ROUND_ADDR( addr, page_mask );
2240 if (process != NtCurrentProcess())
2242 apc_call_t call;
2243 apc_result_t result;
2245 memset( &call, 0, sizeof(call) );
2247 call.unmap_view.type = APC_UNMAP_VIEW;
2248 call.unmap_view.addr = addr;
2249 status = NTDLL_queue_process_apc( process, &call, &result );
2250 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2251 return status;
2254 server_enter_uninterrupted_section( &csVirtual, &sigset );
2255 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2257 delete_view( view );
2258 status = STATUS_SUCCESS;
2260 server_leave_uninterrupted_section( &csVirtual, &sigset );
2261 return status;
2265 /***********************************************************************
2266 * NtFlushVirtualMemory (NTDLL.@)
2267 * ZwFlushVirtualMemory (NTDLL.@)
2269 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2270 SIZE_T *size_ptr, ULONG unknown )
2272 FILE_VIEW *view;
2273 NTSTATUS status = STATUS_SUCCESS;
2274 sigset_t sigset;
2275 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2277 if (process != NtCurrentProcess())
2279 apc_call_t call;
2280 apc_result_t result;
2282 memset( &call, 0, sizeof(call) );
2284 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2285 call.virtual_flush.addr = addr;
2286 call.virtual_flush.size = *size_ptr;
2287 status = NTDLL_queue_process_apc( process, &call, &result );
2288 if (status != STATUS_SUCCESS) return status;
2290 if (result.virtual_flush.status == STATUS_SUCCESS)
2292 *addr_ptr = result.virtual_flush.addr;
2293 *size_ptr = result.virtual_flush.size;
2295 return result.virtual_flush.status;
2298 server_enter_uninterrupted_section( &csVirtual, &sigset );
2299 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2300 else
2302 if (!*size_ptr) *size_ptr = view->size;
2303 *addr_ptr = addr;
2304 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2306 server_leave_uninterrupted_section( &csVirtual, &sigset );
2307 return status;
2311 /***********************************************************************
2312 * NtReadVirtualMemory (NTDLL.@)
2313 * ZwReadVirtualMemory (NTDLL.@)
2315 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2316 SIZE_T size, SIZE_T *bytes_read )
2318 NTSTATUS status;
2320 SERVER_START_REQ( read_process_memory )
2322 req->handle = process;
2323 req->addr = (void *)addr;
2324 wine_server_set_reply( req, buffer, size );
2325 if ((status = wine_server_call( req ))) size = 0;
2327 SERVER_END_REQ;
2328 if (bytes_read) *bytes_read = size;
2329 return status;
2333 /***********************************************************************
2334 * NtWriteVirtualMemory (NTDLL.@)
2335 * ZwWriteVirtualMemory (NTDLL.@)
2337 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2338 SIZE_T size, SIZE_T *bytes_written )
2340 NTSTATUS status;
2342 SERVER_START_REQ( write_process_memory )
2344 req->handle = process;
2345 req->addr = addr;
2346 wine_server_add_data( req, buffer, size );
2347 if ((status = wine_server_call( req ))) size = 0;
2349 SERVER_END_REQ;
2350 if (bytes_written) *bytes_written = size;
2351 return status;
2355 /***********************************************************************
2356 * NtAreMappedFilesTheSame (NTDLL.@)
2357 * ZwAreMappedFilesTheSame (NTDLL.@)
2359 NTSTATUS WINAPI NtAreMappedFilesTheSame(PVOID addr1, PVOID addr2)
2361 TRACE("%p %p\n", addr1, addr2);
2363 return STATUS_NOT_SAME_DEVICE;