-
Notifications
You must be signed in to change notification settings - Fork 528
Expand file tree
/
Copy pathmemory.rs
More file actions
1667 lines (1510 loc) · 57.9 KB
/
Copy pathmemory.rs
File metadata and controls
1667 lines (1510 loc) · 57.9 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
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian, BigEndian};
use std::collections::{btree_map, BTreeMap, HashMap, HashSet, VecDeque};
use std::{fmt, iter, ptr, mem, io};
use std::cell::Cell;
use rustc::ty::Instance;
use rustc::ty::layout::{self, TargetDataLayout, HasDataLayout};
use syntax::ast::Mutability;
use rustc::middle::region;
use super::{EvalResult, EvalErrorKind, PrimVal, Pointer, EvalContext, DynamicLifetime, Machine,
RangeMap};
////////////////////////////////////////////////////////////////////////////////
// Locks
////////////////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum AccessKind {
Read,
Write,
}
/// Information about a lock that is currently held.
#[derive(Clone, Debug)]
struct LockInfo {
/// Stores for which lifetimes (of the original write lock) we got
/// which suspensions.
suspended: HashMap<DynamicLifetime, Vec<region::Scope>>,
/// The current state of the lock that's actually effective.
active: Lock,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Lock {
NoLock,
WriteLock(DynamicLifetime),
ReadLock(Vec<DynamicLifetime>), // This should never be empty -- that would be a read lock held and nobody there to release it...
}
use self::Lock::*;
impl Default for LockInfo {
fn default() -> Self {
LockInfo::new(NoLock)
}
}
impl LockInfo {
fn new(lock: Lock) -> LockInfo {
LockInfo {
suspended: HashMap::new(),
active: lock,
}
}
fn access_permitted(&self, frame: Option<usize>, access: AccessKind) -> bool {
use self::AccessKind::*;
match (&self.active, access) {
(&NoLock, _) => true,
(&ReadLock(ref lfts), Read) => {
assert!(!lfts.is_empty(), "Someone left an empty read lock behind.");
// Read access to read-locked region is okay, no matter who's holding the read lock.
true
}
(&WriteLock(ref lft), _) => {
// All access is okay if we are the ones holding it
Some(lft.frame) == frame
}
_ => false, // Nothing else is okay.
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Allocations and pointers
////////////////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AllocId(u64);
#[derive(Debug)]
pub enum AllocIdKind {
/// We can't ever have more than `usize::max_value` functions at the same time
/// since we never "deallocate" functions
Function(usize),
/// Locals and heap allocations (also statics for now, but those will get their
/// own variant soonish).
Runtime(u64),
}
impl AllocIdKind {
pub fn into_alloc_id(self) -> AllocId {
match self {
AllocIdKind::Function(n) => AllocId(n as u64),
AllocIdKind::Runtime(n) => AllocId((1 << 63) | n),
}
}
}
impl AllocId {
/// Currently yields the top bit to discriminate the `AllocIdKind`s
fn discriminant(self) -> u64 {
self.0 >> 63
}
/// Yields everything but the discriminant bits
pub fn index(self) -> u64 {
self.0 & ((1 << 63) - 1)
}
pub fn into_alloc_id_kind(self) -> AllocIdKind {
match self.discriminant() {
0 => AllocIdKind::Function(self.index() as usize),
1 => AllocIdKind::Runtime(self.index()),
n => bug!("got discriminant {} for AllocId", n),
}
}
}
impl fmt::Display for AllocId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.into_alloc_id_kind())
}
}
impl fmt::Debug for AllocId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.into_alloc_id_kind())
}
}
#[derive(Debug)]
pub struct Allocation<M> {
/// The actual bytes of the allocation.
/// Note that the bytes of a pointer represent the offset of the pointer
pub bytes: Vec<u8>,
/// Maps from byte addresses to allocations.
/// Only the first byte of a pointer is inserted into the map.
pub relocations: BTreeMap<u64, AllocId>,
/// Denotes undefined memory. Reading from undefined memory is forbidden in miri
pub undef_mask: UndefMask,
/// The alignment of the allocation to detect unaligned reads.
pub align: u64,
/// Whether the allocation may be modified.
pub mutable: Mutability,
/// Use the `mark_static_initalized` method of `Memory` to ensure that an error occurs, if the memory of this
/// allocation is modified or deallocated in the future.
/// Helps guarantee that stack allocations aren't deallocated via `rust_deallocate`
pub kind: MemoryKind<M>,
/// Memory regions that are locked by some function
locks: RangeMap<LockInfo>,
}
impl<M> Allocation<M> {
fn check_locks<'tcx>(
&self,
frame: Option<usize>,
offset: u64,
len: u64,
access: AccessKind,
) -> Result<(), LockInfo> {
if len == 0 {
return Ok(());
}
for lock in self.locks.iter(offset, len) {
// Check if the lock is in conflict with the access.
if !lock.access_permitted(frame, access) {
return Err(lock.clone());
}
}
Ok(())
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum MemoryKind<T> {
/// Error if deallocated except during a stack pop
Stack,
/// Static in the process of being initialized.
/// The difference is important: An immutable static referring to a
/// mutable initialized static will freeze immutably and would not
/// be able to distinguish already initialized statics from uninitialized ones
UninitializedStatic,
/// May never be deallocated
Static,
/// Additional memory kinds a machine wishes to distinguish from the builtin ones
Machine(T),
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MemoryPointer {
pub alloc_id: AllocId,
pub offset: u64,
}
impl<'tcx> MemoryPointer {
pub fn new(alloc_id: AllocId, offset: u64) -> Self {
MemoryPointer { alloc_id, offset }
}
pub(crate) fn wrapping_signed_offset<C: HasDataLayout>(self, i: i64, cx: C) -> Self {
MemoryPointer::new(
self.alloc_id,
cx.data_layout().wrapping_signed_offset(self.offset, i),
)
}
pub fn overflowing_signed_offset<C: HasDataLayout>(self, i: i128, cx: C) -> (Self, bool) {
let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset, i);
(MemoryPointer::new(self.alloc_id, res), over)
}
pub(crate) fn signed_offset<C: HasDataLayout>(self, i: i64, cx: C) -> EvalResult<'tcx, Self> {
Ok(MemoryPointer::new(
self.alloc_id,
cx.data_layout().signed_offset(self.offset, i)?,
))
}
pub fn overflowing_offset<C: HasDataLayout>(self, i: u64, cx: C) -> (Self, bool) {
let (res, over) = cx.data_layout().overflowing_offset(self.offset, i);
(MemoryPointer::new(self.alloc_id, res), over)
}
pub fn offset<C: HasDataLayout>(self, i: u64, cx: C) -> EvalResult<'tcx, Self> {
Ok(MemoryPointer::new(
self.alloc_id,
cx.data_layout().offset(self.offset, i)?,
))
}
}
////////////////////////////////////////////////////////////////////////////////
// Top-level interpreter memory
////////////////////////////////////////////////////////////////////////////////
pub struct Memory<'a, 'tcx, M: Machine<'tcx>> {
/// Additional data required by the Machine
pub data: M::MemoryData,
/// Actual memory allocations (arbitrary bytes, may contain pointers into other allocations).
alloc_map: HashMap<u64, Allocation<M::MemoryKinds>>,
/// The AllocId to assign to the next new regular allocation. Always incremented, never gets smaller.
next_alloc_id: u64,
/// Number of virtual bytes allocated.
memory_usage: u64,
/// Maximum number of virtual bytes that may be allocated.
memory_size: u64,
/// Function "allocations". They exist solely so pointers have something to point to, and
/// we can figure out what they point to.
functions: Vec<Instance<'tcx>>,
/// Inverse map of `functions` so we don't allocate a new pointer every time we need one
function_alloc_cache: HashMap<Instance<'tcx>, AllocId>,
/// Target machine data layout to emulate.
pub layout: &'a TargetDataLayout,
/// A cache for basic byte allocations keyed by their contents. This is used to deduplicate
/// allocations for string and bytestring literals.
literal_alloc_cache: HashMap<Vec<u8>, AllocId>,
/// To avoid having to pass flags to every single memory access, we have some global state saying whether
/// alignment checking is currently enforced for read and/or write accesses.
reads_are_aligned: Cell<bool>,
writes_are_aligned: Cell<bool>,
/// The current stack frame. Used to check accesses against locks.
pub(super) cur_frame: usize,
}
impl<'a, 'tcx, M: Machine<'tcx>> Memory<'a, 'tcx, M> {
pub fn new(layout: &'a TargetDataLayout, max_memory: u64, data: M::MemoryData) -> Self {
Memory {
data,
alloc_map: HashMap::new(),
functions: Vec::new(),
function_alloc_cache: HashMap::new(),
next_alloc_id: 0,
layout,
memory_size: max_memory,
memory_usage: 0,
literal_alloc_cache: HashMap::new(),
reads_are_aligned: Cell::new(true),
writes_are_aligned: Cell::new(true),
cur_frame: usize::max_value(),
}
}
pub fn allocations<'x>(
&'x self,
) -> impl Iterator<Item = (AllocId, &'x Allocation<M::MemoryKinds>)> {
self.alloc_map.iter().map(|(&id, alloc)| {
(AllocIdKind::Runtime(id).into_alloc_id(), alloc)
})
}
pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> MemoryPointer {
if let Some(&alloc_id) = self.function_alloc_cache.get(&instance) {
return MemoryPointer::new(alloc_id, 0);
}
let id = self.functions.len();
debug!("creating fn ptr: {}", id);
self.functions.push(instance);
let alloc_id = AllocIdKind::Function(id).into_alloc_id();
self.function_alloc_cache.insert(instance, alloc_id);
MemoryPointer::new(alloc_id, 0)
}
pub fn allocate_cached(&mut self, bytes: &[u8]) -> EvalResult<'tcx, MemoryPointer> {
if let Some(&alloc_id) = self.literal_alloc_cache.get(bytes) {
return Ok(MemoryPointer::new(alloc_id, 0));
}
let ptr = self.allocate(
bytes.len() as u64,
1,
MemoryKind::UninitializedStatic,
)?;
self.write_bytes(ptr.into(), bytes)?;
self.mark_static_initalized(
ptr.alloc_id,
Mutability::Immutable,
)?;
self.literal_alloc_cache.insert(
bytes.to_vec(),
ptr.alloc_id,
);
Ok(ptr)
}
pub fn allocate(
&mut self,
size: u64,
align: u64,
kind: MemoryKind<M::MemoryKinds>,
) -> EvalResult<'tcx, MemoryPointer> {
assert_ne!(align, 0);
assert!(align.is_power_of_two());
if self.memory_size - self.memory_usage < size {
return err!(OutOfMemory {
allocation_size: size,
memory_size: self.memory_size,
memory_usage: self.memory_usage,
});
}
self.memory_usage += size;
assert_eq!(size as usize as u64, size);
let alloc = Allocation {
bytes: vec![0; size as usize],
relocations: BTreeMap::new(),
undef_mask: UndefMask::new(size),
align,
kind,
mutable: Mutability::Mutable,
locks: RangeMap::new(),
};
let id = self.next_alloc_id;
self.next_alloc_id += 1;
self.alloc_map.insert(id, alloc);
Ok(MemoryPointer::new(
AllocIdKind::Runtime(id).into_alloc_id(),
0,
))
}
pub fn reallocate(
&mut self,
ptr: MemoryPointer,
old_size: u64,
old_align: u64,
new_size: u64,
new_align: u64,
kind: MemoryKind<M::MemoryKinds>,
) -> EvalResult<'tcx, MemoryPointer> {
use std::cmp::min;
if ptr.offset != 0 {
return err!(ReallocateNonBasePtr);
}
if let Ok(alloc) = self.get(ptr.alloc_id) {
if alloc.kind != kind {
return err!(ReallocatedWrongMemoryKind(
format!("{:?}", alloc.kind),
format!("{:?}", kind),
));
}
}
// For simplicities' sake, we implement reallocate as "alloc, copy, dealloc"
let new_ptr = self.allocate(new_size, new_align, kind)?;
self.copy(
ptr.into(),
new_ptr.into(),
min(old_size, new_size),
min(old_align, new_align),
/*nonoverlapping*/
true,
)?;
self.deallocate(ptr, Some((old_size, old_align)), kind)?;
Ok(new_ptr)
}
pub fn deallocate(
&mut self,
ptr: MemoryPointer,
size_and_align: Option<(u64, u64)>,
kind: MemoryKind<M::MemoryKinds>,
) -> EvalResult<'tcx> {
if ptr.offset != 0 {
return err!(DeallocateNonBasePtr);
}
let alloc_id = match ptr.alloc_id.into_alloc_id_kind() {
AllocIdKind::Function(_) => {
return err!(DeallocatedWrongMemoryKind(
"function".to_string(),
format!("{:?}", kind),
))
}
AllocIdKind::Runtime(id) => id,
};
let alloc = match self.alloc_map.remove(&alloc_id) {
Some(alloc) => alloc,
None => return err!(DoubleFree),
};
// It is okay for us to still holds locks on deallocation -- for example, we could store data we own
// in a local, and the local could be deallocated (from StorageDead) before the function returns.
// However, we should check *something*. For now, we make sure that there is no conflicting write
// lock by another frame. We *have* to permit deallocation if we hold a read lock.
// TODO: Figure out the exact rules here.
alloc
.check_locks(
Some(self.cur_frame),
0,
alloc.bytes.len() as u64,
AccessKind::Read,
)
.map_err(|lock| {
EvalErrorKind::DeallocatedLockedMemory {
ptr,
lock: lock.active,
}
})?;
if alloc.kind != kind {
return err!(DeallocatedWrongMemoryKind(
format!("{:?}", alloc.kind),
format!("{:?}", kind),
));
}
if let Some((size, align)) = size_and_align {
if size != alloc.bytes.len() as u64 || align != alloc.align {
return err!(IncorrectAllocationInformation);
}
}
self.memory_usage -= alloc.bytes.len() as u64;
debug!("deallocated : {}", ptr.alloc_id);
Ok(())
}
pub fn pointer_size(&self) -> u64 {
self.layout.pointer_size.bytes()
}
pub fn endianess(&self) -> layout::Endian {
self.layout.endian
}
/// Check that the pointer is aligned AND non-NULL.
pub fn check_align(&self, ptr: Pointer, align: u64, access: Option<AccessKind>) -> EvalResult<'tcx> {
// Check non-NULL/Undef, extract offset
let (offset, alloc_align) = match ptr.into_inner_primval() {
PrimVal::Ptr(ptr) => {
let alloc = self.get(ptr.alloc_id)?;
(ptr.offset, alloc.align)
}
PrimVal::Bytes(bytes) => {
let v = ((bytes as u128) % (1 << self.pointer_size())) as u64;
if v == 0 {
return err!(InvalidNullPointerUsage);
}
(v, align) // the base address if the "integer allocation" is 0 and hence always aligned
}
PrimVal::Undef => return err!(ReadUndefBytes),
};
// See if alignment checking is disabled
let enforce_alignment = match access {
Some(AccessKind::Read) => self.reads_are_aligned.get(),
Some(AccessKind::Write) => self.writes_are_aligned.get(),
None => true,
};
if !enforce_alignment {
return Ok(());
}
// Check alignment
if alloc_align < align {
return err!(AlignmentCheckFailed {
has: alloc_align,
required: align,
});
}
if offset % align == 0 {
Ok(())
} else {
err!(AlignmentCheckFailed {
has: offset % align,
required: align,
})
}
}
pub fn check_bounds(&self, ptr: MemoryPointer, access: bool) -> EvalResult<'tcx> {
let alloc = self.get(ptr.alloc_id)?;
let allocation_size = alloc.bytes.len() as u64;
if ptr.offset > allocation_size {
return err!(PointerOutOfBounds {
ptr,
access,
allocation_size,
});
}
Ok(())
}
}
/// Locking
impl<'a, 'tcx, M: Machine<'tcx>> Memory<'a, 'tcx, M> {
pub(crate) fn check_locks(
&self,
ptr: MemoryPointer,
len: u64,
access: AccessKind,
) -> EvalResult<'tcx> {
if len == 0 {
return Ok(());
}
let alloc = self.get(ptr.alloc_id)?;
let frame = self.cur_frame;
alloc
.check_locks(Some(frame), ptr.offset, len, access)
.map_err(|lock| {
EvalErrorKind::MemoryLockViolation {
ptr,
len,
frame,
access,
lock: lock.active,
}.into()
})
}
/// Acquire the lock for the given lifetime
pub(crate) fn acquire_lock(
&mut self,
ptr: MemoryPointer,
len: u64,
region: Option<region::Scope>,
kind: AccessKind,
) -> EvalResult<'tcx> {
let frame = self.cur_frame;
assert!(len > 0);
trace!(
"Frame {} acquiring {:?} lock at {:?}, size {} for region {:?}",
frame,
kind,
ptr,
len,
region
);
self.check_bounds(ptr.offset(len, self.layout)?, true)?; // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
let alloc = self.get_mut_unchecked(ptr.alloc_id)?;
// Iterate over our range and acquire the lock. If the range is already split into pieces,
// we have to manipulate all of them.
let lifetime = DynamicLifetime { frame, region };
for lock in alloc.locks.iter_mut(ptr.offset, len) {
if !lock.access_permitted(None, kind) {
return err!(MemoryAcquireConflict {
ptr,
len,
kind,
lock: lock.active.clone(),
});
}
// See what we have to do
match (&mut lock.active, kind) {
(active @ &mut NoLock, AccessKind::Write) => {
*active = WriteLock(lifetime);
}
(active @ &mut NoLock, AccessKind::Read) => {
*active = ReadLock(vec![lifetime]);
}
(&mut ReadLock(ref mut lifetimes), AccessKind::Read) => {
lifetimes.push(lifetime);
}
_ => bug!("We already checked that there is no conflicting lock"),
}
}
Ok(())
}
/// Release or suspend a write lock of the given lifetime prematurely.
/// When releasing, if there is a read lock or someone else's write lock, that's an error.
/// We *do* accept relasing a NoLock, as this can happen when a local is first acquired and later force_allocate'd.
/// When suspending, the same cases are fine; we just register an additional suspension.
pub(crate) fn suspend_write_lock(
&mut self,
ptr: MemoryPointer,
len: u64,
lock_region: Option<region::Scope>,
suspend: Option<region::Scope>,
) -> EvalResult<'tcx> {
assert!(len > 0);
let cur_frame = self.cur_frame;
let lock_lft = DynamicLifetime {
frame: cur_frame,
region: lock_region,
};
let alloc = self.get_mut_unchecked(ptr.alloc_id)?;
'locks: for lock in alloc.locks.iter_mut(ptr.offset, len) {
let is_our_lock = match lock.active {
WriteLock(lft) => lft == lock_lft,
ReadLock(_) | NoLock => false,
};
if is_our_lock {
trace!("Releasing {:?} at {:?}", lock.active, lock_lft);
// Disable the lock
lock.active = NoLock;
} else {
trace!(
"Not touching {:?} at {:?} as its not our lock",
lock.active,
lock_lft
);
}
match suspend {
Some(suspend_region) => {
trace!("Adding suspension to {:?} at {:?}", lock.active, lock_lft);
// We just released this lock, so add a new suspension.
// FIXME: Really, if there ever already is a suspension when is_our_lock, or if there is no suspension when !is_our_lock, something is amiss.
// But this model is not good enough yet to prevent that.
lock.suspended
.entry(lock_lft)
.or_insert_with(|| Vec::new())
.push(suspend_region);
}
None => {
// Make sure we did not try to release someone else's lock.
if !is_our_lock && lock.active != NoLock {
return err!(InvalidMemoryLockRelease {
ptr,
len,
frame: cur_frame,
lock: lock.active.clone(),
});
}
}
}
}
Ok(())
}
/// Release a suspension from the write lock. If this is the last suspension or if there is no suspension, acquire the lock.
pub(crate) fn recover_write_lock(
&mut self,
ptr: MemoryPointer,
len: u64,
lock_region: Option<region::Scope>,
suspended_region: region::Scope,
) -> EvalResult<'tcx> {
assert!(len > 0);
let cur_frame = self.cur_frame;
let lock_lft = DynamicLifetime {
frame: cur_frame,
region: lock_region,
};
let alloc = self.get_mut_unchecked(ptr.alloc_id)?;
for lock in alloc.locks.iter_mut(ptr.offset, len) {
// Check if we have a suspension here
let (got_the_lock, remove_suspension) = match lock.suspended.get_mut(&lock_lft) {
None => {
trace!("No suspension around, we can just acquire");
(true, false)
}
Some(suspensions) => {
trace!("Found suspension of {:?}, removing it", lock_lft);
// That's us! Remove suspension (it should be in there). The same suspension can
// occur multiple times (when there are multiple shared borrows of this that have the same
// lifetime); only remove one of them.
let idx = match suspensions.iter().enumerate().find(|&(_, re)| re == &suspended_region) {
None => // TODO: Can the user trigger this?
bug!("We have this lock suspended, but not for the given region."),
Some((idx, _)) => idx
};
suspensions.remove(idx);
let got_lock = suspensions.is_empty();
if got_lock {
trace!("All suspensions are gone, we can have the lock again");
}
(got_lock, got_lock)
}
};
if remove_suspension {
// with NLL, we could do that up in the match above...
assert!(got_the_lock);
lock.suspended.remove(&lock_lft);
}
if got_the_lock {
match lock.active {
ref mut active @ NoLock => {
*active = WriteLock(lock_lft);
}
_ => {
return err!(MemoryAcquireConflict {
ptr,
len,
kind: AccessKind::Write,
lock: lock.active.clone(),
})
}
}
}
}
Ok(())
}
pub(crate) fn locks_lifetime_ended(&mut self, ending_region: Option<region::Scope>) {
let cur_frame = self.cur_frame;
trace!(
"Releasing frame {} locks that expire at {:?}",
cur_frame,
ending_region
);
let has_ended = |lifetime: &DynamicLifetime| -> bool {
if lifetime.frame != cur_frame {
return false;
}
match ending_region {
None => true, // When a function ends, we end *all* its locks. It's okay for a function to still have lifetime-related locks
// when it returns, that can happen e.g. with NLL when a lifetime can, but does not have to, extend beyond the
// end of a function. Same for a function still having recoveries.
Some(ending_region) => lifetime.region == Some(ending_region),
}
};
for alloc in self.alloc_map.values_mut() {
for lock in alloc.locks.iter_mut_all() {
// Delete everything that ends now -- i.e., keep only all the other lifetimes.
let lock_ended = match lock.active {
WriteLock(ref lft) => has_ended(lft),
ReadLock(ref mut lfts) => {
lfts.retain(|lft| !has_ended(lft));
lfts.is_empty()
}
NoLock => false,
};
if lock_ended {
lock.active = NoLock;
}
// Also clean up suspended write locks
lock.suspended.retain(|lft, _suspensions| !has_ended(lft));
}
// Clean up the map
alloc.locks.retain(|lock| match lock.active {
NoLock => lock.suspended.len() > 0,
_ => true,
});
}
}
}
/// Allocation accessors
impl<'a, 'tcx, M: Machine<'tcx>> Memory<'a, 'tcx, M> {
pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation<M::MemoryKinds>> {
match id.into_alloc_id_kind() {
AllocIdKind::Function(_) => err!(DerefFunctionPointer),
AllocIdKind::Runtime(id) => {
match self.alloc_map.get(&id) {
Some(alloc) => Ok(alloc),
None => err!(DanglingPointerDeref),
}
}
}
}
fn get_mut_unchecked(
&mut self,
id: AllocId,
) -> EvalResult<'tcx, &mut Allocation<M::MemoryKinds>> {
match id.into_alloc_id_kind() {
AllocIdKind::Function(_) => err!(DerefFunctionPointer),
AllocIdKind::Runtime(id) => {
match self.alloc_map.get_mut(&id) {
Some(alloc) => Ok(alloc),
None => err!(DanglingPointerDeref),
}
}
}
}
fn get_mut(&mut self, id: AllocId) -> EvalResult<'tcx, &mut Allocation<M::MemoryKinds>> {
let alloc = self.get_mut_unchecked(id)?;
if alloc.mutable == Mutability::Mutable {
Ok(alloc)
} else {
err!(ModifiedConstantMemory)
}
}
pub fn get_fn(&self, ptr: MemoryPointer) -> EvalResult<'tcx, Instance<'tcx>> {
if ptr.offset != 0 {
return err!(InvalidFunctionPointer);
}
debug!("reading fn ptr: {}", ptr.alloc_id);
match ptr.alloc_id.into_alloc_id_kind() {
AllocIdKind::Function(id) => Ok(self.functions[id]),
AllocIdKind::Runtime(_) => err!(ExecuteMemory),
}
}
/// For debugging, print an allocation and all allocations it points to, recursively.
pub fn dump_alloc(&self, id: AllocId) {
self.dump_allocs(vec![id]);
}
/// For debugging, print a list of allocations and all allocations they point to, recursively.
pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
use std::fmt::Write;
allocs.sort();
allocs.dedup();
let mut allocs_to_print = VecDeque::from(allocs);
let mut allocs_seen = HashSet::new();
while let Some(id) = allocs_to_print.pop_front() {
let mut msg = format!("Alloc {:<5} ", format!("{}:", id));
let prefix_len = msg.len();
let mut relocations = vec![];
let alloc = match id.into_alloc_id_kind() {
AllocIdKind::Function(id) => {
trace!("{} {}", msg, self.functions[id]);
continue;
}
AllocIdKind::Runtime(id) => {
match self.alloc_map.get(&id) {
Some(a) => a,
None => {
trace!("{} (deallocated)", msg);
continue;
}
}
}
};
for i in 0..(alloc.bytes.len() as u64) {
if let Some(&target_id) = alloc.relocations.get(&i) {
if allocs_seen.insert(target_id) {
allocs_to_print.push_back(target_id);
}
relocations.push((i, target_id));
}
if alloc.undef_mask.is_range_defined(i, i + 1) {
// this `as usize` is fine, since `i` came from a `usize`
write!(msg, "{:02x} ", alloc.bytes[i as usize]).unwrap();
} else {
msg.push_str("__ ");
}
}
let immutable = match (alloc.kind, alloc.mutable) {
(MemoryKind::UninitializedStatic, _) => {
" (static in the process of initialization)".to_owned()
}
(MemoryKind::Static, Mutability::Mutable) => " (static mut)".to_owned(),
(MemoryKind::Static, Mutability::Immutable) => " (immutable)".to_owned(),
(MemoryKind::Machine(m), _) => format!(" ({:?})", m),
(MemoryKind::Stack, _) => " (stack)".to_owned(),
};
trace!(
"{}({} bytes, alignment {}){}",
msg,
alloc.bytes.len(),
alloc.align,
immutable
);
if !relocations.is_empty() {
msg.clear();
write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
let mut pos = 0;
let relocation_width = (self.pointer_size() - 1) * 3;
for (i, target_id) in relocations {
// this `as usize` is fine, since we can't print more chars than `usize::MAX`
write!(msg, "{:1$}", "", ((i - pos) * 3) as usize).unwrap();
let target = format!("({})", target_id);
// this `as usize` is fine, since we can't print more chars than `usize::MAX`
write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
pos = i + self.pointer_size();
}
trace!("{}", msg);
}
}
}
pub fn leak_report(&self) -> usize {
trace!("### LEAK REPORT ###");
let leaks: Vec<_> = self.alloc_map
.iter()
.filter_map(|(&key, val)| if val.kind != MemoryKind::Static {
Some(AllocIdKind::Runtime(key).into_alloc_id())
} else {
None
})
.collect();
let n = leaks.len();
self.dump_allocs(leaks);
n
}
}
/// Byte accessors
impl<'a, 'tcx, M: Machine<'tcx>> Memory<'a, 'tcx, M> {
fn get_bytes_unchecked(
&self,
ptr: MemoryPointer,
size: u64,
align: u64,
) -> EvalResult<'tcx, &[u8]> {
// Zero-sized accesses can use dangling pointers, but they still have to be aligned and non-NULL
self.check_align(ptr.into(), align, Some(AccessKind::Read))?;
if size == 0 {
return Ok(&[]);
}
self.check_locks(ptr, size, AccessKind::Read)?;
self.check_bounds(ptr.offset(size, self)?, true)?; // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
let alloc = self.get(ptr.alloc_id)?;
assert_eq!(ptr.offset as usize as u64, ptr.offset);
assert_eq!(size as usize as u64, size);
let offset = ptr.offset as usize;
Ok(&alloc.bytes[offset..offset + size as usize])
}
fn get_bytes_unchecked_mut(
&mut self,
ptr: MemoryPointer,
size: u64,
align: u64,
) -> EvalResult<'tcx, &mut [u8]> {
// Zero-sized accesses can use dangling pointers, but they still have to be aligned and non-NULL
self.check_align(ptr.into(), align, Some(AccessKind::Write))?;
if size == 0 {
return Ok(&mut []);
}
self.check_locks(ptr, size, AccessKind::Write)?;
self.check_bounds(ptr.offset(size, self.layout)?, true)?; // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
let alloc = self.get_mut(ptr.alloc_id)?;
assert_eq!(ptr.offset as usize as u64, ptr.offset);
assert_eq!(size as usize as u64, size);
let offset = ptr.offset as usize;
Ok(&mut alloc.bytes[offset..offset + size as usize])
}
fn get_bytes(&self, ptr: MemoryPointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
assert_ne!(size, 0);
if self.relocations(ptr, size)?.count() != 0 {
return err!(ReadPointerAsBytes);
}
self.check_defined(ptr, size)?;
self.get_bytes_unchecked(ptr, size, align)
}
fn get_bytes_mut(
&mut self,
ptr: MemoryPointer,
size: u64,
align: u64,
) -> EvalResult<'tcx, &mut [u8]> {
assert_ne!(size, 0);
self.clear_relocations(ptr, size)?;
self.mark_definedness(ptr.into(), size, true)?;
self.get_bytes_unchecked_mut(ptr, size, align)
}
}
/// Reading and writing
impl<'a, 'tcx, M: Machine<'tcx>> Memory<'a, 'tcx, M> {
/// mark an allocation pointed to by a static as static and initialized