forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposix.rs
More file actions
2464 lines (2211 loc) · 86.4 KB
/
Copy pathposix.rs
File metadata and controls
2464 lines (2211 loc) · 86.4 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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// spell-checker:disable
pub(crate) use module::module_def;
pub use rustpython_host_env::posix::set_inheritable;
#[pymodule(name = "posix", with(
super::os::_os,
#[cfg(any(
target_os = "linux",
target_os = "netbsd",
target_os = "freebsd",
target_os = "android"
))]
posix_sched
))]
pub mod module {
use crate::{
AsObject, Py, PyObjectRef, PyResult, VirtualMachine,
builtins::{PyDictRef, PyInt, PyListRef, PyTupleRef, PyUtf8Str},
convert::{IntoPyException, ToPyException, ToPyObject, TryFromObject},
exceptions::OSErrorBuilder,
function::{ArgMapping, Either, KwArgs, OptionalArg},
ospath::{OsPath, OsPathOrFd},
stdlib::os::{
_os, DirFd, FollowSymlinks, SupportFunc, TargetIsDirectory, fs_metadata,
warn_if_bool_fd,
},
};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "linux",
target_os = "openbsd"
))]
use crate::{builtins::PyUtf8StrRef, utils::ToCString};
use alloc::ffi::CString;
use core::ffi::CStr;
use rustpython_host_env::os::ffi::OsStringExt;
use std::{
fs, io,
os::fd::{BorrowedFd, FromRawFd, IntoRawFd, OwnedFd},
};
use strum::IntoEnumIterator;
use strum_macros::{EnumIter, EnumString};
#[cfg(target_os = "linux")]
#[pyattr]
use libc::PIDFD_NONBLOCK;
#[cfg(target_os = "macos")]
#[pyattr]
use libc::{
COPYFILE_DATA as _COPYFILE_DATA, O_EVTONLY, O_NOFOLLOW_ANY, PRIO_DARWIN_BG,
PRIO_DARWIN_NONUI, PRIO_DARWIN_PROCESS, PRIO_DARWIN_THREAD,
};
#[cfg(target_os = "freebsd")]
#[pyattr]
use libc::{SF_MNOWAIT, SF_NOCACHE, SF_NODISKIO, SF_SYNC};
#[cfg(any(target_os = "android", target_os = "linux"))]
#[pyattr]
use libc::{
CLONE_FILES, CLONE_FS, CLONE_NEWCGROUP, CLONE_NEWIPC, CLONE_NEWNET, CLONE_NEWNS,
CLONE_NEWPID, CLONE_NEWUSER, CLONE_NEWUTS, CLONE_SIGHAND, CLONE_SYSVSEM, CLONE_THREAD,
CLONE_VM, MFD_HUGE_SHIFT, O_NOATIME, O_TMPFILE, P_PIDFD, SCHED_BATCH, SCHED_DEADLINE,
SCHED_IDLE, SCHED_NORMAL, SCHED_RESET_ON_FORK, SPLICE_F_MORE, SPLICE_F_MOVE,
SPLICE_F_NONBLOCK,
};
#[cfg(any(target_os = "macos", target_os = "redox"))]
#[pyattr]
use libc::O_SYMLINK;
#[cfg(any(target_os = "android", target_os = "redox", unix))]
#[pyattr]
use libc::{O_NOFOLLOW, PRIO_PGRP, PRIO_PROCESS, PRIO_USER};
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd"))]
#[pyattr]
use libc::{XATTR_CREATE, XATTR_REPLACE};
#[cfg(any(target_os = "android", target_os = "linux", target_os = "netbsd"))]
#[pyattr]
use libc::O_RSYNC;
#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))]
#[pyattr]
use libc::{
MFD_ALLOW_SEALING, MFD_CLOEXEC, MFD_HUGE_MASK, MFD_HUGETLB, POSIX_FADV_DONTNEED,
POSIX_FADV_NOREUSE, POSIX_FADV_NORMAL, POSIX_FADV_RANDOM, POSIX_FADV_SEQUENTIAL,
POSIX_FADV_WILLNEED,
};
#[cfg(any(target_os = "android", target_os = "linux", target_os = "redox", unix))]
#[pyattr]
use libc::{RTLD_LAZY, RTLD_NOW, WNOHANG};
#[cfg(any(target_os = "android", target_os = "macos", target_os = "redox", unix))]
#[pyattr]
use libc::RTLD_GLOBAL;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "linux",
target_os = "redox"
))]
#[pyattr]
use libc::O_PATH;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd"
))]
#[pyattr]
use libc::{
EFD_CLOEXEC, EFD_NONBLOCK, EFD_SEMAPHORE, TFD_CLOEXEC, TFD_NONBLOCK, TFD_TIMER_ABSTIME,
TFD_TIMER_CANCEL_ON_SET,
};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "linux",
target_os = "netbsd"
))]
#[pyattr]
use libc::{GRND_NONBLOCK, GRND_RANDOM};
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "macos",
target_os = "redox",
unix
))]
#[pyattr]
use libc::{F_OK, R_OK, W_OK, X_OK};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "redox",
unix
))]
#[pyattr]
use libc::O_NONBLOCK;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
))]
#[pyattr]
use libc::O_DSYNC;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
))]
#[pyattr]
use libc::SCHED_OTHER;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "macos"
))]
#[pyattr]
use libc::{RTLD_NODELETE, SEEK_DATA, SEEK_HOLE};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd"
))]
#[pyattr]
use libc::O_DIRECT;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "macos",
target_os = "netbsd",
target_os = "redox"
))]
#[pyattr]
use libc::{O_EXLOCK, O_FSYNC, O_SHLOCK};
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "redox",
unix
))]
#[pyattr]
use libc::RTLD_LOCAL;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd",
target_os = "redox",
unix
))]
#[pyattr]
use libc::WUNTRACED;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
))]
#[pyattr]
use libc::{
CLD_CONTINUED, CLD_DUMPED, CLD_EXITED, CLD_KILLED, CLD_STOPPED, CLD_TRAPPED, O_SYNC, P_ALL,
P_PGID, P_PID, SCHED_FIFO, SCHED_RR,
};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "macos",
target_os = "netbsd",
target_os = "redox",
unix
))]
#[pyattr]
use libc::O_DIRECTORY;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "redox"
))]
#[pyattr]
use libc::{
F_LOCK, F_TEST, F_TLOCK, F_ULOCK, O_ASYNC, O_NDELAY, O_NOCTTY, RTLD_NOLOAD, WEXITED,
WNOWAIT, WSTOPPED,
};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "redox",
unix
))]
#[pyattr]
use libc::{O_CLOEXEC, WCONTINUED};
#[pyattr]
const EX_OK: i8 = exitcode::OK as i8;
#[pyattr]
const EX_USAGE: i8 = exitcode::USAGE as i8;
#[pyattr]
const EX_DATAERR: i8 = exitcode::DATAERR as i8;
#[pyattr]
const EX_NOINPUT: i8 = exitcode::NOINPUT as i8;
#[pyattr]
const EX_NOUSER: i8 = exitcode::NOUSER as i8;
#[pyattr]
const EX_NOHOST: i8 = exitcode::NOHOST as i8;
#[pyattr]
const EX_UNAVAILABLE: i8 = exitcode::UNAVAILABLE as i8;
#[pyattr]
const EX_SOFTWARE: i8 = exitcode::SOFTWARE as i8;
#[pyattr]
const EX_OSERR: i8 = exitcode::OSERR as i8;
#[pyattr]
const EX_OSFILE: i8 = exitcode::OSFILE as i8;
#[pyattr]
const EX_CANTCREAT: i8 = exitcode::CANTCREAT as i8;
#[pyattr]
const EX_IOERR: i8 = exitcode::IOERR as i8;
#[pyattr]
const EX_TEMPFAIL: i8 = exitcode::TEMPFAIL as i8;
#[pyattr]
const EX_PROTOCOL: i8 = exitcode::PROTOCOL as i8;
#[pyattr]
const EX_NOPERM: i8 = exitcode::NOPERM as i8;
#[pyattr]
const EX_CONFIG: i8 = exitcode::CONFIG as i8;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
#[pyattr]
const POSIX_SPAWN_OPEN: i32 = PosixSpawnFileActionIdentifier::Open as i32;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
#[pyattr]
const POSIX_SPAWN_CLOSE: i32 = PosixSpawnFileActionIdentifier::Close as i32;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
#[pyattr]
const POSIX_SPAWN_DUP2: i32 = PosixSpawnFileActionIdentifier::Dup2 as i32;
impl TryFromObject for BorrowedFd<'_> {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
crate::stdlib::os::warn_if_bool_fd(&obj, vm)?;
let fd = i32::try_from_object(vm, obj)?;
if fd == -1 {
return Err(io::Error::from_raw_os_error(libc::EBADF).into_pyexception(vm));
}
// SAFETY: none, really. but, python's os api of passing around file descriptors
// everywhere isn't really io-safe anyway, so, this is passed to the user.
Ok(unsafe { BorrowedFd::borrow_raw(fd) })
}
}
impl TryFromObject for OwnedFd {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
let fd = i32::try_from_object(vm, obj)?;
if fd == -1 {
return Err(io::Error::from_raw_os_error(libc::EBADF).into_pyexception(vm));
}
// SAFETY: none, really. but, python's os api of passing around file descriptors
// everywhere isn't really io-safe anyway, so, this is passed to the user.
Ok(unsafe { Self::from_raw_fd(fd) })
}
}
impl ToPyObject for OwnedFd {
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
self.into_raw_fd().to_pyobject(vm)
}
}
#[pyfunction]
fn getgroups(vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
let group_ids =
rustpython_host_env::posix::getgroups().map_err(|e| e.into_pyexception(vm))?;
Ok(group_ids
.into_iter()
.map(|gid| vm.ctx.new_int(gid).into())
.collect())
}
#[pyfunction]
pub(super) fn access(path: OsPath, mode: u8, vm: &VirtualMachine) -> PyResult<bool> {
rustpython_host_env::posix::check_access(path.as_ref(), mode)
.map_err(|err| err.to_pyexception(vm))
}
#[pyattr]
fn environ(vm: &VirtualMachine) -> PyDictRef {
let environ = vm.ctx.new_dict();
for (key, value) in crate::host_env::os::vars_os() {
let key: PyObjectRef = vm.ctx.new_bytes(key.into_vec()).into();
let value: PyObjectRef = vm.ctx.new_bytes(value.into_vec()).into();
environ.set_item(&*key, value, vm).unwrap();
}
environ
}
#[pyfunction]
fn _create_environ(vm: &VirtualMachine) -> PyDictRef {
let environ = vm.ctx.new_dict();
for (key, value) in crate::host_env::os::vars_os() {
let key: PyObjectRef = vm.ctx.new_bytes(key.into_vec()).into();
let value: PyObjectRef = vm.ctx.new_bytes(value.into_vec()).into();
environ.set_item(&*key, value, vm).unwrap();
}
environ
}
#[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<()> {
let src = args.src.into_cstring(vm)?;
let dst = args.dst.into_cstring(vm)?;
#[cfg(not(target_os = "redox"))]
{
rustpython_host_env::posix::symlinkat(&src, args.dir_fd.get().into(), &dst)
.map_err(|err| err.into_pyexception(vm))
}
#[cfg(target_os = "redox")]
{
let [] = args.dir_fd.0;
rustpython_host_env::posix::symlink(&src, &dst).map_err(|err| err.into_pyexception(vm))
}
}
#[pyfunction]
#[pyfunction(name = "unlink")]
fn remove(
path: OsPath,
dir_fd: DirFd<'_, { _os::UNLINK_DIR_FD as usize }>,
vm: &VirtualMachine,
) -> PyResult<()> {
#[cfg(not(target_os = "redox"))]
if let Some(fd) = dir_fd.raw_opt() {
let c_path = path.clone().into_cstring(vm)?;
return rustpython_host_env::posix::unlinkat(fd, &c_path)
.map_err(|err| OSErrorBuilder::with_filename(&err, path, vm));
}
#[cfg(target_os = "redox")]
let [] = dir_fd.0;
crate::host_env::fs::remove_file(&path)
.map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn fchdir(fd: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
warn_if_bool_fd(&fd, vm)?;
let fd = i32::try_from_object(vm, fd)?;
rustpython_host_env::posix::fchdir(fd).map_err(|err| err.into_pyexception(vm))
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn chroot(path: OsPath, vm: &VirtualMachine) -> PyResult<()> {
use crate::exceptions::OSErrorBuilder;
rustpython_host_env::posix::chroot(std::path::Path::new(&path.path))
.map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))
}
// As of now, redox does not seems to support chown command (cf. https://gitlab.redox-os.org/redox-os/coreutils , last checked on 05/07/2020)
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn chown(
path: OsPathOrFd<'_>,
uid: isize,
gid: isize,
dir_fd: DirFd<'_, 1>,
follow_symlinks: FollowSymlinks,
vm: &VirtualMachine,
) -> PyResult<()> {
let uid = if uid >= 0 {
Some(uid as u32)
} else if uid == -1 {
None
} else {
return Err(vm.new_os_error("Specified uid is not valid."));
};
let gid = if gid >= 0 {
Some(gid as u32)
} else if gid == -1 {
None
} else {
return Err(vm.new_os_error("Specified gid is not valid."));
};
match path {
OsPathOrFd::Path(ref p) => rustpython_host_env::posix::fchownat(
dir_fd.get().into(),
p.path.as_os_str(),
uid,
gid,
follow_symlinks.0,
),
OsPathOrFd::Fd(fd) => rustpython_host_env::posix::fchown(fd.into(), uid, gid),
}
.map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn lchown(path: OsPath, uid: isize, gid: isize, vm: &VirtualMachine) -> PyResult<()> {
chown(
OsPathOrFd::Path(path),
uid,
gid,
DirFd::default(),
FollowSymlinks(false),
vm,
)
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn fchown(fd: BorrowedFd<'_>, uid: isize, gid: isize, vm: &VirtualMachine) -> PyResult<()> {
chown(
OsPathOrFd::Fd(fd.into()),
uid,
gid,
DirFd::default(),
FollowSymlinks(true),
vm,
)
}
#[derive(FromArgs)]
struct RegisterAtForkArgs {
#[pyarg(named, optional)]
before: OptionalArg<PyObjectRef>,
#[pyarg(named, optional)]
after_in_parent: OptionalArg<PyObjectRef>,
#[pyarg(named, optional)]
after_in_child: OptionalArg<PyObjectRef>,
}
impl RegisterAtForkArgs {
fn into_validated(
self,
vm: &VirtualMachine,
) -> PyResult<(
Option<PyObjectRef>,
Option<PyObjectRef>,
Option<PyObjectRef>,
)> {
fn into_option(
arg: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> {
match arg {
OptionalArg::Present(obj) => {
if !obj.is_callable() {
return Err(vm.new_type_error("Args must be callable"));
}
Ok(Some(obj))
}
OptionalArg::Missing => Ok(None),
}
}
let before = into_option(self.before, vm)?;
let after_in_parent = into_option(self.after_in_parent, vm)?;
let after_in_child = into_option(self.after_in_child, vm)?;
if before.is_none() && after_in_parent.is_none() && after_in_child.is_none() {
return Err(vm.new_type_error("At least one arg must be present"));
}
Ok((before, after_in_parent, after_in_child))
}
}
#[pyfunction]
fn register_at_fork(
args: RegisterAtForkArgs,
_ignored: KwArgs,
vm: &VirtualMachine,
) -> PyResult<()> {
let (before, after_in_parent, after_in_child) = args.into_validated(vm)?;
if let Some(before) = before {
vm.state.before_forkers.lock().push(before);
}
if let Some(after_in_parent) = after_in_parent {
vm.state.after_forkers_parent.lock().push(after_in_parent);
}
if let Some(after_in_child) = after_in_child {
vm.state.after_forkers_child.lock().push(after_in_child);
}
Ok(())
}
fn run_at_forkers(mut funcs: Vec<PyObjectRef>, reversed: bool, vm: &VirtualMachine) {
if !funcs.is_empty() {
if reversed {
funcs.reverse();
}
for func in funcs {
if let Err(e) = func.call((), vm) {
let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit);
vm.run_unraisable(e, Some("Exception ignored in".to_owned()), func);
if exit {
// Do nothing!
}
}
}
}
}
fn py_os_before_fork(vm: &VirtualMachine) {
let before_forkers: Vec<PyObjectRef> = vm.state.before_forkers.lock().clone();
// functions must be executed in reversed order as they are registered
// only for before_forkers, refer: test_register_at_fork in test_posix
run_at_forkers(before_forkers, true, vm);
#[cfg(feature = "threading")]
crate::stdlib::_imp::acquire_imp_lock_for_fork();
#[cfg(feature = "threading")]
vm.state.stop_the_world.stop_the_world(vm);
}
fn py_os_after_fork_child(vm: &VirtualMachine) {
#[cfg(feature = "threading")]
vm.state.stop_the_world.reset_after_fork();
// Phase 1: Reset all internal locks FIRST.
// After fork(), locks held by dead parent threads would deadlock
// if we try to acquire them. This must happen before anything else.
#[cfg(feature = "threading")]
reinit_locks_after_fork(vm);
// Reinit per-object IO buffer locks on std streams.
// BufferedReader/Writer/TextIOWrapper use PyThreadMutex which can be
// held by dead parent threads, causing deadlocks on any IO in the child.
#[cfg(feature = "threading")]
unsafe {
crate::stdlib::_io::reinit_std_streams_after_fork(vm)
};
// Phase 2: Reset low-level atomic state (no locks needed).
crate::signal::clear_after_fork();
crate::stdlib::_signal::_signal::clear_wakeup_fd_after_fork();
// Reset weakref stripe locks that may have been held during fork.
#[cfg(feature = "threading")]
crate::object::reset_weakref_locks_after_fork();
// Phase 3: Clean up thread state. Locks are now reinit'd so we can
// acquire them normally instead of using try_lock().
#[cfg(feature = "threading")]
crate::stdlib::_thread::after_fork_child(vm);
// CPython parity: reinit import lock ownership metadata in child
// and release the lock acquired by PyOS_BeforeFork().
#[cfg(feature = "threading")]
unsafe {
crate::stdlib::_imp::after_fork_child_imp_lock_release()
};
// Initialize signal handlers for the child's main thread.
// When forked from a worker thread, the OnceCell is empty.
vm.signal_handlers
.get_or_init(crate::signal::new_signal_handlers);
// Phase 4: Run Python-level at-fork callbacks.
let after_forkers_child: Vec<PyObjectRef> = vm.state.after_forkers_child.lock().clone();
run_at_forkers(after_forkers_child, false, vm);
}
/// Reset all parking_lot-based locks in the interpreter state after fork().
///
/// After fork(), only the calling thread survives. Any locks held by other
/// (now-dead) threads would cause deadlocks. We unconditionally reset them
/// to unlocked by zeroing the raw lock bytes.
#[cfg(all(unix, feature = "threading"))]
fn reinit_locks_after_fork(vm: &VirtualMachine) {
use rustpython_common::lock::reinit_mutex_after_fork;
unsafe {
// PyGlobalState PyMutex locks
reinit_mutex_after_fork(&vm.state.before_forkers);
reinit_mutex_after_fork(&vm.state.after_forkers_child);
reinit_mutex_after_fork(&vm.state.after_forkers_parent);
reinit_mutex_after_fork(&vm.state.atexit_funcs);
reinit_mutex_after_fork(&vm.state.global_trace_func);
reinit_mutex_after_fork(&vm.state.global_profile_func);
reinit_mutex_after_fork(&vm.state.monitoring);
// PyGlobalState parking_lot::Mutex locks
reinit_mutex_after_fork(&vm.state.thread_frames);
reinit_mutex_after_fork(&vm.state.thread_handles);
reinit_mutex_after_fork(&vm.state.shutdown_handles);
// Context-level RwLock
vm.ctx.string_pool.reinit_after_fork();
// Codec registry RwLock
vm.state.codec_registry.reinit_after_fork();
// GC state (multiple Mutex + RwLock)
crate::gc_state::gc_state().reinit_after_fork();
// Import lock (RawReentrantMutex<RawMutex, RawThreadId>)
crate::stdlib::_imp::reinit_imp_lock_after_fork();
}
}
fn py_os_after_fork_parent(vm: &VirtualMachine) {
#[cfg(feature = "threading")]
vm.state.stop_the_world.start_the_world(vm);
#[cfg(feature = "threading")]
crate::stdlib::_imp::release_imp_lock_after_fork_parent();
let after_forkers_parent: Vec<PyObjectRef> = vm.state.after_forkers_parent.lock().clone();
run_at_forkers(after_forkers_parent, false, vm);
}
/// Best-effort number of OS threads in this process.
/// Returns <= 0 when unavailable.
fn get_number_of_os_threads() -> isize {
rustpython_host_env::posix::get_number_of_os_threads()
}
/// Warn if forking from a multi-threaded process.
/// `num_os_threads` should be captured before parent after-fork hooks run.
fn warn_if_multi_threaded(name: &str, num_os_threads: isize, vm: &VirtualMachine) {
let num_threads = if num_os_threads > 0 {
num_os_threads as usize
} else {
// CPython fallback: if OS-level count isn't available, use the
// threading module's active+limbo view.
// Only check threading if it was already imported. Avoid vm.import()
// which can execute arbitrary Python code in the fork path.
let threading = match vm
.sys_module
.get_attr("modules", vm)
.and_then(|m| m.get_item("threading", vm))
{
Ok(m) => m,
Err(_) => return,
};
let active = threading.get_attr("_active", vm).ok();
let limbo = threading.get_attr("_limbo", vm).ok();
// Match threading module internals and avoid sequence overcounting:
// count only dict-backed _active/_limbo containers.
let count_dict = |obj: Option<crate::PyObjectRef>| -> usize {
obj.and_then(|o| {
o.downcast_ref::<crate::builtins::PyDict>()
.map(|d| d.__len__())
})
.unwrap_or(0)
};
count_dict(active) + count_dict(limbo)
};
if num_threads > 1 {
let pid = rustpython_host_env::posix::getpid();
let msg = format!(
"This process (pid={pid}) is multi-threaded, use of {name}() may lead to deadlocks in the child."
);
// Match PyErr_WarnFormat(..., stacklevel=1) in CPython.
// Best effort: ignore failures like CPython does in this path.
let _ =
crate::stdlib::_warnings::warn(vm.ctx.exceptions.deprecation_warning, msg, 1, vm);
}
}
#[pyfunction]
fn fork(vm: &VirtualMachine) -> PyResult<i32> {
if vm
.state
.finalizing
.load(core::sync::atomic::Ordering::Acquire)
{
return Err(vm.new_exception_msg(
vm.ctx.exceptions.python_finalization_error.to_owned(),
"can't fork at interpreter shutdown".into(),
));
}
// RustPython does not yet have C-level audit hooks; call sys.audit()
// to preserve Python-visible behavior and failure semantics.
vm.sys_module
.get_attr("audit", vm)?
.call(("os.fork",), vm)?;
py_os_before_fork(vm);
let pid = rustpython_host_env::posix::fork();
match pid {
Ok(0) => {
py_os_after_fork_child(vm);
Ok(0)
}
Ok(pid) => {
// Match CPython timing: capture this before parent after-fork hooks
// in case those hooks start threads.
let num_os_threads = get_number_of_os_threads();
py_os_after_fork_parent(vm);
// Match CPython timing: warn only after parent callback path resumes world.
warn_if_multi_threaded("fork", num_os_threads, vm);
Ok(pid)
}
Err(err) => Err(err.into_pyexception(vm)),
}
}
#[cfg(not(target_os = "redox"))]
const MKNOD_DIR_FD: bool = cfg!(not(target_vendor = "apple"));
#[cfg(not(target_os = "redox"))]
#[derive(FromArgs)]
struct MknodArgs<'fd> {
#[pyarg(any)]
path: OsPath,
#[pyarg(any)]
mode: libc::mode_t,
#[pyarg(any)]
device: libc::dev_t,
#[pyarg(flatten)]
dir_fd: DirFd<'fd, { MKNOD_DIR_FD as usize }>,
}
#[cfg(not(target_os = "redox"))]
impl MknodArgs<'_> {
#[cfg(not(target_vendor = "apple"))]
fn mknod(self, vm: &VirtualMachine) -> PyResult<()> {
let c_path = self.path.clone().into_cstring(vm)?;
match self.dir_fd.raw_opt() {
None => rustpython_host_env::posix::mknod(&c_path, self.mode, self.device),
Some(non_default_fd) => rustpython_host_env::posix::mknodat(
non_default_fd,
&c_path,
self.mode,
self.device,
),
}
.map_err(|err| err.into_pyexception(vm))
}
#[cfg(target_vendor = "apple")]
fn mknod(self, vm: &VirtualMachine) -> PyResult<()> {
let [] = self.dir_fd.0;
let c_path = self.path.clone().into_cstring(vm)?;
rustpython_host_env::posix::mknod(&c_path, self.mode, self.device)
.map_err(|err| err.into_pyexception(vm))
}
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn mknod(args: MknodArgs<'_>, vm: &VirtualMachine) -> PyResult<()> {
args.mknod(vm)
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn nice(increment: i32, vm: &VirtualMachine) -> PyResult<i32> {
rustpython_host_env::posix::nice(increment).map_err(|err| err.into_pyexception(vm))
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn sched_get_priority_max(policy: i32, vm: &VirtualMachine) -> PyResult<i32> {
rustpython_host_env::posix::sched_get_priority_max(policy)
.map_err(|err| err.into_pyexception(vm))
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn sched_get_priority_min(policy: i32, vm: &VirtualMachine) -> PyResult<i32> {
rustpython_host_env::posix::sched_get_priority_min(policy)
.map_err(|err| err.into_pyexception(vm))
}
#[pyfunction]
fn sched_yield(vm: &VirtualMachine) -> PyResult<()> {
rustpython_host_env::posix::sched_yield().map_err(|e| e.into_pyexception(vm))
}
#[pyfunction]
fn get_inheritable(fd: BorrowedFd<'_>, vm: &VirtualMachine) -> PyResult<bool> {
rustpython_host_env::fcntl::get_inheritable(fd).map_err(|err| err.into_pyexception(vm))
}
#[pyfunction]
fn set_inheritable(fd: BorrowedFd<'_>, inheritable: bool, vm: &VirtualMachine) -> PyResult<()> {
super::set_inheritable(fd, inheritable).map_err(|err| err.into_pyexception(vm))
}
#[pyfunction]
fn get_blocking(fd: BorrowedFd<'_>, vm: &VirtualMachine) -> PyResult<bool> {
rustpython_host_env::fcntl::get_blocking(fd).map_err(|err| err.into_pyexception(vm))
}
#[pyfunction]
fn set_blocking(fd: BorrowedFd<'_>, blocking: bool, vm: &VirtualMachine) -> PyResult<()> {
rustpython_host_env::fcntl::set_blocking(fd, blocking)
.map_err(|err| err.into_pyexception(vm))
}
#[pyfunction]
fn pipe(vm: &VirtualMachine) -> PyResult<(OwnedFd, OwnedFd)> {
rustpython_host_env::posix::pipe().map_err(|err| err.into_pyexception(vm))
}
// cfg from nix
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "emscripten",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
))]
#[pyfunction]
fn pipe2(flags: libc::c_int, vm: &VirtualMachine) -> PyResult<(OwnedFd, OwnedFd)> {
rustpython_host_env::posix::pipe2(flags).map_err(|err| err.into_pyexception(vm))
}
fn _chmod(
path: OsPath,
dir_fd: DirFd<'_, 0>,
mode: u32,
follow_symlinks: FollowSymlinks,
vm: &VirtualMachine,
) -> PyResult<()> {
let [] = dir_fd.0;
let err_path = path.clone();
let body = move || {
use std::os::unix::fs::PermissionsExt;
let meta = fs_metadata(&path, follow_symlinks.0)?;
let mut permissions = meta.permissions();
permissions.set_mode(mode);
fs::set_permissions(&path, permissions)
};
body().map_err(|err| OSErrorBuilder::with_filename(&err, err_path, vm))
}
#[cfg(not(target_os = "redox"))]
fn _fchmod(fd: BorrowedFd<'_>, mode: u32, vm: &VirtualMachine) -> PyResult<()> {
rustpython_host_env::posix::fchmod(fd, mode).map_err(|err| err.into_pyexception(vm))
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn chmod(
path: OsPathOrFd<'_>,
dir_fd: DirFd<'_, 0>,
mode: u32,
follow_symlinks: FollowSymlinks,
vm: &VirtualMachine,
) -> PyResult<()> {
match path {
OsPathOrFd::Path(path) => {
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "netbsd",))]
if !follow_symlinks.0 && dir_fd == Default::default() {
return lchmod(path, mode, vm);
}
_chmod(path, dir_fd, mode, follow_symlinks, vm)
}
OsPathOrFd::Fd(fd) => _fchmod(fd.into(), mode, vm),
}
}
#[cfg(target_os = "redox")]
#[pyfunction]
fn chmod(
path: OsPath,
dir_fd: DirFd<0>,
mode: u32,
follow_symlinks: FollowSymlinks,
vm: &VirtualMachine,
) -> PyResult<()> {
_chmod(path, dir_fd, mode, follow_symlinks, vm)
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn fchmod(fd: BorrowedFd<'_>, mode: u32, vm: &VirtualMachine) -> PyResult<()> {
_fchmod(fd, mode, vm)
}
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "netbsd",))]
#[pyfunction]