Debian Codegraph @

debian/rust-vendor/memmap2/src/windows.rs

raw
1 #![allow(non_camel_case_types)]
2 #![allow(non_snake_case)]
3
4 use std::fs::File;
5 use std::mem::ManuallyDrop;
6 use std::os::raw::c_void;
7 use std::os::windows::io::{FromRawHandle, RawHandle};
8 use std::{io, mem, ptr};
9
10 type BOOL = i32;
11 type WORD = u16;
12 type DWORD = u32;
13 type WCHAR = u16;
14 type HANDLE = *mut c_void;
15 type LPHANDLE = *mut HANDLE;
16 type LPVOID = *mut c_void;
17 type LPCVOID = *const c_void;
18 type ULONG_PTR = usize;
19 type SIZE_T = ULONG_PTR;
20 type LPCWSTR = *const WCHAR;
21 type PDWORD = *mut DWORD;
22 type DWORD_PTR = ULONG_PTR;
23 type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES;
24 type LPSYSTEM_INFO = *mut SYSTEM_INFO;
25
26 const INVALID_HANDLE_VALUE: HANDLE = -1isize as HANDLE;
27
28 const DUPLICATE_SAME_ACCESS: DWORD = 0x00000002;
29
30 const STANDARD_RIGHTS_REQUIRED: DWORD = 0x000F0000;
31
32 const SECTION_QUERY: DWORD = 0x0001;
33 const SECTION_MAP_WRITE: DWORD = 0x0002;
34 const SECTION_MAP_READ: DWORD = 0x0004;
35 const SECTION_MAP_EXECUTE: DWORD = 0x0008;
36 const SECTION_EXTEND_SIZE: DWORD = 0x0010;
37 const SECTION_MAP_EXECUTE_EXPLICIT: DWORD = 0x0020;
38 const SECTION_ALL_ACCESS: DWORD = STANDARD_RIGHTS_REQUIRED
39 | SECTION_QUERY
40 | SECTION_MAP_WRITE
41 | SECTION_MAP_READ
42 | SECTION_MAP_EXECUTE
43 | SECTION_EXTEND_SIZE;
44
45 const PAGE_READONLY: DWORD = 0x02;
46 const PAGE_READWRITE: DWORD = 0x04;
47 const PAGE_WRITECOPY: DWORD = 0x08;
48 const PAGE_EXECUTE_READ: DWORD = 0x20;
49 const PAGE_EXECUTE_READWRITE: DWORD = 0x40;
50 const PAGE_EXECUTE_WRITECOPY: DWORD = 0x80;
51
52 const FILE_MAP_WRITE: DWORD = SECTION_MAP_WRITE;
53 const FILE_MAP_READ: DWORD = SECTION_MAP_READ;
54 const FILE_MAP_ALL_ACCESS: DWORD = SECTION_ALL_ACCESS;
55 const FILE_MAP_EXECUTE: DWORD = SECTION_MAP_EXECUTE_EXPLICIT;
56 const FILE_MAP_COPY: DWORD = 0x00000001;
57
58 #[repr(C)]
59 struct SECURITY_ATTRIBUTES {
60 nLength: DWORD,
61 lpSecurityDescriptor: LPVOID,
62 bInheritHandle: BOOL,
63 }
64
65 #[repr(C)]
66 struct SYSTEM_INFO {
67 wProcessorArchitecture: WORD,
68 wReserved: WORD,
69 dwPageSize: DWORD,
70 lpMinimumApplicationAddress: LPVOID,
71 lpMaximumApplicationAddress: LPVOID,
72 dwActiveProcessorMask: DWORD_PTR,
73 dwNumberOfProcessors: DWORD,
74 dwProcessorType: DWORD,
75 dwAllocationGranularity: DWORD,
76 wProcessorLevel: WORD,
77 wProcessorRevision: WORD,
78 }
79
80 #[allow(dead_code)]
81 #[repr(C)]
82 #[derive(Copy, Clone)]
83 pub struct FILETIME {
84 pub dwLowDateTime: DWORD,
85 pub dwHighDateTime: DWORD,
86 }
87
88 extern "system" {
89 fn GetCurrentProcess() -> HANDLE;
90
91 fn CloseHandle(hObject: HANDLE) -> BOOL;
92
93 fn DuplicateHandle(
94 hSourceProcessHandle: HANDLE,
95 hSourceHandle: HANDLE,
96 hTargetProcessHandle: HANDLE,
97 lpTargetHandle: LPHANDLE,
98 dwDesiredAccess: DWORD,
99 bInheritHandle: BOOL,
100 dwOptions: DWORD,
101 ) -> BOOL;
102
103 fn CreateFileMappingW(
104 hFile: HANDLE,
105 lpFileMappingAttributes: LPSECURITY_ATTRIBUTES,
106 flProtect: DWORD,
107 dwMaximumSizeHigh: DWORD,
108 dwMaximumSizeLow: DWORD,
109 lpName: LPCWSTR,
110 ) -> HANDLE;
111
112 fn FlushFileBuffers(hFile: HANDLE) -> BOOL;
113
114 fn FlushViewOfFile(lpBaseAddress: LPCVOID, dwNumberOfBytesToFlush: SIZE_T) -> BOOL;
115
116 fn UnmapViewOfFile(lpBaseAddress: LPCVOID) -> BOOL;
117
118 fn MapViewOfFile(
119 hFileMappingObject: HANDLE,
120 dwDesiredAccess: DWORD,
121 dwFileOffsetHigh: DWORD,
122 dwFileOffsetLow: DWORD,
123 dwNumberOfBytesToMap: SIZE_T,
124 ) -> LPVOID;
125
126 fn VirtualProtect(
127 lpAddress: LPVOID,
128 dwSize: SIZE_T,
129 flNewProtect: DWORD,
130 lpflOldProtect: PDWORD,
131 ) -> BOOL;
132
133 fn GetSystemInfo(lpSystemInfo: LPSYSTEM_INFO);
134 }
135
136 /// Returns a fixed aligned pointer that is valid for `slice::from_raw_parts::<u8>` with `len == 0`.
137 ///
138 /// This aligns the pointer to `allocation_granularity()` or 1 if unknown.
139 fn empty_slice_ptr() -> *mut c_void {
140 allocation_granularity().max(1) as *mut c_void
141 }
142
143 pub struct MmapInner {
144 handle: Option<RawHandle>,
145 ptr: *mut c_void,
146 len: usize,
147 copy: bool,
148 }
149
150 impl MmapInner {
151 /// Creates a new `MmapInner`.
152 ///
153 /// This is a thin wrapper around the `CreateFileMappingW` and `MapViewOfFile` system calls.
154 pub fn new(
155 handle: RawHandle,
156 protect: DWORD,
157 access: DWORD,
158 offset: u64,
159 len: usize,
160 copy: bool,
161 ) -> io::Result<MmapInner> {
162 let alignment = offset % allocation_granularity() as u64;
163 let aligned_offset = offset - alignment;
164 let aligned_len = len + alignment as usize;
165 if aligned_len == 0 {
166 // `CreateFileMappingW` documents:
167 //
168 // https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-createfilemappingw
169 // > An attempt to map a file with a length of 0 (zero) fails with an error code
170 // > of ERROR_FILE_INVALID. Applications should test for files with a length of 0
171 // > (zero) and reject those files.
172 //
173 // For such files, don’t create a mapping at all and use a marker pointer instead.
174 return Ok(MmapInner {
175 handle: None,
176 ptr: empty_slice_ptr(),
177 len: 0,
178 copy,
179 });
180 }
181
182 let mapping =
183 unsafe { CreateFileMappingW(handle, ptr::null_mut(), protect, 0, 0, ptr::null()) };
184 if mapping.is_null() {
185 return Err(io::Error::last_os_error());
186 }
187
188 let ptr = unsafe {
189 MapViewOfFile(
190 mapping,
191 access,
192 (aligned_offset >> 16 >> 16) as DWORD,
193 (aligned_offset & 0xffffffff) as DWORD,
194 aligned_len as SIZE_T,
195 )
196 };
197 unsafe { CloseHandle(mapping) };
198 if ptr.is_null() {
199 return Err(io::Error::last_os_error());
200 }
201
202 let mut new_handle = 0 as RawHandle;
203 let cur_proc = unsafe { GetCurrentProcess() };
204 let ok = unsafe {
205 DuplicateHandle(
206 cur_proc,
207 handle,
208 cur_proc,
209 &mut new_handle,
210 0,
211 0,
212 DUPLICATE_SAME_ACCESS,
213 )
214 };
215 if ok == 0 {
216 unsafe { UnmapViewOfFile(ptr) };
217 return Err(io::Error::last_os_error());
218 }
219
220 // SAFETY: The mapping is guaranteed to contain at-least `alignment` bytes.
221 let ptr = unsafe { ptr.add(alignment as usize) };
222
223 Ok(MmapInner {
224 handle: Some(new_handle),
225 ptr,
226 len,
227 copy,
228 })
229 }
230
231 pub fn map(
232 len: usize,
233 handle: RawHandle,
234 offset: u64,
235 _populate: bool,
236 _no_reserve: bool,
237 ) -> io::Result<MmapInner> {
238 let write = protection_supported(handle, PAGE_READWRITE);
239 let exec = protection_supported(handle, PAGE_EXECUTE_READ);
240 let mut access = FILE_MAP_READ;
241 let protection = match (write, exec) {
242 (true, true) => {
243 access |= FILE_MAP_WRITE | FILE_MAP_EXECUTE;
244 PAGE_EXECUTE_READWRITE
245 }
246 (true, false) => {
247 access |= FILE_MAP_WRITE;
248 PAGE_READWRITE
249 }
250 (false, true) => {
251 access |= FILE_MAP_EXECUTE;
252 PAGE_EXECUTE_READ
253 }
254 (false, false) => PAGE_READONLY,
255 };
256
257 let mut inner = MmapInner::new(handle, protection, access, offset, len, false)?;
258 if write || exec {
259 inner.make_read_only()?;
260 }
261 Ok(inner)
262 }
263
264 pub fn map_exec(
265 len: usize,
266 handle: RawHandle,
267 offset: u64,
268 _populate: bool,
269 _no_reserve: bool,
270 ) -> io::Result<MmapInner> {
271 let write = protection_supported(handle, PAGE_READWRITE);
272 let mut access = FILE_MAP_READ | FILE_MAP_EXECUTE;
273 let protection = if write {
274 access |= FILE_MAP_WRITE;
275 PAGE_EXECUTE_READWRITE
276 } else {
277 PAGE_EXECUTE_READ
278 };
279
280 let mut inner = MmapInner::new(handle, protection, access, offset, len, false)?;
281 if write {
282 inner.make_exec()?;
283 }
284 Ok(inner)
285 }
286
287 pub fn map_mut(
288 len: usize,
289 handle: RawHandle,
290 offset: u64,
291 _populate: bool,
292 _no_reserve: bool,
293 ) -> io::Result<MmapInner> {
294 let exec = protection_supported(handle, PAGE_EXECUTE_READ);
295 let mut access = FILE_MAP_READ | FILE_MAP_WRITE;
296 let protection = if exec {
297 access |= FILE_MAP_EXECUTE;
298 PAGE_EXECUTE_READWRITE
299 } else {
300 PAGE_READWRITE
301 };
302
303 let mut inner = MmapInner::new(handle, protection, access, offset, len, false)?;
304 if exec {
305 inner.make_mut()?;
306 }
307 Ok(inner)
308 }
309
310 pub fn map_copy(
311 len: usize,
312 handle: RawHandle,
313 offset: u64,
314 _populate: bool,
315 _no_reserve: bool,
316 ) -> io::Result<MmapInner> {
317 let exec = protection_supported(handle, PAGE_EXECUTE_READWRITE);
318 let mut access = FILE_MAP_COPY;
319 let protection = if exec {
320 access |= FILE_MAP_EXECUTE;
321 PAGE_EXECUTE_WRITECOPY
322 } else {
323 PAGE_WRITECOPY
324 };
325
326 let mut inner = MmapInner::new(handle, protection, access, offset, len, true)?;
327 if exec {
328 inner.make_mut()?;
329 }
330 Ok(inner)
331 }
332
333 pub fn map_copy_read_only(
334 len: usize,
335 handle: RawHandle,
336 offset: u64,
337 _populate: bool,
338 _no_reserve: bool,
339 ) -> io::Result<MmapInner> {
340 let write = protection_supported(handle, PAGE_READWRITE);
341 let exec = protection_supported(handle, PAGE_EXECUTE_READ);
342 let mut access = FILE_MAP_COPY;
343 let protection = if exec {
344 access |= FILE_MAP_EXECUTE;
345 PAGE_EXECUTE_WRITECOPY
346 } else {
347 PAGE_WRITECOPY
348 };
349
350 let mut inner = MmapInner::new(handle, protection, access, offset, len, true)?;
351 if write || exec {
352 inner.make_read_only()?;
353 }
354 Ok(inner)
355 }
356
357 pub fn map_anon(
358 len: usize,
359 _stack: bool,
360 _populate: bool,
361 _huge: Option<u8>,
362 _no_reserve: bool,
363 ) -> io::Result<MmapInner> {
364 // Ensure a non-zero length for the underlying mapping
365 let mapped_len = len.max(1);
366 unsafe {
367 // Create a mapping and view with maximum access permissions, then use `VirtualProtect`
368 // to set the actual `Protection`. This way, we can set more permissive protection later
369 // on.
370 // Also see https://msdn.microsoft.com/en-us/library/windows/desktop/aa366537.aspx
371
372 let mapping = CreateFileMappingW(
373 INVALID_HANDLE_VALUE,
374 ptr::null_mut(),
375 PAGE_EXECUTE_READWRITE,
376 (mapped_len >> 16 >> 16) as DWORD,
377 (mapped_len & 0xffffffff) as DWORD,
378 ptr::null(),
379 );
380 if mapping.is_null() {
381 return Err(io::Error::last_os_error());
382 }
383 let access = FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE;
384 let ptr = MapViewOfFile(mapping, access, 0, 0, mapped_len as SIZE_T);
385 CloseHandle(mapping);
386
387 if ptr.is_null() {
388 return Err(io::Error::last_os_error());
389 }
390
391 let mut old = 0;
392 let result = VirtualProtect(ptr, mapped_len as SIZE_T, PAGE_READWRITE, &mut old);
393 if result != 0 {
394 Ok(MmapInner {
395 handle: None,
396 ptr,
397 len,
398 copy: false,
399 })
400 } else {
401 Err(io::Error::last_os_error())
402 }
403 }
404 }
405
406 pub fn flush(&self, offset: usize, len: usize) -> io::Result<()> {
407 self.flush_async(offset, len)?;
408
409 if let Some(handle) = self.handle {
410 let ok = unsafe { FlushFileBuffers(handle) };
411 if ok == 0 {
412 return Err(io::Error::last_os_error());
413 }
414 }
415
416 Ok(())
417 }
418
419 pub fn flush_async(&self, offset: usize, len: usize) -> io::Result<()> {
420 if offset > self.len || len > self.len - offset {
421 return Err(io::ErrorKind::InvalidInput.into());
422 }
423 if self.ptr == empty_slice_ptr() {
424 return Ok(());
425 }
426 // SAFETY: We've checked that offset and offset + len fall within the mapped region.
427 let result = unsafe {
428 let ptr = self.ptr.add(offset);
429 FlushViewOfFile(ptr, len as SIZE_T)
430 };
431 if result != 0 {
432 Ok(())
433 } else {
434 Err(io::Error::last_os_error())
435 }
436 }
437
438 fn virtual_protect(&mut self, protect: DWORD) -> io::Result<()> {
439 if self.ptr == empty_slice_ptr() {
440 return Ok(());
441 }
442 let alignment = self.ptr as usize % allocation_granularity();
443 // SAFETY: self.ptr rounded down to `allocation_granularity()` is the real start of the memory map.
444 // So it lies within the same allocation as `self.ptr`.
445 let ptr = unsafe { self.ptr.sub(alignment) };
446 let aligned_len = self.len as SIZE_T + alignment as SIZE_T;
447
448 let mut old = 0;
449 let result = unsafe { VirtualProtect(ptr, aligned_len, protect, &mut old) };
450
451 if result != 0 {
452 Ok(())
453 } else {
454 Err(io::Error::last_os_error())
455 }
456 }
457
458 pub fn make_read_only(&mut self) -> io::Result<()> {
459 self.virtual_protect(PAGE_READONLY)
460 }
461
462 pub fn make_exec(&mut self) -> io::Result<()> {
463 if self.copy {
464 self.virtual_protect(PAGE_EXECUTE_WRITECOPY)
465 } else {
466 self.virtual_protect(PAGE_EXECUTE_READ)
467 }
468 }
469
470 pub fn make_mut(&mut self) -> io::Result<()> {
471 if self.copy {
472 self.virtual_protect(PAGE_WRITECOPY)
473 } else {
474 self.virtual_protect(PAGE_READWRITE)
475 }
476 }
477
478 #[inline]
479 pub fn ptr(&self) -> *const u8 {
480 self.ptr as *const u8
481 }
482
483 #[inline]
484 pub fn mut_ptr(&mut self) -> *mut u8 {
485 self.ptr.cast()
486 }
487
488 #[inline]
489 pub fn len(&self) -> usize {
490 self.len
491 }
492 }
493
494 impl Drop for MmapInner {
495 fn drop(&mut self) {
496 if self.ptr == empty_slice_ptr() {
497 return;
498 }
499 let alignment = self.ptr as usize % allocation_granularity();
500 // SAFETY: self.ptr rounded down to `allocation_granularity()` is the real start of the memory map.
501 // So it lies within the same allocation as `self.ptr`.
502 let ptr = unsafe { self.ptr.sub(alignment) };
503 // Any errors during unmapping/closing are ignored as the only way
504 // to report them would be through panicking which is highly discouraged
505 // in Drop impls, c.f. https://github.com/rust-lang/lang-team/issues/97
506 unsafe {
507 UnmapViewOfFile(ptr);
508
509 if let Some(handle) = self.handle {
510 CloseHandle(handle);
511 }
512 }
513 }
514 }
515
516 unsafe impl Sync for MmapInner {}
517 unsafe impl Send for MmapInner {}
518
519 fn protection_supported(handle: RawHandle, protection: DWORD) -> bool {
520 unsafe {
521 let mapping = CreateFileMappingW(handle, ptr::null_mut(), protection, 0, 0, ptr::null());
522 if mapping.is_null() {
523 return false;
524 }
525 CloseHandle(mapping);
526 true
527 }
528 }
529
530 fn allocation_granularity() -> usize {
531 unsafe {
532 let mut info = mem::zeroed();
533 GetSystemInfo(&mut info);
534 info.dwAllocationGranularity as usize
535 }
536 }
537
538 pub fn file_len(handle: RawHandle) -> io::Result<u64> {
539 // SAFETY: We must not close the passed-in fd by dropping the File we create,
540 // we ensure this by immediately wrapping it in a ManuallyDrop.
541 unsafe {
542 let file = ManuallyDrop::new(File::from_raw_handle(handle));
543 Ok(file.metadata()?.len())
544 }
545 }