API Documentation for SendMessage, GetTickCount, PostQuitMessage,
[wine/multimedia.git] / memory / virtual.c
blob4414e94a6ae8c6415e460346737721f3699dc58c
1 /*
2 * Win32 virtual memory functions
4 * Copyright 1997 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <errno.h>
9 #include <sys/errno.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/types.h>
15 #include <sys/mman.h>
16 #include "winbase.h"
17 #include "winerror.h"
18 #include "file.h"
19 #include "heap.h"
20 #include "process.h"
21 #include "xmalloc.h"
22 #include "global.h"
23 #include "debug.h"
25 #ifndef MS_SYNC
26 #define MS_SYNC 0
27 #endif
29 /* File mapping */
30 typedef struct
32 K32OBJ header;
33 DWORD size_high;
34 DWORD size_low;
35 FILE_OBJECT *file;
36 BYTE protect;
37 } FILE_MAPPING;
39 /* File view */
40 typedef struct _FV
42 struct _FV *next; /* Next view */
43 struct _FV *prev; /* Prev view */
44 UINT32 base; /* Base address */
45 UINT32 size; /* Size in bytes */
46 UINT32 flags; /* Allocation flags */
47 UINT32 offset; /* Offset from start of mapped file */
48 FILE_MAPPING *mapping; /* File mapping */
49 HANDLERPROC handlerProc; /* Fault handler */
50 LPVOID handlerArg; /* Fault handler argument */
51 BYTE protect; /* Protection for all pages at allocation time */
52 BYTE prot[1]; /* Protection byte for each page */
53 } FILE_VIEW;
55 /* Per-page protection byte values */
56 #define VPROT_READ 0x01
57 #define VPROT_WRITE 0x02
58 #define VPROT_EXEC 0x04
59 #define VPROT_WRITECOPY 0x08
60 #define VPROT_GUARD 0x10
61 #define VPROT_NOCACHE 0x20
62 #define VPROT_COMMITTED 0x40
64 /* Per-view flags */
65 #define VFLAG_SYSTEM 0x01
67 /* Conversion from VPROT_* to Win32 flags */
68 static const BYTE VIRTUAL_Win32Flags[16] =
70 PAGE_NOACCESS, /* 0 */
71 PAGE_READONLY, /* READ */
72 PAGE_READWRITE, /* WRITE */
73 PAGE_READWRITE, /* READ | WRITE */
74 PAGE_EXECUTE, /* EXEC */
75 PAGE_EXECUTE_READ, /* READ | EXEC */
76 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
77 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
78 PAGE_WRITECOPY, /* WRITECOPY */
79 PAGE_WRITECOPY, /* READ | WRITECOPY */
80 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
81 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
82 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
83 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
84 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
85 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
89 static FILE_VIEW *VIRTUAL_FirstView;
91 #ifdef __i386__
92 /* These are always the same on an i386, and it will be faster this way */
93 # define page_mask 0xfff
94 # define page_shift 12
95 # define granularity_mask 0xffff
96 #else
97 static UINT32 page_shift;
98 static UINT32 page_mask;
99 static UINT32 granularity_mask; /* Allocation granularity (usually 64k) */
100 #endif /* __i386__ */
102 #define ROUND_ADDR(addr) \
103 ((UINT32)(addr) & ~page_mask)
105 #define ROUND_SIZE(addr,size) \
106 (((UINT32)(size) + ((UINT32)(addr) & page_mask) + page_mask) & ~page_mask)
108 static void VIRTUAL_DestroyMapping( K32OBJ *obj );
110 const K32OBJ_OPS MEM_MAPPED_FILE_Ops =
112 /* Object cannot be waited upon, so we don't need these (except destroy) */
113 NULL, /* signaled */
114 NULL, /* satisfied */
115 NULL, /* add_wait */
116 NULL, /* remove_wait */
117 NULL, /* read */
118 NULL, /* write */
119 VIRTUAL_DestroyMapping /* destroy */
122 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
123 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
125 /***********************************************************************
126 * VIRTUAL_GetProtStr
128 static const char *VIRTUAL_GetProtStr( BYTE prot )
130 static char buffer[6];
131 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
132 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
133 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
134 buffer[3] = (prot & VPROT_WRITE) ?
135 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
136 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
137 buffer[5] = 0;
138 return buffer;
142 /***********************************************************************
143 * VIRTUAL_DumpView
145 static void VIRTUAL_DumpView( FILE_VIEW *view )
147 UINT32 i, count;
148 UINT32 addr = view->base;
149 BYTE prot = view->prot[0];
151 DUMP( "View: %08x - %08x%s",
152 view->base, view->base + view->size - 1,
153 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
154 if (view->mapping && view->mapping->file)
155 DUMP( " %s @ %08x\n", view->mapping->file->unix_name, view->offset );
156 else
157 DUMP( " (anonymous)\n");
159 for (count = i = 1; i < view->size >> page_shift; i++, count++)
161 if (view->prot[i] == prot) continue;
162 DUMP( " %08x - %08x %s\n",
163 addr, addr + (count << page_shift) - 1,
164 VIRTUAL_GetProtStr(prot) );
165 addr += (count << page_shift);
166 prot = view->prot[i];
167 count = 0;
169 if (count)
170 DUMP( " %08x - %08x %s\n",
171 addr, addr + (count << page_shift) - 1,
172 VIRTUAL_GetProtStr(prot) );
176 /***********************************************************************
177 * VIRTUAL_Dump
179 void VIRTUAL_Dump(void)
181 FILE_VIEW *view = VIRTUAL_FirstView;
182 DUMP( "\nDump of all virtual memory views:\n\n" );
183 while (view)
185 VIRTUAL_DumpView( view );
186 view = view->next;
191 /***********************************************************************
192 * VIRTUAL_FindView
194 * Find the view containing a given address.
196 * RETURNS
197 * View: Success
198 * NULL: Failure
200 static FILE_VIEW *VIRTUAL_FindView(
201 UINT32 addr /* [in] Address */
203 FILE_VIEW *view = VIRTUAL_FirstView;
204 while (view)
206 if (view->base > addr) return NULL;
207 if (view->base + view->size > addr) return view;
208 view = view->next;
210 return NULL;
214 /***********************************************************************
215 * VIRTUAL_CreateView
217 * Create a new view and add it in the linked list.
219 static FILE_VIEW *VIRTUAL_CreateView( UINT32 base, UINT32 size, UINT32 offset,
220 UINT32 flags, BYTE vprot,
221 FILE_MAPPING *mapping )
223 FILE_VIEW *view, *prev;
225 /* Create the view structure */
227 assert( !(base & page_mask) );
228 assert( !(size & page_mask) );
229 size >>= page_shift;
230 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
231 view->base = base;
232 view->size = size << page_shift;
233 view->flags = flags;
234 view->offset = offset;
235 view->mapping = mapping;
236 view->protect = vprot;
237 memset( view->prot, vprot, size );
239 /* Insert it in the linked list */
241 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
243 view->next = VIRTUAL_FirstView;
244 view->prev = NULL;
245 if (view->next) view->next->prev = view;
246 VIRTUAL_FirstView = view;
248 else
250 prev = VIRTUAL_FirstView;
251 while (prev->next && (prev->next->base < base)) prev = prev->next;
252 view->next = prev->next;
253 view->prev = prev;
254 if (view->next) view->next->prev = view;
255 prev->next = view;
257 VIRTUAL_DEBUG_DUMP_VIEW( view );
258 return view;
262 /***********************************************************************
263 * VIRTUAL_DeleteView
264 * Deletes a view.
266 * RETURNS
267 * None
269 static void VIRTUAL_DeleteView(
270 FILE_VIEW *view /* [in] View */
272 FILE_munmap( (void *)view->base, 0, view->size );
273 if (view->next) view->next->prev = view->prev;
274 if (view->prev) view->prev->next = view->next;
275 else VIRTUAL_FirstView = view->next;
276 if (view->mapping) K32OBJ_DecCount( &view->mapping->header );
277 free( view );
281 /***********************************************************************
282 * VIRTUAL_GetUnixProt
284 * Convert page protections to protection for mmap/mprotect.
286 static int VIRTUAL_GetUnixProt( BYTE vprot )
288 int prot = 0;
289 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
291 if (vprot & VPROT_READ) prot |= PROT_READ;
292 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
293 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
295 return prot;
299 /***********************************************************************
300 * VIRTUAL_GetWin32Prot
302 * Convert page protections to Win32 flags.
304 * RETURNS
305 * None
307 static void VIRTUAL_GetWin32Prot(
308 BYTE vprot, /* [in] Page protection flags */
309 DWORD *protect, /* [out] Location to store Win32 protection flags */
310 DWORD *state /* [out] Location to store mem state flag */
312 if (protect) {
313 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
314 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
315 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
317 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
320 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
324 /***********************************************************************
325 * VIRTUAL_GetProt
327 * Build page protections from Win32 flags.
329 * RETURNS
330 * Value of page protection flags
332 static BYTE VIRTUAL_GetProt(
333 DWORD protect /* [in] Win32 protection flags */
335 BYTE vprot;
337 switch(protect & 0xff)
339 case PAGE_READONLY:
340 vprot = VPROT_READ;
341 break;
342 case PAGE_READWRITE:
343 vprot = VPROT_READ | VPROT_WRITE;
344 break;
345 case PAGE_WRITECOPY:
346 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
347 break;
348 case PAGE_EXECUTE:
349 vprot = VPROT_EXEC;
350 break;
351 case PAGE_EXECUTE_READ:
352 vprot = VPROT_EXEC | VPROT_READ;
353 break;
354 case PAGE_EXECUTE_READWRITE:
355 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
356 break;
357 case PAGE_EXECUTE_WRITECOPY:
358 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
359 break;
360 case PAGE_NOACCESS:
361 default:
362 vprot = 0;
363 break;
365 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
366 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
367 return vprot;
371 /***********************************************************************
372 * VIRTUAL_SetProt
374 * Change the protection of a range of pages.
376 * RETURNS
377 * TRUE: Success
378 * FALSE: Failure
380 static BOOL32 VIRTUAL_SetProt(
381 FILE_VIEW *view, /* [in] Pointer to view */
382 UINT32 base, /* [in] Starting address */
383 UINT32 size, /* [in] Size in bytes */
384 BYTE vprot /* [in] Protections to use */
386 TRACE(virtual, "%08x-%08x %s\n",
387 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
389 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
390 return FALSE; /* FIXME: last error */
392 memset( view->prot + ((base - view->base) >> page_shift),
393 vprot, size >> page_shift );
394 VIRTUAL_DEBUG_DUMP_VIEW( view );
395 return TRUE;
399 /***********************************************************************
400 * VIRTUAL_CheckFlags
402 * Check that all pages in a range have the given flags.
404 * RETURNS
405 * TRUE: They do
406 * FALSE: They do not
408 static BOOL32 VIRTUAL_CheckFlags(
409 UINT32 base, /* [in] Starting address */
410 UINT32 size, /* [in] Size in bytes */
411 BYTE flags /* [in] Flags to check for */
413 FILE_VIEW *view;
414 UINT32 page;
416 if (!size) return TRUE;
417 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
418 if (view->base + view->size < base + size) return FALSE;
419 page = (base - view->base) >> page_shift;
420 size = ROUND_SIZE( base, size ) >> page_shift;
421 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
422 return TRUE;
426 /***********************************************************************
427 * VIRTUAL_Init
429 BOOL32 VIRTUAL_Init(void)
431 #ifndef __i386__
432 DWORD page_size;
434 # ifdef HAVE_GETPAGESIZE
435 page_size = getpagesize();
436 # else
437 # ifdef __svr4__
438 page_size = sysconf(_SC_PAGESIZE);
439 # else
440 # error Cannot get the page size on this platform
441 # endif
442 # endif
443 page_mask = page_size - 1;
444 granularity_mask = 0xffff; /* hard-coded for now */
445 /* Make sure we have a power of 2 */
446 assert( !(page_size & page_mask) );
447 page_shift = 0;
448 while ((1 << page_shift) != page_size) page_shift++;
449 #endif /* !__i386__ */
451 #ifdef linux
453 /* Do not use stdio here since it may temporarily change the size
454 * of some segments (ie libc6 adds 0x1000 per open FILE)
456 int fd = open ("/proc/self/maps", O_RDONLY);
457 if (fd >= 0)
459 char buffer[512]; /* line might be rather long in 2.1 */
461 for (;;)
463 int start, end, offset;
464 char r, w, x, p;
465 BYTE vprot = VPROT_COMMITTED;
467 char * ptr = buffer;
468 int count = sizeof(buffer);
469 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
470 ptr++;
472 if (*ptr != '\n') break;
473 *ptr = '\0';
475 sscanf( buffer, "%x-%x %c%c%c%c %x",
476 &start, &end, &r, &w, &x, &p, &offset );
477 if (r == 'r') vprot |= VPROT_READ;
478 if (w == 'w') vprot |= VPROT_WRITE;
479 if (x == 'x') vprot |= VPROT_EXEC;
480 if (p == 'p') vprot |= VPROT_WRITECOPY;
481 VIRTUAL_CreateView( start, end - start, 0,
482 VFLAG_SYSTEM, vprot, NULL );
484 close (fd);
487 #endif /* linux */
488 return TRUE;
492 /***********************************************************************
493 * VIRTUAL_GetPageSize
495 DWORD VIRTUAL_GetPageSize(void)
497 return 1 << page_shift;
501 /***********************************************************************
502 * VIRTUAL_GetGranularity
504 DWORD VIRTUAL_GetGranularity(void)
506 return granularity_mask + 1;
510 /***********************************************************************
511 * VIRTUAL_SetFaultHandler
513 BOOL32 VIRTUAL_SetFaultHandler( LPVOID addr, HANDLERPROC proc, LPVOID arg )
515 FILE_VIEW *view;
517 if (!(view = VIRTUAL_FindView((UINT32)addr))) return FALSE;
518 view->handlerProc = proc;
519 view->handlerArg = arg;
520 return TRUE;
523 /***********************************************************************
524 * VIRTUAL_HandleFault
526 BOOL32 VIRTUAL_HandleFault(LPVOID addr)
528 FILE_VIEW *view = VIRTUAL_FindView((UINT32)addr);
530 if (view && view->handlerProc)
531 return view->handlerProc(view->handlerArg, addr);
532 return FALSE;
536 /***********************************************************************
537 * VirtualAlloc (KERNEL32.548)
538 * Reserves or commits a region of pages in virtual address space
540 * RETURNS
541 * Base address of allocated region of pages
542 * NULL: Failure
544 LPVOID WINAPI VirtualAlloc(
545 LPVOID addr, /* [in] Address of region to reserve or commit */
546 DWORD size, /* [in] Size of region */
547 DWORD type, /* [in] Type of allocation */
548 DWORD protect /* [in] Type of access protection */
550 FILE_VIEW *view;
551 UINT32 base, ptr, view_size;
552 BYTE vprot;
554 TRACE(virtual, "%08x %08lx %lx %08lx\n",
555 (UINT32)addr, size, type, protect );
557 /* Round parameters to a page boundary */
559 if (size > 0x7fc00000) /* 2Gb - 4Mb */
561 SetLastError( ERROR_OUTOFMEMORY );
562 return NULL;
564 if (addr)
566 if (type & MEM_RESERVE) /* Round down to 64k boundary */
567 base = ((UINT32)addr + granularity_mask) & ~granularity_mask;
568 else
569 base = ROUND_ADDR( addr );
570 size = (((UINT32)addr + size + page_mask) & ~page_mask) - base;
571 if (base + size < base) /* Disallow wrap-around */
573 SetLastError( ERROR_INVALID_PARAMETER );
574 return NULL;
577 else
579 base = 0;
580 size = (size + page_mask) & ~page_mask;
583 if (type & MEM_TOP_DOWN) {
584 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
585 * Is there _ANY_ way to do it with UNIX mmap()?
587 WARN(virtual,"MEM_TOP_DOWN ignored\n");
588 type &= ~MEM_TOP_DOWN;
590 /* Compute the protection flags */
592 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
593 (type & ~(MEM_COMMIT | MEM_RESERVE)))
595 SetLastError( ERROR_INVALID_PARAMETER );
596 return NULL;
598 if (type & MEM_COMMIT)
599 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
600 else vprot = 0;
602 /* Reserve the memory */
604 if ((type & MEM_RESERVE) || !base)
606 view_size = size + (base ? 0 : granularity_mask + 1);
607 ptr = (UINT32)FILE_dommap( NULL, (LPVOID)base, 0, view_size, 0, 0,
608 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
609 if (ptr == (UINT32)-1)
611 SetLastError( ERROR_OUTOFMEMORY );
612 return NULL;
614 if (!base)
616 /* Release the extra memory while keeping the range */
617 /* starting on a 64k boundary. */
619 if (ptr & granularity_mask)
621 UINT32 extra = granularity_mask + 1 - (ptr & granularity_mask);
622 FILE_munmap( (void *)ptr, 0, extra );
623 ptr += extra;
624 view_size -= extra;
626 if (view_size > size)
627 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
629 else if (ptr != base)
631 /* We couldn't get the address we wanted */
632 FILE_munmap( (void *)ptr, 0, view_size );
633 SetLastError( ERROR_INVALID_ADDRESS );
634 return NULL;
636 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, NULL )))
638 FILE_munmap( (void *)ptr, 0, size );
639 SetLastError( ERROR_OUTOFMEMORY );
640 return NULL;
642 VIRTUAL_DEBUG_DUMP_VIEW( view );
643 return (LPVOID)ptr;
646 /* Commit the pages */
648 if (!(view = VIRTUAL_FindView( base )) ||
649 (base + size > view->base + view->size))
651 SetLastError( ERROR_INVALID_PARAMETER );
652 return NULL;
655 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
656 return (LPVOID)base;
660 /***********************************************************************
661 * VirtualFree (KERNEL32.550)
662 * Release or decommits a region of pages in virtual address space.
664 * RETURNS
665 * TRUE: Success
666 * FALSE: Failure
668 BOOL32 WINAPI VirtualFree(
669 LPVOID addr, /* [in] Address of region of committed pages */
670 DWORD size, /* [in] Size of region */
671 DWORD type /* [in] Type of operation */
673 FILE_VIEW *view;
674 UINT32 base;
676 TRACE(virtual, "%08x %08lx %lx\n",
677 (UINT32)addr, size, type );
679 /* Fix the parameters */
681 size = ROUND_SIZE( addr, size );
682 base = ROUND_ADDR( addr );
684 if (!(view = VIRTUAL_FindView( base )) ||
685 (base + size > view->base + view->size))
687 SetLastError( ERROR_INVALID_PARAMETER );
688 return FALSE;
691 /* Compute the protection flags */
693 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
695 SetLastError( ERROR_INVALID_PARAMETER );
696 return FALSE;
699 /* Free the pages */
701 if (type == MEM_RELEASE)
703 if (size || (base != view->base))
705 SetLastError( ERROR_INVALID_PARAMETER );
706 return FALSE;
708 VIRTUAL_DeleteView( view );
709 return TRUE;
712 /* Decommit the pages */
713 return VIRTUAL_SetProt( view, base, size, 0 );
717 /***********************************************************************
718 * VirtualLock (KERNEL32.551)
719 * Locks the specified region of virtual address space
721 * NOTE
722 * Always returns TRUE
724 * RETURNS
725 * TRUE: Success
726 * FALSE: Failure
728 BOOL32 WINAPI VirtualLock(
729 LPVOID addr, /* [in] Address of first byte of range to lock */
730 DWORD size /* [in] Number of bytes in range to lock */
732 return TRUE;
736 /***********************************************************************
737 * VirtualUnlock (KERNEL32.556)
738 * Unlocks a range of pages in the virtual address space
740 * NOTE
741 * Always returns TRUE
743 * RETURNS
744 * TRUE: Success
745 * FALSE: Failure
747 BOOL32 WINAPI VirtualUnlock(
748 LPVOID addr, /* [in] Address of first byte of range */
749 DWORD size /* [in] Number of bytes in range */
751 return TRUE;
755 /***********************************************************************
756 * VirtualProtect (KERNEL32.552)
757 * Changes the access protection on a region of committed pages
759 * RETURNS
760 * TRUE: Success
761 * FALSE: Failure
763 BOOL32 WINAPI VirtualProtect(
764 LPVOID addr, /* [in] Address of region of committed pages */
765 DWORD size, /* [in] Size of region */
766 DWORD new_prot, /* [in] Desired access protection */
767 LPDWORD old_prot /* [out] Address of variable to get old protection */
769 FILE_VIEW *view;
770 UINT32 base, i;
771 BYTE vprot, *p;
773 TRACE(virtual, "%08x %08lx %08lx\n",
774 (UINT32)addr, size, new_prot );
776 /* Fix the parameters */
778 size = ROUND_SIZE( addr, size );
779 base = ROUND_ADDR( addr );
781 if (!(view = VIRTUAL_FindView( base )) ||
782 (base + size > view->base + view->size))
784 SetLastError( ERROR_INVALID_PARAMETER );
785 return FALSE;
788 /* Make sure all the pages are committed */
790 p = view->prot + ((base - view->base) >> page_shift);
791 for (i = size >> page_shift; i; i--, p++)
793 if (!(*p & VPROT_COMMITTED))
795 SetLastError( ERROR_INVALID_PARAMETER );
796 return FALSE;
800 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
801 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
802 return VIRTUAL_SetProt( view, base, size, vprot );
806 /***********************************************************************
807 * VirtualProtectEx (KERNEL32.553)
808 * Changes the access protection on a region of committed pages in the
809 * virtual address space of a specified process
811 * RETURNS
812 * TRUE: Success
813 * FALSE: Failure
815 BOOL32 WINAPI VirtualProtectEx(
816 HANDLE32 handle, /* [in] Handle of process */
817 LPVOID addr, /* [in] Address of region of committed pages */
818 DWORD size, /* [in] Size of region */
819 DWORD new_prot, /* [in] Desired access protection */
820 LPDWORD old_prot /* [out] Address of variable to get old protection */
822 BOOL32 ret = FALSE;
824 PDB32 *pdb = PROCESS_GetPtr( handle, PROCESS_VM_OPERATION, NULL );
825 if (pdb)
827 if (pdb == PROCESS_Current())
828 ret = VirtualProtect( addr, size, new_prot, old_prot );
829 else
830 ERR(virtual,"Unsupported on other process\n");
831 K32OBJ_DecCount( &pdb->header );
833 return ret;
837 /***********************************************************************
838 * VirtualQuery (KERNEL32.554)
839 * Provides info about a range of pages in virtual address space
841 * RETURNS
842 * Number of bytes returned in information buffer
844 DWORD WINAPI VirtualQuery(
845 LPCVOID addr, /* [in] Address of region */
846 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
847 DWORD len /* [in] Size of buffer */
849 FILE_VIEW *view = VIRTUAL_FirstView;
850 UINT32 base = ROUND_ADDR( addr );
851 UINT32 alloc_base = 0;
852 UINT32 size = 0;
854 /* Find the view containing the address */
856 for (;;)
858 if (!view)
860 size = 0xffff0000 - alloc_base;
861 break;
863 if (view->base > base)
865 size = view->base - alloc_base;
866 view = NULL;
867 break;
869 if (view->base + view->size > base)
871 alloc_base = view->base;
872 size = view->size;
873 break;
875 alloc_base = view->base + view->size;
876 view = view->next;
879 /* Fill the info structure */
881 if (!view)
883 info->State = MEM_FREE;
884 info->Protect = 0;
885 info->AllocationProtect = 0;
886 info->Type = 0;
888 else
890 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
891 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
892 for (size = base - alloc_base; size < view->size; size += page_mask+1)
893 if (view->prot[size >> page_shift] != vprot) break;
894 info->AllocationProtect = view->protect;
895 info->Type = MEM_PRIVATE; /* FIXME */
898 info->BaseAddress = (LPVOID)base;
899 info->AllocationBase = (LPVOID)alloc_base;
900 info->RegionSize = size - (base - alloc_base);
901 return sizeof(*info);
905 /***********************************************************************
906 * VirtualQueryEx (KERNEL32.555)
907 * Provides info about a range of pages in virtual address space of a
908 * specified process
910 * RETURNS
911 * Number of bytes returned in information buffer
913 DWORD WINAPI VirtualQueryEx(
914 HANDLE32 handle, /* [in] Handle of process */
915 LPCVOID addr, /* [in] Address of region */
916 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
917 DWORD len /* [in] Size of buffer */
919 DWORD ret = len;
921 PDB32 *pdb = PROCESS_GetPtr( handle, PROCESS_QUERY_INFORMATION, NULL );
922 if (pdb)
924 if (pdb == PROCESS_Current())
925 ret = VirtualQuery( addr, info, len );
926 else
927 ERR(virtual,"Unsupported on other process\n");
928 K32OBJ_DecCount( &pdb->header );
930 return ret;
934 /***********************************************************************
935 * IsBadReadPtr32 (KERNEL32.354)
937 * RETURNS
938 * FALSE: Process has read access to entire block
939 * TRUE: Otherwise
941 BOOL32 WINAPI IsBadReadPtr32(
942 LPCVOID ptr, /* Address of memory block */
943 UINT32 size /* Size of block */
945 return !VIRTUAL_CheckFlags( (UINT32)ptr, size,
946 VPROT_READ | VPROT_COMMITTED );
950 /***********************************************************************
951 * IsBadWritePtr32 (KERNEL32.357)
953 * RETURNS
954 * FALSE: Process has write access to entire block
955 * TRUE: Otherwise
957 BOOL32 WINAPI IsBadWritePtr32(
958 LPVOID ptr, /* [in] Address of memory block */
959 UINT32 size /* [in] Size of block in bytes */
961 return !VIRTUAL_CheckFlags( (UINT32)ptr, size,
962 VPROT_WRITE | VPROT_COMMITTED );
966 /***********************************************************************
967 * IsBadHugeReadPtr32 (KERNEL32.352)
968 * RETURNS
969 * FALSE: Process has read access to entire block
970 * TRUE: Otherwise
972 BOOL32 WINAPI IsBadHugeReadPtr32(
973 LPCVOID ptr, /* [in] Address of memory block */
974 UINT32 size /* [in] Size of block */
976 return IsBadReadPtr32( ptr, size );
980 /***********************************************************************
981 * IsBadHugeWritePtr32 (KERNEL32.353)
982 * RETURNS
983 * FALSE: Process has write access to entire block
984 * TRUE: Otherwise
986 BOOL32 WINAPI IsBadHugeWritePtr32(
987 LPVOID ptr, /* [in] Address of memory block */
988 UINT32 size /* [in] Size of block */
990 return IsBadWritePtr32( ptr, size );
994 /***********************************************************************
995 * IsBadCodePtr32 (KERNEL32.351)
997 * RETURNS
998 * FALSE: Process has read access to specified memory
999 * TRUE: Otherwise
1001 BOOL32 WINAPI IsBadCodePtr32(
1002 FARPROC32 ptr /* [in] Address of function */
1004 return !VIRTUAL_CheckFlags( (UINT32)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
1008 /***********************************************************************
1009 * IsBadStringPtr32A (KERNEL32.355)
1011 * RETURNS
1012 * FALSE: Read access to all bytes in string
1013 * TRUE: Else
1015 BOOL32 WINAPI IsBadStringPtr32A(
1016 LPCSTR str, /* [in] Address of string */
1017 UINT32 max /* [in] Maximum size of string */
1019 FILE_VIEW *view;
1020 UINT32 page, count;
1022 if (!max) return FALSE;
1023 if (!(view = VIRTUAL_FindView( (UINT32)str ))) return TRUE;
1024 page = ((UINT32)str - view->base) >> page_shift;
1025 count = page_mask + 1 - ((UINT32)str & page_mask);
1027 while (max)
1029 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1030 (VPROT_READ | VPROT_COMMITTED))
1031 return TRUE;
1032 if (count > max) count = max;
1033 max -= count;
1034 while (count--) if (!*str++) return FALSE;
1035 if (++page >= view->size >> page_shift) return TRUE;
1036 count = page_mask + 1;
1038 return FALSE;
1042 /***********************************************************************
1043 * IsBadStringPtr32W (KERNEL32.356)
1044 * See IsBadStringPtr32A
1046 BOOL32 WINAPI IsBadStringPtr32W( LPCWSTR str, UINT32 max )
1048 FILE_VIEW *view;
1049 UINT32 page, count;
1051 if (!max) return FALSE;
1052 if (!(view = VIRTUAL_FindView( (UINT32)str ))) return TRUE;
1053 page = ((UINT32)str - view->base) >> page_shift;
1054 count = (page_mask + 1 - ((UINT32)str & page_mask)) / sizeof(WCHAR);
1056 while (max)
1058 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1059 (VPROT_READ | VPROT_COMMITTED))
1060 return TRUE;
1061 if (count > max) count = max;
1062 max -= count;
1063 while (count--) if (!*str++) return FALSE;
1064 if (++page >= view->size >> page_shift) return TRUE;
1065 count = (page_mask + 1) / sizeof(WCHAR);
1067 return FALSE;
1071 /***********************************************************************
1072 * CreateFileMapping32A (KERNEL32.46)
1073 * Creates a named or unnamed file-mapping object for the specified file
1075 * RETURNS
1076 * Handle: Success
1077 * 0: Mapping object does not exist
1078 * NULL: Failure
1080 HANDLE32 WINAPI CreateFileMapping32A(
1081 HFILE32 hFile, /* [in] Handle of file to map */
1082 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1083 DWORD protect, /* [in] Protection for mapping object */
1084 DWORD size_high, /* [in] High-order 32 bits of object size */
1085 DWORD size_low, /* [in] Low-order 32 bits of object size */
1086 LPCSTR name /* [in] Name of file-mapping object */ )
1088 FILE_MAPPING *mapping = NULL;
1089 HANDLE32 handle;
1090 BYTE vprot;
1091 BOOL32 inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1093 /* First search for an object with the same name */
1095 K32OBJ *obj = K32OBJ_FindName( name );
1097 SetLastError(0); /* Win95 does that for some functions, like CFM */
1098 if (obj)
1100 if (obj->type == K32OBJ_MEM_MAPPED_FILE)
1102 SetLastError( ERROR_ALREADY_EXISTS );
1103 handle = HANDLE_Alloc( PROCESS_Current(), obj,
1104 FILE_MAP_ALL_ACCESS /*FIXME*/, inherit, -1 );
1106 else
1108 SetLastError( ERROR_DUP_NAME );
1109 handle = 0;
1111 K32OBJ_DecCount( obj );
1112 return handle;
1115 /* Check parameters */
1117 TRACE(virtual,"(%x,%p,%08lx,%08lx%08lx,%s)\n",
1118 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1120 vprot = VIRTUAL_GetProt( protect );
1121 if (protect & SEC_RESERVE)
1123 if (hFile != INVALID_HANDLE_VALUE32)
1125 SetLastError( ERROR_INVALID_PARAMETER );
1126 return 0;
1129 else vprot |= VPROT_COMMITTED;
1130 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1132 /* Compute the size and extend the file if necessary */
1134 if (hFile == INVALID_HANDLE_VALUE32)
1136 FIXME(virtual,"shared anon mapping (%s, size %d) not correctly supported!\n",debugstr_a(name),size_low);
1137 if (!size_high && !size_low)
1139 SetLastError( ERROR_INVALID_PARAMETER );
1140 return 0;
1142 obj = NULL;
1143 if (name)
1145 CHAR buf[260];
1147 GetTempPath32A(260,buf);
1148 GetTempFileName32A(buf,"wine",0,buf);
1149 hFile = CreateFile32A(buf,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_ALWAYS,0,0);
1150 /* FIXME: bad hack to avoid lots of leftover tempfiles */
1151 DeleteFile32A(buf);
1152 if (hFile == INVALID_HANDLE_VALUE32)
1153 FIXME(virtual,"could not create temp. file for anon shared mapping: reason was 0x%08lx\n",GetLastError());
1156 if (hFile != INVALID_HANDLE_VALUE32) /* We have a file */
1158 BY_HANDLE_FILE_INFORMATION info;
1159 DWORD access = GENERIC_READ;
1161 if (((protect & 0xff) == PAGE_READWRITE) ||
1162 ((protect & 0xff) == PAGE_WRITECOPY) ||
1163 ((protect & 0xff) == PAGE_EXECUTE_READWRITE) ||
1164 ((protect & 0xff) == PAGE_EXECUTE_WRITECOPY))
1165 access |= GENERIC_WRITE;
1166 if (!(obj = HANDLE_GetObjPtr( PROCESS_Current(), hFile,
1167 K32OBJ_FILE, access, NULL )))
1168 goto error;
1170 if (!GetFileInformationByHandle( hFile, &info )) goto error;
1171 if (!size_high && !size_low)
1173 size_high = info.nFileSizeHigh;
1174 size_low = info.nFileSizeLow;
1176 else if ((size_high > info.nFileSizeHigh) ||
1177 ((size_high == info.nFileSizeHigh) &&
1178 (size_low > info.nFileSizeLow)))
1180 /* We have to grow the file */
1181 if (SetFilePointer( hFile, size_low, &size_high,
1182 FILE_BEGIN ) == 0xffffffff) goto error;
1183 if (!SetEndOfFile( hFile )) goto error;
1187 /* Allocate the mapping object */
1189 if (!(mapping = HeapAlloc( SystemHeap, 0, sizeof(*mapping) ))) goto error;
1190 mapping->header.type = K32OBJ_MEM_MAPPED_FILE;
1191 mapping->header.refcount = 1;
1192 mapping->protect = vprot;
1193 mapping->size_high = size_high;
1194 mapping->size_low = ROUND_SIZE( 0, size_low );
1195 mapping->file = (FILE_OBJECT *)obj;
1197 if (!K32OBJ_AddName( &mapping->header, name )) handle = 0;
1198 else handle = HANDLE_Alloc( PROCESS_Current(), &mapping->header,
1199 FILE_MAP_ALL_ACCESS /*FIXME*/, inherit, -1 );
1200 K32OBJ_DecCount( &mapping->header );
1201 return handle;
1203 error:
1204 if (obj) K32OBJ_DecCount( obj );
1205 if (mapping) HeapFree( SystemHeap, 0, mapping );
1206 return 0;
1210 /***********************************************************************
1211 * CreateFileMapping32W (KERNEL32.47)
1212 * See CreateFileMapping32A
1214 HANDLE32 WINAPI CreateFileMapping32W( HFILE32 hFile, LPSECURITY_ATTRIBUTES attr,
1215 DWORD protect, DWORD size_high,
1216 DWORD size_low, LPCWSTR name )
1218 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1219 HANDLE32 ret = CreateFileMapping32A( hFile, attr, protect,
1220 size_high, size_low, nameA );
1221 HeapFree( GetProcessHeap(), 0, nameA );
1222 return ret;
1226 /***********************************************************************
1227 * OpenFileMapping32A (KERNEL32.397)
1228 * Opens a named file-mapping object.
1230 * RETURNS
1231 * Handle: Success
1232 * NULL: Failure
1234 HANDLE32 WINAPI OpenFileMapping32A(
1235 DWORD access, /* [in] Access mode */
1236 BOOL32 inherit, /* [in] Inherit flag */
1237 LPCSTR name /* [in] Name of file-mapping object */
1239 HANDLE32 handle = 0;
1240 K32OBJ *obj;
1241 SYSTEM_LOCK();
1242 if ((obj = K32OBJ_FindNameType( name, K32OBJ_MEM_MAPPED_FILE )))
1244 handle = HANDLE_Alloc( PROCESS_Current(), obj, access, inherit, -1 );
1245 K32OBJ_DecCount( obj );
1247 SYSTEM_UNLOCK();
1248 return handle;
1252 /***********************************************************************
1253 * OpenFileMapping32W (KERNEL32.398)
1254 * See OpenFileMapping32A
1256 HANDLE32 WINAPI OpenFileMapping32W( DWORD access, BOOL32 inherit, LPCWSTR name)
1258 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1259 HANDLE32 ret = OpenFileMapping32A( access, inherit, nameA );
1260 HeapFree( GetProcessHeap(), 0, nameA );
1261 return ret;
1265 /***********************************************************************
1266 * VIRTUAL_DestroyMapping
1268 * Destroy a FILE_MAPPING object.
1270 static void VIRTUAL_DestroyMapping( K32OBJ *ptr )
1272 FILE_MAPPING *mapping = (FILE_MAPPING *)ptr;
1273 assert( ptr->type == K32OBJ_MEM_MAPPED_FILE );
1275 if (mapping->file) K32OBJ_DecCount( &mapping->file->header );
1276 ptr->type = K32OBJ_UNKNOWN;
1277 HeapFree( SystemHeap, 0, mapping );
1281 /***********************************************************************
1282 * MapViewOfFile (KERNEL32.385)
1283 * Maps a view of a file into the address space
1285 * RETURNS
1286 * Starting address of mapped view
1287 * NULL: Failure
1289 LPVOID WINAPI MapViewOfFile(
1290 HANDLE32 mapping, /* [in] File-mapping object to map */
1291 DWORD access, /* [in] Access mode */
1292 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1293 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1294 DWORD count /* [in] Number of bytes to map */
1296 return MapViewOfFileEx( mapping, access, offset_high,
1297 offset_low, count, NULL );
1301 /***********************************************************************
1302 * MapViewOfFileEx (KERNEL32.386)
1303 * Maps a view of a file into the address space
1305 * RETURNS
1306 * Starting address of mapped view
1307 * NULL: Failure
1309 LPVOID WINAPI MapViewOfFileEx(
1310 HANDLE32 handle, /* [in] File-mapping object to map */
1311 DWORD access, /* [in] Access mode */
1312 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1313 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1314 DWORD count, /* [in] Number of bytes to map */
1315 LPVOID addr /* [in] Suggested starting address for mapped view */
1317 FILE_MAPPING *mapping;
1318 FILE_VIEW *view;
1319 UINT32 ptr = (UINT32)-1, size = 0;
1320 int flags = MAP_PRIVATE;
1322 /* Check parameters */
1324 if ((offset_low & granularity_mask) ||
1325 (addr && ((UINT32)addr & granularity_mask)))
1327 SetLastError( ERROR_INVALID_PARAMETER );
1328 return NULL;
1331 if (!(mapping = (FILE_MAPPING *)HANDLE_GetObjPtr( PROCESS_Current(),
1332 handle,
1333 K32OBJ_MEM_MAPPED_FILE,
1334 0 /* FIXME */, NULL )))
1335 return NULL;
1337 if (mapping->size_high || offset_high)
1338 ERR(virtual, "Offsets larger than 4Gb not supported\n");
1340 if ((offset_low >= mapping->size_low) ||
1341 (count > mapping->size_low - offset_low))
1343 SetLastError( ERROR_INVALID_PARAMETER );
1344 goto error;
1346 if (count) size = ROUND_SIZE( offset_low, count );
1347 else size = mapping->size_low - offset_low;
1349 switch(access)
1351 case FILE_MAP_ALL_ACCESS:
1352 case FILE_MAP_WRITE:
1353 case FILE_MAP_WRITE | FILE_MAP_READ:
1354 if (!(mapping->protect & VPROT_WRITE))
1356 SetLastError( ERROR_INVALID_PARAMETER );
1357 goto error;
1359 flags = MAP_SHARED;
1360 /* fall through */
1361 case FILE_MAP_READ:
1362 case FILE_MAP_COPY:
1363 case FILE_MAP_COPY | FILE_MAP_READ:
1364 if (mapping->protect & VPROT_READ) break;
1365 /* fall through */
1366 default:
1367 SetLastError( ERROR_INVALID_PARAMETER );
1368 goto error;
1371 /* Map the file */
1373 TRACE(virtual, "handle=%x size=%x offset=%lx\n",
1374 handle, size, offset_low );
1376 ptr = (UINT32)FILE_dommap( mapping->file, addr, 0, size, 0, offset_low,
1377 VIRTUAL_GetUnixProt( mapping->protect ),
1378 flags );
1379 if (ptr == (UINT32)-1) {
1380 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1381 * Platform Differences":
1382 * Windows NT: ERROR_INVALID_PARAMETER
1383 * Windows 95: ERROR_INVALID_ADDRESS.
1384 * FIXME: So should we add a module dependend check here? -MM
1386 if (errno==ENOMEM)
1387 SetLastError( ERROR_OUTOFMEMORY );
1388 else
1389 SetLastError( ERROR_INVALID_PARAMETER );
1390 goto error;
1393 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0,
1394 mapping->protect, mapping )))
1396 SetLastError( ERROR_OUTOFMEMORY );
1397 goto error;
1399 return (LPVOID)ptr;
1401 error:
1402 if (ptr != (UINT32)-1) FILE_munmap( (void *)ptr, 0, size );
1403 K32OBJ_DecCount( &mapping->header );
1404 return NULL;
1408 /***********************************************************************
1409 * FlushViewOfFile (KERNEL32.262)
1410 * Writes to the disk a byte range within a mapped view of a file
1412 * RETURNS
1413 * TRUE: Success
1414 * FALSE: Failure
1416 BOOL32 WINAPI FlushViewOfFile(
1417 LPCVOID base, /* [in] Start address of byte range to flush */
1418 DWORD cbFlush /* [in] Number of bytes in range */
1420 FILE_VIEW *view;
1421 UINT32 addr = ROUND_ADDR( base );
1423 TRACE(virtual, "FlushViewOfFile at %p for %ld bytes\n",
1424 base, cbFlush );
1426 if (!(view = VIRTUAL_FindView( addr )))
1428 SetLastError( ERROR_INVALID_PARAMETER );
1429 return FALSE;
1431 if (!cbFlush) cbFlush = view->size;
1432 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1433 SetLastError( ERROR_INVALID_PARAMETER );
1434 return FALSE;
1438 /***********************************************************************
1439 * UnmapViewOfFile (KERNEL32.540)
1440 * Unmaps a mapped view of a file.
1442 * NOTES
1443 * Should addr be an LPCVOID?
1445 * RETURNS
1446 * TRUE: Success
1447 * FALSE: Failure
1449 BOOL32 WINAPI UnmapViewOfFile(
1450 LPVOID addr /* [in] Address where mapped view begins */
1452 FILE_VIEW *view;
1453 UINT32 base = ROUND_ADDR( addr );
1454 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1456 SetLastError( ERROR_INVALID_PARAMETER );
1457 return FALSE;
1459 VIRTUAL_DeleteView( view );
1460 return TRUE;
1463 /***********************************************************************
1464 * VIRTUAL_MapFileW
1466 * Helper function to map a file to memory:
1467 * name - file name
1468 * [RETURN] ptr - pointer to mapped file
1470 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1472 HANDLE32 hFile, hMapping;
1473 LPVOID ptr = NULL;
1475 hFile = CreateFile32W( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1476 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1477 if (hFile != INVALID_HANDLE_VALUE32)
1479 hMapping = CreateFileMapping32A( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1480 CloseHandle( hFile );
1481 if (hMapping)
1483 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1484 CloseHandle( hMapping );
1487 return ptr;