-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess_standard.rs
2150 lines (1908 loc) · 88.6 KB
/
process_standard.rs
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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Tock default Process implementation.
//!
//! `ProcessStandard` is an implementation for a userspace process running on
//! the Tock kernel.
use core::cell::Cell;
use core::cmp;
use core::fmt::Write;
use core::num::NonZeroU32;
use core::ptr::NonNull;
use core::{mem, slice, str};
use flux_support::*;
use crate::collections::queue::Queue;
use crate::collections::ring_buffer::RingBuffer;
use crate::config;
use crate::debug;
use crate::errorcode::ErrorCode;
use crate::kernel::Kernel;
use crate::platform::chip::Chip;
use crate::platform::mpu::{self, MPU};
use crate::process::BinaryVersion;
use crate::process::ProcessBinary;
use crate::process::{Error, FunctionCall, FunctionCallSource, Process, Task};
use crate::process::{FaultAction, ProcessCustomGrantIdentifier, ProcessId};
use crate::process::{ProcessAddresses, ProcessSizes, ShortId};
use crate::process::{State, StoppedState};
use crate::process_checker::AcceptedCredential;
use crate::process_loading::ProcessLoadError;
use crate::process_policies::ProcessFaultPolicy;
use crate::processbuffer::{ReadOnlyProcessBuffer, ReadWriteProcessBuffer};
use crate::storage_permissions;
use crate::syscall::{self, Syscall, SyscallReturn, UserspaceKernelBoundary};
use crate::upcall::UpcallId;
use crate::utilities::cells::{MapCell, NumericCellExt, OptionalCell};
use tock_tbf::types::CommandPermissions;
/// State for helping with debugging apps.
///
/// These pointers and counters are not strictly required for kernel operation,
/// but provide helpful information when an app crashes.
struct ProcessStandardDebug {
/// If this process was compiled for fixed addresses, save the address
/// it must be at in flash. This is useful for debugging and saves having
/// to re-parse the entire TBF header.
fixed_address_flash: Option<u32>,
/// If this process was compiled for fixed addresses, save the address
/// it must be at in RAM. This is useful for debugging and saves having
/// to re-parse the entire TBF header.
fixed_address_ram: Option<u32>,
/// Where the process has started its heap in RAM.
app_heap_start_pointer: Option<FluxPtrU8Mut>,
/// Where the start of the stack is for the process. If the kernel does the
/// PIC setup for this app then we know this, otherwise we need the app to
/// tell us where it put its stack.
app_stack_start_pointer: Option<FluxPtrU8Mut>,
/// How low have we ever seen the stack pointer.
app_stack_min_pointer: Option<FluxPtrU8Mut>,
/// How many syscalls have occurred since the process started.
syscall_count: usize,
/// What was the most recent syscall.
last_syscall: Option<Syscall>,
/// How many upcalls were dropped because the queue was insufficiently
/// long.
dropped_upcall_count: usize,
/// How many times this process has been paused because it exceeded its
/// timeslice.
timeslice_expiration_count: usize,
}
/// Entry that is stored in the grant pointer table at the top of process
/// memory.
///
/// One copy of this entry struct is stored per grant region defined in the
/// kernel. This type allows the core kernel to lookup a grant based on the
/// driver_num associated with the grant, and also holds the pointer to the
/// memory allocated for the particular grant.
#[repr(C)]
struct GrantPointerEntry {
/// The syscall driver number associated with the allocated grant.
///
/// This defaults to 0 if the grant has not been allocated. Note, however,
/// that 0 is a valid driver_num, and therefore cannot be used to check if a
/// grant is allocated or not.
driver_num: usize,
/// The start of the memory location where the grant has been allocated, or
/// null if the grant has not been allocated.
grant_ptr: FluxPtrU8Mut,
}
// VTOCK-TODO: break up this struct when we have a better solution for interior mutability
// VTOCK-TODO: is it ok for app_break == kernel_break?
// kernel_memory_break > app_break && app_break <= high_water_mark
#[flux_rs::refined_by(kernel_break: int, app_break: int, allow_high_water_mark: int)]
#[flux_rs::invariant(kernel_break >= app_break)]
#[flux_rs::invariant(app_break >= allow_high_water_mark)]
#[derive(Clone, Copy)]
struct ProcessBreaks {
/// Pointer to the end of the allocated (and MPU protected) grant region.
#[field({FluxPtrU8Mut[kernel_break] | kernel_break >= app_break})]
pub kernel_memory_break: FluxPtrU8Mut,
/// Pointer to the end of process RAM that has been sbrk'd to the process.
#[field(FluxPtrU8Mut[app_break])]
pub app_break: FluxPtrU8Mut,
/// Pointer to high water mark for process buffers shared through `allow`
#[field({FluxPtrU8Mut[allow_high_water_mark] | app_break >= allow_high_water_mark})]
pub allow_high_water_mark: FluxPtrU8Mut,
}
/// A type for userspace processes in Tock.
#[flux_rs::refined_by(mem_start: FluxPtrU8Mut, mem_len: int)]
#[flux_rs::invariant(mem_start + mem_len <= usize::MAX)] // mem doesn't overflow address space
pub struct ProcessStandard<'a, C: 'static + Chip> {
/// Identifier of this process and the index of the process in the process
/// table.
process_id: Cell<ProcessId>,
/// An application ShortId, generated from process loading and
/// checking, which denotes the security identity of this process.
app_id: ShortId,
/// Pointer to the main Kernel struct.
kernel: &'static Kernel,
/// Pointer to the struct that defines the actual chip the kernel is running
/// on. This is used because processes have subtle hardware-based
/// differences. Specifically, the actual syscall interface and how
/// processes are switched to is architecture-specific, and how memory must
/// be allocated for memory protection units is also hardware-specific.
chip: &'static C,
/// Application memory layout:
///
/// ```text
/// ╒════════ ← memory_start + memory_len
/// ╔═ │ Grant Pointers
/// ║ │ ──────
/// │ Process Control Block
/// D │ ──────
/// Y │ Grant Regions
/// N │
/// A │ ↓
/// M │ ────── ← kernel_memory_break
/// I │
/// C │ ────── ← app_break ═╗
/// │ ║
/// ║ │ ↑ A
/// ║ │ Heap P C
/// ╠═ │ ────── ← app_heap_start R C
/// │ Data O E
/// F │ ────── ← data_start_pointer C S
/// I │ Stack E S
/// X │ ↓ S I
/// E │ S B
/// D │ ────── ← current_stack_pointer L
/// │ ║ E
/// ╚═ ╘════════ ← memory_start ═╝
/// ```
///
/// The start of process memory. We store this as a pointer and length and
/// not a slice due to Rust aliasing rules. If we were to store a slice,
/// then any time another slice to the same memory or an ProcessBuffer is
/// used in the kernel would be undefined behavior.
#[field(FluxPtrU8Mut[mem_start])]
memory_start: FluxPtrU8Mut,
/// Number of bytes of memory allocated to this process.
#[field({usize[mem_len] | mem_start + mem_len <= usize::MAX})]
memory_len: usize,
/// Reference to the slice of `GrantPointerEntry`s stored in the process's
/// memory reserved for the kernel. These driver numbers are zero and
/// pointers are null if the grant region has not been allocated. When the
/// grant region is allocated these pointers are updated to point to the
/// allocated memory and the driver number is set to match the driver that
/// owns the grant. No other reference to these pointers exists in the Tock
/// kernel.
grant_pointers: MapCell<&'static mut [GrantPointerEntry]>,
/// Pointers that demarcate kernel-managed regions and userspace-managed regions.
// #[field(Cell<ProcessBreaks[breaks]>)]
breaks: Cell<ProcessBreaks>,
/// Process flash segment. This is the region of nonvolatile flash that
/// the process occupies.
flash: &'static [u8],
/// The footers of the process binary (may be zero-sized), which are metadata
/// about the process not covered by integrity. Used, among other things, to
/// store signatures.
footers: &'static [u8],
/// Collection of pointers to the TBF header in flash.
header: tock_tbf::types::TbfHeader,
/// Credential that was approved for this process, or `None` if the
/// credential was permitted to run without an accepted credential.
credential: Option<AcceptedCredential>,
/// State saved on behalf of the process each time the app switches to the
/// kernel.
stored_state:
MapCell<<<C as Chip>::UserspaceKernelBoundary as UserspaceKernelBoundary>::StoredState>,
/// The current state of the app. The scheduler uses this to determine
/// whether it can schedule this app to execute.
///
/// The `state` is used both for bookkeeping for the scheduler as well as
/// for enabling control by other parts of the system. The scheduler keeps
/// track of if a process is ready to run or not by switching between the
/// `Running` and `Yielded` states. The system can control the process by
/// switching it to a "stopped" state to prevent the scheduler from
/// scheduling it.
state: Cell<State>,
/// How to respond if this process faults.
fault_policy: &'a dyn ProcessFaultPolicy,
/// Configuration data for the MPU
mpu_config: MapCell<<<C as Chip>::MPU as MPU>::MpuConfig>,
/// MPU regions are saved as a pointer-size pair.
mpu_regions: [Cell<Option<mpu::Region>>; 6],
/// Essentially a list of upcalls that want to call functions in the
/// process.
tasks: MapCell<RingBuffer<'a, Task>>,
/// Count of how many times this process has entered the fault condition and
/// been restarted. This is used by some `ProcessRestartPolicy`s to
/// determine if the process should be restarted or not.
restart_count: Cell<usize>,
/// The completion code set by the process when it last exited, restarted,
/// or was terminated. If the process is has never terminated, then the
/// `OptionalCell` will be empty (i.e. `None`). If the process has exited,
/// restarted, or terminated, the `OptionalCell` will contain an optional 32
/// bit value. The option will be `None` if the process crashed or was
/// stopped by the kernel and there is no provided completion code. If the
/// process called the exit syscall then the provided completion code will
/// be stored as `Some(completion code)`.
completion_code: OptionalCell<Option<u32>>,
/// Values kept so that we can print useful debug messages when apps fault.
debug: MapCell<ProcessStandardDebug>,
}
impl<C: Chip> Process for ProcessStandard<'_, C> {
fn processid(&self) -> ProcessId {
self.process_id.get()
}
fn short_app_id(&self) -> ShortId {
self.app_id
}
fn binary_version(&self) -> Option<BinaryVersion> {
let version = self.header.get_binary_version();
match NonZeroU32::new(version) {
Some(version_nonzero) => Some(BinaryVersion::new(version_nonzero)),
None => None,
}
}
fn get_credential(&self) -> Option<AcceptedCredential> {
self.credential
}
fn enqueue_task(&self, task: Task) -> Result<(), ErrorCode> {
// If this app is in a `Fault` state then we shouldn't schedule
// any work for it.
if !self.is_running() {
return Err(ErrorCode::NODEVICE);
}
let ret = self.tasks.map_or(Err(ErrorCode::FAIL), |tasks| {
match tasks.enqueue(task) {
true => {
// The task has been successfully enqueued.
Ok(())
}
false => {
// The task could not be enqueued as there is
// insufficient space in the ring buffer.
Err(ErrorCode::NOMEM)
}
}
});
if ret.is_err() {
// On any error we were unable to enqueue the task. Record the
// error, but importantly do _not_ increment kernel work.
self.debug.map(|debug| {
debug.dropped_upcall_count += 1;
});
}
ret
}
fn ready(&self) -> bool {
self.tasks.map_or(false, |ring_buf| ring_buf.has_elements())
|| self.state.get() == State::Running
}
fn remove_pending_upcalls(&self, upcall_id: UpcallId) {
self.tasks.map(|tasks| {
let count_before = tasks.len();
// VTOCK-TODO: prove tasks.retain() reduces number of tasks
tasks.retain(|task| match task {
// Remove only tasks that are function calls with an id equal
// to `upcall_id`.
Task::FunctionCall(function_call) => match function_call.source {
FunctionCallSource::Kernel => true,
FunctionCallSource::Driver(id) => id != upcall_id,
},
_ => true,
});
if config::CONFIG.trace_syscalls {
let count_after = tasks.len();
assume(count_before >= count_after); // requires refined ringbuffer
debug!(
"[{:?}] remove_pending_upcalls[{:#x}:{}] = {} upcall(s) removed",
self.processid(),
upcall_id.driver_num,
upcall_id.subscribe_num,
count_before - count_after,
);
}
});
}
fn is_running(&self) -> bool {
match self.state.get() {
State::Running | State::Yielded | State::YieldedFor(_) | State::Stopped(_) => true,
_ => false,
}
}
fn get_state(&self) -> State {
self.state.get()
}
fn set_yielded_state(&self) {
if self.state.get() == State::Running {
self.state.set(State::Yielded);
}
}
fn set_yielded_for_state(&self, upcall_id: UpcallId) {
if self.state.get() == State::Running {
self.state.set(State::YieldedFor(upcall_id));
}
}
fn stop(&self) {
match self.state.get() {
State::Running => self.state.set(State::Stopped(StoppedState::Running)),
State::Yielded => self.state.set(State::Stopped(StoppedState::Yielded)),
State::YieldedFor(upcall_id) => self
.state
.set(State::Stopped(StoppedState::YieldedFor(upcall_id))),
State::Stopped(_stopped_state) => {
// Already stopped, nothing to do.
}
State::Faulted | State::Terminated => {
// Stop has no meaning on a inactive process.
}
}
}
fn resume(&self) {
match self.state.get() {
State::Stopped(stopped_state) => match stopped_state {
StoppedState::Running => self.state.set(State::Running),
StoppedState::Yielded => self.state.set(State::Yielded),
StoppedState::YieldedFor(upcall_id) => self.state.set(State::YieldedFor(upcall_id)),
},
_ => {} // Do nothing
}
}
fn set_fault_state(&self) {
// Use the per-process fault policy to determine what action the kernel
// should take since the process faulted.
let action = self.fault_policy.action(self);
match action {
FaultAction::Panic => {
// process faulted. Panic and print status
self.state.set(State::Faulted);
panic!("Process {} had a fault", self.get_process_name());
}
FaultAction::Restart => {
self.try_restart(None);
}
FaultAction::Stop => {
// This looks a lot like restart, except we just leave the app
// how it faulted and mark it as `Faulted`. By clearing
// all of the app's todo work it will not be scheduled, and
// clearing all of the grant regions will cause capsules to drop
// this app as well.
self.terminate(None);
self.state.set(State::Faulted);
}
}
}
fn start(&self, _cap: &dyn crate::capabilities::ProcessStartCapability) {
// `start()` can only be called on a terminated process.
if self.get_state() != State::Terminated {
return;
}
// Reset to start the process.
if let Ok(()) = self.reset() {
self.state.set(State::Yielded);
}
}
fn try_restart(&self, completion_code: Option<u32>) {
// `try_restart()` cannot be called if the process is terminated. Only
// `start()` can start a terminated process.
if self.get_state() == State::Terminated {
return;
}
// Terminate the process, freeing its state and removing any
// pending tasks from the scheduler's queue.
self.terminate(completion_code);
// If there is a kernel policy that controls restarts, it should be
// implemented here. For now, always restart.
if let Ok(()) = self.reset() {
self.state.set(State::Yielded);
}
// Decide what to do with res later. E.g., if we can't restart
// want to reclaim the process resources.
}
fn terminate(&self, completion_code: Option<u32>) {
// A process can be terminated if it is running or in the `Faulted`
// state. Otherwise, you cannot terminate it and this method return
// early.
//
// The kernel can terminate in the `Faulted` state to return the process
// to a state in which it can run again (e.g., reset it).
if !self.is_running() && self.get_state() != State::Faulted {
return;
}
// And remove those tasks
self.tasks.map(|tasks| {
tasks.empty();
});
// Clear any grant regions this app has setup with any capsules.
unsafe {
self.grant_ptrs_reset();
}
// Save the completion code.
self.completion_code.set(completion_code);
// Mark the app as stopped so the scheduler won't try to run it.
self.state.set(State::Terminated);
}
fn get_restart_count(&self) -> usize {
self.restart_count.get()
}
fn has_tasks(&self) -> bool {
self.tasks.map_or(false, |tasks| tasks.has_elements())
}
fn dequeue_task(&self) -> Option<Task> {
self.tasks.map_or(None, |tasks| tasks.dequeue())
}
fn remove_upcall(&self, upcall_id: UpcallId) -> Option<Task> {
self.tasks.map_or(None, |tasks| {
tasks.remove_first_matching(|task| match task {
Task::FunctionCall(fc) => match fc.source {
FunctionCallSource::Driver(upid) => upid == upcall_id,
_ => false,
},
Task::ReturnValue(rv) => rv.upcall_id == upcall_id,
Task::IPC(_) => false,
})
})
}
fn pending_tasks(&self) -> usize {
self.tasks.map_or(0, |tasks| tasks.len())
}
fn get_command_permissions(&self, driver_num: usize, offset: usize) -> CommandPermissions {
self.header.get_command_permissions(driver_num, offset)
}
fn get_storage_permissions(&self) -> Option<storage_permissions::StoragePermissions> {
let (read_count, read_ids) = self.header.get_storage_read_ids().unwrap_or((0, [0; 8]));
let (modify_count, modify_ids) =
self.header.get_storage_modify_ids().unwrap_or((0, [0; 8]));
let write_id = self.header.get_storage_write_id();
Some(storage_permissions::StoragePermissions::new(
read_count,
read_ids,
modify_count,
modify_ids,
write_id,
))
}
fn number_writeable_flash_regions(&self) -> usize {
self.header.number_writeable_flash_regions()
}
fn get_writeable_flash_region(&self, region_index: usize) -> (u32, u32) {
self.header.get_writeable_flash_region(region_index)
}
fn update_stack_start_pointer(&self, stack_pointer: FluxPtrU8Mut) {
if stack_pointer >= self.mem_start() && stack_pointer < self.mem_end() {
self.debug.map(|debug| {
debug.app_stack_start_pointer = Some(stack_pointer);
// We also reset the minimum stack pointer because whatever
// value we had could be entirely wrong by now.
debug.app_stack_min_pointer = Some(stack_pointer);
});
}
}
fn update_heap_start_pointer(&self, heap_pointer: FluxPtrU8Mut) {
if heap_pointer >= self.mem_start() && heap_pointer < self.mem_end() {
self.debug.map(|debug| {
debug.app_heap_start_pointer = Some(heap_pointer);
});
}
}
fn setup_mpu(&self) {
self.mpu_config.map(|config| {
self.chip.mpu().configure_mpu(config);
});
}
fn add_mpu_region(
&self,
unallocated_memory_start: FluxPtrU8Mut,
unallocated_memory_size: usize,
min_region_size: usize,
) -> Option<mpu::Region> {
self.mpu_config.and_then(|config| {
let new_region = self.chip.mpu().allocate_region(
unallocated_memory_start,
unallocated_memory_size,
min_region_size,
mpu::Permissions::ReadWriteOnly,
config,
)?;
for region in self.mpu_regions.iter() {
if region.get().is_none() {
region.set(Some(new_region));
return Some(new_region);
}
}
// Not enough room in Process struct to store the MPU region.
None
})
}
fn remove_mpu_region(&self, region: mpu::Region) -> Result<(), ErrorCode> {
self.mpu_config.map_or(Err(ErrorCode::INVAL), |config| {
// Find the existing mpu region that we are removing; it needs to match exactly.
if let Some(internal_region) = self
.mpu_regions
.iter()
.find(|r| r.get().map_or(false, |r| r == region))
{
self.chip
.mpu()
.remove_memory_region(region, config)
.or(Err(ErrorCode::FAIL))?;
// Remove this region from the tracking cache of mpu_regions
internal_region.set(None);
Ok(())
} else {
Err(ErrorCode::INVAL)
}
})
}
fn sbrk(&self, increment: isize) -> Result<FluxPtrU8Mut, Error> {
// Do not modify an inactive process.
if !self.is_running() {
return Err(Error::InactiveApp);
}
let new_break = unsafe { self.app_memory_break().offset(increment) };
self.brk(new_break)
}
fn brk(&self, new_break: FluxPtrU8Mut) -> Result<FluxPtrU8Mut, Error> {
// Do not modify an inactive process.
if !self.is_running() {
return Err(Error::InactiveApp);
}
self.mpu_config.map_or(Err(Error::KernelError), |config| {
let mut breaks = self.breaks.get();
let high_water_mark = breaks.allow_high_water_mark;
if new_break < high_water_mark || new_break >= self.mem_end() {
Err(Error::AddressOutOfBounds)
} else if new_break > breaks.kernel_memory_break {
Err(Error::OutOfMemory)
} else if let Err(()) = self.chip.mpu().update_app_memory_region(
new_break,
breaks.kernel_memory_break,
mpu::Permissions::ReadWriteOnly,
config,
) {
Err(Error::OutOfMemory)
} else {
let old_break = breaks.app_break;
breaks.app_break = new_break;
self.breaks.set(breaks);
self.chip.mpu().configure_mpu(config);
Ok(old_break)
}
})
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn build_readwrite_process_buffer(
&self,
buf_start_addr: FluxPtrU8Mut,
size: usize,
) -> Result<ReadWriteProcessBuffer, ErrorCode> {
if !self.is_running() {
// Do not operate on an inactive process
return Err(ErrorCode::FAIL);
}
// A process is allowed to pass any pointer if the buffer length is 0,
// as to revoke kernel access to a memory region without granting access
// to another one
if size == 0 {
// Clippy complains that we're dereferencing a pointer in a public
// and safe function here. While we are not dereferencing the
// pointer here, we pass it along to an unsafe function, which is as
// dangerous (as it is likely to be dereferenced down the line).
//
// Relevant discussion:
// https://github.com/rust-lang/rust-clippy/issues/3045
//
// It should be fine to ignore the lint here, as a buffer of length
// 0 will never allow dereferencing any memory in a safe manner.
//
// ### Safety
//
// We specify a zero-length buffer, so the implementation of
// `ReadWriteProcessBuffer` will handle any safety issues.
// Therefore, we can encapsulate the unsafe.
Ok(unsafe { ReadWriteProcessBuffer::new(buf_start_addr, 0, self.processid()) })
} else if self.in_app_owned_memory(buf_start_addr, size) {
// TODO: Check for buffer aliasing here
let mut breaks = self.breaks.get();
// Valid buffer, we need to adjust the app's watermark
// note: `in_app_owned_memory` ensures this offset does not wrap
let buf_end_addr = buf_start_addr.wrapping_add(size);
assume(breaks.app_break >= buf_end_addr);
let new_water_mark = max_ptr(breaks.allow_high_water_mark, buf_end_addr);
assert(breaks.kernel_memory_break >= breaks.app_break);
assert(breaks.app_break >= breaks.allow_high_water_mark);
assert(breaks.app_break >= new_water_mark);
breaks.allow_high_water_mark = new_water_mark;
self.breaks.set(breaks);
// Clippy complains that we're dereferencing a pointer in a public
// and safe function here. While we are not dereferencing the
// pointer here, we pass it along to an unsafe function, which is as
// dangerous (as it is likely to be dereferenced down the line).
//
// Relevant discussion:
// https://github.com/rust-lang/rust-clippy/issues/3045
//
// It should be fine to ignore the lint here, as long as we make
// sure that we're pointing towards userspace memory (verified using
// `in_app_owned_memory`) and respect alignment and other
// constraints of the Rust references created by
// `ReadWriteProcessBuffer`.
//
// ### Safety
//
// We encapsulate the unsafe here on the condition in the TODO
// above, as we must ensure that this `ReadWriteProcessBuffer` will
// be the only reference to this memory.
Ok(unsafe { ReadWriteProcessBuffer::new(buf_start_addr, size, self.processid()) })
} else {
Err(ErrorCode::INVAL)
}
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[flux_rs::trusted]
fn build_readonly_process_buffer(
&self,
buf_start_addr: FluxPtrU8Mut,
size: usize,
) -> Result<ReadOnlyProcessBuffer, ErrorCode> {
if !self.is_running() {
// Do not operate on an inactive process
return Err(ErrorCode::FAIL);
}
// A process is allowed to pass any pointer if the buffer length is 0,
// as to revoke kernel access to a memory region without granting access
// to another one
if size == 0 {
// Clippy complains that we're dereferencing a pointer in a public
// and safe function here. While we are not dereferencing the
// pointer here, we pass it along to an unsafe function, which is as
// dangerous (as it is likely to be dereferenced down the line).
//
// Relevant discussion:
// https://github.com/rust-lang/rust-clippy/issues/3045
//
// It should be fine to ignore the lint here, as a buffer of length
// 0 will never allow dereferencing any memory in a safe manner.
//
// ### Safety
//
// We specify a zero-length buffer, so the implementation of
// `ReadOnlyProcessBuffer` will handle any safety issues. Therefore,
// we can encapsulate the unsafe.
Ok(unsafe { ReadOnlyProcessBuffer::new(buf_start_addr, 0, self.processid()) })
} else if self.in_app_owned_memory(buf_start_addr, size)
|| self.in_app_flash_memory(buf_start_addr, size)
{
// TODO: Check for buffer aliasing here
if self.in_app_owned_memory(buf_start_addr, size) {
// Valid buffer, and since this is in read-write memory (i.e.
// not flash), we need to adjust the process's watermark. Note:
// `in_app_owned_memory()` ensures this offset does not wrap.
let buf_end_addr = buf_start_addr.wrapping_add(size);
let mut breaks = self.breaks.get();
let new_water_mark = cmp::max(breaks.allow_high_water_mark, buf_end_addr);
breaks.allow_high_water_mark = new_water_mark;
self.breaks.set(breaks);
// self.allow_high_water_mark.set(new_water_mark);
}
// Clippy complains that we're dereferencing a pointer in a public
// and safe function here. While we are not dereferencing the
// pointer here, we pass it along to an unsafe function, which is as
// dangerous (as it is likely to be dereferenced down the line).
//
// Relevant discussion:
// https://github.com/rust-lang/rust-clippy/issues/3045
//
// It should be fine to ignore the lint here, as long as we make
// sure that we're pointing towards userspace memory (verified using
// `in_app_owned_memory` or `in_app_flash_memory`) and respect
// alignment and other constraints of the Rust references created by
// `ReadWriteProcessBuffer`.
//
// ### Safety
//
// We encapsulate the unsafe here on the condition in the TODO
// above, as we must ensure that this `ReadOnlyProcessBuffer` will
// be the only reference to this memory.
Ok(unsafe { ReadOnlyProcessBuffer::new(buf_start_addr, size, self.processid()) })
} else {
Err(ErrorCode::INVAL)
}
}
unsafe fn set_byte(&self, mut addr: FluxPtrU8Mut, value: u8) -> bool {
if self.in_app_owned_memory(addr, 1) {
// We verify that this will only write process-accessible memory,
// but this can still be undefined behavior if something else holds
// a reference to this memory.
*addr = value;
true
} else {
false
}
}
fn grant_is_allocated(&self, grant_num: usize) -> Option<bool> {
// Do not modify an inactive process.
if !self.is_running() {
return None;
}
// Update the grant pointer to the address of the new allocation.
self.grant_pointers.map_or(None, |grant_pointers| {
// Implement `grant_pointers[grant_num]` without a chance of a
// panic.
grant_pointers
.get(grant_num)
.map(|grant_entry| !grant_entry.grant_ptr.is_null())
})
}
fn allocate_grant(
&self,
grant_num: usize,
driver_num: usize,
size: usize,
align: usize,
) -> Result<(), ()> {
// Do not modify an inactive process.
if !self.is_running() {
return Err(());
}
// Verify the grant_num is valid.
if grant_num >= self.kernel.get_grant_count_and_finalize() {
return Err(());
}
// Verify that the grant is not already allocated. If the pointer is not
// null then the grant is already allocated.
if let Some(is_allocated) = self.grant_is_allocated(grant_num) {
if is_allocated {
return Err(());
}
}
// Verify that there is not already a grant allocated with the same
// `driver_num`.
let exists = self.grant_pointers.map_or(false, |grant_pointers| {
// Check our list of grant pointers if the driver number is used.
grant_pointers.iter().any(|grant_entry| {
// Check if the grant is both allocated (its grant pointer is
// non null) and the driver number matches.
(!grant_entry.grant_ptr.is_null()) && grant_entry.driver_num == driver_num
})
});
// If we find a match, then the `driver_num` must already be used and
// the grant allocation fails.
if exists {
return Err(());
}
// Use the shared grant allocator function to actually allocate memory.
// Returns `None` if the allocation cannot be created.
if let Some(grant_ptr) = self.allocate_in_grant_region_internal(size, align) {
// Update the grant pointer to the address of the new allocation.
self.grant_pointers.map_or(Err(()), |grant_pointers| {
// Implement `grant_pointers[grant_num] = grant_ptr` without a
// chance of a panic.
grant_pointers
.get_mut(grant_num)
.map_or(Err(()), |grant_entry| {
// Actually set the driver num and grant pointer.
grant_entry.driver_num = driver_num;
grant_entry.grant_ptr = grant_ptr.as_fluxptr();
// If all of this worked, return true.
Ok(())
})
})
} else {
// Could not allocate the memory for the grant region.
Err(())
}
}
#[flux_rs::trusted]
fn allocate_custom_grant(
&self,
size: usize,
align: usize,
) -> Result<(ProcessCustomGrantIdentifier, NonNull<u8>), ()> {
// Do not modify an inactive process.
if !self.is_running() {
return Err(());
}
// Use the shared grant allocator function to actually allocate memory.
// Returns `None` if the allocation cannot be created.
if let Some(ptr) = self.allocate_in_grant_region_internal(size, align) {
// Create the identifier that the caller will use to get access to
// this custom grant in the future.
let identifier = self.create_custom_grant_identifier(ptr);
Ok((identifier, ptr))
} else {
// Could not allocate memory for the custom grant.
Err(())
}
}
fn enter_grant(&self, grant_num: usize) -> Result<NonNull<u8>, Error> {
// Do not try to access the grant region of an inactive process.
if !self.is_running() {
return Err(Error::InactiveApp);
}
// Retrieve the grant pointer from the `grant_pointers` slice. We use
// `[slice].get()` so that if the grant number is invalid this will
// return `Err` and not panic.
self.grant_pointers
.map_or(Err(Error::KernelError), |grant_pointers| {
// Implement `grant_pointers[grant_num]` without a chance of a
// panic.
match grant_pointers.get_mut(grant_num) {
Some(grant_entry) => {
// Get a copy of the actual grant pointer.
let grant_ptr = grant_entry.grant_ptr;
// Check if the grant pointer is marked that the grant
// has already been entered. If so, return an error.
if (grant_ptr.as_usize()) & 0x1 == 0x1 {
// Lowest bit is one, meaning this grant has been
// entered.
Err(Error::AlreadyInUse)
} else {
// Now, to mark that the grant has been entered, we
// set the lowest bit to one and save this as the
// grant pointer.
grant_entry.grant_ptr = (grant_ptr.as_usize() | 0x1).as_fluxptr();
// And we return the grant pointer to the entered
// grant.
Ok(unsafe { NonNull::new_unchecked(grant_ptr.unsafe_as_ptr()) })
}
}
None => Err(Error::AddressOutOfBounds),
}
})
}
fn enter_custom_grant(
&self,
identifier: ProcessCustomGrantIdentifier,
) -> Result<FluxPtrU8Mut, Error> {
// Do not try to access the grant region of an inactive process.
if !self.is_running() {
return Err(Error::InactiveApp);
}
// Get the address of the custom grant based on the identifier.
let custom_grant_address = self.get_custom_grant_address(identifier);
// We never deallocate custom grants and only we can change the
// `identifier` so we know this is a valid address for the custom grant.
Ok(custom_grant_address.as_fluxptr())
}
unsafe fn leave_grant(&self, grant_num: usize) {
// Do not modify an inactive process.
if !self.is_running() {
return;
}
self.grant_pointers.map(|grant_pointers| {
// Implement `grant_pointers[grant_num]` without a chance of a
// panic.
if let Some(grant_entry) = grant_pointers.get_mut(grant_num) {
// Get a copy of the actual grant pointer.
let grant_ptr = grant_entry.grant_ptr;
// Now, to mark that the grant has been released, we set the
// lowest bit back to zero and save this as the grant
// pointer.
grant_entry.grant_ptr = (grant_ptr.as_usize() & !0x1).as_fluxptr();
}
});