Added beginnings of server-side file handling.
[wine/multimedia.git] / memory / virtual.c
blob7493022ba8b1a96d08fd00ec78f0041386e57365
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 int unix_handle;
37 BYTE protect;
38 } FILE_MAPPING;
40 /* File view */
41 typedef struct _FV
43 struct _FV *next; /* Next view */
44 struct _FV *prev; /* Prev view */
45 UINT32 base; /* Base address */
46 UINT32 size; /* Size in bytes */
47 UINT32 flags; /* Allocation flags */
48 UINT32 offset; /* Offset from start of mapped file */
49 FILE_MAPPING *mapping; /* File mapping */
50 HANDLERPROC handlerProc; /* Fault handler */
51 LPVOID handlerArg; /* Fault handler argument */
52 BYTE protect; /* Protection for all pages at allocation time */
53 BYTE prot[1]; /* Protection byte for each page */
54 } FILE_VIEW;
56 /* Per-page protection byte values */
57 #define VPROT_READ 0x01
58 #define VPROT_WRITE 0x02
59 #define VPROT_EXEC 0x04
60 #define VPROT_WRITECOPY 0x08
61 #define VPROT_GUARD 0x10
62 #define VPROT_NOCACHE 0x20
63 #define VPROT_COMMITTED 0x40
65 /* Per-view flags */
66 #define VFLAG_SYSTEM 0x01
68 /* Conversion from VPROT_* to Win32 flags */
69 static const BYTE VIRTUAL_Win32Flags[16] =
71 PAGE_NOACCESS, /* 0 */
72 PAGE_READONLY, /* READ */
73 PAGE_READWRITE, /* WRITE */
74 PAGE_READWRITE, /* READ | WRITE */
75 PAGE_EXECUTE, /* EXEC */
76 PAGE_EXECUTE_READ, /* READ | EXEC */
77 PAGE_EXECUTE_READWRITE, /* WRITE | EXEC */
78 PAGE_EXECUTE_READWRITE, /* READ | WRITE | EXEC */
79 PAGE_WRITECOPY, /* WRITECOPY */
80 PAGE_WRITECOPY, /* READ | WRITECOPY */
81 PAGE_WRITECOPY, /* WRITE | WRITECOPY */
82 PAGE_WRITECOPY, /* READ | WRITE | WRITECOPY */
83 PAGE_EXECUTE_WRITECOPY, /* EXEC | WRITECOPY */
84 PAGE_EXECUTE_WRITECOPY, /* READ | EXEC | WRITECOPY */
85 PAGE_EXECUTE_WRITECOPY, /* WRITE | EXEC | WRITECOPY */
86 PAGE_EXECUTE_WRITECOPY /* READ | WRITE | EXEC | WRITECOPY */
90 static FILE_VIEW *VIRTUAL_FirstView;
92 #ifdef __i386__
93 /* These are always the same on an i386, and it will be faster this way */
94 # define page_mask 0xfff
95 # define page_shift 12
96 # define granularity_mask 0xffff
97 #else
98 static UINT32 page_shift;
99 static UINT32 page_mask;
100 static UINT32 granularity_mask; /* Allocation granularity (usually 64k) */
101 #endif /* __i386__ */
103 #define ROUND_ADDR(addr) \
104 ((UINT32)(addr) & ~page_mask)
106 #define ROUND_SIZE(addr,size) \
107 (((UINT32)(size) + ((UINT32)(addr) & page_mask) + page_mask) & ~page_mask)
109 static void VIRTUAL_DestroyMapping( K32OBJ *obj );
111 const K32OBJ_OPS MEM_MAPPED_FILE_Ops =
113 /* Object cannot be waited upon, so we don't need these (except destroy) */
114 NULL, /* signaled */
115 NULL, /* satisfied */
116 NULL, /* add_wait */
117 NULL, /* remove_wait */
118 NULL, /* read */
119 NULL, /* write */
120 VIRTUAL_DestroyMapping /* destroy */
123 #define VIRTUAL_DEBUG_DUMP_VIEW(view) \
124 if (!TRACE_ON(virtual)); else VIRTUAL_DumpView(view)
126 /***********************************************************************
127 * VIRTUAL_GetProtStr
129 static const char *VIRTUAL_GetProtStr( BYTE prot )
131 static char buffer[6];
132 buffer[0] = (prot & VPROT_COMMITTED) ? 'c' : '-';
133 buffer[1] = (prot & VPROT_GUARD) ? 'g' : '-';
134 buffer[2] = (prot & VPROT_READ) ? 'r' : '-';
135 buffer[3] = (prot & VPROT_WRITE) ?
136 ((prot & VPROT_WRITECOPY) ? 'w' : 'W') : '-';
137 buffer[4] = (prot & VPROT_EXEC) ? 'x' : '-';
138 buffer[5] = 0;
139 return buffer;
143 /***********************************************************************
144 * VIRTUAL_DumpView
146 static void VIRTUAL_DumpView( FILE_VIEW *view )
148 UINT32 i, count;
149 UINT32 addr = view->base;
150 BYTE prot = view->prot[0];
152 DUMP( "View: %08x - %08x%s",
153 view->base, view->base + view->size - 1,
154 (view->flags & VFLAG_SYSTEM) ? " (system)" : "" );
155 if (view->mapping && view->mapping->file)
156 DUMP( " %s @ %08x\n", view->mapping->file->unix_name, view->offset );
157 else
158 DUMP( " (anonymous)\n");
160 for (count = i = 1; i < view->size >> page_shift; i++, count++)
162 if (view->prot[i] == prot) continue;
163 DUMP( " %08x - %08x %s\n",
164 addr, addr + (count << page_shift) - 1,
165 VIRTUAL_GetProtStr(prot) );
166 addr += (count << page_shift);
167 prot = view->prot[i];
168 count = 0;
170 if (count)
171 DUMP( " %08x - %08x %s\n",
172 addr, addr + (count << page_shift) - 1,
173 VIRTUAL_GetProtStr(prot) );
177 /***********************************************************************
178 * VIRTUAL_Dump
180 void VIRTUAL_Dump(void)
182 FILE_VIEW *view = VIRTUAL_FirstView;
183 DUMP( "\nDump of all virtual memory views:\n\n" );
184 while (view)
186 VIRTUAL_DumpView( view );
187 view = view->next;
192 /***********************************************************************
193 * VIRTUAL_FindView
195 * Find the view containing a given address.
197 * RETURNS
198 * View: Success
199 * NULL: Failure
201 static FILE_VIEW *VIRTUAL_FindView(
202 UINT32 addr /* [in] Address */
204 FILE_VIEW *view = VIRTUAL_FirstView;
205 while (view)
207 if (view->base > addr) return NULL;
208 if (view->base + view->size > addr) return view;
209 view = view->next;
211 return NULL;
215 /***********************************************************************
216 * VIRTUAL_CreateView
218 * Create a new view and add it in the linked list.
220 static FILE_VIEW *VIRTUAL_CreateView( UINT32 base, UINT32 size, UINT32 offset,
221 UINT32 flags, BYTE vprot,
222 FILE_MAPPING *mapping )
224 FILE_VIEW *view, *prev;
226 /* Create the view structure */
228 assert( !(base & page_mask) );
229 assert( !(size & page_mask) );
230 size >>= page_shift;
231 if (!(view = (FILE_VIEW *)malloc( sizeof(*view) + size - 1 ))) return NULL;
232 view->base = base;
233 view->size = size << page_shift;
234 view->flags = flags;
235 view->offset = offset;
236 view->mapping = mapping;
237 view->protect = vprot;
238 memset( view->prot, vprot, size );
240 /* Insert it in the linked list */
242 if (!VIRTUAL_FirstView || (VIRTUAL_FirstView->base > base))
244 view->next = VIRTUAL_FirstView;
245 view->prev = NULL;
246 if (view->next) view->next->prev = view;
247 VIRTUAL_FirstView = view;
249 else
251 prev = VIRTUAL_FirstView;
252 while (prev->next && (prev->next->base < base)) prev = prev->next;
253 view->next = prev->next;
254 view->prev = prev;
255 if (view->next) view->next->prev = view;
256 prev->next = view;
258 VIRTUAL_DEBUG_DUMP_VIEW( view );
259 return view;
263 /***********************************************************************
264 * VIRTUAL_DeleteView
265 * Deletes a view.
267 * RETURNS
268 * None
270 static void VIRTUAL_DeleteView(
271 FILE_VIEW *view /* [in] View */
273 FILE_munmap( (void *)view->base, 0, view->size );
274 if (view->next) view->next->prev = view->prev;
275 if (view->prev) view->prev->next = view->next;
276 else VIRTUAL_FirstView = view->next;
277 if (view->mapping) K32OBJ_DecCount( &view->mapping->header );
278 free( view );
282 /***********************************************************************
283 * VIRTUAL_GetUnixProt
285 * Convert page protections to protection for mmap/mprotect.
287 static int VIRTUAL_GetUnixProt( BYTE vprot )
289 int prot = 0;
290 if ((vprot & VPROT_COMMITTED) && !(vprot & VPROT_GUARD))
292 if (vprot & VPROT_READ) prot |= PROT_READ;
293 if (vprot & VPROT_WRITE) prot |= PROT_WRITE;
294 if (vprot & VPROT_EXEC) prot |= PROT_EXEC;
296 return prot;
300 /***********************************************************************
301 * VIRTUAL_GetWin32Prot
303 * Convert page protections to Win32 flags.
305 * RETURNS
306 * None
308 static void VIRTUAL_GetWin32Prot(
309 BYTE vprot, /* [in] Page protection flags */
310 DWORD *protect, /* [out] Location to store Win32 protection flags */
311 DWORD *state /* [out] Location to store mem state flag */
313 if (protect) {
314 *protect = VIRTUAL_Win32Flags[vprot & 0x0f];
315 /* if (vprot & VPROT_GUARD) *protect |= PAGE_GUARD;*/
316 if (vprot & VPROT_NOCACHE) *protect |= PAGE_NOCACHE;
318 if (vprot & VPROT_GUARD) *protect = PAGE_NOACCESS;
321 if (state) *state = (vprot & VPROT_COMMITTED) ? MEM_COMMIT : MEM_RESERVE;
325 /***********************************************************************
326 * VIRTUAL_GetProt
328 * Build page protections from Win32 flags.
330 * RETURNS
331 * Value of page protection flags
333 static BYTE VIRTUAL_GetProt(
334 DWORD protect /* [in] Win32 protection flags */
336 BYTE vprot;
338 switch(protect & 0xff)
340 case PAGE_READONLY:
341 vprot = VPROT_READ;
342 break;
343 case PAGE_READWRITE:
344 vprot = VPROT_READ | VPROT_WRITE;
345 break;
346 case PAGE_WRITECOPY:
347 vprot = VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
348 break;
349 case PAGE_EXECUTE:
350 vprot = VPROT_EXEC;
351 break;
352 case PAGE_EXECUTE_READ:
353 vprot = VPROT_EXEC | VPROT_READ;
354 break;
355 case PAGE_EXECUTE_READWRITE:
356 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE | VPROT_WRITECOPY;
357 break;
358 case PAGE_EXECUTE_WRITECOPY:
359 vprot = VPROT_EXEC | VPROT_READ | VPROT_WRITE;
360 break;
361 case PAGE_NOACCESS:
362 default:
363 vprot = 0;
364 break;
366 if (protect & PAGE_GUARD) vprot |= VPROT_GUARD;
367 if (protect & PAGE_NOCACHE) vprot |= VPROT_NOCACHE;
368 return vprot;
372 /***********************************************************************
373 * VIRTUAL_SetProt
375 * Change the protection of a range of pages.
377 * RETURNS
378 * TRUE: Success
379 * FALSE: Failure
381 static BOOL32 VIRTUAL_SetProt(
382 FILE_VIEW *view, /* [in] Pointer to view */
383 UINT32 base, /* [in] Starting address */
384 UINT32 size, /* [in] Size in bytes */
385 BYTE vprot /* [in] Protections to use */
387 TRACE(virtual, "%08x-%08x %s\n",
388 base, base + size - 1, VIRTUAL_GetProtStr( vprot ) );
390 if (mprotect( (void *)base, size, VIRTUAL_GetUnixProt(vprot) ))
391 return FALSE; /* FIXME: last error */
393 memset( view->prot + ((base - view->base) >> page_shift),
394 vprot, size >> page_shift );
395 VIRTUAL_DEBUG_DUMP_VIEW( view );
396 return TRUE;
400 /***********************************************************************
401 * VIRTUAL_CheckFlags
403 * Check that all pages in a range have the given flags.
405 * RETURNS
406 * TRUE: They do
407 * FALSE: They do not
409 static BOOL32 VIRTUAL_CheckFlags(
410 UINT32 base, /* [in] Starting address */
411 UINT32 size, /* [in] Size in bytes */
412 BYTE flags /* [in] Flags to check for */
414 FILE_VIEW *view;
415 UINT32 page;
417 if (!size) return TRUE;
418 if (!(view = VIRTUAL_FindView( base ))) return FALSE;
419 if (view->base + view->size < base + size) return FALSE;
420 page = (base - view->base) >> page_shift;
421 size = ROUND_SIZE( base, size ) >> page_shift;
422 while (size--) if ((view->prot[page++] & flags) != flags) return FALSE;
423 return TRUE;
427 /***********************************************************************
428 * VIRTUAL_Init
430 BOOL32 VIRTUAL_Init(void)
432 #ifndef __i386__
433 DWORD page_size;
435 # ifdef HAVE_GETPAGESIZE
436 page_size = getpagesize();
437 # else
438 # ifdef __svr4__
439 page_size = sysconf(_SC_PAGESIZE);
440 # else
441 # error Cannot get the page size on this platform
442 # endif
443 # endif
444 page_mask = page_size - 1;
445 granularity_mask = 0xffff; /* hard-coded for now */
446 /* Make sure we have a power of 2 */
447 assert( !(page_size & page_mask) );
448 page_shift = 0;
449 while ((1 << page_shift) != page_size) page_shift++;
450 #endif /* !__i386__ */
452 #ifdef linux
454 /* Do not use stdio here since it may temporarily change the size
455 * of some segments (ie libc6 adds 0x1000 per open FILE)
457 int fd = open ("/proc/self/maps", O_RDONLY);
458 if (fd >= 0)
460 char buffer[512]; /* line might be rather long in 2.1 */
462 for (;;)
464 int start, end, offset;
465 char r, w, x, p;
466 BYTE vprot = VPROT_COMMITTED;
468 char * ptr = buffer;
469 int count = sizeof(buffer);
470 while (1 == read(fd, ptr, 1) && *ptr != '\n' && --count > 0)
471 ptr++;
473 if (*ptr != '\n') break;
474 *ptr = '\0';
476 sscanf( buffer, "%x-%x %c%c%c%c %x",
477 &start, &end, &r, &w, &x, &p, &offset );
478 if (r == 'r') vprot |= VPROT_READ;
479 if (w == 'w') vprot |= VPROT_WRITE;
480 if (x == 'x') vprot |= VPROT_EXEC;
481 if (p == 'p') vprot |= VPROT_WRITECOPY;
482 VIRTUAL_CreateView( start, end - start, 0,
483 VFLAG_SYSTEM, vprot, NULL );
485 close (fd);
488 #endif /* linux */
489 return TRUE;
493 /***********************************************************************
494 * VIRTUAL_GetPageSize
496 DWORD VIRTUAL_GetPageSize(void)
498 return 1 << page_shift;
502 /***********************************************************************
503 * VIRTUAL_GetGranularity
505 DWORD VIRTUAL_GetGranularity(void)
507 return granularity_mask + 1;
511 /***********************************************************************
512 * VIRTUAL_SetFaultHandler
514 BOOL32 VIRTUAL_SetFaultHandler( LPVOID addr, HANDLERPROC proc, LPVOID arg )
516 FILE_VIEW *view;
518 if (!(view = VIRTUAL_FindView((UINT32)addr))) return FALSE;
519 view->handlerProc = proc;
520 view->handlerArg = arg;
521 return TRUE;
524 /***********************************************************************
525 * VIRTUAL_HandleFault
527 BOOL32 VIRTUAL_HandleFault(LPVOID addr)
529 FILE_VIEW *view = VIRTUAL_FindView((UINT32)addr);
531 if (view && view->handlerProc)
532 return view->handlerProc(view->handlerArg, addr);
533 return FALSE;
537 /***********************************************************************
538 * VirtualAlloc (KERNEL32.548)
539 * Reserves or commits a region of pages in virtual address space
541 * RETURNS
542 * Base address of allocated region of pages
543 * NULL: Failure
545 LPVOID WINAPI VirtualAlloc(
546 LPVOID addr, /* [in] Address of region to reserve or commit */
547 DWORD size, /* [in] Size of region */
548 DWORD type, /* [in] Type of allocation */
549 DWORD protect /* [in] Type of access protection */
551 FILE_VIEW *view;
552 UINT32 base, ptr, view_size;
553 BYTE vprot;
555 TRACE(virtual, "%08x %08lx %lx %08lx\n",
556 (UINT32)addr, size, type, protect );
558 /* Round parameters to a page boundary */
560 if (size > 0x7fc00000) /* 2Gb - 4Mb */
562 SetLastError( ERROR_OUTOFMEMORY );
563 return NULL;
565 if (addr)
567 if (type & MEM_RESERVE) /* Round down to 64k boundary */
568 base = ((UINT32)addr + granularity_mask) & ~granularity_mask;
569 else
570 base = ROUND_ADDR( addr );
571 size = (((UINT32)addr + size + page_mask) & ~page_mask) - base;
572 if (base + size < base) /* Disallow wrap-around */
574 SetLastError( ERROR_INVALID_PARAMETER );
575 return NULL;
578 else
580 base = 0;
581 size = (size + page_mask) & ~page_mask;
584 if (type & MEM_TOP_DOWN) {
585 /* FIXME: MEM_TOP_DOWN allocates the largest possible address.
586 * Is there _ANY_ way to do it with UNIX mmap()?
588 WARN(virtual,"MEM_TOP_DOWN ignored\n");
589 type &= ~MEM_TOP_DOWN;
591 /* Compute the protection flags */
593 if (!(type & (MEM_COMMIT | MEM_RESERVE)) ||
594 (type & ~(MEM_COMMIT | MEM_RESERVE)))
596 SetLastError( ERROR_INVALID_PARAMETER );
597 return NULL;
599 if (type & MEM_COMMIT)
600 vprot = VIRTUAL_GetProt( protect ) | VPROT_COMMITTED;
601 else vprot = 0;
603 /* Reserve the memory */
605 if ((type & MEM_RESERVE) || !base)
607 view_size = size + (base ? 0 : granularity_mask + 1);
608 ptr = (UINT32)FILE_dommap( NULL, -1, (LPVOID)base, 0, view_size, 0, 0,
609 VIRTUAL_GetUnixProt( vprot ), MAP_PRIVATE );
610 if (ptr == (UINT32)-1)
612 SetLastError( ERROR_OUTOFMEMORY );
613 return NULL;
615 if (!base)
617 /* Release the extra memory while keeping the range */
618 /* starting on a 64k boundary. */
620 if (ptr & granularity_mask)
622 UINT32 extra = granularity_mask + 1 - (ptr & granularity_mask);
623 FILE_munmap( (void *)ptr, 0, extra );
624 ptr += extra;
625 view_size -= extra;
627 if (view_size > size)
628 FILE_munmap( (void *)(ptr + size), 0, view_size - size );
630 else if (ptr != base)
632 /* We couldn't get the address we wanted */
633 FILE_munmap( (void *)ptr, 0, view_size );
634 SetLastError( ERROR_INVALID_ADDRESS );
635 return NULL;
637 if (!(view = VIRTUAL_CreateView( ptr, size, 0, 0, vprot, NULL )))
639 FILE_munmap( (void *)ptr, 0, size );
640 SetLastError( ERROR_OUTOFMEMORY );
641 return NULL;
643 VIRTUAL_DEBUG_DUMP_VIEW( view );
644 return (LPVOID)ptr;
647 /* Commit the pages */
649 if (!(view = VIRTUAL_FindView( base )) ||
650 (base + size > view->base + view->size))
652 SetLastError( ERROR_INVALID_PARAMETER );
653 return NULL;
656 if (!VIRTUAL_SetProt( view, base, size, vprot )) return NULL;
657 return (LPVOID)base;
661 /***********************************************************************
662 * VirtualFree (KERNEL32.550)
663 * Release or decommits a region of pages in virtual address space.
665 * RETURNS
666 * TRUE: Success
667 * FALSE: Failure
669 BOOL32 WINAPI VirtualFree(
670 LPVOID addr, /* [in] Address of region of committed pages */
671 DWORD size, /* [in] Size of region */
672 DWORD type /* [in] Type of operation */
674 FILE_VIEW *view;
675 UINT32 base;
677 TRACE(virtual, "%08x %08lx %lx\n",
678 (UINT32)addr, size, type );
680 /* Fix the parameters */
682 size = ROUND_SIZE( addr, size );
683 base = ROUND_ADDR( addr );
685 if (!(view = VIRTUAL_FindView( base )) ||
686 (base + size > view->base + view->size))
688 SetLastError( ERROR_INVALID_PARAMETER );
689 return FALSE;
692 /* Compute the protection flags */
694 if ((type != MEM_DECOMMIT) && (type != MEM_RELEASE))
696 SetLastError( ERROR_INVALID_PARAMETER );
697 return FALSE;
700 /* Free the pages */
702 if (type == MEM_RELEASE)
704 if (size || (base != view->base))
706 SetLastError( ERROR_INVALID_PARAMETER );
707 return FALSE;
709 VIRTUAL_DeleteView( view );
710 return TRUE;
713 /* Decommit the pages */
714 return VIRTUAL_SetProt( view, base, size, 0 );
718 /***********************************************************************
719 * VirtualLock (KERNEL32.551)
720 * Locks the specified region of virtual address space
722 * NOTE
723 * Always returns TRUE
725 * RETURNS
726 * TRUE: Success
727 * FALSE: Failure
729 BOOL32 WINAPI VirtualLock(
730 LPVOID addr, /* [in] Address of first byte of range to lock */
731 DWORD size /* [in] Number of bytes in range to lock */
733 return TRUE;
737 /***********************************************************************
738 * VirtualUnlock (KERNEL32.556)
739 * Unlocks a range of pages in the virtual address space
741 * NOTE
742 * Always returns TRUE
744 * RETURNS
745 * TRUE: Success
746 * FALSE: Failure
748 BOOL32 WINAPI VirtualUnlock(
749 LPVOID addr, /* [in] Address of first byte of range */
750 DWORD size /* [in] Number of bytes in range */
752 return TRUE;
756 /***********************************************************************
757 * VirtualProtect (KERNEL32.552)
758 * Changes the access protection on a region of committed pages
760 * RETURNS
761 * TRUE: Success
762 * FALSE: Failure
764 BOOL32 WINAPI VirtualProtect(
765 LPVOID addr, /* [in] Address of region of committed pages */
766 DWORD size, /* [in] Size of region */
767 DWORD new_prot, /* [in] Desired access protection */
768 LPDWORD old_prot /* [out] Address of variable to get old protection */
770 FILE_VIEW *view;
771 UINT32 base, i;
772 BYTE vprot, *p;
774 TRACE(virtual, "%08x %08lx %08lx\n",
775 (UINT32)addr, size, new_prot );
777 /* Fix the parameters */
779 size = ROUND_SIZE( addr, size );
780 base = ROUND_ADDR( addr );
782 if (!(view = VIRTUAL_FindView( base )) ||
783 (base + size > view->base + view->size))
785 SetLastError( ERROR_INVALID_PARAMETER );
786 return FALSE;
789 /* Make sure all the pages are committed */
791 p = view->prot + ((base - view->base) >> page_shift);
792 for (i = size >> page_shift; i; i--, p++)
794 if (!(*p & VPROT_COMMITTED))
796 SetLastError( ERROR_INVALID_PARAMETER );
797 return FALSE;
801 VIRTUAL_GetWin32Prot( view->prot[0], old_prot, NULL );
802 vprot = VIRTUAL_GetProt( new_prot ) | VPROT_COMMITTED;
803 return VIRTUAL_SetProt( view, base, size, vprot );
807 /***********************************************************************
808 * VirtualProtectEx (KERNEL32.553)
809 * Changes the access protection on a region of committed pages in the
810 * virtual address space of a specified process
812 * RETURNS
813 * TRUE: Success
814 * FALSE: Failure
816 BOOL32 WINAPI VirtualProtectEx(
817 HANDLE32 handle, /* [in] Handle of process */
818 LPVOID addr, /* [in] Address of region of committed pages */
819 DWORD size, /* [in] Size of region */
820 DWORD new_prot, /* [in] Desired access protection */
821 LPDWORD old_prot /* [out] Address of variable to get old protection */
823 BOOL32 ret = FALSE;
825 PDB32 *pdb = PROCESS_GetPtr( handle, PROCESS_VM_OPERATION, NULL );
826 if (pdb)
828 if (pdb == PROCESS_Current())
829 ret = VirtualProtect( addr, size, new_prot, old_prot );
830 else
831 ERR(virtual,"Unsupported on other process\n");
832 K32OBJ_DecCount( &pdb->header );
834 return ret;
838 /***********************************************************************
839 * VirtualQuery (KERNEL32.554)
840 * Provides info about a range of pages in virtual address space
842 * RETURNS
843 * Number of bytes returned in information buffer
845 DWORD WINAPI VirtualQuery(
846 LPCVOID addr, /* [in] Address of region */
847 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
848 DWORD len /* [in] Size of buffer */
850 FILE_VIEW *view = VIRTUAL_FirstView;
851 UINT32 base = ROUND_ADDR( addr );
852 UINT32 alloc_base = 0;
853 UINT32 size = 0;
855 /* Find the view containing the address */
857 for (;;)
859 if (!view)
861 size = 0xffff0000 - alloc_base;
862 break;
864 if (view->base > base)
866 size = view->base - alloc_base;
867 view = NULL;
868 break;
870 if (view->base + view->size > base)
872 alloc_base = view->base;
873 size = view->size;
874 break;
876 alloc_base = view->base + view->size;
877 view = view->next;
880 /* Fill the info structure */
882 if (!view)
884 info->State = MEM_FREE;
885 info->Protect = 0;
886 info->AllocationProtect = 0;
887 info->Type = 0;
889 else
891 BYTE vprot = view->prot[(base - alloc_base) >> page_shift];
892 VIRTUAL_GetWin32Prot( vprot, &info->Protect, &info->State );
893 for (size = base - alloc_base; size < view->size; size += page_mask+1)
894 if (view->prot[size >> page_shift] != vprot) break;
895 info->AllocationProtect = view->protect;
896 info->Type = MEM_PRIVATE; /* FIXME */
899 info->BaseAddress = (LPVOID)base;
900 info->AllocationBase = (LPVOID)alloc_base;
901 info->RegionSize = size - (base - alloc_base);
902 return sizeof(*info);
906 /***********************************************************************
907 * VirtualQueryEx (KERNEL32.555)
908 * Provides info about a range of pages in virtual address space of a
909 * specified process
911 * RETURNS
912 * Number of bytes returned in information buffer
914 DWORD WINAPI VirtualQueryEx(
915 HANDLE32 handle, /* [in] Handle of process */
916 LPCVOID addr, /* [in] Address of region */
917 LPMEMORY_BASIC_INFORMATION info, /* [out] Address of info buffer */
918 DWORD len /* [in] Size of buffer */
920 DWORD ret = len;
922 PDB32 *pdb = PROCESS_GetPtr( handle, PROCESS_QUERY_INFORMATION, NULL );
923 if (pdb)
925 if (pdb == PROCESS_Current())
926 ret = VirtualQuery( addr, info, len );
927 else
928 ERR(virtual,"Unsupported on other process\n");
929 K32OBJ_DecCount( &pdb->header );
931 return ret;
935 /***********************************************************************
936 * IsBadReadPtr32 (KERNEL32.354)
938 * RETURNS
939 * FALSE: Process has read access to entire block
940 * TRUE: Otherwise
942 BOOL32 WINAPI IsBadReadPtr32(
943 LPCVOID ptr, /* Address of memory block */
944 UINT32 size /* Size of block */
946 return !VIRTUAL_CheckFlags( (UINT32)ptr, size,
947 VPROT_READ | VPROT_COMMITTED );
951 /***********************************************************************
952 * IsBadWritePtr32 (KERNEL32.357)
954 * RETURNS
955 * FALSE: Process has write access to entire block
956 * TRUE: Otherwise
958 BOOL32 WINAPI IsBadWritePtr32(
959 LPVOID ptr, /* [in] Address of memory block */
960 UINT32 size /* [in] Size of block in bytes */
962 return !VIRTUAL_CheckFlags( (UINT32)ptr, size,
963 VPROT_WRITE | VPROT_COMMITTED );
967 /***********************************************************************
968 * IsBadHugeReadPtr32 (KERNEL32.352)
969 * RETURNS
970 * FALSE: Process has read access to entire block
971 * TRUE: Otherwise
973 BOOL32 WINAPI IsBadHugeReadPtr32(
974 LPCVOID ptr, /* [in] Address of memory block */
975 UINT32 size /* [in] Size of block */
977 return IsBadReadPtr32( ptr, size );
981 /***********************************************************************
982 * IsBadHugeWritePtr32 (KERNEL32.353)
983 * RETURNS
984 * FALSE: Process has write access to entire block
985 * TRUE: Otherwise
987 BOOL32 WINAPI IsBadHugeWritePtr32(
988 LPVOID ptr, /* [in] Address of memory block */
989 UINT32 size /* [in] Size of block */
991 return IsBadWritePtr32( ptr, size );
995 /***********************************************************************
996 * IsBadCodePtr32 (KERNEL32.351)
998 * RETURNS
999 * FALSE: Process has read access to specified memory
1000 * TRUE: Otherwise
1002 BOOL32 WINAPI IsBadCodePtr32(
1003 FARPROC32 ptr /* [in] Address of function */
1005 return !VIRTUAL_CheckFlags( (UINT32)ptr, 1, VPROT_EXEC | VPROT_COMMITTED );
1009 /***********************************************************************
1010 * IsBadStringPtr32A (KERNEL32.355)
1012 * RETURNS
1013 * FALSE: Read access to all bytes in string
1014 * TRUE: Else
1016 BOOL32 WINAPI IsBadStringPtr32A(
1017 LPCSTR str, /* [in] Address of string */
1018 UINT32 max /* [in] Maximum size of string */
1020 FILE_VIEW *view;
1021 UINT32 page, count;
1023 if (!max) return FALSE;
1024 if (!(view = VIRTUAL_FindView( (UINT32)str ))) return TRUE;
1025 page = ((UINT32)str - view->base) >> page_shift;
1026 count = page_mask + 1 - ((UINT32)str & page_mask);
1028 while (max)
1030 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1031 (VPROT_READ | VPROT_COMMITTED))
1032 return TRUE;
1033 if (count > max) count = max;
1034 max -= count;
1035 while (count--) if (!*str++) return FALSE;
1036 if (++page >= view->size >> page_shift) return TRUE;
1037 count = page_mask + 1;
1039 return FALSE;
1043 /***********************************************************************
1044 * IsBadStringPtr32W (KERNEL32.356)
1045 * See IsBadStringPtr32A
1047 BOOL32 WINAPI IsBadStringPtr32W( LPCWSTR str, UINT32 max )
1049 FILE_VIEW *view;
1050 UINT32 page, count;
1052 if (!max) return FALSE;
1053 if (!(view = VIRTUAL_FindView( (UINT32)str ))) return TRUE;
1054 page = ((UINT32)str - view->base) >> page_shift;
1055 count = (page_mask + 1 - ((UINT32)str & page_mask)) / sizeof(WCHAR);
1057 while (max)
1059 if ((view->prot[page] & (VPROT_READ | VPROT_COMMITTED)) !=
1060 (VPROT_READ | VPROT_COMMITTED))
1061 return TRUE;
1062 if (count > max) count = max;
1063 max -= count;
1064 while (count--) if (!*str++) return FALSE;
1065 if (++page >= view->size >> page_shift) return TRUE;
1066 count = (page_mask + 1) / sizeof(WCHAR);
1068 return FALSE;
1072 /***********************************************************************
1073 * CreateFileMapping32A (KERNEL32.46)
1074 * Creates a named or unnamed file-mapping object for the specified file
1076 * RETURNS
1077 * Handle: Success
1078 * 0: Mapping object does not exist
1079 * NULL: Failure
1081 HANDLE32 WINAPI CreateFileMapping32A(
1082 HFILE32 hFile, /* [in] Handle of file to map */
1083 SECURITY_ATTRIBUTES *sa, /* [in] Optional security attributes*/
1084 DWORD protect, /* [in] Protection for mapping object */
1085 DWORD size_high, /* [in] High-order 32 bits of object size */
1086 DWORD size_low, /* [in] Low-order 32 bits of object size */
1087 LPCSTR name /* [in] Name of file-mapping object */ )
1089 FILE_MAPPING *mapping = NULL;
1090 int unix_handle = -1;
1091 HANDLE32 handle;
1092 BYTE vprot;
1093 BOOL32 inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
1095 /* First search for an object with the same name */
1097 K32OBJ *obj = K32OBJ_FindName( name );
1099 if (obj)
1101 if (obj->type == K32OBJ_MEM_MAPPED_FILE)
1103 SetLastError( ERROR_ALREADY_EXISTS );
1104 handle = HANDLE_Alloc( PROCESS_Current(), obj,
1105 FILE_MAP_ALL_ACCESS /*FIXME*/, inherit, -1 );
1107 else
1109 SetLastError( ERROR_DUP_NAME );
1110 handle = 0;
1112 K32OBJ_DecCount( obj );
1113 return handle;
1116 /* Check parameters */
1118 TRACE(virtual,"(%x,%p,%08lx,%08lx%08lx,%s)\n",
1119 hFile, sa, protect, size_high, size_low, debugstr_a(name) );
1121 vprot = VIRTUAL_GetProt( protect );
1122 if (protect & SEC_RESERVE)
1124 if (hFile != INVALID_HANDLE_VALUE32)
1126 SetLastError( ERROR_INVALID_PARAMETER );
1127 return 0;
1130 else vprot |= VPROT_COMMITTED;
1131 if (protect & SEC_NOCACHE) vprot |= VPROT_NOCACHE;
1133 /* Compute the size and extend the file if necessary */
1135 if (hFile == INVALID_HANDLE_VALUE32)
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(
1150 buf,
1151 GENERIC_READ|GENERIC_WRITE,
1152 FILE_SHARE_READ|FILE_SHARE_WRITE,/* so we can reuse the tmpfn */
1153 NULL,
1154 OPEN_ALWAYS,
1158 /* FIXME: bad hack to avoid lots of leftover tempfiles */
1159 DeleteFile32A(buf);
1160 if (hFile == INVALID_HANDLE_VALUE32)
1161 FIXME(virtual,"could not create temp. file for anon shared mapping: reason was 0x%08lx\n",GetLastError());
1164 if (hFile != INVALID_HANDLE_VALUE32) /* We have a file */
1166 BY_HANDLE_FILE_INFORMATION info;
1167 DWORD access = GENERIC_READ;
1169 if (((protect & 0xff) == PAGE_READWRITE) ||
1170 ((protect & 0xff) == PAGE_WRITECOPY) ||
1171 ((protect & 0xff) == PAGE_EXECUTE_READWRITE) ||
1172 ((protect & 0xff) == PAGE_EXECUTE_WRITECOPY))
1173 access |= GENERIC_WRITE;
1174 if (!(obj = HANDLE_GetObjPtr( PROCESS_Current(), hFile,
1175 K32OBJ_FILE, access, NULL )))
1176 goto error;
1177 if ((unix_handle = FILE_GetUnixHandle( hFile, access )) == -1) goto error;
1178 if (!GetFileInformationByHandle( hFile, &info )) goto error;
1179 if (!size_high && !size_low)
1181 size_high = info.nFileSizeHigh;
1182 size_low = info.nFileSizeLow;
1184 else if ((size_high > info.nFileSizeHigh) ||
1185 ((size_high == info.nFileSizeHigh) &&
1186 (size_low > info.nFileSizeLow)))
1188 /* We have to grow the file */
1189 if (SetFilePointer( hFile, size_low, &size_high,
1190 FILE_BEGIN ) == 0xffffffff) goto error;
1191 if (!SetEndOfFile( hFile )) goto error;
1195 /* Allocate the mapping object */
1197 if (!(mapping = HeapAlloc( SystemHeap, 0, sizeof(*mapping) ))) goto error;
1198 mapping->header.type = K32OBJ_MEM_MAPPED_FILE;
1199 mapping->header.refcount = 1;
1200 mapping->protect = vprot;
1201 mapping->size_high = size_high;
1202 mapping->size_low = ROUND_SIZE( 0, size_low );
1203 mapping->file = (FILE_OBJECT *)obj;
1204 mapping->unix_handle = unix_handle;
1206 if (!K32OBJ_AddName( &mapping->header, name )) handle = 0;
1207 else handle = HANDLE_Alloc( PROCESS_Current(), &mapping->header,
1208 FILE_MAP_ALL_ACCESS /*FIXME*/, inherit, -1 );
1209 K32OBJ_DecCount( &mapping->header );
1210 SetLastError(0); /* Last error value is relevant. (see the start of fun) */
1211 return handle;
1213 error:
1214 if (obj) K32OBJ_DecCount( obj );
1215 if (unix_handle != -1) close( unix_handle );
1216 if (mapping) HeapFree( SystemHeap, 0, mapping );
1217 return 0;
1221 /***********************************************************************
1222 * CreateFileMapping32W (KERNEL32.47)
1223 * See CreateFileMapping32A
1225 HANDLE32 WINAPI CreateFileMapping32W( HFILE32 hFile, LPSECURITY_ATTRIBUTES attr,
1226 DWORD protect, DWORD size_high,
1227 DWORD size_low, LPCWSTR name )
1229 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1230 HANDLE32 ret = CreateFileMapping32A( hFile, attr, protect,
1231 size_high, size_low, nameA );
1232 HeapFree( GetProcessHeap(), 0, nameA );
1233 return ret;
1237 /***********************************************************************
1238 * OpenFileMapping32A (KERNEL32.397)
1239 * Opens a named file-mapping object.
1241 * RETURNS
1242 * Handle: Success
1243 * NULL: Failure
1245 HANDLE32 WINAPI OpenFileMapping32A(
1246 DWORD access, /* [in] Access mode */
1247 BOOL32 inherit, /* [in] Inherit flag */
1248 LPCSTR name /* [in] Name of file-mapping object */
1250 HANDLE32 handle = 0;
1251 K32OBJ *obj;
1252 SYSTEM_LOCK();
1253 if ((obj = K32OBJ_FindNameType( name, K32OBJ_MEM_MAPPED_FILE )))
1255 handle = HANDLE_Alloc( PROCESS_Current(), obj, access, inherit, -1 );
1256 K32OBJ_DecCount( obj );
1258 SYSTEM_UNLOCK();
1259 return handle;
1263 /***********************************************************************
1264 * OpenFileMapping32W (KERNEL32.398)
1265 * See OpenFileMapping32A
1267 HANDLE32 WINAPI OpenFileMapping32W( DWORD access, BOOL32 inherit, LPCWSTR name)
1269 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1270 HANDLE32 ret = OpenFileMapping32A( access, inherit, nameA );
1271 HeapFree( GetProcessHeap(), 0, nameA );
1272 return ret;
1276 /***********************************************************************
1277 * VIRTUAL_DestroyMapping
1279 * Destroy a FILE_MAPPING object.
1281 static void VIRTUAL_DestroyMapping( K32OBJ *ptr )
1283 FILE_MAPPING *mapping = (FILE_MAPPING *)ptr;
1284 assert( ptr->type == K32OBJ_MEM_MAPPED_FILE );
1286 if (mapping->file) K32OBJ_DecCount( &mapping->file->header );
1287 if (mapping->unix_handle != -1) close( mapping->unix_handle );
1288 ptr->type = K32OBJ_UNKNOWN;
1289 HeapFree( SystemHeap, 0, mapping );
1293 /***********************************************************************
1294 * MapViewOfFile (KERNEL32.385)
1295 * Maps a view of a file into the address space
1297 * RETURNS
1298 * Starting address of mapped view
1299 * NULL: Failure
1301 LPVOID WINAPI MapViewOfFile(
1302 HANDLE32 mapping, /* [in] File-mapping object to map */
1303 DWORD access, /* [in] Access mode */
1304 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1305 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1306 DWORD count /* [in] Number of bytes to map */
1308 return MapViewOfFileEx( mapping, access, offset_high,
1309 offset_low, count, NULL );
1313 /***********************************************************************
1314 * MapViewOfFileEx (KERNEL32.386)
1315 * Maps a view of a file into the address space
1317 * RETURNS
1318 * Starting address of mapped view
1319 * NULL: Failure
1321 LPVOID WINAPI MapViewOfFileEx(
1322 HANDLE32 handle, /* [in] File-mapping object to map */
1323 DWORD access, /* [in] Access mode */
1324 DWORD offset_high, /* [in] High-order 32 bits of file offset */
1325 DWORD offset_low, /* [in] Low-order 32 bits of file offset */
1326 DWORD count, /* [in] Number of bytes to map */
1327 LPVOID addr /* [in] Suggested starting address for mapped view */
1329 FILE_MAPPING *mapping;
1330 FILE_VIEW *view;
1331 UINT32 ptr = (UINT32)-1, size = 0;
1332 int flags = MAP_PRIVATE;
1334 /* Check parameters */
1336 if ((offset_low & granularity_mask) ||
1337 (addr && ((UINT32)addr & granularity_mask)))
1339 SetLastError( ERROR_INVALID_PARAMETER );
1340 return NULL;
1343 if (!(mapping = (FILE_MAPPING *)HANDLE_GetObjPtr( PROCESS_Current(),
1344 handle,
1345 K32OBJ_MEM_MAPPED_FILE,
1346 0 /* FIXME */, NULL )))
1347 return NULL;
1349 if (mapping->size_high || offset_high)
1350 ERR(virtual, "Offsets larger than 4Gb not supported\n");
1352 if ((offset_low >= mapping->size_low) ||
1353 (count > mapping->size_low - offset_low))
1355 SetLastError( ERROR_INVALID_PARAMETER );
1356 goto error;
1358 if (count) size = ROUND_SIZE( offset_low, count );
1359 else size = mapping->size_low - offset_low;
1361 switch(access)
1363 case FILE_MAP_ALL_ACCESS:
1364 case FILE_MAP_WRITE:
1365 case FILE_MAP_WRITE | FILE_MAP_READ:
1366 if (!(mapping->protect & VPROT_WRITE))
1368 SetLastError( ERROR_INVALID_PARAMETER );
1369 goto error;
1371 flags = MAP_SHARED;
1372 /* fall through */
1373 case FILE_MAP_READ:
1374 case FILE_MAP_COPY:
1375 case FILE_MAP_COPY | FILE_MAP_READ:
1376 if (mapping->protect & VPROT_READ) break;
1377 /* fall through */
1378 default:
1379 SetLastError( ERROR_INVALID_PARAMETER );
1380 goto error;
1383 /* Map the file */
1385 TRACE(virtual, "handle=%x size=%x offset=%lx\n",
1386 handle, size, offset_low );
1388 ptr = (UINT32)FILE_dommap( mapping->file, mapping->unix_handle,
1389 addr, 0, size, 0, offset_low,
1390 VIRTUAL_GetUnixProt( mapping->protect ),
1391 flags );
1392 if (ptr == (UINT32)-1) {
1393 /* KB: Q125713, 25-SEP-1995, "Common File Mapping Problems and
1394 * Platform Differences":
1395 * Windows NT: ERROR_INVALID_PARAMETER
1396 * Windows 95: ERROR_INVALID_ADDRESS.
1397 * FIXME: So should we add a module dependend check here? -MM
1399 if (errno==ENOMEM)
1400 SetLastError( ERROR_OUTOFMEMORY );
1401 else
1402 SetLastError( ERROR_INVALID_PARAMETER );
1403 goto error;
1406 if (!(view = VIRTUAL_CreateView( ptr, size, offset_low, 0,
1407 mapping->protect, mapping )))
1409 SetLastError( ERROR_OUTOFMEMORY );
1410 goto error;
1412 return (LPVOID)ptr;
1414 error:
1415 if (ptr != (UINT32)-1) FILE_munmap( (void *)ptr, 0, size );
1416 K32OBJ_DecCount( &mapping->header );
1417 return NULL;
1421 /***********************************************************************
1422 * FlushViewOfFile (KERNEL32.262)
1423 * Writes to the disk a byte range within a mapped view of a file
1425 * RETURNS
1426 * TRUE: Success
1427 * FALSE: Failure
1429 BOOL32 WINAPI FlushViewOfFile(
1430 LPCVOID base, /* [in] Start address of byte range to flush */
1431 DWORD cbFlush /* [in] Number of bytes in range */
1433 FILE_VIEW *view;
1434 UINT32 addr = ROUND_ADDR( base );
1436 TRACE(virtual, "FlushViewOfFile at %p for %ld bytes\n",
1437 base, cbFlush );
1439 if (!(view = VIRTUAL_FindView( addr )))
1441 SetLastError( ERROR_INVALID_PARAMETER );
1442 return FALSE;
1444 if (!cbFlush) cbFlush = view->size;
1445 if (!msync( (void *)addr, cbFlush, MS_SYNC )) return TRUE;
1446 SetLastError( ERROR_INVALID_PARAMETER );
1447 return FALSE;
1451 /***********************************************************************
1452 * UnmapViewOfFile (KERNEL32.540)
1453 * Unmaps a mapped view of a file.
1455 * NOTES
1456 * Should addr be an LPCVOID?
1458 * RETURNS
1459 * TRUE: Success
1460 * FALSE: Failure
1462 BOOL32 WINAPI UnmapViewOfFile(
1463 LPVOID addr /* [in] Address where mapped view begins */
1465 FILE_VIEW *view;
1466 UINT32 base = ROUND_ADDR( addr );
1467 if (!(view = VIRTUAL_FindView( base )) || (base != view->base))
1469 SetLastError( ERROR_INVALID_PARAMETER );
1470 return FALSE;
1472 VIRTUAL_DeleteView( view );
1473 return TRUE;
1476 /***********************************************************************
1477 * VIRTUAL_MapFileW
1479 * Helper function to map a file to memory:
1480 * name - file name
1481 * [RETURN] ptr - pointer to mapped file
1483 LPVOID VIRTUAL_MapFileW( LPCWSTR name )
1485 HANDLE32 hFile, hMapping;
1486 LPVOID ptr = NULL;
1488 hFile = CreateFile32W( name, GENERIC_READ, FILE_SHARE_READ, NULL,
1489 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
1490 if (hFile != INVALID_HANDLE_VALUE32)
1492 hMapping = CreateFileMapping32A( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1493 CloseHandle( hFile );
1494 if (hMapping)
1496 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
1497 CloseHandle( hMapping );
1500 return ptr;