Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/object/process.rs

kernel/object/
process.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use foreign_box::ForeignBox;
16use pw_status::{Error, Result};
17use syscall_defs::ExitStatus;
18
19use crate::Kernel;
20use crate::object::{KernelObject, ObjectBase, SignalUpdate, Signals};
21use crate::scheduler::{Process, ProcessHandle, SchedulerState};
22use crate::sync::spinlock::{SpinLock, SpinLockGuard};
23
24#[derive(Clone)]
25pub struct MainThread<K: Kernel> {
26    pub thread: foreign_box::ForeignRc<K::AtomicUsize, super::thread::ThreadObject<K>>,
27    pub initial_pc: usize,
28    pub initial_sp: usize,
29    pub args: (usize, usize, usize),
30}
31
32enum ProcessState<K: Kernel> {
33    Stopped(ForeignBox<Process<K>>),
34    Running(ProcessHandle<K>),
35    Empty,
36}
37
38impl<K: Kernel> ProcessState<K> {
39    fn take_process(&mut self) -> Option<ForeignBox<Process<K>>> {
40        match core::mem::replace(self, ProcessState::Empty) {
41            ProcessState::Stopped(process) => Some(process),
42            state => {
43                *self = state;
44                None
45            }
46        }
47    }
48}
49
50struct State<K: Kernel> {
51    process_state: ProcessState<K>,
52    main_thread: Option<MainThread<K>>,
53}
54
55pub struct ProcessObject<K: Kernel> {
56    base: ObjectBase<K>,
57    state: SpinLock<K, State<K>>,
58}
59
60impl<K: Kernel> ProcessObject<K> {
61    #[must_use]
62    pub const fn new(process: ForeignBox<Process<K>>, main_thread: Option<MainThread<K>>) -> Self {
63        Self {
64            base: ObjectBase::new(Signals::no_active()),
65            state: SpinLock::new(State {
66                process_state: ProcessState::Stopped(process),
67                main_thread,
68            }),
69        }
70    }
71
72    #[must_use]
73    pub const fn new_empty() -> Self {
74        Self {
75            base: ObjectBase::new(Signals::no_active()),
76            state: SpinLock::new(State {
77                process_state: ProcessState::Empty,
78                main_thread: None,
79            }),
80        }
81    }
82
83    pub fn set_process(
84        &self,
85        kernel: K,
86        process: ForeignBox<Process<K>>,
87        main_thread: Option<MainThread<K>>,
88    ) -> Result<()> {
89        let mut state = self.state.lock(kernel);
90        match state.process_state {
91            ProcessState::Empty => {
92                state.process_state = ProcessState::Stopped(process);
93                state.main_thread = main_thread;
94                Ok(())
95            }
96            _ => Err(Error::AlreadyExists),
97        }
98    }
99
100    pub fn start(&self, kernel: K) -> Result<()> {
101        let mut state = self.state.lock(kernel);
102
103        let Some(mut process) = state.process_state.take_process() else {
104            return Err(Error::AlreadyExists);
105        };
106
107        // SAFETY: `ProcessObject` is a kernel object that is always managed
108        // within a `ForeignRcState` (e.g., when wrapped in `ForeignRc` or
109        // `ForeignBox` for the object table). Thus, the `&self` reference
110        // points to storage contained inside a `ForeignRcState`.
111        let self_rc = unsafe { foreign_box::ForeignRcState::create_ref_from_inner(self) };
112        process.object = Some(self_rc.clone());
113
114        let process_handle = crate::scheduler::add_process(kernel, process);
115        state.process_state = ProcessState::Running(process_handle.clone());
116
117        if let Some(main_thread) = &state.main_thread {
118            main_thread.thread.start(
119                kernel,
120                process_handle,
121                main_thread.initial_pc,
122                main_thread.initial_sp,
123                main_thread.args,
124            )?;
125        }
126
127        Ok(())
128    }
129
130    pub fn terminate(&self, kernel: K) -> Result<()> {
131        let process_handle = {
132            let state = self.state.lock(kernel);
133            match &state.process_state {
134                ProcessState::Running(process_handle) => process_handle.clone(),
135                ProcessState::Stopped(_) => return Err(Error::FailedPrecondition),
136                ProcessState::Empty => return Err(Error::Internal),
137            }
138        };
139        process_handle.terminate(kernel, ExitStatus::TerminatedBySyscall);
140        Ok(())
141    }
142
143    pub fn join(&self, kernel: K) -> Result<ExitStatus> {
144        let process_handle = {
145            let mut state = self.state.lock(kernel);
146            match core::mem::replace(&mut state.process_state, ProcessState::Empty) {
147                ProcessState::Running(p) => p,
148                old_state => {
149                    state.process_state = old_state;
150                    return Err(Error::FailedPrecondition);
151                }
152            }
153        };
154
155        use crate::scheduler::ProcessTryJoinResult;
156        match process_handle.try_join(kernel) {
157            ProcessTryJoinResult::Joined(process, status) => {
158                #[cfg(feature = "user_space")]
159                process.reset_objects(kernel)?;
160                let mut state = self.state.lock(kernel);
161                state.process_state = ProcessState::Stopped(process);
162                Ok(status)
163            }
164            ProcessTryJoinResult::Wait(process_handle) => {
165                let mut state = self.state.lock(kernel);
166                state.process_state = ProcessState::Running(process_handle);
167                Err(Error::Unavailable)
168            }
169            ProcessTryJoinResult::Err {
170                error,
171                process: process_handle,
172            } => {
173                let mut state = self.state.lock(kernel);
174                state.process_state = ProcessState::Running(process_handle);
175                Err(error)
176            }
177        }
178    }
179
180    pub(crate) fn signal_locked<'a>(
181        &self,
182        kernel: K,
183        sched: SpinLockGuard<'a, K, SchedulerState<K>>,
184        update: SignalUpdate,
185    ) -> SpinLockGuard<'a, K, SchedulerState<K>> {
186        self.base.signal_locked(kernel, sched, update)
187    }
188}
189
190impl<K: Kernel> KernelObject<K> for ProcessObject<K> {
191    fn base(&self) -> Option<&ObjectBase<K>> {
192        Some(&self.base)
193    }
194
195    fn object_wait(
196        &self,
197        kernel: K,
198        signal_mask: Signals,
199        deadline: pw_time_core::Instant<K::Clock>,
200    ) -> Result<crate::object::WaitReturn> {
201        self.base.wait_until(kernel, signal_mask, deadline)
202    }
203
204    fn process_start(&self, kernel: K) -> Result<()> {
205        self.start(kernel)
206    }
207
208    fn task_terminate(&self, kernel: K) -> Result<()> {
209        self.terminate(kernel)
210    }
211
212    fn task_join(&self, kernel: K) -> Result<ExitStatus> {
213        self.join(kernel)
214    }
215}