8 #ifndef FILE_MAP_EXECUTE
9 #define FILE_MAP_EXECUTE 0x0020
10 #endif /* FILE_MAP_EXECUTE */
12 static int __map_mman_error(const DWORD err, const int deferr)
20 static DWORD __map_mmap_prot_page(const int prot)
24 if (prot == PROT_NONE)
27 if ((prot & PROT_EXEC) != 0)
29 protect = ((prot & PROT_WRITE) != 0) ?
30 PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ;
34 protect = ((prot & PROT_WRITE) != 0) ?
35 PAGE_READWRITE : PAGE_READONLY;
41 static DWORD __map_mmap_prot_file(const int prot)
43 DWORD desiredAccess = 0;
45 if (prot == PROT_NONE)
48 if ((prot & PROT_READ) != 0)
49 desiredAccess |= FILE_MAP_READ;
50 if ((prot & PROT_WRITE) != 0)
51 desiredAccess |= FILE_MAP_WRITE;
52 if ((prot & PROT_EXEC) != 0)
53 desiredAccess |= FILE_MAP_EXECUTE;
58 void* mmap(void *addr, size_t len, int prot, int flags, int fildes, OffsetType off)
62 void * map = MAP_FAILED;
66 #pragma warning(disable: 4293)
69 const DWORD dwFileOffsetLow = (sizeof(OffsetType) <= sizeof(DWORD)) ?
70 (DWORD)off : (DWORD)(off & 0xFFFFFFFFL);
71 const DWORD dwFileOffsetHigh = (sizeof(OffsetType) <= sizeof(DWORD)) ?
72 (DWORD)0 : (DWORD)((off >> 32) & 0xFFFFFFFFL);
73 const DWORD protect = __map_mmap_prot_page(prot);
74 const DWORD desiredAccess = __map_mmap_prot_file(prot);
76 const OffsetType maxSize = off + (OffsetType)len;
78 const DWORD dwMaxSizeLow = (sizeof(OffsetType) <= sizeof(DWORD)) ?
79 (DWORD)maxSize : (DWORD)(maxSize & 0xFFFFFFFFL);
80 const DWORD dwMaxSizeHigh = (sizeof(OffsetType) <= sizeof(DWORD)) ?
81 (DWORD)0 : (DWORD)((maxSize >> 32) & 0xFFFFFFFFL);
90 /* Usupported protection combinations */
97 h = ((flags & MAP_ANONYMOUS) == 0) ?
98 (HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE;
100 if ((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE)
106 fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL);
110 errno = __map_mman_error(GetLastError(), EPERM);
114 if ((flags & MAP_FIXED) == 0)
116 map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len);
120 map = MapViewOfFileEx(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len, addr);
127 errno = __map_mman_error(GetLastError(), EPERM);
134 int munmap(void *addr, size_t len)
136 if (UnmapViewOfFile(addr))
139 errno = __map_mman_error(GetLastError(), EPERM);
144 int _mprotect(void *addr, size_t len, int prot)
146 DWORD newProtect = __map_mmap_prot_page(prot);
147 DWORD oldProtect = 0;
149 if (VirtualProtect(addr, len, newProtect, &oldProtect))
152 errno = __map_mman_error(GetLastError(), EPERM);
157 int msync(void *addr, size_t len, int flags)
159 if (FlushViewOfFile(addr, len))
162 errno = __map_mman_error(GetLastError(), EPERM);
167 int mlock(const void *addr, size_t len)
169 if (VirtualLock((LPVOID)addr, len))
172 errno = __map_mman_error(GetLastError(), EPERM);
177 int munlock(const void *addr, size_t len)
179 if (VirtualUnlock((LPVOID)addr, len))
182 errno = __map_mman_error(GetLastError(), EPERM);