about summary refs log tree commit diff
path: root/src/tools/miri/tests/pass-dep/shims/windows-fs.rs
blob: 7b756603d929b3898dc2584a8181e38e4b4f45db (plain)
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//@only-target: windows # this directly tests windows-only functions
//@compile-flags: -Zmiri-disable-isolation
#![allow(nonstandard_style)]

use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle};
use std::path::Path;
use std::{fs, mem, ptr};

#[path = "../../utils/mod.rs"]
mod utils;

use windows_sys::Wdk::Storage::FileSystem::{NtReadFile, NtWriteFile};
use windows_sys::Win32::Foundation::{
    CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, ERROR_ACCESS_DENIED, ERROR_ALREADY_EXISTS,
    ERROR_IO_DEVICE, FALSE, GENERIC_READ, GENERIC_WRITE, GetLastError, RtlNtStatusToDosError,
    STATUS_ACCESS_DENIED, STATUS_IO_DEVICE_ERROR, STATUS_SUCCESS, SetLastError,
};
use windows_sys::Win32::Storage::FileSystem::{
    BY_HANDLE_FILE_INFORMATION, CREATE_ALWAYS, CREATE_NEW, CreateFileW, DeleteFileW,
    FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL, FILE_BEGIN, FILE_CURRENT,
    FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ,
    FILE_SHARE_WRITE, GetFileInformationByHandle, OPEN_ALWAYS, OPEN_EXISTING, SetFilePointerEx,
};
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::Threading::GetCurrentProcess;

fn main() {
    unsafe {
        test_create_dir_file();
        test_create_normal_file();
        test_create_always_twice();
        test_open_always_twice();
        test_open_dir_reparse();
        test_delete_file();
        test_ntstatus_to_dos();
        test_file_read_write();
        test_file_seek();
        test_dup_handle();
    }
}

unsafe fn test_create_dir_file() {
    let temp = utils::tmp();
    let raw_path = to_wide_cstr(&temp);
    // Open the `temp` directory.
    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        OPEN_EXISTING,
        FILE_FLAG_BACKUP_SEMANTICS,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    let mut info = std::mem::zeroed::<BY_HANDLE_FILE_INFORMATION>();
    if GetFileInformationByHandle(handle, &mut info) == 0 {
        panic!("Failed to get file information")
    };
    assert!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };
}

unsafe fn test_create_normal_file() {
    let temp = utils::tmp().join("test.txt");
    let raw_path = to_wide_cstr(&temp);
    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        CREATE_NEW,
        0,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    let mut info = std::mem::zeroed::<BY_HANDLE_FILE_INFORMATION>();
    if GetFileInformationByHandle(handle, &mut info) == 0 {
        panic!("Failed to get file information: {}", GetLastError())
    };
    assert!(info.dwFileAttributes & FILE_ATTRIBUTE_NORMAL != 0);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };

    // Test metadata-only handle
    let handle = CreateFileW(
        raw_path.as_ptr(),
        0,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        OPEN_EXISTING,
        0,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    let mut info = std::mem::zeroed::<BY_HANDLE_FILE_INFORMATION>();
    if GetFileInformationByHandle(handle, &mut info) == 0 {
        panic!("Failed to get file information: {}", GetLastError())
    };
    assert!(info.dwFileAttributes & FILE_ATTRIBUTE_NORMAL != 0);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };
}

/// Tests that CREATE_ALWAYS sets the error value correctly based on whether the file already exists
unsafe fn test_create_always_twice() {
    let temp = utils::tmp().join("test_create_always.txt");
    let raw_path = to_wide_cstr(&temp);
    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        CREATE_ALWAYS,
        0,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    assert_eq!(GetLastError(), 0);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };

    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        CREATE_ALWAYS,
        0,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    assert_eq!(GetLastError(), ERROR_ALREADY_EXISTS);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };
}

/// Tests that OPEN_ALWAYS sets the error value correctly based on whether the file already exists
unsafe fn test_open_always_twice() {
    let temp = utils::tmp().join("test_open_always.txt");
    let raw_path = to_wide_cstr(&temp);
    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        OPEN_ALWAYS,
        0,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    assert_eq!(GetLastError(), 0);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };

    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        OPEN_ALWAYS,
        0,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    assert_eq!(GetLastError(), ERROR_ALREADY_EXISTS);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };
}

// TODO: Once we support more of the std API, it would be nice to test against an actual symlink
unsafe fn test_open_dir_reparse() {
    let temp = utils::tmp();
    let raw_path = to_wide_cstr(&temp);
    // Open the `temp` directory.
    let handle = CreateFileW(
        raw_path.as_ptr(),
        GENERIC_READ,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        ptr::null_mut(),
        OPEN_EXISTING,
        FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
        ptr::null_mut(),
    );
    assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError());
    let mut info = std::mem::zeroed::<BY_HANDLE_FILE_INFORMATION>();
    if GetFileInformationByHandle(handle, &mut info) == 0 {
        panic!("Failed to get file information")
    };
    assert!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0);
    if CloseHandle(handle) == 0 {
        panic!("Failed to close file")
    };
}

