source: trunk/src/kernel32/mmap.cpp@ 10572

Last change on this file since 10572 was 10572, checked in by sandervl, 21 years ago

Changed check for number of memory map views

File size: 36.3 KB
Line 
1/* $Id: mmap.cpp,v 1.72 2004-04-06 14:20:20 sandervl Exp $ */
2
3/*
4 * Win32 Memory mapped file & view classes
5 *
6 * Copyright 1999-2003 Sander van Leeuwen (sandervl@xs4all.nl)
7 *
8 * NOTE: Memory mapping DOES NOT work when kernel-mode code causes
9 * a pagefault in the memory mapped object. (exceptions aren't
10 * dispatched to our exception handler until after the kernel mode
11 * call returns (too late))
12 *
13 * NOTE: Are apps allowed to change the protection flags of memory mapped pages?
14 * I'm assuming they aren't for now.
15 *
16 * TODO: Handles returned should be usable by all apis that accept file handles
17 * TODO: Sharing memory mapped files between multiple processes
18 * TODO: Memory mapped files with views that extend the file (not 100% correct now)
19 * TODO: Suspend all threads when a page is committed (possible that another thread
20 * accesses the same memory before the page is read from disk
21 * TODO: File maps for new files (must select an initial size)!
22 *
23 * Project Odin Software License can be found in LICENSE.TXT
24 *
25 */
26#include <os2win.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <win\virtual.h>
31#include <odincrt.h>
32#include <handlemanager.h>
33#include "mmap.h"
34#include "oslibdos.h"
35#include "oslibmem.h"
36#include <winimagepeldr.h>
37#include <custombuild.h>
38#include "asmutil.h"
39
40#define DBG_LOCALLOG DBG_mmap
41#include "dbglocal.h"
42
43
44
45//Global DLL Data
46#pragma data_seg(_GLOBALDATA)
47Win32MemMap *Win32MemMap::memmaps = NULL;
48CRITICAL_SECTION_OS2 globalmapcritsect = {0};
49#pragma data_seg()
50
51
52static char *pszMMapSemName = MEMMAP_CRITSECTION_NAME;
53
54//******************************************************************************
55//******************************************************************************
56void WIN32API SetCustomMMapSemName(LPSTR pszSemName)
57{
58 pszMMapSemName = pszSemName;
59}
60//******************************************************************************
61//******************************************************************************
62void InitializeMemMaps()
63{
64 if(globalmapcritsect.hevLock == 0) {
65 dprintf(("InitializeMemMaps -> create shared critical section"));
66 }
67 else {
68 dprintf(("InitializeMemMaps -> access shared critical section"));
69 }
70 DosAccessCriticalSection(&globalmapcritsect, pszMMapSemName);
71}
72//******************************************************************************
73//******************************************************************************
74void FinalizeMemMaps()
75{
76 DosDeleteCriticalSection(&globalmapcritsect);
77}
78//******************************************************************************
79//******************************************************************************
80Win32MemMap::Win32MemMap(HANDLE hfile, ULONG size, ULONG fdwProtect, LPSTR lpszName)
81 : nrMappings(0), pMapping(NULL), mMapAccess(0), referenced(0),
82 image(0), pWriteBitmap(NULL), lpszFileName(NULL)
83{
84 DosEnterCriticalSection(&globalmapcritsect);
85 next = memmaps;
86 memmaps = this;
87 DosLeaveCriticalSection(&globalmapcritsect);
88
89 hMemFile = hOrgMemFile = hfile;
90
91 mSize = size;
92 mProtFlags = fdwProtect;
93
94 mProcessId = GetCurrentProcessId();
95
96 if(lpszName) {
97 lpszMapName = (char *)_smalloc(strlen(lpszName)+1);
98 strcpy(lpszMapName, lpszName);
99 }
100 else lpszMapName = NULL;
101 AddRef();
102}
103//******************************************************************************
104//Map constructor used for executable image maps (only used internally)
105//******************************************************************************
106Win32MemMap::Win32MemMap(Win32PeLdrImage *pImage, ULONG baseAddress, ULONG size)
107 : nrMappings(0), pMapping(NULL), mMapAccess(0), referenced(0),
108 image(0), pWriteBitmap(NULL), lpszFileName(NULL)
109{
110 DosEnterCriticalSection(&globalmapcritsect);
111 next = memmaps;
112 memmaps = this;
113 DosLeaveCriticalSection(&globalmapcritsect);
114
115 hMemFile = hOrgMemFile = -1;
116
117 mSize = size;
118 mProtFlags = PAGE_READWRITE;
119 mProcessId = GetCurrentProcessId();
120
121 pMapping = (LPVOID)baseAddress;
122
123 image = pImage;
124 lpszMapName= NULL;
125 AddRef();
126}
127//******************************************************************************
128//******************************************************************************
129BOOL Win32MemMap::Init(DWORD aMSize)
130{
131 mapMutex.enter();
132 if(hMemFile != -1)
133 {
134 lpszFileName = (char *)_smalloc(MMAP_MAX_FILENAME_LENGTH);
135 if(HMGetFileNameFromHandle(hMemFile, lpszFileName, MMAP_MAX_FILENAME_LENGTH) == FALSE) {
136 return FALSE;
137 }
138#if 0
139 if(DuplicateHandle(GetCurrentProcess(), hMemFile, GetCurrentProcess(),
140 &hMemFile, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE)
141#else
142 if(HMDuplicateHandle(GetCurrentProcess(), hMemFile, GetCurrentProcess(),
143 &hMemFile, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE)
144#endif
145 {
146 dprintf(("Win32MemMap::Init: DuplicateHandle failed!"));
147 goto fail;
148 }
149 mSize = SetFilePointer(hMemFile, 0, NULL, FILE_BEGIN);
150 mSize = SetFilePointer(hMemFile, 0, NULL, FILE_END);
151 if(mSize == -1) {
152 dprintf(("Win32MemMap::init: SetFilePointer failed to set pos end"));
153 goto fail;
154 }
155 if (mSize < aMSize)
156 {
157 dprintf(("Win32MemMap::init: file size %d, memory map size %d", mSize, aMSize));
158 //Froloff: Need to check if exist the possibility of file to memory
159 // mapping not from the beginning of file
160 mSize = SetFilePointer(hMemFile, aMSize, NULL, FILE_BEGIN);
161 // Commit filesize changes onto disk
162 SetEndOfFile(hMemFile);
163 }
164#if 0
165 //SvL: Temporary limitation of size (Warp Server Advanced doesn't allow
166 // one to reserve more than 450 MB (unless you override the virtual
167 // memory max limit) of continuous memory; (Warp 4 much less))
168 if(mSize > 64*1024*1024) {
169 mSize = 64*1024*1024;
170 }
171#endif
172 }
173 // Allocate the memory for the map right now
174 if(allocateMap() == FALSE) {
175 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
176 goto fail;
177 }
178
179 dprintf(("CreateFileMappingA for file %x, prot %x size %d, name %s", hMemFile, mProtFlags, mSize, lpszMapName));
180 mapMutex.leave();
181 return TRUE;
182fail:
183 mapMutex.leave();
184 return FALSE;
185}
186//******************************************************************************
187//******************************************************************************
188Win32MemMap::~Win32MemMap()
189{
190 Win32MemMapView::deleteViews(this); //delete all views of our memory mapped file
191
192 dprintf(("Win32MemMap dtor: deleting map %x %x", pMapping, mSize));
193
194 mapMutex.enter();
195 if(lpszMapName) {
196 free(lpszMapName);
197 }
198 if(lpszFileName) {
199 free(lpszFileName);
200 }
201 if(pMapping && !image) {
202 dprintf(("Free map memory"));
203 if(lpszMapName) {
204 OSLibDosFreeMem(pMapping);
205 }
206 else VirtualFree(pMapping, 0, MEM_RELEASE);
207
208 pMapping = NULL;
209 }
210 if(hMemFile != -1) {
211 dprintf(("Win32MemMap dtor: closing memory file %x", hMemFile));
212 CloseHandle(hMemFile);
213 hMemFile = -1;
214 }
215 if(pWriteBitmap) free(pWriteBitmap);
216
217 mapMutex.leave();
218
219 DosEnterCriticalSection(&globalmapcritsect);
220 Win32MemMap *map = memmaps;
221
222 if(map == this) {
223 memmaps = next;
224 }
225 else {
226 while(map->next) {
227 if(map->next == this)
228 break;
229 map = map->next;
230 }
231 if(map->next) {
232 map->next = next;
233 }
234 else dprintf(("Win32MemMap::~Win32MemMap: map not found!! (%x)", this));
235 }
236 DosLeaveCriticalSection(&globalmapcritsect);
237}
238//******************************************************************************
239//******************************************************************************
240int Win32MemMap::Release()
241{
242 dprintf(("Win32MemMap::Release %s (%d)", lpszMapName, referenced-1));
243 --referenced;
244 if(referenced == 0) {
245 delete this;
246 return 0;
247 }
248 return referenced;
249}
250//******************************************************************************
251// Win32MemMap::commitRange
252//
253// Commit a range of pages
254//
255// Parameters:
256//
257// ULONG ulFaultAddr - exception address
258// ULONG ulOffset - offset in memory map
259// BOOL fWriteAccess - TRUE -> write exception
260// FALSE -> read exception
261// int nrpages - number of pages
262//
263// Returns:
264// TRUE - success
265// FALSE - failure
266//
267//******************************************************************************
268BOOL Win32MemMap::commitRange(ULONG ulFaultAddr, ULONG offset, BOOL fWriteAccess, int nrpages)
269{
270 LPVOID lpPageFaultAddr = (LPVOID)((ULONG)pMapping + offset);
271 DWORD pageAddr = (DWORD)lpPageFaultAddr & ~0xFFF;
272
273 dprintf(("Win32MemMap::commitRange %x (faultaddr %x)", pageAddr, lpPageFaultAddr));
274
275 if(fWriteAccess)
276 {//writes are handled on a per-page basis
277 for(int i=0;i<nrpages;i++)
278 {
279 if(commitPage(ulFaultAddr, offset, TRUE, 1) == FALSE) {
280 dprintf(("Win32MemMap::commit: commitPage failed!!"));
281 return FALSE;
282 }
283 ulFaultAddr += PAGE_SIZE;
284 offset += PAGE_SIZE;
285 }
286 return TRUE;
287 }
288 else return commitPage(ulFaultAddr, offset, FALSE, nrpages);
289}
290//******************************************************************************
291// Win32MemMap::commitPage
292//
293// Handle a pagefault for a memory map
294//
295// Parameters:
296//
297// ULONG ulFaultAddr - exception address
298// ULONG ulOffset - offset in memory map
299// BOOL fWriteAccess - TRUE -> write exception
300// FALSE -> read exception
301// int nrpages - number of pages
302//
303// Returns:
304// TRUE - success
305// FALSE - failure
306//
307// NOTE:
308// We handle only one pages for write access!
309//
310// REMARKS:
311// We determine whether a page has been modified by checking it's protection flags
312// If the write flag is set, this means commitPage had to enable this due to a pagefault
313// (all pages are readonly until the app tries to write to it)
314//******************************************************************************
315BOOL Win32MemMap::commitPage(ULONG ulFaultAddr, ULONG offset, BOOL fWriteAccess, int nrpages)
316{
317 MEMORY_BASIC_INFORMATION memInfo;
318 LPVOID lpPageFaultAddr = (LPVOID)((ULONG)pMapping + offset);
319 DWORD pageAddr = (DWORD)lpPageFaultAddr & ~0xFFF;
320 DWORD oldProt, newProt, nrBytesRead;
321 int i;
322
323// mapMutex.enter();
324
325 if(image) {
326 return image->commitPage(pageAddr, fWriteAccess);
327 }
328
329 if(fWriteAccess && (mProtFlags & PAGE_WRITECOPY))
330 {//this is a COW map, call commitGuardPage to handle write faults
331 return commitGuardPage(ulFaultAddr, offset, fWriteAccess);
332 }
333
334 dprintf(("Win32MemMap::commitPage %x (faultaddr %x)", pageAddr, lpPageFaultAddr));
335
336 //align at page boundary
337 offset &= ~0xFFF;
338
339 //If it's a write access violation and the view is readonly, then fail
340 if(fWriteAccess) {
341 Win32MemMapView *view = Win32MemMapView::findView(ulFaultAddr);
342 if(view) {
343 if(!(view->getAccessFlags() & MEMMAP_ACCESS_WRITE)) {
344 dprintf(("Write access for a readonly view!!"));
345 return FALSE;
346 }
347 }
348 else {
349 DebugInt3(); //can't happen
350 return FALSE;
351 }
352 }
353
354 int faultsize = nrpages*PAGE_SIZE;
355
356 if(fWriteAccess)
357 {//write access needs special care, so do that on a per page basis
358 dprintf(("Write access -> handle only one page"));
359 faultsize = PAGE_SIZE;
360 }
361
362 offset = pageAddr - (ULONG)pMapping;
363 if(offset + faultsize > mSize) {
364 faultsize = mSize - offset;
365 }
366
367 while(faultsize)
368 {
369 if(VirtualQuery((LPSTR)pageAddr, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0) {
370 dprintf(("Win32MemMap::commitPage: VirtualQuery (%x,%x) failed for %x", pageAddr, nrpages*PAGE_SIZE));
371 goto fail;
372 }
373 memInfo.RegionSize = min(memInfo.RegionSize, faultsize);
374 //Only changes the state of the pages with the same attribute flags
375 //(returned in memInfo.RegionSize)
376 //If it's smaller than the mNrPages, it simply means one or more of the
377 //other pages have already been committed
378 if(!(memInfo.State & MEM_COMMIT))
379 {
380 if(VirtualAlloc((LPVOID)pageAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE) == FALSE) {
381 goto fail;
382 }
383
384 //Part of the memory map has been committed, so now we can change
385 //the protection flags of the aliases (DosSetMem fails for reserved pages)
386 updateViewPages(offset, memInfo.RegionSize, (fWriteAccess) ? PAGEVIEW_VIEW : PAGEVIEW_READONLY);
387
388 if(hMemFile != -1)
389 {//now read the page(s) from disk
390 DWORD size;
391
392 offset = pageAddr - (ULONG)pMapping;
393 size = memInfo.RegionSize;
394 if(offset + size > mSize) {
395 dprintf(("Adjusting size from %d to %d", size, mSize - offset));
396 size = mSize - offset;
397 }
398 if(SetFilePointer(hMemFile, offset, NULL, FILE_BEGIN) != offset) {
399 dprintf(("Win32MemMap::commitPage: SetFilePointer failed to set pos to %x", offset));
400 goto fail;
401 }
402 if(ReadFile(hMemFile, (LPSTR)pageAddr, size, &nrBytesRead, NULL) == FALSE) {
403 dprintf(("Win32MemMap::commitPage: ReadFile failed for %x", pageAddr));
404 goto fail;
405 }
406 if(nrBytesRead != size) {
407 dprintf(("Win32MemMap::commitPage: ReadFile didn't read all bytes for %x", pageAddr));
408 goto fail;
409 }
410 }
411 //We set the protection flags to PAGE_READONLY, unless this pagefault
412 //was due to a write access
413 //This way we can track dirty pages which need to be flushed to
414 //disk when FlushViewOfFile is called or the map is closed.
415 if(!fWriteAccess)
416 {
417 if(VirtualProtect((LPVOID)pageAddr, memInfo.RegionSize, PAGE_READONLY, &oldProt) == FALSE) {
418 dprintf(("VirtualProtect %x %x PAGE_READWRITE failed with %d!!", pageAddr, memInfo.RegionSize, GetLastError()));
419 goto fail;
420 }
421 }
422 else
423 {//make these pages as dirty
424 ULONG startPage = (pageAddr - (ULONG)pMapping) >> PAGE_SHIFT;
425 ULONG nrPages = memInfo.RegionSize >> PAGE_SHIFT;
426
427 if(memInfo.RegionSize & 0xFFF)
428 nrPages++;
429
430 dprintf(("Mark %d page(s) starting at %x as dirty", nrPages, pageAddr));
431 markDirtyPages(startPage, nrPages);
432
433 //Write access means that the next time the corresponding COW page
434 //is touched, we need to reload it. So set the GUARD flags.
435 updateViewPages(offset, memInfo.RegionSize, PAGEVIEW_GUARD);
436 }
437 }
438 else
439 if(fWriteAccess)
440 {
441 //mark these pages as dirty
442 ULONG startPage = (pageAddr - (ULONG)pMapping) >> PAGE_SHIFT;
443 ULONG nrPages = memInfo.RegionSize >> PAGE_SHIFT;
444
445 if(memInfo.RegionSize & 0xFFF)
446 nrPages++;
447
448 dprintf(("Mark %d page(s) starting at %x as dirty", nrPages, pageAddr));
449 markDirtyPages(startPage, nrPages);
450
451 //and turn on a write access
452 if(VirtualProtect((LPVOID)pageAddr, memInfo.RegionSize, PAGE_READWRITE, &oldProt) == FALSE) {
453 dprintf(("VirtualProtect %x %x PAGE_READWRITE failed with %d!!", pageAddr, memInfo.RegionSize, GetLastError()));
454 goto fail;
455 }
456 //Now change all the aliased pages according to their view protection flags
457 updateViewPages(offset, memInfo.RegionSize, PAGEVIEW_VIEW);
458
459 //Write access means that the next time the corresponding COW page
460 //is touched, we need to reload it. So set the GUARD flags.
461 updateViewPages(offset, memInfo.RegionSize, PAGEVIEW_GUARD);
462 }
463 faultsize -= memInfo.RegionSize;
464 pageAddr += memInfo.RegionSize;
465 }
466
467// mapMutex.leave();
468 return TRUE;
469fail:
470// mapMutex.leave();
471 return FALSE;
472}
473//******************************************************************************
474// Win32MemMap::commitGuardPage
475//
476// Handle a guard page exception for a copy-on-write view (one page only)
477//
478// Parameters:
479//
480// ULONG ulFaultAddr - exception address
481// ULONG ulOffset - offset in memory map
482// BOOL fWriteAccess - TRUE -> write exception
483// FALSE -> read exception
484//
485// Returns:
486// TRUE - success
487// FALSE - failure
488//
489//******************************************************************************
490BOOL Win32MemMap::commitGuardPage(ULONG ulFaultAddr, ULONG ulOffset, BOOL fWriteAccess)
491{
492 MEMORY_BASIC_INFORMATION memInfo;
493 BOOL ret;
494 DWORD pageAddr = ulFaultAddr & ~0xFFF;
495 DWORD dwNewProt, dwOldProt;
496
497 dprintf(("Win32MemMap::commitGuardPage %x (faultaddr %x)", pageAddr, ulFaultAddr));
498
499 //align at page boundary
500 ulOffset &= ~0xFFF;
501
502 //commit a single page in the original mapping (pretend read access)
503 ret = commitPage(ulFaultAddr, ulOffset, FALSE, 1);
504 if(ret == FALSE) {
505 DebugInt3();
506 goto fail;
507 }
508 //clear PAGE_GUARD flag, since this page must now be made accessible
509 dwNewProt = mProtFlags & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY);
510 if(dwNewProt & PAGE_WRITECOPY) {
511 dwNewProt |= PAGE_GUARD;
512 }
513 dwNewProt &= ~PAGE_GUARD;
514 if(VirtualProtect((LPVOID)pageAddr, PAGE_SIZE, dwNewProt, &dwOldProt) == FALSE) {
515 dprintf(("Win32MemMap::commitGuardPage: VirtualProtect %x 0x1000 %x failed!!", pageAddr, dwNewProt));
516 goto fail;
517 }
518 //copy the data from the original mapping to the COW page
519 memcpy((LPVOID)pageAddr, (char *)pMapping+ulOffset, PAGE_SIZE);
520
521 if(fWriteAccess)
522 {//copy on write; mark pages as private
523 DWORD startpage = (ulOffset) >> PAGE_SHIFT;
524
525 dprintf(("Win32MemMap::commitGuardPage: write access -> mark page as private"));
526
527 Win32MemMapView *view = Win32MemMapView::findView(ulFaultAddr);
528 if(view)
529 {
530 view->markCOWPages(startpage, 1);
531 }
532 else DebugInt3(); //oh, oh
533 }
534 else
535 {//read access; must set the map + all views to READONLY to track write access
536
537 dprintf(("Win32MemMap::commitGuardPage: read access -> set page as READONLY in map + all views"));
538
539 //first the memory map page
540 if(VirtualProtect((LPVOID)pageAddr, PAGE_SIZE, PAGE_READONLY, &dwOldProt) == FALSE) {
541 dprintf(("Win32MemMap::commitGuardPage: VirtualProtect %x 0x1000 %x failed!!", pageAddr, dwNewProt));
542 goto fail;
543 }
544 //now for any views that exist
545 updateViewPages(ulOffset, PAGE_SIZE, PAGEVIEW_READONLY);
546 }
547
548 return TRUE;
549fail:
550 return FALSE;
551}
552//******************************************************************************
553// Win32MemMap::updateViewPages
554//
555// Update the page flags of all views
556//
557// Parameters:
558//
559// ULONG offset - offset in memory map
560// ULONG size - range size
561// PAGEVIEW flags - page flags
562// PAGEVIEW_READONLY -> set page flags to readonly
563// PAGEVIEW_VIEW -> set page flags to view default
564// PAGEVIEW_GUARD -> set page flags of COW view to GUARD
565//
566// Returns:
567// TRUE - success
568// FALSE - failure
569//
570//******************************************************************************
571BOOL Win32MemMap::updateViewPages(ULONG offset, ULONG size, PAGEVIEW flags)
572{
573 Win32MemMapView **views = (Win32MemMapView **)alloca(sizeof(Win32MemMapView*)*nrMappings);
574 int localmaps;
575
576 if(views)
577 {
578 localmaps = Win32MemMapView::findViews(this, nrMappings, views);
579 if(localmaps <= nrMappings)
580 {
581 for(int i=0;i<localmaps;i++)
582 {
583 views[i]->changePageFlags(offset, size, flags);
584 }
585 }
586 else {
587 dprintf(("unexpected number of views %d vs %d", localmaps, nrMappings));
588 DebugInt3(); //oh, oh
589 }
590 }
591 return TRUE;
592}
593//******************************************************************************
594// Win32MemMap::invalidatePages
595//
596// Invalidate map pages. (called by WriteFile)
597//
598// Parameters:
599//
600// ULONG offset - offset in memory map
601// ULONG size - invalid range size
602//
603// Returns:
604// TRUE - success
605// FALSE - failure
606//
607//******************************************************************************
608BOOL Win32MemMap::invalidatePages(ULONG offset, ULONG size)
609{
610 ULONG diff = offset & 0xFFF;
611 BOOL ret;
612
613 offset &= ~0xFFF;
614 size += diff;
615
616 dprintf(("Win32MemMap::invalidatePages %x %x", offset, size));
617 ret = VirtualFree((LPSTR)pMapping + offset, size, MEM_DECOMMIT);
618 if(ret == FALSE) {
619 dprintf(("ERROR: Win32MemMap::invalidatePages: VirtualFree failed!!"));
620 }
621 //invalidate all shared COW pages too by setting the GUARD flag
622 //(which forces a resync the next time the app touches them)
623 return updateViewPages(offset, size, PAGEVIEW_GUARD);
624}
625//******************************************************************************
626// Win32MemMap::allocateMap
627//
628// Allocate memory for the map if not yet already done.
629//
630// Returns:
631// FALSE - success
632// TRUE - failure
633//
634//******************************************************************************
635BOOL Win32MemMap::allocateMap()
636{
637 ULONG fAlloc = 0;
638
639 fAlloc = MEM_RESERVE;
640
641 //Memory has already been allocated for executable image maps (only used internally)
642 if(!pMapping && nrMappings == 0)
643 {//if not mapped, reserve/commit entire view
644 //SvL: Always read/write access or else ReadFile will crash once we
645 // start committing pages.
646 // This is most likely an OS/2 bug and doesn't happen in Aurora
647 // when allocating memory with the PAG_ANY bit set. (without this
648 // flag it will also crash)
649 //NOTE: If this is ever changed, then we must update setProtFlags!!!!
650
651 //All named file mappings are shared (files & memory only)
652 if(lpszMapName) {
653 pMapping = VirtualAllocShared(mSize, fAlloc, PAGE_READWRITE, lpszMapName);
654 }
655 else {
656 pMapping = VirtualAlloc(0, mSize, fAlloc, PAGE_READWRITE);
657 }
658 if(pMapping == NULL) {
659 dprintf(("Win32MemMap::mapViewOfFile: VirtualAlloc %x %x failed!", mSize, fAlloc));
660 goto fail;
661 }
662 //Windows NT seems to commit memory for memory maps, regardsless of the SEC_COMMIT flag
663 if((hMemFile == -1 && !image)) {//commit memory
664 VirtualAlloc(pMapping, mSize, MEM_COMMIT, PAGE_READWRITE);
665 }
666
667 DWORD nrPages = mSize >> PAGE_SHIFT;
668 if(mSize & 0xFFF)
669 nrPages++;
670
671 if(hMemFile != -1 && (mProtFlags & SEC_COMMIT)) {
672 commitPage((ULONG)pMapping, 0, FALSE, nrPages);
673 }
674 //Allocate bitmap for all pages to keep track of write access (file maps only)
675 //Necessary for FlushViewOfFile.
676 if(hMemFile != -1) {
677 int sizebitmap = nrPages/8 + 1;
678
679 pWriteBitmap = (char *)_smalloc(sizebitmap);
680 if(pWriteBitmap == NULL) {
681 DebugInt3();
682 goto fail;
683 }
684 memset(pWriteBitmap, 0, sizebitmap);
685 }
686 }
687 return TRUE;
688
689fail:
690 return FALSE;
691}
692//******************************************************************************
693// Win32MemMap::mapViewOfFile
694//
695// Map the view identified by addr
696//
697// Parameters:
698//
699// ULONG size - size of view
700// ULONG offset - offset in memory map
701// ULONG fdwAccess - access flags
702// FILE_MAP_WRITE, FILE_MAP_READ, FILE_MAP_COPY
703// FILE_MAP_ALL_ACCESS
704//
705//
706// Returns:
707// <>NULL - success, view address
708// NULL - failure
709//
710//******************************************************************************
711LPVOID Win32MemMap::mapViewOfFile(ULONG size, ULONG offset, ULONG fdwAccess)
712{
713 DWORD processId = GetCurrentProcessId();
714
715 mapMutex.enter();
716 ULONG memFlags = (mProtFlags & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY));
717 Win32MemMapView *mapview;
718
719 //@@@PH: if(fdwAccess & ~(FILE_MAP_WRITE|FILE_MAP_READ|FILE_MAP_COPY))
720 // Docs say FILE_MAP_ALL_ACCESS is same as FILE_MAP_WRITE. Doesn't match reality though.
721 if(fdwAccess & ~FILE_MAP_ALL_ACCESS)
722 goto parmfail;
723 if((fdwAccess & FILE_MAP_WRITE) && !(mProtFlags & PAGE_READWRITE))
724 goto parmfail;
725 if((fdwAccess & FILE_MAP_READ) && !(mProtFlags & (PAGE_READWRITE|PAGE_READONLY)))
726 goto parmfail;
727
728 if (fdwAccess != FILE_MAP_ALL_ACCESS)
729 if((fdwAccess & FILE_MAP_COPY) && !(mProtFlags & PAGE_WRITECOPY))
730 goto parmfail;
731
732 if(offset+size > mSize && (!(fdwAccess & FILE_MAP_WRITE) || hMemFile == -1))
733 goto parmfail;
734
735 //SvL: TODO: Doesn't work for multiple views
736 if(offset+size > mSize) {
737 mSize = offset+size;
738 }
739
740 mapview = new Win32MemMapView(this, offset, (size == 0) ? (mSize - offset) : size, fdwAccess);
741 if(mapview == NULL) {
742 goto fail;
743 }
744 if(mapview->everythingOk() == FALSE) {
745 dprintf(("Win32MemMap::mapViewOfFile: !mapview->everythingOk"));
746 delete mapview;
747 goto fail;
748 }
749 mapMutex.leave();
750 SetLastError(ERROR_SUCCESS);
751 return mapview->getViewAddr();
752
753parmfail:
754 dprintf(("Win32MemMap::mapViewOfFile: invalid parameter (ERROR_ACCESS_DENIED)"));
755 //NT4 SP6 returns ERROR_ACCESS_DENIED for most invalid parameters
756 SetLastError(ERROR_ACCESS_DENIED);
757fail:
758 mapMutex.leave();
759 return 0;
760}
761//******************************************************************************
762// Win32MemMap::unmapViewOfFile
763//
764// Unmap the view identified by addr
765//
766// Parameters:
767//
768// LPVOID addr - view address; doesn't need to be the address
769// returned by MapViewOfFile(Ex) (as MSDN clearly says);
770// can be any address within the view range
771//
772// Returns:
773// TRUE - success
774// FALSE - failure
775//
776//******************************************************************************
777BOOL Win32MemMap::unmapViewOfFile(LPVOID addr)
778{
779 Win32MemMapView *view;
780
781 dprintf(("Win32MemMap::unmapViewOfFile %x (nrmaps=%d)", addr, nrMappings));
782 mapMutex.enter();
783
784 if(nrMappings == 0)
785 goto fail;
786
787 view = Win32MemMapView::findView((ULONG)addr);
788 if(view == NULL)
789 goto fail;
790
791 delete view;
792
793 mapMutex.leave();
794
795 SetLastError(ERROR_SUCCESS);
796 return TRUE;
797fail:
798 mapMutex.leave();
799 SetLastError(ERROR_INVALID_ADDRESS);
800 return FALSE;
801}
802//******************************************************************************
803//We determine whether a page has been modified by checking it's protection flags
804//If the write flag is set, this means commitPage had to enable this due to a pagefault
805//(all pages are readonly until the app tries to modify the contents of the page)
806//
807//TODO: Are apps allowed to change the protection flags of memory mapped pages?
808// I'm assuming they aren't for now.
809//******************************************************************************
810BOOL Win32MemMap::flushView(ULONG viewaddr, ULONG offset, ULONG cbFlush)
811{
812 ULONG nrBytesWritten, size, accessflags, oldProt;
813 Win32MemMapView *view;
814 int i;
815
816 dprintf(("Win32MemMap::flushView: %x %x", (ULONG)pMapping+offset, cbFlush));
817
818 if(image) //no flushing for image maps
819 return TRUE;
820
821 if(hMemFile == -1)
822 goto success; //TODO: Return an error here?
823
824 if(offset > mSize)
825 goto parmfail;
826
827 if(viewaddr != MMAP_FLUSHVIEW_ALL)
828 {
829 view = Win32MemMapView::findView(viewaddr);
830 if(nrMappings == 0 || view == NULL) {
831 DebugInt3(); //should never happen
832 goto parmfail;
833 }
834 accessflags = view->getAccessFlags();
835 }
836 else {
837 //force a flush to disk; only those pages marked dirty are flushed anyway
838 accessflags = FILE_MAP_WRITE;
839 }
840 //If the view is readonly or copy on write, then the flush is ignored
841 if(!(accessflags & MEMMAP_ACCESS_WRITE) || (accessflags & MEMMAP_ACCESS_COPYONWRITE))
842 {
843 dprintf(("Readonly or Copy-On-Write memory map -> ignore flush"));
844 //this is not a failure; NT4 SP6 returns success
845 goto success;
846 }
847
848 if(cbFlush == 0)
849 cbFlush = mSize;
850
851 if(offset + cbFlush > mSize) {
852 cbFlush -= (offset + cbFlush - mSize);
853 }
854
855 //Check the write page bitmap for dirty pages and write them to disk
856 while(cbFlush)
857 {
858 int startPage = offset >> PAGE_SHIFT;
859 size = PAGE_SIZE;
860
861 if(isDirtyPage(startPage))
862 {
863 if(size > cbFlush) {
864 size = cbFlush;
865 }
866 dprintf(("Win32MemMap::flushView for offset %x, size %d", offset, size));
867
868 if(SetFilePointer(hMemFile, offset, NULL, FILE_BEGIN) != offset) {
869 dprintf(("Win32MemMap::flushView: SetFilePointer failed to set pos to %x", offset));
870 goto fail;
871 }
872 if(WriteFile(hMemFile, (LPSTR)((ULONG)pMapping + offset), size, &nrBytesWritten, NULL) == FALSE) {
873 dprintf(("Win32MemMap::flushView: WriteFile failed for %x", (ULONG)pMapping + offset));
874 goto fail;
875 }
876 if(nrBytesWritten != size) {
877 dprintf(("Win32MemMap::flushView: WriteFile didn't write all bytes for %x", (ULONG)pMapping + offset));
878 goto fail;
879 }
880 clearDirtyPages(startPage, 1);
881
882 //We've just flushed the page to disk, so we need to track future writes
883 //again; Set page to readonly (first memory map, then alias(es))
884 if(VirtualProtect((LPVOID)((ULONG)pMapping + offset), size, PAGE_READONLY, &oldProt) == FALSE) {
885 dprintf(("VirtualProtect %x %x PAGE_READWRITE failed with %d!!", (ULONG)pMapping + offset, size, GetLastError()));
886 goto fail;
887 }
888 updateViewPages(offset, size, PAGEVIEW_READONLY);
889 }
890
891 if(cbFlush < size)
892 break;
893
894 cbFlush -= size;
895 offset += size;
896 }
897success:
898 SetLastError(ERROR_SUCCESS);
899 return TRUE;
900
901parmfail:
902 SetLastError(ERROR_INVALID_PARAMETER);
903 return FALSE;
904fail:
905 return FALSE;
906}
907//******************************************************************************
908//******************************************************************************
909Win32MemMap *Win32MemMap::findMap(LPSTR lpszName)
910{
911 if(lpszName == NULL)
912 return NULL;
913
914 DosEnterCriticalSection(&globalmapcritsect);
915 Win32MemMap *map = memmaps;
916
917 if(map != NULL) {
918 while(map) {
919 if(map->lpszMapName && !strcmp(map->lpszMapName, lpszName))
920 break;
921 map = map->next;
922 }
923 }
924 if(map) map->AddRef();
925
926 DosLeaveCriticalSection(&globalmapcritsect);
927 if(!map) dprintf(("Win32MemMap::findMap: couldn't find map %s", lpszName));
928 return map;
929}
930//******************************************************************************
931//******************************************************************************
932Win32MemMap *Win32MemMap::findMapByFile(HANDLE hFile)
933{
934 DWORD processId = GetCurrentProcessId();
935 char szFileName[260];
936
937 if(hFile == -1)
938 return NULL;
939
940 if(HMGetFileNameFromHandle(hFile, szFileName, sizeof(szFileName)) == FALSE)
941 return NULL;
942
943 DosEnterCriticalSection(&globalmapcritsect);
944 Win32MemMap *map = memmaps;
945
946 if(map != NULL)
947 {
948 while(map) {
949 //TODO: we currently don't support sharing file maps between processes
950 if(map->mProcessId == processId && map->lpszFileName)
951 {
952 if(!strcmp(map->lpszFileName, szFileName))
953 break;
954 }
955 map = map->next;
956 }
957 }
958 if(map) map->AddRef();
959 DosLeaveCriticalSection(&globalmapcritsect);
960 if(!map) dprintf2(("Win32MemMap::findMapByFile: couldn't find map with file handle %x", hFile));
961 return map;
962}
963//******************************************************************************
964//******************************************************************************
965Win32MemMap *Win32MemMap::findMap(ULONG address)
966{
967 DosEnterCriticalSection(&globalmapcritsect);
968 Win32MemMap *map = memmaps;
969
970 if(map != NULL) {
971 while(map) {
972 if(map->pMapping && (ULONG)map->pMapping <= address &&
973 (ULONG)map->pMapping + map->mSize > address)
974 {
975 break;
976 }
977 map = map->next;
978 }
979 }
980 if(map) map->AddRef();
981 DosLeaveCriticalSection(&globalmapcritsect);
982 return map;
983}
984//******************************************************************************
985//******************************************************************************
986void Win32MemMap::deleteAll()
987{
988 Win32MemMap *map, *nextmap;
989 DWORD processId = GetCurrentProcessId();
990
991 //delete all maps created by this process
992 DosEnterCriticalSection(&globalmapcritsect);
993
994startdeleteviews:
995 map = memmaps;
996 while(map) {
997 map->AddRef(); //make sure it doesn't get deleted
998
999 //delete all views created by this process for this map
1000 Win32MemMapView::deleteViews(map);
1001
1002 nextmap = map->next;
1003
1004 //map->Release can delete multiple objects (duplicate memory map), so make
1005 //sure our nextmap pointer remains valid by increasing the refcount
1006 if(nextmap) nextmap->AddRef();
1007 map->Release();
1008
1009 if(nextmap && nextmap->Release() == 0) {
1010 //oops, nextmap was just deleted and is no longer valid
1011 //can't continue from here, so let's start again
1012 dprintf(("oops, nextmap is invalid -> start again (1)"));
1013 goto startdeleteviews;
1014 }
1015
1016 map = nextmap;
1017 }
1018startdelete:
1019 map = memmaps;
1020 while(map) {
1021 nextmap = map->next;
1022 if(map->getProcessId() == processId)
1023 {
1024 //delete map can delete multiple objects (duplicate memory map), so make
1025 //sure our nextmap pointer remains valid by increasing the refcount
1026 if(nextmap) nextmap->AddRef();
1027 delete map;
1028
1029 if(nextmap && nextmap->Release() == 0) {
1030 //oops, nextmap was just deleted and is no longer valid
1031 //can't continue from here, so let's start again
1032 dprintf(("oops, nextmap is invalid -> start again (2)"));
1033 goto startdelete;
1034 }
1035 }
1036 map = nextmap;
1037 }
1038 DosLeaveCriticalSection(&globalmapcritsect);
1039}
1040//******************************************************************************
1041// Win32MemMapView::markDirtyPages
1042//
1043// Mark pages as dirty (changed) in the write page bitmap
1044//
1045// Parameters:
1046//
1047// int startpage - start page
1048// int nrpages - number of pages
1049//
1050//
1051//******************************************************************************
1052void Win32MemMap::markDirtyPages(int startpage, int nrpages)
1053{
1054 if(pWriteBitmap == NULL) return; //can be NULL for non-file mappings
1055
1056 for(int i=startpage;i<startpage+nrpages;i++) {
1057 set_bit(i, pWriteBitmap);
1058 }
1059}
1060//******************************************************************************
1061// Win32MemMapView::clearDirtyPages
1062//
1063// Mark pages as clean in the write page bitmap
1064//
1065// Parameters:
1066//
1067// int startpage - start page
1068// int nrpages - number of pages
1069//
1070//
1071//******************************************************************************
1072void Win32MemMap::clearDirtyPages(int startpage, int nrpages)
1073{
1074 if(pWriteBitmap == NULL) return; //can be NULL for non-file mappings
1075
1076 for(int i=startpage;i<startpage+nrpages;i++) {
1077 clear_bit(i, pWriteBitmap);
1078 }
1079}
1080//******************************************************************************
1081//******************************************************************************
Note: See TracBrowser for help on using the repository browser.