forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmmap.rs
More file actions
1403 lines (1212 loc) · 47.8 KB
/
Copy pathmmap.rs
File metadata and controls
1403 lines (1212 loc) · 47.8 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
//! mmap module
pub(crate) use mmap::module_def;
#[pymodule]
mod mmap {
use crate::common::{
borrow::{BorrowedValue, BorrowedValueMut},
lock::{MapImmutable, PyMutex, PyMutexGuard},
};
use crate::vm::{
AsObject, FromArgs, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
TryFromBorrowedObject, VirtualMachine, atomic_func,
builtins::{PyBytes, PyBytesRef, PyInt, PyIntRef, PyType, PyTypeRef},
byte::{bytes_from_object, value_from_object},
convert::ToPyException,
function::{ArgBytesLike, FuncArgs, OptionalArg},
protocol::{
BufferDescriptor, BufferMethods, PyBuffer, PyMappingMethods, PySequenceMethods,
},
sliceable::{SaturatedSlice, SequenceIndex, SequenceIndexOp},
types::{AsBuffer, AsMapping, AsSequence, Constructor, Representable},
};
use core::ops::{Deref, DerefMut};
use crossbeam_utils::atomic::AtomicCell;
use num_traits::Signed;
#[cfg(windows)]
use std::io;
use std::io::Write;
#[cfg(unix)]
use rustpython_host_env::crt_fd;
#[cfg(any(unix, windows))]
use rustpython_host_env::mmap as host_mmap;
#[cfg(windows)]
use rustpython_host_env::nt as host_nt;
#[repr(C)]
#[derive(PartialEq, Eq, Debug)]
enum AccessMode {
Default = 0,
Read = 1,
Write = 2,
Copy = 3,
}
impl<'a> TryFromBorrowedObject<'a> for AccessMode {
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
let i = u32::try_from_borrowed_object(vm, obj)?;
Ok(match i {
0 => Self::Default,
1 => Self::Read,
2 => Self::Write,
3 => Self::Copy,
_ => return Err(vm.new_value_error("Not a valid AccessMode value")),
})
}
}
#[cfg(unix)]
#[pyattr]
use libc::{
MADV_DONTNEED, MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_WILLNEED, MAP_ANON,
MAP_ANONYMOUS, MAP_PRIVATE, MAP_SHARED, PROT_EXEC, PROT_READ, PROT_WRITE,
};
#[cfg(target_os = "macos")]
#[pyattr]
use libc::{MADV_FREE_REUSABLE, MADV_FREE_REUSE};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple"
))]
#[pyattr]
use libc::MADV_FREE;
#[cfg(target_os = "linux")]
#[pyattr]
use libc::{
MADV_DODUMP, MADV_DOFORK, MADV_DONTDUMP, MADV_DONTFORK, MADV_HUGEPAGE, MADV_HWPOISON,
MADV_MERGEABLE, MADV_NOHUGEPAGE, MADV_REMOVE, MADV_UNMERGEABLE,
};
#[cfg(any(
target_os = "android",
all(
target_os = "linux",
any(
target_arch = "aarch64",
target_arch = "arm",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "s390x",
target_arch = "x86",
target_arch = "x86_64",
target_arch = "sparc64"
)
)
))]
#[pyattr]
use libc::MADV_SOFT_OFFLINE;
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
#[pyattr]
use libc::{MAP_DENYWRITE, MAP_EXECUTABLE, MAP_POPULATE};
// MAP_STACK is available on Linux, OpenBSD, and NetBSD
#[cfg(any(target_os = "linux", target_os = "openbsd", target_os = "netbsd"))]
#[pyattr]
use libc::MAP_STACK;
// FreeBSD-specific MADV constants
#[cfg(target_os = "freebsd")]
#[pyattr]
use libc::{MADV_AUTOSYNC, MADV_CORE, MADV_NOCORE, MADV_NOSYNC, MADV_PROTECT};
#[pyattr]
const ACCESS_DEFAULT: u32 = AccessMode::Default as u32;
#[pyattr]
const ACCESS_READ: u32 = AccessMode::Read as u32;
#[pyattr]
const ACCESS_WRITE: u32 = AccessMode::Write as u32;
#[pyattr]
const ACCESS_COPY: u32 = AccessMode::Copy as u32;
#[pyattr(name = "PAGESIZE", once)]
fn page_size(_vm: &VirtualMachine) -> usize {
rustpython_host_env::os::page_size()
}
#[cfg(not(target_arch = "wasm32"))]
#[pyattr(name = "ALLOCATIONGRANULARITY", once)]
fn granularity(_vm: &VirtualMachine) -> usize {
rustpython_host_env::os::alloc_granularity()
}
#[pyattr(name = "error", once)]
fn error_type(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.exceptions.os_error.to_owned()
}
#[derive(Debug)]
enum MmapObj {
Mapped(host_mmap::MappedFile),
#[cfg(windows)]
Named(host_mmap::NamedMmap),
}
impl MmapObj {
fn as_slice(&self) -> &[u8] {
match self {
Self::Mapped(mmap) => mmap.as_slice(),
#[cfg(windows)]
Self::Named(named) => named.as_slice(),
}
}
}
#[pyattr]
#[pyclass(name = "mmap")]
#[derive(Debug, PyPayload)]
struct PyMmap {
closed: AtomicCell<bool>,
mmap: PyMutex<Option<MmapObj>>,
#[cfg(unix)]
fd: AtomicCell<i32>,
#[cfg(windows)]
handle: AtomicCell<isize>, // host_mmap::Handle is isize on Windows
offset: i64,
size: AtomicCell<usize>,
pos: AtomicCell<usize>, // relative to offset
exports: AtomicCell<usize>,
access: AccessMode,
}
impl PyMmap {
/// Close the underlying file handle/descriptor if open
fn close_handle(&self) {
#[cfg(unix)]
{
let fd = self.fd.swap(-1);
host_mmap::close_descriptor(fd);
}
#[cfg(windows)]
{
let handle = self.handle.swap(host_mmap::INVALID_HANDLE as isize);
if handle != host_mmap::INVALID_HANDLE as isize {
host_mmap::close_handle(handle as host_mmap::Handle);
}
}
}
}
impl Drop for PyMmap {
fn drop(&mut self) {
self.close_handle();
}
}
#[cfg(unix)]
#[derive(FromArgs)]
struct MmapNewArgs {
#[pyarg(any)]
fileno: i32,
#[pyarg(any)]
length: isize,
#[pyarg(any, default = libc::MAP_SHARED)]
flags: libc::c_int,
#[pyarg(any, default = libc::PROT_WRITE | libc::PROT_READ)]
prot: libc::c_int,
#[pyarg(any, default = AccessMode::Default)]
access: AccessMode,
#[pyarg(any, default = 0)]
offset: i64,
}
#[cfg(windows)]
#[derive(FromArgs)]
struct MmapNewArgs {
#[pyarg(any)]
fileno: i32,
#[pyarg(any)]
length: isize,
#[pyarg(any, default)]
tagname: Option<PyObjectRef>,
#[pyarg(any, default = AccessMode::Default)]
access: AccessMode,
#[pyarg(any, default = 0)]
offset: i64,
}
impl MmapNewArgs {
/// Validate mmap constructor arguments
fn validate_new_args(&self, vm: &VirtualMachine) -> PyResult<usize> {
if self.length < 0 {
return Err(vm.new_overflow_error("memory mapped length must be positive"));
}
if self.offset < 0 {
return Err(vm.new_overflow_error("memory mapped offset must be positive"));
}
Ok(self.length as usize)
}
}
#[derive(FromArgs)]
pub(super) struct FlushOptions {
#[pyarg(positional, default)]
offset: Option<isize>,
#[pyarg(positional, default)]
size: Option<isize>,
}
impl FlushOptions {
fn values(self, len: usize) -> Option<(usize, usize)> {
let offset = match self.offset {
Some(o) if o < 0 => return None,
Some(o) => o as usize,
None => 0,
};
let size = match self.size {
Some(s) if s < 0 => return None,
Some(s) => s as usize,
None => len,
};
if len.checked_sub(offset)? < size {
return None;
}
Some((offset, size))
}
}
#[derive(FromArgs, Clone)]
pub(super) struct FindOptions {
#[pyarg(positional)]
sub: Vec<u8>,
#[pyarg(positional, default)]
start: Option<isize>,
#[pyarg(positional, default)]
end: Option<isize>,
}
#[cfg(all(unix, not(target_os = "redox")))]
#[derive(FromArgs)]
pub(super) struct AdviseOptions {
#[pyarg(positional)]
option: libc::c_int,
#[pyarg(positional, default)]
start: Option<PyIntRef>,
#[pyarg(positional, default)]
length: Option<PyIntRef>,
}
#[cfg(all(unix, not(target_os = "redox")))]
impl AdviseOptions {
fn values(self, len: usize, vm: &VirtualMachine) -> PyResult<(libc::c_int, usize, usize)> {
let start = self
.start
.map(|s| {
s.try_to_primitive::<usize>(vm)
.ok()
.filter(|s| *s < len)
.ok_or_else(|| vm.new_value_error("madvise start out of bounds"))
})
.transpose()?
.unwrap_or(0);
let length = self
.length
.map(|s| {
s.try_to_primitive::<usize>(vm)
.map_err(|_| vm.new_value_error("madvise length invalid"))
})
.transpose()?
.unwrap_or(len);
if isize::MAX as usize - start < length {
return Err(vm.new_overflow_error("madvise length too large"));
}
let length = if start + length > len {
len - start
} else {
length
};
Ok((self.option, start, length))
}
}
impl Constructor for PyMmap {
type Args = MmapNewArgs;
#[cfg(unix)]
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
use libc::{MAP_PRIVATE, MAP_SHARED, PROT_READ, PROT_WRITE};
let mut map_size = args.validate_new_args(vm)?;
let MmapNewArgs {
fileno: fd,
flags,
prot,
access,
offset,
..
} = args;
if (access != AccessMode::Default)
&& ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))
{
return Err(vm.new_value_error("mmap can't specify both access and flags, prot."));
}
// TODO: memmap2 doesn't support mapping with prot and flags right now
let (_flags, _prot, access) = match access {
AccessMode::Read => (MAP_SHARED, PROT_READ, access),
AccessMode::Write => (MAP_SHARED, PROT_READ | PROT_WRITE, access),
AccessMode::Copy => (MAP_PRIVATE, PROT_READ | PROT_WRITE, access),
AccessMode::Default => {
let access = if (prot & PROT_READ) != 0 && (prot & PROT_WRITE) != 0 {
access
} else if (prot & PROT_WRITE) != 0 {
AccessMode::Write
} else {
AccessMode::Read
};
(flags, prot, access)
}
};
let fd = unsafe { crt_fd::Borrowed::try_borrow_raw(fd) };
// macOS: Issue #11277: fsync(2) is not enough on OS X - a special, OS X specific
// fcntl(2) is necessary to force DISKSYNC and get around mmap(2) bug
#[cfg(target_os = "macos")]
if let Ok(fd) = fd {
host_mmap::prepare_file_mapping(fd);
}
if let Ok(fd) = fd {
let file_len = host_mmap::file_len(fd).map_err(|err| err.to_pyexception(vm))?;
if map_size == 0 {
if file_len == 0 {
return Err(vm.new_value_error("cannot mmap an empty file"));
}
if offset > file_len {
return Err(vm.new_value_error("mmap offset is greater than file size"));
}
map_size = (file_len - offset)
.try_into()
.map_err(|_| vm.new_value_error("mmap length is too large"))?;
} else if offset > file_len || file_len - offset < map_size as i64 {
return Err(vm.new_value_error("mmap length is greater than file size"));
}
}
let (fd, mmap) = || -> std::io::Result<_> {
if let Ok(fd) = fd {
let (new_fd, mmap) = host_mmap::map_file(
fd,
offset,
map_size,
match access {
AccessMode::Default => host_mmap::AccessMode::Default,
AccessMode::Read => host_mmap::AccessMode::Read,
AccessMode::Write => host_mmap::AccessMode::Write,
AccessMode::Copy => host_mmap::AccessMode::Copy,
},
)?;
Ok((Some(new_fd), mmap))
} else {
let mmap = host_mmap::map_anon(map_size)?;
Ok((None, mmap))
}
}()
.map_err(|e| e.to_pyexception(vm))?;
Ok(Self {
closed: AtomicCell::new(false),
mmap: PyMutex::new(Some(MmapObj::Mapped(mmap))),
fd: AtomicCell::new(fd.map_or(-1, |fd| fd.into_raw())),
offset,
size: AtomicCell::new(map_size),
pos: AtomicCell::new(0),
exports: AtomicCell::new(0),
access,
})
}
#[cfg(windows)]
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
let mut map_size = args.validate_new_args(vm)?;
let MmapNewArgs {
fileno,
tagname,
access,
offset,
..
} = args;
// Parse tagname: None or a string
let tag_str: Option<String> = match tagname {
Some(ref obj) if !vm.is_none(obj) => {
let s = obj
.try_to_value::<String>(vm)
.map_err(|_| vm.new_type_error("tagname must be a string or None"))?;
if s.contains('\0') {
return Err(vm.new_value_error("tagname must not contain null characters"));
}
Some(s)
}
_ => None,
};
// Get file handle from fileno. fileno -1 means anonymous mapping.
let fh: Option<host_mmap::Handle> = if fileno != -1 {
// Convert CRT file descriptor to a Windows file mapping handle.
// Use suppress_iph! to avoid crashes when the fd is invalid.
// This is critical because socket fds wrapped via _open_osfhandle
// may cause crashes in _get_osfhandle on Windows.
// See Python bug https://bugs.python.org/issue30114
let handle = host_nt::handle_from_fd(fileno);
// Check for invalid handle value (-1 on Windows)
if host_mmap::is_invalid_handle_value(handle as isize) {
return Err(vm.new_os_error(format!("Invalid file descriptor: {fileno}")));
}
Some(handle as host_mmap::Handle)
} else {
None
};
// Get file size if we have a file handle and map_size is 0
let mut duplicated_handle: host_mmap::Handle = host_mmap::INVALID_HANDLE;
if let Some(fh) = fh {
// Duplicate handle so Python code can close the original
duplicated_handle =
host_mmap::duplicate_handle(fh).map_err(|e| e.to_pyexception(vm))?;
// Get file size
let file_len = match host_mmap::get_file_len(fh) {
Ok(len) => len,
Err(err) => {
host_mmap::close_handle(duplicated_handle);
return Err(err.to_pyexception(vm));
}
};
if map_size == 0 {
if file_len == 0 {
host_mmap::close_handle(duplicated_handle);
return Err(vm.new_value_error("cannot mmap an empty file"));
}
if offset >= file_len {
host_mmap::close_handle(duplicated_handle);
return Err(vm.new_value_error("mmap offset is greater than file size"));
}
if file_len - offset > isize::MAX as i64 {
host_mmap::close_handle(duplicated_handle);
return Err(vm.new_value_error("mmap length is too large"));
}
map_size = (file_len - offset) as usize;
} else {
// If map_size > file_len, extend the file (Windows behavior)
let required_size = offset.checked_add(map_size as i64).ok_or_else(|| {
host_mmap::close_handle(duplicated_handle);
vm.new_overflow_error("mmap size would cause file size overflow")
})?;
if required_size > file_len
&& let Err(err) = host_mmap::extend_file(duplicated_handle, required_size)
{
host_mmap::close_handle(duplicated_handle);
return Err(err.to_pyexception(vm));
}
}
}
// When tagname is provided, use raw Win32 APIs for named shared memory
if let Some(ref tag) = tag_str {
let fh = if let Some(fh) = fh {
// Close the duplicated handle - we'll use the original
// file handle for CreateFileMappingW
if duplicated_handle != host_mmap::INVALID_HANDLE {
host_mmap::close_handle(duplicated_handle);
}
fh
} else {
host_mmap::INVALID_HANDLE
};
let named = host_mmap::create_named_mapping(
fh,
tag,
match access {
AccessMode::Default => host_mmap::AccessMode::Default,
AccessMode::Read => host_mmap::AccessMode::Read,
AccessMode::Write => host_mmap::AccessMode::Write,
AccessMode::Copy => host_mmap::AccessMode::Copy,
},
offset,
map_size,
)
.map_err(|err| {
if err.raw_os_error() == Some(libc::EOVERFLOW) {
vm.new_overflow_error("mmap offset plus size would overflow")
} else {
err.to_pyexception(vm)
}
})?;
return Ok(Self {
closed: AtomicCell::new(false),
mmap: PyMutex::new(Some(MmapObj::Named(named))),
handle: AtomicCell::new(host_mmap::INVALID_HANDLE as isize),
offset,
size: AtomicCell::new(map_size),
pos: AtomicCell::new(0),
exports: AtomicCell::new(0),
access,
});
}
let (handle, mmap) = if duplicated_handle != host_mmap::INVALID_HANDLE {
let mmap = Self::create_mmap_windows(duplicated_handle, offset, map_size, &access)
.map_err(|e| e.to_pyexception(vm))?;
(duplicated_handle as isize, mmap)
} else {
// Anonymous mapping
let mmap = host_mmap::map_anon(map_size).map_err(|e| e.to_pyexception(vm))?;
(host_mmap::INVALID_HANDLE as isize, MmapObj::Mapped(mmap))
};
Ok(Self {
closed: AtomicCell::new(false),
mmap: PyMutex::new(Some(mmap)),
handle: AtomicCell::new(handle),
offset,
size: AtomicCell::new(map_size),
pos: AtomicCell::new(0),
exports: AtomicCell::new(0),
access,
})
}
}
static BUFFER_METHODS: BufferMethods = BufferMethods {
obj_bytes: |buffer| buffer.obj_as::<PyMmap>().as_bytes(),
obj_bytes_mut: |buffer| buffer.obj_as::<PyMmap>().as_bytes_mut(),
release: |buffer| {
buffer.obj_as::<PyMmap>().exports.fetch_sub(1);
},
retain: |buffer| {
buffer.obj_as::<PyMmap>().exports.fetch_add(1);
},
};
impl AsBuffer for PyMmap {
fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> {
let readonly = matches!(zelf.access, AccessMode::Read);
let buf = PyBuffer::new(
zelf.to_owned().into(),
BufferDescriptor::simple(zelf.__len__(), readonly),
&BUFFER_METHODS,
);
Ok(buf)
}
}
impl AsMapping for PyMmap {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(
|mapping, _vm| Ok(PyMmap::mapping_downcast(mapping).__len__())
),
subscript: atomic_func!(|mapping, needle, vm| {
PyMmap::mapping_downcast(mapping).getitem_inner(needle, vm)
}),
ass_subscript: atomic_func!(|mapping, needle, value, vm| {
let zelf = PyMmap::mapping_downcast(mapping);
if let Some(value) = value {
PyMmap::setitem_inner(zelf, needle, value, vm)
} else {
Err(vm
.new_type_error("mmap object doesn't support item deletion".to_owned()))
}
}),
};
&AS_MAPPING
}
}
impl AsSequence for PyMmap {
fn as_sequence() -> &'static PySequenceMethods {
use rustpython_common::lock::LazyLock;
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyMmap::sequence_downcast(seq).__len__())),
item: atomic_func!(|seq, i, vm| {
let zelf = PyMmap::sequence_downcast(seq);
zelf.getitem_by_index(i, vm)
}),
ass_item: atomic_func!(|seq, i, value, vm| {
let zelf = PyMmap::sequence_downcast(seq);
if let Some(value) = value {
PyMmap::setitem_by_index(zelf, i, value, vm)
} else {
Err(vm
.new_type_error("mmap object doesn't support item deletion".to_owned()))
}
}),
..PySequenceMethods::NOT_IMPLEMENTED
});
&AS_SEQUENCE
}
}
#[pyclass(
with(Constructor, AsMapping, AsSequence, AsBuffer, Representable),
flags(BASETYPE, HAS_WEAKREF)
)]
impl PyMmap {
fn as_bytes_mut(&self) -> BorrowedValueMut<'_, [u8]> {
PyMutexGuard::map(self.mmap.lock(), |m| {
match m.as_mut().expect("mmap closed or invalid") {
MmapObj::Mapped(mmap) => mmap.as_mut_slice(),
#[cfg(windows)]
MmapObj::Named(named) => named.as_mut_slice(),
}
})
.into()
}
fn as_bytes(&self) -> BorrowedValue<'_, [u8]> {
PyMutexGuard::map_immutable(self.mmap.lock(), |m| {
m.as_ref().expect("mmap closed or invalid").as_slice()
})
.into()
}
fn __len__(&self) -> usize {
self.size.load()
}
#[inline]
fn pos(&self) -> usize {
self.pos.load()
}
#[inline]
fn advance_pos(&self, step: usize) {
self.pos.store(self.pos() + step);
}
#[inline]
fn try_writable<R>(
&self,
vm: &VirtualMachine,
f: impl FnOnce(&mut [u8]) -> R,
) -> PyResult<R> {
if matches!(self.access, AccessMode::Read) {
return Err(vm.new_type_error("mmap can't modify a readonly memory map."));
}
match self.check_valid(vm)?.deref_mut().as_mut().unwrap() {
MmapObj::Mapped(mmap) => Ok(f(mmap.as_mut_slice())),
#[cfg(windows)]
MmapObj::Named(named) => Ok(f(named.as_mut_slice())),
}
}
fn check_valid(&self, vm: &VirtualMachine) -> PyResult<PyMutexGuard<'_, Option<MmapObj>>> {
let m = self.mmap.lock();
if m.is_none() {
return Err(vm.new_value_error("mmap closed or invalid"));
}
Ok(m)
}
/// TODO: impl resize
#[allow(dead_code)]
fn check_resizeable(&self, vm: &VirtualMachine) -> PyResult<()> {
if self.exports.load() > 0 {
return Err(vm.new_buffer_error("mmap can't resize with extant buffers exported."));
}
if self.access == AccessMode::Write || self.access == AccessMode::Default {
return Ok(());
}
Err(vm.new_type_error("mmap can't resize a readonly or copy-on-write memory map."))
}
#[pygetset]
fn closed(&self) -> bool {
self.closed.load()
}
#[pymethod]
fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
if self.closed() {
return Ok(());
}
if self.exports.load() > 0 {
return Err(vm.new_buffer_error("cannot close exported pointers exist."));
}
let mut mmap = self.mmap.lock();
self.closed.store(true);
*mmap = None;
self.close_handle();
Ok(())
}
fn get_find_range(&self, options: FindOptions) -> (usize, usize) {
let size = self.__len__();
let start = options
.start
.map_or_else(|| self.pos(), |start| start.saturated_at(size));
let end = options.end.map_or(size, |end| end.saturated_at(size));
(start, end)
}
#[pymethod]
fn find(&self, options: FindOptions, vm: &VirtualMachine) -> PyResult<PyInt> {
let (start, end) = self.get_find_range(options.clone());
let sub = &options.sub;
// returns start position for empty string
if sub.is_empty() {
return Ok(PyInt::from(start as isize));
}
let mmap = self.check_valid(vm)?;
let buf = &mmap.as_ref().unwrap().as_slice()[start..end];
let pos = buf.windows(sub.len()).position(|window| window == sub);
Ok(pos.map_or_else(|| PyInt::from(-1isize), |i| PyInt::from(start + i)))
}
#[pymethod]
fn rfind(&self, options: FindOptions, vm: &VirtualMachine) -> PyResult<PyInt> {
let (start, end) = self.get_find_range(options.clone());
let sub = &options.sub;
// returns start position for empty string
if sub.is_empty() {
return Ok(PyInt::from(start as isize));
}
let mmap = self.check_valid(vm)?;
let buf = &mmap.as_ref().unwrap().as_slice()[start..end];
let pos = buf.windows(sub.len()).rposition(|window| window == sub);
Ok(pos.map_or_else(|| PyInt::from(-1isize), |i| PyInt::from(start + i)))
}
#[pymethod]
fn flush(&self, options: FlushOptions, vm: &VirtualMachine) -> PyResult<()> {
let (offset, size) = options
.values(self.__len__())
.ok_or_else(|| vm.new_value_error("flush values out of range"))?;
if self.access == AccessMode::Read || self.access == AccessMode::Copy {
return Ok(());
}
match self.check_valid(vm)?.deref().as_ref().unwrap() {
MmapObj::Mapped(mmap) => {
mmap.flush_range(offset, size)
.map_err(|e| e.to_pyexception(vm))?;
}
#[cfg(windows)]
MmapObj::Named(named) => {
named
.flush_range(offset, size)
.map_err(|e| e.to_pyexception(vm))?;
}
}
Ok(())
}
#[cfg(all(unix, not(target_os = "redox")))]
#[pymethod]
fn madvise(&self, options: AdviseOptions, vm: &VirtualMachine) -> PyResult<()> {
let (option, start, length) = options.values(self.__len__(), vm)?;
if !host_mmap::validate_advice(option) {
return Err(vm.new_value_error("Not a valid Advice value"));
}
let guard = self.check_valid(vm)?;
let mmap = guard.deref().as_ref().unwrap();
match mmap {
MmapObj::Mapped(m) => m.madvise_range(start, length, option),
#[cfg(windows)]
MmapObj::Named(_) => unreachable!("unix-only method"),
}
.map_err(|e| e.to_pyexception(vm))?;
Ok(())
}
#[pymethod(name = "move")]
fn move_(
&self,
dest: PyIntRef,
src: PyIntRef,
cnt: PyIntRef,
vm: &VirtualMachine,
) -> PyResult<()> {
fn args(
dest: PyIntRef,
src: PyIntRef,
cnt: PyIntRef,
size: usize,
vm: &VirtualMachine,
) -> Option<(usize, usize, usize)> {
if dest.as_bigint().is_negative()
|| src.as_bigint().is_negative()
|| cnt.as_bigint().is_negative()
{
return None;
}
let dest = dest.try_to_primitive(vm).ok()?;
let src = src.try_to_primitive(vm).ok()?;
let cnt = cnt.try_to_primitive(vm).ok()?;
if size - dest < cnt || size - src < cnt {
return None;
}
Some((dest, src, cnt))
}
let size = self.__len__();
let (dest, src, cnt) = args(dest, src, cnt, size, vm)
.ok_or_else(|| vm.new_value_error("source, destination, or count out of range"))?;
let dest_end = dest + cnt;
let src_end = src + cnt;
self.try_writable(vm, |mmap| {
let src_buf = mmap[src..src_end].to_vec();
(&mut mmap[dest..dest_end])
.write(&src_buf)
.map_err(|e| e.to_pyexception(vm))?;
Ok(())
})?
}
#[pymethod]
fn read(&self, n: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
let num_bytes = n
.map(|obj| {
let class = obj.class().to_owned();
obj.try_into_value::<Option<isize>>(vm).map_err(|_| {
vm.new_type_error(format!(
"read argument must be int or None, not {}",
class.name()
))
})
})
.transpose()?
.flatten();
let mmap = self.check_valid(vm)?;
let pos = self.pos();
let remaining = self.__len__().saturating_sub(pos);
let num_bytes = num_bytes
.filter(|&n| n >= 0 && (n as usize) <= remaining)
.map_or(remaining, |n| n as usize);
let end_pos = pos + num_bytes;
let bytes = mmap.deref().as_ref().unwrap().as_slice()[pos..end_pos].to_vec();
let result = PyBytes::from(bytes).into_ref(&vm.ctx);
self.advance_pos(num_bytes);
Ok(result)
}
#[pymethod]
fn read_byte(&self, vm: &VirtualMachine) -> PyResult<PyIntRef> {
let pos = self.pos();
if pos >= self.__len__() {
return Err(vm.new_value_error("read byte out of range"));
}
let b = self.check_valid(vm)?.deref().as_ref().unwrap().as_slice()[pos];
self.advance_pos(1);
Ok(PyInt::from(b).into_ref(&vm.ctx))
}
#[pymethod]
fn readline(&self, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
let pos = self.pos();
let mmap = self.check_valid(vm)?;
let remaining = self.__len__().saturating_sub(pos);
if remaining == 0 {
return Ok(PyBytes::from(vec![]).into_ref(&vm.ctx));
}
let slice = mmap.as_ref().unwrap().as_slice();
let eof = slice[pos..].iter().position(|&x| x == b'\n');
let end_pos = if let Some(i) = eof {
pos + i + 1
} else {
self.__len__()
};
let bytes = slice[pos..end_pos].to_vec();
let result = PyBytes::from(bytes).into_ref(&vm.ctx);
self.advance_pos(end_pos - pos);
Ok(result)
}
#[cfg(unix)]
#[pymethod]
fn resize(&self, _newsize: PyIntRef, vm: &VirtualMachine) -> PyResult<()> {
self.check_resizeable(vm)?;
// TODO: implement using mremap on Linux
Err(vm.new_system_error("mmap: resizing not available--no mremap()"))
}
#[cfg(windows)]
#[pymethod]
fn resize(&self, newsize: PyIntRef, vm: &VirtualMachine) -> PyResult<()> {
self.check_resizeable(vm)?;
let newsize: usize = newsize
.try_to_primitive(vm)
.map_err(|_| vm.new_value_error("new size out of range"))?;
if newsize == 0 {
return Err(vm.new_value_error("new size must be positive"));
}
let handle = self.handle.load();