unsafe fn test_delete_file() {
    let temp = utils::tmp().join("test_delete_file.txt");
    let raw_path = to_wide_cstr(&temp);
    let _ = fs::File::create(&temp).unwrap();

    if DeleteFileW(raw_path.as_ptr()) == 0 {
        panic!("Failed to delete file");
    }

    match fs::File::open(temp) {
        Ok(_) => panic!("File not deleted"),
        Err(e) => assert!(e.kind() == ErrorKind::NotFound, "File not deleted"),
    }
}

unsafe fn test_ntstatus_to_dos() {
    // We won't test all combinations, just a couple common ones
    assert_eq!(RtlNtStatusToDosError(STATUS_IO_DEVICE_ERROR), ERROR_IO_DEVICE);
    assert_eq!(RtlNtStatusToDosError(STATUS_ACCESS_DENIED), ERROR_ACCESS_DENIED);
}

unsafe fn test_file_read_write() {
    let temp = utils::tmp().join("test_file_read_write.txt");
    let file = fs::File::create(&temp).unwrap();
    let handle = file.as_raw_handle();

    // Testing NtWriteFile doesn't clobber the error
    SetLastError(1234);

    let text = b"Example text!";
    let mut status = std::mem::zeroed::<IO_STATUS_BLOCK>();
    let out = NtWriteFile(
        handle,
        ptr::null_mut(),
        None,
        ptr::null_mut(),
        &mut status,
        text.as_ptr().cast(),
        text.len() as u32,
        ptr::null_mut(),
        ptr::null_mut(),
    );

    assert_eq!(out, status.Anonymous.Status);
    assert_eq!(out, STATUS_SUCCESS);
    assert_eq!(GetLastError(), 1234);

    let file = fs::File::open(&temp).unwrap();
    let handle = file.as_raw_handle();

    // Testing NtReadFile doesn't clobber the error
    SetLastError(1234);

    let mut buffer = vec![0; 13];
    let out = NtReadFile(
        handle,
        ptr::null_mut(),
        None,
        ptr::null_mut(),
        &mut status,
        buffer.as_mut_ptr().cast(),
        buffer.len() as u32,
        ptr::null_mut(),
        ptr::null_mut(),
    );

    assert_eq!(out, status.Anonymous.Status);
    assert_eq!(out, STATUS_SUCCESS);
    assert_eq!(buffer, text);
    assert_eq!(GetLastError(), 1234);
}

unsafe fn test_dup_handle() {
    let temp = utils::tmp().join("test_dup.txt");

    let mut file1 = fs::File::options().read(true).write(true).create(true).open(&temp).unwrap();

    file1.write_all(b"Hello, World!\n").unwrap();
    file1.seek(SeekFrom::Start(0)).unwrap();

    let first_handle = file1.as_raw_handle();

    let cur_proc = GetCurrentProcess();
    let mut second_handle = mem::zeroed();
    let res = DuplicateHandle(
        cur_proc,
        first_handle,
        cur_proc,
        &mut second_handle,
        0,
        FALSE,
        DUPLICATE_SAME_ACCESS,
    );
    assert!(res != 0);

    let mut buf1 = [0; 5];
    file1.read(&mut buf1).unwrap();
    assert_eq!(&buf1, b"Hello");

    let mut file2 = fs::File::from_raw_handle(second_handle);
    let mut buf2 = [0; 5];
    file2.read(&mut buf2).unwrap();
    assert_eq!(&buf2, b", Wor");
}

unsafe fn test_file_seek() {
    let temp = utils::tmp().join("test_file_seek.txt");
    let mut file = fs::File::options().create(true).write(true).read(true).open(&temp).unwrap();
    file.write_all(b"Hello, World!\n").unwrap();

    let handle = file.as_raw_handle();

    if SetFilePointerEx(handle, 7, ptr::null_mut(), FILE_BEGIN) == 0 {
        panic!("Failed to seek");
    }

    let mut buf = vec![0; 5];
    file.read(&mut buf).unwrap();
    assert_eq!(buf, b"World");

    let mut pos = 0;
    if SetFilePointerEx(handle, -7, &mut pos, FILE_CURRENT) == 0 {
        panic!("Failed to seek");
    }
    buf.truncate(2);
    file.read_exact(&mut buf).unwrap();
    assert_eq!(buf, b", ");
    assert_eq!(pos, 5);
}

fn to_wide_cstr(path: &Path) -> Vec<u16> {
    let mut raw_path = path.as_os_str().encode_wide().collect::<Vec<_>>();
    raw_path.extend([0, 0]);
    raw_path
}