Portability fixes.
[wine.git] / dlls / ntdll / virtual.c
blob25c82d2fa11d8871a4bcb10ba8e10e46dbf7df3c
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_MMAN_H
38 #include <sys/mman.h>
39 #endif
41 #define NONAMELESSUNION
42 #define NONAMELESSSTRUCT
43 #include "winternl.h"
44 #include "global.h"
45 #include "wine/library.h"
46 #include "wine/server.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
50 WINE_DECLARE_DEBUG_CHANNEL(module);
52 #ifndef MS_SYNC
53 #define MS_SYNC 0
54 #endif
56 /* File view */
57 typedef struct _FV
59 struct _FV *next; /* Next view */
60 struct _FV *prev; /* Prev view */
61 void *base; /* Base address */
62 UINT size; /* Size in bytes */
63 UINT flags; /* Allocation flags */
64 HANDLE mapping; /* Handle to the file mapping */
65 HANDLERPROC handlerProc; /* Fault handler */
66 LPVOID handlerArg; /* Fault handler argument */
67 BYTE protect; /* Protection for all pages at allocation time */
68 BYTE prot[1]; /* Protection byte for each page */
69 } FILE_VIEW;
71 /* Per-view flags */
72 #define VFLAG_SYSTEM 0x01
73 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
75 /* Conversion from VPROT_* to Win32 flags */
76 static const BYTE VIRTUAL_Win32Flags[16] =
78 PAGE_NOACCESS, /* 0 */
79 PAGE_READONLY, /* READ */
80 PAGE_READWRITE, /* WRITE */
81 PAGE_READWRITE, /* READ | WRITE */
82 PAGE_EXECUTE, /* EXEC */
83 PAGE_EXECUTE_READ, /* READ | EXEC */
84 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
85 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
86 PAGE_WRITECOPY, /* WRITECOPY */
87 PAGE_WRITECOPY, /* READ | WRITECOPY */
88 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
89 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
90 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
91 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
92 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
93 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
97 static FILE_VIEW *VIRTUAL_FirstView;
99 static CRITICAL_SECTION csVirtual;
100 static CRITICAL_SECTION_DEBUG critsect_debug =
102 0, 0, &csVirtual,
103 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
104 0, 0, { 0, (DWORD)(__FILE__ ": csVirtual") }
106 static CRITICAL_SECTION csVirtual = { &critsect_debug, -1, 0, 0, 0, 0 };
108 #ifdef __i386__
109 /* These are always the same on an i386, and it will be faster this way */
110 # define page_mask 0xfff
111 # define page_shift 12
112 # define page_size 0x1000
113 /* Note: ADDRESS_SPACE_LIMIT is a Windows limit, you cannot change it.
114 * If you are on Solaris you need to find a way to avoid having the system
115 * allocate things above 0xc000000. Don't touch that define.
117 # define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the user address space */
118 #else
119 static UINT page_shift;
120 static UINT page_mask;
121 static UINT page_size;
122 # define ADDRESS_SPACE_LIMIT 0 /* no limit needed on other platforms */
123 #endif /* __i386__ */
124 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
126 #define ROUND_ADDR(addr,mask) \
127 ((void *)((UINT_PTR)(addr) & ~(mask)))
129 #define ROUND_SIZE(addr,size) \
130 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
132 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
133 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
135 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size, DWORD offset_low,
136 DWORD offset_high, int prot, int flags, BOOL *removable );
139 /***********************************************************************
140 * VIRTUAL_GetProtStr
142 static const char *VIRTUAL_GetProtStr( BYTE prot )
144 static char buffer[6];
145 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
146 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
147 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
148 buffer[3] = (prot & VPROT_WRITE) ?
149 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
150 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
151 buffer[5] = 0;
152 return buffer;
156 /***********************************************************************
157 * VIRTUAL_DumpView
159 static void VIRTUAL_DumpView( FILE_VIEW *view )
161 UINT i, count;
162 char *addr = view->base;
163 BYTE prot = view->prot[0];
165 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
166 if (view->flags & VFLAG_SYSTEM)
167 DPRINTF( " (system)\n" );
168 else if (view->flags & VFLAG_VALLOC)
169 DPRINTF( " (valloc)\n" );
170 else if (view->mapping)
171 DPRINTF( " %p\n", view->mapping );
172 else
173 DPRINTF( " (anonymous)\n");
175 for (count = i = 1; i < view->size >> page_shift; i++, count++)
177 if (view->prot[i] == prot) continue;
178 DPRINTF( " %p - %p %s\n",
179 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
180 addr += (count << page_shift);
181 prot = view->prot[i];
182 count = 0;
184 if (count)
185 DPRINTF( " %p - %p %s\n",
186 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
190 /***********************************************************************
191 * VIRTUAL_Dump
193 void VIRTUAL_Dump(void)
195 FILE_VIEW *view;
196 DPRINTF( "\nDump of all virtual memory views:\n\n" );
197 RtlEnterCriticalSection(&csVirtual);
198 view = VIRTUAL_FirstView;
199 while (view)
201 VIRTUAL_DumpView( view );
202 view = view->next;
204 RtlLeaveCriticalSection(&csVirtual);
208 /***********************************************************************
209 * VIRTUAL_FindView
211 * Find the view containing a given address.
213 * RETURNS
214 * View: Success
215 * NULL: Failure
217 static FILE_VIEW *VIRTUAL_FindView( const void *addr ) /* [in] Address */
219 FILE_VIEW *view;
221 RtlEnterCriticalSection(&csVirtual);
222 view = VIRTUAL_FirstView;
223 while (view)
225 if (view->base > addr)
227 view = NULL;
228 break;
230 if ((char*)view->base + view->size > (char*)addr) break;
231 view = view->next;
233 RtlLeaveCriticalSection(&csVirtual);
234 return view;
238 /***********************************************************************
239 * VIRTUAL_CreateView
241 * Create a new view and add it in the linked list.
243 static FILE_VIEW *VIRTUAL_CreateView( void *base, UINT size, UINT flags,
244 BYTE vprot, HANDLE mapping )
246 FILE_VIEW *view, *prev;
248 /* Create the view structure */
250 assert( !((unsigned int)base & page_mask) );
251 assert( !(size & page_mask) );
252 size >>= page_shift;
253 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
254 view->base = base;
255 view->size = size << page_shift;
256 view->flags = flags;
257 view->mapping = mapping;
258 view->protect = vprot;
259 view->handlerProc = NULL;
260 memset( view->prot, vprot, size );
262 /* Duplicate the mapping handle */
264 if (view->mapping &&
265 NtDuplicateObject( GetCurrentProcess(), view->mapping,
266 GetCurrentProcess(), &view->mapping,
267 0, 0, DUPLICATE_SAME_ACCESS ))
269 free( view );
270 return NULL;
273 /* Insert it in the linked list */
275 RtlEnterCriticalSection(&csVirtual);
276 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
278 view->next = VIRTUAL_FirstView;
279 view->prev = NULL;
280 if (view->next) view->next->prev = view;
281 VIRTUAL_FirstView = view;
283 else
285 prev = VIRTUAL_FirstView;
286 while (prev->next && (prev->next->base < base)) prev = prev->next;
287 view->next = prev->next;
288 view->prev = prev;
289 if (view->next) view->next->prev = view;
290 prev->next = view;
292 RtlLeaveCriticalSection(&csVirtual);
293 VIRTUAL_DEBUG_DUMP_VIEW( view );
294 return view;
298 /***********************************************************************
299 * VIRTUAL_DeleteView
300 * Deletes a view.
302 * RETURNS
303 * None
305 static void VIRTUAL_DeleteView( FILE_VIEW *view ) /* [in] View */
307 if (!(view->flags & VFLAG_SYSTEM))
308 munmap( (void *)view->base, view->size );
309 RtlEnterCriticalSection(&csVirtual);
310 if (view->next) view->next->prev = view->prev;
311 if (view->prev) view->prev->next = view->next;
312 else VIRTUAL_FirstView = view->next;
313 RtlLeaveCriticalSection(&csVirtual);
314 if (view->mapping) NtClose( view->mapping );
315 free( view );
319 /***********************************************************************
320 * VIRTUAL_GetUnixProt
322 * Convert page protections to protection for mmap/mprotect.
324 static int VIRTUAL_GetUnixProt( BYTE vprot )
326 int prot = 0;
327 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
329 if (vprot & VPROT_READ) prot |= PROT_READ;
330 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
331 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
332 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
334 return prot;
338 /***********************************************************************
339 * VIRTUAL_GetWin32Prot
341 * Convert page protections to Win32 flags.
343 * RETURNS
344 * None
346 static void VIRTUAL_GetWin32Prot(
347 BYTE vprot, /* [in] Page protection flags */
348 DWORD *protect, /* [out] Location to store Win32 protection flags */
349 DWORD *state ) /* [out] Location to store mem state flag */
351 if (protect) {
352 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
353 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
354 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
356 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
359 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
363 /***********************************************************************
364 * VIRTUAL_GetProt
366 * Build page protections from Win32 flags.
368 * RETURNS
369 * Value of page protection flags
371 static BYTE VIRTUAL_GetProt( DWORD protect ) /* [in] Win32 protection flags */
373 BYTE vprot;
375 switch(protect & 0xff)
377 case PAGE_READONLY:
378 vprot = VPROT_READ;
379 break;
380 case PAGE_READWRITE:
381 vprot = VPROT_READ | VPROT_WRITE;
382 break;
383 case PAGE_WRITECOPY:
384 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
385 * that the hFile must have been opened with GENERIC_READ and
386 * GENERIC_WRITE access. This is WRONG as tests show that you
387 * only need GENERIC_READ access (at least for Win9x,
388 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
389 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
391 vprot = VPROT_READ | VPROT_WRITECOPY;
392 break;
393 case PAGE_EXECUTE:
394 vprot = VPROT_EXEC;
395 break;
396 case PAGE_EXECUTE_READ:
397 vprot = VPROT_EXEC | VPROT_READ;
398 break;
399 case PAGE_EXECUTE_READWRITE:
400 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
401 break;
402 case PAGE_EXECUTE_WRITECOPY:
403 /* See comment for PAGE_WRITECOPY above */
404 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
405 break;
406 case PAGE_NOACCESS:
407 default:
408 vprot = 0;
409 break;
411 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
412 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
413 return vprot;
417 /***********************************************************************
418 * VIRTUAL_SetProt
420 * Change the protection of a range of pages.
422 * RETURNS
423 * TRUE: Success
424 * FALSE: Failure
426 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
427 void *base, /* [in] Starting address */
428 UINT size, /* [in] Size in bytes */
429 BYTE vprot ) /* [in] Protections to use */
431 TRACE("%p-%p %s\n",
432 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
434 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
435 return FALSE; /* FIXME: last error */
437 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
438 vprot, size >> page_shift );
439 VIRTUAL_DEBUG_DUMP_VIEW( view );
440 return TRUE;
444 /***********************************************************************
445 * anon_mmap_aligned
447 * Create an anonymous mapping aligned to the allocation granularity.
449 static NTSTATUS anon_mmap_aligned( void **addr, unsigned int size, int prot, int flags )
451 void *ptr, *base = *addr;
452 unsigned int view_size = size + (base ? 0 : granularity_mask + 1);
454 if ((ptr = wine_anon_mmap( base, view_size, prot, flags )) == (void *)-1)
456 if (errno == ENOMEM) return STATUS_NO_MEMORY;
457 return STATUS_INVALID_PARAMETER;
460 if (!base)
462 /* Release the extra memory while keeping the range
463 * starting on the granularity boundary. */
464 if ((unsigned int)ptr & granularity_mask)
466 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
467 munmap( ptr, extra );
468 ptr = (char *)ptr + extra;
469 view_size -= extra;
471 if (view_size > size)
472 munmap( (char *)ptr + size, view_size - size );
474 else if (ptr != base)
476 /* We couldn't get the address we wanted */
477 munmap( ptr, view_size );
478 return STATUS_CONFLICTING_ADDRESSES;
480 *addr = ptr;
481 return STATUS_SUCCESS;
485 /***********************************************************************
486 * do_relocations
488 * Apply the relocations to a mapped PE image
490 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
491 int delta, DWORD total_size )
493 IMAGE_BASE_RELOCATION *rel;
495 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
496 base - delta, base - delta + total_size, base, base + total_size );
498 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
499 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
500 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
502 char *page = base + rel->VirtualAddress;
503 WORD *TypeOffset = (WORD *)(rel + 1);
504 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
506 if (!count) continue;
508 /* sanity checks */
509 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
510 page > base + total_size)
512 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
513 rel, rel->VirtualAddress, rel->SizeOfBlock,
514 base, dir->VirtualAddress, dir->Size );
515 return 0;
518 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
520 /* patching in reverse order */
521 for (i = 0 ; i < count; i++)
523 int offset = TypeOffset[i] & 0xFFF;
524 int type = TypeOffset[i] >> 12;
525 switch(type)
527 case IMAGE_REL_BASED_ABSOLUTE:
528 break;
529 case IMAGE_REL_BASED_HIGH:
530 *(short*)(page+offset) += HIWORD(delta);
531 break;
532 case IMAGE_REL_BASED_LOW:
533 *(short*)(page+offset) += LOWORD(delta);
534 break;
535 case IMAGE_REL_BASED_HIGHLOW:
536 *(int*)(page+offset) += delta;
537 /* FIXME: if this is an exported address, fire up enhanced logic */
538 break;
539 default:
540 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
541 break;
545 return 1;
549 /***********************************************************************
550 * map_image
552 * Map an executable (PE format) image into memory.
554 static NTSTATUS map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
555 DWORD header_size, int shared_fd, DWORD shared_size,
556 BOOL removable, PVOID *addr_ptr )
558 IMAGE_DOS_HEADER *dos;
559 IMAGE_NT_HEADERS *nt;
560 IMAGE_SECTION_HEADER *sec;
561 IMAGE_DATA_DIRECTORY *imports;
562 NTSTATUS status = STATUS_INVALID_IMAGE_FORMAT; /* generic error (FIXME) */
563 int i, pos;
564 FILE_VIEW *view;
565 char *ptr;
567 /* zero-map the whole range */
569 if (base < (char *)0x110000 || /* make sure the DOS area remains free */
570 (ptr = wine_anon_mmap( base, total_size,
571 PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
573 ptr = wine_anon_mmap( NULL, total_size,
574 PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
575 if (ptr == (char *)-1)
577 ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
578 goto error;
581 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
583 /* map the header */
585 if (VIRTUAL_mmap( fd, ptr, header_size, 0, 0, PROT_READ,
586 MAP_PRIVATE | MAP_FIXED, &removable ) == (char *)-1) goto error;
587 dos = (IMAGE_DOS_HEADER *)ptr;
588 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
589 if ((char *)(nt + 1) > ptr + header_size) goto error;
591 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
592 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
594 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
595 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
597 /* check the architecture */
599 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
601 MESSAGE("Trying to load PE image for unsupported architecture (");
602 switch (nt->FileHeader.Machine)
604 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
605 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
606 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
607 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
608 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
609 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
610 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
611 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
613 MESSAGE(")\n");
614 goto error;
617 /* map all the sections */
619 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
621 DWORD size;
623 /* a few sanity checks */
624 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
625 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
627 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
628 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
629 goto error;
632 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
633 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
635 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
636 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
637 sec->Name, ptr + sec->VirtualAddress,
638 sec->PointerToRawData, pos, sec->SizeOfRawData,
639 size, sec->Characteristics );
640 if (VIRTUAL_mmap( shared_fd, ptr + sec->VirtualAddress, size,
641 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
642 MAP_SHARED|MAP_FIXED, NULL ) == (void *)-1)
644 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
645 goto error;
648 /* check if the import directory falls inside this section */
649 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
650 imports->VirtualAddress < sec->VirtualAddress + size)
652 UINT_PTR base = imports->VirtualAddress & ~page_mask;
653 UINT_PTR end = base + ROUND_SIZE( imports->VirtualAddress, imports->Size );
654 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
655 if (end > base) VIRTUAL_mmap( shared_fd, ptr + base, end - base,
656 pos + (base - sec->VirtualAddress), 0,
657 PROT_READ|PROT_WRITE|PROT_EXEC,
658 MAP_PRIVATE|MAP_FIXED, NULL );
660 pos += size;
661 continue;
664 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
665 sec->Name, ptr + sec->VirtualAddress,
666 sec->PointerToRawData, sec->SizeOfRawData,
667 sec->Characteristics );
669 if ((sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) &&
670 !(sec->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) continue;
671 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
673 /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
674 * fall back to read(), so we don't need to check anything here.
676 if (VIRTUAL_mmap( fd, ptr + sec->VirtualAddress, sec->SizeOfRawData,
677 sec->PointerToRawData, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
678 MAP_PRIVATE | MAP_FIXED, &removable ) == (void *)-1)
680 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
681 goto error;
684 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
686 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
687 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
688 TRACE_(module)("clearing %p - %p\n",
689 ptr + sec->VirtualAddress + sec->SizeOfRawData,
690 ptr + sec->VirtualAddress + end );
691 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
692 end - sec->SizeOfRawData );
697 /* perform base relocation, if necessary */
699 if (ptr != base)
701 const IMAGE_DATA_DIRECTORY *relocs;
703 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
704 if (!relocs->VirtualAddress || !relocs->Size)
706 if (nt->OptionalHeader.ImageBase == 0x400000)
707 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
708 else
709 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
710 nt->OptionalHeader.ImageBase );
711 goto error;
714 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
715 * really make sure that the *new* base address is also > 2GB.
716 * Some DLLs really check the MSB of the module handle :-/
718 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
719 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
721 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
723 goto error;
727 if (removable) hmapping = 0; /* don't keep handle open on removable media */
728 if (!(view = VIRTUAL_CreateView( ptr, total_size, 0, VPROT_COMMITTED|VPROT_READ, hmapping )))
730 status = STATUS_NO_MEMORY;
731 goto error;
734 /* set the image protections */
736 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
737 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
739 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
740 BYTE vprot = VPROT_COMMITTED;
741 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
742 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITE|VPROT_WRITECOPY;
743 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
745 /* make sure the import directory is writable */
746 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
747 imports->VirtualAddress < sec->VirtualAddress + size)
748 vprot |= VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY;
750 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
753 close( fd );
754 *addr_ptr = ptr;
755 return STATUS_SUCCESS;
757 error:
758 if (ptr != (char *)-1) munmap( ptr, total_size );
759 close( fd );
760 return status;
764 /***********************************************************************
765 * is_current_process
767 * Check whether a process handle is for the current process.
769 static BOOL is_current_process( HANDLE handle )
771 BOOL ret = FALSE;
773 if (handle == GetCurrentProcess()) return TRUE;
774 SERVER_START_REQ( get_process_info )
776 req->handle = handle;
777 if (!wine_server_call( req ))
778 ret = ((DWORD)reply->pid == GetCurrentProcessId());
780 SERVER_END_REQ;
781 return ret;
785 /***********************************************************************
786 * VIRTUAL_Init
788 #ifndef page_mask
789 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
791 page_size = getpagesize();
792 page_mask = page_size - 1;
793 /* Make sure we have a power of 2 */
794 assert( !(page_size & page_mask) );
795 page_shift = 0;
796 while ((1 << page_shift) != page_size) page_shift++;
798 #endif /* page_mask */
801 /***********************************************************************
802 * VIRTUAL_SetFaultHandler
804 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
806 FILE_VIEW *view;
808 if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
809 view->handlerProc = proc;
810 view->handlerArg = arg;
811 return TRUE;
814 /***********************************************************************
815 * VIRTUAL_HandleFault
817 DWORD VIRTUAL_HandleFault( LPCVOID addr )
819 FILE_VIEW *view = VIRTUAL_FindView( addr );
820 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
822 if (view)
824 if (view->handlerProc)
826 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
828 else
830 BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
831 void *page = (void *)((UINT_PTR)addr & ~page_mask);
832 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
833 if (vprot & VPROT_GUARD)
835 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
836 ret = STATUS_GUARD_PAGE_VIOLATION;
838 /* is it inside the stack guard pages? */
839 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
840 ret = STATUS_STACK_OVERFLOW;
843 return ret;
848 /***********************************************************************
849 * unaligned_mmap
851 * Linux kernels before 2.4.x can support non page-aligned offsets, as
852 * long as the offset is aligned to the filesystem block size. This is
853 * a big performance gain so we want to take advantage of it.
855 * However, when we use 64-bit file support this doesn't work because
856 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
857 * in that it rounds unaligned offsets down to a page boundary. For
858 * these reasons we do a direct system call here.
860 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
861 unsigned int flags, int fd, unsigned int offset_low,
862 unsigned int offset_high )
864 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
865 if (!offset_high && (offset_low & page_mask))
867 int ret;
869 struct
871 void *addr;
872 unsigned int length;
873 unsigned int prot;
874 unsigned int flags;
875 unsigned int fd;
876 unsigned int offset;
877 } args;
879 args.addr = addr;
880 args.length = length;
881 args.prot = prot;
882 args.flags = flags;
883 args.fd = fd;
884 args.offset = offset_low;
886 __asm__ __volatile__("push %%ebx\n\t"
887 "movl %2,%%ebx\n\t"
888 "int $0x80\n\t"
889 "popl %%ebx"
890 : "=a" (ret)
891 : "0" (90), /* SYS_mmap */
892 "g" (&args) );
893 if (ret < 0 && ret > -4096)
895 errno = -ret;
896 ret = -1;
898 return (void *)ret;
900 #endif
901 return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
905 /***********************************************************************
906 * VIRTUAL_mmap
908 * Wrapper for mmap() that handles anonymous mappings portably,
909 * and falls back to read if mmap of a file fails.
911 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
912 DWORD offset_low, DWORD offset_high,
913 int prot, int flags, BOOL *removable )
915 int pos;
916 LPVOID ret;
917 off_t offset;
918 BOOL is_shared_write = FALSE;
920 if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
922 if (prot & PROT_WRITE)
924 #ifdef MAP_SHARED
925 if (flags & MAP_SHARED) is_shared_write = TRUE;
926 #endif
927 #ifdef MAP_PRIVATE
928 if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
929 #endif
932 if (removable && *removable)
934 /* if on removable media, try using read instead of mmap */
935 if (!is_shared_write) goto fake_mmap;
936 *removable = FALSE;
939 if ((ret = unaligned_mmap( start, size, prot, flags, fd,
940 offset_low, offset_high )) != (LPVOID)-1) return ret;
942 /* mmap() failed; if this is because the file offset is not */
943 /* page-aligned (EINVAL), or because the underlying filesystem */
944 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
946 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
947 if (is_shared_write) return ret; /* we cannot fake shared write mappings */
949 fake_mmap:
950 /* Reserve the memory with an anonymous mmap */
951 ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
952 if (ret == (LPVOID)-1) return ret;
953 /* Now read in the file */
954 offset = ((off_t)offset_high << 32) | offset_low;
955 if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
957 munmap( ret, size );
958 return (LPVOID)-1;
960 read( fd, ret, size );
961 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
962 mprotect( ret, size, prot ); /* Set the right protection */
963 return ret;
967 /***********************************************************************
968 * NtAllocateVirtualMemory (NTDLL.@)
969 * ZwAllocateVirtualMemory (NTDLL.@)
971 NTSTATUS WINAPI NtAllocateVirtualMemory( HANDLE process, PVOID *ret, PVOID addr,
972 ULONG *size_ptr, ULONG type, ULONG protect )
974 FILE_VIEW *view;
975 void *base;
976 BYTE vprot;
977 DWORD size = *size_ptr;
979 if (!is_current_process( process ))
981 ERR("Unsupported on other process\n");
982 return STATUS_ACCESS_DENIED;
985 TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
987 /* Round parameters to a page boundary */
989 if (size > 0x7fc00000) return STATUS_WORKING_SET_LIMIT_RANGE; /* 2Gb - 4Mb */
991 if (addr)
993 if (type & MEM_RESERVE) /* Round down to 64k boundary */
994 base = ROUND_ADDR( addr, granularity_mask );
995 else
996 base = ROUND_ADDR( addr, page_mask );
997 size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
999 /* disallow low 64k, wrap-around and kernel space */
1000 if (((char *)base <= (char *)granularity_mask) ||
1001 ((char *)base + size < (char *)base) ||
1002 (ADDRESS_SPACE_LIMIT && ((char *)base + size > (char *)ADDRESS_SPACE_LIMIT)))
1003 return STATUS_INVALID_PARAMETER;
1005 else
1007 base = NULL;
1008 size = (size + page_mask) & ~page_mask;
1011 if (type & MEM_TOP_DOWN) {
1012 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
1013 * Is there _ANY_ way to do it with UNIX mmap()?
1015 WARN("MEM_TOP_DOWN ignored\n");
1016 type &= ~MEM_TOP_DOWN;
1019 /* Compute the alloc type flags */
1021 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
1022 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
1024 ERR("called with wrong alloc type flags (%08lx) !\n", type);
1025 return STATUS_INVALID_PARAMETER;
1027 if (type & (MEM_COMMIT | MEM_SYSTEM))
1028 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
1029 else vprot = 0;
1031 /* Reserve the memory */
1033 if ((type & MEM_RESERVE) || !base)
1035 if (type & MEM_SYSTEM)
1037 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
1038 return STATUS_NO_MEMORY;
1040 else
1042 NTSTATUS res = anon_mmap_aligned( &base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
1043 if (res) return res;
1045 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC, vprot, 0 )))
1047 munmap( base, size );
1048 return STATUS_NO_MEMORY;
1052 else
1054 /* Commit the pages */
1056 if (!(view = VIRTUAL_FindView( base )) ||
1057 ((char *)base + size > (char *)view->base + view->size)) return STATUS_NOT_MAPPED_VIEW;
1059 if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1062 *ret = base;
1063 *size_ptr = size;
1064 return STATUS_SUCCESS;
1068 /***********************************************************************
1069 * NtFreeVirtualMemory (NTDLL.@)
1070 * ZwFreeVirtualMemory (NTDLL.@)
1072 NTSTATUS WINAPI NtFreeVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr, ULONG type )
1074 FILE_VIEW *view;
1075 char *base;
1076 LPVOID addr = *addr_ptr;
1077 DWORD size = *size_ptr;
1079 if (!is_current_process( process ))
1081 ERR("Unsupported on other process\n");
1082 return STATUS_ACCESS_DENIED;
1085 TRACE("%p %08lx %lx\n", addr, size, type );
1087 /* Fix the parameters */
1089 size = ROUND_SIZE( addr, size );
1090 base = ROUND_ADDR( addr, page_mask );
1092 if (!(view = VIRTUAL_FindView( base )) ||
1093 (base + size > (char *)view->base + view->size) ||
1094 !(view->flags & VFLAG_VALLOC))
1095 return STATUS_INVALID_PARAMETER;
1097 /* Check the type */
1099 if (type & MEM_SYSTEM)
1101 view->flags |= VFLAG_SYSTEM;
1102 type &= ~MEM_SYSTEM;
1105 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
1107 ERR("called with wrong free type flags (%08lx) !\n", type);
1108 return STATUS_INVALID_PARAMETER;
1111 /* Free the pages */
1113 if (type == MEM_RELEASE)
1115 if (size || (base != view->base)) return STATUS_INVALID_PARAMETER;
1116 VIRTUAL_DeleteView( view );
1118 else
1120 /* Decommit the pages by remapping zero-pages instead */
1122 if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1123 ERR( "Could not remap pages, expect trouble\n" );
1124 if (!VIRTUAL_SetProt( view, base, size, 0 )) return STATUS_ACCESS_DENIED; /* FIXME */
1127 *addr_ptr = base;
1128 *size_ptr = size;
1129 return STATUS_SUCCESS;
1133 /***********************************************************************
1134 * NtProtectVirtualMemory (NTDLL.@)
1135 * ZwProtectVirtualMemory (NTDLL.@)
1137 NTSTATUS WINAPI NtProtectVirtualMemory( HANDLE process, PVOID *addr_ptr, ULONG *size_ptr,
1138 ULONG new_prot, ULONG *old_prot )
1140 FILE_VIEW *view;
1141 char *base;
1142 UINT i;
1143 BYTE vprot, *p;
1144 DWORD prot, size = *size_ptr;
1145 LPVOID addr = *addr_ptr;
1147 if (!is_current_process( process ))
1149 ERR("Unsupported on other process\n");
1150 return STATUS_ACCESS_DENIED;
1153 TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1155 /* Fix the parameters */
1157 size = ROUND_SIZE( addr, size );
1158 base = ROUND_ADDR( addr, page_mask );
1160 if (!(view = VIRTUAL_FindView( base )) ||
1161 (base + size > (char *)view->base + view->size))
1162 return STATUS_INVALID_PARAMETER;
1164 /* Make sure all the pages are committed */
1166 p = view->prot + ((base - (char *)view->base) >> page_shift);
1167 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1168 for (i = size >> page_shift; i; i--, p++)
1170 if (!(*p & VPROT_COMMITTED)) return STATUS_INVALID_PARAMETER;
1173 if (old_prot) *old_prot = prot;
1174 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1175 if (!VIRTUAL_SetProt( view, base, size, vprot )) return STATUS_ACCESS_DENIED;
1177 *addr_ptr = base;
1178 *size_ptr = size;
1179 return STATUS_SUCCESS;
1183 /***********************************************************************
1184 * NtQueryVirtualMemory (NTDLL.@)
1185 * ZwQueryVirtualMemory (NTDLL.@)
1187 NTSTATUS WINAPI NtQueryVirtualMemory( HANDLE process, LPCVOID addr,
1188 MEMORY_INFORMATION_CLASS info_class, PVOID buffer,
1189 ULONG len, ULONG *res_len )
1191 FILE_VIEW *view;
1192 char *base, *alloc_base = 0;
1193 UINT size = 0;
1194 MEMORY_BASIC_INFORMATION *info = buffer;
1196 if (info_class != MemoryBasicInformation) return STATUS_INVALID_INFO_CLASS;
1197 if (ADDRESS_SPACE_LIMIT && addr >= ADDRESS_SPACE_LIMIT)
1198 return STATUS_WORKING_SET_LIMIT_RANGE; /* FIXME */
1200 if (!is_current_process( process ))
1202 ERR("Unsupported on other process\n");
1203 return STATUS_ACCESS_DENIED;
1206 base = ROUND_ADDR( addr, page_mask );
1208 /* Find the view containing the address */
1210 RtlEnterCriticalSection(&csVirtual);
1211 view = VIRTUAL_FirstView;
1212 for (;;)
1214 if (!view)
1216 size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1217 break;
1219 if ((char *)view->base > base)
1221 size = (char *)view->base - alloc_base;
1222 view = NULL;
1223 break;
1225 if ((char *)view->base + view->size > base)
1227 alloc_base = view->base;
1228 size = view->size;
1229 break;
1231 alloc_base = (char *)view->base + view->size;
1232 view = view->next;
1234 RtlLeaveCriticalSection(&csVirtual);
1236 /* Fill the info structure */
1238 if (!view)
1240 info->State = MEM_FREE;
1241 info->Protect = 0;
1242 info->AllocationProtect = 0;
1243 info->Type = 0;
1245 else
1247 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1248 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1249 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1250 if (view->prot[size >> page_shift] != vprot) break;
1251 info->AllocationProtect = view->protect;
1252 info->Type = MEM_PRIVATE; /* FIXME */
1255 info->BaseAddress = (LPVOID)base;
1256 info->AllocationBase = (LPVOID)alloc_base;
1257 info->RegionSize = size - (base - alloc_base);
1258 if (res_len) *res_len = sizeof(*info);
1259 return STATUS_SUCCESS;
1263 /***********************************************************************
1264 * NtLockVirtualMemory (NTDLL.@)
1265 * ZwLockVirtualMemory (NTDLL.@)
1267 NTSTATUS WINAPI NtLockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1269 if (!is_current_process( process ))
1271 ERR("Unsupported on other process\n");
1272 return STATUS_ACCESS_DENIED;
1274 return STATUS_SUCCESS;
1278 /***********************************************************************
1279 * NtUnlockVirtualMemory (NTDLL.@)
1280 * ZwUnlockVirtualMemory (NTDLL.@)
1282 NTSTATUS WINAPI NtUnlockVirtualMemory( HANDLE process, PVOID *addr, ULONG *size, ULONG unknown )
1284 if (!is_current_process( process ))
1286 ERR("Unsupported on other process\n");
1287 return STATUS_ACCESS_DENIED;
1289 return STATUS_SUCCESS;
1293 /***********************************************************************
1294 * NtCreateSection (NTDLL.@)
1295 * ZwCreateSection (NTDLL.@)
1297 NTSTATUS WINAPI NtCreateSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr,
1298 const LARGE_INTEGER *size, ULONG protect,
1299 ULONG sec_flags, HANDLE file )
1301 NTSTATUS ret;
1302 BYTE vprot;
1303 DWORD len = attr->ObjectName ? attr->ObjectName->Length : 0;
1305 /* Check parameters */
1307 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1309 vprot = VIRTUAL_GetProt( protect );
1310 if (sec_flags & SEC_RESERVE)
1312 if (file) return STATUS_INVALID_PARAMETER;
1314 else vprot |= VPROT_COMMITTED;
1315 if (sec_flags & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1316 if (sec_flags & SEC_IMAGE) vprot |= VPROT_IMAGE;
1318 /* Create the server object */
1320 SERVER_START_REQ( create_mapping )
1322 req->file_handle = file;
1323 req->size_high = size ? size->s.HighPart : 0;
1324 req->size_low = size ? size->s.LowPart : 0;
1325 req->protect = vprot;
1326 req->access = access;
1327 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1328 if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
1329 ret = wine_server_call( req );
1330 *handle = reply->handle;
1332 SERVER_END_REQ;
1333 return ret;
1337 /***********************************************************************
1338 * NtOpenSection (NTDLL.@)
1339 * ZwOpenSection (NTDLL.@)
1341 NTSTATUS WINAPI NtOpenSection( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1343 NTSTATUS ret;
1344 DWORD len = attr->ObjectName->Length;
1346 if (len > MAX_PATH*sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
1348 SERVER_START_REQ( open_mapping )
1350 req->access = access;
1351 req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
1352 wine_server_add_data( req, attr->ObjectName->Buffer, len );
1353 if (!(ret = wine_server_call( req ))) *handle = reply->handle;
1355 SERVER_END_REQ;
1356 return ret;
1360 /***********************************************************************
1361 * NtMapViewOfSection (NTDLL.@)
1362 * ZwMapViewOfSection (NTDLL.@)
1364 NTSTATUS WINAPI NtMapViewOfSection( HANDLE handle, HANDLE process, PVOID *addr_ptr, ULONG zero_bits,
1365 ULONG commit_size, const LARGE_INTEGER *offset, ULONG *size_ptr,
1366 SECTION_INHERIT inherit, ULONG alloc_type, ULONG protect )
1368 FILE_VIEW *view;
1369 NTSTATUS res;
1370 UINT size = 0;
1371 int flags = MAP_PRIVATE;
1372 int unix_handle = -1;
1373 int prot;
1374 void *base, *ptr = (void *)-1, *ret;
1375 DWORD size_low, size_high, header_size, shared_size;
1376 HANDLE shared_file;
1377 BOOL removable;
1379 if (!is_current_process( process ))
1381 ERR("Unsupported on other process\n");
1382 return STATUS_ACCESS_DENIED;
1385 TRACE("handle=%p addr=%p off=%lx%08lx size=%x access=%lx\n",
1386 handle, *addr_ptr, offset->s.HighPart, offset->s.LowPart, size, protect );
1388 /* Check parameters */
1390 if ((offset->s.LowPart & granularity_mask) ||
1391 (*addr_ptr && ((UINT_PTR)*addr_ptr & granularity_mask)))
1392 return STATUS_INVALID_PARAMETER;
1394 SERVER_START_REQ( get_mapping_info )
1396 req->handle = handle;
1397 res = wine_server_call( req );
1398 prot = reply->protect;
1399 base = reply->base;
1400 size_low = reply->size_low;
1401 size_high = reply->size_high;
1402 header_size = reply->header_size;
1403 shared_file = reply->shared_file;
1404 shared_size = reply->shared_size;
1405 removable = (reply->drive_type == DRIVE_REMOVABLE ||
1406 reply->drive_type == DRIVE_CDROM);
1408 SERVER_END_REQ;
1409 if (res) goto error;
1411 if ((res = wine_server_handle_to_fd( handle, 0, &unix_handle, NULL, NULL ))) goto error;
1413 if (prot & VPROT_IMAGE)
1415 int shared_fd = -1;
1417 if (shared_file)
1419 if ((res = wine_server_handle_to_fd( shared_file, GENERIC_READ, &shared_fd,
1420 NULL, NULL ))) goto error;
1421 NtClose( shared_file ); /* we no longer need it */
1423 res = map_image( handle, unix_handle, base, size_low, header_size,
1424 shared_fd, shared_size, removable, addr_ptr );
1425 if (shared_fd != -1) close( shared_fd );
1426 if (!res) *size_ptr = size_low;
1427 return res;
1431 if (size_high)
1432 ERR("Sizes larger than 4Gb not supported\n");
1434 if ((offset->s.LowPart >= size_low) ||
1435 (*size_ptr > size_low - offset->s.LowPart))
1437 res = STATUS_INVALID_PARAMETER;
1438 goto error;
1440 if (*size_ptr) size = ROUND_SIZE( offset->s.LowPart, *size_ptr );
1441 else size = size_low - offset->s.LowPart;
1443 switch(protect)
1445 case PAGE_NOACCESS:
1446 break;
1447 case PAGE_READWRITE:
1448 case PAGE_EXECUTE_READWRITE:
1449 if (!(prot & VPROT_WRITE))
1451 res = STATUS_INVALID_PARAMETER;
1452 goto error;
1454 flags = MAP_SHARED;
1455 /* fall through */
1456 case PAGE_READONLY:
1457 case PAGE_WRITECOPY:
1458 case PAGE_EXECUTE:
1459 case PAGE_EXECUTE_READ:
1460 case PAGE_EXECUTE_WRITECOPY:
1461 if (prot & VPROT_READ) break;
1462 /* fall through */
1463 default:
1464 res = STATUS_INVALID_PARAMETER;
1465 goto error;
1468 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1469 * which has a view of this mapping commits some pages, they will
1470 * appear commited in all other processes, which have the same
1471 * view created. Since we don`t support this yet, we create the
1472 * whole mapping commited.
1474 prot |= VPROT_COMMITTED;
1476 /* Reserve a properly aligned area */
1478 if ((res = anon_mmap_aligned( addr_ptr, size, PROT_NONE, 0 ))) goto error;
1479 ptr = *addr_ptr;
1481 /* Map the file */
1483 TRACE("handle=%p size=%x offset=%lx\n", handle, size, offset->s.LowPart );
1485 ret = VIRTUAL_mmap( unix_handle, ptr, size, offset->s.LowPart, offset->s.HighPart,
1486 VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1487 if (ret != ptr)
1489 ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n",
1490 ptr, size, offset->s.HighPart, offset->s.LowPart );
1491 res = STATUS_NO_MEMORY; /* FIXME */
1492 goto error;
1494 if (removable) handle = 0; /* don't keep handle open on removable media */
1496 if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1498 res = STATUS_NO_MEMORY;
1499 goto error;
1501 if (unix_handle != -1) close( unix_handle );
1502 *size_ptr = size;
1503 return STATUS_SUCCESS;
1505 error:
1506 if (unix_handle != -1) close( unix_handle );
1507 if (ptr != (void *)-1) munmap( ptr, size );
1508 return res;
1512 /***********************************************************************
1513 * NtUnmapViewOfSection (NTDLL.@)
1514 * ZwUnmapViewOfSection (NTDLL.@)
1516 NTSTATUS WINAPI NtUnmapViewOfSection( HANDLE process, PVOID addr )
1518 FILE_VIEW *view;
1519 void *base = ROUND_ADDR( addr, page_mask );
1521 if (!is_current_process( process ))
1523 ERR("Unsupported on other process\n");
1524 return STATUS_ACCESS_DENIED;
1526 if (!(view = VIRTUAL_FindView( base )) || (base != view->base)) return STATUS_INVALID_PARAMETER;
1527 VIRTUAL_DeleteView( view );
1528 return STATUS_SUCCESS;
1532 /***********************************************************************
1533 * NtFlushVirtualMemory (NTDLL.@)
1534 * ZwFlushVirtualMemory (NTDLL.@)
1536 NTSTATUS WINAPI NtFlushVirtualMemory( HANDLE process, LPCVOID *addr_ptr,
1537 ULONG *size_ptr, ULONG unknown )
1539 FILE_VIEW *view;
1540 void *addr = ROUND_ADDR( *addr_ptr, page_mask );
1542 if (!is_current_process( process ))
1544 ERR("Unsupported on other process\n");
1545 return STATUS_ACCESS_DENIED;
1547 if (!(view = VIRTUAL_FindView( addr ))) return STATUS_INVALID_PARAMETER;
1548 if (!*size_ptr) *size_ptr = view->size;
1549 *addr_ptr = addr;
1550 if (!msync( addr, *size_ptr, MS_SYNC )) return STATUS_SUCCESS;
1551 return STATUS_NOT_MAPPED_DATA;
1555 /***********************************************************************
1556 * NtReadVirtualMemory (NTDLL.@)
1557 * ZwReadVirtualMemory (NTDLL.@)
1559 NTSTATUS WINAPI NtReadVirtualMemory( HANDLE process, const void *addr, void *buffer,
1560 SIZE_T size, SIZE_T *bytes_read )
1562 NTSTATUS status;
1564 SERVER_START_REQ( read_process_memory )
1566 req->handle = process;
1567 req->addr = (void *)addr;
1568 wine_server_set_reply( req, buffer, size );
1569 if ((status = wine_server_call( req ))) size = 0;
1571 SERVER_END_REQ;
1572 if (bytes_read) *bytes_read = size;
1573 return status;
1577 /***********************************************************************
1578 * NtWriteVirtualMemory (NTDLL.@)
1579 * ZwWriteVirtualMemory (NTDLL.@)
1581 NTSTATUS WINAPI NtWriteVirtualMemory( HANDLE process, void *addr, const void *buffer,
1582 SIZE_T size, SIZE_T *bytes_written )
1584 static const unsigned int zero;
1585 unsigned int first_offset, last_offset, first_mask, last_mask;
1586 NTSTATUS status;
1588 if (!size) return STATUS_INVALID_PARAMETER;
1590 /* compute the mask for the first int */
1591 first_mask = ~0;
1592 first_offset = (unsigned int)addr % sizeof(int);
1593 memset( &first_mask, 0, first_offset );
1595 /* compute the mask for the last int */
1596 last_offset = (size + first_offset) % sizeof(int);
1597 last_mask = 0;
1598 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1600 SERVER_START_REQ( write_process_memory )
1602 req->handle = process;
1603 req->addr = (char *)addr - first_offset;
1604 req->first_mask = first_mask;
1605 req->last_mask = last_mask;
1606 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1607 wine_server_add_data( req, buffer, size );
1608 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1610 if ((status = wine_server_call( req ))) size = 0;
1612 SERVER_END_REQ;
1613 if (bytes_written) *bytes_written = size;
1614 return status;