Repository navigation
Expand file tree
/
Copy pathnt.rs
More file actions
815 lines (718 loc) · 27 KB
/
Copy pathnt.rs
File metadata and controls
815 lines (718 loc) · 27 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
// spell-checker:disable
use crate::{PyRef, VirtualMachine, builtins::PyModule};
pub use module::raw_set_handle_inheritable;
pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> {
let module = module::make_module(vm);
super::os::extend_module(vm, &module);
module
}
#[pymodule(name = "nt", with(super::os::_os))]
pub(crate) mod module {
use crate::{
PyResult, TryFromObject, VirtualMachine,
builtins::{PyBaseExceptionRef, PyDictRef, PyListRef, PyStrRef, PyTupleRef},
common::{crt_fd, os::last_os_error, suppress_iph, windows::ToWideString},
convert::ToPyException,
function::{Either, OptionalArg},
ospath::OsPath,
stdlib::os::{_os, DirFd, FollowSymlinks, SupportFunc, TargetIsDirectory, errno_err},
};
use libc::intptr_t;
use std::os::windows::io::AsRawHandle;
use std::{env, fs, io, mem::MaybeUninit, os::windows::ffi::OsStringExt};
use windows_sys::Win32::{
Foundation::{self, INVALID_HANDLE_VALUE},
Storage::FileSystem,
System::{Console, Threading},
};
#[pyattr]
use libc::{O_BINARY, O_NOINHERIT, O_RANDOM, O_SEQUENTIAL, O_TEMPORARY, O_TEXT};
// Windows spawn mode constants
#[pyattr]
const P_WAIT: i32 = 0;
#[pyattr]
const P_NOWAIT: i32 = 1;
#[pyattr]
const P_OVERLAY: i32 = 2;
#[pyattr]
const P_NOWAITO: i32 = 3;
#[pyattr]
const P_DETACH: i32 = 4;
// _O_SHORT_LIVED is not in libc, define manually
#[pyattr]
const O_SHORT_LIVED: i32 = 0x1000;
// Exit code constant
#[pyattr]
const EX_OK: i32 = 0;
// Maximum number of temporary files
#[pyattr]
const TMP_MAX: i32 = i32::MAX;
#[pyattr]
use windows_sys::Win32::System::LibraryLoader::{
LOAD_LIBRARY_SEARCH_APPLICATION_DIR as _LOAD_LIBRARY_SEARCH_APPLICATION_DIR,
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS as _LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR as _LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR,
LOAD_LIBRARY_SEARCH_SYSTEM32 as _LOAD_LIBRARY_SEARCH_SYSTEM32,
LOAD_LIBRARY_SEARCH_USER_DIRS as _LOAD_LIBRARY_SEARCH_USER_DIRS,
};
#[pyfunction]
pub(super) fn access(path: OsPath, mode: u8, vm: &VirtualMachine) -> PyResult<bool> {
let attr = unsafe { FileSystem::GetFileAttributesW(path.to_wide_cstring(vm)?.as_ptr()) };
Ok(attr != FileSystem::INVALID_FILE_ATTRIBUTES
&& (mode & 2 == 0
|| attr & FileSystem::FILE_ATTRIBUTE_READONLY == 0
|| attr & FileSystem::FILE_ATTRIBUTE_DIRECTORY != 0))
}
#[pyfunction]
pub(super) fn _supports_virtual_terminal() -> PyResult<bool> {
// TODO: implement this
Ok(true)
}
#[derive(FromArgs)]
pub(super) struct SymlinkArgs<'fd> {
src: OsPath,
dst: OsPath,
#[pyarg(flatten)]
target_is_directory: TargetIsDirectory,
#[pyarg(flatten)]
_dir_fd: DirFd<'fd, { _os::SYMLINK_DIR_FD as usize }>,
}
#[pyfunction]
pub(super) fn symlink(args: SymlinkArgs<'_>, vm: &VirtualMachine) -> PyResult<()> {
use std::os::windows::fs as win_fs;
let dir = args.target_is_directory.target_is_directory
|| args
.dst
.as_path()
.parent()
.and_then(|dst_parent| dst_parent.join(&args.src).symlink_metadata().ok())
.is_some_and(|meta| meta.is_dir());
let res = if dir {
win_fs::symlink_dir(args.src.path, args.dst.path)
} else {
win_fs::symlink_file(args.src.path, args.dst.path)
};
res.map_err(|err| err.to_pyexception(vm))
}
#[pyfunction]
fn set_inheritable(
fd: crt_fd::Borrowed<'_>,
inheritable: bool,
vm: &VirtualMachine,
) -> PyResult<()> {
let handle = crt_fd::as_handle(fd).map_err(|e| e.to_pyexception(vm))?;
set_handle_inheritable(handle.as_raw_handle() as _, inheritable, vm)
}
#[pyattr]
fn environ(vm: &VirtualMachine) -> PyDictRef {
let environ = vm.ctx.new_dict();
for (key, value) in env::vars() {
environ.set_item(&key, vm.new_pyobj(value), vm).unwrap();
}
environ
}
#[pyfunction]
fn chmod(
path: OsPath,
dir_fd: DirFd<'_, 0>,
mode: u32,
follow_symlinks: FollowSymlinks,
vm: &VirtualMachine,
) -> PyResult<()> {
const S_IWRITE: u32 = 128;
let [] = dir_fd.0;
let metadata = if follow_symlinks.0 {
fs::metadata(&path)
} else {
fs::symlink_metadata(&path)
};
let meta = metadata.map_err(|err| err.to_pyexception(vm))?;
let mut permissions = meta.permissions();
permissions.set_readonly(mode & S_IWRITE == 0);
fs::set_permissions(&path, permissions).map_err(|err| err.to_pyexception(vm))
}
// cwait is available on MSVC only (according to CPython)
#[cfg(target_env = "msvc")]
unsafe extern "C" {
fn _cwait(termstat: *mut i32, procHandle: intptr_t, action: i32) -> intptr_t;
}
#[cfg(target_env = "msvc")]
#[pyfunction]
fn waitpid(pid: intptr_t, opt: i32, vm: &VirtualMachine) -> PyResult<(intptr_t, u64)> {
let mut status: i32 = 0;
let pid = unsafe { suppress_iph!(_cwait(&mut status, pid, opt)) };
if pid == -1 {
Err(errno_err(vm))
} else {
// Cast to unsigned to handle large exit codes (like 0xC000013A)
// then shift left by 8 to match POSIX waitpid format
let ustatus = (status as u32) as u64;
Ok((pid, ustatus << 8))
}
}
#[cfg(target_env = "msvc")]
#[pyfunction]
fn wait(vm: &VirtualMachine) -> PyResult<(intptr_t, u64)> {
waitpid(-1, 0, vm)
}
#[pyfunction]
fn kill(pid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> {
let sig = sig as u32;
let pid = pid as u32;
if sig == Console::CTRL_C_EVENT || sig == Console::CTRL_BREAK_EVENT {
let ret = unsafe { Console::GenerateConsoleCtrlEvent(sig, pid) };
let res = if ret == 0 { Err(errno_err(vm)) } else { Ok(()) };
return res;
}
let h = unsafe { Threading::OpenProcess(Threading::PROCESS_ALL_ACCESS, 0, pid) };
if h.is_null() {
return Err(errno_err(vm));
}
let ret = unsafe { Threading::TerminateProcess(h, sig) };
let res = if ret == 0 { Err(errno_err(vm)) } else { Ok(()) };
unsafe { Foundation::CloseHandle(h) };
res
}
#[pyfunction]
fn get_terminal_size(
fd: OptionalArg<i32>,
vm: &VirtualMachine,
) -> PyResult<_os::TerminalSizeData> {
let (columns, lines) = {
let stdhandle = match fd {
OptionalArg::Present(0) => Console::STD_INPUT_HANDLE,
OptionalArg::Present(1) | OptionalArg::Missing => Console::STD_OUTPUT_HANDLE,
OptionalArg::Present(2) => Console::STD_ERROR_HANDLE,
_ => return Err(vm.new_value_error("bad file descriptor")),
};
let h = unsafe { Console::GetStdHandle(stdhandle) };
if h.is_null() {
return Err(vm.new_os_error("handle cannot be retrieved".to_owned()));
}
if h == INVALID_HANDLE_VALUE {
return Err(errno_err(vm));
}
let mut csbi = MaybeUninit::uninit();
let ret = unsafe { Console::GetConsoleScreenBufferInfo(h, csbi.as_mut_ptr()) };
let csbi = unsafe { csbi.assume_init() };
if ret == 0 {
return Err(errno_err(vm));
}
let w = csbi.srWindow;
(
(w.Right - w.Left + 1) as usize,
(w.Bottom - w.Top + 1) as usize,
)
};
Ok(_os::TerminalSizeData { columns, lines })
}
#[cfg(target_env = "msvc")]
unsafe extern "C" {
fn _wexecv(cmdname: *const u16, argv: *const *const u16) -> intptr_t;
fn _wexecve(
cmdname: *const u16,
argv: *const *const u16,
envp: *const *const u16,
) -> intptr_t;
fn _wspawnv(mode: i32, cmdname: *const u16, argv: *const *const u16) -> intptr_t;
fn _wspawnve(
mode: i32,
cmdname: *const u16,
argv: *const *const u16,
envp: *const *const u16,
) -> intptr_t;
}
#[cfg(target_env = "msvc")]
#[pyfunction]
fn spawnv(
mode: i32,
path: OsPath,
argv: Either<PyListRef, PyTupleRef>,
vm: &VirtualMachine,
) -> PyResult<intptr_t> {
use std::iter::once;
let make_widestring =
|s: &str| widestring::WideCString::from_os_str(s).map_err(|err| err.to_pyexception(vm));
let path = path.to_wide_cstring(vm)?;
let argv = vm.extract_elements_with(argv.as_ref(), |obj| {
let arg = PyStrRef::try_from_object(vm, obj)?;
make_widestring(arg.as_str())
})?;
let first = argv
.first()
.ok_or_else(|| vm.new_value_error("spawnv() arg 3 must not be empty"))?;
if first.is_empty() {
return Err(vm.new_value_error("spawnv() arg 3 first element cannot be empty"));
}
let argv_spawn: Vec<*const u16> = argv
.iter()
.map(|v| v.as_ptr())
.chain(once(std::ptr::null()))
.collect();
let result = unsafe { suppress_iph!(_wspawnv(mode, path.as_ptr(), argv_spawn.as_ptr())) };
if result == -1 {
Err(errno_err(vm))
} else {
Ok(result)
}
}
#[cfg(target_env = "msvc")]
#[pyfunction]
fn spawnve(
mode: i32,
path: OsPath,
argv: Either<PyListRef, PyTupleRef>,
env: PyDictRef,
vm: &VirtualMachine,
) -> PyResult<intptr_t> {
use std::iter::once;
let make_widestring =
|s: &str| widestring::WideCString::from_os_str(s).map_err(|err| err.to_pyexception(vm));
let path = path.to_wide_cstring(vm)?;
let argv = vm.extract_elements_with(argv.as_ref(), |obj| {
let arg = PyStrRef::try_from_object(vm, obj)?;
make_widestring(arg.as_str())
})?;
let first = argv
.first()
.ok_or_else(|| vm.new_value_error("spawnve() arg 2 cannot be empty"))?;
if first.is_empty() {
return Err(vm.new_value_error("spawnve() arg 2 first element cannot be empty"));
}
let argv_spawn: Vec<*const u16> = argv
.iter()
.map(|v| v.as_ptr())
.chain(once(std::ptr::null()))
.collect();
// Build environment strings as "KEY=VALUE\0" wide strings
let mut env_strings: Vec<widestring::WideCString> = Vec::new();
for (key, value) in env.into_iter() {
let key = PyStrRef::try_from_object(vm, key)?;
let value = PyStrRef::try_from_object(vm, value)?;
let key_str = key.as_str();
let value_str = value.as_str();
// Validate: no null characters in key or value
if key_str.contains('\0') || value_str.contains('\0') {
return Err(vm.new_value_error("embedded null character"));
}
// Validate: no '=' in key
if key_str.contains('=') {
return Err(vm.new_value_error("illegal environment variable name"));
}
let env_str = format!("{}={}", key_str, value_str);
env_strings.push(make_widestring(&env_str)?);
}
let envp: Vec<*const u16> = env_strings
.iter()
.map(|s| s.as_ptr())
.chain(once(std::ptr::null()))
.collect();
let result = unsafe {
suppress_iph!(_wspawnve(
mode,
path.as_ptr(),
argv_spawn.as_ptr(),
envp.as_ptr()
))
};
if result == -1 {
Err(errno_err(vm))
} else {
Ok(result)
}
}
#[cfg(target_env = "msvc")]
#[pyfunction]
fn execv(
path: OsPath,
argv: Either<PyListRef, PyTupleRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
use std::iter::once;
let make_widestring =
|s: &str| widestring::WideCString::from_os_str(s).map_err(|err| err.to_pyexception(vm));
let path = path.to_wide_cstring(vm)?;
let argv = vm.extract_elements_with(argv.as_ref(), |obj| {
let arg = PyStrRef::try_from_object(vm, obj)?;
make_widestring(arg.as_str())
})?;
let first = argv
.first()
.ok_or_else(|| vm.new_value_error("execv() arg 2 must not be empty"))?;
if first.is_empty() {
return Err(vm.new_value_error("execv() arg 2 first element cannot be empty"));
}
let argv_execv: Vec<*const u16> = argv
.iter()
.map(|v| v.as_ptr())
.chain(once(std::ptr::null()))
.collect();
if (unsafe { suppress_iph!(_wexecv(path.as_ptr(), argv_execv.as_ptr())) } == -1) {
Err(errno_err(vm))
} else {
Ok(())
}
}
#[cfg(target_env = "msvc")]
#[pyfunction]
fn execve(
path: OsPath,
argv: Either<PyListRef, PyTupleRef>,
env: PyDictRef,
vm: &VirtualMachine,
) -> PyResult<()> {
use std::iter::once;
let make_widestring =
|s: &str| widestring::WideCString::from_os_str(s).map_err(|err| err.to_pyexception(vm));
let path = path.to_wide_cstring(vm)?;
let argv = vm.extract_elements_with(argv.as_ref(), |obj| {
let arg = PyStrRef::try_from_object(vm, obj)?;
make_widestring(arg.as_str())
})?;
let first = argv
.first()
.ok_or_else(|| vm.new_value_error("execve: argv must not be empty"))?;
if first.is_empty() {
return Err(vm.new_value_error("execve: argv first element cannot be empty"));
}
let argv_execve: Vec<*const u16> = argv
.iter()
.map(|v| v.as_ptr())
.chain(once(std::ptr::null()))
.collect();
// Build environment strings as "KEY=VALUE\0" wide strings
let mut env_strings: Vec<widestring::WideCString> = Vec::new();
for (key, value) in env.into_iter() {
let key = PyStrRef::try_from_object(vm, key)?;
let value = PyStrRef::try_from_object(vm, value)?;
let key_str = key.as_str();
let value_str = value.as_str();
// Validate: no null characters in key or value
if key_str.contains('\0') || value_str.contains('\0') {
return Err(vm.new_value_error("embedded null character"));
}
// Validate: no '=' in key
if key_str.contains('=') {
return Err(vm.new_value_error("illegal environment variable name"));
}
let env_str = format!("{}={}", key_str, value_str);
env_strings.push(make_widestring(&env_str)?);
}
let envp: Vec<*const u16> = env_strings
.iter()
.map(|s| s.as_ptr())
.chain(once(std::ptr::null()))
.collect();
if (unsafe { suppress_iph!(_wexecve(path.as_ptr(), argv_execve.as_ptr(), envp.as_ptr())) }
== -1)
{
Err(errno_err(vm))
} else {
Ok(())
}
}
#[pyfunction]
fn _getfinalpathname(path: OsPath, vm: &VirtualMachine) -> PyResult {
let real = path
.as_ref()
.canonicalize()
.map_err(|e| e.to_pyexception(vm))?;
Ok(path.mode.process_path(real, vm))
}
#[pyfunction]
fn _getfullpathname(path: OsPath, vm: &VirtualMachine) -> PyResult {
let wpath = path.to_wide_cstring(vm)?;
let mut buffer = vec![0u16; Foundation::MAX_PATH as usize];
let ret = unsafe {
FileSystem::GetFullPathNameW(
wpath.as_ptr(),
buffer.len() as _,
buffer.as_mut_ptr(),
std::ptr::null_mut(),
)
};
if ret == 0 {
return Err(errno_err(vm));
}
if ret as usize > buffer.len() {
buffer.resize(ret as usize, 0);
let ret = unsafe {
FileSystem::GetFullPathNameW(
wpath.as_ptr(),
buffer.len() as _,
buffer.as_mut_ptr(),
std::ptr::null_mut(),
)
};
if ret == 0 {
return Err(errno_err(vm));
}
}
let buffer = widestring::WideCString::from_vec_truncate(buffer);
Ok(path.mode.process_path(buffer.to_os_string(), vm))
}
#[pyfunction]
fn _getvolumepathname(path: OsPath, vm: &VirtualMachine) -> PyResult {
let wide = path.to_wide_cstring(vm)?;
let buflen = std::cmp::max(wide.len(), Foundation::MAX_PATH as usize);
let mut buffer = vec![0u16; buflen];
let ret = unsafe {
FileSystem::GetVolumePathNameW(wide.as_ptr(), buffer.as_mut_ptr(), buflen as _)
};
if ret == 0 {
return Err(errno_err(vm));
}
let buffer = widestring::WideCString::from_vec_truncate(buffer);
Ok(path.mode.process_path(buffer.to_os_string(), vm))
}
#[pyfunction]
fn _path_splitroot(path: OsPath, vm: &VirtualMachine) -> PyResult<(String, String)> {
let orig: Vec<_> = path.path.to_wide();
if orig.is_empty() {
return Ok(("".to_owned(), "".to_owned()));
}
let backslashed: Vec<_> = orig
.iter()
.copied()
.map(|c| if c == b'/' as u16 { b'\\' as u16 } else { c })
.chain(std::iter::once(0)) // null-terminated
.collect();
fn from_utf16(wstr: &[u16], vm: &VirtualMachine) -> PyResult<String> {
String::from_utf16(wstr).map_err(|e| vm.new_unicode_decode_error(e.to_string()))
}
let wbuf = windows::core::PCWSTR::from_raw(backslashed.as_ptr());
let (root, path) = match unsafe { windows::Win32::UI::Shell::PathCchSkipRoot(wbuf) } {
Ok(end) => {
assert!(!end.is_null());
let len: usize = unsafe { end.as_ptr().offset_from(wbuf.as_ptr()) }
.try_into()
.expect("len must be non-negative");
assert!(
len < backslashed.len(), // backslashed is null-terminated
"path: {:?} {} < {}",
std::path::PathBuf::from(std::ffi::OsString::from_wide(&backslashed)),
len,
backslashed.len()
);
(from_utf16(&orig[..len], vm)?, from_utf16(&orig[len..], vm)?)
}
Err(_) => ("".to_owned(), from_utf16(&orig, vm)?),
};
Ok((root, path))
}
#[pyfunction]
fn _getdiskusage(path: OsPath, vm: &VirtualMachine) -> PyResult<(u64, u64)> {
use FileSystem::GetDiskFreeSpaceExW;
let wpath = path.to_wide_cstring(vm)?;
let mut _free_to_me: u64 = 0;
let mut total: u64 = 0;
let mut free: u64 = 0;
let ret =
unsafe { GetDiskFreeSpaceExW(wpath.as_ptr(), &mut _free_to_me, &mut total, &mut free) };
if ret != 0 {
return Ok((total, free));
}
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(Foundation::ERROR_DIRECTORY as i32)
&& let Some(parent) = path.as_ref().parent()
{
let parent = widestring::WideCString::from_os_str(parent).unwrap();
let ret = unsafe {
GetDiskFreeSpaceExW(parent.as_ptr(), &mut _free_to_me, &mut total, &mut free)
};
return if ret == 0 {
Err(errno_err(vm))
} else {
Ok((total, free))
};
}
Err(err.to_pyexception(vm))
}
#[pyfunction]
fn get_handle_inheritable(handle: intptr_t, vm: &VirtualMachine) -> PyResult<bool> {
let mut flags = 0;
if unsafe { Foundation::GetHandleInformation(handle as _, &mut flags) } == 0 {
Err(errno_err(vm))
} else {
Ok(flags & Foundation::HANDLE_FLAG_INHERIT != 0)
}
}
#[pyfunction]
fn get_inheritable(fd: i32, vm: &VirtualMachine) -> PyResult<bool> {
let borrowed = unsafe { crt_fd::Borrowed::borrow_raw(fd) };
let handle = crt_fd::as_handle(borrowed).map_err(|e| e.to_pyexception(vm))?;
get_handle_inheritable(handle.as_raw_handle() as _, vm)
}
#[pyfunction]
fn getlogin(vm: &VirtualMachine) -> PyResult<String> {
let mut buffer = [0u16; 257];
let mut size = buffer.len() as u32;
let success = unsafe {
windows_sys::Win32::System::WindowsProgramming::GetUserNameW(
buffer.as_mut_ptr(),
&mut size,
)
};
if success != 0 {
// Convert the buffer (which is UTF-16) to a Rust String
let username = std::ffi::OsString::from_wide(&buffer[..(size - 1) as usize]);
Ok(username.to_str().unwrap().to_string())
} else {
Err(vm.new_os_error(format!("Error code: {success}")))
}
}
pub fn raw_set_handle_inheritable(handle: intptr_t, inheritable: bool) -> std::io::Result<()> {
let flags = if inheritable {
Foundation::HANDLE_FLAG_INHERIT
} else {
0
};
let res = unsafe {
Foundation::SetHandleInformation(handle as _, Foundation::HANDLE_FLAG_INHERIT, flags)
};
if res == 0 {
Err(last_os_error())
} else {
Ok(())
}
}
#[pyfunction]
fn listdrives(vm: &VirtualMachine) -> PyResult<PyListRef> {
use windows_sys::Win32::Foundation::ERROR_MORE_DATA;
let mut buffer = [0u16; 256];
let len =
unsafe { FileSystem::GetLogicalDriveStringsW(buffer.len() as _, buffer.as_mut_ptr()) };
if len == 0 {
return Err(errno_err(vm));
}
if len as usize >= buffer.len() {
return Err(std::io::Error::from_raw_os_error(ERROR_MORE_DATA as _).to_pyexception(vm));
}
let drives: Vec<_> = buffer[..(len - 1) as usize]
.split(|&c| c == 0)
.map(|drive| vm.new_pyobj(String::from_utf16_lossy(drive)))
.collect();
Ok(vm.ctx.new_list(drives))
}
#[pyfunction]
fn set_handle_inheritable(
handle: intptr_t,
inheritable: bool,
vm: &VirtualMachine,
) -> PyResult<()> {
raw_set_handle_inheritable(handle, inheritable).map_err(|e| e.to_pyexception(vm))
}
#[derive(FromArgs)]
struct MkdirArgs<'a> {
#[pyarg(any)]
path: OsPath,
#[pyarg(any, default = 0o777)]
mode: i32,
#[pyarg(flatten)]
dir_fd: DirFd<'a, { _os::MKDIR_DIR_FD as usize }>,
}
#[pyfunction]
fn mkdir(args: MkdirArgs<'_>, vm: &VirtualMachine) -> PyResult<()> {
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::{
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
let [] = args.dir_fd.0;
let wide = args.path.to_wide_cstring(vm)?;
// CPython special case: mode 0o700 sets a protected ACL
let res = if args.mode == 0o700 {
let mut sec_attr = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: std::ptr::null_mut(),
bInheritHandle: 0,
};
// Set a discretionary ACL (D) that is protected (P) and includes
// inheritable (OICI) entries that allow (A) full control (FA) to
// SYSTEM (SY), Administrators (BA), and the owner (OW).
let sddl: Vec<u16> = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)\0"
.encode_utf16()
.collect();
let convert_result = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
SDDL_REVISION_1,
&mut sec_attr.lpSecurityDescriptor,
std::ptr::null_mut(),
)
};
if convert_result == 0 {
return Err(errno_err(vm));
}
let res =
unsafe { FileSystem::CreateDirectoryW(wide.as_ptr(), &sec_attr as *const _ as _) };
unsafe { LocalFree(sec_attr.lpSecurityDescriptor) };
res
} else {
unsafe { FileSystem::CreateDirectoryW(wide.as_ptr(), std::ptr::null_mut()) }
};
if res == 0 {
return Err(errno_err(vm));
}
Ok(())
}
unsafe extern "C" {
fn _umask(mask: i32) -> i32;
fn _dup(fd: i32) -> i32;
fn _dup2(fd: i32, fd2: i32) -> i32;
}
/// Close fd and convert error to PyException (PEP 446 cleanup)
#[cold]
fn close_fd_and_raise(fd: i32, err: std::io::Error, vm: &VirtualMachine) -> PyBaseExceptionRef {
let _ = unsafe { crt_fd::Owned::from_raw(fd) };
err.to_pyexception(vm)
}
#[pyfunction]
fn umask(mask: i32, vm: &VirtualMachine) -> PyResult<i32> {
let result = unsafe { _umask(mask) };
if result < 0 {
Err(errno_err(vm))
} else {
Ok(result)
}
}
#[pyfunction]
fn dup(fd: i32, vm: &VirtualMachine) -> PyResult<i32> {
let fd2 = unsafe { suppress_iph!(_dup(fd)) };
if fd2 < 0 {
return Err(errno_err(vm));
}
let borrowed = unsafe { crt_fd::Borrowed::borrow_raw(fd2) };
let handle = crt_fd::as_handle(borrowed).map_err(|e| close_fd_and_raise(fd2, e, vm))?;
raw_set_handle_inheritable(handle.as_raw_handle() as _, false)
.map_err(|e| close_fd_and_raise(fd2, e, vm))?;
Ok(fd2)
}
#[derive(FromArgs)]
struct Dup2Args {
#[pyarg(positional)]
fd: i32,
#[pyarg(positional)]
fd2: i32,
#[pyarg(any, default = true)]
inheritable: bool,
}
#[pyfunction]
fn dup2(args: Dup2Args, vm: &VirtualMachine) -> PyResult<i32> {
let result = unsafe { suppress_iph!(_dup2(args.fd, args.fd2)) };
if result < 0 {
return Err(errno_err(vm));
}
if !args.inheritable {
let borrowed = unsafe { crt_fd::Borrowed::borrow_raw(args.fd2) };
let handle =
crt_fd::as_handle(borrowed).map_err(|e| close_fd_and_raise(args.fd2, e, vm))?;
raw_set_handle_inheritable(handle.as_raw_handle() as _, false)
.map_err(|e| close_fd_and_raise(args.fd2, e, vm))?;
}
Ok(args.fd2)
}
pub(crate) fn support_funcs() -> Vec<SupportFunc> {
Vec::new()
}
}