File: wmman.cpp

package info (click to toggle)
0ad 0.0.23.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,412 kB
  • sloc: cpp: 245,162; ansic: 200,249; javascript: 19,244; python: 13,754; sh: 6,104; perl: 4,620; makefile: 977; xml: 810; java: 533; ruby: 229; erlang: 46; pascal: 30; sql: 21; tcl: 4
file content (232 lines) | stat: -rw-r--r-- 7,206 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/* Copyright (C) 2011 Wildfire Games.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "precompiled.h"
#include "lib/sysdep/os/win/wposix/wmman.h"

#include "lib/sysdep/os/win/wposix/wposix_internal.h"
#include "lib/sysdep/os/win/wposix/crt_posix.h"		// _get_osfhandle


unsigned MemoryProtectionFromPosix(int prot)
{
	if(prot == PROT_NONE)
		return PAGE_NOACCESS;

	// this covers all 8 combinations of read|write|exec
	switch(prot & (PROT_READ|PROT_WRITE|PROT_EXEC))
	{
	case PROT_READ:
		return PAGE_READONLY;
	case PROT_WRITE:
		// not supported by Win32; POSIX allows us to also grant read access.
		return PAGE_READWRITE;
	case PROT_EXEC:
		return PAGE_EXECUTE;
	case PROT_READ|PROT_WRITE:
		return PAGE_READWRITE;
	case PROT_READ|PROT_EXEC:
		return PAGE_EXECUTE_READ;
	case PROT_WRITE|PROT_EXEC:
		// not supported by Win32; POSIX allows us to also grant read access.
		return PAGE_EXECUTE_READWRITE;
	case PROT_READ|PROT_WRITE|PROT_EXEC:
		return PAGE_EXECUTE_READWRITE;
	default:	// none set
		DEBUG_WARN_ERR(ERR::INVALID_FLAG);
		return PAGE_NOACCESS;
	}

	// UNREACHABLE
}


//-----------------------------------------------------------------------------
// memory mapping
//-----------------------------------------------------------------------------

int mprotect(void* addr, size_t len, int prot)
{
	const DWORD newProtect = (DWORD)MemoryProtectionFromPosix(prot);
	DWORD oldProtect;	// required by VirtualProtect
	const BOOL ok = VirtualProtect(addr, len, newProtect, &oldProtect);
	WARN_IF_FALSE(ok);
	return ok? 0 : -1;
}


// called when flags & MAP_ANONYMOUS
static Status mmap_mem(void* start, size_t len, int prot, int flags, int fd, void** pp)
{
	// sanity checks. we don't care about these but enforce them to
	// ensure callers are compatible with mmap.
	// .. MAP_ANONYMOUS is documented to require this.
	ENSURE(fd == -1);
	// .. if MAP_SHARED, writes are to change "the underlying [mapped]
	//    object", but there is none here (we're backed by the page file).
	ENSURE(!(flags & MAP_SHARED));

	// see explanation at MAP_NORESERVE definition.
	bool want_commit = (prot != PROT_NONE && !(flags & MAP_NORESERVE));

	// decommit a given area (leaves its address space reserved)
	if(!want_commit && start != 0 && flags & MAP_FIXED)
	{
		MEMORY_BASIC_INFORMATION mbi;
		if(!VirtualQuery(start, &mbi, sizeof(mbi)))
			WARN_RETURN(StatusFromWin());
		if(mbi.State == MEM_COMMIT)
		{
			WARN_IF_FALSE(VirtualFree(start, len, MEM_DECOMMIT));
			*pp = 0;
			// make sure *pp won't be misinterpreted as an error
			cassert(MAP_FAILED);
			return INFO::OK;
		}
	}

	const DWORD allocationType = want_commit? MEM_COMMIT : MEM_RESERVE;
	const DWORD protect = (DWORD)MemoryProtectionFromPosix(prot);
	void* p = VirtualAlloc(start, len, allocationType, protect);
	if(!p)
	{
		debug_printf("wmman: VirtualAlloc(%p, 0x%I64X) failed\n", start, len);
		WARN_RETURN(ERR::NO_MEM);
	}
	*pp = p;
	return INFO::OK;
}


// given mmap prot and flags, output protection/access values for use with
// CreateFileMapping / MapViewOfFile. they only support read-only,
// read/write and copy-on-write, so we dumb it down to that and later
// set the correct (and more restrictive) permission via mprotect.
static Status DecodeFlags(int prot, int flags, DWORD& protect, DWORD& access)
{
	// ensure exactly one of (MAP_SHARED, MAP_PRIVATE) is specified
	switch(flags & (MAP_SHARED|MAP_PRIVATE))
	{
	case 0:
	case MAP_SHARED|MAP_PRIVATE:
		WARN_RETURN(ERR::INVALID_PARAM);
	default:;
	}

	if(prot & PROT_WRITE)
	{
		// determine write behavior: (whether they change the underlying file)
		if(flags & MAP_SHARED)	// writes affect the file
		{
			protect = PAGE_READWRITE;
			access  = FILE_MAP_WRITE;	// read and write
		}
		else	// copy on write (file remains unchanged)
		{
			protect = PAGE_WRITECOPY;
			access  = FILE_MAP_COPY;
		}
	}
	else
	{
		protect = PAGE_READONLY;
		access  = FILE_MAP_READ;
	}

	return INFO::OK;
}


static Status mmap_file(void* start, size_t len, int prot, int flags, int fd, off_t ofs, void** pp)
{
	WinScopedPreserveLastError s;

	ENSURE(fd != -1);	// handled by mmap_mem

	HANDLE hFile = HANDLE_from_intptr(_get_osfhandle(fd));
	if(hFile == INVALID_HANDLE_VALUE)
		WARN_RETURN(ERR::INVALID_HANDLE);

	// MapViewOfFileEx will fail if the "suggested" base address is
	// nonzero but cannot be honored, so wipe out <start> unless MAP_FIXED.
	if(!(flags & MAP_FIXED))
		start = 0;

	// choose protection and access rights for CreateFileMapping /
	// MapViewOfFile. these are weaker than what PROT_* allows and
	// are augmented below by subsequently mprotect-ing.
	DWORD protect; DWORD access;
	RETURN_STATUS_IF_ERR(DecodeFlags(prot, flags, protect, access));

	const HANDLE hMap = CreateFileMapping(hFile, 0, protect, 0, 0, 0);
	if(!hMap)
		WARN_RETURN(ERR::NO_MEM);
	void* p = MapViewOfFileEx(hMap, access, u64_hi(ofs), u64_lo(ofs), (SIZE_T)len, start);
	// ensure we got the requested address if MAP_FIXED was passed.
	ENSURE(!(flags & MAP_FIXED) || (p == start));
	// free the mapping object now, so that we don't have to hold on to its
	// handle until munmap(). it's not actually released yet due to the
	// reference held by MapViewOfFileEx (if it succeeded).
	CloseHandle(hMap);
	// map failed; bail now to avoid "restoring" the last error value.
	if(!p)
		WARN_RETURN(ERR::NO_MEM);

	// enforce the desired (more restrictive) protection.
	(void)mprotect(p, len, prot);

	*pp = p;
	return INFO::OK;
}


void* mmap(void* start, size_t len, int prot, int flags, int fd, off_t ofs)
{
	ASSERT(len != 0);

	void* p;
	Status status;
	if(flags & MAP_ANONYMOUS)
		status = mmap_mem(start, len, prot, flags, fd, &p);
	else
		status = mmap_file(start, len, prot, flags, fd, ofs, &p);
	if(status < 0)
	{
		errno = ErrnoFromStatus(status);
		return MAP_FAILED;	// NOWARN - already done
	}

	return p;
}


int munmap(void* start, size_t UNUSED(len))
{
	// UnmapViewOfFile checks if start was returned by MapViewOfFile*;
	// if not, it will fail.
	BOOL ok = UnmapViewOfFile(start);
	if(!ok)
		// VirtualFree requires dwSize to be 0 (entire region is released).
		ok = VirtualFree(start, 0, MEM_RELEASE);
	WARN_IF_FALSE(ok);
	return ok? 0 : -1;
}