Added writing META_ESCAPE records.
[wine.git] / memory / virtual.c
blob1ecbfb603ef38902a5dab9cc5149466fb72685ae
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 ROUND_ADDR(addr,mask) \
114 ((void *)((UINT_PTR)(addr) & ~(mask)))
116 #define ROUND_SIZE(addr,size) \
117 (((UINT)(size) + ((UINT_PTR)(addr) & page_mask) + page_mask) & ~page_mask)
119 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
120 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
122 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size, DWORD offset_low,
123 DWORD offset_high, int prot, int flags, BOOL *removable );
125 /* filter for page-fault exceptions */
126 static WINE_EXCEPTION_FILTER(page_fault)
128 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
129 return EXCEPTION_EXECUTE_HANDLER;
130 return EXCEPTION_CONTINUE_SEARCH;
133 /***********************************************************************
134 * VIRTUAL_GetProtStr
136 static const char *VIRTUAL_GetProtStr( BYTE prot )
138 static char buffer[6];
139 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
140 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
141 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
142 buffer[3] = (prot & VPROT_WRITE) ?
143 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
144 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
145 buffer[5] = 0;
146 return buffer;
150 /***********************************************************************
151 * VIRTUAL_DumpView
153 static void VIRTUAL_DumpView( FILE_VIEW *view )
155 UINT i, count;
156 char *addr = view->base;
157 BYTE prot = view->prot[0];
159 DPRINTF( "View: %p - %p", addr, addr + view->size - 1 );
160 if (view->flags & VFLAG_SYSTEM)
161 DPRINTF( " (system)\n" );
162 else if (view->flags & VFLAG_VALLOC)
163 DPRINTF( " (valloc)\n" );
164 else if (view->mapping)
165 DPRINTF( " %d\n", view->mapping );
166 else
167 DPRINTF( " (anonymous)\n");
169 for (count = i = 1; i < view->size >> page_shift; i++, count++)
171 if (view->prot[i] == prot) continue;
172 DPRINTF( " %p - %p %s\n",
173 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
174 addr += (count << page_shift);
175 prot = view->prot[i];
176 count = 0;
178 if (count)
179 DPRINTF( " %p - %p %s\n",
180 addr, addr + (count << page_shift) - 1, VIRTUAL_GetProtStr(prot) );
184 /***********************************************************************
185 * VIRTUAL_Dump
187 void VIRTUAL_Dump(void)
189 FILE_VIEW *view;
190 DPRINTF( "\nDump of all virtual memory views:\n\n" );
191 EnterCriticalSection(&csVirtual);
192 view = VIRTUAL_FirstView;
193 while (view)
195 VIRTUAL_DumpView( view );
196 view = view->next;
198 LeaveCriticalSection(&csVirtual);
202 /***********************************************************************
203 * VIRTUAL_FindView
205 * Find the view containing a given address.
207 * RETURNS
208 * View: Success
209 * NULL: Failure
211 static FILE_VIEW *VIRTUAL_FindView( const void *addr ) /* [in] Address */
213 FILE_VIEW *view;
215 EnterCriticalSection(&csVirtual);
216 view = VIRTUAL_FirstView;
217 while (view)
219 if (view->base > addr)
221 view = NULL;
222 break;
224 if (view->base + view->size > addr) break;
225 view = view->next;
227 LeaveCriticalSection(&csVirtual);
228 return view;
232 /***********************************************************************
233 * VIRTUAL_CreateView
235 * Create a new view and add it in the linked list.
237 static FILE_VIEW *VIRTUAL_CreateView( void *base, UINT size, UINT flags,
238 BYTE vprot, HANDLE mapping )
240 FILE_VIEW *view, *prev;
242 /* Create the view structure */
244 assert( !((unsigned int)base & page_mask) );
245 assert( !(size & page_mask) );
246 size >>= page_shift;
247 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
248 view->base = base;
249 view->size = size << page_shift;
250 view->flags = flags;
251 view->mapping = mapping;
252 view->protect = vprot;
253 view->handlerProc = NULL;
254 memset( view->prot, vprot, size );
256 /* Duplicate the mapping handle */
258 if (view->mapping &&
259 !DuplicateHandle( GetCurrentProcess(), view->mapping,
260 GetCurrentProcess(), &view->mapping,
261 0, FALSE, DUPLICATE_SAME_ACCESS ))
263 free( view );
264 return NULL;
267 /* Insert it in the linked list */
269 EnterCriticalSection(&csVirtual);
270 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
272 view->next = VIRTUAL_FirstView;
273 view->prev = NULL;
274 if (view->next) view->next->prev = view;
275 VIRTUAL_FirstView = view;
277 else
279 prev = VIRTUAL_FirstView;
280 while (prev->next && (prev->next->base < base)) prev = prev->next;
281 view->next = prev->next;
282 view->prev = prev;
283 if (view->next) view->next->prev = view;
284 prev->next = view;
286 LeaveCriticalSection(&csVirtual);
287 VIRTUAL_DEBUG_DUMP_VIEW( view );
288 return view;
292 /***********************************************************************
293 * VIRTUAL_DeleteView
294 * Deletes a view.
296 * RETURNS
297 * None
299 static void VIRTUAL_DeleteView(
300 FILE_VIEW *view /* [in] View */
302 if (!(view->flags & VFLAG_SYSTEM))
303 munmap( (void *)view->base, view->size );
304 EnterCriticalSection(&csVirtual);
305 if (view->next) view->next->prev = view->prev;
306 if (view->prev) view->prev->next = view->next;
307 else VIRTUAL_FirstView = view->next;
308 LeaveCriticalSection(&csVirtual);
309 if (view->mapping) NtClose( view->mapping );
310 free( view );
314 /***********************************************************************
315 * VIRTUAL_GetUnixProt
317 * Convert page protections to protection for mmap/mprotect.
319 static int VIRTUAL_GetUnixProt( BYTE vprot )
321 int prot = 0;
322 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
324 if (vprot & VPROT_READ) prot |= PROT_READ;
325 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
326 if (vprot & VPROT_WRITECOPY) prot |= PROT_WRITE;
327 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
329 return prot;
333 /***********************************************************************
334 * VIRTUAL_GetWin32Prot
336 * Convert page protections to Win32 flags.
338 * RETURNS
339 * None
341 static void VIRTUAL_GetWin32Prot(
342 BYTE vprot, /* [in] Page protection flags */
343 DWORD *protect, /* [out] Location to store Win32 protection flags */
344 DWORD *state /* [out] Location to store mem state flag */
346 if (protect) {
347 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
348 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
349 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
351 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
354 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
358 /***********************************************************************
359 * VIRTUAL_GetProt
361 * Build page protections from Win32 flags.
363 * RETURNS
364 * Value of page protection flags
366 static BYTE VIRTUAL_GetProt(
367 DWORD protect /* [in] Win32 protection flags */
369 BYTE vprot;
371 switch(protect & 0xff)
373 case PAGE_READONLY:
374 vprot = VPROT_READ;
375 break;
376 case PAGE_READWRITE:
377 vprot = VPROT_READ | VPROT_WRITE;
378 break;
379 case PAGE_WRITECOPY:
380 /* MSDN CreateFileMapping() states that if PAGE_WRITECOPY is given,
381 * that the hFile must have been opened with GENERIC_READ and
382 * GENERIC_WRITE access. This is WRONG as tests show that you
383 * only need GENERIC_READ access (at least for Win9x,
384 * FIXME: what about NT?). Thus, we don't put VPROT_WRITE in
385 * PAGE_WRITECOPY and PAGE_EXECUTE_WRITECOPY.
387 vprot = VPROT_READ | VPROT_WRITECOPY;
388 break;
389 case PAGE_EXECUTE:
390 vprot = VPROT_EXEC;
391 break;
392 case PAGE_EXECUTE_READ:
393 vprot = VPROT_EXEC | VPROT_READ;
394 break;
395 case PAGE_EXECUTE_READWRITE:
396 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
397 break;
398 case PAGE_EXECUTE_WRITECOPY:
399 /* See comment for PAGE_WRITECOPY above */
400 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITECOPY;
401 break;
402 case PAGE_NOACCESS:
403 default:
404 vprot = 0;
405 break;
407 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
408 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
409 return vprot;
413 /***********************************************************************
414 * VIRTUAL_SetProt
416 * Change the protection of a range of pages.
418 * RETURNS
419 * TRUE: Success
420 * FALSE: Failure
422 static BOOL VIRTUAL_SetProt( FILE_VIEW *view, /* [in] Pointer to view */
423 void *base, /* [in] Starting address */
424 UINT size, /* [in] Size in bytes */
425 BYTE vprot ) /* [in] Protections to use */
427 TRACE("%p-%p %s\n",
428 base, (char *)base + size - 1, VIRTUAL_GetProtStr( vprot ) );
430 if (mprotect( base, size, VIRTUAL_GetUnixProt(vprot) ))
431 return FALSE; /* FIXME: last error */
433 memset( view->prot + (((char *)base - (char *)view->base) >> page_shift),
434 vprot, size >> page_shift );
435 VIRTUAL_DEBUG_DUMP_VIEW( view );
436 return TRUE;
440 /***********************************************************************
441 * anon_mmap_aligned
443 * Create an anonymous mapping aligned to the allocation granularity.
445 static void *anon_mmap_aligned( void *base, unsigned int size, int prot, int flags )
447 void *ptr;
448 unsigned int view_size = size + (base ? 0 : granularity_mask + 1);
450 if ((ptr = wine_anon_mmap( base, view_size, prot, flags )) == (void *)-1)
452 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
453 * Platform Differences":
454 * Windows NT: ERROR_INVALID_PARAMETER
455 * Windows 95: ERROR_INVALID_ADDRESS.
457 if (errno == ENOMEM) SetLastError( ERROR_OUTOFMEMORY );
458 else
460 if (GetVersion() & 0x80000000) /* win95 */
461 SetLastError( ERROR_INVALID_ADDRESS );
462 else
463 SetLastError( ERROR_INVALID_PARAMETER );
465 return ptr;
468 if (!base)
470 /* Release the extra memory while keeping the range
471 * starting on the granularity boundary. */
472 if ((unsigned int)ptr & granularity_mask)
474 unsigned int extra = granularity_mask + 1 - ((unsigned int)ptr & granularity_mask);
475 munmap( ptr, extra );
476 ptr = (char *)ptr + extra;
477 view_size -= extra;
479 if (view_size > size)
480 munmap( (char *)ptr + size, view_size - size );
482 else if (ptr != base)
484 /* We couldn't get the address we wanted */
485 munmap( ptr, view_size );
486 SetLastError( ERROR_INVALID_ADDRESS );
487 ptr = (void *)-1;
489 return ptr;
493 /***********************************************************************
494 * map_image
496 * Map an executable (PE format) image into memory.
498 static LPVOID map_image( HANDLE hmapping, int fd, char *base, DWORD total_size,
499 DWORD header_size, HANDLE shared_file, DWORD shared_size,
500 BOOL removable )
502 IMAGE_DOS_HEADER *dos;
503 IMAGE_NT_HEADERS *nt;
504 IMAGE_SECTION_HEADER *sec;
505 IMAGE_DATA_DIRECTORY *imports;
506 int i, pos;
507 DWORD err = GetLastError();
508 FILE_VIEW *view;
509 char *ptr;
510 int shared_fd = -1;
512 SetLastError( ERROR_BAD_EXE_FORMAT ); /* generic error */
514 /* zero-map the whole range */
516 if ((ptr = wine_anon_mmap( base, total_size,
517 PROT_READ | PROT_WRITE | PROT_EXEC, 0 )) == (char *)-1)
519 ptr = wine_anon_mmap( NULL, total_size,
520 PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
521 if (ptr == (char *)-1)
523 ERR_(module)("Not enough memory for module (%ld bytes)\n", total_size);
524 goto error;
527 TRACE_(module)( "mapped PE file at %p-%p\n", ptr, ptr + total_size );
529 /* map the header */
531 if (VIRTUAL_mmap( fd, ptr, header_size, 0, 0, PROT_READ,
532 MAP_PRIVATE | MAP_FIXED, &removable ) == (char *)-1) goto error;
533 dos = (IMAGE_DOS_HEADER *)ptr;
534 nt = (IMAGE_NT_HEADERS *)(ptr + dos->e_lfanew);
535 if ((char *)(nt + 1) > ptr + header_size) goto error;
537 sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader+nt->FileHeader.SizeOfOptionalHeader);
538 if ((char *)(sec + nt->FileHeader.NumberOfSections) > ptr + header_size) goto error;
540 imports = nt->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_IMPORT;
541 if (!imports->Size || !imports->VirtualAddress) imports = NULL;
543 /* check the architecture */
545 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
547 MESSAGE("Trying to load PE image for unsupported architecture (");
548 switch (nt->FileHeader.Machine)
550 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
551 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
552 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
553 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
554 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
555 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
556 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
557 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
559 MESSAGE(")\n");
560 goto error;
563 /* retrieve the shared sections file */
565 if (shared_size)
567 if ((shared_fd = FILE_GetUnixHandle( shared_file, GENERIC_READ )) == -1) goto error;
568 CloseHandle( shared_file ); /* we no longer need it */
569 shared_file = 0;
572 /* map all the sections */
574 for (i = pos = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
576 DWORD size;
578 /* a few sanity checks */
579 size = sec->VirtualAddress + ROUND_SIZE( sec->VirtualAddress, sec->Misc.VirtualSize );
580 if (sec->VirtualAddress > total_size || size > total_size || size < sec->VirtualAddress)
582 ERR_(module)( "Section %.8s too large (%lx+%lx/%lx)\n",
583 sec->Name, sec->VirtualAddress, sec->Misc.VirtualSize, total_size );
584 goto error;
587 if ((sec->Characteristics & IMAGE_SCN_MEM_SHARED) &&
588 (sec->Characteristics & IMAGE_SCN_MEM_WRITE))
590 size = ROUND_SIZE( 0, sec->Misc.VirtualSize );
591 TRACE_(module)( "mapping shared section %.8s at %p off %lx (%x) size %lx (%lx) flags %lx\n",
592 sec->Name, ptr + sec->VirtualAddress,
593 sec->PointerToRawData, pos, sec->SizeOfRawData,
594 size, sec->Characteristics );
595 if (VIRTUAL_mmap( shared_fd, ptr + sec->VirtualAddress, size,
596 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
597 MAP_SHARED|MAP_FIXED, NULL ) == (void *)-1)
599 ERR_(module)( "Could not map shared section %.8s\n", sec->Name );
600 goto error;
603 /* check if the import directory falls inside this section */
604 if (imports && imports->VirtualAddress >= sec->VirtualAddress &&
605 imports->VirtualAddress < sec->VirtualAddress + size)
607 DWORD base = imports->VirtualAddress & ~page_mask;
608 DWORD end = imports->VirtualAddress + ROUND_SIZE( imports->VirtualAddress,
609 imports->Size );
610 if (end > sec->VirtualAddress + size) end = sec->VirtualAddress + size;
611 if (end > base) VIRTUAL_mmap( shared_fd, ptr + base, end - base,
612 pos, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
613 MAP_PRIVATE|MAP_FIXED, NULL );
615 pos += size;
616 continue;
619 if (sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
620 if (!sec->PointerToRawData || !sec->SizeOfRawData) continue;
622 TRACE_(module)( "mapping section %.8s at %p off %lx size %lx flags %lx\n",
623 sec->Name, ptr + sec->VirtualAddress,
624 sec->PointerToRawData, sec->SizeOfRawData,
625 sec->Characteristics );
627 /* Note: if the section is not aligned properly VIRTUAL_mmap will magically
628 * fall back to read(), so we don't need to check anything here.
630 if (VIRTUAL_mmap( fd, ptr + sec->VirtualAddress, sec->SizeOfRawData,
631 sec->PointerToRawData, 0, PROT_READ|PROT_WRITE|PROT_EXEC,
632 MAP_PRIVATE | MAP_FIXED, &removable ) == (void *)-1)
634 ERR_(module)( "Could not map section %.8s, file probably truncated\n", sec->Name );
635 goto error;
638 if ((sec->SizeOfRawData < sec->Misc.VirtualSize) && (sec->SizeOfRawData & page_mask))
640 DWORD end = ROUND_SIZE( 0, sec->SizeOfRawData );
641 if (end > sec->Misc.VirtualSize) end = sec->Misc.VirtualSize;
642 TRACE_(module)("clearing %p - %p\n",
643 ptr + sec->VirtualAddress + sec->SizeOfRawData,
644 ptr + sec->VirtualAddress + end );
645 memset( ptr + sec->VirtualAddress + sec->SizeOfRawData, 0,
646 end - sec->SizeOfRawData );
650 if (removable) hmapping = 0; /* don't keep handle open on removable media */
651 if (!(view = VIRTUAL_CreateView( ptr, total_size, 0,
652 VPROT_COMMITTED|VPROT_READ|VPROT_WRITE|VPROT_WRITECOPY,
653 hmapping )))
655 SetLastError( ERROR_OUTOFMEMORY );
656 goto error;
659 SetLastError( err ); /* restore last error */
660 close( fd );
661 if (shared_fd != -1) close( shared_fd );
662 return ptr;
664 error:
665 if (ptr != (char *)-1) munmap( ptr, total_size );
666 close( fd );
667 if (shared_fd != -1) close( shared_fd );
668 if (shared_file) CloseHandle( shared_file );
669 return NULL;
673 /***********************************************************************
674 * VIRTUAL_Init
676 #ifndef page_mask
677 DECL_GLOBAL_CONSTRUCTOR(VIRTUAL_Init)
679 page_size = getpagesize();
680 page_mask = page_size - 1;
681 /* Make sure we have a power of 2 */
682 assert( !(page_size & page_mask) );
683 page_shift = 0;
684 while ((1 << page_shift) != page_size) page_shift++;
686 #endif /* page_mask */
689 /***********************************************************************
690 * VIRTUAL_SetFaultHandler
692 BOOL VIRTUAL_SetFaultHandler( LPCVOID addr, HANDLERPROC proc, LPVOID arg )
694 FILE_VIEW *view;
696 if (!(view = VIRTUAL_FindView( addr ))) return FALSE;
697 view->handlerProc = proc;
698 view->handlerArg = arg;
699 return TRUE;
702 /***********************************************************************
703 * VIRTUAL_HandleFault
705 DWORD VIRTUAL_HandleFault( LPCVOID addr )
707 FILE_VIEW *view = VIRTUAL_FindView( addr );
708 DWORD ret = EXCEPTION_ACCESS_VIOLATION;
710 if (view)
712 if (view->handlerProc)
714 if (view->handlerProc(view->handlerArg, addr)) ret = 0; /* handled */
716 else
718 BYTE vprot = view->prot[((char *)addr - (char *)view->base) >> page_shift];
719 void *page = (void *)((UINT_PTR)addr & ~page_mask);
720 char *stack = (char *)NtCurrentTeb()->stack_base + SIGNAL_STACK_SIZE + page_mask + 1;
721 if (vprot & VPROT_GUARD)
723 VIRTUAL_SetProt( view, page, page_mask + 1, vprot & ~VPROT_GUARD );
724 ret = STATUS_GUARD_PAGE_VIOLATION;
726 /* is it inside the stack guard pages? */
727 if (((char *)addr >= stack) && ((char *)addr < stack + 2*(page_mask+1)))
728 ret = STATUS_STACK_OVERFLOW;
731 return ret;
736 /***********************************************************************
737 * unaligned_mmap
739 * Linux kernels before 2.4.x can support non page-aligned offsets, as
740 * long as the offset is aligned to the filesystem block size. This is
741 * a big performance gain so we want to take advantage of it.
743 * However, when we use 64-bit file support this doesn't work because
744 * glibc rejects unaligned offsets. Also glibc 2.1.3 mmap64 is broken
745 * in that it rounds unaligned offsets down to a page boundary. For
746 * these reasons we do a direct system call here.
748 static void *unaligned_mmap( void *addr, size_t length, unsigned int prot,
749 unsigned int flags, int fd, unsigned int offset_low,
750 unsigned int offset_high )
752 #if defined(linux) && defined(__i386__) && defined(__GNUC__)
753 if (!offset_high && (offset_low & page_mask))
755 int ret;
756 __asm__ __volatile__("push %%ebx\n\t"
757 "movl %2,%%ebx\n\t"
758 "int $0x80\n\t"
759 "popl %%ebx"
760 : "=a" (ret)
761 : "0" (90), /* SYS_mmap */
762 "g" (&addr) );
763 if (ret < 0 && ret > -4096)
765 errno = -ret;
766 ret = -1;
768 return (void *)ret;
770 #endif
771 return mmap( addr, length, prot, flags, fd, ((off_t)offset_high << 32) | offset_low );
775 /***********************************************************************
776 * VIRTUAL_mmap
778 * Wrapper for mmap() that handles anonymous mappings portably,
779 * and falls back to read if mmap of a file fails.
781 static LPVOID VIRTUAL_mmap( int fd, LPVOID start, DWORD size,
782 DWORD offset_low, DWORD offset_high,
783 int prot, int flags, BOOL *removable )
785 int pos;
786 LPVOID ret;
787 off_t offset;
788 BOOL is_shared_write = FALSE;
790 if (fd == -1) return wine_anon_mmap( start, size, prot, flags );
792 if (prot & PROT_WRITE)
794 #ifdef MAP_SHARED
795 if (flags & MAP_SHARED) is_shared_write = TRUE;
796 #endif
797 #ifdef MAP_PRIVATE
798 if (!(flags & MAP_PRIVATE)) is_shared_write = TRUE;
799 #endif
802 if (removable && *removable)
804 /* if on removable media, try using read instead of mmap */
805 if (!is_shared_write) goto fake_mmap;
806 *removable = FALSE;
809 if ((ret = unaligned_mmap( start, size, prot, flags, fd,
810 offset_low, offset_high )) != (LPVOID)-1) return ret;
812 /* mmap() failed; if this is because the file offset is not */
813 /* page-aligned (EINVAL), or because the underlying filesystem */
814 /* does not support mmap() (ENOEXEC,ENODEV), we do it by hand. */
816 if ((errno != ENOEXEC) && (errno != EINVAL) && (errno != ENODEV)) return ret;
817 if (is_shared_write) return ret; /* we cannot fake shared write mappings */
819 fake_mmap:
820 /* Reserve the memory with an anonymous mmap */
821 ret = wine_anon_mmap( start, size, PROT_READ | PROT_WRITE, flags );
822 if (ret == (LPVOID)-1) return ret;
823 /* Now read in the file */
824 offset = ((off_t)offset_high << 32) | offset_low;
825 if ((pos = lseek( fd, offset, SEEK_SET )) == -1)
827 munmap( ret, size );
828 return (LPVOID)-1;
830 read( fd, ret, size );
831 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
832 mprotect( ret, size, prot ); /* Set the right protection */
833 return ret;
837 /***********************************************************************
838 * VirtualAlloc (KERNEL32.@)
839 * Reserves or commits a region of pages in virtual address space
841 * RETURNS
842 * Base address of allocated region of pages
843 * NULL: Failure
845 LPVOID WINAPI VirtualAlloc(
846 LPVOID addr, /* [in] Address of region to reserve or commit */
847 DWORD size, /* [in] Size of region */
848 DWORD type, /* [in] Type of allocation */
849 DWORD protect)/* [in] Type of access protection */
851 FILE_VIEW *view;
852 char *ptr, *base;
853 BYTE vprot;
855 TRACE("%p %08lx %lx %08lx\n", addr, size, type, protect );
857 /* Round parameters to a page boundary */
859 if (size > 0x7fc00000) /* 2Gb - 4Mb */
861 SetLastError( ERROR_OUTOFMEMORY );
862 return NULL;
864 if (addr)
866 if (type & MEM_RESERVE) /* Round down to 64k boundary */
867 base = ROUND_ADDR( addr, granularity_mask );
868 else
869 base = ROUND_ADDR( addr, page_mask );
870 size = (((UINT_PTR)addr + size + page_mask) & ~page_mask) - (UINT_PTR)base;
871 if ((base <= (char *)granularity_mask) || (base + size < base))
873 /* disallow low 64k and wrap-around */
874 SetLastError( ERROR_INVALID_PARAMETER );
875 return NULL;
878 else
880 base = 0;
881 size = (size + page_mask) & ~page_mask;
884 if (type & MEM_TOP_DOWN) {
885 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
886 * Is there _ANY_ way to do it with UNIX mmap()?
888 WARN("MEM_TOP_DOWN ignored\n");
889 type &= ~MEM_TOP_DOWN;
891 /* Compute the alloc type flags */
893 if (!(type & (MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)) ||
894 (type & ~(MEM_COMMIT | MEM_RESERVE | MEM_SYSTEM)))
896 ERR("called with wrong alloc type flags (%08lx) !\n", type);
897 SetLastError( ERROR_INVALID_PARAMETER );
898 return NULL;
900 if (type & (MEM_COMMIT | MEM_SYSTEM))
901 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
902 else vprot = 0;
904 /* Reserve the memory */
906 if ((type & MEM_RESERVE) || !base)
908 if (type & MEM_SYSTEM)
910 if (!(view = VIRTUAL_CreateView( base, size, VFLAG_VALLOC | VFLAG_SYSTEM, vprot, 0 )))
912 SetLastError( ERROR_OUTOFMEMORY );
913 return NULL;
915 return (LPVOID)base;
917 ptr = anon_mmap_aligned( base, size, VIRTUAL_GetUnixProt( vprot ), 0 );
918 if (ptr == (void *)-1) return NULL;
920 if (!(view = VIRTUAL_CreateView( ptr, size, VFLAG_VALLOC, vprot, 0 )))
922 munmap( ptr, size );
923 SetLastError( ERROR_OUTOFMEMORY );
924 return NULL;
926 return ptr;
929 /* Commit the pages */
931 if (!(view = VIRTUAL_FindView( base )) ||
932 (base + size > (char *)view->base + view->size))
934 SetLastError( ERROR_INVALID_ADDRESS );
935 return NULL;
938 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
939 return (LPVOID)base;
943 /***********************************************************************
944 * VirtualAllocEx (KERNEL32.@)
946 * Seems to be just as VirtualAlloc, but with process handle.
948 LPVOID WINAPI VirtualAllocEx(
949 HANDLE hProcess, /* [in] Handle of process to do mem operation */
950 LPVOID addr, /* [in] Address of region to reserve or commit */
951 DWORD size, /* [in] Size of region */
952 DWORD type, /* [in] Type of allocation */
953 DWORD protect /* [in] Type of access protection */
955 if (MapProcessHandle( hProcess ) == GetCurrentProcessId())
956 return VirtualAlloc( addr, size, type, protect );
957 ERR("Unsupported on other process\n");
958 return NULL;
962 /***********************************************************************
963 * VirtualFree (KERNEL32.@)
964 * Release or decommits a region of pages in virtual address space.
966 * RETURNS
967 * TRUE: Success
968 * FALSE: Failure
970 BOOL WINAPI VirtualFree(
971 LPVOID addr, /* [in] Address of region of committed pages */
972 DWORD size, /* [in] Size of region */
973 DWORD type /* [in] Type of operation */
975 FILE_VIEW *view;
976 char *base;
978 TRACE("%p %08lx %lx\n", addr, size, type );
980 /* Fix the parameters */
982 size = ROUND_SIZE( addr, size );
983 base = ROUND_ADDR( addr, page_mask );
985 if (!(view = VIRTUAL_FindView( base )) ||
986 (base + size > (char *)view->base + view->size) ||
987 !(view->flags & VFLAG_VALLOC))
989 SetLastError( ERROR_INVALID_PARAMETER );
990 return FALSE;
993 /* Check the type */
995 if (type & MEM_SYSTEM)
997 view->flags |= VFLAG_SYSTEM;
998 type &= ~MEM_SYSTEM;
1001 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
1003 ERR("called with wrong free type flags (%08lx) !\n", type);
1004 SetLastError( ERROR_INVALID_PARAMETER );
1005 return FALSE;
1008 /* Free the pages */
1010 if (type == MEM_RELEASE)
1012 if (size || (base != view->base))
1014 SetLastError( ERROR_INVALID_PARAMETER );
1015 return FALSE;
1017 VIRTUAL_DeleteView( view );
1018 return TRUE;
1021 /* Decommit the pages by remapping zero-pages instead */
1023 if (wine_anon_mmap( (LPVOID)base, size, VIRTUAL_GetUnixProt(0), MAP_FIXED ) != (LPVOID)base)
1024 ERR( "Could not remap pages, expect trouble\n" );
1025 return VIRTUAL_SetProt( view, base, size, 0 );
1029 /***********************************************************************
1030 * VirtualLock (KERNEL32.@)
1031 * Locks the specified region of virtual address space
1033 * NOTE
1034 * Always returns TRUE
1036 * RETURNS
1037 * TRUE: Success
1038 * FALSE: Failure
1040 BOOL WINAPI VirtualLock(
1041 LPVOID addr, /* [in] Address of first byte of range to lock */
1042 DWORD size /* [in] Number of bytes in range to lock */
1044 return TRUE;
1048 /***********************************************************************
1049 * VirtualUnlock (KERNEL32.@)
1050 * Unlocks a range of pages in the virtual address space
1052 * NOTE
1053 * Always returns TRUE
1055 * RETURNS
1056 * TRUE: Success
1057 * FALSE: Failure
1059 BOOL WINAPI VirtualUnlock(
1060 LPVOID addr, /* [in] Address of first byte of range */
1061 DWORD size /* [in] Number of bytes in range */
1063 return TRUE;
1067 /***********************************************************************
1068 * VirtualProtect (KERNEL32.@)
1069 * Changes the access protection on a region of committed pages
1071 * RETURNS
1072 * TRUE: Success
1073 * FALSE: Failure
1075 BOOL WINAPI VirtualProtect(
1076 LPVOID addr, /* [in] Address of region of committed pages */
1077 DWORD size, /* [in] Size of region */
1078 DWORD new_prot, /* [in] Desired access protection */
1079 LPDWORD old_prot /* [out] Address of variable to get old protection */
1081 FILE_VIEW *view;
1082 char *base;
1083 UINT i;
1084 BYTE vprot, *p;
1085 DWORD prot;
1087 TRACE("%p %08lx %08lx\n", addr, size, new_prot );
1089 /* Fix the parameters */
1091 size = ROUND_SIZE( addr, size );
1092 base = ROUND_ADDR( addr, page_mask );
1094 if (!(view = VIRTUAL_FindView( base )) ||
1095 (base + size > (char *)view->base + view->size))
1097 SetLastError( ERROR_INVALID_PARAMETER );
1098 return FALSE;
1101 /* Make sure all the pages are committed */
1103 p = view->prot + ((base - (char *)view->base) >> page_shift);
1104 VIRTUAL_GetWin32Prot( *p, &prot, NULL );
1105 for (i = size >> page_shift; i; i--, p++)
1107 if (!(*p & VPROT_COMMITTED))
1109 SetLastError( ERROR_INVALID_PARAMETER );
1110 return FALSE;
1114 if (old_prot) *old_prot = prot;
1115 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
1116 return VIRTUAL_SetProt( view, base, size, vprot );
1120 /***********************************************************************
1121 * VirtualProtectEx (KERNEL32.@)
1122 * Changes the access protection on a region of committed pages in the
1123 * virtual address space of a specified process
1125 * RETURNS
1126 * TRUE: Success
1127 * FALSE: Failure
1129 BOOL WINAPI VirtualProtectEx(
1130 HANDLE handle, /* [in] Handle of process */
1131 LPVOID addr, /* [in] Address of region of committed pages */
1132 DWORD size, /* [in] Size of region */
1133 DWORD new_prot, /* [in] Desired access protection */
1134 LPDWORD old_prot /* [out] Address of variable to get old protection */ )
1136 if (MapProcessHandle( handle ) == GetCurrentProcessId())
1137 return VirtualProtect( addr, size, new_prot, old_prot );
1138 ERR("Unsupported on other process\n");
1139 return FALSE;
1143 /***********************************************************************
1144 * VirtualQuery (KERNEL32.@)
1145 * Provides info about a range of pages in virtual address space
1147 * RETURNS
1148 * Number of bytes returned in information buffer
1149 * or 0 if addr is >= 0xc0000000 (kernel space).
1151 DWORD WINAPI VirtualQuery(
1152 LPCVOID addr, /* [in] Address of region */
1153 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1154 DWORD len /* [in] Size of buffer */
1156 FILE_VIEW *view;
1157 char *base, *alloc_base = 0;
1158 UINT size = 0;
1160 if (addr >= (void*)0xc0000000) return 0;
1162 base = ROUND_ADDR( addr, page_mask );
1164 /* Find the view containing the address */
1166 EnterCriticalSection(&csVirtual);
1167 view = VIRTUAL_FirstView;
1168 for (;;)
1170 if (!view)
1172 size = (char *)0xffff0000 - alloc_base;
1173 break;
1175 if ((char *)view->base > base)
1177 size = (char *)view->base - alloc_base;
1178 view = NULL;
1179 break;
1181 if ((char *)view->base + view->size > base)
1183 alloc_base = view->base;
1184 size = view->size;
1185 break;
1187 alloc_base = (char *)view->base + view->size;
1188 view = view->next;
1190 LeaveCriticalSection(&csVirtual);
1192 /* Fill the info structure */
1194 if (!view)
1196 info->State = MEM_FREE;
1197 info->Protect = 0;
1198 info->AllocationProtect = 0;
1199 info->Type = 0;
1201 else
1203 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
1204 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
1205 for (size = base - alloc_base; size < view->size; size += page_mask+1)
1206 if (view->prot[size >> page_shift] != vprot) break;
1207 info->AllocationProtect = view->protect;
1208 info->Type = MEM_PRIVATE; /* FIXME */
1211 info->BaseAddress = (LPVOID)base;
1212 info->AllocationBase = (LPVOID)alloc_base;
1213 info->RegionSize = size - (base - alloc_base);
1214 return sizeof(*info);
1218 /***********************************************************************
1219 * VirtualQueryEx (KERNEL32.@)
1220 * Provides info about a range of pages in virtual address space of a
1221 * specified process
1223 * RETURNS
1224 * Number of bytes returned in information buffer
1226 DWORD WINAPI VirtualQueryEx(
1227 HANDLE handle, /* [in] Handle of process */
1228 LPCVOID addr, /* [in] Address of region */
1229 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
1230 DWORD len /* [in] Size of buffer */ )
1232 if (MapProcessHandle( handle ) == GetCurrentProcessId())
1233 return VirtualQuery( addr, info, len );
1234 ERR("Unsupported on other process\n");
1235 return 0;
1239 /***********************************************************************
1240 * IsBadReadPtr (KERNEL32.@)
1242 * RETURNS
1243 * FALSE: Process has read access to entire block
1244 * TRUE: Otherwise
1246 BOOL WINAPI IsBadReadPtr(
1247 LPCVOID ptr, /* [in] Address of memory block */
1248 UINT size ) /* [in] Size of block */
1250 if (!size) return FALSE; /* handle 0 size case w/o reference */
1251 __TRY
1253 volatile const char *p = ptr;
1254 char dummy;
1255 UINT count = size;
1257 while (count > page_size)
1259 dummy = *p;
1260 p += page_size;
1261 count -= page_size;
1263 dummy = p[0];
1264 dummy = p[count - 1];
1266 __EXCEPT(page_fault) { return TRUE; }
1267 __ENDTRY
1268 return FALSE;
1272 /***********************************************************************
1273 * IsBadWritePtr (KERNEL32.@)
1275 * RETURNS
1276 * FALSE: Process has write access to entire block
1277 * TRUE: Otherwise
1279 BOOL WINAPI IsBadWritePtr(
1280 LPVOID ptr, /* [in] Address of memory block */
1281 UINT size ) /* [in] Size of block in bytes */
1283 if (!size) return FALSE; /* handle 0 size case w/o reference */
1284 __TRY
1286 volatile char *p = ptr;
1287 UINT count = size;
1289 while (count > page_size)
1291 *p |= 0;
1292 p += page_size;
1293 count -= page_size;
1295 p[0] |= 0;
1296 p[count - 1] |= 0;
1298 __EXCEPT(page_fault) { return TRUE; }
1299 __ENDTRY
1300 return FALSE;
1304 /***********************************************************************
1305 * IsBadHugeReadPtr (KERNEL32.@)
1306 * RETURNS
1307 * FALSE: Process has read access to entire block
1308 * TRUE: Otherwise
1310 BOOL WINAPI IsBadHugeReadPtr(
1311 LPCVOID ptr, /* [in] Address of memory block */
1312 UINT size /* [in] Size of block */
1314 return IsBadReadPtr( ptr, size );
1318 /***********************************************************************
1319 * IsBadHugeWritePtr (KERNEL32.@)
1320 * RETURNS
1321 * FALSE: Process has write access to entire block
1322 * TRUE: Otherwise
1324 BOOL WINAPI IsBadHugeWritePtr(
1325 LPVOID ptr, /* [in] Address of memory block */
1326 UINT size /* [in] Size of block */
1328 return IsBadWritePtr( ptr, size );
1332 /***********************************************************************
1333 * IsBadCodePtr (KERNEL32.@)
1335 * RETURNS
1336 * FALSE: Process has read access to specified memory
1337 * TRUE: Otherwise
1339 BOOL WINAPI IsBadCodePtr( FARPROC ptr ) /* [in] Address of function */
1341 return IsBadReadPtr( ptr, 1 );
1345 /***********************************************************************
1346 * IsBadStringPtrA (KERNEL32.@)
1348 * RETURNS
1349 * FALSE: Read access to all bytes in string
1350 * TRUE: Else
1352 BOOL WINAPI IsBadStringPtrA(
1353 LPCSTR str, /* [in] Address of string */
1354 UINT max ) /* [in] Maximum size of string */
1356 __TRY
1358 volatile const char *p = str;
1359 while (p != str + max) if (!*p++) break;
1361 __EXCEPT(page_fault) { return TRUE; }
1362 __ENDTRY
1363 return FALSE;
1367 /***********************************************************************
1368 * IsBadStringPtrW (KERNEL32.@)
1369 * See IsBadStringPtrA
1371 BOOL WINAPI IsBadStringPtrW( LPCWSTR str, UINT max )
1373 __TRY
1375 volatile const WCHAR *p = str;
1376 while (p != str + max) if (!*p++) break;
1378 __EXCEPT(page_fault) { return TRUE; }
1379 __ENDTRY
1380 return FALSE;
1384 /***********************************************************************
1385 * CreateFileMappingA (KERNEL32.@)
1386 * Creates a named or unnamed file-mapping object for the specified file
1388 * RETURNS
1389 * Handle: Success
1390 * 0: Mapping object does not exist
1391 * NULL: Failure
1393 HANDLE WINAPI CreateFileMappingA(
1394 HANDLE hFile, /* [in] Handle of file to map */
1395 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1396 DWORD protect, /* [in] Protection for mapping object */
1397 DWORD size_high, /* [in] High-order 32 bits of object size */
1398 DWORD size_low, /* [in] Low-order 32 bits of object size */
1399 LPCSTR name /* [in] Name of file-mapping object */ )
1401 WCHAR buffer[MAX_PATH];
1403 if (!name) return CreateFileMappingW( hFile, sa, protect, size_high, size_low, NULL );
1405 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1407 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1408 return 0;
1410 return CreateFileMappingW( hFile, sa, protect, size_high, size_low, buffer );
1414 /***********************************************************************
1415 * CreateFileMappingW (KERNEL32.@)
1416 * See CreateFileMappingA
1418 HANDLE WINAPI CreateFileMappingW( HANDLE hFile, LPSECURITY_ATTRIBUTES sa,
1419 DWORD protect, DWORD size_high,
1420 DWORD size_low, LPCWSTR name )
1422 HANDLE ret;
1423 BYTE vprot;
1424 DWORD len = name ? strlenW(name) : 0;
1426 /* Check parameters */
1428 TRACE("(%x,%p,%08lx,%08lx%08lx,%s)\n",
1429 hFile, sa, protect, size_high, size_low, debugstr_w(name) );
1431 if (len > MAX_PATH)
1433 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1434 return 0;
1437 vprot = VIRTUAL_GetProt( protect );
1438 if (protect & SEC_RESERVE)
1440 if (hFile != INVALID_HANDLE_VALUE)
1442 SetLastError( ERROR_INVALID_PARAMETER );
1443 return 0;
1446 else vprot |= VPROT_COMMITTED;
1447 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1448 if (protect & SEC_IMAGE) vprot |= VPROT_IMAGE;
1450 /* Create the server object */
1452 if (hFile == INVALID_HANDLE_VALUE) hFile = 0;
1453 SERVER_START_REQ( create_mapping )
1455 req->file_handle = hFile;
1456 req->size_high = size_high;
1457 req->size_low = size_low;
1458 req->protect = vprot;
1459 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1460 wine_server_add_data( req, name, len * sizeof(WCHAR) );
1461 SetLastError(0);
1462 wine_server_call_err( req );
1463 ret = reply->handle;
1465 SERVER_END_REQ;
1466 return ret;
1470 /***********************************************************************
1471 * OpenFileMappingA (KERNEL32.@)
1472 * Opens a named file-mapping object.
1474 * RETURNS
1475 * Handle: Success
1476 * NULL: Failure
1478 HANDLE WINAPI OpenFileMappingA(
1479 DWORD access, /* [in] Access mode */
1480 BOOL inherit, /* [in] Inherit flag */
1481 LPCSTR name ) /* [in] Name of file-mapping object */
1483 WCHAR buffer[MAX_PATH];
1485 if (!name) return OpenFileMappingW( access, inherit, NULL );
1487 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1489 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1490 return 0;
1492 return OpenFileMappingW( access, inherit, buffer );
1496 /***********************************************************************
1497 * OpenFileMappingW (KERNEL32.@)
1498 * See OpenFileMappingA
1500 HANDLE WINAPI OpenFileMappingW( DWORD access, BOOL inherit, LPCWSTR name)
1502 HANDLE ret;
1503 DWORD len = name ? strlenW(name) : 0;
1504 if (len >= MAX_PATH)
1506 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1507 return 0;
1509 SERVER_START_REQ( open_mapping )
1511 req->access = access;
1512 req->inherit = inherit;
1513 wine_server_add_data( req, name, len * sizeof(WCHAR) );
1514 wine_server_call_err( req );
1515 ret = reply->handle;
1517 SERVER_END_REQ;
1518 return ret;
1522 /***********************************************************************
1523 * MapViewOfFile (KERNEL32.@)
1524 * Maps a view of a file into the address space
1526 * RETURNS
1527 * Starting address of mapped view
1528 * NULL: Failure
1530 LPVOID WINAPI MapViewOfFile(
1531 HANDLE mapping, /* [in] File-mapping object to map */
1532 DWORD access, /* [in] Access mode */
1533 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1534 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1535 DWORD count /* [in] Number of bytes to map */
1537 return MapViewOfFileEx( mapping, access, offset_high,
1538 offset_low, count, NULL );
1542 /***********************************************************************
1543 * MapViewOfFileEx (KERNEL32.@)
1544 * Maps a view of a file into the address space
1546 * RETURNS
1547 * Starting address of mapped view
1548 * NULL: Failure
1550 LPVOID WINAPI MapViewOfFileEx(
1551 HANDLE handle, /* [in] File-mapping object to map */
1552 DWORD access, /* [in] Access mode */
1553 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1554 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1555 DWORD count, /* [in] Number of bytes to map */
1556 LPVOID addr /* [in] Suggested starting address for mapped view */
1558 FILE_VIEW *view;
1559 UINT size = 0;
1560 int flags = MAP_PRIVATE;
1561 int unix_handle = -1;
1562 int prot, res;
1563 void *base, *ptr = (void *)-1, *ret;
1564 DWORD size_low, size_high, header_size, shared_size;
1565 HANDLE shared_file;
1566 BOOL removable;
1568 /* Check parameters */
1570 if ((offset_low & granularity_mask) ||
1571 (addr && ((UINT_PTR)addr & granularity_mask)))
1573 SetLastError( ERROR_INVALID_PARAMETER );
1574 return NULL;
1577 SERVER_START_REQ( get_mapping_info )
1579 req->handle = handle;
1580 res = wine_server_call_err( req );
1581 prot = reply->protect;
1582 base = reply->base;
1583 size_low = reply->size_low;
1584 size_high = reply->size_high;
1585 header_size = reply->header_size;
1586 shared_file = reply->shared_file;
1587 shared_size = reply->shared_size;
1588 removable = (reply->drive_type == DRIVE_REMOVABLE ||
1589 reply->drive_type == DRIVE_CDROM);
1591 SERVER_END_REQ;
1592 if (res) goto error;
1594 if ((unix_handle = FILE_GetUnixHandle( handle, 0 )) == -1) goto error;
1596 if (prot & VPROT_IMAGE)
1597 return map_image( handle, unix_handle, base, size_low, header_size,
1598 shared_file, shared_size, removable );
1601 if (size_high)
1602 ERR("Sizes larger than 4Gb not supported\n");
1604 if ((offset_low >= size_low) ||
1605 (count > size_low - offset_low))
1607 SetLastError( ERROR_INVALID_PARAMETER );
1608 goto error;
1610 if (count) size = ROUND_SIZE( offset_low, count );
1611 else size = size_low - offset_low;
1613 switch(access)
1615 case FILE_MAP_ALL_ACCESS:
1616 case FILE_MAP_WRITE:
1617 case FILE_MAP_WRITE | FILE_MAP_READ:
1618 if (!(prot & VPROT_WRITE))
1620 SetLastError( ERROR_INVALID_PARAMETER );
1621 goto error;
1623 flags = MAP_SHARED;
1624 /* fall through */
1625 case FILE_MAP_READ:
1626 case FILE_MAP_COPY:
1627 case FILE_MAP_COPY | FILE_MAP_READ:
1628 if (prot & VPROT_READ) break;
1629 /* fall through */
1630 default:
1631 SetLastError( ERROR_INVALID_PARAMETER );
1632 goto error;
1635 /* FIXME: If a mapping is created with SEC_RESERVE and a process,
1636 * which has a view of this mapping commits some pages, they will
1637 * appear commited in all other processes, which have the same
1638 * view created. Since we don`t support this yet, we create the
1639 * whole mapping commited.
1641 prot |= VPROT_COMMITTED;
1643 /* Reserve a properly aligned area */
1645 if ((ptr = anon_mmap_aligned( addr, size, PROT_NONE, 0 )) == (void *)-1) goto error;
1647 /* Map the file */
1649 TRACE("handle=%x size=%x offset=%lx\n", handle, size, offset_low );
1651 ret = VIRTUAL_mmap( unix_handle, ptr, size, offset_low, offset_high,
1652 VIRTUAL_GetUnixProt( prot ), flags | MAP_FIXED, &removable );
1653 if (ret != ptr)
1655 ERR( "VIRTUAL_mmap %p %x %lx%08lx failed\n", ptr, size, offset_high, offset_low );
1656 goto error;
1658 if (removable) handle = 0; /* don't keep handle open on removable media */
1660 if (!(view = VIRTUAL_CreateView( ptr, size, 0, prot, handle )))
1662 SetLastError( ERROR_OUTOFMEMORY );
1663 goto error;
1665 if (unix_handle != -1) close( unix_handle );
1666 return ptr;
1668 error:
1669 if (unix_handle != -1) close( unix_handle );
1670 if (ptr != (void *)-1) munmap( ptr, size );
1671 return NULL;
1675 /***********************************************************************
1676 * FlushViewOfFile (KERNEL32.@)
1677 * Writes to the disk a byte range within a mapped view of a file
1679 * RETURNS
1680 * TRUE: Success
1681 * FALSE: Failure
1683 BOOL WINAPI FlushViewOfFile(
1684 LPCVOID base, /* [in] Start address of byte range to flush */
1685 DWORD cbFlush /* [in] Number of bytes in range */
1687 FILE_VIEW *view;
1688 void *addr = ROUND_ADDR( base, page_mask );
1690 TRACE("FlushViewOfFile at %p for %ld bytes\n",
1691 base, cbFlush );
1693 if (!(view = VIRTUAL_FindView( addr )))
1695 SetLastError( ERROR_INVALID_PARAMETER );
1696 return FALSE;
1698 if (!cbFlush) cbFlush = view->size;
1699 if (!msync( addr, cbFlush, MS_SYNC )) return TRUE;
1700 SetLastError( ERROR_INVALID_PARAMETER );
1701 return FALSE;
1705 /***********************************************************************
1706 * UnmapViewOfFile (KERNEL32.@)
1707 * Unmaps a mapped view of a file.
1709 * NOTES
1710 * Should addr be an LPCVOID?
1712 * RETURNS
1713 * TRUE: Success
1714 * FALSE: Failure
1716 BOOL WINAPI UnmapViewOfFile(
1717 LPVOID addr /* [in] Address where mapped view begins */
1719 FILE_VIEW *view;
1720 void *base = ROUND_ADDR( addr, page_mask );
1721 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1723 SetLastError( ERROR_INVALID_PARAMETER );
1724 return FALSE;
1726 VIRTUAL_DeleteView( view );
1727 return TRUE;