Skip to main content

miri/shims/windows/
foreign_items.rs

1use std::ffi::OsStr;
2use std::path::{self, Path, PathBuf};
3use std::{io, iter, str};
4
5use rustc_abi::{Align, Size};
6use rustc_middle::ty::Ty;
7use rustc_span::Symbol;
8use rustc_target::callconv::FnAbi;
9use rustc_target::spec::Env;
10
11use self::shims::windows::handle::{Handle, PseudoHandle};
12use crate::eval::{ExitType, ProgramExitHandler};
13use crate::shims::os_str::bytes_to_os_str;
14use crate::shims::tls::TlsKey;
15use crate::shims::windows::*;
16use crate::*;
17
18pub fn is_dyn_sym(name: &str) -> bool {
19    // std does dynamic detection for these symbols
20    matches!(
21        name,
22        "SetThreadDescription" | "GetThreadDescription" | "WaitOnAddress" | "WakeByAddressSingle"
23    )
24}
25
26#[cfg(windows)]
27fn win_get_full_path_name<'tcx>(path: &Path) -> InterpResult<'tcx, io::Result<PathBuf>> {
28    // We are on Windows so we can simply let the host do this.
29    interp_ok(path::absolute(path))
30}
31
32#[cfg(unix)]
33#[expect(clippy::get_first, clippy::arithmetic_side_effects)]
34fn win_get_full_path_name<'tcx>(path: &Path) -> InterpResult<'tcx, io::Result<PathBuf>> {
35    use std::sync::LazyLock;
36
37    use rustc_data_structures::fx::FxHashSet;
38
39    // We are on Unix, so we need to implement parts of the logic ourselves. `path` will use `/`
40    // separators, and the result should also use `/`.
41    // See <https://chrisdenton.github.io/omnipath/Overview.html#absolute-win32-paths> for more
42    // information about Windows paths.
43    // This does not handle all corner cases correctly, see
44    // <https://github.com/rust-lang/miri/pull/4262#issuecomment-2792168853> for more cursed
45    // examples.
46    let bytes = path.as_os_str().as_encoded_bytes();
47    // If it starts with `//./` or `//?/` then this is a magic special path, we just leave it
48    // unchanged.
49    if bytes.get(0).copied() == Some(b'/')
50        && bytes.get(1).copied() == Some(b'/')
51        && matches!(bytes.get(2), Some(b'.' | b'?'))
52        && bytes.get(3).copied() == Some(b'/')
53    {
54        return interp_ok(Ok(path.into()));
55    };
56    let is_unc = bytes.starts_with(b"//");
57    // Special treatment for Windows' magic filenames: they are treated as being relative to `//./`.
58    static MAGIC_FILENAMES: LazyLock<FxHashSet<&'static str>> = LazyLock::new(|| {
59        FxHashSet::from_iter([
60            "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
61            "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
62        ])
63    });
64    if str::from_utf8(bytes).is_ok_and(|s| MAGIC_FILENAMES.contains(&*s.to_ascii_uppercase())) {
65        let mut result: Vec<u8> = b"//./".into();
66        result.extend(bytes);
67        return interp_ok(Ok(bytes_to_os_str(&result)?.into()));
68    }
69    // Otherwise we try to do something kind of close to what Windows does, but this is probably not
70    // right in all cases.
71    let mut result: Vec<&[u8]> = vec![]; // will be a vector of components, joined by `/`.
72    let mut bytes = bytes; // the remaining bytes to process
73    let mut stop = false;
74    while !stop {
75        // Find next component, and advance `bytes`.
76        let mut component = match bytes.iter().position(|&b| b == b'/') {
77            Some(pos) => {
78                let (component, tail) = bytes.split_at(pos);
79                bytes = &tail[1..]; // remove the `/`.
80                component
81            }
82            None => {
83                // There's no more `/`.
84                stop = true;
85                let component = bytes;
86                bytes = &[];
87                component
88            }
89        };
90        // `NUL` and only `NUL` also gets changed to be relative to `//./` later in the path.
91        // (This changed with Windows 11; previously, all magic filenames behaved like this.)
92        // Also, this does not apply to UNC paths.
93        if !is_unc && component.eq_ignore_ascii_case(b"NUL") {
94            let mut result: Vec<u8> = b"//./".into();
95            result.extend(component);
96            return interp_ok(Ok(bytes_to_os_str(&result)?.into()));
97        }
98        // Deal with `..` -- Windows handles this entirely syntactically.
99        if component == b".." {
100            // Remove previous component, unless we are at the "root" already, then just ignore the `..`.
101            let is_root = {
102                // Paths like `/C:`.
103                result.len() == 2 && matches!(result[0], []) && matches!(result[1], [_, b':'])
104            } || {
105                // Paths like `//server/share`
106                result.len() == 4 && matches!(result[0], []) && matches!(result[1], [])
107            };
108            if !is_root {
109                result.pop();
110            }
111            continue;
112        }
113        // Preserve this component.
114        // Strip trailing `.`, but preserve trailing `..`. But not for UNC paths!
115        let len = component.len();
116        if !is_unc && len >= 2 && component[len - 1] == b'.' && component[len - 2] != b'.' {
117            component = &component[..len - 1];
118        }
119        // Add this component to output.
120        result.push(component);
121    }
122    // Drive letters must be followed by a `/`.
123    if result.len() == 2 && matches!(result[0], []) && matches!(result[1], [_, b':']) {
124        result.push(&[]);
125    }
126    // Let the host `absolute` function do working-dir handling.
127    let result = result.join(&b'/');
128    interp_ok(path::absolute(bytes_to_os_str(&result)?))
129}
130
131impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
132pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
133    fn emulate_foreign_item_inner(
134        &mut self,
135        link_name: Symbol,
136        abi: &FnAbi<'tcx, Ty<'tcx>>,
137        args: &[OpTy<'tcx>],
138        dest: &MPlaceTy<'tcx>,
139    ) -> InterpResult<'tcx, EmulateItemResult> {
140        let ecx = self.eval_context_mut();
141
142        // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern.
143
144        // Windows API stubs.
145        // HANDLE = *mut c_void (formerly: isize)
146        // NTSTATUS = LONG = i32
147        // DWORD = ULONG = u32
148        // BOOL = i32
149        // BOOLEAN = u8
150        match link_name.as_str() {
151            // Environment related shims
152            "GetEnvironmentVariableW" => {
153                // FIXME: This does not have a direct test (#3179).
154                let [name, buf, size] = &ecx.check_shim_sig(
155                    shim_sig!(extern "system" fn(*_, *_, u32) -> u32),
156                    (link_name, abi, args),
157                )?;
158                let result = ecx.GetEnvironmentVariableW(name, buf, size)?;
159                ecx.write_scalar(result, dest)?;
160            }
161            "SetEnvironmentVariableW" => {
162                // FIXME: This does not have a direct test (#3179).
163                let [name, value] = &ecx.check_shim_sig(
164                    shim_sig!(extern "system" fn(*_, *_) -> winapi::BOOL),
165                    (link_name, abi, args),
166                )?;
167                let result = ecx.SetEnvironmentVariableW(name, value)?;
168                ecx.write_scalar(result, dest)?;
169            }
170            "GetEnvironmentStringsW" => {
171                // FIXME: This does not have a direct test (#3179).
172                let [] = &ecx.check_shim_sig(
173                    shim_sig!(extern "system" fn() -> *_),
174                    (link_name, abi, args),
175                )?;
176                let result = ecx.GetEnvironmentStringsW()?;
177                ecx.write_pointer(result, dest)?;
178            }
179            "FreeEnvironmentStringsW" => {
180                // FIXME: This does not have a direct test (#3179).
181                let [env_block] = &ecx.check_shim_sig(
182                    shim_sig!(extern "system" fn(*_) -> winapi::BOOL),
183                    (link_name, abi, args),
184                )?;
185                let result = ecx.FreeEnvironmentStringsW(env_block)?;
186                ecx.write_scalar(result, dest)?;
187            }
188            "GetCurrentDirectoryW" => {
189                // FIXME: This does not have a direct test (#3179).
190                let [size, buf] = &ecx.check_shim_sig(
191                    shim_sig!(extern "system" fn(u32, *_) -> u32),
192                    (link_name, abi, args),
193                )?;
194                let result = ecx.GetCurrentDirectoryW(size, buf)?;
195                ecx.write_scalar(result, dest)?;
196            }
197            "SetCurrentDirectoryW" => {
198                // FIXME: This does not have a direct test (#3179).
199                let [path] = &ecx.check_shim_sig(
200                    shim_sig!(extern "system" fn(*_) -> winapi::BOOL),
201                    (link_name, abi, args),
202                )?;
203                let result = ecx.SetCurrentDirectoryW(path)?;
204                ecx.write_scalar(result, dest)?;
205            }
206            "GetUserProfileDirectoryW" => {
207                // FIXME: This does not have a direct test (#3179).
208                let [token, buf, size] = &ecx.check_shim_sig(
209                    shim_sig!(extern "system" fn(winapi::HANDLE, *_, *u32) -> winapi::BOOL),
210                    (link_name, abi, args),
211                )?;
212                let result = ecx.GetUserProfileDirectoryW(token, buf, size)?;
213                ecx.write_scalar(result, dest)?;
214            }
215            "GetCurrentProcessId" => {
216                let [] = &ecx.check_shim_sig(
217                    shim_sig!(extern "system" fn() -> u32),
218                    (link_name, abi, args),
219                )?;
220                let result = ecx.GetCurrentProcessId()?;
221                ecx.write_scalar(result, dest)?;
222            }
223            "GetTempPathW" => {
224                // FIXME: This does not have a direct test (#3179).
225                let [bufferlength, buffer] = &ecx.check_shim_sig(
226                    shim_sig!(extern "system" fn(u32, *_) -> u32),
227                    (link_name, abi, args),
228                )?;
229                let result = ecx.GetTempPathW(bufferlength, buffer)?;
230                ecx.write_scalar(result, dest)?;
231            }
232
233            // File related shims
234            "NtWriteFile" => {
235                let [
236                    handle,
237                    event,
238                    apc_routine,
239                    apc_context,
240                    io_status_block,
241                    buf,
242                    n,
243                    byte_offset,
244                    key,
245                ] = &ecx.check_shim_sig(
246                    shim_sig!(
247                        extern "system" fn(
248                            winapi::HANDLE,
249                            winapi::HANDLE,
250                            *_,
251                            *_,
252                            *winapi::IO_STATUS_BLOCK,
253                            *_,
254                            u32,
255                            *_,
256                            *_,
257                        ) -> i32
258                    ),
259                    (link_name, abi, args),
260                )?;
261                ecx.NtWriteFile(
262                    handle,
263                    event,
264                    apc_routine,
265                    apc_context,
266                    io_status_block,
267                    buf,
268                    n,
269                    byte_offset,
270                    key,
271                    dest,
272                )?;
273            }
274            "NtReadFile" => {
275                let [
276                    handle,
277                    event,
278                    apc_routine,
279                    apc_context,
280                    io_status_block,
281                    buf,
282                    n,
283                    byte_offset,
284                    key,
285                ] = &ecx.check_shim_sig(
286                    shim_sig!(
287                        extern "system" fn(
288                            winapi::HANDLE,
289                            winapi::HANDLE,
290                            *_,
291                            *_,
292                            *winapi::IO_STATUS_BLOCK,
293                            *_,
294                            u32,
295                            *_,
296                            *_,
297                        ) -> i32
298                    ),
299                    (link_name, abi, args),
300                )?;
301                ecx.NtReadFile(
302                    handle,
303                    event,
304                    apc_routine,
305                    apc_context,
306                    io_status_block,
307                    buf,
308                    n,
309                    byte_offset,
310                    key,
311                    dest,
312                )?;
313            }
314            "GetFullPathNameW" => {
315                // FIXME: This does not have a direct test (#3179).
316                let [filename, size, buffer, filepart] = &ecx.check_shim_sig(
317                    shim_sig!(extern "system" fn(*_, u32, *_, *_) -> u32),
318                    (link_name, abi, args),
319                )?;
320                ecx.check_no_isolation("`GetFullPathNameW`")?;
321
322                let filename = ecx.read_pointer(filename)?;
323                let size = ecx.read_scalar(size)?.to_u32()?;
324                let buffer = ecx.read_pointer(buffer)?;
325                let filepart = ecx.read_pointer(filepart)?;
326
327                if !ecx.ptr_is_null(filepart)? {
328                    throw_unsup_format!("GetFullPathNameW: non-null `lpFilePart` is not supported");
329                }
330
331                let filename = ecx.read_path_from_wide_str(filename)?;
332                let result = match win_get_full_path_name(&filename)? {
333                    Err(err) => {
334                        ecx.set_last_error(err)?;
335                        Scalar::from_u32(0) // return zero upon failure
336                    }
337                    Ok(abs_filename) => {
338                        Scalar::from_u32(helpers::windows_check_buffer_size(
339                            ecx.write_path_to_wide_str(&abs_filename, buffer, size.into())?,
340                        ))
341                        // This can in fact return 0. It is up to the caller to set last_error to 0
342                        // beforehand and check it afterwards to exclude that case.
343                    }
344                };
345                ecx.write_scalar(result, dest)?;
346            }
347            "CreateFileW" => {
348                let [
349                    file_name,
350                    desired_access,
351                    share_mode,
352                    security_attributes,
353                    creation_disposition,
354                    flags_and_attributes,
355                    template_file,
356                ] = &ecx.check_shim_sig(
357                    shim_sig!(
358                        extern "system" fn(
359                            *_,
360                            u32,
361                            u32,
362                            *_,
363                            u32,
364                            u32,
365                            winapi::HANDLE,
366                        ) -> winapi::HANDLE
367                    ),
368                    (link_name, abi, args),
369                )?;
370                let handle = ecx.CreateFileW(
371                    file_name,
372                    desired_access,
373                    share_mode,
374                    security_attributes,
375                    creation_disposition,
376                    flags_and_attributes,
377                    template_file,
378                )?;
379                ecx.write_scalar(handle.to_scalar(ecx), dest)?;
380            }
381            "GetFileInformationByHandle" => {
382                let [handle, info] = &ecx.check_shim_sig(
383                    shim_sig!(
384                        extern "system" fn(
385                            winapi::HANDLE,
386                            *winapi::BY_HANDLE_FILE_INFORMATION,
387                        ) -> winapi::BOOL
388                    ),
389                    (link_name, abi, args),
390                )?;
391                let res = ecx.GetFileInformationByHandle(handle, info)?;
392                ecx.write_scalar(res, dest)?;
393            }
394            "SetFileInformationByHandle" => {
395                let [handle, class, info, size] = &ecx.check_shim_sig(
396                    shim_sig!(
397                        extern "system" fn(
398                            winapi::HANDLE,
399                            winapi::FILE_INFO_BY_HANDLE_CLASS,
400                            *_,
401                            u32,
402                        ) -> winapi::BOOL
403                    ),
404                    (link_name, abi, args),
405                )?;
406                let res = ecx.SetFileInformationByHandle(handle, class, info, size)?;
407                ecx.write_scalar(res, dest)?;
408            }
409            "FlushFileBuffers" => {
410                let [handle] = &ecx.check_shim_sig(
411                    shim_sig!(extern "system" fn(winapi::HANDLE) -> winapi::BOOL),
412                    (link_name, abi, args),
413                )?;
414                let res = ecx.FlushFileBuffers(handle)?;
415                ecx.write_scalar(res, dest)?;
416            }
417            "DeleteFileW" => {
418                let [file_name] = &ecx.check_shim_sig(
419                    shim_sig!(extern "system" fn(*_) -> winapi::BOOL),
420                    (link_name, abi, args),
421                )?;
422                let res = ecx.DeleteFileW(file_name)?;
423                ecx.write_scalar(res, dest)?;
424            }
425            "SetFilePointerEx" => {
426                let [file, distance_to_move, new_file_pointer, move_method] = &ecx.check_shim_sig(
427                    // i64 is actually a LARGE_INTEGER union of {u32, i32} and {i64}
428                    shim_sig!(extern "system" fn(winapi::HANDLE, i64, *i64, u32) -> winapi::BOOL),
429                    (link_name, abi, args),
430                )?;
431                let res =
432                    ecx.SetFilePointerEx(file, distance_to_move, new_file_pointer, move_method)?;
433                ecx.write_scalar(res, dest)?;
434            }
435            "MoveFileExW" => {
436                let [existing_name, new_name, flags] = &ecx.check_shim_sig(
437                    shim_sig!(extern "system" fn(*_, *_, u32) -> winapi::BOOL),
438                    (link_name, abi, args),
439                )?;
440                let res = ecx.MoveFileExW(existing_name, new_name, flags)?;
441                ecx.write_scalar(res, dest)?;
442            }
443
444            // Allocation
445            "HeapAlloc" => {
446                // FIXME: This does not have a direct test (#3179).
447                let [handle, flags, size] = &ecx.check_shim_sig(
448                    shim_sig!(extern "system" fn(winapi::HANDLE, u32, usize) -> *_),
449                    (link_name, abi, args),
450                )?;
451                ecx.read_target_isize(handle)?;
452                let flags = ecx.read_scalar(flags)?.to_u32()?;
453                let size = ecx.read_target_usize(size)?;
454                const HEAP_ZERO_MEMORY: u32 = 0x00000008;
455                let init = if (flags & HEAP_ZERO_MEMORY) == HEAP_ZERO_MEMORY {
456                    AllocInit::Zero
457                } else {
458                    AllocInit::Uninit
459                };
460                // Alignment is twice the pointer size.
461                // Source: <https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc>
462                let align = ecx.tcx.pointer_size().bytes().strict_mul(2);
463                let ptr = ecx.allocate_ptr(
464                    Size::from_bytes(size),
465                    Align::from_bytes(align).unwrap(),
466                    MiriMemoryKind::WinHeap.into(),
467                    init,
468                )?;
469                ecx.write_pointer(ptr, dest)?;
470            }
471            "HeapFree" => {
472                // FIXME: This does not have a direct test (#3179).
473                let [handle, flags, ptr] = &ecx.check_shim_sig(
474                    shim_sig!(extern "system" fn(winapi::HANDLE, u32, *_) -> winapi::BOOL),
475                    (link_name, abi, args),
476                )?;
477                ecx.read_target_isize(handle)?;
478                ecx.read_scalar(flags)?.to_u32()?;
479                let ptr = ecx.read_pointer(ptr)?;
480                // "This pointer can be NULL." It doesn't say what happens then, but presumably nothing.
481                // (https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapfree)
482                if !ecx.ptr_is_null(ptr)? {
483                    ecx.deallocate_ptr(ptr, None, MiriMemoryKind::WinHeap.into())?;
484                }
485                ecx.write_scalar(Scalar::from_i32(1), dest)?;
486            }
487            "HeapReAlloc" => {
488                // FIXME: This does not have a direct test (#3179).
489                let [handle, flags, old_ptr, size] = &ecx.check_shim_sig(
490                    shim_sig!(extern "system" fn(winapi::HANDLE, u32, *_, usize) -> *_),
491                    (link_name, abi, args),
492                )?;
493                ecx.read_target_isize(handle)?;
494                ecx.read_scalar(flags)?.to_u32()?;
495                let old_ptr = ecx.read_pointer(old_ptr)?;
496                let size = ecx.read_target_usize(size)?;
497                let align = ecx.tcx.pointer_size().bytes().strict_mul(2); // same as above
498                // The docs say that `old_ptr` must come from an earlier HeapAlloc or HeapReAlloc,
499                // so unlike C `realloc` we do *not* allow a NULL here.
500                // (https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heaprealloc)
501                let new_ptr = ecx.reallocate_ptr(
502                    old_ptr,
503                    None,
504                    Size::from_bytes(size),
505                    Align::from_bytes(align).unwrap(),
506                    MiriMemoryKind::WinHeap.into(),
507                    AllocInit::Uninit,
508                )?;
509                ecx.write_pointer(new_ptr, dest)?;
510            }
511            "LocalFree" => {
512                let [ptr] = &ecx.check_shim_sig(
513                    shim_sig!(extern "system" fn(winapi::HLOCAL) -> winapi::HLOCAL),
514                    (link_name, abi, args),
515                )?;
516                let ptr = ecx.read_pointer(ptr)?;
517                // "If the hMem parameter is NULL, LocalFree ignores the parameter and returns NULL."
518                // (https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localfree)
519                if !ecx.ptr_is_null(ptr)? {
520                    ecx.deallocate_ptr(ptr, None, MiriMemoryKind::WinLocal.into())?;
521                }
522                ecx.write_int(0, dest)?;
523            }
524
525            // errno
526            "SetLastError" => {
527                let [error] = &ecx.check_shim_sig(
528                    shim_sig!(extern "system" fn(u32) -> ()),
529                    (link_name, abi, args),
530                )?;
531                let error = ecx.read_scalar(error)?;
532                ecx.set_last_error(error)?;
533            }
534            "GetLastError" => {
535                let [] = &ecx.check_shim_sig(
536                    shim_sig!(extern "system" fn() -> u32),
537                    (link_name, abi, args),
538                )?;
539                let last_error = ecx.get_last_error()?;
540                ecx.write_scalar(last_error, dest)?;
541            }
542            "RtlNtStatusToDosError" => {
543                let [status] = &ecx.check_shim_sig(
544                    shim_sig!(extern "system" fn(i32) -> u32),
545                    (link_name, abi, args),
546                )?;
547                let status = ecx.read_scalar(status)?.to_u32()?;
548                let err = match status {
549                    // STATUS_MEDIA_WRITE_PROTECTED => ERROR_WRITE_PROTECT
550                    0xC00000A2 => 19,
551                    // STATUS_FILE_INVALID => ERROR_FILE_INVALID
552                    0xC0000098 => 1006,
553                    // STATUS_DISK_FULL => ERROR_DISK_FULL
554                    0xC000007F => 112,
555                    // STATUS_IO_DEVICE_ERROR => ERROR_IO_DEVICE
556                    0xC0000185 => 1117,
557                    // STATUS_ACCESS_DENIED => ERROR_ACCESS_DENIED
558                    0xC0000022 => 5,
559                    // Anything without an error code => ERROR_MR_MID_NOT_FOUND
560                    _ => 317,
561                };
562                ecx.write_scalar(Scalar::from_i32(err), dest)?;
563            }
564
565            // Querying system information
566            "GetSystemInfo" => {
567                // FIXME: This does not have a direct test (#3179).
568                // Also called from `page_size` crate.
569                let [system_info] = &ecx.check_shim_sig(
570                    shim_sig!(extern "system" fn(*winapi::SYSTEM_INFO) -> ()),
571                    (link_name, abi, args),
572                )?;
573                let system_info = ecx.deref_pointer(system_info)?;
574                // Initialize with `0`.
575                // FIXME: ideally we'd just initialize fields that are guaranteed to be valid.
576                ecx.write_bytes_ptr(
577                    system_info.ptr(),
578                    iter::repeat_n(0u8, system_info.layout.size.bytes_usize()),
579                )?;
580                // Set selected fields.
581                ecx.write_int_fields_named(
582                    &[
583                        ("dwPageSize", ecx.machine.page_size.into()),
584                        ("dwNumberOfProcessors", ecx.machine.num_cpus.into()),
585                    ],
586                    &system_info,
587                )?;
588            }
589
590            // Thread-local storage
591            "TlsAlloc" => {
592                // This just creates a key; Windows does not natively support TLS destructors.
593
594                // Create key and return it.
595                let [] = &ecx.check_shim_sig(
596                    shim_sig!(extern "system" fn() -> u32),
597                    (link_name, abi, args),
598                )?;
599                let key = ecx.machine.tls.create_tls_key(None, dest.layout.size)?;
600                ecx.write_int(key, dest)?;
601            }
602            "TlsGetValue" => {
603                let [key] = &ecx.check_shim_sig(
604                    shim_sig!(extern "system" fn(u32) -> *_),
605                    (link_name, abi, args),
606                )?;
607                let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?);
608                let active_thread = ecx.active_thread();
609                let ptr = ecx.machine.tls.load_tls_key(key, active_thread)?;
610                ecx.write_pointer(ptr, dest)?;
611            }
612            "TlsSetValue" => {
613                let [key, new_ptr] = &ecx.check_shim_sig(
614                    shim_sig!(extern "system" fn(u32, *_) -> winapi::BOOL),
615                    (link_name, abi, args),
616                )?;
617                let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?);
618                let active_thread = ecx.active_thread();
619                let new_data = ecx.read_pointer(new_ptr)?;
620                ecx.machine.tls.store_tls_key(key, active_thread, new_data)?;
621
622                // Return success (`1`).
623                ecx.write_int(1, dest)?;
624            }
625            "TlsFree" => {
626                let [key] = &ecx.check_shim_sig(
627                    shim_sig!(extern "system" fn(u32) -> winapi::BOOL),
628                    (link_name, abi, args),
629                )?;
630                let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?);
631                ecx.machine.tls.delete_tls_key(key)?;
632
633                // Return success (`1`).
634                ecx.write_int(1, dest)?;
635            }
636
637            // Fiber-local storage - similar to TLS but supports destructors.
638            "FlsAlloc" => {
639                // Create key and return it.
640                let [dtor] = &ecx.check_shim_sig(
641                    shim_sig!(extern "system" fn(winapi::PFLS_CALLBACK_FUNCTION) -> u32),
642                    (link_name, abi, args),
643                )?;
644                let dtor = ecx.read_pointer(dtor)?;
645
646                // Extract the function type out of the signature (that seems easier than constructing it ourselves).
647                let dtor = if !ecx.ptr_is_null(dtor)? {
648                    Some((
649                        ecx.get_ptr_fn(dtor)?.as_instance()?,
650                        ecx.machine.current_user_relevant_span(),
651                    ))
652                } else {
653                    None
654                };
655
656                let key = ecx.machine.tls.create_tls_key(dtor, dest.layout.size)?;
657                ecx.write_int(key, dest)?;
658            }
659            "FlsGetValue" => {
660                let [key] = &ecx.check_shim_sig(
661                    shim_sig!(extern "system" fn(u32) -> *_),
662                    (link_name, abi, args),
663                )?;
664                let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?);
665                let active_thread = ecx.active_thread();
666                let ptr = ecx.machine.tls.load_tls_key(key, active_thread)?;
667                ecx.write_pointer(ptr, dest)?;
668            }
669            "FlsSetValue" => {
670                let [key, new_ptr] = &ecx.check_shim_sig(
671                    shim_sig!(extern "system" fn(u32, *_) -> winapi::BOOL),
672                    (link_name, abi, args),
673                )?;
674                let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?);
675                let active_thread = ecx.active_thread();
676                let new_data = ecx.read_pointer(new_ptr)?;
677                ecx.machine.tls.store_tls_key(key, active_thread, new_data)?;
678
679                // Return success (`1`).
680                ecx.write_int(1, dest)?;
681            }
682            "FlsFree" => {
683                let [key] = &ecx.check_shim_sig(
684                    shim_sig!(extern "system" fn(u32) -> winapi::BOOL),
685                    (link_name, abi, args),
686                )?;
687                let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?);
688                let tls_entry = ecx.machine.tls.delete_tls_key(key)?;
689
690                // FIXME: We should run the destructor here *for all threads*. But that's non-trivial and std doesn't need it so we bail out with an "unsupported" error.
691                if !tls_entry.data.is_empty() && tls_entry.dtor.is_some() {
692                    throw_unsup_format!(
693                        "calling `FlsFree` on a key with an associated dtor is not supported"
694                    );
695                }
696
697                // Return success (`1`).
698                ecx.write_int(1, dest)?;
699            }
700            "IsThreadAFiber" => {
701                let [] = &ecx.check_shim_sig(
702                    shim_sig!(extern "system" fn() -> winapi::BOOL),
703                    (link_name, abi, args),
704                )?;
705
706                // Return FALSE, as Miri does not support fibers.
707                ecx.write_int(0, dest)?;
708            }
709
710            // Access to command-line arguments
711            "GetCommandLineW" => {
712                // FIXME: This does not have a direct test (#3179).
713                let [] = &ecx.check_shim_sig(
714                    shim_sig!(extern "system" fn() -> *_),
715                    (link_name, abi, args),
716                )?;
717                ecx.write_pointer(
718                    ecx.machine.cmd_line.expect("machine must be initialized"),
719                    dest,
720                )?;
721            }
722
723            // Time related shims
724            "GetSystemTimeAsFileTime" | "GetSystemTimePreciseAsFileTime" => {
725                // FIXME: This does not have a direct test (#3179).
726                let [filetime] = &ecx.check_shim_sig(
727                    shim_sig!(extern "system" fn(*winapi::FILETIME) -> ()),
728                    (link_name, abi, args),
729                )?;
730                ecx.GetSystemTimeAsFileTime(link_name.as_str(), filetime)?;
731            }
732            "QueryPerformanceCounter" => {
733                let [performance_count] = &ecx.check_shim_sig(
734                    shim_sig!(extern "system" fn(*i64) -> winapi::BOOL),
735                    (link_name, abi, args),
736                )?;
737                let result = ecx.QueryPerformanceCounter(performance_count)?;
738                ecx.write_scalar(result, dest)?;
739            }
740            "QueryPerformanceFrequency" => {
741                let [frequency] = &ecx.check_shim_sig(
742                    shim_sig!(extern "system" fn(*i64) -> winapi::BOOL),
743                    (link_name, abi, args),
744                )?;
745                let result = ecx.QueryPerformanceFrequency(frequency)?;
746                ecx.write_scalar(result, dest)?;
747            }
748            "Sleep" => {
749                // FIXME: This does not have a direct test (#3179).
750                let [timeout] = &ecx.check_shim_sig(
751                    shim_sig!(extern "system" fn(u32) -> ()),
752                    (link_name, abi, args),
753                )?;
754
755                ecx.Sleep(timeout)?;
756            }
757            "CreateWaitableTimerExW" => {
758                // FIXME: This does not have a direct test (#3179).
759                let [attributes, name, flags, access] = &ecx.check_shim_sig(
760                    shim_sig!(extern "system" fn(*_, *_, u32, u32) -> winapi::HANDLE),
761                    (link_name, abi, args),
762                )?;
763                ecx.read_pointer(attributes)?;
764                ecx.read_pointer(name)?;
765                ecx.read_scalar(flags)?.to_u32()?;
766                ecx.read_scalar(access)?.to_u32()?;
767                // Unimplemented. Always return failure.
768                let not_supported = ecx.eval_windows("c", "ERROR_NOT_SUPPORTED");
769                ecx.set_last_error(not_supported)?;
770                ecx.write_int(0, dest)?;
771            }
772
773            // Synchronization primitives
774            "InitOnceBeginInitialize" => {
775                let [ptr, flags, pending, context] = &ecx.check_shim_sig(
776                    shim_sig!(
777                        extern "system" fn(*winapi::INIT_ONCE, u32, *winapi::BOOL, *_) -> winapi::BOOL
778                    ),
779                    (link_name, abi, args),
780                )?;
781                ecx.InitOnceBeginInitialize(ptr, flags, pending, context, dest)?;
782            }
783            "InitOnceComplete" => {
784                let [ptr, flags, context] = &ecx.check_shim_sig(
785                    shim_sig!(extern "system" fn(*winapi::INIT_ONCE, u32, *_) -> winapi::BOOL),
786                    (link_name, abi, args),
787                )?;
788                let result = ecx.InitOnceComplete(ptr, flags, context)?;
789                ecx.write_scalar(result, dest)?;
790            }
791            "WaitOnAddress" => {
792                // FIXME: This does not have a direct test (#3179).
793                let [ptr_op, compare_op, size_op, timeout_op] = &ecx.check_shim_sig(
794                    // First pointer is volatile
795                    shim_sig!(extern "system" fn(*_, *_, usize, u32) -> winapi::BOOL),
796                    (link_name, abi, args),
797                )?;
798
799                ecx.WaitOnAddress(ptr_op, compare_op, size_op, timeout_op, dest)?;
800            }
801            "WakeByAddressSingle" => {
802                // FIXME: This does not have a direct test (#3179).
803                let [ptr_op] = &ecx.check_shim_sig(
804                    shim_sig!(extern "system" fn(*_) -> ()),
805                    (link_name, abi, args),
806                )?;
807
808                ecx.WakeByAddressSingle(ptr_op)?;
809            }
810            "WakeByAddressAll" => {
811                // FIXME: This does not have a direct test (#3179).
812                let [ptr_op] = &ecx.check_shim_sig(
813                    shim_sig!(extern "system" fn(*_) -> ()),
814                    (link_name, abi, args),
815                )?;
816
817                ecx.WakeByAddressAll(ptr_op)?;
818            }
819
820            // Dynamic symbol loading
821            "GetProcAddress" => {
822                // FIXME: This does not have a direct test (#3179).
823                let [module, proc_name] = &ecx.check_shim_sig(
824                    shim_sig!(extern "system" fn(winapi::HMODULE, *_) -> winapi::FARPROC),
825                    (link_name, abi, args),
826                )?;
827                ecx.read_target_isize(module)?; // FIXME validate the module!
828                let name = ecx.read_c_str(ecx.read_pointer(proc_name)?)?;
829                if let Ok(name) = str::from_utf8(name)
830                    && is_dyn_sym(name)
831                {
832                    let ptr = ecx.fn_ptr(FnVal::Other(DynSym::from_str(name)));
833                    ecx.write_pointer(ptr, dest)?;
834                } else if ecx.machine.error_on_unknown_optional_symbols {
835                    throw_unsup_format!("GetProcAddress: encountered unknown symbol {name:?}");
836                } else {
837                    ecx.write_int(0, dest)?;
838                }
839            }
840
841            // Threading
842            "CreateThread" => {
843                let [security, stacksize, start, arg, flags, thread] = &ecx.check_shim_sig(
844                    shim_sig!(
845                        extern "system" fn(
846                            *_,
847                            usize,
848                            *_,
849                            *_,
850                            u32,
851                            *u32,
852                        ) -> winapi::HANDLE
853                    ),
854                    (link_name, abi, args),
855                )?;
856
857                let thread_id = ecx.CreateThread(security, stacksize, start, arg, flags, thread)?;
858
859                ecx.write_scalar(Handle::Thread(thread_id).to_scalar(ecx), dest)?;
860            }
861            "WaitForSingleObject" => {
862                let [handle, timeout] = &ecx.check_shim_sig(
863                    shim_sig!(extern "system" fn(winapi::HANDLE, u32) -> u32),
864                    (link_name, abi, args),
865                )?;
866
867                ecx.WaitForSingleObject(handle, timeout, dest)?;
868            }
869            "GetCurrentProcess" => {
870                let [] = &ecx.check_shim_sig(
871                    shim_sig!(extern "system" fn() -> winapi::HANDLE),
872                    (link_name, abi, args),
873                )?;
874
875                ecx.write_scalar(
876                    Handle::Pseudo(PseudoHandle::CurrentProcess).to_scalar(ecx),
877                    dest,
878                )?;
879            }
880            "GetCurrentThread" => {
881                let [] = &ecx.check_shim_sig(
882                    shim_sig!(extern "system" fn() -> winapi::HANDLE),
883                    (link_name, abi, args),
884                )?;
885
886                ecx.write_scalar(Handle::Pseudo(PseudoHandle::CurrentThread).to_scalar(ecx), dest)?;
887            }
888            "SetThreadDescription" => {
889                let [handle, name] = &ecx.check_shim_sig(
890                    shim_sig!(extern "system" fn(winapi::HANDLE, *_) -> i32),
891                    (link_name, abi, args),
892                )?;
893
894                let handle = ecx.read_handle(handle, "SetThreadDescription")?;
895                let name = ecx.read_wide_str(ecx.read_pointer(name)?)?;
896
897                let thread = match handle {
898                    Handle::Thread(thread) => thread,
899                    Handle::Pseudo(PseudoHandle::CurrentThread) => ecx.active_thread(),
900                    _ => ecx.invalid_handle("SetThreadDescription")?,
901                };
902                // FIXME: use non-lossy conversion
903                ecx.set_thread_name(thread, String::from_utf16_lossy(&name).into_bytes());
904                ecx.write_scalar(Scalar::from_u32(0), dest)?;
905            }
906            "GetThreadDescription" => {
907                let [handle, name_ptr] = &ecx.check_shim_sig(
908                    shim_sig!(extern "system" fn(winapi::HANDLE, **u16) -> i32),
909                    (link_name, abi, args),
910                )?;
911
912                let handle = ecx.read_handle(handle, "GetThreadDescription")?;
913                let name_ptr = ecx.deref_pointer(name_ptr)?; // the pointer where we should store the ptr to the name
914
915                let thread = match handle {
916                    Handle::Thread(thread) => thread,
917                    Handle::Pseudo(PseudoHandle::CurrentThread) => ecx.active_thread(),
918                    _ => ecx.invalid_handle("GetThreadDescription")?,
919                };
920                // Looks like the default thread name is empty.
921                let name = ecx.get_thread_name(thread).unwrap_or(b"").to_owned();
922                let name = ecx.alloc_os_str_as_wide_str(
923                    bytes_to_os_str(&name)?,
924                    MiriMemoryKind::WinLocal.into(),
925                )?;
926                let name = Scalar::from_maybe_pointer(name, ecx);
927                let res = Scalar::from_u32(0);
928
929                ecx.write_scalar(name, &name_ptr)?;
930                ecx.write_scalar(res, dest)?;
931            }
932            "GetThreadId" => {
933                let [handle] = &ecx.check_shim_sig(
934                    shim_sig!(extern "system" fn(winapi::HANDLE) -> u32),
935                    (link_name, abi, args),
936                )?;
937                let handle = ecx.read_handle(handle, "GetThreadId")?;
938                let thread = match handle {
939                    Handle::Thread(thread) => thread,
940                    Handle::Pseudo(PseudoHandle::CurrentThread) => ecx.active_thread(),
941                    _ => ecx.invalid_handle("GetThreadDescription")?,
942                };
943                ecx.write_scalar(Scalar::from_u32(thread.to_u32()), dest)?;
944            }
945            "GetCurrentThreadId" => {
946                let [] = &ecx.check_shim_sig(
947                    shim_sig!(extern "system" fn() -> u32),
948                    (link_name, abi, args),
949                )?;
950                ecx.write_scalar(Scalar::from_u32(ecx.active_thread().to_u32()), dest)?;
951            }
952
953            // Miscellaneous
954            "ExitProcess" => {
955                // FIXME: This does not have a direct test (#3179).
956                let [code] = &ecx.check_shim_sig(
957                    shim_sig!(extern "system" fn(u32) -> ()),
958                    (link_name, abi, args),
959                )?;
960                // Windows technically uses u32, but we unify everything to a Unix-style i32.
961                let exit_code = ecx.read_scalar(code)?.to_i32()?;
962                // Initialize the at-exit state machine.
963                ecx.replace_active_thread_stack({
964                    let mut state_machine =
965                        ProgramExitHandler::new(exit_code, ExitType::ExitCalled);
966                    Box::new(move |m| state_machine.on_stack_empty(m))
967                });
968                // We "jumped" to the exit handling.
969                return interp_ok(EmulateItemResult::AlreadyJumped);
970            }
971            "SystemFunction036" => {
972                // used by getrandom 0.1
973                // This is really 'RtlGenRandom'.
974                let [ptr, len] = &ecx.check_shim_sig(
975                    // Returns winapi::BOOLEAN, which is a byte
976                    shim_sig!(extern "system" fn(*_, u32) -> u8),
977                    (link_name, abi, args),
978                )?;
979                let ptr = ecx.read_pointer(ptr)?;
980                let len = ecx.read_scalar(len)?.to_u32()?;
981                ecx.gen_random(ptr, len.into())?;
982                ecx.write_scalar(Scalar::from_bool(true), dest)?;
983            }
984            "ProcessPrng" => {
985                // used by `std`
986                let [ptr, len] = &ecx.check_shim_sig(
987                    shim_sig!(extern "system" fn(*_, usize) -> winapi::BOOL),
988                    (link_name, abi, args),
989                )?;
990                let ptr = ecx.read_pointer(ptr)?;
991                let len = ecx.read_target_usize(len)?;
992                ecx.gen_random(ptr, len)?;
993                ecx.write_int(1, dest)?;
994            }
995            "BCryptGenRandom" => {
996                // used by getrandom 0.2
997                let [algorithm, ptr, len, flags] = &ecx.check_shim_sig(
998                    shim_sig!(extern "system" fn(*_, *_, u32, u32) -> i32),
999                    (link_name, abi, args),
1000                )?;
1001                let algorithm = ecx.read_scalar(algorithm)?;
1002                let algorithm = algorithm.to_target_usize(ecx)?;
1003                let ptr = ecx.read_pointer(ptr)?;
1004                let len = ecx.read_scalar(len)?.to_u32()?;
1005                let flags = ecx.read_scalar(flags)?.to_u32()?;
1006                match flags {
1007                    0 => {
1008                        if algorithm != 0x81 {
1009                            // BCRYPT_RNG_ALG_HANDLE
1010                            throw_unsup_format!(
1011                                "BCryptGenRandom algorithm must be BCRYPT_RNG_ALG_HANDLE when the flag is 0"
1012                            );
1013                        }
1014                    }
1015                    2 => {
1016                        // BCRYPT_USE_SYSTEM_PREFERRED_RNG
1017                        if algorithm != 0 {
1018                            throw_unsup_format!(
1019                                "BCryptGenRandom algorithm must be NULL when the flag is BCRYPT_USE_SYSTEM_PREFERRED_RNG"
1020                            );
1021                        }
1022                    }
1023                    _ => {
1024                        throw_unsup_format!(
1025                            "BCryptGenRandom is only supported with BCRYPT_USE_SYSTEM_PREFERRED_RNG or BCRYPT_RNG_ALG_HANDLE"
1026                        );
1027                    }
1028                }
1029                ecx.gen_random(ptr, len.into())?;
1030                ecx.write_int(0, dest)?; // STATUS_SUCCESS
1031            }
1032            "GetConsoleScreenBufferInfo" => {
1033                // FIXME: This does not have a direct test (#3179).
1034                // `term` needs this, so we fake it.
1035                let [console, buffer_info] = &ecx.check_shim_sig(
1036                    shim_sig!(extern "system" fn(winapi::HANDLE, *_) -> winapi::BOOL),
1037                    (link_name, abi, args),
1038                )?;
1039                ecx.read_target_isize(console)?;
1040                ecx.read_pointer(buffer_info)?;
1041                // Indicate an error.
1042                ecx.set_last_error(io::ErrorKind::Unsupported)?;
1043                ecx.write_int(0, dest)?;
1044            }
1045            "GetStdHandle" => {
1046                // FIXME: This does not have a direct test (#3179).
1047                let [which] = &ecx.check_shim_sig(
1048                    shim_sig!(extern "system" fn(u32) -> winapi::HANDLE),
1049                    (link_name, abi, args),
1050                )?;
1051                let res = ecx.GetStdHandle(which)?;
1052                ecx.write_scalar(res, dest)?;
1053            }
1054            "DuplicateHandle" => {
1055                let [src_proc, src_handle, target_proc, target_handle, access, inherit, options] =
1056                    &ecx.check_shim_sig(
1057                        shim_sig!(
1058                            extern "system" fn(
1059                                winapi::HANDLE,
1060                                winapi::HANDLE,
1061                                winapi::HANDLE,
1062                                *winapi::HANDLE,
1063                                u32,
1064                                winapi::BOOL,
1065                                u32,
1066                            ) -> winapi::BOOL
1067                        ),
1068                        (link_name, abi, args),
1069                    )?;
1070                let res = ecx.DuplicateHandle(
1071                    src_proc,
1072                    src_handle,
1073                    target_proc,
1074                    target_handle,
1075                    access,
1076                    inherit,
1077                    options,
1078                )?;
1079                ecx.write_scalar(res, dest)?;
1080            }
1081            "CloseHandle" => {
1082                let [handle] = &ecx.check_shim_sig(
1083                    shim_sig!(extern "system" fn(winapi::HANDLE) -> winapi::BOOL),
1084                    (link_name, abi, args),
1085                )?;
1086
1087                let ret = ecx.CloseHandle(handle)?;
1088
1089                ecx.write_scalar(ret, dest)?;
1090            }
1091            "GetModuleFileNameW" => {
1092                // FIXME: This does not have a direct test (#3179).
1093                let [handle, filename, size] = &ecx.check_shim_sig(
1094                    shim_sig!(extern "system" fn(winapi::HMODULE, *_, u32) -> u32),
1095                    (link_name, abi, args),
1096                )?;
1097                ecx.check_no_isolation("`GetModuleFileNameW`")?;
1098
1099                let handle = ecx.read_handle(handle, "GetModuleFileNameW")?;
1100                let filename = ecx.read_pointer(filename)?;
1101                let size = ecx.read_scalar(size)?.to_u32()?;
1102
1103                if handle != Handle::Null {
1104                    throw_unsup_format!("`GetModuleFileNameW` only supports the NULL handle");
1105                }
1106
1107                let Some(path) = ecx.machine.current_exe.clone() else {
1108                    throw_unsup_format!("GetModuleFileNameW only works when Miri is run on a file")
1109                };
1110                let (all_written, size_needed) =
1111                    ecx.write_path_to_wide_str_truncated(&path, filename, size.into())?;
1112
1113                if all_written {
1114                    // If the function succeeds, the return value is the length of the string that
1115                    // is copied to the buffer, in characters, not including the terminating null
1116                    // character.
1117                    ecx.write_int(size_needed.strict_sub(1), dest)?;
1118                } else {
1119                    // If the buffer is too small to hold the module name, the string is truncated
1120                    // to nSize characters including the terminating null character, the function
1121                    // returns nSize, and the function sets the last error to
1122                    // ERROR_INSUFFICIENT_BUFFER.
1123                    ecx.write_int(size, dest)?;
1124                    let insufficient_buffer = ecx.eval_windows("c", "ERROR_INSUFFICIENT_BUFFER");
1125                    ecx.set_last_error(insufficient_buffer)?;
1126                }
1127            }
1128            "FormatMessageW" => {
1129                // FIXME: This does not have a direct test (#3179).
1130                let [flags, module, message_id, language_id, buffer, size, arguments] = &ecx
1131                    .check_shim_sig(
1132                        shim_sig!(
1133                            extern "system" fn(u32, *_, u32, u32, *_, u32, *_) -> u32
1134                        ),
1135                        (link_name, abi, args),
1136                    )?;
1137
1138                let flags = ecx.read_scalar(flags)?.to_u32()?;
1139                let _module = ecx.read_pointer(module)?; // seems to contain a module name
1140                let message_id = ecx.read_scalar(message_id)?;
1141                let _language_id = ecx.read_scalar(language_id)?.to_u32()?;
1142                let buffer = ecx.read_pointer(buffer)?;
1143                let size = ecx.read_scalar(size)?.to_u32()?;
1144                let _arguments = ecx.read_pointer(arguments)?;
1145
1146                // We only support `FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS`
1147                // This also means `arguments` can be ignored.
1148                if flags != 4096u32 | 512u32 {
1149                    throw_unsup_format!("FormatMessageW: unsupported flags {flags:#x}");
1150                }
1151
1152                let error = ecx.try_errnum_to_io_error(message_id)?;
1153                let formatted = match error {
1154                    Some(err) => format!("{err}"),
1155                    None => format!("<unknown error in FormatMessageW: {message_id}>"),
1156                };
1157                let (complete, length) =
1158                    ecx.write_os_str_to_wide_str(OsStr::new(&formatted), buffer, size.into())?;
1159                if !complete {
1160                    // The API docs don't say what happens when the buffer is not big enough...
1161                    // Let's just bail.
1162                    throw_unsup_format!("FormatMessageW: buffer not big enough");
1163                }
1164                // The return value is the number of characters stored *excluding* the null terminator.
1165                ecx.write_int(length.strict_sub(1), dest)?;
1166            }
1167
1168            "_Unwind_RaiseException" => {
1169                // This is not formally part of POSIX, but it is very wide-spread on POSIX systems.
1170                // It was originally specified as part of the Itanium C++ ABI:
1171                // https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html#base-throw.
1172                // MinGW implements _Unwind_RaiseException on top of SEH exceptions.
1173                if ecx.tcx.sess.target.env != Env::Gnu {
1174                    throw_unsup_format!(
1175                        "`_Unwind_RaiseException` is not supported on non-MinGW Windows",
1176                    );
1177                }
1178                // This function looks and behaves exactly like miri_start_unwind.
1179                let [payload] = &ecx.check_shim_sig(
1180                    // Look up the return type via `panic_unwind::`, not via `unwind::`, as
1181                    // the latter it not always unique.
1182                    shim_sig!(extern "C" fn(*_) -> panic_unwind::imp::uw::_Unwind_Reason_Code),
1183                    (link_name, abi, args),
1184                )?;
1185                ecx.handle_miri_start_unwind(payload)?;
1186                return interp_ok(EmulateItemResult::NeedsUnwind);
1187            }
1188
1189            // Incomplete shims that we "stub out" just to get std to work.
1190            // These shims are enabled only when the caller is in the standard library.
1191            "NtQueryVolumeInformationFile" if ecx.frame_in_std() => {
1192                let [_handle, _iosb, _info, _length, _class] = &ecx.check_shim_sig(
1193                    shim_sig!(extern "system" fn(winapi::HANDLE, *_, *_, u32, i32) -> i32),
1194                    (link_name, abi, args),
1195                )?;
1196                // Return an error to make std think that nothing is a console.
1197                // This means the normal NtWriteFile is used for stdout/stderr, greatly simplifying our lives.
1198                let not_implemented = ecx.eval_windows("c", "STATUS_NOT_IMPLEMENTED");
1199                ecx.write_scalar(not_implemented, dest)?;
1200            }
1201            "GetProcessHeap" if ecx.frame_in_std() => {
1202                let [] = &ecx.check_shim_sig(
1203                    shim_sig!(extern "system" fn() -> winapi::HANDLE),
1204                    (link_name, abi, args),
1205                )?;
1206                // Just fake a HANDLE
1207                // It's fine to not use the Handle type here because its a stub
1208                ecx.write_int(1, dest)?;
1209            }
1210            "GetModuleHandleA" if ecx.frame_in_std() => {
1211                let [_module_name] = &ecx.check_shim_sig(
1212                    shim_sig!(extern "system" fn(*_) -> winapi::HMODULE),
1213                    (link_name, abi, args),
1214                )?;
1215                // We need to return something non-null here to make `compat_fn!` work.
1216                ecx.write_int(1, dest)?;
1217            }
1218            "GetModuleHandleW" if ecx.frame_in_std() => {
1219                let [_module_name] = &ecx.check_shim_sig(
1220                    shim_sig!(extern "system" fn(*_) -> winapi::HMODULE),
1221                    (link_name, abi, args),
1222                )?;
1223                // Returning null works best for `format_error`.
1224                ecx.write_int(0, dest)?;
1225            }
1226            "SetConsoleTextAttribute" if ecx.frame_in_std() => {
1227                let [_console_output, _attribute] = &ecx.check_shim_sig(
1228                    shim_sig!(extern "system" fn(winapi::HANDLE, u16) -> winapi::BOOL),
1229                    (link_name, abi, args),
1230                )?;
1231                // Pretend these does not exist / nothing happened, by returning zero.
1232                ecx.write_int(0, dest)?;
1233            }
1234            "AddVectoredExceptionHandler" if ecx.frame_in_std() => {
1235                let [_first, _handler] = &ecx.check_shim_sig(
1236                    shim_sig!(extern "system" fn(u32, *_) -> *_),
1237                    (link_name, abi, args),
1238                )?;
1239                // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
1240                ecx.write_int(1, dest)?;
1241            }
1242            "SetThreadStackGuarantee" if ecx.frame_in_std() => {
1243                let [_stack_size_in_bytes] = &ecx.check_shim_sig(
1244                    shim_sig!(extern "system" fn(*_) -> winapi::BOOL),
1245                    (link_name, abi, args),
1246                )?;
1247                // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
1248                ecx.write_int(1, dest)?;
1249            }
1250            "SwitchToThread" if ecx.frame_in_std() => {
1251                // this is only callable from std because we know that std ignores the return value
1252                let [] = &ecx.check_shim_sig(
1253                    shim_sig!(extern "system" fn() -> winapi::BOOL),
1254                    (link_name, abi, args),
1255                )?;
1256
1257                ecx.yield_active_thread();
1258
1259                // FIXME: this should return a nonzero value if this call does result in switching to another thread.
1260                ecx.write_int(0, dest)?;
1261            }
1262            "GetFinalPathNameByHandleW" if ecx.frame_in_std() => {
1263                // Std uses this when debug-printing `File`. We stub it out by returning an error.
1264                let [_file, _buf, _bufsz, _flags] = &ecx.check_shim_sig(
1265                    shim_sig!(extern "system" fn(winapi::HANDLE, *_, u32, u32) -> u32),
1266                    (link_name, abi, args),
1267                )?;
1268
1269                ecx.set_last_error(IoError::WindowsError("ERROR_NOT_SUPPORTED"))?;
1270                ecx.write_int(0, dest)?;
1271            }
1272
1273            _ => return interp_ok(EmulateItemResult::NotSupported),
1274        }
1275
1276        interp_ok(EmulateItemResult::NeedsReturn)
1277    }
1278}