Some more RPC definitions.
[wine/multimedia.git] / memory / virtual.c
blobd3583c4feadb03d31eea1cfc0dca1d0dde4afb08
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997 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 #include <unistd.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_MMAN_H
36 #include <sys/mman.h>
37 #endif
38 #include "winnls.h"
39 #include "winbase.h"
40 #include "wine/exception.h"
41 #include "wine/unicode.h"
42 #include "wine/library.h"
43 #include "winerror.h"
44 #include "file.h"
45 #include "global.h"
46 #include "wine/server.h"
47 #include "msvcrt/excpt.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(virtual);
51 WINE_DECLARE_DEBUG_CHANNEL(module);
53 #ifndef MS_SYNC
54 #define MS_SYNC 0
55 #endif
57 /* File view */
58 typedef struct _FV
60 struct _FV *next; /* Next view */
61 struct _FV *prev; /* Prev view */
62 void *base; /* Base address */
63 UINT size; /* Size in bytes */
64 UINT flags; /* Allocation flags */
65 HANDLE mapping; /* Handle to the file mapping */
66 HANDLERPROC handlerProc; /* Fault handler */
67 LPVOID handlerArg; /* Fault handler argument */
68 BYTE protect; /* Protection for all pages at allocation time */
69 BYTE prot[1]; /* Protection byte for each page */
70 } FILE_VIEW;
72 /* Per-view flags */
73 #define VFLAG_SYSTEM 0x01
74 #define VFLAG_VALLOC 0x02 /* allocated by VirtualAlloc */
76 /* Conversion from VPROT_* to Win32 flags */
77 static const BYTE VIRTUAL_Win32Flags[16] =
79 PAGE_NOACCESS, /* 0 */
80 PAGE_READONLY, /* READ */
81 PAGE_READWRITE, /* WRITE */
82 PAGE_READWRITE, /* READ | WRITE */
83 PAGE_EXECUTE, /* EXEC */
84 PAGE_EXECUTE_READ, /* READ | EXEC */
85 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
86 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
87 PAGE_WRITECOPY, /* WRITECOPY */
88 PAGE_WRITECOPY, /* READ | WRITECOPY */
89 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
90 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
91 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
92 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
93 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
94 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
98 static FILE_VIEW *VIRTUAL_FirstView;
99 static CRITICAL_SECTION csVirtual = CRITICAL_SECTION_INIT("csVirtual");
101 #ifdef __i386__
102 /* These are always the same on an i386, and it will be faster this way */
103 # define page_mask 0xfff
104 # define page_shift 12
105 # define page_size 0x1000
106 #else
107 static UINT page_shift;
108 static UINT page_mask;
109 static UINT page_size;
110 #endif /* __i386__ */
111 #define granularity_mask 0xffff /* Allocation granularity (usually 64k) */
113 #define ADDRESS_SPACE_LIMIT ((void *)0xc0000000) /* top of the user address space */
115 #define ROUND_ADDR(addr,mask) \
116 ((void *)((UINT_PTR)(addr) & ~(mask)))
118 #define ROUND_SIZE(addr,size) \
119 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
121 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
122 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
124 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size, DWORD offset_low,
125 DWORD offset_high, int prot, int flags, BOOL *removable );
127 /* filter for page-fault exceptions */
128 static WINE_EXCEPTION_FILTER(page_fault)
130 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
131 return EXCEPTION_EXECUTE_HANDLER;
132 return EXCEPTION_CONTINUE_SEARCH;
135 /***********************************************************************
136 * VIRTUAL_GetProtStr
138 static const char *VIRTUAL_GetProtStr( BYTE prot )
140 static char buffer[6];
141 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
142 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
143 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
144 buffer[3] = (prot & VPROT_WRITE) ?
145 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
146 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
147 buffer[5] = 0;
148 return buffer;
152 /***********************************************************************
153 * VIRTUAL_DumpView
155 static void VIRTUAL_DumpView( FILE_VIEW *view )
157 UINT i, count;
158 char *addr = view->base;
159 BYTE prot = view->prot[0];
161 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
162 if (view->flags & VFLAG_SYSTEM)
163 DPRINTF( " (system)\n" );
164 else if (view->flags & VFLAG_VALLOC)
165 DPRINTF( " (valloc)\n" );
166 else if (view->mapping)
167 DPRINTF( " %d\n", view->mapping );
168 else
169 DPRINTF( " (anonymous)\n");
171 for (count = i = 1; i < view->size >> page_shift; i++, count++)
173 if (view->prot[i] == prot) continue;
174 DPRINTF( " %p - %p %s\n",
175 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
176 addr += (count << page_shift);
177 prot = view->prot[i];
178 count = 0;
180 if (count)
181 DPRINTF( " %p - %p %s\n",
182 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
186 /***********************************************************************
187 * VIRTUAL_Dump
189 void VIRTUAL_Dump(void)
191 FILE_VIEW *view;
192 DPRINTF( "\nDump of all virtual memory views:\n\n" );
193 EnterCriticalSection(&csVirtual);
194 view = VIRTUAL_FirstView;
195 while (view)
197 VIRTUAL_DumpView( view );
198 view = view->next;
200 LeaveCriticalSection(&csVirtual);
204 /***********************************************************************
205 * VIRTUAL_FindView
207 * Find the view containing a given address.
209 * RETURNS
210 * View: Success
211 * NULL: Failure
213 static FILE_VIEW *VIRTUAL_FindView( const void *addr ) /* [in] Address */
215 FILE_VIEW *view;
217 EnterCriticalSection(&csVirtual);
218 view = VIRTUAL_FirstView;
219 while (view)
221 if (view->base > addr)
223 view = NULL;
224 break;
226 if ((char*)view->base + view->size > (char*)addr) break;
227 view = view->next;
229 LeaveCriticalSection(&csVirtual);
230 return view;
234 /***********************************************************************
235 * VIRTUAL_CreateView
237 * Create a new view and add it in the linked list.
239 static FILE_VIEW *VIRTUAL_CreateView( void *base, UINT size, UINT flags,
240 BYTE vprot, HANDLE mapping )
242 FILE_VIEW *view, *prev;
244 /* Create the view structure */
246 assert( !((unsigned int)base & page_mask) );
247 assert( !(size & page_mask) );
248 size >>= page_shift;
249 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
250 view->base = base;
251 view->size = size << page_shift;
252 view->flags = flags;
253 view->mapping = mapping;
254 view->protect = vprot;
255 view->handlerProc = NULL;
256 memset( view->prot, vprot, size );
258 /* Duplicate the mapping handle */
260 if (view->mapping &&
261 !DuplicateHandle( GetCurrentProcess(), view->mapping,
262 GetCurrentProcess(), &view->mapping,
263 0, FALSE, DUPLICATE_SAME_ACCESS ))
265 free( view );
266 return NULL;
269 /* Insert it in the linked list */
271 EnterCriticalSection(&csVirtual);
272 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
274 view->next = VIRTUAL_FirstView;
275 view->prev = NULL;
276 if (view->next) view->next->prev = view;
277 VIRTUAL_FirstView = view;
279 else
281 prev = VIRTUAL_FirstView;
282 while (prev->next && (prev->next->base < base)) prev = prev->next;
283 view->next = prev->next;
284 view->prev = prev;
285 if (view->next) view->next->prev = view;
286 prev->next = view;
288 LeaveCriticalSection(&csVirtual);
289 VIRTUAL_DEBUG_DUMP_VIEW( view );
290 return view;
294 /***********************************************************************
295 * VIRTUAL_DeleteView
296 * Deletes a view.
298 * RETURNS
299 * None
301 static void VIRTUAL_DeleteView(
302 FILE_VIEW *view /* [in] View */
304 if (!(view->flags & VFLAG_SYSTEM))
305 munmap( (void *)view->base, view->size );
306 EnterCriticalSection(&csVirtual);
307 if (view->next) view->next->prev = view->prev;
308 if (view->prev) view->prev->next = view->next;
309 else VIRTUAL_FirstView = view->next;
310 LeaveCriticalSection(&csVirtual);
311 if (view->mapping) NtClose( view->mapping );
312 free( view );
316 /***********************************************************************
317 * VIRTUAL_GetUnixProt
319 * Convert page protections to protection for mmap/mprotect.
321 static int VIRTUAL_GetUnixProt( BYTE vprot )
323 int prot = 0;
324 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
326 if (vprot & VPROT_READ) prot |= PROT_READ;
327 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
328 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
329 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
331 return prot;
335 /***********************************************************************
336 * VIRTUAL_GetWin32Prot
338 * Convert page protections to Win32 flags.
340 * RETURNS
341 * None
343 static void VIRTUAL_GetWin32Prot(
344 BYTE vprot, /* [in] Page protection flags */
345 DWORD *protect, /* [out] Location to store Win32 protection flags */
346 DWORD *state /* [out] Location to store mem state flag */
348 if (protect) {
349 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
350 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
351 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
353 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
356 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
360 /***********************************************************************
361 * VIRTUAL_GetProt
363 * Build page protections from Win32 flags.
365 * RETURNS
366 * Value of page protection flags
368 static BYTE VIRTUAL_GetProt(
369 DWORD protect /* [in] Win32 protection flags */
371 BYTE vprot;
373 switch(protect & 0xff)
375 case PAGE_READONLY:
376 vprot = VPROT_READ;
377 break;
378 case PAGE_READWRITE:
379 vprot = VPROT_READ | VPROT_WRITE;
380 break;
381 case PAGE_WRITECOPY:
382 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
383 * that the hFile must have been opened with GENERIC_READ and
384 * GENERIC_WRITE access. This is WRONG as tests show that you
385 * only need GENERIC_READ access (at least for Win9x,
386 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
387 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
389 vprot = VPROT_READ | VPROT_WRITECOPY;
390 break;
391 case PAGE_EXECUTE:
392 vprot = VPROT_EXEC;
393 break;
394 case PAGE_EXECUTE_READ:
395 vprot = VPROT_EXEC | VPROT_READ;
396 break;
397 case PAGE_EXECUTE_READWRITE:
398 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
399 break;
400 case PAGE_EXECUTE_WRITECOPY:
401 /* See comment for PAGE_WRITECOPY above */
402 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
403 break;
404 case PAGE_NOACCESS:
405 default:
406 vprot = 0;
407 break;
409 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
410 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
411 return vprot;
415 /***********************************************************************
416 * VIRTUAL_SetProt
418 * Change the protection of a range of pages.
420 * RETURNS
421 * TRUE: Success
422 * FALSE: Failure
424 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
425 void *base, /* [in] Starting address */
426 UINT size, /* [in] Size in bytes */
427 BYTE vprot ) /* [in] Protections to use */
429 TRACE("%p-%p %s\n",
430 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
432 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
433 return FALSE; /* FIXME: last error */
435 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
436 vprot, size >> page_shift );
437 VIRTUAL_DEBUG_DUMP_VIEW( view );
438 return TRUE;
442 /***********************************************************************
443 * anon_mmap_aligned
445 * Create an anonymous mapping aligned to the allocation granularity.
447 static void *anon_mmap_aligned( void *base, unsigned int size, int prot, int flags )
449 void *ptr;
450 unsigned int view_size = size + (base ? 0 : granularity_mask + 1);
452 if ((ptr = wine_anon_mmap( base, view_size, prot, flags )) == (void *)-1)
454 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
455 * Platform Differences":
456 * Windows NT: ERROR_INVALID_PARAMETER
457 * Windows 95: ERROR_INVALID_ADDRESS.
459 if (errno == ENOMEM) SetLastError( ERROR_OUTOFMEMORY );
460 else
462 if (GetVersion() & 0x80000000) /* win95 */
463 SetLastError( ERROR_INVALID_ADDRESS );
464 else
465 SetLastError( ERROR_INVALID_PARAMETER );
467 return ptr;
470 if (!base)
472 /* Release the extra memory while keeping the range
473 * starting on the granularity boundary. */
474 if ((unsigned int)ptr & granularity_mask)
476 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
477 munmap( ptr, extra );
478 ptr = (char *)ptr + extra;
479 view_size -= extra;
481 if (view_size > size)
482 munmap( (char *)ptr + size, view_size - size );
484 else if (ptr != base)
486 /* We couldn't get the address we wanted */
487 munmap( ptr, view_size );
488 SetLastError( ERROR_INVALID_ADDRESS );
489 ptr = (void *)-1;
491 return ptr;
495 /***********************************************************************
496 * do_relocations
498 * Apply the relocations to a mapped PE image
500 static int do_relocations( char *base, const IMAGE_DATA_DIRECTORY *dir,
501 int delta, DWORD total_size )
503 IMAGE_BASE_RELOCATION *rel;
505 TRACE_(module)( "relocating from %p-%p to %p-%p\n",
506 base - delta, base - delta + total_size, base, base + total_size );
508 for (rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
509 ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
510 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock) )
512 char *page = base + rel->VirtualAddress;
513 WORD *TypeOffset = (WORD *)(rel + 1);
514 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
516 if (!count) continue;
518 /* sanity checks */
519 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
520 page > base + total_size)
522 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
523 rel, rel->VirtualAddress, rel->SizeOfBlock,
524 base, dir->VirtualAddress, dir->Size );
525 return 0;
528 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
530 /* patching in reverse order */
531 for (i = 0 ; i < count; i++)
533 int offset = TypeOffset[i] & 0xFFF;
534 int type = TypeOffset[i] >> 12;
535 switch(type)
537 case IMAGE_REL_BASED_ABSOLUTE:
538 break;
539 case IMAGE_REL_BASED_HIGH:
540 *(short*)(page+offset) += HIWORD(delta);
541 break;
542 case IMAGE_REL_BASED_LOW:
543 *(short*)(page+offset) += LOWORD(delta);
544 break;
545 case IMAGE_REL_BASED_HIGHLOW:
546 *(int*)(page+offset) += delta;
547 /* FIXME: if this is an exported address, fire up enhanced logic */
548 break;
549 default:
550 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
551 break;
555 return 1;
559 /***********************************************************************
560 * map_image
562 * Map an executable (PE format) image into memory.
564 static LPVOID map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
565 DWORD header_size, HANDLE shared_file, DWORD shared_size,
566 BOOL removable )
568 IMAGE_DOS_HEADER *dos;
569 IMAGE_NT_HEADERS *nt;
570 IMAGE_SECTION_HEADER *sec;
571 IMAGE_DATA_DIRECTORY *imports;
572 int i, pos;
573 DWORD err = GetLastError();
574 FILE_VIEW *view;
575 char *ptr;
576 int shared_fd = -1;
578 SetLastError( ERROR_BAD_EXE_FORMAT ); /* generic error */
580 /* zero-map the whole range */
582 if (base < (char *)0x110000 || /* make sure the DOS area remains free */
583 (ptr = wine_anon_mmap( base, total_size,
584 PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
586 ptr = wine_anon_mmap( NULL, total_size,
587 PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
588 if (ptr == (char *)-1)
590 ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
591 goto error;
594 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
596 /* map the header */
598 if (VIRTUAL_mmap( fd, ptr, header_size, 0, 0, PROT_READ,
599 MAP_PRIVATE | MAP_FIXED, &removable ) == (char *)-1) goto error;
600 dos = (IMAGE_DOS_HEADER *)ptr;
601 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
602 if ((char *)(nt + 1) > ptr + header_size) goto error;
604 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
605 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
607 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
608 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
610 /* check the architecture */
612 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
614 MESSAGE("Trying to load PE image for unsupported architecture (");
615 switch (nt->FileHeader.Machine)
617 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
618 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
619 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
620 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
621 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
622 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
623 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
624 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
626 MESSAGE(")\n");
627 goto error;
630 /* retrieve the shared sections file */
632 if (shared_size)
634 if ((shared_fd = FILE_GetUnixHandle( shared_file, GENERIC_READ )) == -1) goto error;
635 CloseHandle( shared_file ); /* we no longer need it */
636 shared_file = 0;
639 /* map all the sections */
641 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
643 DWORD size;
645 /* a few sanity checks */
646 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
647 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
649 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
650 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
651 goto error;
654 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
655 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
657 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
658 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
659 sec->Name, ptr + sec->VirtualAddress,
660 sec->PointerToRawData, pos, sec->SizeOfRawData,
661 size, sec->Characteristics );
662 if (VIRTUAL_mmap( shared_fd, ptr + sec->VirtualAddress, size,
663 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
664 MAP_SHARED|MAP_FIXED, NULL ) == (void *)-1)
666 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
667 goto error;
670 /* check if the import directory falls inside this section */
671 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
672 imports->VirtualAddress < sec->VirtualAddress + size)
674 DWORD base = imports->VirtualAddress & ~page_mask;
675 DWORD end = imports->VirtualAddress + ROUND_SIZE( imports->VirtualAddress,
676 imports->Size );
677 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
678 if (end > base) VIRTUAL_mmap( shared_fd, ptr + base, end - base,
679 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
680 MAP_PRIVATE|MAP_FIXED, NULL );
682 pos += size;
683 continue;
686 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
687 sec->Name, ptr + sec->VirtualAddress,
688 sec->PointerToRawData, sec->SizeOfRawData,
689 sec->Characteristics );
691 if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
692 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
694 /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
695 * fall back to read(), so we don't need to check anything here.
697 if (VIRTUAL_mmap( fd, ptr + sec->VirtualAddress, sec->SizeOfRawData,
698 sec->PointerToRawData, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
699 MAP_PRIVATE | MAP_FIXED, &removable ) == (void *)-1)
701 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
702 goto error;
705 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
707 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
708 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
709 TRACE_(module)("clearing %p - %p\n",
710 ptr + sec->VirtualAddress + sec->SizeOfRawData,
711 ptr + sec->VirtualAddress + end );
712 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
713 end - sec->SizeOfRawData );
718 /* perform base relocation, if necessary */
720 if (ptr != base)
722 const IMAGE_DATA_DIRECTORY *relocs;
724 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
725 if (!relocs->VirtualAddress || !relocs->Size)
727 if (nt->OptionalHeader.ImageBase == 0x400000)
728 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
729 else
730 ERR( "FATAL: Need to relocate module from addr %lx, but there are no relocation records\n",
731 nt->OptionalHeader.ImageBase );
732 SetLastError( ERROR_BAD_EXE_FORMAT );
733 goto error;
736 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
737 * really make sure that the *new* base address is also > 2GB.
738 * Some DLLs really check the MSB of the module handle :-/
740 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
741 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
743 if (!do_relocations( ptr, relocs, ptr - base, total_size ))
745 SetLastError( ERROR_BAD_EXE_FORMAT );
746 goto error;
750 if (removable) hmapping = 0; /* don't keep handle open on removable media */
751 if (!(view = VIRTUAL_CreateView( ptr, total_size, 0, VPROT_COMMITTED|VPROT_READ, hmapping )))
753 SetLastError( ERROR_OUTOFMEMORY );
754 goto error;
757 /* set the image protections */
759 sec = (IMAGE_SECTION_HEADER*)((char *)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
760 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
762 DWORD size = ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
763 BYTE vprot = VPROT_COMMITTED;
764 if (sec->Characteristics & IMAGE_SCN_MEM_READ) vprot |= VPROT_READ;
765 if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) vprot |= VPROT_WRITE|VPROT_WRITECOPY;
766 if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) vprot |= VPROT_EXEC;
768 /* make sure the import directory is writable */
769 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
770 imports->VirtualAddress < sec->VirtualAddress + size)
771 vprot |= VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY;
773 VIRTUAL_SetProt( view, ptr + sec->VirtualAddress, size, vprot );
776 SetLastError( err ); /* restore last error */
777 close( fd );
778 if (shared_fd != -1) close( shared_fd );
779 return ptr;
781 error:
782 if (ptr != (char *)-1) munmap( ptr, total_size );
783 close( fd );
784 if (shared_fd != -1) close( shared_fd );
785 if (shared_file) CloseHandle( shared_file );
786 return NULL;
790 /***********************************************************************
791 * VIRTUAL_Init
793 #ifndef page_mask
794 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
796 page_size = getpagesize();
797 page_mask = page_size - 1;
798 /* Make sure we have a power of 2 */
799 assert( !(page_size & page_mask) );
800 page_shift = 0;
801 while ((1 << page_shift) != page_size) page_shift++;
803 #endif /* page_mask */
806 /***********************************************************************
807 * VIRTUAL_SetFaultHandler
809 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
811 FILE_VIEW *view;
813 if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
814 view->handlerProc = proc;
815 view->handlerArg = arg;
816 return TRUE;
819 /***********************************************************************
820 * VIRTUAL_HandleFault
822 DWORD VIRTUAL_HandleFault( LPCVOID addr )
824 FILE_VIEW *view = VIRTUAL_FindView( addr );
825 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
827 if (view)
829 if (view->handlerProc)
831 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
833 else
835 BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
836 void *page = (void *)((UINT_PTR)addr & ~page_mask);
837 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
838 if (vprot & VPROT_GUARD)
840 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
841 ret = STATUS_GUARD_PAGE_VIOLATION;
843 /* is it inside the stack guard pages? */
844 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
845 ret = STATUS_STACK_OVERFLOW;
848 return ret;
853 /***********************************************************************
854 * unaligned_mmap
856 * Linux kernels before 2.4.x can support non page-aligned offsets, as
857 * long as the offset is aligned to the filesystem block size. This is
858 * a big performance gain so we want to take advantage of it.
860 * However, when we use 64-bit file support this doesn't work because
861 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
862 * in that it rounds unaligned offsets down to a page boundary. For
863 * these reasons we do a direct system call here.
865 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
866 unsigned int flags, int fd, unsigned int offset_low,
867 unsigned int offset_high )
869 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
870 if (!offset_high && (offset_low & page_mask))
872 int ret;
874 struct
876 void *addr;
877 unsigned int length;
878 unsigned int prot;
879 unsigned int flags;
880 unsigned int fd;
881 unsigned int offset;
882 } args;
884 args.addr = addr;
885 args.length = length;
886 args.prot = prot;
887 args.flags = flags;
888 args.fd = fd;
889 args.offset = offset_low;
891 __asm__ __volatile__("push %%ebx\n\t"
892 "movl %2,%%ebx\n\t"
893 "int $0x80\n\t"
894 "popl %%ebx"
895 : "=a" (ret)
896 : "0" (90), /* SYS_mmap */
897 "g" (&args) );
898 if (ret < 0 && ret > -4096)
900 errno = -ret;
901 ret = -1;
903 return (void *)ret;
905 #endif
906 return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
910 /***********************************************************************
911 * VIRTUAL_mmap
913 * Wrapper for mmap() that handles anonymous mappings portably,
914 * and falls back to read if mmap of a file fails.
916 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
917 DWORD offset_low, DWORD offset_high,
918 int prot, int flags, BOOL *removable )
920 int pos;
921 LPVOID ret;
922 off_t offset;
923 BOOL is_shared_write = FALSE;
925 if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
927 if (prot & PROT_WRITE)
929 #ifdef MAP_SHARED
930 if (flags & MAP_SHARED) is_shared_write = TRUE;
931 #endif
932 #ifdef MAP_PRIVATE
933 if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
934 #endif
937 if (removable && *removable)
939 /* if on removable media, try using read instead of mmap */
940 if (!is_shared_write) goto fake_mmap;
941 *removable = FALSE;
944 if ((ret = unaligned_mmap( start, size, prot, flags, fd,
945 offset_low, offset_high )) != (LPVOID)-1) return ret;
947 /* mmap() failed; if this is because the file offset is not */
948 /* page-aligned (EINVAL), or because the underlying filesystem */
949 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
951 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
952 if (is_shared_write) return ret; /* we cannot fake shared write mappings */
954 fake_mmap:
955 /* Reserve the memory with an anonymous mmap */
956 ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
957 if (ret == (LPVOID)-1) return ret;
958 /* Now read in the file */
959 offset = ((off_t)offset_high << 32) | offset_low;
960 if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
962 munmap( ret, size );
963 return (LPVOID)-1;
965 read( fd, ret, size );
966 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
967 mprotect( ret, size, prot ); /* Set the right protection */
968 return ret;
972 /***********************************************************************
973 * VirtualAlloc (KERNEL32.@)
974 * Reserves or commits a region of pages in virtual address space
976 * RETURNS
977 * Base address of allocated region of pages
978 * NULL: Failure
980 LPVOID WINAPI VirtualAlloc(
981 LPVOID addr, /* [in] Address of region to reserve or commit */
982 DWORD size, /* [in] Size of region */
983 DWORD type, /* [in] Type of allocation */
984 DWORD protect)/* [in] Type of access protection */
986 FILE_VIEW *view;
987 char *ptr, *base;
988 BYTE vprot;
990 TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
992 /* Round parameters to a page boundary */
994 if (size > 0x7fc00000) /* 2Gb - 4Mb */
996 SetLastError( ERROR_OUTOFMEMORY );
997 return NULL;
999 if (addr)
1001 if (type & MEM_RESERVE) /* Round down to 64k boundary */
1002 base = ROUND_ADDR( addr, granularity_mask );
1003 else
1004 base = ROUND_ADDR( addr, page_mask );
1005 size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
1007 /* disallow low 64k, wrap-around and kernel space */
1008 if ((base <= (char *)granularity_mask) ||
1009 (base + size < base) ||
1010 (base + size > (char *)ADDRESS_SPACE_LIMIT))
1012 SetLastError( ERROR_INVALID_PARAMETER );
1013 return NULL;
1016 else
1018 base = 0;
1019 size = (size + page_mask) & ~page_mask;
1022 if (type & MEM_TOP_DOWN) {
1023 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
1024 * Is there _ANY_ way to do it with UNIX mmap()?
1026 WARN("MEM_TOP_DOWN ignored\n");
1027 type &= ~MEM_TOP_DOWN;
1029 /* Compute the alloc type flags */
1031 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
1032 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
1034 ERR("called with wrong alloc type flags (%08lx) !\n", type);
1035 SetLastError( ERROR_INVALID_PARAMETER );
1036 return NULL;
1038 if (type & (MEM_COMMIT | MEM_SYSTEM))
1039 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
1040 else vprot = 0;
1042 /* Reserve the memory */
1044 if ((type & MEM_RESERVE) || !base)
1046 if (type & MEM_SYSTEM)
1048 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
1050 SetLastError( ERROR_OUTOFMEMORY );
1051 return NULL;
1053 return (LPVOID)base;
1055 ptr = anon_mmap_aligned( base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
1056 if (ptr == (void *)-1) return NULL;
1058 if (!(view = VIRTUAL_CreateView( ptr, size, VFLAG_VALLOC, vprot, 0 )))
1060 munmap( ptr, size );
1061 SetLastError( ERROR_OUTOFMEMORY );
1062 return NULL;
1064 return ptr;
1067 /* Commit the pages */
1069 if (!(view = VIRTUAL_FindView( base )) ||
1070 (base + size > (char *)view->base + view->size))
1072 SetLastError( ERROR_INVALID_ADDRESS );
1073 return NULL;
1076 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
1077 return (LPVOID)base;
1081 /***********************************************************************
1082 * VirtualAllocEx (KERNEL32.@)
1084 * Seems to be just as VirtualAlloc, but with process handle.
1086 LPVOID WINAPI VirtualAllocEx(
1087 HANDLE hProcess, /* [in] Handle of process to do mem operation */
1088 LPVOID addr, /* [in] Address of region to reserve or commit */
1089 DWORD size, /* [in] Size of region */
1090 DWORD type, /* [in] Type of allocation */
1091 DWORD protect /* [in] Type of access protection */
1093 if (MapProcessHandle( hProcess ) == GetCurrentProcessId())
1094 return VirtualAlloc( addr, size, type, protect );
1095 ERR("Unsupported on other process\n");
1096 return NULL;
1100 /***********************************************************************
1101 * VirtualFree (KERNEL32.@)
1102 * Release or decommits a region of pages in virtual address space.
1104 * RETURNS
1105 * TRUE: Success
1106 * FALSE: Failure
1108 BOOL WINAPI VirtualFree(
1109 LPVOID addr, /* [in] Address of region of committed pages */
1110 DWORD size, /* [in] Size of region */
1111 DWORD type /* [in] Type of operation */
1113 FILE_VIEW *view;
1114 char *base;
1116 TRACE("%p %08lx %lx\n", addr, size, type );
1118 /* Fix the parameters */
1120 size = ROUND_SIZE( addr, size );
1121 base = ROUND_ADDR( addr, page_mask );
1123 if (!(view = VIRTUAL_FindView( base )) ||
1124 (base + size > (char *)view->base + view->size) ||
1125 !(view->flags & VFLAG_VALLOC))
1127 SetLastError( ERROR_INVALID_PARAMETER );
1128 return FALSE;
1131 /* Check the type */
1133 if (type & MEM_SYSTEM)
1135 view->flags |= VFLAG_SYSTEM;
1136 type &= ~MEM_SYSTEM;
1139 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
1141 ERR("called with wrong free type flags (%08lx) !\n", type);
1142 SetLastError( ERROR_INVALID_PARAMETER );
1143 return FALSE;
1146 /* Free the pages */
1148 if (type == MEM_RELEASE)
1150 if (size || (base != view->base))
1152 SetLastError( ERROR_INVALID_PARAMETER );
1153 return FALSE;
1155 VIRTUAL_DeleteView( view );
1156 return TRUE;
1159 /* Decommit the pages by remapping zero-pages instead */
1161 if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1162 ERR( "Could not remap pages, expect trouble\n" );
1163 return VIRTUAL_SetProt( view, base, size, 0 );
1167 /***********************************************************************
1168 * VirtualLock (KERNEL32.@)
1169 * Locks the specified region of virtual address space
1171 * NOTE
1172 * Always returns TRUE
1174 * RETURNS
1175 * TRUE: Success
1176 * FALSE: Failure
1178 BOOL WINAPI VirtualLock(
1179 LPVOID addr, /* [in] Address of first byte of range to lock */
1180 DWORD size /* [in] Number of bytes in range to lock */
1182 return TRUE;
1186 /***********************************************************************
1187 * VirtualUnlock (KERNEL32.@)
1188 * Unlocks a range of pages in the virtual address space
1190 * NOTE
1191 * Always returns TRUE
1193 * RETURNS
1194 * TRUE: Success
1195 * FALSE: Failure
1197 BOOL WINAPI VirtualUnlock(
1198 LPVOID addr, /* [in] Address of first byte of range */
1199 DWORD size /* [in] Number of bytes in range */
1201 return TRUE;
1205 /***********************************************************************
1206 * VirtualProtect (KERNEL32.@)
1207 * Changes the access protection on a region of committed pages
1209 * RETURNS
1210 * TRUE: Success
1211 * FALSE: Failure
1213 BOOL WINAPI VirtualProtect(
1214 LPVOID addr, /* [in] Address of region of committed pages */
1215 DWORD size, /* [in] Size of region */
1216 DWORD new_prot, /* [in] Desired access protection */
1217 LPDWORD old_prot /* [out] Address of variable to get old protection */
1219 FILE_VIEW *view;
1220 char *base;
1221 UINT i;
1222 BYTE vprot, *p;
1223 DWORD prot;
1225 TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1227 /* Fix the parameters */
1229 size = ROUND_SIZE( addr, size );
1230 base = ROUND_ADDR( addr, page_mask );
1232 if (!(view = VIRTUAL_FindView( base )) ||
1233 (base + size > (char *)view->base + view->size))
1235 SetLastError( ERROR_INVALID_PARAMETER );
1236 return FALSE;
1239 /* Make sure all the pages are committed */
1241 p = view->prot + ((base - (char *)view->base) >> page_shift);
1242 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1243 for (i = size >> page_shift; i; i--, p++)
1245 if (!(*p & VPROT_COMMITTED))
1247 SetLastError( ERROR_INVALID_PARAMETER );
1248 return FALSE;
1252 if (old_prot) *old_prot = prot;
1253 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1254 return VIRTUAL_SetProt( view, base, size, vprot );
1258 /***********************************************************************
1259 * VirtualProtectEx (KERNEL32.@)
1260 * Changes the access protection on a region of committed pages in the
1261 * virtual address space of a specified process
1263 * RETURNS
1264 * TRUE: Success
1265 * FALSE: Failure
1267 BOOL WINAPI VirtualProtectEx(
1268 HANDLE handle, /* [in] Handle of process */
1269 LPVOID addr, /* [in] Address of region of committed pages */
1270 DWORD size, /* [in] Size of region */
1271 DWORD new_prot, /* [in] Desired access protection */
1272 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
1274 if (MapProcessHandle( handle ) == GetCurrentProcessId())
1275 return VirtualProtect( addr, size, new_prot, old_prot );
1276 ERR("Unsupported on other process\n");
1277 return FALSE;
1281 /***********************************************************************
1282 * VirtualQuery (KERNEL32.@)
1283 * Provides info about a range of pages in virtual address space
1285 * RETURNS
1286 * Number of bytes returned in information buffer
1287 * or 0 if addr is >= 0xc0000000 (kernel space).
1289 DWORD WINAPI VirtualQuery(
1290 LPCVOID addr, /* [in] Address of region */
1291 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1292 DWORD len /* [in] Size of buffer */
1294 FILE_VIEW *view;
1295 char *base, *alloc_base = 0;
1296 UINT size = 0;
1298 if (addr >= ADDRESS_SPACE_LIMIT) return 0;
1300 base = ROUND_ADDR( addr, page_mask );
1302 /* Find the view containing the address */
1304 EnterCriticalSection(&csVirtual);
1305 view = VIRTUAL_FirstView;
1306 for (;;)
1308 if (!view)
1310 size = (char *)ADDRESS_SPACE_LIMIT - alloc_base;
1311 break;
1313 if ((char *)view->base > base)
1315 size = (char *)view->base - alloc_base;
1316 view = NULL;
1317 break;
1319 if ((char *)view->base + view->size > base)
1321 alloc_base = view->base;
1322 size = view->size;
1323 break;
1325 alloc_base = (char *)view->base + view->size;
1326 view = view->next;
1328 LeaveCriticalSection(&csVirtual);
1330 /* Fill the info structure */
1332 if (!view)
1334 info->State = MEM_FREE;
1335 info->Protect = 0;
1336 info->AllocationProtect = 0;
1337 info->Type = 0;
1339 else
1341 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1342 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1343 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1344 if (view->prot[size >> page_shift] != vprot) break;
1345 info->AllocationProtect = view->protect;
1346 info->Type = MEM_PRIVATE; /* FIXME */
1349 info->BaseAddress = (LPVOID)base;
1350 info->AllocationBase = (LPVOID)alloc_base;
1351 info->RegionSize = size - (base - alloc_base);
1352 return sizeof(*info);
1356 /***********************************************************************
1357 * VirtualQueryEx (KERNEL32.@)
1358 * Provides info about a range of pages in virtual address space of a
1359 * specified process
1361 * RETURNS
1362 * Number of bytes returned in information buffer
1364 DWORD WINAPI VirtualQueryEx(
1365 HANDLE handle, /* [in] Handle of process */
1366 LPCVOID addr, /* [in] Address of region */
1367 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1368 DWORD len /* [in] Size of buffer */ )
1370 if (MapProcessHandle( handle ) == GetCurrentProcessId())
1371 return VirtualQuery( addr, info, len );
1372 ERR("Unsupported on other process\n");
1373 return 0;
1377 /***********************************************************************
1378 * IsBadReadPtr (KERNEL32.@)
1380 * RETURNS
1381 * FALSE: Process has read access to entire block
1382 * TRUE: Otherwise
1384 BOOL WINAPI IsBadReadPtr(
1385 LPCVOID ptr, /* [in] Address of memory block */
1386 UINT size ) /* [in] Size of block */
1388 if (!size) return FALSE; /* handle 0 size case w/o reference */
1389 __TRY
1391 volatile const char *p = ptr;
1392 char dummy;
1393 UINT count = size;
1395 while (count > page_size)
1397 dummy = *p;
1398 p += page_size;
1399 count -= page_size;
1401 dummy = p[0];
1402 dummy = p[count - 1];
1404 __EXCEPT(page_fault) { return TRUE; }
1405 __ENDTRY
1406 return FALSE;
1410 /***********************************************************************
1411 * IsBadWritePtr (KERNEL32.@)
1413 * RETURNS
1414 * FALSE: Process has write access to entire block
1415 * TRUE: Otherwise
1417 BOOL WINAPI IsBadWritePtr(
1418 LPVOID ptr, /* [in] Address of memory block */
1419 UINT size ) /* [in] Size of block in bytes */
1421 if (!size) return FALSE; /* handle 0 size case w/o reference */
1422 __TRY
1424 volatile char *p = ptr;
1425 UINT count = size;
1427 while (count > page_size)
1429 *p |= 0;
1430 p += page_size;
1431 count -= page_size;
1433 p[0] |= 0;
1434 p[count - 1] |= 0;
1436 __EXCEPT(page_fault) { return TRUE; }
1437 __ENDTRY
1438 return FALSE;
1442 /***********************************************************************
1443 * IsBadHugeReadPtr (KERNEL32.@)
1444 * RETURNS
1445 * FALSE: Process has read access to entire block
1446 * TRUE: Otherwise
1448 BOOL WINAPI IsBadHugeReadPtr(
1449 LPCVOID ptr, /* [in] Address of memory block */
1450 UINT size /* [in] Size of block */
1452 return IsBadReadPtr( ptr, size );
1456 /***********************************************************************
1457 * IsBadHugeWritePtr (KERNEL32.@)
1458 * RETURNS
1459 * FALSE: Process has write access to entire block
1460 * TRUE: Otherwise
1462 BOOL WINAPI IsBadHugeWritePtr(
1463 LPVOID ptr, /* [in] Address of memory block */
1464 UINT size /* [in] Size of block */
1466 return IsBadWritePtr( ptr, size );
1470 /***********************************************************************
1471 * IsBadCodePtr (KERNEL32.@)
1473 * RETURNS
1474 * FALSE: Process has read access to specified memory
1475 * TRUE: Otherwise
1477 BOOL WINAPI IsBadCodePtr( FARPROC ptr ) /* [in] Address of function */
1479 return IsBadReadPtr( ptr, 1 );
1483 /***********************************************************************
1484 * IsBadStringPtrA (KERNEL32.@)
1486 * RETURNS
1487 * FALSE: Read access to all bytes in string
1488 * TRUE: Else
1490 BOOL WINAPI IsBadStringPtrA(
1491 LPCSTR str, /* [in] Address of string */
1492 UINT max ) /* [in] Maximum size of string */
1494 __TRY
1496 volatile const char *p = str;
1497 while (p != str + max) if (!*p++) break;
1499 __EXCEPT(page_fault) { return TRUE; }
1500 __ENDTRY
1501 return FALSE;
1505 /***********************************************************************
1506 * IsBadStringPtrW (KERNEL32.@)
1507 * See IsBadStringPtrA
1509 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1511 __TRY
1513 volatile const WCHAR *p = str;
1514 while (p != str + max) if (!*p++) break;
1516 __EXCEPT(page_fault) { return TRUE; }
1517 __ENDTRY
1518 return FALSE;
1522 /***********************************************************************
1523 * CreateFileMappingA (KERNEL32.@)
1524 * Creates a named or unnamed file-mapping object for the specified file
1526 * RETURNS
1527 * Handle: Success
1528 * 0: Mapping object does not exist
1529 * NULL: Failure
1531 HANDLE WINAPI CreateFileMappingA(
1532 HANDLE hFile, /* [in] Handle of file to map */
1533 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1534 DWORD protect, /* [in] Protection for mapping object */
1535 DWORD size_high, /* [in] High-order 32 bits of object size */
1536 DWORD size_low, /* [in] Low-order 32 bits of object size */
1537 LPCSTR name /* [in] Name of file-mapping object */ )
1539 WCHAR buffer[MAX_PATH];
1541 if (!name) return CreateFileMappingW( hFile, sa, protect, size_high, size_low, NULL );
1543 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1545 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1546 return 0;
1548 return CreateFileMappingW( hFile, sa, protect, size_high, size_low, buffer );
1552 /***********************************************************************
1553 * CreateFileMappingW (KERNEL32.@)
1554 * See CreateFileMappingA
1556 HANDLE WINAPI CreateFileMappingW( HANDLE hFile, LPSECURITY_ATTRIBUTES sa,
1557 DWORD protect, DWORD size_high,
1558 DWORD size_low, LPCWSTR name )
1560 HANDLE ret;
1561 BYTE vprot;
1562 DWORD len = name ? strlenW(name) : 0;
1564 /* Check parameters */
1566 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1567 hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1569 if (len > MAX_PATH)
1571 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1572 return 0;
1575 vprot = VIRTUAL_GetProt( protect );
1576 if (protect & SEC_RESERVE)
1578 if (hFile != INVALID_HANDLE_VALUE)
1580 SetLastError( ERROR_INVALID_PARAMETER );
1581 return 0;
1584 else vprot |= VPROT_COMMITTED;
1585 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1586 if (protect & SEC_IMAGE) vprot |= VPROT_IMAGE;
1588 /* Create the server object */
1590 if (hFile == INVALID_HANDLE_VALUE) hFile = 0;
1591 SERVER_START_REQ( create_mapping )
1593 req->file_handle = hFile;
1594 req->size_high = size_high;
1595 req->size_low = size_low;
1596 req->protect = vprot;
1597 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1598 wine_server_add_data( req, name, len * sizeof(WCHAR) );
1599 SetLastError(0);
1600 wine_server_call_err( req );
1601 ret = reply->handle;
1603 SERVER_END_REQ;
1604 return ret;
1608 /***********************************************************************
1609 * OpenFileMappingA (KERNEL32.@)
1610 * Opens a named file-mapping object.
1612 * RETURNS
1613 * Handle: Success
1614 * NULL: Failure
1616 HANDLE WINAPI OpenFileMappingA(
1617 DWORD access, /* [in] Access mode */
1618 BOOL inherit, /* [in] Inherit flag */
1619 LPCSTR name ) /* [in] Name of file-mapping object */
1621 WCHAR buffer[MAX_PATH];
1623 if (!name) return OpenFileMappingW( access, inherit, NULL );
1625 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1627 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1628 return 0;
1630 return OpenFileMappingW( access, inherit, buffer );
1634 /***********************************************************************
1635 * OpenFileMappingW (KERNEL32.@)
1636 * See OpenFileMappingA
1638 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1640 HANDLE ret;
1641 DWORD len = name ? strlenW(name) : 0;
1642 if (len >= MAX_PATH)
1644 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1645 return 0;
1647 SERVER_START_REQ( open_mapping )
1649 req->access = access;
1650 req->inherit = inherit;
1651 wine_server_add_data( req, name, len * sizeof(WCHAR) );
1652 wine_server_call_err( req );
1653 ret = reply->handle;
1655 SERVER_END_REQ;
1656 return ret;
1660 /***********************************************************************
1661 * MapViewOfFile (KERNEL32.@)
1662 * Maps a view of a file into the address space
1664 * RETURNS
1665 * Starting address of mapped view
1666 * NULL: Failure
1668 LPVOID WINAPI MapViewOfFile(
1669 HANDLE mapping, /* [in] File-mapping object to map */
1670 DWORD access, /* [in] Access mode */
1671 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1672 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1673 DWORD count /* [in] Number of bytes to map */
1675 return MapViewOfFileEx( mapping, access, offset_high,
1676 offset_low, count, NULL );
1680 /***********************************************************************
1681 * MapViewOfFileEx (KERNEL32.@)
1682 * Maps a view of a file into the address space
1684 * RETURNS
1685 * Starting address of mapped view
1686 * NULL: Failure
1688 LPVOID WINAPI MapViewOfFileEx(
1689 HANDLE handle, /* [in] File-mapping object to map */
1690 DWORD access, /* [in] Access mode */
1691 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1692 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1693 DWORD count, /* [in] Number of bytes to map */
1694 LPVOID addr /* [in] Suggested starting address for mapped view */
1696 FILE_VIEW *view;
1697 UINT size = 0;
1698 int flags = MAP_PRIVATE;
1699 int unix_handle = -1;
1700 int prot, res;
1701 void *base, *ptr = (void *)-1, *ret;
1702 DWORD size_low, size_high, header_size, shared_size;
1703 HANDLE shared_file;
1704 BOOL removable;
1706 /* Check parameters */
1708 if ((offset_low & granularity_mask) ||
1709 (addr && ((UINT_PTR)addr & granularity_mask)))
1711 SetLastError( ERROR_INVALID_PARAMETER );
1712 return NULL;
1715 SERVER_START_REQ( get_mapping_info )
1717 req->handle = handle;
1718 res = wine_server_call_err( req );
1719 prot = reply->protect;
1720 base = reply->base;
1721 size_low = reply->size_low;
1722 size_high = reply->size_high;
1723 header_size = reply->header_size;
1724 shared_file = reply->shared_file;
1725 shared_size = reply->shared_size;
1726 removable = (reply->drive_type == DRIVE_REMOVABLE ||
1727 reply->drive_type == DRIVE_CDROM);
1729 SERVER_END_REQ;
1730 if (res) goto error;
1732 if ((unix_handle = FILE_GetUnixHandle( handle, 0 )) == -1) goto error;
1734 if (prot & VPROT_IMAGE)
1735 return map_image( handle, unix_handle, base, size_low, header_size,
1736 shared_file, shared_size, removable );
1739 if (size_high)
1740 ERR("Sizes larger than 4Gb not supported\n");
1742 if ((offset_low >= size_low) ||
1743 (count > size_low - offset_low))
1745 SetLastError( ERROR_INVALID_PARAMETER );
1746 goto error;
1748 if (count) size = ROUND_SIZE( offset_low, count );
1749 else size = size_low - offset_low;
1751 switch(access)
1753 case FILE_MAP_ALL_ACCESS:
1754 case FILE_MAP_WRITE:
1755 case FILE_MAP_WRITE | FILE_MAP_READ:
1756 if (!(prot & VPROT_WRITE))
1758 SetLastError( ERROR_INVALID_PARAMETER );
1759 goto error;
1761 flags = MAP_SHARED;
1762 /* fall through */
1763 case FILE_MAP_READ:
1764 case FILE_MAP_COPY:
1765 case FILE_MAP_COPY | FILE_MAP_READ:
1766 if (prot & VPROT_READ) break;
1767 /* fall through */
1768 default:
1769 SetLastError( ERROR_INVALID_PARAMETER );
1770 goto error;
1773 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1774 * which has a view of this mapping commits some pages, they will
1775 * appear commited in all other processes, which have the same
1776 * view created. Since we don`t support this yet, we create the
1777 * whole mapping commited.
1779 prot |= VPROT_COMMITTED;
1781 /* Reserve a properly aligned area */
1783 if ((ptr = anon_mmap_aligned( addr, size, PROT_NONE, 0 )) == (void *)-1) goto error;
1785 /* Map the file */
1787 TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1789 ret = VIRTUAL_mmap( unix_handle, ptr, size, offset_low, offset_high,
1790 VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1791 if (ret != ptr)
1793 ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n", ptr, size, offset_high, offset_low );
1794 goto error;
1796 if (removable) handle = 0; /* don't keep handle open on removable media */
1798 if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1800 SetLastError( ERROR_OUTOFMEMORY );
1801 goto error;
1803 if (unix_handle != -1) close( unix_handle );
1804 return ptr;
1806 error:
1807 if (unix_handle != -1) close( unix_handle );
1808 if (ptr != (void *)-1) munmap( ptr, size );
1809 return NULL;
1813 /***********************************************************************
1814 * FlushViewOfFile (KERNEL32.@)
1815 * Writes to the disk a byte range within a mapped view of a file
1817 * RETURNS
1818 * TRUE: Success
1819 * FALSE: Failure
1821 BOOL WINAPI FlushViewOfFile(
1822 LPCVOID base, /* [in] Start address of byte range to flush */
1823 DWORD cbFlush /* [in] Number of bytes in range */
1825 FILE_VIEW *view;
1826 void *addr = ROUND_ADDR( base, page_mask );
1828 TRACE("FlushViewOfFile at %p for %ld bytes\n",
1829 base, cbFlush );
1831 if (!(view = VIRTUAL_FindView( addr )))
1833 SetLastError( ERROR_INVALID_PARAMETER );
1834 return FALSE;
1836 if (!cbFlush) cbFlush = view->size;
1837 if (!msync( addr, cbFlush, MS_SYNC )) return TRUE;
1838 SetLastError( ERROR_INVALID_PARAMETER );
1839 return FALSE;
1843 /***********************************************************************
1844 * UnmapViewOfFile (KERNEL32.@)
1845 * Unmaps a mapped view of a file.
1847 * NOTES
1848 * Should addr be an LPCVOID?
1850 * RETURNS
1851 * TRUE: Success
1852 * FALSE: Failure
1854 BOOL WINAPI UnmapViewOfFile(
1855 LPVOID addr /* [in] Address where mapped view begins */
1857 FILE_VIEW *view;
1858 void *base = ROUND_ADDR( addr, page_mask );
1859 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1861 SetLastError( ERROR_INVALID_PARAMETER );
1862 return FALSE;
1864 VIRTUAL_DeleteView( view );
1865 return TRUE;