Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / ntdll / virtual.c
blob59024e2341e5a1045c864717ac7a6d8e7ec12315
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
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "winioctl.h"
52 #include "wine/library.h"
53 #include "wine/server.h"
54 #include "wine/list.h"
55 #include "wine/debug.h"
56 #include "ntdll_misc.h"
57 #include "wine/unicode.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
60 WINE_DECLARE_DEBUG_CHANNEL(module);
62 #ifndef MS_SYNC
63 #define MS_SYNC 0
64 #endif
66 #ifndef MAP_NORESERVE
67 #define MAP_NORESERVE 0
68 #endif
70 /* File view */
71 typedef struct file_view
73 struct list entry; /* Entry in global view list */
74 void *base; /* Base address */
75 size_t size; /* Size in bytes */
76 HANDLE mapping; /* Handle to the file mapping */
77 int id; /* a unique ID for this mapping */
78 UINT refcount; /* number of times this view is references */
79 BYTE flags; /* Allocation flags (VFLAG_*) */
80 BYTE protect; /* Protection for all pages at allocation time */
81 BYTE prot[1]; /* Protection byte for each page */
82 } FILE_VIEW;
84 /* Per-view flags */
85 #define VFLAG_SYSTEM 0x01 /* system view (underlying mmap not under our control) */
86 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
88 /* Conversion from VPROT_* to Win32 flags */
89 static const BYTE VIRTUAL_Win32Flags[16] =
91 PAGE_NOACCESS, /* 0 */
92 PAGE_READONLY, /* READ */
93 PAGE_READWRITE, /* WRITE */
94 PAGE_READWRITE, /* READ | WRITE */
95 PAGE_EXECUTE, /* EXEC */
96 PAGE_EXECUTE_READ, /* READ | EXEC */
97 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
98 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
99 PAGE_WRITECOPY, /* WRITECOPY */
100 PAGE_WRITECOPY, /* READ | WRITECOPY */
101 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
102 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
103 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
104 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
105 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
106 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
109 static struct list views_list = LIST_INIT(views_list);
111 static RTL_CRITICAL_SECTION csVirtual;
112 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
114 0, 0, &csVirtual,
115 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
116 0, 0, { (DWORD_PTR)(__FILE__ ": csVirtual") }
118 static RTL_CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
120 #ifdef __i386__
121 /* These are always the same on an i386, and it will be faster this way */
122 # define page_mask 0xfff
123 # define page_shift 12
124 # define page_size 0x1000
125 /* Note: these are Windows limits, you cannot change them. */
126 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the total available address space */
127 # define USER_SPACE_LIMIT ((void *)0x7fff0000) /* top of the user address space */
128 #else
129 static UINT page_shift;
130 static UINT page_size;
131 static UINT_PTR page_mask;
132 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
133 # define USER_SPACE_LIMIT 0 /* no limit needed on other platforms */
134 #endif /* __i386__ */
136 #define ROUND_ADDR(addr,mask) \
137 ((void *)((UINT_PTR)(addr) & ~(UINT_PTR)(mask)))
139 #define ROUND_SIZE(addr,size) \
140 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
142 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
143 do { if (TRACE_ON(virtual)) VIRTUAL_DumpView(view); } while (0)
145 static void *user_space_limit = USER_SPACE_LIMIT;
146 static void *preload_reserve_start;
147 static void *preload_reserve_end;
148 static int use_locks;
149 static int force_exec_prot; /* whether to force PROT_EXEC on all PROT_READ mmaps */
152 /***********************************************************************
153 * VIRTUAL_GetProtStr
155 static const char *VIRTUAL_GetProtStr( BYTE prot )
157 static char buffer[6];
158 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
159 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
160 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
161 buffer[3] = (prot & VPROT_WRITECOPY) ? 'W' : ((prot & VPROT_WRITE) ? 'w' : '-');
162 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
163 buffer[5] = 0;
164 return buffer;
168 /***********************************************************************
169 * VIRTUAL_GetUnixProt
171 * Convert page protections to protection for mmap/mprotect.
173 static int VIRTUAL_GetUnixProt( BYTE vprot )
175 int prot = 0;
176 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
178 if (vprot & VPROT_READ) prot |= PROT_READ;
179 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
180 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
181 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
183 if (!prot) prot = PROT_NONE;
184 return prot;
188 /***********************************************************************
189 * VIRTUAL_DumpView
191 static void VIRTUAL_DumpView( FILE_VIEW *view )
193 UINT i, count;
194 char *addr = view->base;
195 BYTE prot = view->prot[0];
197 TRACE( "View: %p - %p", addr, addr + view->size - 1 );
198 if (view->flags & VFLAG_SYSTEM)
199 TRACE( " (system)\n" );
200 else if (view->flags & VFLAG_VALLOC)
201 TRACE( " (valloc)\n" );
202 else if (view->mapping)
203 TRACE( " %p\n", view->mapping );
204 else
205 TRACE( " (anonymous)\n");
207 for (count = i = 1; i < view->size >> page_shift; i++, count++)
209 if (view->prot[i] == prot) continue;
210 TRACE( " %p - %p %s\n",
211 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
212 addr += (count << page_shift);
213 prot = view->prot[i];
214 count = 0;
216 if (count)
217 TRACE( " %p - %p %s\n",
218 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
222 /***********************************************************************
223 * VIRTUAL_Dump
225 #if WINE_VM_DEBUG
226 static void VIRTUAL_Dump(void)
228 sigset_t sigset;
229 struct file_view *view;
231 TRACE( "Dump of all virtual memory views:\n" );
232 server_enter_uninterrupted_section( &csVirtual, &sigset );
233 LIST_FOR_EACH_ENTRY( view, &views_list, FILE_VIEW, entry )
235 VIRTUAL_DumpView( view );
237 server_leave_uninterrupted_section( &csVirtual, &sigset );
239 #endif
242 /***********************************************************************
243 * VIRTUAL_FindView
245 * Find the view containing a given address. The csVirtual section must be held by caller.
247 * PARAMS
248 * addr [I] Address
250 * RETURNS
251 * View: Success
252 * NULL: Failure
254 static struct file_view *VIRTUAL_FindView( const void *addr )
256 struct file_view *view;
258 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
260 if (view->base > addr) break;
261 if ((const char*)view->base + view->size > (const char*)addr) return view;
263 return NULL;
267 /***********************************************************************
268 * get_mask
270 static inline UINT_PTR get_mask( ULONG zero_bits )
272 if (!zero_bits) return 0xffff; /* allocations are aligned to 64K by default */
273 if (zero_bits < page_shift) zero_bits = page_shift;
274 return (1 << zero_bits) - 1;
278 /***********************************************************************
279 * find_view_range
281 * Find the first view overlapping at least part of the specified range.
282 * The csVirtual section must be held by caller.
284 static struct file_view *find_view_range( const void *addr, size_t size )
286 struct file_view *view;
288 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
290 if ((const char *)view->base >= (const char *)addr + size) break;
291 if ((const char *)view->base + view->size > (const char *)addr) return view;
293 return NULL;
297 /***********************************************************************
298 * find_free_area
300 * Find a free area between views inside the specified range.
301 * The csVirtual section must be held by caller.
303 static void *find_free_area( void *base, void *end, size_t size, size_t mask, int top_down )
305 struct list *ptr;
306 void *start;
308 if (top_down)
310 start = ROUND_ADDR( (char *)end - size, mask );
311 if (start >= end || start < base) return NULL;
313 for (ptr = views_list.prev; ptr != &views_list; ptr = ptr->prev)
315 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
317 if ((char *)view->base + view->size <= (char *)start) break;
318 if ((char *)view->base >= (char *)start + size) continue;
319 start = ROUND_ADDR( (char *)view->base - size, mask );
320 /* stop if remaining space is not large enough */
321 if (!start || start >= end || start < base) return NULL;
324 else
326 start = ROUND_ADDR( (char *)base + mask, mask );
327 if (start >= end || (char *)end - (char *)start < size) return NULL;
329 for (ptr = views_list.next; ptr != &views_list; ptr = ptr->next)
331 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
333 if ((char *)view->base >= (char *)start + size) break;
334 if ((char *)view->base + view->size <= (char *)start) continue;
335 start = ROUND_ADDR( (char *)view->base + view->size + mask, mask );
336 /* stop if remaining space is not large enough */
337 if (!start || start >= end || (char *)end - (char *)start < size) return NULL;
340 return start;
344 /***********************************************************************
345 * add_reserved_area
347 * Add a reserved area to the list maintained by libwine.
348 * The csVirtual section must be held by caller.
350 static void add_reserved_area( void *addr, size_t size )
352 TRACE( "adding %p-%p\n", addr, (char *)addr + size );
354 if (addr < user_space_limit)
356 /* unmap the part of the area that is below the limit */
357 assert( (char *)addr + size > (char *)user_space_limit );
358 munmap( addr, (char *)user_space_limit - (char *)addr );
359 size -= (char *)user_space_limit - (char *)addr;
360 addr = user_space_limit;
362 /* blow away existing mappings */
363 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
364 wine_mmap_add_reserved_area( addr, size );
368 /***********************************************************************
369 * is_beyond_limit
371 * Check if an address range goes beyond a given limit.
373 static inline int is_beyond_limit( void *addr, size_t size, void *limit )
375 return (limit && (addr >= limit || (char *)addr + size > (char *)limit));
378 /**********************************************************************/
379 /******************** CODEWEAVERS HACKS START HERE ********************/
381 /***********************************************************************
382 * VIRTUAL_FindViewById
384 * Find the view matching an ID
386 * RETURNS
387 * View: Success
388 * NULL: Failure
390 static BOOL VIRTUAL_FindViewById( int id, PVOID *addr_ptr, SIZE_T *size_ptr )
392 struct list *ptr;
394 LIST_FOR_EACH( ptr, &views_list )
396 struct file_view *view = LIST_ENTRY( ptr, struct file_view, entry );
397 if (view->id == id)
399 view->refcount++;
400 *size_ptr = view->size;
401 *addr_ptr = view->base;
402 return TRUE;
406 return FALSE;
409 /********************* CODEWEAVERS HACKS END HERE *********************/
410 /**********************************************************************/
413 /***********************************************************************
414 * unmap_area
416 * Unmap an area, or simply replace it by an empty mapping if it is
417 * in a reserved area. The csVirtual section must be held by caller.
419 static inline void unmap_area( void *addr, size_t size )
421 if (wine_mmap_is_in_reserved_area( addr, size ))
422 wine_anon_mmap( addr, size, PROT_NONE, MAP_NORESERVE | MAP_FIXED );
423 else if (is_beyond_limit( addr, size, user_space_limit ))
424 add_reserved_area( addr, size );
425 else
426 munmap( addr, size );
430 /***********************************************************************
431 * delete_view
433 * Deletes a view. The csVirtual section must be held by caller.
435 static void delete_view( struct file_view *view ) /* [in] View */
437 if ( --view->refcount > 0 )
438 return;
439 if (!(view->flags & VFLAG_SYSTEM)) unmap_area( view->base, view->size );
440 list_remove( &view->entry );
441 if (view->mapping) NtClose( view->mapping );
442 free( view );
446 /***********************************************************************
447 * create_view
449 * Create a view. The csVirtual section must be held by caller.
451 static NTSTATUS create_view( struct file_view **view_ret, void *base, size_t size, BYTE vprot )
453 struct file_view *view;
454 struct list *ptr;
455 int unix_prot = VIRTUAL_GetUnixProt( vprot );
457 assert( !((UINT_PTR)base & page_mask) );
458 assert( !(size & page_mask) );
460 /* Create the view structure */
462 if (!(view = malloc( sizeof(*view) + (size >> page_shift) - 1 ))) return STATUS_NO_MEMORY;
464 view->base = base;
465 view->size = size;
466 view->flags = 0;
467 view->mapping = 0;
468 view->protect = vprot;
469 view->refcount = 1;
470 view->id = 0;
471 memset( view->prot, vprot & ~VPROT_IMAGE, size >> page_shift );
473 /* Insert it in the linked list */
475 LIST_FOR_EACH( ptr, &views_list )
477 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
478 if (next->base > base) break;
480 list_add_before( ptr, &view->entry );
482 /* Check for overlapping views. This can happen if the previous view
483 * was a system view that got unmapped behind our back. In that case
484 * we recover by simply deleting it. */
486 if ((ptr = list_prev( &views_list, &view->entry )) != NULL)
488 struct file_view *prev = LIST_ENTRY( ptr, struct file_view, entry );
489 if ((char *)prev->base + prev->size > (char *)base)
491 TRACE( "overlapping prev view %p-%p for %p-%p\n",
492 prev->base, (char *)prev->base + prev->size,
493 base, (char *)base + view->size );
494 assert( prev->flags & VFLAG_SYSTEM );
495 delete_view( prev );
498 if ((ptr = list_next( &views_list, &view->entry )) != NULL)
500 struct file_view *next = LIST_ENTRY( ptr, struct file_view, entry );
501 if ((char *)base + view->size > (char *)next->base)
503 TRACE( "overlapping next view %p-%p for %p-%p\n",
504 next->base, (char *)next->base + next->size,
505 base, (char *)base + view->size );
506 assert( next->flags & VFLAG_SYSTEM );
507 delete_view( next );
511 *view_ret = view;
512 VIRTUAL_DEBUG_DUMP_VIEW( view );
514 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
516 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
517 mprotect( base, size, unix_prot | PROT_EXEC );
519 return STATUS_SUCCESS;
523 /***********************************************************************
524 * VIRTUAL_GetWin32Prot
526 * Convert page protections to Win32 flags.
528 static DWORD VIRTUAL_GetWin32Prot( BYTE vprot )
530 DWORD ret = VIRTUAL_Win32Flags[vprot & 0x0f];
531 if (vprot & VPROT_NOCACHE) ret |= PAGE_NOCACHE;
532 if (vprot & VPROT_GUARD) ret |= PAGE_GUARD;
533 return ret;
537 /***********************************************************************
538 * VIRTUAL_GetProt
540 * Build page protections from Win32 flags.
542 * PARAMS
543 * protect [I] Win32 protection flags
545 * RETURNS
546 * Value of page protection flags
548 static BYTE VIRTUAL_GetProt( DWORD protect )
550 BYTE vprot;
552 switch(protect & 0xff)
554 case PAGE_READONLY:
555 vprot = VPROT_READ;
556 break;
557 case PAGE_READWRITE:
558 vprot = VPROT_READ | VPROT_WRITE;
559 break;
560 case PAGE_WRITECOPY:
561 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
562 * that the hFile must have been opened with GENERIC_READ and
563 * GENERIC_WRITE access. This is WRONG as tests show that you
564 * only need GENERIC_READ access (at least for Win9x,
565 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
566 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
568 vprot = VPROT_READ | VPROT_WRITECOPY;
569 break;
570 case PAGE_EXECUTE:
571 vprot = VPROT_EXEC;
572 break;
573 case PAGE_EXECUTE_READ:
574 vprot = VPROT_EXEC | VPROT_READ;
575 break;
576 case PAGE_EXECUTE_READWRITE:
577 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
578 break;
579 case PAGE_EXECUTE_WRITECOPY:
580 /* See comment for PAGE_WRITECOPY above */
581 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
582 break;
583 case PAGE_NOACCESS:
584 default:
585 vprot = 0;
586 break;
588 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
589 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
590 return vprot;
594 /***********************************************************************
595 * VIRTUAL_SetProt
597 * Change the protection of a range of pages.
599 * RETURNS
600 * TRUE: Success
601 * FALSE: Failure
603 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
604 void *base, /* [in] Starting address */
605 size_t size, /* [in] Size in bytes */
606 BYTE vprot ) /* [in] Protections to use */
608 int unix_prot = VIRTUAL_GetUnixProt(vprot);
610 TRACE("%p-%p %s\n",
611 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
613 if (force_exec_prot && (unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
615 TRACE( "forcing exec permission on %p-%p\n", base, (char *)base + size - 1 );
616 if (!mprotect( base, size, unix_prot | PROT_EXEC )) goto done;
617 /* exec + write may legitimately fail, in that case fall back to write only */
618 if (!(unix_prot & PROT_WRITE)) return FALSE;
621 if (mprotect( base, size, unix_prot )) return FALSE; /* FIXME: last error */
623 done:
624 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
625 vprot, size >> page_shift );
626 VIRTUAL_DEBUG_DUMP_VIEW( view );
627 return TRUE;
631 /***********************************************************************
632 * unmap_extra_space
634 * Release the extra memory while keeping the range starting on the granularity boundary.
636 static inline void *unmap_extra_space( void *ptr, size_t total_size, size_t wanted_size, size_t mask )
638 if ((ULONG_PTR)ptr & mask)
640 size_t extra = mask + 1 - ((ULONG_PTR)ptr & mask);
641 munmap( ptr, extra );
642 ptr = (char *)ptr + extra;
643 total_size -= extra;
645 if (total_size > wanted_size)
646 munmap( (char *)ptr + wanted_size, total_size - wanted_size );
647 return ptr;
651 struct alloc_area
653 size_t size;
654 size_t mask;
655 int top_down;
656 void *result;
659 /***********************************************************************
660 * alloc_reserved_area_callback
662 * Try to map some space inside a reserved area. Callback for wine_mmap_enum_reserved_areas.
664 static int alloc_reserved_area_callback( void *start, size_t size, void *arg )
666 static void * const address_space_start = (void *)0x110000;
667 struct alloc_area *alloc = arg;
668 void *end = (char *)start + size;
670 if (start < address_space_start) start = address_space_start;
671 if (user_space_limit && end > user_space_limit) end = user_space_limit;
672 if (start >= end) return 0;
674 /* make sure we don't touch the preloader reserved range */
675 if (preload_reserve_end >= start)
677 if (preload_reserve_end >= end)
679 if (preload_reserve_start <= start) return 0; /* no space in that area */
680 if (preload_reserve_start < end) end = preload_reserve_start;
682 else if (preload_reserve_start <= start) start = preload_reserve_end;
683 else
685 /* range is split in two by the preloader reservation, try first part */
686 if ((alloc->result = find_free_area( start, preload_reserve_start, alloc->size,
687 alloc->mask, alloc->top_down )))
688 return 1;
689 /* then fall through to try second part */
690 start = preload_reserve_end;
693 if ((alloc->result = find_free_area( start, end, alloc->size, alloc->mask, alloc->top_down )))
694 return 1;
696 return 0;
700 /***********************************************************************
701 * map_view
703 * Create a view and mmap the corresponding memory area.
704 * The csVirtual section must be held by caller.
706 static NTSTATUS map_view( struct file_view **view_ret, void *base, size_t size, size_t mask,
707 int top_down, BYTE vprot )
709 void *ptr;
710 NTSTATUS status;
712 if (base)
714 if (is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
715 return STATUS_WORKING_SET_LIMIT_RANGE;
717 switch (wine_mmap_is_in_reserved_area( base, size ))
719 case -1: /* partially in a reserved area */
720 return STATUS_CONFLICTING_ADDRESSES;
722 case 0: /* not in a reserved area, do a normal allocation */
723 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
725 if (errno == ENOMEM) return STATUS_NO_MEMORY;
726 return STATUS_INVALID_PARAMETER;
728 if (ptr != base)
730 /* We couldn't get the address we wanted */
731 if (is_beyond_limit( ptr, size, user_space_limit )) add_reserved_area( ptr, size );
732 else munmap( ptr, size );
733 return STATUS_CONFLICTING_ADDRESSES;
735 break;
737 default:
738 case 1: /* in a reserved area, make sure the address is available */
739 if (find_view_range( base, size )) return STATUS_CONFLICTING_ADDRESSES;
740 /* replace the reserved area by our mapping */
741 if ((ptr = wine_anon_mmap( base, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED )) != base)
742 return STATUS_INVALID_PARAMETER;
743 break;
746 else
748 size_t view_size = size + mask + 1;
749 struct alloc_area alloc;
751 alloc.size = size;
752 alloc.mask = mask;
753 alloc.top_down = top_down;
754 if (wine_mmap_enum_reserved_areas( alloc_reserved_area_callback, &alloc, top_down ))
756 ptr = alloc.result;
757 TRACE( "got mem in reserved area %p-%p\n", ptr, (char *)ptr + size );
758 if (wine_anon_mmap( ptr, size, VIRTUAL_GetUnixProt(vprot), MAP_FIXED ) != ptr)
759 return STATUS_INVALID_PARAMETER;
760 goto done;
763 for (;;)
765 if ((ptr = wine_anon_mmap( NULL, view_size, VIRTUAL_GetUnixProt(vprot), 0 )) == (void *)-1)
767 if (errno == ENOMEM) return STATUS_NO_MEMORY;
768 return STATUS_INVALID_PARAMETER;
770 TRACE( "got mem with anon mmap %p-%p\n", ptr, (char *)ptr + size );
771 /* if we got something beyond the user limit, unmap it and retry */
772 if (is_beyond_limit( ptr, view_size, user_space_limit )) add_reserved_area( ptr, view_size );
773 else break;
775 ptr = unmap_extra_space( ptr, view_size, size, mask );
777 done:
778 status = create_view( view_ret, ptr, size, vprot );
779 if (status != STATUS_SUCCESS) unmap_area( ptr, size );
780 return status;
784 /***********************************************************************
785 * unaligned_mmap
787 * Linux kernels before 2.4.x can support non page-aligned offsets, as
788 * long as the offset is aligned to the filesystem block size. This is
789 * a big performance gain so we want to take advantage of it.
791 * However, when we use 64-bit file support this doesn't work because
792 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
793 * in that it rounds unaligned offsets down to a page boundary. For
794 * these reasons we do a direct system call here.
796 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
797 unsigned int flags, int fd, off_t offset )
799 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
800 if (!(offset >> 32) && (offset & page_mask))
802 int ret;
804 struct
806 void *addr;
807 unsigned int length;
808 unsigned int prot;
809 unsigned int flags;
810 unsigned int fd;
811 unsigned int offset;
812 } args;
814 args.addr = addr;
815 args.length = length;
816 args.prot = prot;
817 args.flags = flags;
818 args.fd = fd;
819 args.offset = offset;
821 __asm__ __volatile__("push %%ebx\n\t"
822 "movl %2,%%ebx\n\t"
823 "int $0x80\n\t"
824 "popl %%ebx"
825 : "=a" (ret)
826 : "0" (90), /* SYS_mmap */
827 "q" (&args)
828 : "memory" );
829 if (ret < 0 && ret > -4096)
831 errno = -ret;
832 ret = -1;
834 return (void *)ret;
836 #endif
837 return mmap( addr, length, prot, flags, fd, offset );
841 /***********************************************************************
842 * map_file_into_view
844 * Wrapper for mmap() to map a file into a view, falling back to read if mmap fails.
845 * The csVirtual section must be held by caller.
847 static NTSTATUS map_file_into_view( struct file_view *view, int fd, size_t start, size_t size,
848 off_t offset, BYTE vprot, BOOL removable )
850 void *ptr;
851 int prot = VIRTUAL_GetUnixProt( vprot );
852 BOOL shared_write = (vprot & VPROT_WRITE) != 0;
854 assert( start < view->size );
855 assert( start + size <= view->size );
857 /* only try mmap if media is not removable (or if we require write access) */
858 if (!removable || shared_write)
860 int flags = MAP_FIXED | (shared_write ? MAP_SHARED : MAP_PRIVATE);
862 if (unaligned_mmap( (char *)view->base + start, size, prot, flags, fd, offset ) != (void *)-1)
863 goto done;
865 /* mmap() failed; if this is because the file offset is not */
866 /* page-aligned (EINVAL), or because the underlying filesystem */
867 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
868 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return FILE_GetNtStatus();
869 if (shared_write) return FILE_GetNtStatus(); /* we cannot fake shared write mappings */
872 /* Reserve the memory with an anonymous mmap */
873 ptr = wine_anon_mmap( (char *)view->base + start, size, PROT_READ | PROT_WRITE, MAP_FIXED );
874 if (ptr == (void *)-1) return FILE_GetNtStatus();
875 /* Now read in the file */
876 pread( fd, ptr, size, offset );
877 if (prot != (PROT_READ|PROT_WRITE)) mprotect( ptr, size, prot ); /* Set the right protection */
878 done:
879 memset( view->prot + (start >> page_shift), vprot, ROUND_SIZE(start,size) >> page_shift );
880 return STATUS_SUCCESS;
884 /***********************************************************************
885 * decommit_view
887 * Decommit some pages of a given view.
888 * The csVirtual section must be held by caller.
890 static NTSTATUS decommit_pages( struct file_view *view, size_t start, size_t size )
892 if (wine_anon_mmap( (char *)view->base + start, size, PROT_NONE, MAP_FIXED ) != (void *)-1)
894 BYTE *p = view->prot + (start >> page_shift);
895 size >>= page_shift;
896 while (size--) *p++ &= ~VPROT_COMMITTED;
897 return STATUS_SUCCESS;
899 return FILE_GetNtStatus();
903 /***********************************************************************
904 * do_relocations
906 * Apply the relocations to a mapped PE image
908 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
909 int delta, SIZE_T total_size )
911 IMAGE_BASE_RELOCATION *rel;
913 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
914 base - delta, base - delta + total_size, base, base + total_size );
916 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
917 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
918 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
920 char *page = base + rel->VirtualAddress;
921 WORD *TypeOffset = (WORD *)(rel + 1);
922 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
924 if (!count) continue;
926 /* sanity checks */
927 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size)
929 ERR_(module)("invalid relocation %p,%x,%d at %p,%x,%x\n",
930 rel, rel->VirtualAddress, rel->SizeOfBlock,
931 base, dir->VirtualAddress, dir->Size );
932 return 0;
935 if (page > base + total_size)
937 WARN_(module)("skipping %d relocations for page %p beyond module %p-%p\n",
938 count, page, base, base + total_size );
939 continue;
942 TRACE_(module)("%d relocations for page %x\n", count, rel->VirtualAddress);
944 /* patching in reverse order */
945 for (i = 0 ; i < count; i++)
947 int offset = TypeOffset[i] & 0xFFF;
948 int type = TypeOffset[i] >> 12;
949 switch(type)
951 case IMAGE_REL_BASED_ABSOLUTE:
952 break;
953 case IMAGE_REL_BASED_HIGH:
954 *(short*)(page+offset) += HIWORD(delta);
955 break;
956 case IMAGE_REL_BASED_LOW:
957 *(short*)(page+offset) += LOWORD(delta);
958 break;
959 case IMAGE_REL_BASED_HIGHLOW:
960 *(int*)(page+offset) += delta;
961 /* FIXME: if this is an exported address, fire up enhanced logic */
962 break;
963 default:
964 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
965 break;
969 return 1;
973 /***********************************************************************
974 * map_image
976 * Map an executable (PE format) image into memory.
978 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, SIZE_T total_size, SIZE_T mask,
979 SIZE_T header_size, int shared_fd, HANDLE dup_mapping, PVOID *addr_ptr )
981 IMAGE_DOS_HEADER *dos;
982 IMAGE_NT_HEADERS *nt;
983 IMAGE_SECTION_HEADER *sec;
984 IMAGE_DATA_DIRECTORY *imports;
985 NTSTATUS status = STATUS_CONFLICTING_ADDRESSES;
986 int i;
987 off_t pos;
988 sigset_t sigset;
989 struct stat st;
990 struct file_view *view = NULL;
991 char *ptr, *header_end;
993 /* zero-map the whole range */
995 server_enter_uninterrupted_section( &csVirtual, &sigset );
997 if (base >= (char *)0x110000) /* make sure the DOS area remains free */
998 status = map_view( &view, base, total_size, mask, FALSE,
999 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1001 if (status == STATUS_CONFLICTING_ADDRESSES)
1002 status = map_view( &view, NULL, total_size, mask, FALSE,
1003 VPROT_COMMITTED | VPROT_READ | VPROT_EXEC | VPROT_WRITECOPY | VPROT_IMAGE );
1005 if (status != STATUS_SUCCESS) goto error;
1007 ptr = view->base;
1008 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
1010 /* map the header */
1012 if (fstat( fd, &st ) == -1)
1014 status = FILE_GetNtStatus();
1015 goto error;
1017 status = STATUS_INVALID_IMAGE_FORMAT; /* generic error */
1018 if (!st.st_size) goto error;
1019 header_size = min( header_size, st.st_size );
1020 if (map_file_into_view( view, fd, 0, header_size, 0, VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1021 !dup_mapping ) != STATUS_SUCCESS) goto error;
1022 dos = (IMAGE_DOS_HEADER *)ptr;
1023 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
1024 header_end = ptr + ROUND_SIZE( 0, header_size );
1025 memset( ptr + header_size, 0, header_end - (ptr + header_size) );
1026 if ((char *)(nt + 1) > header_end) goto error;
1027 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1028 if ((char *)(sec + nt->FileHeader.NumberOfSections) > header_end) goto error;
1030 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
1031 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
1033 /* check the architecture */
1035 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
1037 MESSAGE("Trying to load PE image for unsupported architecture (");
1038 switch (nt->FileHeader.Machine)
1040 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
1041 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
1042 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
1043 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
1044 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
1045 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
1046 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
1047 case IMAGE_FILE_MACHINE_IA64: MESSAGE("IA-64"); break;
1048 case IMAGE_FILE_MACHINE_ALPHA64: MESSAGE("Alpha-64"); break;
1049 case IMAGE_FILE_MACHINE_AMD64: MESSAGE("AMD-64"); break;
1050 case IMAGE_FILE_MACHINE_ARM: MESSAGE("ARM"); break;
1051 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
1053 MESSAGE(")\n");
1054 goto error;
1057 /* check for non page-aligned binary */
1059 if (nt->OptionalHeader.SectionAlignment <= page_mask)
1061 /* unaligned sections, this happens for native subsystem binaries */
1062 /* in that case Windows simply maps in the whole file */
1064 if (map_file_into_view( view, fd, 0, total_size, 0, VPROT_COMMITTED | VPROT_READ,
1065 !dup_mapping ) != STATUS_SUCCESS) goto error;
1067 /* check that all sections are loaded at the right offset */
1068 if (nt->OptionalHeader.FileAlignment != nt->OptionalHeader.SectionAlignment) goto error;
1069 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1071 if (sec[i].VirtualAddress != sec[i].PointerToRawData)
1072 goto error; /* Windows refuses to load in that case too */
1075 /* set the image protections */
1076 VIRTUAL_SetProt( view, ptr, total_size,
1077 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1079 /* perform relocations if necessary */
1080 /* FIXME: not 100% compatible, Windows doesn't do this for non page-aligned binaries */
1081 if (ptr != base)
1083 const IMAGE_DATA_DIRECTORY *relocs;
1084 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1085 if (relocs->VirtualAddress && relocs->Size)
1086 do_relocations( ptr, relocs, ptr - base, total_size );
1089 goto done;
1093 /* map all the sections */
1095 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1097 static const SIZE_T sector_align = 0x1ff;
1098 SIZE_T map_size, file_start, file_size, end;
1100 if (!sec->Misc.VirtualSize)
1101 map_size = ROUND_SIZE( 0, sec->SizeOfRawData );
1102 else
1103 map_size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
1105 /* file positions are rounded to sector boundaries regardless of OptionalHeader.FileAlignment */
1106 file_start = sec->PointerToRawData & ~sector_align;
1107 file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
1108 if (file_size > map_size) file_size = map_size;
1110 /* a few sanity checks */
1111 end = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, map_size );
1112 if (sec->VirtualAddress > total_size || end > total_size || end < sec->VirtualAddress)
1114 WARN_(module)( "Section %.8s too large (%x+%lx/%lx)\n",
1115 sec->Name, sec->VirtualAddress, map_size, total_size );
1116 goto error;
1119 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
1120 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
1122 TRACE_(module)( "mapping shared section %.8s at %p off %x (%x) size %lx (%lx) flags %x\n",
1123 sec->Name, ptr + sec->VirtualAddress,
1124 sec->PointerToRawData, (int)pos, file_size, map_size,
1125 sec->Characteristics );
1126 if (map_file_into_view( view, shared_fd, sec->VirtualAddress, map_size, pos,
1127 VPROT_COMMITTED | VPROT_READ | VPROT_WRITE,
1128 FALSE ) != STATUS_SUCCESS)
1130 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
1131 goto error;
1134 /* check if the import directory falls inside this section */
1135 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
1136 imports->VirtualAddress < sec->VirtualAddress + map_size)
1138 UINT_PTR base = imports->VirtualAddress & ~page_mask;
1139 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
1140 if (end > sec->VirtualAddress + map_size) end = sec->VirtualAddress + map_size;
1141 if (end > base)
1142 map_file_into_view( view, shared_fd, base, end - base,
1143 pos + (base - sec->VirtualAddress),
1144 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1145 FALSE );
1147 pos += map_size;
1148 continue;
1151 TRACE_(module)( "mapping section %.8s at %p off %x size %x virt %x flags %x\n",
1152 sec->Name, ptr + sec->VirtualAddress,
1153 sec->PointerToRawData, sec->SizeOfRawData,
1154 sec->Misc.VirtualSize, sec->Characteristics );
1156 if (!sec->PointerToRawData || !file_size) continue;
1158 /* Note: if the section is not aligned properly map_file_into_view will magically
1159 * fall back to read(), so we don't need to check anything here.
1161 end = file_start + file_size;
1162 if (sec->PointerToRawData >= st.st_size ||
1163 end > ((st.st_size + sector_align) & ~sector_align) ||
1164 end < file_start ||
1165 map_file_into_view( view, fd, sec->VirtualAddress, file_size, file_start,
1166 VPROT_COMMITTED | VPROT_READ | VPROT_WRITECOPY,
1167 !dup_mapping ) != STATUS_SUCCESS)
1169 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
1170 goto error;
1173 if (file_size & page_mask)
1175 end = ROUND_SIZE( 0, file_size );
1176 if (end > map_size) end = map_size;
1177 TRACE_(module)("clearing %p - %p\n",
1178 ptr + sec->VirtualAddress + file_size,
1179 ptr + sec->VirtualAddress + end );
1180 memset( ptr + sec->VirtualAddress + file_size, 0, end - file_size );
1185 /* perform base relocation, if necessary */
1187 if (ptr != base)
1189 const IMAGE_DATA_DIRECTORY *relocs;
1191 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1192 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1194 WARN( "Need to relocate module from addr %x, but there are no relocation records\n",
1195 nt->OptionalHeader.ImageBase );
1196 status = STATUS_CONFLICTING_ADDRESSES;
1197 goto error;
1200 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
1201 * really make sure that the *new* base address is also > 2GB.
1202 * Some DLLs really check the MSB of the module handle :-/
1204 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((ULONG_PTR)base & 0x80000000))
1205 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
1207 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
1209 goto error;
1213 /* set the image protections */
1215 VIRTUAL_SetProt( view, ptr, ROUND_SIZE( 0, header_size ), VPROT_COMMITTED | VPROT_READ );
1217 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
1218 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1220 SIZE_T size;
1221 BYTE vprot = VPROT_COMMITTED;
1223 if (sec->Misc.VirtualSize)
1224 size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
1225 else
1226 size = ROUND_SIZE( sec->VirtualAddress, sec->SizeOfRawData );
1228 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
1229 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_READ|VPROT_WRITECOPY;
1230 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
1232 /* Dumb game crack lets the AOEP point into a data section. Adjust. */
1233 if ((nt->OptionalHeader.AddressOfEntryPoint >= sec->VirtualAddress) &&
1234 (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress + size))
1235 vprot |= VPROT_EXEC;
1237 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
1240 done:
1241 view->mapping = dup_mapping;
1242 server_leave_uninterrupted_section( &csVirtual, &sigset );
1244 *addr_ptr = ptr;
1245 return STATUS_SUCCESS;
1247 error:
1248 if (view) delete_view( view );
1249 server_leave_uninterrupted_section( &csVirtual, &sigset );
1250 if (dup_mapping) NtClose( dup_mapping );
1251 return status;
1255 /***********************************************************************
1256 * virtual_init
1258 void virtual_init(void)
1260 const char *preload;
1261 #ifndef page_mask
1262 page_size = getpagesize();
1263 page_mask = page_size - 1;
1264 /* Make sure we have a power of 2 */
1265 assert( !(page_size & page_mask) );
1266 page_shift = 0;
1267 while ((1 << page_shift) != page_size) page_shift++;
1268 #endif /* page_mask */
1269 if ((preload = getenv("WINEPRELOADRESERVE")))
1271 unsigned long start, end;
1272 if (sscanf( preload, "%lx-%lx", &start, &end ) == 2)
1274 preload_reserve_start = (void *)start;
1275 preload_reserve_end = (void *)end;
1281 /***********************************************************************
1282 * virtual_init_threading
1284 void virtual_init_threading(void)
1286 use_locks = 1;
1290 /***********************************************************************
1291 * VIRTUAL_HandleFault
1293 NTSTATUS VIRTUAL_HandleFault( LPCVOID addr )
1295 FILE_VIEW *view;
1296 NTSTATUS ret = STATUS_ACCESS_VIOLATION;
1297 sigset_t sigset;
1299 server_enter_uninterrupted_section( &csVirtual, &sigset );
1300 if ((view = VIRTUAL_FindView( addr )))
1302 void *page = ROUND_ADDR( addr, page_mask );
1303 BYTE vprot = view->prot[((const char *)page - (const char *)view->base) >> page_shift];
1304 if (vprot & VPROT_GUARD)
1306 VIRTUAL_SetProt( view, page, page_size, vprot & ~VPROT_GUARD );
1307 ret = STATUS_GUARD_PAGE_VIOLATION;
1310 server_leave_uninterrupted_section( &csVirtual, &sigset );
1311 return ret;
1315 /***********************************************************************
1316 * VIRTUAL_SetForceExec
1318 * Whether to force exec prot on all views.
1320 void VIRTUAL_SetForceExec( BOOL enable )
1322 struct file_view *view;
1323 sigset_t sigset;
1325 server_enter_uninterrupted_section( &csVirtual, &sigset );
1326 if (!force_exec_prot != !enable) /* change all existing views */
1328 force_exec_prot = enable;
1330 LIST_FOR_EACH_ENTRY( view, &views_list, struct file_view, entry )
1332 UINT i, count;
1333 int unix_prot;
1334 char *addr = view->base;
1335 BYTE prot = view->prot[0];
1337 for (count = i = 1; i < view->size >> page_shift; i++, count++)
1339 if (view->prot[i] == prot) continue;
1340 unix_prot = VIRTUAL_GetUnixProt( prot );
1341 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1343 TRACE( "%s exec prot for %p-%p\n",
1344 force_exec_prot ? "enabling" : "disabling",
1345 addr, addr + (count << page_shift) - 1 );
1346 mprotect( addr, count << page_shift,
1347 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1349 addr += (count << page_shift);
1350 prot = view->prot[i];
1351 count = 0;
1353 if (count)
1355 unix_prot = VIRTUAL_GetUnixProt( prot );
1356 if ((unix_prot & PROT_READ) && !(unix_prot & PROT_EXEC))
1358 TRACE( "%s exec prot for %p-%p\n",
1359 force_exec_prot ? "enabling" : "disabling",
1360 addr, addr + (count << page_shift) - 1 );
1361 mprotect( addr, count << page_shift,
1362 unix_prot | (force_exec_prot ? PROT_EXEC : 0) );
1367 server_leave_uninterrupted_section( &csVirtual, &sigset );
1371 /***********************************************************************
1372 * VIRTUAL_UseLargeAddressSpace
1374 * Increase the address space size for apps that support it.
1376 void VIRTUAL_UseLargeAddressSpace(void)
1378 /* no large address space on win9x */
1379 if (NtCurrentTeb()->Peb->OSPlatformId != VER_PLATFORM_WIN32_NT) return;
1380 user_space_limit = ADDRESS_SPACE_LIMIT;
1384 /***********************************************************************
1385 * NtAllocateVirtualMemory (NTDLL.@)
1386 * ZwAllocateVirtualMemory (NTDLL.@)
1388 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, ULONG zero_bits,
1389 SIZE_T *size_ptr, ULONG type, ULONG protect )
1391 void *base;
1392 BYTE vprot;
1393 SIZE_T size = *size_ptr;
1394 SIZE_T mask = get_mask( zero_bits );
1395 NTSTATUS status = STATUS_SUCCESS;
1396 struct file_view *view;
1397 sigset_t sigset;
1399 TRACE("%p %p %08lx %x %08x\n", process, *ret, size, type, protect );
1401 if (!size) return STATUS_INVALID_PARAMETER;
1403 if (process != NtCurrentProcess())
1405 apc_call_t call;
1406 apc_result_t result;
1408 call.virtual_alloc.type = APC_VIRTUAL_ALLOC;
1409 call.virtual_alloc.addr = *ret;
1410 call.virtual_alloc.size = *size_ptr;
1411 call.virtual_alloc.zero_bits = zero_bits;
1412 call.virtual_alloc.op_type = type;
1413 call.virtual_alloc.prot = protect;
1414 status = NTDLL_queue_process_apc( process, &call, &result );
1415 if (status != STATUS_SUCCESS) return status;
1417 if (result.virtual_alloc.status == STATUS_SUCCESS)
1419 *ret = result.virtual_alloc.addr;
1420 *size_ptr = result.virtual_alloc.size;
1422 return result.virtual_alloc.status;
1425 /* Round parameters to a page boundary */
1427 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
1429 if (*ret)
1431 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1432 base = ROUND_ADDR( *ret, mask );
1433 else
1434 base = ROUND_ADDR( *ret, page_mask );
1435 size = (((UINT_PTR)*ret + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1437 /* disallow low 64k, wrap-around and kernel space */
1438 if (((char *)base < (char *)0x10000) ||
1439 ((char *)base + size < (char *)base) ||
1440 is_beyond_limit( base, size, ADDRESS_SPACE_LIMIT ))
1441 return STATUS_INVALID_PARAMETER;
1443 else
1445 base = NULL;
1446 size = (size + page_mask) & ~page_mask;
1449 /* Compute the alloc type flags */
1451 if (!(type & MEM_SYSTEM))
1453 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
1454 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_WRITE_WATCH | MEM_RESET)))
1456 WARN("called with wrong alloc type flags (%08x) !\n", type);
1457 return STATUS_INVALID_PARAMETER;
1459 if (type & MEM_WRITE_WATCH)
1461 FIXME("MEM_WRITE_WATCH type not supported\n");
1462 return STATUS_NOT_SUPPORTED;
1465 vprot = VIRTUAL_GetProt( protect );
1466 if (type & MEM_COMMIT) vprot |= VPROT_COMMITTED;
1468 /* Reserve the memory */
1470 if (use_locks) server_enter_uninterrupted_section( &csVirtual, &sigset );
1472 if (type & MEM_SYSTEM)
1474 if (type & MEM_IMAGE) vprot |= VPROT_IMAGE;
1475 status = create_view( &view, base, size, vprot | VPROT_COMMITTED );
1476 if (status == STATUS_SUCCESS)
1478 view->flags |= VFLAG_VALLOC | VFLAG_SYSTEM;
1479 base = view->base;
1482 else if ((type & MEM_RESERVE) || !base)
1484 status = map_view( &view, base, size, mask, type & MEM_TOP_DOWN, vprot );
1485 if (status == STATUS_SUCCESS)
1487 view->flags |= VFLAG_VALLOC;
1488 base = view->base;
1491 else /* commit the pages */
1493 if (!(view = VIRTUAL_FindView( base )) ||
1494 ((char *)base + size > (char *)view->base + view->size)) status = STATUS_NOT_MAPPED_VIEW;
1495 else if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1498 if (use_locks) server_leave_uninterrupted_section( &csVirtual, &sigset );
1500 if (status == STATUS_SUCCESS)
1502 *ret = base;
1503 *size_ptr = size;
1505 return status;
1509 /***********************************************************************
1510 * NtFreeVirtualMemory (NTDLL.@)
1511 * ZwFreeVirtualMemory (NTDLL.@)
1513 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr, ULONG type )
1515 FILE_VIEW *view;
1516 char *base;
1517 sigset_t sigset;
1518 NTSTATUS status = STATUS_SUCCESS;
1519 LPVOID addr = *addr_ptr;
1520 SIZE_T size = *size_ptr;
1522 TRACE("%p %p %08lx %x\n", process, addr, size, type );
1524 if (process != NtCurrentProcess())
1526 apc_call_t call;
1527 apc_result_t result;
1529 call.virtual_free.type = APC_VIRTUAL_FREE;
1530 call.virtual_free.addr = addr;
1531 call.virtual_free.size = size;
1532 call.virtual_free.op_type = type;
1533 status = NTDLL_queue_process_apc( process, &call, &result );
1534 if (status != STATUS_SUCCESS) return status;
1536 if (result.virtual_free.status == STATUS_SUCCESS)
1538 *addr_ptr = result.virtual_free.addr;
1539 *size_ptr = result.virtual_free.size;
1541 return result.virtual_free.status;
1544 /* Fix the parameters */
1546 size = ROUND_SIZE( addr, size );
1547 base = ROUND_ADDR( addr, page_mask );
1549 /* avoid freeing the DOS area when a broken app passes a NULL pointer */
1550 if (!base && !(type & MEM_SYSTEM)) return STATUS_INVALID_PARAMETER;
1552 server_enter_uninterrupted_section( &csVirtual, &sigset );
1554 if (!(view = VIRTUAL_FindView( base )) ||
1555 (base + size > (char *)view->base + view->size) ||
1556 !(view->flags & VFLAG_VALLOC))
1558 status = STATUS_INVALID_PARAMETER;
1560 else if (type & MEM_SYSTEM)
1562 /* return the values that the caller should use to unmap the area */
1563 *addr_ptr = view->base;
1564 if (!wine_mmap_is_in_reserved_area( view->base, view->size )) *size_ptr = view->size;
1565 else *size_ptr = 0; /* make sure we don't munmap anything from a reserved area */
1566 view->flags |= VFLAG_SYSTEM;
1567 delete_view( view );
1569 else if (type == MEM_RELEASE)
1571 /* Free the pages */
1573 if (size || (base != view->base)) status = STATUS_INVALID_PARAMETER;
1574 else
1576 delete_view( view );
1577 *addr_ptr = base;
1578 *size_ptr = size;
1581 else if (type == MEM_DECOMMIT)
1583 status = decommit_pages( view, base - (char *)view->base, size );
1584 if (status == STATUS_SUCCESS)
1586 *addr_ptr = base;
1587 *size_ptr = size;
1590 else
1592 WARN("called with wrong free type flags (%08x) !\n", type);
1593 status = STATUS_INVALID_PARAMETER;
1596 server_leave_uninterrupted_section( &csVirtual, &sigset );
1597 return status;
1601 /***********************************************************************
1602 * NtProtectVirtualMemory (NTDLL.@)
1603 * ZwProtectVirtualMemory (NTDLL.@)
1605 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, SIZE_T *size_ptr,
1606 ULONG new_prot, ULONG *old_prot )
1608 FILE_VIEW *view;
1609 sigset_t sigset;
1610 NTSTATUS status = STATUS_SUCCESS;
1611 char *base;
1612 UINT i;
1613 BYTE vprot, *p;
1614 ULONG prot;
1615 SIZE_T size = *size_ptr;
1616 LPVOID addr = *addr_ptr;
1618 TRACE("%p %p %08lx %08x\n", process, addr, size, new_prot );
1620 if (process != NtCurrentProcess())
1622 apc_call_t call;
1623 apc_result_t result;
1625 call.virtual_protect.type = APC_VIRTUAL_PROTECT;
1626 call.virtual_protect.addr = addr;
1627 call.virtual_protect.size = size;
1628 call.virtual_protect.prot = new_prot;
1629 status = NTDLL_queue_process_apc( process, &call, &result );
1630 if (status != STATUS_SUCCESS) return status;
1632 if (result.virtual_protect.status == STATUS_SUCCESS)
1634 *addr_ptr = result.virtual_protect.addr;
1635 *size_ptr = result.virtual_protect.size;
1636 if (old_prot) *old_prot = result.virtual_protect.prot;
1638 return result.virtual_protect.status;
1641 /* Fix the parameters */
1643 size = ROUND_SIZE( addr, size );
1644 base = ROUND_ADDR( addr, page_mask );
1646 server_enter_uninterrupted_section( &csVirtual, &sigset );
1648 if (!(view = VIRTUAL_FindView( base )) || (base + size > (char *)view->base + view->size))
1650 status = STATUS_INVALID_PARAMETER;
1652 else
1654 /* Make sure all the pages are committed */
1656 p = view->prot + ((base - (char *)view->base) >> page_shift);
1657 prot = VIRTUAL_GetWin32Prot( *p );
1658 for (i = size >> page_shift; i; i--, p++)
1660 if (!(*p & VPROT_COMMITTED))
1662 status = STATUS_NOT_COMMITTED;
1663 break;
1666 if (!i)
1668 if (old_prot) *old_prot = prot;
1669 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1670 if (!VIRTUAL_SetProt( view, base, size, vprot )) status = STATUS_ACCESS_DENIED;
1673 server_leave_uninterrupted_section( &csVirtual, &sigset );
1675 if (status == STATUS_SUCCESS)
1677 *addr_ptr = base;
1678 *size_ptr = size;
1680 return status;
1683 #define UNIMPLEMENTED_INFO_CLASS(c) \
1684 case c: \
1685 FIXME("(process=%p,addr=%p) Unimplemented information class: " #c "\n", process, addr); \
1686 return STATUS_INVALID_INFO_CLASS
1688 /***********************************************************************
1689 * NtQueryVirtualMemory (NTDLL.@)
1690 * ZwQueryVirtualMemory (NTDLL.@)
1692 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1693 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1694 SIZE_T len, SIZE_T *res_len )
1696 FILE_VIEW *view;
1697 char *base, *alloc_base = 0;
1698 struct list *ptr;
1699 SIZE_T size = 0;
1700 MEMORY_BASIC_INFORMATION *info = buffer;
1701 sigset_t sigset;
1703 if (info_class != MemoryBasicInformation)
1705 switch(info_class)
1707 UNIMPLEMENTED_INFO_CLASS(MemoryWorkingSetList);
1708 UNIMPLEMENTED_INFO_CLASS(MemorySectionName);
1709 UNIMPLEMENTED_INFO_CLASS(MemoryBasicVlmInformation);
1711 default:
1712 FIXME("(%p,%p,info_class=%d,%p,%ld,%p) Unknown information class\n",
1713 process, addr, info_class, buffer, len, res_len);
1714 return STATUS_INVALID_INFO_CLASS;
1717 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1718 return STATUS_WORKING_SET_LIMIT_RANGE;
1720 if (process != NtCurrentProcess())
1722 NTSTATUS status;
1723 apc_call_t call;
1724 apc_result_t result;
1726 call.virtual_query.type = APC_VIRTUAL_QUERY;
1727 call.virtual_query.addr = addr;
1728 status = NTDLL_queue_process_apc( process, &call, &result );
1729 if (status != STATUS_SUCCESS) return status;
1731 if (result.virtual_query.status == STATUS_SUCCESS)
1733 info->BaseAddress = result.virtual_query.base;
1734 info->AllocationBase = result.virtual_query.alloc_base;
1735 info->RegionSize = result.virtual_query.size;
1736 info->State = result.virtual_query.state;
1737 info->Protect = result.virtual_query.prot;
1738 info->AllocationProtect = result.virtual_query.alloc_prot;
1739 info->Type = result.virtual_query.alloc_type;
1740 if (res_len) *res_len = sizeof(*info);
1742 return result.virtual_query.status;
1745 base = ROUND_ADDR( addr, page_mask );
1747 /* Find the view containing the address */
1749 server_enter_uninterrupted_section( &csVirtual, &sigset );
1750 ptr = list_head( &views_list );
1751 for (;;)
1753 if (!ptr)
1755 /* make the address space end at the user limit, except if
1756 * the last view was mapped beyond that */
1757 if (alloc_base <= (char *)user_space_limit)
1759 if (user_space_limit && base >= (char *)user_space_limit)
1761 server_leave_uninterrupted_section( &csVirtual, &sigset );
1762 return STATUS_WORKING_SET_LIMIT_RANGE;
1764 size = (char *)user_space_limit - alloc_base;
1766 else size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1767 view = NULL;
1768 break;
1770 view = LIST_ENTRY( ptr, struct file_view, entry );
1771 if ((char *)view->base > base)
1773 size = (char *)view->base - alloc_base;
1774 view = NULL;
1775 break;
1777 if ((char *)view->base + view->size > base)
1779 alloc_base = view->base;
1780 size = view->size;
1781 break;
1783 alloc_base = (char *)view->base + view->size;
1784 ptr = list_next( &views_list, ptr );
1787 /* Fill the info structure */
1789 if (view)
1791 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1792 info->State = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
1793 info->Protect = VIRTUAL_GetWin32Prot( vprot );
1794 info->AllocationBase = alloc_base;
1795 info->AllocationProtect = VIRTUAL_GetWin32Prot( view->protect );
1796 if (view->protect & VPROT_IMAGE) info->Type = MEM_IMAGE;
1797 else if (view->flags & VFLAG_VALLOC) info->Type = MEM_PRIVATE;
1798 else info->Type = MEM_MAPPED;
1799 for (size = base - alloc_base; size < view->size; size += page_size)
1800 if (view->prot[size >> page_shift] != vprot) break;
1801 size -= base - alloc_base;
1803 else
1805 unsigned char vec;
1806 size_t i;
1807 int rc;
1809 rc = mincore((caddr_t)base, page_size, &vec);
1810 if (rc == -1)
1812 TRACE("mincore() == -1: %p is free\n", base);
1813 info->State = MEM_FREE;
1814 info->Protect = PAGE_NOACCESS;
1815 info->AllocationBase = 0;
1816 info->AllocationProtect = 0;
1817 info->Type = 0;
1819 else
1821 /* We don't have any real information for these
1822 * so make something up
1824 TRACE("mincore() == 0: %p is in use\n", base);
1825 info->State = MEM_COMMIT;
1826 info->Protect = PAGE_EXECUTE_READ;
1827 info->AllocationProtect = PAGE_EXECUTE_READ;
1828 info->Type = MEM_MAPPED;
1831 /* Scan up so we see how big this range really is */
1832 size -= base - alloc_base;
1833 for (i = page_size; i < size; i += page_size)
1835 if (mincore((caddr_t)base + i, page_size, &vec) != rc)
1837 TRACE("mincore() != %d for %p\n", rc, base + i);
1838 break;
1841 size = i;
1843 /* And scan down so we report the proper AllocationBase */
1844 for (i = page_size; i <= base - alloc_base; i += page_size)
1846 if (mincore((caddr_t)base - i, page_size, &vec) != rc)
1848 TRACE("mincore() != %d for %p\n", rc, base - i);
1849 break;
1852 alloc_base = base - (i - page_size);
1853 if (info->State != MEM_FREE) info->AllocationBase = alloc_base;
1855 server_leave_uninterrupted_section( &csVirtual, &sigset );
1857 info->BaseAddress = base;
1858 info->RegionSize = size;
1859 if (res_len) *res_len = sizeof(*info);
1860 TRACE("%p-%p alloc=%p size=0x%08lx State=%04x Protect=%04x Type=%04x\n", base, base+size, alloc_base, size, info->State, info->Protect, info->Type);
1861 return STATUS_SUCCESS;
1865 /***********************************************************************
1866 * NtLockVirtualMemory (NTDLL.@)
1867 * ZwLockVirtualMemory (NTDLL.@)
1869 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1871 NTSTATUS status = STATUS_SUCCESS;
1873 if (process != NtCurrentProcess())
1875 apc_call_t call;
1876 apc_result_t result;
1878 call.virtual_lock.type = APC_VIRTUAL_LOCK;
1879 call.virtual_lock.addr = *addr;
1880 call.virtual_lock.size = *size;
1881 status = NTDLL_queue_process_apc( process, &call, &result );
1882 if (status != STATUS_SUCCESS) return status;
1884 if (result.virtual_lock.status == STATUS_SUCCESS)
1886 *addr = result.virtual_lock.addr;
1887 *size = result.virtual_lock.size;
1889 return result.virtual_lock.status;
1892 *size = ROUND_SIZE( *addr, *size );
1893 *addr = ROUND_ADDR( *addr, page_mask );
1895 if (mlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1896 return status;
1900 /***********************************************************************
1901 * NtUnlockVirtualMemory (NTDLL.@)
1902 * ZwUnlockVirtualMemory (NTDLL.@)
1904 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, SIZE_T *size, ULONG unknown )
1906 NTSTATUS status = STATUS_SUCCESS;
1908 if (process != NtCurrentProcess())
1910 apc_call_t call;
1911 apc_result_t result;
1913 call.virtual_unlock.type = APC_VIRTUAL_UNLOCK;
1914 call.virtual_unlock.addr = *addr;
1915 call.virtual_unlock.size = *size;
1916 status = NTDLL_queue_process_apc( process, &call, &result );
1917 if (status != STATUS_SUCCESS) return status;
1919 if (result.virtual_unlock.status == STATUS_SUCCESS)
1921 *addr = result.virtual_unlock.addr;
1922 *size = result.virtual_unlock.size;
1924 return result.virtual_unlock.status;
1927 *size = ROUND_SIZE( *addr, *size );
1928 *addr = ROUND_ADDR( *addr, page_mask );
1930 if (munlock( *addr, *size )) status = STATUS_ACCESS_DENIED;
1931 return status;
1935 /***********************************************************************
1936 * NtCreateSection (NTDLL.@)
1937 * ZwCreateSection (NTDLL.@)
1939 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1940 const LARGE_INTEGER *size, ULONG protect,
1941 ULONG sec_flags, HANDLE file )
1943 NTSTATUS ret;
1944 BYTE vprot;
1945 DWORD len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
1947 /******************** CODEWEAVERS HACKS START HERE ********************/
1948 DWORD hack_val = 0;
1949 WCHAR cw_magic[] = { 'M','A','P','I','-','H','P','!' };
1951 if( (file==NULL) && (len>sizeof cw_magic) &&
1952 !memcmp( cw_magic, attr->ObjectName->Buffer, sizeof cw_magic ) )
1954 hack_val = 1;
1956 /******************** CODEWEAVERS HACKS ENDS HERE *********************/
1958 /* Check parameters */
1960 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1962 vprot = VIRTUAL_GetProt( protect );
1963 if (sec_flags & SEC_RESERVE)
1965 if (file) return STATUS_INVALID_PARAMETER;
1967 else vprot |= VPROT_COMMITTED;
1968 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1969 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1971 /* Create the server object */
1973 SERVER_START_REQ( create_mapping )
1975 req->access = access;
1976 req->attributes = (attr) ? attr->Attributes : 0;
1977 req->rootdir = attr ? attr->RootDirectory : 0;
1978 req->file_handle = file;
1979 req->size_high = size ? size->u.HighPart : 0;
1980 req->size_low = size ? size->u.LowPart : 0;
1981 req->protect = vprot;
1982 req->hack_val = hack_val;
1983 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1984 ret = wine_server_call( req );
1985 *handle = reply->handle;
1987 SERVER_END_REQ;
1988 return ret;
1992 /***********************************************************************
1993 * NtOpenSection (NTDLL.@)
1994 * ZwOpenSection (NTDLL.@)
1996 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1998 NTSTATUS ret;
1999 DWORD len = attr->ObjectName->Length;
2001 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
2003 SERVER_START_REQ( open_mapping )
2005 req->access = access;
2006 req->attributes = (attr) ? attr->Attributes : 0;
2007 req->rootdir = attr ? attr->RootDirectory : 0;
2008 wine_server_add_data( req, attr->ObjectName->Buffer, len );
2009 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
2011 SERVER_END_REQ;
2012 return ret;
2016 /***********************************************************************
2017 * NtMapViewOfSection (NTDLL.@)
2018 * ZwMapViewOfSection (NTDLL.@)
2020 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
2021 SIZE_T commit_size, const LARGE_INTEGER *offset_ptr, SIZE_T *size_ptr,
2022 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
2024 NTSTATUS res;
2025 SIZE_T size = 0;
2026 SIZE_T mask = get_mask( zero_bits );
2027 int unix_handle = -1, needs_close;
2028 int prot;
2029 void *base;
2030 struct file_view *view;
2031 DWORD size_low, size_high, header_size, shared_size;
2032 HANDLE dup_mapping, shared_file;
2033 LARGE_INTEGER offset;
2034 sigset_t sigset;
2035 int id, hack_val;
2037 offset.QuadPart = offset_ptr ? offset_ptr->QuadPart : 0;
2039 TRACE("handle=%p process=%p addr=%p off=%x%08x size=%lx access=%x\n",
2040 handle, process, *addr_ptr, offset.u.HighPart, offset.u.LowPart, size, protect );
2042 /* Check parameters */
2044 if ((offset.u.LowPart & mask) || (*addr_ptr && ((UINT_PTR)*addr_ptr & mask)))
2045 return STATUS_INVALID_PARAMETER;
2047 if (process != NtCurrentProcess())
2049 apc_call_t call;
2050 apc_result_t result;
2052 call.map_view.type = APC_MAP_VIEW;
2053 call.map_view.handle = handle;
2054 call.map_view.addr = *addr_ptr;
2055 call.map_view.size = *size_ptr;
2056 call.map_view.offset_low = offset.u.LowPart;
2057 call.map_view.offset_high = offset.u.HighPart;
2058 call.map_view.zero_bits = zero_bits;
2059 call.map_view.alloc_type = alloc_type;
2060 call.map_view.prot = protect;
2061 res = NTDLL_queue_process_apc( process, &call, &result );
2062 if (res != STATUS_SUCCESS) return res;
2064 if (result.map_view.status == STATUS_SUCCESS)
2066 *addr_ptr = result.map_view.addr;
2067 *size_ptr = result.map_view.size;
2069 return result.map_view.status;
2072 SERVER_START_REQ( get_mapping_info )
2074 req->handle = handle;
2075 res = wine_server_call( req );
2076 prot = reply->protect;
2077 base = reply->base;
2078 size_low = reply->size_low;
2079 size_high = reply->size_high;
2080 header_size = reply->header_size;
2081 dup_mapping = reply->mapping;
2082 shared_file = reply->shared_file;
2083 shared_size = reply->shared_size;
2084 id = reply->id;
2085 hack_val = reply->hack_val;
2087 SERVER_END_REQ;
2088 if (res) return res;
2090 size = ((ULONGLONG)size_high << 32) | size_low;
2091 if (sizeof(size) == sizeof(size_low) && size_high)
2092 ERR( "Sizes larger than 4Gb (%x%08x) not supported on this platform\n", size_high, size_low );
2094 if ((res = server_get_unix_fd( handle, 0, &unix_handle, &needs_close, NULL, NULL ))) goto done;
2096 if (prot & VPROT_IMAGE)
2098 if (shared_file)
2100 int shared_fd, shared_needs_close;
2102 if ((res = server_get_unix_fd( shared_file, FILE_READ_DATA|FILE_WRITE_DATA,
2103 &shared_fd, &shared_needs_close, NULL, NULL ))) goto done;
2104 res = map_image( handle, unix_handle, base, size, mask, header_size,
2105 shared_fd, dup_mapping, addr_ptr );
2106 if (shared_needs_close) close( shared_fd );
2107 NtClose( shared_file );
2109 else
2111 res = map_image( handle, unix_handle, base, size, mask, header_size,
2112 -1, dup_mapping, addr_ptr );
2114 if (needs_close) close( unix_handle );
2115 if (!res) *size_ptr = size;
2116 return res;
2119 if ((offset.QuadPart >= size) || (*size_ptr > size - offset.QuadPart))
2121 res = STATUS_INVALID_PARAMETER;
2122 goto done;
2124 if (*size_ptr) size = ROUND_SIZE( offset.u.LowPart, *size_ptr );
2125 else size = size - offset.QuadPart;
2127 switch(protect)
2129 case PAGE_NOACCESS:
2130 break;
2131 case PAGE_READWRITE:
2132 case PAGE_EXECUTE_READWRITE:
2133 if (!(prot & VPROT_WRITE))
2135 res = STATUS_INVALID_PARAMETER;
2136 goto done;
2138 /* fall through */
2139 case PAGE_READONLY:
2140 case PAGE_WRITECOPY:
2141 case PAGE_EXECUTE:
2142 case PAGE_EXECUTE_READ:
2143 case PAGE_EXECUTE_WRITECOPY:
2144 if (prot & VPROT_READ) break;
2145 /* fall through */
2146 default:
2147 res = STATUS_INVALID_PARAMETER;
2148 goto done;
2151 /* Reserve a properly aligned area */
2153 server_enter_uninterrupted_section( &csVirtual, &sigset );
2155 /******************* CODEWEAVERS HACKS START HERE *******************
2157 * These two problems both happen with the section generated by
2158 * msmapi32.dll in Windows 9x. This hack detects that section by name.
2160 * PROBLEM 1
2162 * In Windows 9x, two mappings of the same section result in
2163 * the same pointer across threads and processes.
2165 * In Wine this is hard to duplicate across processes, so
2166 * just try and do it in one process for the time being
2168 * PROBLEM 2
2170 * FIXME: If a mapping is created with SEC_RESERVE and a process,
2171 * which has a view of this mapping commits some pages, they will
2172 * appear committed in all other processes, which have the same
2173 * view created. Since we don't support this yet, we create the
2174 * whole mapping committed.
2176 * This hack is for Outlook XP - don't set VPROT_COMMITTED
2178 if( hack_val )
2180 if (VIRTUAL_FindViewById( id, addr_ptr, size_ptr ))
2182 TRACE("Trying to be compatible with win9x mapping\n");
2183 res = STATUS_SUCCESS;
2184 server_leave_uninterrupted_section( &csVirtual, &sigset );
2185 goto done;
2188 /* prot |= VPROT_COMMITTED; */
2190 else
2191 prot |= VPROT_COMMITTED;
2193 /******************* CODEWEAVERS HACKS END HERE ********************/
2195 res = map_view( &view, *addr_ptr, size, mask, FALSE, prot );
2196 if (res)
2198 server_leave_uninterrupted_section( &csVirtual, &sigset );
2199 goto done;
2202 /* Map the file */
2204 TRACE("handle=%p size=%lx offset=%x%08x\n",
2205 handle, size, offset.u.HighPart, offset.u.LowPart );
2207 res = map_file_into_view( view, unix_handle, 0, size, offset.QuadPart, prot, !dup_mapping );
2208 if (res == STATUS_SUCCESS)
2210 *addr_ptr = view->base;
2211 *size_ptr = size;
2212 view->id = id;
2213 view->mapping = dup_mapping;
2214 dup_mapping = 0; /* don't close it */
2216 else
2218 ERR( "map_file_into_view %p %lx %x%08x failed\n",
2219 view->base, size, offset.u.HighPart, offset.u.LowPart );
2220 delete_view( view );
2223 server_leave_uninterrupted_section( &csVirtual, &sigset );
2225 done:
2226 if (dup_mapping) NtClose( dup_mapping );
2227 if (needs_close) close( unix_handle );
2228 return res;
2232 /***********************************************************************
2233 * NtUnmapViewOfSection (NTDLL.@)
2234 * ZwUnmapViewOfSection (NTDLL.@)
2236 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
2238 FILE_VIEW *view;
2239 NTSTATUS status = STATUS_INVALID_PARAMETER;
2240 sigset_t sigset;
2241 void *base = ROUND_ADDR( addr, page_mask );
2243 if (process != NtCurrentProcess())
2245 apc_call_t call;
2246 apc_result_t result;
2248 call.unmap_view.type = APC_UNMAP_VIEW;
2249 call.unmap_view.addr = addr;
2250 status = NTDLL_queue_process_apc( process, &call, &result );
2251 if (status == STATUS_SUCCESS) status = result.unmap_view.status;
2252 return status;
2255 server_enter_uninterrupted_section( &csVirtual, &sigset );
2256 if ((view = VIRTUAL_FindView( base )) && (base == view->base))
2258 delete_view( view );
2259 status = STATUS_SUCCESS;
2261 server_leave_uninterrupted_section( &csVirtual, &sigset );
2262 return status;
2266 /***********************************************************************
2267 * NtFlushVirtualMemory (NTDLL.@)
2268 * ZwFlushVirtualMemory (NTDLL.@)
2270 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
2271 SIZE_T *size_ptr, ULONG unknown )
2273 FILE_VIEW *view;
2274 NTSTATUS status = STATUS_SUCCESS;
2275 sigset_t sigset;
2276 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
2278 if (process != NtCurrentProcess())
2280 apc_call_t call;
2281 apc_result_t result;
2283 call.virtual_flush.type = APC_VIRTUAL_FLUSH;
2284 call.virtual_flush.addr = addr;
2285 call.virtual_flush.size = *size_ptr;
2286 status = NTDLL_queue_process_apc( process, &call, &result );
2287 if (status != STATUS_SUCCESS) return status;
2289 if (result.virtual_flush.status == STATUS_SUCCESS)
2291 *addr_ptr = result.virtual_flush.addr;
2292 *size_ptr = result.virtual_flush.size;
2294 return result.virtual_flush.status;
2297 server_enter_uninterrupted_section( &csVirtual, &sigset );
2298 if (!(view = VIRTUAL_FindView( addr ))) status = STATUS_INVALID_PARAMETER;
2299 else
2301 if (!*size_ptr) *size_ptr = view->size;
2302 *addr_ptr = addr;
2303 if (msync( addr, *size_ptr, MS_SYNC )) status = STATUS_NOT_MAPPED_DATA;
2305 server_leave_uninterrupted_section( &csVirtual, &sigset );
2306 return status;
2310 /***********************************************************************
2311 * NtReadVirtualMemory (NTDLL.@)
2312 * ZwReadVirtualMemory (NTDLL.@)
2314 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
2315 SIZE_T size, SIZE_T *bytes_read )
2317 NTSTATUS status;
2319 SERVER_START_REQ( read_process_memory )
2321 req->handle = process;
2322 req->addr = (void *)addr;
2323 wine_server_set_reply( req, buffer, size );
2324 if ((status = wine_server_call( req ))) size = 0;
2326 SERVER_END_REQ;
2327 if (bytes_read) *bytes_read = size;
2328 return status;
2332 /***********************************************************************
2333 * NtWriteVirtualMemory (NTDLL.@)
2334 * ZwWriteVirtualMemory (NTDLL.@)
2336 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
2337 SIZE_T size, SIZE_T *bytes_written )
2339 NTSTATUS status;
2341 SERVER_START_REQ( write_process_memory )
2343 req->handle = process;
2344 req->addr = addr;
2345 wine_server_add_data( req, buffer, size );
2346 if ((status = wine_server_call( req ))) size = 0;
2348 SERVER_END_REQ;
2349 if (bytes_written) *bytes_written = size;
2350 return status;