Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
1 value
test_patch
stringlengths
335
66.3k
issue_numbers
sequencelengths
1
2
version
stringclasses
9 values
base_commit
stringlengths
40
40
problem_statement
stringlengths
33
13k
instance_id
stringlengths
24
25
pull_number
int64
183
1.64k
patch
stringlengths
448
420k
hints_text
stringlengths
0
64.4k
created_at
stringlengths
20
20
environment_setup_commit
stringclasses
10 values
asterinas/asterinas
diff --git /dev/null b/test/apps/pthread/pthread_signal_test.c new file mode 100644 --- /dev/null +++ b/test/apps/pthread/pthread_signal_test.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: MPL-2.0 +// A regression test for the futex lost wakeup bug fixed in https://github.com/asterinas/asterinas/pull/1642 + +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <signal.h> +#include <stdatomic.h> + +pthread_mutex_t mutex; +atomic_int sync_flag = ATOMIC_VAR_INIT(0); // Atomic flag for synchronization + +// Signal handler for SIGUSR1 +void signal_handler(int signum) +{ + atomic_store(&sync_flag, 2); +} + +// Thread function that tries to lock the mutex and waits if it is locked +void *thread_function(void *arg) +{ + printf("Thread: Trying to lock mutex...\n"); + + // Set the atomic flag to signal the main thread + atomic_store(&sync_flag, 1); + + // Try to lock the mutex + pthread_mutex_lock(&mutex); + printf("Thread: Got the mutex!\n"); + + printf("Thread: Exiting.\n"); + pthread_mutex_unlock(&mutex); + + // Set the atomic flag to signal the main thread + atomic_store(&sync_flag, 3); + return NULL; +} + +int main() +{ + pthread_t thread; + + // Initialize mutex + if (pthread_mutex_init(&mutex, NULL) != 0) { + perror("Mutex initialization failed"); + return -1; + } + + // Set up signal handler for SIGUSR1 + struct sigaction sa; + sa.sa_handler = signal_handler; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) == -1) { + perror("sigaction failed"); + return -1; + } + + // Main thread locks the mutex + pthread_mutex_lock(&mutex); + printf("Main thread: Mutex locked.\n"); + + // Create the second thread + if (pthread_create(&thread, NULL, thread_function, NULL) != 0) { + perror("Thread creation failed"); + return -1; + } + + // Detach the thread to allow it to run independently + if (pthread_detach(thread) != 0) { + perror("Thread detachment failed"); + return -1; + } + + // Wait for the second thread to prepare + while (atomic_load(&sync_flag) != 1) { + } + sleep(1); + + // Send signal to the second thread + pthread_kill(thread, SIGUSR1); + printf("Main thread: Signal sent to the thread.\n"); + + // Wait for the second thread to process signal + while (atomic_load(&sync_flag) != 2) { + } + sleep(1); + + // Unlock the mutex + pthread_mutex_unlock(&mutex); + printf("Main thread: Mutex unlocked.\n"); + + // Wait for the second thread to exit + int count = 3; + while (atomic_load(&sync_flag) != 3 && count--) { + sleep(1); + } + if (atomic_load(&sync_flag) != 3) { + printf("ERROR: Thread does not exit after timeout.\n"); + exit(EXIT_FAILURE); + } + + // Destroy mutex + pthread_mutex_destroy(&mutex); + + printf("All tests passed.\n"); + return 0; +}
[ "1587" ]
0.9
9da6af03943c15456cdfd781021820a7da78ea40
`futex_wait_bitset()` should remove `futex_item` when `pause_timeout()` fails ### Describe the bug 1. When signaled or timeout, the `futex_item` is not removed from the `futex_bucket`, which can lead to lost-wakeup. 2. `waiter.pause_timeout()` returns `Ok(())` upon waking up from a signal, which can lead to incorrect handling of the wake-up event. https://github.com/asterinas/asterinas/blob/11382524d1d23cc6d41adf977a72138baa39e38d/kernel/src/process/posix_thread/futex.rs#L76
asterinas__asterinas-1642
1,642
diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs --- a/kernel/src/process/posix_thread/futex.rs +++ b/kernel/src/process/posix_thread/futex.rs @@ -253,7 +253,9 @@ impl FutexBucket { } let item = item_cursor.remove().unwrap(); - item.wake(); + if !item.wake() { + continue; + } count += 1; } diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs --- a/kernel/src/process/posix_thread/futex.rs +++ b/kernel/src/process/posix_thread/futex.rs @@ -253,7 +253,9 @@ impl FutexBucket { } let item = item_cursor.remove().unwrap(); - item.wake(); + if !item.wake() { + continue; + } count += 1; } diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs --- a/kernel/src/process/posix_thread/futex.rs +++ b/kernel/src/process/posix_thread/futex.rs @@ -323,8 +325,9 @@ impl FutexItem { (futex_item, waiter) } - pub fn wake(&self) { - self.waker.wake_up(); + #[must_use] + pub fn wake(&self) -> bool { + self.waker.wake_up() } pub fn match_up(&self, another: &Self) -> bool { diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs --- a/kernel/src/process/posix_thread/futex.rs +++ b/kernel/src/process/posix_thread/futex.rs @@ -323,8 +325,9 @@ impl FutexItem { (futex_item, waiter) } - pub fn wake(&self) { - self.waker.wake_up(); + #[must_use] + pub fn wake(&self) -> bool { + self.waker.wake_up() } pub fn match_up(&self, another: &Self) -> bool { diff --git /dev/null b/test/apps/pthread/pthread_signal_test.c new file mode 100644 --- /dev/null +++ b/test/apps/pthread/pthread_signal_test.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: MPL-2.0 +// A regression test for the futex lost wakeup bug fixed in https://github.com/asterinas/asterinas/pull/1642 + +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <signal.h> +#include <stdatomic.h> + +pthread_mutex_t mutex; +atomic_int sync_flag = ATOMIC_VAR_INIT(0); // Atomic flag for synchronization + +// Signal handler for SIGUSR1 +void signal_handler(int signum) +{ + atomic_store(&sync_flag, 2); +} + +// Thread function that tries to lock the mutex and waits if it is locked +void *thread_function(void *arg) +{ + printf("Thread: Trying to lock mutex...\n"); + + // Set the atomic flag to signal the main thread + atomic_store(&sync_flag, 1); + + // Try to lock the mutex + pthread_mutex_lock(&mutex); + printf("Thread: Got the mutex!\n"); + + printf("Thread: Exiting.\n"); + pthread_mutex_unlock(&mutex); + + // Set the atomic flag to signal the main thread + atomic_store(&sync_flag, 3); + return NULL; +} + +int main() +{ + pthread_t thread; + + // Initialize mutex + if (pthread_mutex_init(&mutex, NULL) != 0) { + perror("Mutex initialization failed"); + return -1; + } + + // Set up signal handler for SIGUSR1 + struct sigaction sa; + sa.sa_handler = signal_handler; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) == -1) { + perror("sigaction failed"); + return -1; + } + + // Main thread locks the mutex + pthread_mutex_lock(&mutex); + printf("Main thread: Mutex locked.\n"); + + // Create the second thread + if (pthread_create(&thread, NULL, thread_function, NULL) != 0) { + perror("Thread creation failed"); + return -1; + } + + // Detach the thread to allow it to run independently + if (pthread_detach(thread) != 0) { + perror("Thread detachment failed"); + return -1; + } + + // Wait for the second thread to prepare + while (atomic_load(&sync_flag) != 1) { + } + sleep(1); + + // Send signal to the second thread + pthread_kill(thread, SIGUSR1); + printf("Main thread: Signal sent to the thread.\n"); + + // Wait for the second thread to process signal + while (atomic_load(&sync_flag) != 2) { + } + sleep(1); + + // Unlock the mutex + pthread_mutex_unlock(&mutex); + printf("Main thread: Mutex unlocked.\n"); + + // Wait for the second thread to exit + int count = 3; + while (atomic_load(&sync_flag) != 3 && count--) { + sleep(1); + } + if (atomic_load(&sync_flag) != 3) { + printf("ERROR: Thread does not exit after timeout.\n"); + exit(EXIT_FAILURE); + } + + // Destroy mutex + pthread_mutex_destroy(&mutex); + + printf("All tests passed.\n"); + return 0; +}
The [wakeup test](https://github.com/torvalds/linux/blob/2d5404caa8c7bb5c4e0435f94b28834ae5456623/kernel/futex/waitwake.c#L671-L673) must take precedence over the [pending signals test](https://github.com/torvalds/linux/blob/2d5404caa8c7bb5c4e0435f94b28834ae5456623/kernel/futex/waitwake.c#L678-L683). This is the real cause of the failed CI due to 6421fd0b36aafb3fcd9a8f12d5bc6e89f3f86546, cc https://github.com/asterinas/asterinas/pull/1577. I also wonder if we can remove the `pause_timeout` API and let the futex use the normal `pause_until` API, but I am not sure since I have not read the futex implementation. > can lead to lost-wakeup. This should only result in spurious wake?
2024-11-26T12:04:42Z
9da6af03943c15456cdfd781021820a7da78ea40
asterinas/asterinas
diff --git a/ostd/src/arch/x86/trap/trap.S b/ostd/src/arch/x86/trap/trap.S --- a/ostd/src/arch/x86/trap/trap.S +++ b/ostd/src/arch/x86/trap/trap.S @@ -57,6 +57,7 @@ trap_handler_table: .section .text .global trap_common trap_common: + cld # clear DF before calling/returning to any C function to conform to x86-64 calling convention push rax mov ax, [rsp + 4*8] # load cs and ax, 0x3 # test
[ "1606" ]
0.9
5f35189a51ebc54298ea2cb0e4d53afe4e4e75eb
Shift overflow in `CpuSet` (`bit_idx` out of range) ### Describe the bug A kernel panic is triggered due to a shift overflow. The `bit_idx` value is huge: `bit_idx=18446603338235158984`, which seems like an address (`0xffff8000780aa1c8`). https://github.com/asterinas/asterinas/blob/e6c613f53841983765a7b3c56ea9958775c76199/ostd/src/cpu/set.rs#L105 Other variable values: ```txt part_idx=18446603338241563904 part=18446603338235158976 bit_idx=18446603338235158984 BITS_PER_PART=64 ``` I cannot find where the `CpuSet` can be corrupted. I guess it might related to a stack issue, as `SmallVec` is stored on the stack. ### To Reproduce ``` for i in `seq 1000000`; do ./memset || (echo $i && break); done` ``` <details><summary>memset.c ( **dynamically linked** , staticly linked will trigger segv described in #1603) </summary> ```c #include <stdio.h> #include <unistd.h> #include <string.h> #include <assert.h> int main() { // Get the current program break address (end of the data segment) void *initial_brk = sbrk(0); //printf("Initial brk: %p\n", initial_brk); // Define the size of memory we want to allocate size_t allocation_size = 0xDC0; // 0x4dcdc0 - 0x4dc000 = 0xDC0 // Extend the program break by allocation_size bytes void *new_brk = sbrk(allocation_size); if (new_brk == (void *) -1) { perror("sbrk failed"); return 1; } //printf("New brk: %p\n", sbrk(0)); // Fill the allocated range with -1 (0xFF) memset(initial_brk, -1, allocation_size); // Verify the memory range is filled with -1 unsigned char *ptr = (unsigned char *)initial_brk; for (size_t i = 0; i < allocation_size; i++) { assert(ptr[i] == 0xFF); // -1 is represented as 0xFF in memory } //printf("Memory range successfully filled and verified.\n"); return 0; } ``` </details> ### Environment ac71234b8964a664111dbf038ba75f36e1b0d740 ### Logs <details><summary>gdb logs</summary> ```gdb #0 ostd::panic::print_stack_trace () at src/console.rs:25 #1 0xffffffff8804b9e9 in aster_nix::thread::oops::panic_handler (info=0xffffdffffe597850) at src/thread/oops.rs:124 #2 0xffffffff8804aa5a in aster_nix::thread::oops::__ostd_panic_handler (info=0xffffdffffe597850) at src/thread/oops.rs:82 #3 0xffffffff8804900a in aster_nix_osdk_bin::panic (info=0xffffdffffe597850) at src/main.rs:11 #4 0xffffffff889e3544 in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74 #5 0xffffffff889d342e in core::panicking::panic_const::panic_const_shl_overflow () at src/panicking.rs:181 #6 0xffffffff887b79e6 in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=18446603338235158984) at src/cpu/set.rs:105 #7 0xffffffff887b77ab in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdffffe5979a8, args=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294 #8 0xffffffff887aaab3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=18446603338235158984) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903 #9 0xffffffff887b3e71 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdffffe597db0, init=(), f=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406 --Type <RET> for more, q to quit, c to continue without paging-- #10 0xffffffff887b3dd2 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdffffe597db0, f=0xffffdffffe597dc0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909 #11 0xffffffff887b4271 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdffffe597db0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64 #12 0xffffffff888829b3 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #13 0xffffffff88890a3c in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdffffe597da8, f=0xdffffe597d20ffff) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838 #14 0xffffffff8889086c in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::enumerate::En--Type <RET> for more, q to quit, c to continue without paging-- umerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> (self=0xffffdffffe597da8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605 #15 0xffffffff8889084a in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdffffe597da8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64 #16 0xffffffff883de192 in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> (self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+185664>, entity=0xffffdffffe597f50) at src/sched/priority_scheduler.rs:69 #17 0xffffffff883de444 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task> ( self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+185664>, task=..., flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93 #18 0xffffffff88829b1a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159 #19 0xffffffff887a9e7c in ostd::sync::wait::Waker::wake_up (self=0xffff800078731e10) at src/sync/wait.rs:263 #20 0xffffffff882f2ee2 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closur--Type <RET> for more, q to quit, c to continue without paging-- e_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> () at src/time/wait.rs:163 #21 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000786c5b98, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #22 0xffffffff882d20e0 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff800078731600) at src/time/core/timer.rs:137 #23 0xffffffff883129ca in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89 #24 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff800078732de0, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #25 0xffffffff882d286a in aster_nix::time::core::timer::TimerManager::process_expired_timers ( self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+185936>) at src/time/core/timer.rs:206 #26 0xffffffff8839b392 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} () at src/time/clocks/system_wide.rs:273 #27 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89eb0 <ostd::mm::heap_allocator::init::HEAP_SPACE+212656>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 --Type <RET> for more, q to quit, c to continue without paging-- #28 0xffffffff8815ba95 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31 #29 0xffffffff8832cf1e in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #30 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d55650 <aster_softirq::LINES+32>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #31 0xffffffff886418bc in aster_softirq::process_pending () at src/lib.rs:165 #32 0xffffffff8863cc5e in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #33 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d55930 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #34 0xffffffff887ae899 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42 #35 0xffffffff887ae90c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdffffe598a40, irq_number=33) at src/trap/handler.rs:56 #36 0xffffffff88834b8b in ostd::arch::x86::trap::trap_handler (f=0xffffdffffe598a40) at src/arch/x86/trap/mod.rs:251 #37 0xffffffff8882c232 in __from_kernel () #38 0x0000000000000000 in ?? () ``` </details> cpu_affinity (frame 16): ``` (gdb) p (*entity.thread.ptr.pointer).data.cpu_affinity $8 = ostd::cpu::set::AtomicCpuSet {bits: smallvec::SmallVec<[core::sync::atomic::AtomicU64; 2]> {capacity: 1, data: smallvec::SmallVecData<[core::sync::atomic::AtomicU64; 2]>::Inline(core::mem::maybe_uninit::MaybeUninit<[core::sync::atomic::AtomicU64; 2]> {uninit: (), value: core::mem::manually_drop::ManuallyDrop<[core::sync::atomic::AtomicU64; 2]> {value: [ core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 1}}, core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 18446708889337447720}}]}})}} ```
asterinas__asterinas-1637
1,637
diff --git a/ostd/src/arch/x86/trap/trap.S b/ostd/src/arch/x86/trap/trap.S --- a/ostd/src/arch/x86/trap/trap.S +++ b/ostd/src/arch/x86/trap/trap.S @@ -57,6 +57,7 @@ trap_handler_table: .section .text .global trap_common trap_common: + cld # clear DF before calling/returning to any C function to conform to x86-64 calling convention push rax mov ax, [rsp + 4*8] # load cs and ax, 0x3 # test
I did some debugging. It seems that using stack data in IRQs (like `SmallVec` in this case) might not be safe. Below is a summary of my findings to assist with further debugging. ### Create a test case to reproduce the bug reliably Test case: `test/apps/dynamic/execve.c` <details> ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[], char *environ[]) { int number = 0; // If there is an argument, parse it as a number. if (argc > 1) { number = atoi(argv[1]); // Convert argument to integer. } // Print the current number. printf("%d\n", number); // Increment the number. number++; // Prepare arguments for execve. char new_number[16]; snprintf(new_number, sizeof(new_number), "%d", number); // Convert number to string. char *new_argv[] = {argv[0], new_number, NULL}; // New argument list. // Re-execute the program with the new arguments. if (execve(argv[0], new_argv, environ) == -1) { perror("execve failed"); exit(EXIT_FAILURE); } return 0; // This line should never be reached if execve is successful. } ``` </details> Makefile: `test/apps/dynamic/Makefile` <details> ``` include ../test_common.mk EXTRA_C_FLAGS := ``` </details> ### Stop at panic Run gdb server and client: ```sh make gdb_server make gdb_client # in another tmux pane ``` Set a breakpoint and continue in gdb: ``` b panic_const_shl_overflow c ``` Run the testcase in qemu: ``` /test/dynamic/execve ``` Panic is likely to occur between 7000 and 10000 rounds (in my environment). ### Show backtraces Show current backtrace: ``` bt ``` <details> ``` #0 core::panicking::panic_const::panic_const_shl_overflow () at src/panicking.rs:181 #1 0xffffffff88861456 in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=18446603338107140168) at src/cpu/set.rs:105 #2 0xffffffff8886122b in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7d8d8, args=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294 #3 0xffffffff8888f5d3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=18446603338107140168) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903 #4 0xffffffff8887b3a1 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdfffffd7dce0, init=(), f=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406 #5 0xffffffff8887b302 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7dce0, f=0xffffdfffffd7dcf0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909 #6 0xffffffff8886a931 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7dce0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64 #7 0xffffffff8887e673 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #8 0xffffffff8887771c in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdfffffd7dcd8, f=0xdfffffd7dc50ffff) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838 #9 0xffffffff8887754c in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> ( self=0xffffdfffffd7dcd8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605 #10 0xffffffff8887752a in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdfffffd7dcd8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64 #11 0xffffffff8826cc12 in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> ( self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+492864>, entity=0xffffdfffffd7de80) at src/sched/priority_scheduler.rs:69 #12 0xffffffff8826cec4 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task> (self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+492864>, task=..., flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93 #13 0xffffffff88861b8a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159 #14 0xffffffff88846c3c in ostd::sync::wait::Waker::wake_up (self=0xffff8000706f3790) at src/sync/wait.rs:263 #15 0xffffffff88153612 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> () at src/time/wait.rs:163 #16 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706c1e18, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #17 0xffffffff880b5720 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff8000706f3880) at src/time/core/timer.rs:137 #18 0xffffffff8827ef2a in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89 #19 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706f2260, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #20 0xffffffff880b5eaa in aster_nix::time::core::timer::TimerManager::process_expired_timers ( self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+493136>) at src/time/core/timer.rs:206 #21 0xffffffff882eaa82 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} () at src/time/clocks/system_wide.rs:273 #22 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89eb0 <ostd::mm::heap_allocator::init::HEAP_SPACE+519856>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #23 0xffffffff88163515 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31 #24 0xffffffff8836578e in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #25 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d09650 <aster_softirq::LINES+32>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #26 0xffffffff88607d1c in aster_softirq::process_pending () at src/lib.rs:165 #27 0xffffffff8860558e in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #28 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d09970 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #29 0xffffffff887996e9 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42 #30 0xffffffff8879975c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdfffffd7e970, irq_number=33) at src/trap/handler.rs:56 #31 0xffffffff887c86ab in ostd::arch::x86::trap::trap_handler (f=0xffffdfffffd7e970) at src/arch/x86/trap/mod.rs:251 #32 0xffffffff88838e66 in __from_kernel () #33 0x0000000000000000 in ?? () ``` </details> In the backtrace, we can see the trap originates from `0xffffffff88838e66` in `__from_kernel ()` (frame `32`). Specifically, the address `0xffffffff88838e66` is the start address of `trap_return`. Go back to frame `32` and show registers: ``` frame 32 info reg ``` <details> ``` rax 0xffff8000706c1f00 -140735602221312 rbx 0x0 0 rcx 0x1 1 rdx 0xffff800070693848 -140735602411448 rsi 0xffff800070693848 -140735602411448 rdi 0xffffffff88a560a0 -2002427744 rbp 0x0 0x0 rsp 0xffffdfffffd7e970 0xffffdfffffd7e970 r8 0x0 0 r9 0x1000 4096 r10 0x1bd000 1822720 r11 0xffffdfffffd998a8 -35184374605656 r12 0x0 0 r13 0x0 0 r14 0x0 0 r15 0x0 0 rip 0xffffffff88838e66 0xffffffff88838e66 <trap_return> eflags 0x200486 [ ID IOPL=0 DF SF PF ] cs 0x8 8 ss 0x38 56 ds 0x0 0 es 0x0 0 fs 0x0 0 gs 0x0 0 fs_base 0x7ffffff07780 140737487337344 gs_base 0xffffffff88d08000 -1999601664 k_gs_base 0x0 0 cr0 0x80010033 [ PG WP NE ET MP PE ] cr2 0x7ffffff04fdc 140737487327196 cr3 0x7cf59000 [ PDBR=511833 PCID=0 ] cr4 0x506e8 [ OSXSAVE FSGSBASE OSXMMEXCPT OSFXSR PGE MCE PAE DE ] cr8 0x0 0 efer 0xd01 [ NXE LMA LME SCE ] --- fpu regs ignored --- ``` </details> Discard all stack frames from this trap and return to `trap_return`: ``` frame 0 set $rsp=0xffffdfffffd7e970 set $rip=0xffffffff88838e66 b *$rip b *$rip+1 ``` Step to the `iret` instruction: ``` si # Press `Enter` repeatedly to step until reaching the `iret` instruction ``` Show the stack to find the return address: ``` x/20gx $rsp ``` <details> ``` 0xffffdfffffd7d900: 0x0000000000000000 0x0000000000000021 0xffffdfffffd7d910: 0x0000000000000000 **0xffffffff889c725e** 0xffffdfffffd7d920: 0x0000000000000030 0x0000000000210682 0xffffdfffffd7d930: 0xffffdfffffd7d940 0x0000000000000038 0xffffdfffffd7d940: 0x0000000000000038 0x0100000000000002 0xffffdfffffd7d950: 0xffff8000706a4047 0x000000000000002f 0xffffdfffffd7d960: 0x0100000000000007 0x0000000000000000 0xffffdfffffd7d970: 0x0000000000000006 0x0000000000000000 0xffffdfffffd7d980: 0x000000000000002f 0x0000000000000030 0xffffdfffffd7d990: 0xffff8000706a4010 0xffff8000706a4018 ``` </details> Set a breakpoint at the return address: ``` b *0xffffffff889c725e # Output: Breakpoint 3 at 0xffffffff889c725e: file src/mem/x86_64.rs, line 68. ``` Step to the original trap address: ``` si ``` Show the backtrace and registers: ``` bt ``` <details> ``` #0 0xffffffff889c7253 in compiler_builtins::mem::impls::copy_backward (dest=0xffff8000706a4020, src=0xffff8000706a4018, count=56) at src/mem/x86_64.rs:68 #1 compiler_builtins::mem::memmove (dest=0xffff8000706a4020, src=0xffff8000706a4018, n=56) at src/mem/mod.rs:37 #2 0xffffffff889ca0f7 in compiler_builtins::mem::memmove::memmove (dest=0xffff8000706a4020, src=0xffff8000706a4018, n=56) at src/macros.rs:480 #3 0xffffffff887d465c in core::intrinsics::copy<core::mem::maybe_uninit::MaybeUninit<usize>> (src=0xffff8000706a4018, dst=0xffff8000706a4020, count=7) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/intrinsics.rs:3419 #4 alloc::collections::btree::node::slice_insert<usize> (slice=..., idx=2, val=1888256) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1791 #5 0xffffffff884acab6 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_fit<usize, aster_nix::vm::vmar::vm_mapping::VmMapping> (self=..., key=1888256, val=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:919 #6 0xffffffff884bf1ff in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global> (self=..., key=1888256, val=..., alloc=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:945 #7 0xffffffff884b64f7 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_recursing<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global, alloc::collections::btree::map::entry::{impl#8}::insert::{closure_env#0}<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>> (self=..., key=1888256, value=..., alloc=..., split_root=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1046 #8 0xffffffff88292b65 in alloc::collections::btree::map::entry::VacantEntry<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global> (self=..., value=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map/entry.rs:364 #9 0xffffffff8825a89d in alloc::collections::btree::map::BTreeMap<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global> (self=0xffff8000706c01d0, key=1888256, value=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map.rs:993 #10 0xffffffff881c9ab2 in aster_nix::vm::vmar::interval_set::IntervalSet<usize, aster_nix::vm::vmar::vm_mapping::VmMapping>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping> (self=0xffff8000706c01d0, item=...) at src/vm/vmar/interval_set.rs:55 #11 0xffffffff88418a44 in aster_nix::vm::vmar::Vmar_::add_mapping (self=0xffff8000706c0190, mapping=...) at src/vm/vmar/mod.rs:387 #12 0xffffffff8840f92f in aster_nix::vm::vmar::vm_mapping::VmarMapOptions<aster_rights::TRightSet<typeflags_util::set::Cons<aster_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>, aster_rights::Rights>::build<aster_rights::TRightSet<typeflags_util::set::Cons<aster_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>, aster_rights::Rights> (self=...) at src/vm/vmar/vm_mapping.rs:575 #13 0xffffffff882d06b3 in aster_nix::syscall::mmap::do_sys_mmap (addr=1888256, len=360448, vm_perms=..., option=..., fd=3, offset=1822720, ctx=0xffffdfffffd998a8) at src/syscall/mmap.rs:155 #14 0xffffffff882cf051 in aster_nix::syscall::mmap::sys_mmap (addr=1888256, len=360448, perms=1, flags=2066, fd=3, offset=1822720, ctx=0xffffdfffffd998a8) at src/syscall/mmap.rs:29 #15 0xffffffff88187633 in aster_nix::syscall::arch::x86::syscall_dispatch (syscall_number=9, args=..., ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0) at src/syscall/mod.rs:221 #16 0xffffffff8818196e in aster_nix::syscall::handle_syscall (ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0) at src/syscall/mod.rs:322 #17 0xffffffff8830c3dc in aster_nix::thread::task::create_new_user_task::user_task_entry () at src/thread/task.rs:70 #18 0xffffffff88368346 in core::ops::function::FnOnce::call_once<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #19 0xffffffff8814f0c7 in unwinding::panicking::catch_unwind::do_call<fn(), ()> (data=0xffffdfffffd99c50) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:54 #20 0xffffffff8814ff68 in __rust_try () #21 0xffffffff8814efbf in unwinding::panicking::catch_unwind<unwinding::panic::RustPanic, (), fn()> (f=0xffdfffffd99c5020) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:42 #22 0xffffffff8840e022 in unwinding::panic::catch_unwind<(), fn()> (f=0xffffff885ffc5600) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panic.rs:87 #23 0xffffffff885ffc56 in aster_nix::thread::oops::catch_panics_as_oops<fn(), ()> (f=0x100) at src/thread/oops.rs:54 #24 0xffffffff88083d1c in aster_nix::thread::task::create_new_user_task::{closure#0} () at src/thread/task.rs:95 #25 0xffffffff8836664e in core::ops::function::FnOnce::call_once<aster_nix::thread::task::create_new_user_task::{closure_env#0}, ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #26 0xffffffff888651e8 in alloc::boxed::{impl#48}::call_once<(), (dyn core::ops::function::FnOnce<(), Output=()> + core::marker::Send), alloc::alloc::Global> (self=..., args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2454 #27 0xffffffff88835a87 in ostd::task::{impl#1}::build::kernel_task_entry () at src/task/mod.rs:175 #28 0x00000a000d004e00 in ?? () ``` </details> ``` info reg ``` <details> ``` rax 0x0 0 rbx 0x0 0 rcx 0x0 0 rdx 0x7 7 rsi 0xffff8000706a404f -140735602343857 rdi 0xffff8000706a4057 -140735602343849 rbp 0x0 0x0 rsp 0xffffdfffffd7ea30 0xffffdfffffd7ea30 r8 0x37 55 r9 0x1000 4096 r10 0x1bd000 1822720 r11 0xffffdfffffd998a8 -35184374605656 r12 0x0 0 r13 0x0 0 r14 0x0 0 r15 0x0 0 rip 0xffffffff889c7253 0xffffffff889c7253 <compiler_builtins::mem::memmove+451> eflags 0x200682 [ ID IOPL=0 DF IF SF ] cs 0x30 48 ss 0x38 56 ds 0x0 0 es 0x0 0 fs 0x0 0 --Type <RET> for more, q to quit, c to continue without paging-- gs 0x0 0 fs_base 0x7ffffff07780 140737487337344 gs_base 0xffffffff88d08000 -1999601664 k_gs_base 0x0 0 cr0 0x80010033 [ PG WP NE ET MP PE ] cr2 0x7ffffff04fdc 140737487327196 cr3 0x7cf59000 [ PDBR=511833 PCID=0 ] cr4 0x506e8 [ OSXSAVE FSGSBASE OSXMMEXCPT OSFXSR PGE MCE PAE DE ] cr8 0x0 0 efer 0xd01 [ NXE LMA LME SCE ] --- fpu regs ignored --- ``` </details> From the backtrace, we can see that execution is in the middle of `memmove`, indicating that the data might not have been completely moved. I have tested it twice, and both backtraces were the same. It makes me doubtful about `SmallVec` implementation. Maybe try a fixed array like `[u64; 4]` and see if it reproduces? The bug still exists. Here is my patch: <details> ```diff diff --git a/ostd/src/cpu/set.rs b/ostd/src/cpu/set.rs index dc751090..86f9236b 100644 --- a/ostd/src/cpu/set.rs +++ b/ostd/src/cpu/set.rs @@ -4,7 +4,7 @@ use core::sync::atomic::{AtomicU64, Ordering}; -use smallvec::SmallVec; +// use smallvec::SmallVec; use static_assertions::const_assert_eq; use super::{num_cpus, CpuId}; @@ -13,13 +13,13 @@ use super::{num_cpus, CpuId}; #[derive(Clone, Debug, Default)] pub struct CpuSet { // A bitset representing the CPUs in the system. - bits: SmallVec<[InnerPart; NR_PARTS_NO_ALLOC]>, + bits: [u64; 4], } type InnerPart = u64; const BITS_PER_PART: usize = core::mem::size_of::<InnerPart>() * 8; -const NR_PARTS_NO_ALLOC: usize = 2; +// const NR_PARTS_NO_ALLOC: usize = 2; const fn part_idx(cpu_id: CpuId) -> usize { cpu_id.as_usize() / BITS_PER_PART @@ -51,7 +51,8 @@ impl CpuSet { let part_idx = part_idx(cpu_id); let bit_idx = bit_idx(cpu_id); if part_idx >= self.bits.len() { - self.bits.resize(part_idx + 1, 0); + panic!("cannot resize"); + // self.bits.resize(part_idx + 1, 0); } self.bits[part_idx] |= 1 << bit_idx; } @@ -115,8 +116,13 @@ impl CpuSet { /// Only for internal use. The set cannot contain non-existent CPUs. fn with_capacity_val(num_cpus: usize, val: InnerPart) -> Self { let num_parts = parts_for_cpus(num_cpus); - let mut bits = SmallVec::with_capacity(num_parts); - bits.resize(num_parts, val); + if num_parts > 4 { + panic!("should not bigger than 4"); + } + let mut bits = [0; 4]; + for i in 0..num_parts { + bits[i] = val; + } Self { bits } } @@ -143,16 +149,43 @@ impl From<CpuId> for CpuSet { /// operation contains multiple CPUs, the ordering is not guaranteed. #[derive(Debug)] pub struct AtomicCpuSet { - bits: SmallVec<[AtomicInnerPart; NR_PARTS_NO_ALLOC]>, + bits: [AtomicInnerPart; 4], } type AtomicInnerPart = AtomicU64; const_assert_eq!(core::mem::size_of::<AtomicInnerPart>() * 8, BITS_PER_PART); +impl From<CpuSet> for AtomicCpuSet { + fn from(cpu_set: CpuSet) -> Self { + // Map each `u64` in `cpu_set.bits` to an `AtomicInnerPart` + let atomic_bits: [AtomicInnerPart; 4] = [ + AtomicInnerPart::new(0), + AtomicInnerPart::new(0), + AtomicInnerPart::new(0), + AtomicInnerPart::new(0), + ]; + + for (i, &bit) in cpu_set.bits.iter().enumerate() { + atomic_bits[i].store(bit, Ordering::SeqCst); + } + + AtomicCpuSet { bits: atomic_bits } + } +} + +fn atomic_array_to_u64_array(array: &[AtomicU64; 4]) -> [u64; 4] { + [ + array[0].load(Ordering::SeqCst), + array[1].load(Ordering::SeqCst), + array[2].load(Ordering::SeqCst), + array[3].load(Ordering::SeqCst), + ] +} + impl AtomicCpuSet { /// Creates a new `AtomicCpuSet` with an initial value. pub fn new(value: CpuSet) -> Self { - let bits = value.bits.into_iter().map(AtomicU64::new).collect(); + let bits = AtomicCpuSet::from(value).bits; Self { bits } } @@ -161,11 +194,7 @@ impl AtomicCpuSet { /// This operation can only be done in the [`Ordering::Relaxed`] memory /// order. It cannot be used to synchronize anything between CPUs. pub fn load(&self) -> CpuSet { - let bits = self - .bits - .iter() - .map(|part| part.load(Ordering::Relaxed)) - .collect(); + let bits = atomic_array_to_u64_array(&self.bits); CpuSet { bits } } ``` </details> The backtrace: <details> ``` #0 ostd::panic::print_stack_trace () at src/panic.rs:62 #1 0xffffffff88291c99 in aster_nix::thread::oops::panic_handler (info=0xffffdfffffd7b8a0) at src/thread/oops.rs:124 #2 0xffffffff88290d0a in aster_nix::thread::oops::__ostd_panic_handler (info=0xffffdfffffd7b8a0) at src/thread/oops.rs:82 #3 0xffffffff8804900a in aster_nix_osdk_bin::panic (info=0xffffdfffffd7b8a0) at src/main.rs:11 #4 0xffffffff889a2934 in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74 #5 0xffffffff8899281e in core::panicking::panic_const::panic_const_shl_overflow () at src/panicking.rs:181 #6 0xffffffff887a3326 in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=18446603338107140168) at src/cpu/set.rs:106 #7 0xffffffff887a30fb in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7b9f8, args=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294 #8 0xffffffff888891c3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=18446603338107140168) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903 #9 0xffffffff88876e91 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdfffffd7be00, init=(), f=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406 #10 0xffffffff88876df2 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7be00, f=0xffffdfffffd7be10) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909 #11 0xffffffff88867341 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7be00) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64 #12 0xffffffff8887a943 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #13 0xffffffff888738bc in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdfffffd7bdf8, f=0xdfffffd7bd70ffff) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838 #14 0xffffffff888736ec in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::e--Type <RET> for more, q to quit, c to continue without paging-- numerate::Enumerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> ( self=0xffffdfffffd7bdf8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605 #15 0xffffffff888736ca in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdfffffd7bdf8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64 #16 0xffffffff882f367a in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> ( self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+517440>, entity=0xffffdfffffd7bfa0) at src/sched/priority_scheduler.rs:69 #17 0xffffffff882f3924 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task> (self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+517440>, task=..., flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93 #18 0xffffffff8885de1a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159 #19 0xffffffff88844c6c in ostd::sync::wait::Waker::wake_up (self=0xffff8000706e7410) at src/sync/wait.rs:263 #20 0xffffffff8812b072 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> () at src/time/wait.rs:163 #21 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706c1e18, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #22 0xffffffff88269f20 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff8000706e76c0) at src/time/core/timer.rs:137 #23 0xffffffff88267eda in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89 #24 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706e74e0, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #25 0xffffffff8826a6aa in aster_nix::time::core::timer::TimerManager::process_expired_timers ( self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+517712>) at src/time/core/timer.rs:206 #26 0xffffffff885d7ed2 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} () at src/time/clocks/system_wide.rs:273 #27 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89eb0 <ostd::mm::heap_allocator::init::HEAP_SPACE+544432>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #28 0xffffffff882bdc25 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31 #29 0xffffffff88355cfe in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #30 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d02650 <aster_softirq::LINES+32>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #31 0xffffffff88607a6c in aster_softirq::process_pending () at src/lib.rs:165 #32 0xffffffff886052de in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #33 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d029a0 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #34 0xffffffff88799109 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42 #35 0xffffffff8879917c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdfffffd7ca90, irq_number=33) at src/trap/handler.rs:56 #36 0xffffffff887c82db in ostd::arch::x86::trap::trap_handler (f=0xffffdfffffd7ca90) at src/arch/x86/trap/mod.rs:251 #37 0xffffffff888a6c6e in __from_kernel () #38 0x0000000000000000 in ?? () ``` </details> `cpu_affinity` in frame `16` ``` (gdb) p (*entity.thread.ptr.pointer).data.cpu_affinity $1 = ostd::cpu::set::AtomicCpuSet {bits: [core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 1}}, core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 0}}, core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 0}}, core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 0}}]} ``` Backtrace before the trap: <details> ``` #0 0xffffffff889c17bf in compiler_builtins::mem::impls::copy_backward (dest=0xffff8000706e3818, src=0xffff8000706e3810, count=16) at src/mem/x86_64.rs:68 #1 compiler_builtins::mem::memmove (dest=0xffff8000706e3818, src=0xffff8000706e3810, n=16) at src/mem/mod.rs:37 #2 0xffffffff889c4647 in compiler_builtins::mem::memmove::memmove (dest=0xffff8000706e3818, src=0xffff8000706e3810, n=16) at src/macros.rs:480 #3 0xffffffff88453f7c in core::intrinsics::copy<core::mem::maybe_uninit::MaybeUninit<u64>> (src=0xffff8000706e3810, dst=0xffff8000706e3818, count=2) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/intrinsics.rs:3419 #4 alloc::collections::btree::node::slice_insert<u64> (slice=..., idx=1, val=56) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1791 #5 0xffffffff8849e157 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_fit<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64> (self=..., key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, val=56) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:920 #6 0xffffffff884b228b in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global> (self=..., key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, val=56, alloc=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:945 #7 0xffffffff884a4ff0 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_recursing<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global, alloc::collections::btree::map::entry::{impl#8}::insert::{closure_env#0}<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global>> (self=..., key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, value=56, alloc=..., split_root=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1046 #8 0xffffffff88277e1c in alloc::collections::btree::map::entry::VacantEntry<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global>::insert<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global> (self=..., value=56) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map/entry.rs:364 #9 0xffffffff8827454d in alloc::collections::btree::map::entry::Entry<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global>::or_insert<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global> (self=..., default=56) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map/entry.rs:163 #10 0xffffffff885d3dc1 in aster_nix::process::process_vm::init_stack::aux_vec::AuxVec::set (self=0xffffdfffffd7d6f0, key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, val=56) at src/process/process_vm/init_stack/aux_vec.rs:77 #11 0xffffffff8810f07c in aster_nix::process::program_loader::elf::load_elf::init_aux_vec (elf=0xffffdfffffd7de98, elf_map_addr=335790080, ldso_base=...) at src/process/program_loader/elf/load_elf.rs:394 #12 0xffffffff8810bc4b in aster_nix::process::program_loader::elf::load_elf::init_and_map_vmos ( process_vm=0xffff8000706a3810, ldso=..., parsed_elf=0xffffdfffffd7de98, elf_file=0xffffdfffffd7de88) at src/process/program_loader/elf/load_elf.rs:134 #13 0xffffffff8810a6ec in aster_nix::process::program_loader::elf::load_elf::load_elf_to_vm (process_vm=0xffff8000706a3810, file_header=..., elf_file=..., fs_resolver=0xffff8000706c00c8, argv=..., envp=...) at src/process/program_loader/elf/load_elf.rs:46 #14 0xffffffff881f6f76 in aster_nix::process::program_loader::load_program_to_vm (process_vm=0xffff8000706a3810, elf_file=..., argv=..., envp=..., fs_resolver=0xffff8000706c00c8, recursion_limit=1) at src/process/program_loader/mod.rs:66 #15 0xffffffff881e5b76 in aster_nix::syscall::execve::do_execve (elf_file=..., argv_ptr_ptr=140737487793456, envp_ptr_ptr=140737487793824, ctx=0xffffdfffffd998a8, user_context=0xffffdfffffd993d0) at src/syscall/execve.rs:117 #16 0xffffffff881e3fe3 in aster_nix::syscall::execve::sys_execve (filename_ptr=140737487794071, argv_ptr_ptr=140737487793456, envp_ptr_ptr=140737487793824, ctx=0xffffdfffffd998a8, user_context=0xffffdfffffd993d0) at src/syscall/execve.rs:33 #17 0xffffffff881b1879 in aster_nix::syscall::arch::x86::syscall_dispatch (syscall_number=59, args=..., ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0) at src/syscall/mod.rs:175 #18 0xffffffff880bda9e in aster_nix::syscall::handle_syscall (ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0) at src/syscall/mod.rs:322 #19 0xffffffff8819456c in aster_nix::thread::task::create_new_user_task::user_task_entry () at src/thread/task.rs:70 #20 0xffffffff883588d6 in core::ops::function::FnOnce::call_once<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #21 0xffffffff880db0e7 in unwinding::panicking::catch_unwind::do_call<fn(), ()> (data=0xffffdfffffd99c50) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:54 #22 0xffffffff880db508 in __rust_try () #23 0xffffffff880dafdf in unwinding::panicking::catch_unwind<unwinding::panic::RustPanic, (), fn()> (f=0xffdfffffd99c5000) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:42 #24 0xffffffff882fe622 in unwinding::panic::catch_unwind<(), fn()> (f=0xffffff880c3a262c) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panic.rs:87 #25 0xffffffff880c3a26 in aster_nix::thread::oops::catch_panics_as_oops<fn(), ()> (f=0x100) at src/thread/oops.rs:54 #26 0xffffffff8814a55c in aster_nix::thread::task::create_new_user_task::{closure#0} () at src/thread/task.rs:95 #27 0xffffffff88356bbe in core::ops::function::FnOnce::call_once<aster_nix::thread::task::create_new_user_task::{closure_env#0}, ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #28 0xffffffff88861478 in alloc::boxed::{impl#48}::call_once<(), (dyn core::ops::function::FnOnce<(), Output=()> + core::marker::Send), alloc::alloc::Global> (self=..., args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2454 #29 0xffffffff888370f7 in ostd::task::{impl#1}::build::kernel_task_entry () at src/task/mod.rs:175 #30 0x2000650068007400 in ?? () ``` </details> > The bug still exists. Here is my patch: Seems proper. So I don't have a clue for now. Since you have mentioned nested traps in a comment of #1611 , I am wondering if the red zone of the current stack was corrupted by the nested trap. Try recompile Asterinas with [`no-redzone=true`](https://doc.rust-lang.org/rustc/codegen-options/index.html#no-redzone) and see if the problem disappears. --- Edit: Check out the cargo flags in [the OSDK source code](https://github.com/asterinas/asterinas/blob/f1aae232341bda78aa7bf1906e3d00df160962a8/osdk/src/commands/build/mod.rs#L205). The `no-redzone` option is not specified. According to the rustc book, when unspecified, whether the option is enabled by default is determined by the target. Our target for x86 is `x86_64-unknown-none`. > On x86_64-unknown-none, extern "C" uses the [standard System V calling convention](https://gitlab.com/x86-psABIs/x86-64-ABI), without red zones. So it looks like that only extern "C" functions have no red zones, but normal Rust functions have. And I don't think our assembly code in `trap.s` or other trap-related code skips the red zones. So nested traps will corrupt red zones. @cqs21 What is your judgement on this issue? You are more familiar with the trap and system call handling code. > I am wondering if the red zone of the current stack was corrupted by the nested trap. @tatetian Indeed, the CPU and the exception handler overwrite the data in the red zone, and we cannot avoid this in `trap.S`, since the hardware automatically pushes registers and error code onto the stack. The bug still occurs (the error slightly changed from `panic_const_shl_overflow` to `panic_const_mul_overflow`). ``` (gdb) p/x part_idx $2 = 0xffffffff8841661f ``` https://github.com/asterinas/asterinas/blob/f1aae232341bda78aa7bf1906e3d00df160962a8/ostd/src/cpu/set.rs#L106 Below is my patch: ``` diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs index 042a2bd2..6b15d9ef 100644 --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -178,6 +178,8 @@ fn install_setup_with_arch( let target_feature_args = match arch { SetupInstallArch::X86_64 => { concat!( + "-Cno-redzone=y", + "-Ccode-model=kernel", "-Ctarget-feature=", "+crt-static", ",-adx", ``` <details> ``` #0 ostd::panic::print_stack_trace () at src/panic.rs:62 #1 0xffffffff881baec9 in aster_nix::thread::oops::panic_handler (info=0xffffdfffffd7dd80) at src/thread/oops.rs:124 #2 0xffffffff881b9f3a in aster_nix::thread::oops::__ostd_panic_handler (info=0xffffdfffffd7dd80) at src/thread/oops.rs:82 #3 0xffffffff8804900a in aster_nix_osdk_bin::panic (info=0xffffdfffffd7dd80) at src/main.rs:11 #4 0xffffffff889a88c4 in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74 #5 0xffffffff889986be in core::panicking::panic_const::panic_const_mul_overflow () at src/panicking.rs:181 #6 0xffffffff8878259e in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=0) at src/cpu/set.rs:106 #7 0xffffffff8878223b in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7ded8, args=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294 #8 0xffffffff887e27a3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903 #9 0xffffffff88823361 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdfffffd7e2e0, init=(), f=...) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406 #10 0xffffffff888232c2 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7e2e0, f=0xffffdfffffd7e2f0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909 #11 0xffffffff8878f241 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7e2e0) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64 #12 0xffffffff887f41c3 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250 #13 0xffffffff8880fd8c in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdfffffd7e2d8, f=0xdfffffd7e250ffff) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838 #14 0xffffffff8880fbbc in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> (self=0xffffdfffffd7e2d8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605 #15 0xffffffff8880fb9a in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdfffffd7e2d8) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64 #16 0xffffffff88415062 in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> (self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+488768>, entity=0xffffdfffffd7e480) at src/sched/priority_scheduler.rs:69 #17 0xffffffff88415314 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task> ( self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+488768>, task=..., flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93 #18 0xffffffff88770f6a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159 #19 0xffffffff887c2c5c in ostd::sync::wait::Waker::wake_up (self=0xffff8000706f3a50) at src/sync/wait.rs:263 #20 0xffffffff88103982 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> () at src/time/wait.rs:163 #21 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff800070687f98, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #22 0xffffffff882d9c20 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff8000706f2600) at src/time/core/timer.rs:137 #23 0xffffffff880f77da in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89 #24 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706f39e0, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #25 0xffffffff882da3aa in aster_nix::time::core::timer::TimerManager::process_expired_timers ( self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+489040>) at src/time/core/timer.rs:206 #26 0xffffffff880954f2 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} () at src/time/clocks/system_wide.rs:273 #27 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89f30 <ostd::mm::heap_allocator::init::HEAP_SPACE+515888>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #28 0xffffffff882934f5 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31 #29 0xffffffff88112b4e in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #30 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d0a650 <aster_softirq::LINES+32>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #31 0xffffffff88606d2c in aster_softirq::process_pending () at src/lib.rs:165 #32 0xffffffff8860892e in core::ops::function::Fn::call<fn(), ()> () at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79 #33 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88e0c538 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=()) at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468 #34 0xffffffff887acf99 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42 #35 0xffffffff887ad00c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdfffffd7ef70, irq_number=33) at src/trap/handler.rs:56 #36 0xffffffff8877b89b in ostd::arch::x86::trap::trap_handler (f=0xffffdfffffd7ef70) at src/arch/x86/trap/mod.rs:251 #37 0xffffffff887c121a in __from_kernel () #38 0x0000000000000000 in ?? () ``` </details> But it makes sense because we should disable the red zone. We also need to review the compile flags used in OSDK, as they appear to differ from the ones specified in the [Linux Makefile](https://github.com/torvalds/linux/blob/43fb83c17ba2d63dfb798f0be7453ed55ca3f9c2/arch/x86/Makefile) (`-Cno-redzone=y -Ccode-model=kernel -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2`). https://github.com/asterinas/asterinas/blob/f1aae232341bda78aa7bf1906e3d00df160962a8/osdk/src/commands/build/bin.rs#L178-L196 @tangruize No, I don't think that we should add the `no-redzone` option to `osdk/src/build/bin.rs`, which affects the build of the `linux-bzimage-setup` tool, not the kernel code itself. The kernel code is built in the `build_kernel_elf` function in `osdk/src/build/mod.rs`. > We also need to review the compile flags used in OSDK, as they appear to differ from the ones specified in the [Linux Makefile](https://github.com/torvalds/linux/blob/43fb83c17ba2d63dfb798f0be7453ed55ca3f9c2/arch/x86/Makefile) (-Cno-redzone=y -Ccode-model=kernel -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2). Other CPU features such has sse and avx are disabled by default for the `x86_64-unknown-none` target. > By default, Rust code generated for this target does not use any vector or floating-point registers (e.g. SSE, AVX). This allows the generated code to run in environments, such as kernels, which may need to avoid the use of such registers or which may have special considerations about the use of such registers (e.g. saving and restoring them to avoid breaking userspace code using the same registers). You can change code generation to use additional CPU features via the -C target-feature= codegen options to rustc, or via the #[target_feature] mechanism within Rust code. The bug still occurs. It seems we should investigate why the panic always occurs during `memmove` ~~in `mmap` syscall~~. @tangruize Regardless of whether the bug is fixed or not, we should disable redzones. Could you submit a PR for this fix? We should also check if signal handling considers the red zone of user-space programs. We can open another issue or PR to address all the red zone things. > We should also check if signal handling considers the red zone of user-space programs. We can open another issue or PR to address all the red zone things. These are two separate problems and the user signal handling logic has correctly skipped the red zone in user space. https://github.com/asterinas/asterinas/blob/495c93c2ada285d8abe44e7a6abd9e7adf0917b3/kernel/src/process/signal/mod.rs#L159-L160 Given that the bug always occurs in the `copy_backward` function of `memmove`, let's investigate [the function's implementation](https://github.com/rust-lang/compiler-builtins/blob/a09218f1c4d23ffbd97d68f0fefb5feed2469dc5/src/mem/x86_64.rs#L64-L89): ```rust #[inline(always)] pub unsafe fn copy_backward(dest: *mut u8, src: *const u8, count: usize) { let (pre_byte_count, qword_count, byte_count) = rep_param(dest, count); // We can't separate this block due to std/cld asm!( "std", "rep movsb", "sub $7, %rsi", "sub $7, %rdi", "mov {qword_count}, %rcx", "rep movsq", "test {pre_byte_count:e}, {pre_byte_count:e}", "add $7, %rsi", "add $7, %rdi", "mov {pre_byte_count:e}, %ecx", "rep movsb", "cld", pre_byte_count = in(reg) pre_byte_count, qword_count = in(reg) qword_count, inout("ecx") byte_count => _, inout("rdi") dest.add(count - 1) => _, inout("rsi") src.add(count - 1) => _, // We modify flags, but we restore it afterwards options(att_syntax, nostack, preserves_flags) ); } ``` The function uses `std` (set `DF`) and `cld` (clear `DF`). In the trap stack, the `DF` flag is set: ``` eflags 0x200486 [ ID IOPL=0 DF SF PF ] ``` In another run, I set a breakpoint before the shift instruction (which doesn't cause shift overflow), the `DF` flag is not set: ``` eflags 0x200082 [ ID IOPL=0 SF ] ``` We need to check if the `DF` flag is properly managed during traps (Note: [Linux clears both the `DF` and `AC` flags](https://github.com/torvalds/linux/blob/28eb75e178d389d325f1666e422bc13bbbb9804c/arch/x86/entry/entry_64.S), but we may not need to clear the `AC` flag because [SMAP](https://en.wikipedia.org/wiki/Supervisor_Mode_Access_Prevention) is currently not enabled). I've tested this patch. The bug no longer occurs. But I'm not sure if the instruction is placed at the right location: ```diff diff --git a/ostd/src/arch/x86/trap/trap.S b/ostd/src/arch/x86/trap/trap.S index 7ab5ede4..f6096b57 100644 --- a/ostd/src/arch/x86/trap/trap.S +++ b/ostd/src/arch/x86/trap/trap.S @@ -124,6 +124,7 @@ __from_kernel: push rax mov rdi, rsp + cld call trap_handler .global trap_return ``` @cqs21 Could you assist @tangruize on this issue? > I've tested this patch. The bug no longer occurs. But I'm not sure if the instruction is placed at the right location. @tangruize Good job! The trap path from user should also be covered. Maybe place it at the beginning of `trap_common`. Thanks. https://github.com/asterinas/asterinas/blob/5f35189a51ebc54298ea2cb0e4d53afe4e4e75eb/ostd/src/arch/x86/trap/trap.S#L59-L63
2024-11-24T15:05:40Z
9da6af03943c15456cdfd781021820a7da78ea40
asterinas/asterinas
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -247,7 +247,7 @@ mod test { W: Fn(Arc<PipeWriter>) + Sync + Send + 'static, R: Fn(Arc<PipeReader>) + Sync + Send + 'static, { - let channel = Channel::with_capacity(1); + let channel = Channel::with_capacity(2); let (writer, readr) = channel.split(); let writer = PipeWriter::new(writer, StatusFlags::empty()).unwrap(); diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -313,13 +313,13 @@ mod test { fn test_write_full() { test_blocking( |writer| { - assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2); assert_eq!(writer.write(&mut reader_from(&[2])).unwrap(), 1); }, |reader| { - let mut buf = [0; 2]; - assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); - assert_eq!(&buf[..1], &[1]); + let mut buf = [0; 3]; + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2); + assert_eq!(&buf[..2], &[1, 2]); assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); assert_eq!(&buf[..1], &[2]); }, diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -343,7 +343,7 @@ mod test { fn test_write_closed() { test_blocking( |writer| { - assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2); assert_eq!( writer.write(&mut reader_from(&[2])).unwrap_err().error(), Errno::EPIPE diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -354,6 +354,24 @@ mod test { ); } + #[ktest] + fn test_write_atomicity() { + test_blocking( + |writer| { + assert_eq!(writer.write(&mut reader_from(&[1])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 2); + }, + |reader| { + let mut buf = [0; 3]; + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); + assert_eq!(&buf[..1], &[1]); + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2); + assert_eq!(&buf[..2], &[1, 2]); + }, + Ordering::WriteThenRead, + ); + } + fn reader_from(buf: &[u8]) -> VmReader { VmReader::from(buf).to_fallible() } diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -22,6 +22,19 @@ pub struct Channel<T> { consumer: Consumer<T>, } +/// Maximum number of bytes guaranteed to be written to a pipe atomically. +/// +/// If the number of bytes to be written is less than the threshold, the write must be atomic. +/// A non-blocking atomic write may fail with `EAGAIN`, even if there is room for a partial write. +/// In other words, a partial write is not allowed for an atomic write. +/// +/// For more details, see the description of `PIPE_BUF` in +/// <https://man7.org/linux/man-pages/man7/pipe.7.html>. +#[cfg(not(ktest))] +const PIPE_BUF: usize = 4096; +#[cfg(ktest)] +const PIPE_BUF: usize = 2; + impl<T> Channel<T> { /// Creates a new channel with the given capacity. ///
[ "1554" ]
0.9
11382524d1d23cc6d41adf977a72138baa39e38d
PIPE implementation does not guarantee atomic writes for up to PIPE_BUF bytes ### Describe the bug The current implementation of the PIPE in Asterinas does not ensure that writes of up to PIPE_BUF bytes are atomic. ### To Reproduce Apply the following patch and run `test/pipe/pipe_atomicity` <details><summary>patch file</summary> ```diff diff --git a/test/apps/pipe/pipe_atomicity.c b/test/apps/pipe/pipe_atomicity.c new file mode 100644 index 00000000..1e473d78 --- /dev/null +++ b/test/apps/pipe/pipe_atomicity.c @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MPL-2.0 + +#define _GNU_SOURCE + +#include "../network/test.h" +#include <signal.h> +#include <string.h> +#include <sys/poll.h> +#include <unistd.h> + +static int rfd, wfd; + +FN_SETUP(short_read_and_write) +{ + int fildes[2]; + + CHECK(pipe(fildes)); + rfd = fildes[0]; + wfd = fildes[1]; + +} +END_SETUP() + +FN_TEST(atomicity) +{ + char buf[511] = { 0 }; + + // for (int i = 0; i < 130; i++) + // TEST_RES(write(wfd, buf, 511), _ret == 511); + for (int i = 0; i < 130; i++) + { + ssize_t res = write(wfd, buf, 511); + printf("i=%d, res=%ld\n", i, res); + } +} +END_TEST() ``` </details> ### Expected behavior In the current Asterinas implementation, writing 511 bytes results in partial writes (128 bytes) after 128 iterations, while the Linux implementation blocks after 127 iterations: ![aster_vs_linux](https://github.com/user-attachments/assets/e8b9377b-fff3-4c23-bb81-8e3fa6f253e1) ### Environment branch: [7ddfd42](https://github.com/asterinas/asterinas/tree/7ddfd42baa210656127044995d8707fde74fab4d)
asterinas__asterinas-1559
1,559
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -247,7 +247,7 @@ mod test { W: Fn(Arc<PipeWriter>) + Sync + Send + 'static, R: Fn(Arc<PipeReader>) + Sync + Send + 'static, { - let channel = Channel::with_capacity(1); + let channel = Channel::with_capacity(2); let (writer, readr) = channel.split(); let writer = PipeWriter::new(writer, StatusFlags::empty()).unwrap(); diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -313,13 +313,13 @@ mod test { fn test_write_full() { test_blocking( |writer| { - assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2); assert_eq!(writer.write(&mut reader_from(&[2])).unwrap(), 1); }, |reader| { - let mut buf = [0; 2]; - assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); - assert_eq!(&buf[..1], &[1]); + let mut buf = [0; 3]; + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2); + assert_eq!(&buf[..2], &[1, 2]); assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); assert_eq!(&buf[..1], &[2]); }, diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -343,7 +343,7 @@ mod test { fn test_write_closed() { test_blocking( |writer| { - assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2); assert_eq!( writer.write(&mut reader_from(&[2])).unwrap_err().error(), Errno::EPIPE diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -354,6 +354,24 @@ mod test { ); } + #[ktest] + fn test_write_atomicity() { + test_blocking( + |writer| { + assert_eq!(writer.write(&mut reader_from(&[1])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 2); + }, + |reader| { + let mut buf = [0; 3]; + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); + assert_eq!(&buf[..1], &[1]); + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2); + assert_eq!(&buf[..2], &[1, 2]); + }, + Ordering::WriteThenRead, + ); + } + fn reader_from(buf: &[u8]) -> VmReader { VmReader::from(buf).to_fallible() } diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -22,6 +22,19 @@ pub struct Channel<T> { consumer: Consumer<T>, } +/// Maximum number of bytes guaranteed to be written to a pipe atomically. +/// +/// If the number of bytes to be written is less than the threshold, the write must be atomic. +/// A non-blocking atomic write may fail with `EAGAIN`, even if there is room for a partial write. +/// In other words, a partial write is not allowed for an atomic write. +/// +/// For more details, see the description of `PIPE_BUF` in +/// <https://man7.org/linux/man-pages/man7/pipe.7.html>. +#[cfg(not(ktest))] +const PIPE_BUF: usize = 4096; +#[cfg(ktest)] +const PIPE_BUF: usize = 2; + impl<T> Channel<T> { /// Creates a new channel with the given capacity. /// diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -114,7 +127,7 @@ impl<T> Producer<T> { } fn update_pollee(&self) { - // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either + // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either // `this_end` or `peer_end`, should reflect the same state. However, we need to take the // correct lock when updating the events to avoid races between the state check and the // event update. diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -114,7 +127,7 @@ impl<T> Producer<T> { } fn update_pollee(&self) { - // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either + // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either // `this_end` or `peer_end`, should reflect the same state. However, we need to take the // correct lock when updating the events to avoid races between the state check and the // event update. diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -123,7 +136,7 @@ impl<T> Producer<T> { let rb = this_end.rb(); if self.is_shutdown() { // The POLLOUT event is always set in this case. Don't try to remove it. - } else if rb.is_full() { + } else if rb.free_len() < PIPE_BUF { this_end.pollee.del_events(IoEvents::OUT); } drop(rb); diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -123,7 +136,7 @@ impl<T> Producer<T> { let rb = this_end.rb(); if self.is_shutdown() { // The POLLOUT event is always set in this case. Don't try to remove it. - } else if rb.is_full() { + } else if rb.free_len() < PIPE_BUF { this_end.pollee.del_events(IoEvents::OUT); } drop(rb); diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -204,7 +217,7 @@ impl<T> Consumer<T> { } fn update_pollee(&self) { - // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either + // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either // `this_end` or `peer_end`, should reflect the same state. However, we need to take the // correct lock when updating the events to avoid races between the state check and the // event update. diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -204,7 +217,7 @@ impl<T> Consumer<T> { } fn update_pollee(&self) { - // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either + // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either // `this_end` or `peer_end`, should reflect the same state. However, we need to take the // correct lock when updating the events to avoid races between the state check and the // event update. diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -218,7 +231,7 @@ impl<T> Consumer<T> { let peer_end = self.peer_end(); let rb = peer_end.rb(); - if !rb.is_full() { + if rb.free_len() >= PIPE_BUF { peer_end.pollee.add_events(IoEvents::OUT); } drop(rb); diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -218,7 +231,7 @@ impl<T> Consumer<T> { let peer_end = self.peer_end(); let rb = peer_end.rb(); - if !rb.is_full() { + if rb.free_len() >= PIPE_BUF { peer_end.pollee.add_events(IoEvents::OUT); } drop(rb); diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -307,6 +320,10 @@ impl<R: TRights> Fifo<u8, R> { #[require(R > Write)] pub fn write(&self, reader: &mut dyn MultiRead) -> Result<usize> { let mut rb = self.common.producer.rb(); + if rb.free_len() < reader.sum_lens() && reader.sum_lens() <= PIPE_BUF { + // No sufficient space for an atomic write + return Ok(0); + } rb.write_fallible(reader) } } diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -307,6 +320,10 @@ impl<R: TRights> Fifo<u8, R> { #[require(R > Write)] pub fn write(&self, reader: &mut dyn MultiRead) -> Result<usize> { let mut rb = self.common.producer.rb(); + if rb.free_len() < reader.sum_lens() && reader.sum_lens() <= PIPE_BUF { + // No sufficient space for an atomic write + return Ok(0); + } rb.write_fallible(reader) } }
This one is easy to fix. Just check if the remaining space in the internal buffer of a pipe is no less than `PIPE_BUF` before actually writing the data.
2024-11-05T07:28:33Z
9da6af03943c15456cdfd781021820a7da78ea40
asterinas/asterinas
diff --git a/tools/bump_version.sh b/tools/bump_version.sh --- a/tools/bump_version.sh +++ b/tools/bump_version.sh @@ -106,6 +106,9 @@ DOCS_DIR=${ASTER_SRC_DIR}/docs OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml OSTD_TEST_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-test/Cargo.toml OSTD_MACROS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-macros/Cargo.toml +LINUX_BOOT_PARAMS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/boot-params/Cargo.toml +LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/builder/Cargo.toml +LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/setup/Cargo.toml OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml OSDK_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml VERSION_PATH=${ASTER_SRC_DIR}/VERSION diff --git a/tools/bump_version.sh b/tools/bump_version.sh --- a/tools/bump_version.sh +++ b/tools/bump_version.sh @@ -125,11 +128,17 @@ new_version=$(bump_version ${current_version}) update_package_version ${OSTD_TEST_CARGO_TOML_PATH} update_package_version ${OSTD_MACROS_CARGO_TOML_PATH} update_package_version ${OSTD_CARGO_TOML_PATH} +update_package_version ${LINUX_BOOT_PARAMS_CARGO_TOML_PATH} +update_package_version ${LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH} +update_package_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-test +update_dep_version ${OSTD_CARGO_TOML_PATH} linux-boot-params update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-macros +update_dep_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} linux-boot-params update_package_version ${OSDK_CARGO_TOML_PATH} update_package_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} update_dep_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} ostd +update_dep_version ${OSDK_CARGO_TOML_PATH} linux-bzimage-builder # Automatically bump Cargo.lock files cargo update -p aster-nix --precise $new_version # For Cargo.lock diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh --- a/tools/github_workflows/publish_osdk_and_ostd.sh +++ b/tools/github_workflows/publish_osdk_and_ostd.sh @@ -67,6 +69,7 @@ TARGETS="x86_64-unknown-none" for TARGET in $TARGETS; do do_publish_for ostd/libs/ostd-macros $TARGET do_publish_for ostd/libs/ostd-test $TARGET + do_publish_for ostd/libs/linux-bzimage/setup $TARGET do_publish_for ostd $TARGET do_publish_for osdk/test-kernel $TARGET
[ "1291" ]
0.9
2af9916de92f8ca1e694bb6ac5e33111bbcf51fd
Invalid opcode after relocation for Linux EFI-handover boot <!-- Thank you for taking the time to report a bug. Your input is valuable to us. Please replace all the <angle brackets> below with your own information. --> ### Describe the bug <!-- A clear and concise description of what the bug is. --> Sometimes the Linux EFI-handover boot will fail due to invalid opcode failure during early booting. ### To Reproduce With KVM on, ```bash make run AUTO_TEST=syscall BOOT_PROTOCOL=linux-efi-handover64 ``` <!-- Steps to reproduce the behavior. Example: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error --> ### Logs ``` ... Adding bitflags v1.3.2 (latest: v2.6.0) Adding raw-cpuid v10.7.0 (latest: v11.1.0) Adding syn v1.0.109 (latest: v2.0.77) Adding uefi v0.26.0 (latest: v0.31.0) BdsDxe: loading Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0) BdsDxe: starting Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0) [EFI stub] Relocations applied. !!!! X64 Exception Type - 06(#UD - Invalid Opcode) CPU Apic ID - 00000000 !!!! RIP - 000000007CBC90F0, CS - 0000000000000038, RFLAGS - 0000000000210217 RAX - 000000007FF12BB9, RCX - 000000007CBC19A8, RDX - 0000000000000001 RBX - 000000007CBC23B8, RSP - 000000007CBC2398, RBP - 0000000000000001 RSI - 000000007CBBBB77, RDI - 000000007CBC2408 R8 - 00000000000000AF, R9 - 0000000000000014, R10 - 000000007E43F78D R11 - 0000000000000008, R12 - 000000007E43F78D, R13 - 0000000000000008 R14 - 0000000000000002, R15 - 000000007E977518 DS - 0000000000000030, ES - 0000000000000030, FS - 0000000000000030 GS - 0000000000000030, SS - 0000000000000030 CR0 - 0000000080010033, CR2 - 0000000000000000, CR3 - 000000007FC01000 CR4 - 0000000000000668, CR8 - 0000000000000000 DR0 - 0000000000000000, DR1 - 0000000000000000, DR2 - 0000000000000000 DR3 - 0000000000000000, DR6 - 00000000FFFF0FF0, DR7 - 0000000000000400 GDTR - 000000007F9DE000 0000000000000047, LDTR - 0000000000000000 IDTR - 000000007F470018 0000000000000FFF, TR - 0000000000000000 FXSAVE_STATE - 000000007CBC1FF0 ``` <!-- If applicable, add log snippets or files to help explain and debug the problem. Please use code blocks (```) to format logs. --> <!-- Once again, thank you for helping us improve our project! -->
asterinas__asterinas-1447
1,447
diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "acpi" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "acpi" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -875,9 +875,9 @@ dependencies = [ "log", "uart_16550", "uefi", - "uefi-services", - "x86_64", - "xmas-elf 0.8.0", + "uefi-raw", + "x86_64 0.15.1", + "xmas-elf 0.9.1", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -875,9 +875,9 @@ dependencies = [ "log", "uart_16550", "uefi", - "uefi-services", - "x86_64", - "xmas-elf 0.8.0", + "uefi-raw", + "x86_64 0.15.1", + "xmas-elf 0.9.1", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -953,7 +953,7 @@ dependencies = [ "log", "multiboot2-common", "ptr_meta", - "uefi-raw 0.8.0", + "uefi-raw", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -953,7 +953,7 @@ dependencies = [ "log", "multiboot2-common", "ptr_meta", - "uefi-raw 0.8.0", + "uefi-raw", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1119,7 +1119,7 @@ dependencies = [ "unwinding", "volatile", "x86", - "x86_64", + "x86_64 0.14.11", "xarray", ] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1119,7 +1119,7 @@ dependencies = [ "unwinding", "volatile", "x86", - "x86_64", + "x86_64 0.14.11", "xarray", ] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1238,6 +1238,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "qemu-exit" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb0fd6580eeed0103c054e3fba2c2618ff476943762f28a645b63b8692b21c9" + [[package]] name = "quote" version = "1.0.37" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1238,6 +1238,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "qemu-exit" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb0fd6580eeed0103c054e3fba2c2618ff476943762f28a645b63b8692b21c9" + [[package]] name = "quote" version = "1.0.37" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1470,7 +1476,7 @@ dependencies = [ "iced-x86", "lazy_static", "raw-cpuid", - "x86_64", + "x86_64 0.14.11", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1470,7 +1476,7 @@ dependencies = [ "iced-x86", "lazy_static", "raw-cpuid", - "x86_64", + "x86_64 0.14.11", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1572,50 +1578,41 @@ dependencies = [ [[package]] name = "ucs2" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad643914094137d475641b6bab89462505316ec2ce70907ad20102d28a79ab8" +checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba" dependencies = [ "bit_field", ] [[package]] name = "uefi" -version = "0.26.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07ead9f748a4646479b850add36b527113a80e80a7e0f44d7b0334291850dcc5" +checksum = "91f17ea8502a6bd414acb2bf5194f90ca4c48e33a2d18cb57eab3294d2050d99" dependencies = [ "bitflags 2.6.0", + "cfg-if", "log", "ptr_meta", + "qemu-exit", "ucs2", "uefi-macros", - "uefi-raw 0.5.0", + "uefi-raw", "uguid", ] [[package]] name = "uefi-macros" -version = "0.13.0" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26a7b1c2c808c3db854a54d5215e3f7e7aaf5dcfbce095598cba6af29895695d" +checksum = "c19ee3a01d435eda42cb9931269b349d28a1762f91ddf01c68d276f74b957cc3" dependencies = [ "proc-macro2", "quote", "syn 2.0.77", ] -[[package]] -name = "uefi-raw" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864ac69eadd877bfb34e7814be1928122ed0057d9f975169a56ee496aa7bdfd7" -dependencies = [ - "bitflags 2.6.0", - "ptr_meta", - "uguid", -] - [[package]] name = "uefi-raw" version = "0.8.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1572,50 +1578,41 @@ dependencies = [ [[package]] name = "ucs2" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad643914094137d475641b6bab89462505316ec2ce70907ad20102d28a79ab8" +checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba" dependencies = [ "bit_field", ] [[package]] name = "uefi" -version = "0.26.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07ead9f748a4646479b850add36b527113a80e80a7e0f44d7b0334291850dcc5" +checksum = "91f17ea8502a6bd414acb2bf5194f90ca4c48e33a2d18cb57eab3294d2050d99" dependencies = [ "bitflags 2.6.0", + "cfg-if", "log", "ptr_meta", + "qemu-exit", "ucs2", "uefi-macros", - "uefi-raw 0.5.0", + "uefi-raw", "uguid", ] [[package]] name = "uefi-macros" -version = "0.13.0" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26a7b1c2c808c3db854a54d5215e3f7e7aaf5dcfbce095598cba6af29895695d" +checksum = "c19ee3a01d435eda42cb9931269b349d28a1762f91ddf01c68d276f74b957cc3" dependencies = [ "proc-macro2", "quote", "syn 2.0.77", ] -[[package]] -name = "uefi-raw" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864ac69eadd877bfb34e7814be1928122ed0057d9f975169a56ee496aa7bdfd7" -dependencies = [ - "bitflags 2.6.0", - "ptr_meta", - "uguid", -] - [[package]] name = "uefi-raw" version = "0.8.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1627,17 +1624,6 @@ dependencies = [ "uguid", ] -[[package]] -name = "uefi-services" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a79fcb420624743c895bad0f9480fbc2f64e7c8d8611fb1ada6bdd799942feb4" -dependencies = [ - "cfg-if", - "log", - "uefi", -] - [[package]] name = "uguid" version = "2.1.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1627,17 +1624,6 @@ dependencies = [ "uguid", ] -[[package]] -name = "uefi-services" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a79fcb420624743c895bad0f9480fbc2f64e7c8d8611fb1ada6bdd799942feb4" -dependencies = [ - "cfg-if", - "log", - "uefi", -] - [[package]] name = "uguid" version = "2.1.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1751,6 +1737,18 @@ dependencies = [ "volatile", ] +[[package]] +name = "x86_64" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df" +dependencies = [ + "bit_field", + "bitflags 2.6.0", + "rustversion", + "volatile", +] + [[package]] name = "xarray" version = "0.1.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1751,6 +1737,18 @@ dependencies = [ "volatile", ] +[[package]] +name = "x86_64" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df" +dependencies = [ + "bit_field", + "bitflags 2.6.0", + "rustversion", + "volatile", +] + [[package]] name = "xarray" version = "0.1.0" diff --git a/Makefile b/Makefile --- a/Makefile +++ b/Makefile @@ -89,7 +89,7 @@ endif ifeq ($(BOOT_PROTOCOL), linux-efi-handover64) CARGO_OSDK_ARGS += --grub-mkrescue=/usr/bin/grub-mkrescue CARGO_OSDK_ARGS += --grub-boot-protocol="linux" -CARGO_OSDK_ARGS += --encoding gzip +CARGO_OSDK_ARGS += --encoding raw # FIXME: GZIP self-decompression triggers CPU faults else ifeq ($(BOOT_PROTOCOL), linux-legacy32) CARGO_OSDK_ARGS += --linux-x86-legacy-boot CARGO_OSDK_ARGS += --grub-boot-protocol="linux" diff --git a/Makefile b/Makefile --- a/Makefile +++ b/Makefile @@ -89,7 +89,7 @@ endif ifeq ($(BOOT_PROTOCOL), linux-efi-handover64) CARGO_OSDK_ARGS += --grub-mkrescue=/usr/bin/grub-mkrescue CARGO_OSDK_ARGS += --grub-boot-protocol="linux" -CARGO_OSDK_ARGS += --encoding gzip +CARGO_OSDK_ARGS += --encoding raw # FIXME: GZIP self-decompression triggers CPU faults else ifeq ($(BOOT_PROTOCOL), linux-legacy32) CARGO_OSDK_ARGS += --linux-x86-legacy-boot CARGO_OSDK_ARGS += --grub-boot-protocol="linux" diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml --- a/osdk/Cargo.toml +++ b/osdk/Cargo.toml @@ -9,15 +9,8 @@ repository = "https://github.com/asterinas/asterinas" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[dependencies.linux-bzimage-builder] -# The path for local development -path = "../ostd/libs/linux-bzimage/builder" -# The version specified here is used for publishing on crates.io. -# Please update this version when publishing the cargo-osdk crate -# if there have been any changes to the dependent crate. -version = "0.2.0" - [dependencies] +linux-bzimage-builder = { version = "0.2.0", path = "../ostd/libs/linux-bzimage/builder" } clap = { version = "4.4.17", features = ["cargo", "derive"] } chrono = "0.4.38" env_logger = "0.11.0" diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml --- a/osdk/Cargo.toml +++ b/osdk/Cargo.toml @@ -9,15 +9,8 @@ repository = "https://github.com/asterinas/asterinas" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[dependencies.linux-bzimage-builder] -# The path for local development -path = "../ostd/libs/linux-bzimage/builder" -# The version specified here is used for publishing on crates.io. -# Please update this version when publishing the cargo-osdk crate -# if there have been any changes to the dependent crate. -version = "0.2.0" - [dependencies] +linux-bzimage-builder = { version = "0.2.0", path = "../ostd/libs/linux-bzimage/builder" } clap = { version = "4.4.17", features = ["cargo", "derive"] } chrono = "0.4.38" env_logger = "0.11.0" diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -167,7 +167,37 @@ fn install_setup_with_arch( let target_dir = std::fs::canonicalize(target_dir).unwrap(); let mut cmd = Command::new("cargo"); - cmd.env("RUSTFLAGS", "-Ccode-model=kernel -Crelocation-model=pie -Ctarget-feature=+crt-static -Zplt=yes -Zrelax-elf-relocations=yes -Crelro-level=full"); + let mut rustflags = vec![ + "-Cdebuginfo=2", + "-Ccode-model=kernel", + "-Crelocation-model=pie", + "-Zplt=yes", + "-Zrelax-elf-relocations=yes", + "-Crelro-level=full", + ]; + let target_feature_args = match arch { + SetupInstallArch::X86_64 => { + concat!( + "-Ctarget-feature=", + "+crt-static", + ",-adx", + ",-aes", + ",-avx", + ",-avx2", + ",-fxsr", + ",-sse", + ",-sse2", + ",-sse3", + ",-sse4.1", + ",-sse4.2", + ",-ssse3", + ",-xsave", + ) + } + SetupInstallArch::Other(_) => "-Ctarget-feature=+crt-static", + }; + rustflags.push(target_feature_args); + cmd.env("RUSTFLAGS", rustflags.join(" ")); cmd.arg("install").arg("linux-bzimage-setup"); cmd.arg("--force"); cmd.arg("--root").arg(install_dir.as_ref()); diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -167,7 +167,37 @@ fn install_setup_with_arch( let target_dir = std::fs::canonicalize(target_dir).unwrap(); let mut cmd = Command::new("cargo"); - cmd.env("RUSTFLAGS", "-Ccode-model=kernel -Crelocation-model=pie -Ctarget-feature=+crt-static -Zplt=yes -Zrelax-elf-relocations=yes -Crelro-level=full"); + let mut rustflags = vec![ + "-Cdebuginfo=2", + "-Ccode-model=kernel", + "-Crelocation-model=pie", + "-Zplt=yes", + "-Zrelax-elf-relocations=yes", + "-Crelro-level=full", + ]; + let target_feature_args = match arch { + SetupInstallArch::X86_64 => { + concat!( + "-Ctarget-feature=", + "+crt-static", + ",-adx", + ",-aes", + ",-avx", + ",-avx2", + ",-fxsr", + ",-sse", + ",-sse2", + ",-sse3", + ",-sse4.1", + ",-sse4.2", + ",-ssse3", + ",-xsave", + ) + } + SetupInstallArch::Other(_) => "-Ctarget-feature=+crt-static", + }; + rustflags.push(target_feature_args); + cmd.env("RUSTFLAGS", rustflags.join(" ")); cmd.arg("install").arg("linux-bzimage-setup"); cmd.arg("--force"); cmd.arg("--root").arg(install_dir.as_ref()); diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -175,10 +205,9 @@ fn install_setup_with_arch( let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let setup_dir = crate_dir.join("../ostd/libs/linux-bzimage/setup"); cmd.arg("--path").arg(setup_dir); + } else { + cmd.arg("--version").arg(env!("CARGO_PKG_VERSION")); } - // Remember to upgrade this version if new version of linux-bzimage-setup is released. - const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0"; - cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION); cmd.arg("--target").arg(match arch { SetupInstallArch::X86_64 => "x86_64-unknown-none", SetupInstallArch::Other(path) => path.to_str().unwrap(), diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -175,10 +205,9 @@ fn install_setup_with_arch( let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let setup_dir = crate_dir.join("../ostd/libs/linux-bzimage/setup"); cmd.arg("--path").arg(setup_dir); + } else { + cmd.arg("--version").arg(env!("CARGO_PKG_VERSION")); } - // Remember to upgrade this version if new version of linux-bzimage-setup is released. - const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0"; - cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION); cmd.arg("--target").arg(match arch { SetupInstallArch::X86_64 => "x86_64-unknown-none", SetupInstallArch::Other(path) => path.to_str().unwrap(), diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml --- a/ostd/Cargo.toml +++ b/ostd/Cargo.toml @@ -28,7 +28,7 @@ inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-ma int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" } intrusive-collections = { version = "0.9.6", features = ["nightly"] } lazy_static = { version = "1.0", features = ["spin_no_std"] } -linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" } +linux-boot-params = { version = "0.1.0", path = "libs/linux-bzimage/boot-params" } log = "0.4" num = { version = "0.4", default-features = false } num-derive = { version = "0.4", default-features = false } diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml --- a/ostd/Cargo.toml +++ b/ostd/Cargo.toml @@ -28,7 +28,7 @@ inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-ma int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" } intrusive-collections = { version = "0.9.6", features = ["nightly"] } lazy_static = { version = "1.0", features = ["spin_no_std"] } -linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" } +linux-boot-params = { version = "0.1.0", path = "libs/linux-bzimage/boot-params" } log = "0.4" num = { version = "0.4", default-features = false } num-derive = { version = "0.4", default-features = false } diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -8,7 +8,7 @@ //! The reference to the Linux PE header definition: //! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h> -use std::{mem::size_of, ops::Range}; +use std::{mem::size_of, vec}; use bytemuck::{Pod, Zeroable}; use serde::Serialize; diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -8,7 +8,7 @@ //! The reference to the Linux PE header definition: //! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h> -use std::{mem::size_of, ops::Range}; +use std::{mem::size_of, vec}; use bytemuck::{Pod, Zeroable}; use serde::Serialize; diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -202,80 +202,6 @@ struct PeSectionHdr { flags: u32, } -struct ImageSectionAddrInfo { - pub text: Range<SetupVA>, - pub data: Range<SetupVA>, - pub bss: Range<SetupVA>, - /// All the readonly but loaded sections. - pub rodata: Range<SetupVA>, -} - -impl ImageSectionAddrInfo { - fn from(elf: &xmas_elf::ElfFile) -> Self { - let mut text_start = None; - let mut text_end = None; - let mut data_start = None; - let mut data_end = None; - let mut bss_start = None; - let mut bss_end = None; - let mut rodata_start = None; - let mut rodata_end = None; - for program in elf.program_iter() { - if program.get_type().unwrap() == xmas_elf::program::Type::Load { - let offset = SetupVA::from(program.virtual_addr() as usize); - let length = program.mem_size() as usize; - if program.flags().is_execute() { - text_start = Some(offset); - text_end = Some(offset + length); - } else if program.flags().is_write() { - data_start = Some(offset); - data_end = Some(offset + program.file_size() as usize); - bss_start = Some(offset + program.file_size() as usize); - bss_end = Some(offset + length); - } else if program.flags().is_read() { - rodata_start = Some(offset); - rodata_end = Some(offset + length); - } - } - } - - Self { - text: text_start.unwrap()..text_end.unwrap(), - data: data_start.unwrap()..data_end.unwrap(), - bss: bss_start.unwrap()..bss_end.unwrap(), - rodata: rodata_start.unwrap()..rodata_end.unwrap(), - } - } - - fn text_virt_size(&self) -> usize { - self.text.end - self.text.start - } - - fn text_file_size(&self) -> usize { - SetupFileOffset::from(self.text.end) - SetupFileOffset::from(self.text.start) - } - - fn data_virt_size(&self) -> usize { - self.data.end - self.data.start - } - - fn data_file_size(&self) -> usize { - SetupFileOffset::from(self.data.end) - SetupFileOffset::from(self.data.start) - } - - fn bss_virt_size(&self) -> usize { - self.bss.end - self.bss.start - } - - fn rodata_virt_size(&self) -> usize { - self.rodata.end - self.rodata.start - } - - fn rodata_file_size(&self) -> usize { - SetupFileOffset::from(self.rodata.end) - SetupFileOffset::from(self.rodata.start) - } -} - pub struct ImagePeCoffHeaderBuf { pub header_at_zero: Vec<u8>, pub relocs: (SetupFileOffset, Vec<u8>), diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -202,80 +202,6 @@ struct PeSectionHdr { flags: u32, } -struct ImageSectionAddrInfo { - pub text: Range<SetupVA>, - pub data: Range<SetupVA>, - pub bss: Range<SetupVA>, - /// All the readonly but loaded sections. - pub rodata: Range<SetupVA>, -} - -impl ImageSectionAddrInfo { - fn from(elf: &xmas_elf::ElfFile) -> Self { - let mut text_start = None; - let mut text_end = None; - let mut data_start = None; - let mut data_end = None; - let mut bss_start = None; - let mut bss_end = None; - let mut rodata_start = None; - let mut rodata_end = None; - for program in elf.program_iter() { - if program.get_type().unwrap() == xmas_elf::program::Type::Load { - let offset = SetupVA::from(program.virtual_addr() as usize); - let length = program.mem_size() as usize; - if program.flags().is_execute() { - text_start = Some(offset); - text_end = Some(offset + length); - } else if program.flags().is_write() { - data_start = Some(offset); - data_end = Some(offset + program.file_size() as usize); - bss_start = Some(offset + program.file_size() as usize); - bss_end = Some(offset + length); - } else if program.flags().is_read() { - rodata_start = Some(offset); - rodata_end = Some(offset + length); - } - } - } - - Self { - text: text_start.unwrap()..text_end.unwrap(), - data: data_start.unwrap()..data_end.unwrap(), - bss: bss_start.unwrap()..bss_end.unwrap(), - rodata: rodata_start.unwrap()..rodata_end.unwrap(), - } - } - - fn text_virt_size(&self) -> usize { - self.text.end - self.text.start - } - - fn text_file_size(&self) -> usize { - SetupFileOffset::from(self.text.end) - SetupFileOffset::from(self.text.start) - } - - fn data_virt_size(&self) -> usize { - self.data.end - self.data.start - } - - fn data_file_size(&self) -> usize { - SetupFileOffset::from(self.data.end) - SetupFileOffset::from(self.data.start) - } - - fn bss_virt_size(&self) -> usize { - self.bss.end - self.bss.start - } - - fn rodata_virt_size(&self) -> usize { - self.rodata.end - self.rodata.start - } - - fn rodata_file_size(&self) -> usize { - SetupFileOffset::from(self.rodata.end) - SetupFileOffset::from(self.rodata.start) - } -} - pub struct ImagePeCoffHeaderBuf { pub header_at_zero: Vec<u8>, pub relocs: (SetupFileOffset, Vec<u8>), diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -350,17 +276,53 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP }, }; - let addr_info = ImageSectionAddrInfo::from(&elf); - // PE section headers - let sec_hdrs = [ - // .reloc - PeSectionHdr { + let mut sec_hdrs = get_pe_sec_headers_from(&elf); + + sec_hdrs.push(PeSectionHdr::new_reloc( + relocs.len() as u32, + usize::from(SetupVA::from(reloc_offset)) as u32, + relocs.len() as u32, + usize::from(reloc_offset) as u32, + )); + + // Write the MS-DOS header + bin.extend_from_slice(&MZ_MAGIC.to_le_bytes()); + // Write the MS-DOS stub at 0x3c + bin.extend_from_slice(&[0x0; 0x3c - 0x2]); + // Write the PE header offset, the header is right after the offset field + bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes()); + + // Write the PE header + pe_hdr.sections = sec_hdrs.len() as u16; + bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr)); + // Write the PE32+ optional header + bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr)); + bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs)); + // Write the PE section headers + for sec_hdr in sec_hdrs { + bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr)); + } + + ImagePeCoffHeaderBuf { + header_at_zero: bin, + relocs: (reloc_offset, relocs), + } +} + +impl PeSectionHdr { + fn new_reloc( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'r', b'e', b'l', b'o', b'c', 0, 0], - virtual_size: relocs.len() as u32, - virtual_address: usize::from(SetupVA::from(reloc_offset)) as u32, - raw_data_size: relocs.len() as u32, - data_addr: usize::from(reloc_offset) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -350,17 +276,53 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP }, }; - let addr_info = ImageSectionAddrInfo::from(&elf); - // PE section headers - let sec_hdrs = [ - // .reloc - PeSectionHdr { + let mut sec_hdrs = get_pe_sec_headers_from(&elf); + + sec_hdrs.push(PeSectionHdr::new_reloc( + relocs.len() as u32, + usize::from(SetupVA::from(reloc_offset)) as u32, + relocs.len() as u32, + usize::from(reloc_offset) as u32, + )); + + // Write the MS-DOS header + bin.extend_from_slice(&MZ_MAGIC.to_le_bytes()); + // Write the MS-DOS stub at 0x3c + bin.extend_from_slice(&[0x0; 0x3c - 0x2]); + // Write the PE header offset, the header is right after the offset field + bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes()); + + // Write the PE header + pe_hdr.sections = sec_hdrs.len() as u16; + bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr)); + // Write the PE32+ optional header + bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr)); + bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs)); + // Write the PE section headers + for sec_hdr in sec_hdrs { + bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr)); + } + + ImagePeCoffHeaderBuf { + header_at_zero: bin, + relocs: (reloc_offset, relocs), + } +} + +impl PeSectionHdr { + fn new_reloc( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'r', b'e', b'l', b'o', b'c', 0, 0], - virtual_size: relocs.len() as u32, - virtual_address: usize::from(SetupVA::from(reloc_offset)) as u32, - raw_data_size: relocs.len() as u32, - data_addr: usize::from(reloc_offset) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -370,14 +332,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_DISCARDABLE) .bits | PeSectionHdrFlagsAlign::_1Bytes as u32, - }, - // .text - PeSectionHdr { + } + } + + fn new_text( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b't', b'e', b'x', b't', 0, 0, 0], - virtual_size: addr_info.text_virt_size() as u32, - virtual_address: usize::from(addr_info.text.start) as u32, - raw_data_size: addr_info.text_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.text.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -370,14 +332,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_DISCARDABLE) .bits | PeSectionHdrFlagsAlign::_1Bytes as u32, - }, - // .text - PeSectionHdr { + } + } + + fn new_text( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b't', b'e', b'x', b't', 0, 0, 0], - virtual_size: addr_info.text_virt_size() as u32, - virtual_address: usize::from(addr_info.text.start) as u32, - raw_data_size: addr_info.text_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.text.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -387,14 +356,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_EXECUTE) .bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .data - PeSectionHdr { + } + } + + fn new_data( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'd', b'a', b't', b'a', 0, 0, 0], - virtual_size: addr_info.data_virt_size() as u32, - virtual_address: usize::from(addr_info.data.start) as u32, - raw_data_size: addr_info.data_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.data.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -387,14 +356,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_EXECUTE) .bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .data - PeSectionHdr { + } + } + + fn new_data( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'd', b'a', b't', b'a', 0, 0, 0], - virtual_size: addr_info.data_virt_size() as u32, - virtual_address: usize::from(addr_info.data.start) as u32, - raw_data_size: addr_info.data_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.data.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -404,59 +380,69 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_WRITE) .bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .bss - PeSectionHdr { - name: [b'.', b'b', b's', b's', 0, 0, 0, 0], - virtual_size: addr_info.bss_virt_size() as u32, - virtual_address: usize::from(addr_info.bss.start) as u32, - raw_data_size: 0, - data_addr: 0, - relocs: 0, - line_numbers: 0, - num_relocs: 0, - num_lin_numbers: 0, - flags: (PeSectionHdrFlags::CNT_UNINITIALIZED_DATA - | PeSectionHdrFlags::MEM_READ - | PeSectionHdrFlags::MEM_WRITE) - .bits - | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .rodata - PeSectionHdr { + } + } + + fn new_rodata( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'r', b'o', b'd', b'a', b't', b'a', 0], - virtual_size: addr_info.rodata_virt_size() as u32, - virtual_address: usize::from(addr_info.rodata.start) as u32, - raw_data_size: addr_info.rodata_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.rodata.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, num_lin_numbers: 0, flags: (PeSectionHdrFlags::CNT_INITIALIZED_DATA | PeSectionHdrFlags::MEM_READ).bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - ]; - // Write the MS-DOS header - bin.extend_from_slice(&MZ_MAGIC.to_le_bytes()); - // Write the MS-DOS stub at 0x3c - bin.extend_from_slice(&[0x0; 0x3c - 0x2]); - // Write the PE header offset, the header is right after the offset field - bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes()); - - // Write the PE header - pe_hdr.sections = sec_hdrs.len() as u16; - bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr)); - // Write the PE32+ optional header - bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr)); - bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs)); - // Write the PE section headers - for sec_hdr in sec_hdrs { - bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr)); + } } +} - ImagePeCoffHeaderBuf { - header_at_zero: bin, - relocs: (reloc_offset, relocs), +fn get_pe_sec_headers_from(elf: &xmas_elf::ElfFile) -> Vec<PeSectionHdr> { + let mut result = vec![]; + + for program in elf.program_iter() { + if program.get_type().unwrap() == xmas_elf::program::Type::Load { + let offset = SetupVA::from(program.virtual_addr() as usize); + let length = program.mem_size() as usize; + + if program.flags().is_execute() { + result.push(PeSectionHdr::new_text( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } else if program.flags().is_write() { + // We don't care about `.bss` sections since the binary is + // expanded to raw. + if program.file_size() == 0 { + continue; + } + + result.push(PeSectionHdr::new_data( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } else if program.flags().is_read() { + result.push(PeSectionHdr::new_rodata( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } + } } + + result } diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -404,59 +380,69 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_WRITE) .bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .bss - PeSectionHdr { - name: [b'.', b'b', b's', b's', 0, 0, 0, 0], - virtual_size: addr_info.bss_virt_size() as u32, - virtual_address: usize::from(addr_info.bss.start) as u32, - raw_data_size: 0, - data_addr: 0, - relocs: 0, - line_numbers: 0, - num_relocs: 0, - num_lin_numbers: 0, - flags: (PeSectionHdrFlags::CNT_UNINITIALIZED_DATA - | PeSectionHdrFlags::MEM_READ - | PeSectionHdrFlags::MEM_WRITE) - .bits - | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .rodata - PeSectionHdr { + } + } + + fn new_rodata( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'r', b'o', b'd', b'a', b't', b'a', 0], - virtual_size: addr_info.rodata_virt_size() as u32, - virtual_address: usize::from(addr_info.rodata.start) as u32, - raw_data_size: addr_info.rodata_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.rodata.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, num_lin_numbers: 0, flags: (PeSectionHdrFlags::CNT_INITIALIZED_DATA | PeSectionHdrFlags::MEM_READ).bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - ]; - // Write the MS-DOS header - bin.extend_from_slice(&MZ_MAGIC.to_le_bytes()); - // Write the MS-DOS stub at 0x3c - bin.extend_from_slice(&[0x0; 0x3c - 0x2]); - // Write the PE header offset, the header is right after the offset field - bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes()); - - // Write the PE header - pe_hdr.sections = sec_hdrs.len() as u16; - bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr)); - // Write the PE32+ optional header - bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr)); - bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs)); - // Write the PE section headers - for sec_hdr in sec_hdrs { - bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr)); + } } +} - ImagePeCoffHeaderBuf { - header_at_zero: bin, - relocs: (reloc_offset, relocs), +fn get_pe_sec_headers_from(elf: &xmas_elf::ElfFile) -> Vec<PeSectionHdr> { + let mut result = vec![]; + + for program in elf.program_iter() { + if program.get_type().unwrap() == xmas_elf::program::Type::Load { + let offset = SetupVA::from(program.virtual_addr() as usize); + let length = program.mem_size() as usize; + + if program.flags().is_execute() { + result.push(PeSectionHdr::new_text( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } else if program.flags().is_write() { + // We don't care about `.bss` sections since the binary is + // expanded to raw. + if program.file_size() == 0 { + continue; + } + + result.push(PeSectionHdr::new_data( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } else if program.flags().is_read() { + result.push(PeSectionHdr::new_rodata( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } + } } + + result } diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml --- a/ostd/libs/linux-bzimage/setup/Cargo.toml +++ b/ostd/libs/linux-bzimage/setup/Cargo.toml @@ -16,16 +16,16 @@ path = "src/main.rs" cfg-if = "1.0.0" core2 = { version = "0.4.0", default-features = false, features = ["nightly"] } libflate = { version = "2.1.0", default-features = false } -linux-boot-params = { path = "../boot-params", version = "0.1.0" } +linux-boot-params = { version = "0.1.0", path = "../boot-params" } uart_16550 = "0.3.0" -xmas-elf = "0.8.0" +xmas-elf = "0.9.1" [target.x86_64-unknown-none.dependencies] bitflags = "2.4.1" log = "0.4.20" -uefi = "0.26.0" -uefi-services = "0.23.0" -x86_64 = "0.14.11" +uefi = { version = "0.32.0", features = ["global_allocator", "panic_handler", "logger", "qemu"]} +uefi-raw = "0.8.0" +x86_64 = "0.15.1" [features] default = [] diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml --- a/ostd/libs/linux-bzimage/setup/Cargo.toml +++ b/ostd/libs/linux-bzimage/setup/Cargo.toml @@ -16,16 +16,16 @@ path = "src/main.rs" cfg-if = "1.0.0" core2 = { version = "0.4.0", default-features = false, features = ["nightly"] } libflate = { version = "2.1.0", default-features = false } -linux-boot-params = { path = "../boot-params", version = "0.1.0" } +linux-boot-params = { version = "0.1.0", path = "../boot-params" } uart_16550 = "0.3.0" -xmas-elf = "0.8.0" +xmas-elf = "0.9.1" [target.x86_64-unknown-none.dependencies] bitflags = "2.4.1" log = "0.4.20" -uefi = "0.26.0" -uefi-services = "0.23.0" -x86_64 = "0.14.11" +uefi = { version = "0.32.0", features = ["global_allocator", "panic_handler", "logger", "qemu"]} +uefi-raw = "0.8.0" +x86_64 = "0.15.1" [features] default = [] diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -2,19 +2,17 @@ use linux_boot_params::BootParams; use uefi::{ - data_types::Handle, + boot::{exit_boot_services, open_protocol_exclusive}, + mem::memory_map::{MemoryMap, MemoryMapOwned}, + prelude::*, proto::loaded_image::LoadedImage, - table::{ - boot::MemoryMap, - cfg::{ACPI2_GUID, ACPI_GUID}, - Boot, Runtime, SystemTable, - }, }; +use uefi_raw::table::system::SystemTable; use super::{ decoder::decode_payload, paging::{Ia32eFlags, PageNumber, PageTableCreator}, - relocation::apply_rela_dyn_relocations, + relocation::apply_rela_relocations, }; // Suppress warnings since using todo!. diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -2,19 +2,17 @@ use linux_boot_params::BootParams; use uefi::{ - data_types::Handle, + boot::{exit_boot_services, open_protocol_exclusive}, + mem::memory_map::{MemoryMap, MemoryMapOwned}, + prelude::*, proto::loaded_image::LoadedImage, - table::{ - boot::MemoryMap, - cfg::{ACPI2_GUID, ACPI_GUID}, - Boot, Runtime, SystemTable, - }, }; +use uefi_raw::table::system::SystemTable; use super::{ decoder::decode_payload, paging::{Ia32eFlags, PageNumber, PageTableCreator}, - relocation::apply_rela_dyn_relocations, + relocation::apply_rela_relocations, }; // Suppress warnings since using todo!. diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -22,77 +20,92 @@ use super::{ #[allow(unused_variables)] #[allow(clippy::diverging_sub_expression)] #[export_name = "efi_stub_entry"] -extern "sysv64" fn efi_stub_entry(handle: Handle, mut system_table: SystemTable<Boot>) -> ! { - unsafe { - system_table.boot_services().set_image_handle(handle); - } - uefi_services::init(&mut system_table).unwrap(); +extern "sysv64" fn efi_stub_entry(handle: Handle, system_table: *const SystemTable) -> ! { + // SAFETY: handle and system_table are valid pointers. It is only called once. + unsafe { system_init(handle, system_table) }; + + uefi::helpers::init().unwrap(); let boot_params = todo!("Use EFI boot services to fill boot params"); - efi_phase_boot(handle, system_table, boot_params); + efi_phase_boot(boot_params); } #[export_name = "efi_handover_entry"] extern "sysv64" fn efi_handover_entry( handle: Handle, - mut system_table: SystemTable<Boot>, + system_table: *const SystemTable, boot_params_ptr: *mut BootParams, ) -> ! { - unsafe { - system_table.boot_services().set_image_handle(handle); - } - uefi_services::init(&mut system_table).unwrap(); + // SAFETY: handle and system_table are valid pointers. It is only called once. + unsafe { system_init(handle, system_table) }; + + uefi::helpers::init().unwrap(); // SAFETY: boot_params is a valid pointer. let boot_params = unsafe { &mut *boot_params_ptr }; - efi_phase_boot(handle, system_table, boot_params) + efi_phase_boot(boot_params) } -fn efi_phase_boot( - handle: Handle, - system_table: SystemTable<Boot>, - boot_params: &mut BootParams, -) -> ! { - // SAFETY: this init function is only called once. - unsafe { crate::console::init() }; +/// Initialize the system. +/// +/// # Safety +/// +/// This function should be called only once with valid parameters before all +/// operations. +unsafe fn system_init(handle: Handle, system_table: *const SystemTable) { + // SAFETY: This is the right time to initialize the console and it is only + // called once here before all console operations. + unsafe { + crate::console::init(); + } - // SAFETY: this is the right time to apply relocations. - unsafe { apply_rela_dyn_relocations() }; + // SAFETY: This is the right time to apply relocations. + unsafe { apply_rela_relocations() }; - uefi_services::println!("[EFI stub] Relocations applied."); + // SAFETY: The handle and system_table are valid pointers. They are passed + // from the UEFI firmware. They are only called once. + unsafe { + boot::set_image_handle(handle); + uefi::table::set_system_table(system_table); + } +} + +fn efi_phase_boot(boot_params: &mut BootParams) -> ! { + uefi::println!("[EFI stub] Relocations applied."); + uefi::println!( + "[EFI stub] Stub loaded at {:#x?}", + crate::x86::get_image_loaded_offset() + ); // Fill the boot params with the RSDP address if it is not provided. if boot_params.acpi_rsdp_addr == 0 { - boot_params.acpi_rsdp_addr = get_rsdp_addr(&system_table); + boot_params.acpi_rsdp_addr = get_rsdp_addr(); } // Load the kernel payload to memory. let payload = crate::get_payload(boot_params); let kernel = decode_payload(payload); - uefi_services::println!("[EFI stub] Loading payload."); + uefi::println!("[EFI stub] Loading payload."); crate::loader::load_elf(&kernel); - uefi_services::println!("[EFI stub] Exiting EFI boot services."); + uefi::println!("[EFI stub] Exiting EFI boot services."); let memory_type = { - let boot_services = system_table.boot_services(); - let Ok(loaded_image) = boot_services.open_protocol_exclusive::<LoadedImage>(handle) else { + let Ok(loaded_image) = open_protocol_exclusive::<LoadedImage>(boot::image_handle()) else { panic!("Failed to open LoadedImage protocol"); }; loaded_image.data_type() }; - let (system_table, memory_map) = system_table.exit_boot_services(memory_type); + // SAFETY: All allocations in the boot services phase are not used after + // this point. + let memory_map = unsafe { exit_boot_services(memory_type) }; - efi_phase_runtime(system_table, memory_map, boot_params); + efi_phase_runtime(memory_map, boot_params); } -fn efi_phase_runtime( - _system_table: SystemTable<Runtime>, - memory_map: MemoryMap<'static>, - boot_params: &mut BootParams, -) -> ! { +fn efi_phase_runtime(memory_map: MemoryMapOwned, boot_params: &mut BootParams) -> ! { unsafe { crate::console::print_str("[EFI stub] Entered runtime services.\n"); } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -22,77 +20,92 @@ use super::{ #[allow(unused_variables)] #[allow(clippy::diverging_sub_expression)] #[export_name = "efi_stub_entry"] -extern "sysv64" fn efi_stub_entry(handle: Handle, mut system_table: SystemTable<Boot>) -> ! { - unsafe { - system_table.boot_services().set_image_handle(handle); - } - uefi_services::init(&mut system_table).unwrap(); +extern "sysv64" fn efi_stub_entry(handle: Handle, system_table: *const SystemTable) -> ! { + // SAFETY: handle and system_table are valid pointers. It is only called once. + unsafe { system_init(handle, system_table) }; + + uefi::helpers::init().unwrap(); let boot_params = todo!("Use EFI boot services to fill boot params"); - efi_phase_boot(handle, system_table, boot_params); + efi_phase_boot(boot_params); } #[export_name = "efi_handover_entry"] extern "sysv64" fn efi_handover_entry( handle: Handle, - mut system_table: SystemTable<Boot>, + system_table: *const SystemTable, boot_params_ptr: *mut BootParams, ) -> ! { - unsafe { - system_table.boot_services().set_image_handle(handle); - } - uefi_services::init(&mut system_table).unwrap(); + // SAFETY: handle and system_table are valid pointers. It is only called once. + unsafe { system_init(handle, system_table) }; + + uefi::helpers::init().unwrap(); // SAFETY: boot_params is a valid pointer. let boot_params = unsafe { &mut *boot_params_ptr }; - efi_phase_boot(handle, system_table, boot_params) + efi_phase_boot(boot_params) } -fn efi_phase_boot( - handle: Handle, - system_table: SystemTable<Boot>, - boot_params: &mut BootParams, -) -> ! { - // SAFETY: this init function is only called once. - unsafe { crate::console::init() }; +/// Initialize the system. +/// +/// # Safety +/// +/// This function should be called only once with valid parameters before all +/// operations. +unsafe fn system_init(handle: Handle, system_table: *const SystemTable) { + // SAFETY: This is the right time to initialize the console and it is only + // called once here before all console operations. + unsafe { + crate::console::init(); + } - // SAFETY: this is the right time to apply relocations. - unsafe { apply_rela_dyn_relocations() }; + // SAFETY: This is the right time to apply relocations. + unsafe { apply_rela_relocations() }; - uefi_services::println!("[EFI stub] Relocations applied."); + // SAFETY: The handle and system_table are valid pointers. They are passed + // from the UEFI firmware. They are only called once. + unsafe { + boot::set_image_handle(handle); + uefi::table::set_system_table(system_table); + } +} + +fn efi_phase_boot(boot_params: &mut BootParams) -> ! { + uefi::println!("[EFI stub] Relocations applied."); + uefi::println!( + "[EFI stub] Stub loaded at {:#x?}", + crate::x86::get_image_loaded_offset() + ); // Fill the boot params with the RSDP address if it is not provided. if boot_params.acpi_rsdp_addr == 0 { - boot_params.acpi_rsdp_addr = get_rsdp_addr(&system_table); + boot_params.acpi_rsdp_addr = get_rsdp_addr(); } // Load the kernel payload to memory. let payload = crate::get_payload(boot_params); let kernel = decode_payload(payload); - uefi_services::println!("[EFI stub] Loading payload."); + uefi::println!("[EFI stub] Loading payload."); crate::loader::load_elf(&kernel); - uefi_services::println!("[EFI stub] Exiting EFI boot services."); + uefi::println!("[EFI stub] Exiting EFI boot services."); let memory_type = { - let boot_services = system_table.boot_services(); - let Ok(loaded_image) = boot_services.open_protocol_exclusive::<LoadedImage>(handle) else { + let Ok(loaded_image) = open_protocol_exclusive::<LoadedImage>(boot::image_handle()) else { panic!("Failed to open LoadedImage protocol"); }; loaded_image.data_type() }; - let (system_table, memory_map) = system_table.exit_boot_services(memory_type); + // SAFETY: All allocations in the boot services phase are not used after + // this point. + let memory_map = unsafe { exit_boot_services(memory_type) }; - efi_phase_runtime(system_table, memory_map, boot_params); + efi_phase_runtime(memory_map, boot_params); } -fn efi_phase_runtime( - _system_table: SystemTable<Runtime>, - memory_map: MemoryMap<'static>, - boot_params: &mut BootParams, -) -> ! { +fn efi_phase_runtime(memory_map: MemoryMapOwned, boot_params: &mut BootParams) -> ! { unsafe { crate::console::print_str("[EFI stub] Entered runtime services.\n"); } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -218,16 +231,18 @@ fn efi_phase_runtime( } } -fn get_rsdp_addr(boot_table: &SystemTable<Boot>) -> u64 { - let config_table = boot_table.config_table(); - for entry in config_table { - // Prefer ACPI2 over ACPI. - if entry.guid == ACPI2_GUID { - return entry.address as usize as u64; - } - if entry.guid == ACPI_GUID { - return entry.address as usize as u64; +fn get_rsdp_addr() -> u64 { + use uefi::table::cfg::{ACPI2_GUID, ACPI_GUID}; + uefi::system::with_config_table(|table| { + for entry in table { + // Prefer ACPI2 over ACPI. + if entry.guid == ACPI2_GUID { + return entry.address as usize as u64; + } + if entry.guid == ACPI_GUID { + return entry.address as usize as u64; + } } - } - panic!("ACPI RSDP not found"); + panic!("ACPI RSDP not found"); + }) } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -218,16 +231,18 @@ fn efi_phase_runtime( } } -fn get_rsdp_addr(boot_table: &SystemTable<Boot>) -> u64 { - let config_table = boot_table.config_table(); - for entry in config_table { - // Prefer ACPI2 over ACPI. - if entry.guid == ACPI2_GUID { - return entry.address as usize as u64; - } - if entry.guid == ACPI_GUID { - return entry.address as usize as u64; +fn get_rsdp_addr() -> u64 { + use uefi::table::cfg::{ACPI2_GUID, ACPI_GUID}; + uefi::system::with_config_table(|table| { + for entry in table { + // Prefer ACPI2 over ACPI. + if entry.guid == ACPI2_GUID { + return entry.address as usize as u64; + } + if entry.guid == ACPI_GUID { + return entry.address as usize as u64; + } } - } - panic!("ACPI RSDP not found"); + panic!("ACPI RSDP not found"); + }) } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld @@ -40,15 +40,11 @@ SECTIONS .eh_frame_hdr : { *(.eh_frame_hdr .eh_frame_hdr.*) } - - .rela.dyn : { - PROVIDE(__rela_dyn_start = .); - *(.rela.dyn .rela.dyn.*) - PROVIDE(__rela_dyn_end = .); - } - - .rela.plt : { - *(.rela.plt .rela.plt.*) + + .rela : { + PROVIDE(__rela_start = .); + *(.rela .rela.*) + PROVIDE(__rela_end = .); } .comment : { *(.comment) } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld @@ -40,15 +40,11 @@ SECTIONS .eh_frame_hdr : { *(.eh_frame_hdr .eh_frame_hdr.*) } - - .rela.dyn : { - PROVIDE(__rela_dyn_start = .); - *(.rela.dyn .rela.dyn.*) - PROVIDE(__rela_dyn_end = .); - } - - .rela.plt : { - *(.rela.plt .rela.plt.*) + + .rela : { + PROVIDE(__rela_start = .); + *(.rela .rela.*) + PROVIDE(__rela_end = .); } .comment : { *(.comment) } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs @@ -18,6 +18,7 @@ const TABLE_ENTRY_COUNT: usize = 512; bitflags::bitflags! { #[derive(Clone, Copy)] + #[repr(C)] pub struct Ia32eFlags: u64 { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs @@ -18,6 +18,7 @@ const TABLE_ENTRY_COUNT: usize = 512; bitflags::bitflags! { #[derive(Clone, Copy)] + #[repr(C)] pub struct Ia32eFlags: u64 { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs @@ -32,9 +33,11 @@ bitflags::bitflags! { } } +#[repr(C)] pub struct Ia32eEntry(u64); /// The table in the IA32E paging specification that occupies a physical page frame. +#[repr(C)] pub struct Ia32eTable([Ia32eEntry; TABLE_ENTRY_COUNT]); /// A page number. It could be either a physical page number or a virtual page number. diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs @@ -32,9 +33,11 @@ bitflags::bitflags! { } } +#[repr(C)] pub struct Ia32eEntry(u64); /// The table in the IA32E paging specification that occupies a physical page frame. +#[repr(C)] pub struct Ia32eTable([Ia32eEntry; TABLE_ENTRY_COUNT]); /// A page number. It could be either a physical page number or a virtual page number. diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs @@ -2,62 +2,68 @@ use crate::x86::get_image_loaded_offset; -struct Elf64Rela { - r_offset: u64, - r_info: u64, - r_addend: i64, -} +/// Apply the relocations in the `.rela.*` sections. +/// +/// The function will enable dyn Trait objects to work since they rely on +/// vtable pointers. Vtable won't work without relocations. +/// +/// We currently support R_X86_64_RELATIVE relocations only. And this type of +/// relocation seems to be the only existing type if we compile Rust code to +/// PIE ELF binaries. +/// +/// # Safety +/// +/// This function will modify the memory pointed by the relocations. And the +/// Rust memory safety mechanisms are not aware of these kind of modification. +/// Failure to do relocations will cause `dyn Trait` objects to break. +pub unsafe fn apply_rela_relocations() { + use core::arch::asm; + let image_loaded_offset = get_image_loaded_offset(); + + let mut start: usize; + let end: usize; -fn get_rela_array() -> &'static [Elf64Rela] { - extern "C" { - fn __rela_dyn_start(); - fn __rela_dyn_end(); + unsafe { + asm!( + "lea {}, [rip + __rela_start]", + out(reg) start, + ); + asm!( + "lea {}, [rip + __rela_end]", + out(reg) end, + ); } - let start = __rela_dyn_start as *const Elf64Rela; - let end = __rela_dyn_end as *const Elf64Rela; - let len = unsafe { end.offset_from(start) } as usize; + #[cfg(feature = "debug_print")] unsafe { use crate::console::{print_hex, print_str}; - print_str("[EFI stub debug] .rela.dyn section size = "); - print_hex(len as u64); - print_str("; __rela_dyn_start = "); + print_str("[EFI stub debug] loaded offset = "); + print_hex(image_loaded_offset as u64); + print_str("\n"); + print_str("[EFI stub debug] .rela section start = "); print_hex(start as u64); - print_str(", __rela_dyn_end = "); + print_str(", end = "); print_hex(end as u64); print_str("\n"); } - // SAFETY: the linker will ensure that the symbols are valid. - unsafe { core::slice::from_raw_parts(start, len) } -} -const R_X86_64_RELATIVE: u32 = 8; + #[cfg(feature = "debug_print")] + let mut count = 0; -/// Apply the relocations in the `.rela.dyn` section. -/// -/// The function will enable dyn Trait objects to work since they rely on vtable pointers. Vtable -/// won't work without relocations. -/// -/// We currently support R_X86_64_RELATIVE relocations only. And this type of relocation seems to -/// be the only existing type if we compile Rust code to PIC ELF binaries. -/// -/// # Safety -/// This function will modify the memory pointed by the relocations. And the Rust memory safety -/// mechanisms are not aware of these kind of modification. Failure to do relocations will cause -/// dyn Trait objects to break. -pub unsafe fn apply_rela_dyn_relocations() { - let image_loaded_offset = get_image_loaded_offset(); - let relas = get_rela_array(); - for rela in relas { + while start < end { + let rela = (start as *const Elf64Rela).read_volatile(); let r_type = (rela.r_info & 0xffffffff) as u32; let _r_sym = (rela.r_info >> 32) as usize; - let r_addend = rela.r_addend; - let r_offset = rela.r_offset as usize; - let target = (image_loaded_offset + r_offset as isize) as usize; + let r_addend = rela.r_addend as isize; + let r_offset = rela.r_offset as isize; + let target = image_loaded_offset.wrapping_add(r_offset) as usize; #[cfg(feature = "debug_print")] unsafe { use crate::console::{print_hex, print_str}; - print_str("[EFI stub debug] Applying relocation at offset "); + count += 1; + print_str("[EFI stub debug] Applying relocation #"); + print_hex(count as u64); + print_str(" at offset "); print_hex(r_offset as u64); print_str(", type = "); print_hex(r_type as u64); diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs @@ -2,62 +2,68 @@ use crate::x86::get_image_loaded_offset; -struct Elf64Rela { - r_offset: u64, - r_info: u64, - r_addend: i64, -} +/// Apply the relocations in the `.rela.*` sections. +/// +/// The function will enable dyn Trait objects to work since they rely on +/// vtable pointers. Vtable won't work without relocations. +/// +/// We currently support R_X86_64_RELATIVE relocations only. And this type of +/// relocation seems to be the only existing type if we compile Rust code to +/// PIE ELF binaries. +/// +/// # Safety +/// +/// This function will modify the memory pointed by the relocations. And the +/// Rust memory safety mechanisms are not aware of these kind of modification. +/// Failure to do relocations will cause `dyn Trait` objects to break. +pub unsafe fn apply_rela_relocations() { + use core::arch::asm; + let image_loaded_offset = get_image_loaded_offset(); + + let mut start: usize; + let end: usize; -fn get_rela_array() -> &'static [Elf64Rela] { - extern "C" { - fn __rela_dyn_start(); - fn __rela_dyn_end(); + unsafe { + asm!( + "lea {}, [rip + __rela_start]", + out(reg) start, + ); + asm!( + "lea {}, [rip + __rela_end]", + out(reg) end, + ); } - let start = __rela_dyn_start as *const Elf64Rela; - let end = __rela_dyn_end as *const Elf64Rela; - let len = unsafe { end.offset_from(start) } as usize; + #[cfg(feature = "debug_print")] unsafe { use crate::console::{print_hex, print_str}; - print_str("[EFI stub debug] .rela.dyn section size = "); - print_hex(len as u64); - print_str("; __rela_dyn_start = "); + print_str("[EFI stub debug] loaded offset = "); + print_hex(image_loaded_offset as u64); + print_str("\n"); + print_str("[EFI stub debug] .rela section start = "); print_hex(start as u64); - print_str(", __rela_dyn_end = "); + print_str(", end = "); print_hex(end as u64); print_str("\n"); } - // SAFETY: the linker will ensure that the symbols are valid. - unsafe { core::slice::from_raw_parts(start, len) } -} -const R_X86_64_RELATIVE: u32 = 8; + #[cfg(feature = "debug_print")] + let mut count = 0; -/// Apply the relocations in the `.rela.dyn` section. -/// -/// The function will enable dyn Trait objects to work since they rely on vtable pointers. Vtable -/// won't work without relocations. -/// -/// We currently support R_X86_64_RELATIVE relocations only. And this type of relocation seems to -/// be the only existing type if we compile Rust code to PIC ELF binaries. -/// -/// # Safety -/// This function will modify the memory pointed by the relocations. And the Rust memory safety -/// mechanisms are not aware of these kind of modification. Failure to do relocations will cause -/// dyn Trait objects to break. -pub unsafe fn apply_rela_dyn_relocations() { - let image_loaded_offset = get_image_loaded_offset(); - let relas = get_rela_array(); - for rela in relas { + while start < end { + let rela = (start as *const Elf64Rela).read_volatile(); let r_type = (rela.r_info & 0xffffffff) as u32; let _r_sym = (rela.r_info >> 32) as usize; - let r_addend = rela.r_addend; - let r_offset = rela.r_offset as usize; - let target = (image_loaded_offset + r_offset as isize) as usize; + let r_addend = rela.r_addend as isize; + let r_offset = rela.r_offset as isize; + let target = image_loaded_offset.wrapping_add(r_offset) as usize; #[cfg(feature = "debug_print")] unsafe { use crate::console::{print_hex, print_str}; - print_str("[EFI stub debug] Applying relocation at offset "); + count += 1; + print_str("[EFI stub debug] Applying relocation #"); + print_hex(count as u64); + print_str(" at offset "); print_hex(r_offset as u64); print_str(", type = "); print_hex(r_type as u64); diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs @@ -67,12 +73,23 @@ pub unsafe fn apply_rela_dyn_relocations() { } match r_type { R_X86_64_RELATIVE => { - let value = (image_loaded_offset as i64 + r_addend) as usize; - *(target as *mut usize) = value; + let value = image_loaded_offset.wrapping_add(r_addend) as usize; + (target as *mut usize).write(value); } _ => { panic!("Unknown relocation type: {}", r_type); } } + start = start.wrapping_add(core::mem::size_of::<Elf64Rela>()); } } + +const R_X86_64_RELATIVE: u32 = 8; + +#[derive(Copy, Clone)] +#[repr(C)] +struct Elf64Rela { + r_offset: u64, + r_info: u64, + r_addend: i64, +} diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs @@ -67,12 +73,23 @@ pub unsafe fn apply_rela_dyn_relocations() { } match r_type { R_X86_64_RELATIVE => { - let value = (image_loaded_offset as i64 + r_addend) as usize; - *(target as *mut usize) = value; + let value = image_loaded_offset.wrapping_add(r_addend) as usize; + (target as *mut usize).write(value); } _ => { panic!("Unknown relocation type: {}", r_type); } } + start = start.wrapping_add(core::mem::size_of::<Elf64Rela>()); } } + +const R_X86_64_RELATIVE: u32 = 8; + +#[derive(Copy, Clone)] +#[repr(C)] +struct Elf64Rela { + r_offset: u64, + r_info: u64, + r_addend: i64, +} diff --git a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs @@ -16,10 +16,23 @@ const START_OF_SETUP32_VA: usize = 0x100000; /// The setup is a position-independent executable. We can get the loaded base /// address from the symbol. #[inline] -#[allow(clippy::fn_to_numeric_cast)] pub fn get_image_loaded_offset() -> isize { - extern "C" { - fn start_of_setup32(); + let address_of_start: usize; + #[cfg(target_arch = "x86_64")] + unsafe { + core::arch::asm!( + "lea {}, [rip + start_of_setup32]", + out(reg) address_of_start, + options(pure, nomem, nostack) + ); } - start_of_setup32 as isize - START_OF_SETUP32_VA as isize + #[cfg(target_arch = "x86")] + unsafe { + core::arch::asm!( + "lea {}, [start_of_setup32]", + out(reg) address_of_start, + options(pure, nomem, nostack) + ); + } + address_of_start as isize - START_OF_SETUP32_VA as isize } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs @@ -16,10 +16,23 @@ const START_OF_SETUP32_VA: usize = 0x100000; /// The setup is a position-independent executable. We can get the loaded base /// address from the symbol. #[inline] -#[allow(clippy::fn_to_numeric_cast)] pub fn get_image_loaded_offset() -> isize { - extern "C" { - fn start_of_setup32(); + let address_of_start: usize; + #[cfg(target_arch = "x86_64")] + unsafe { + core::arch::asm!( + "lea {}, [rip + start_of_setup32]", + out(reg) address_of_start, + options(pure, nomem, nostack) + ); } - start_of_setup32 as isize - START_OF_SETUP32_VA as isize + #[cfg(target_arch = "x86")] + unsafe { + core::arch::asm!( + "lea {}, [start_of_setup32]", + out(reg) address_of_start, + options(pure, nomem, nostack) + ); + } + address_of_start as isize - START_OF_SETUP32_VA as isize } diff --git a/tools/bump_version.sh b/tools/bump_version.sh --- a/tools/bump_version.sh +++ b/tools/bump_version.sh @@ -106,6 +106,9 @@ DOCS_DIR=${ASTER_SRC_DIR}/docs OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml OSTD_TEST_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-test/Cargo.toml OSTD_MACROS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-macros/Cargo.toml +LINUX_BOOT_PARAMS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/boot-params/Cargo.toml +LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/builder/Cargo.toml +LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/setup/Cargo.toml OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml OSDK_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml VERSION_PATH=${ASTER_SRC_DIR}/VERSION diff --git a/tools/bump_version.sh b/tools/bump_version.sh --- a/tools/bump_version.sh +++ b/tools/bump_version.sh @@ -125,11 +128,17 @@ new_version=$(bump_version ${current_version}) update_package_version ${OSTD_TEST_CARGO_TOML_PATH} update_package_version ${OSTD_MACROS_CARGO_TOML_PATH} update_package_version ${OSTD_CARGO_TOML_PATH} +update_package_version ${LINUX_BOOT_PARAMS_CARGO_TOML_PATH} +update_package_version ${LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH} +update_package_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-test +update_dep_version ${OSTD_CARGO_TOML_PATH} linux-boot-params update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-macros +update_dep_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} linux-boot-params update_package_version ${OSDK_CARGO_TOML_PATH} update_package_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} update_dep_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} ostd +update_dep_version ${OSDK_CARGO_TOML_PATH} linux-bzimage-builder # Automatically bump Cargo.lock files cargo update -p aster-nix --precise $new_version # For Cargo.lock diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh --- a/tools/github_workflows/publish_osdk_and_ostd.sh +++ b/tools/github_workflows/publish_osdk_and_ostd.sh @@ -60,6 +60,8 @@ do_publish_for() { } do_publish_for osdk +do_publish_for ostd/libs/linux-bzimage/build +do_publish_for ostd/libs/linux-bzimage/boot-params # All supported targets of OSTD, this array should keep consistent with # `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`. diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh --- a/tools/github_workflows/publish_osdk_and_ostd.sh +++ b/tools/github_workflows/publish_osdk_and_ostd.sh @@ -60,6 +60,8 @@ do_publish_for() { } do_publish_for osdk +do_publish_for ostd/libs/linux-bzimage/build +do_publish_for ostd/libs/linux-bzimage/boot-params # All supported targets of OSTD, this array should keep consistent with # `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`. diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh --- a/tools/github_workflows/publish_osdk_and_ostd.sh +++ b/tools/github_workflows/publish_osdk_and_ostd.sh @@ -67,6 +69,7 @@ TARGETS="x86_64-unknown-none" for TARGET in $TARGETS; do do_publish_for ostd/libs/ostd-macros $TARGET do_publish_for ostd/libs/ostd-test $TARGET + do_publish_for ostd/libs/linux-bzimage/setup $TARGET do_publish_for ostd $TARGET do_publish_for osdk/test-kernel $TARGET
2024-10-14T14:03:58Z
9da6af03943c15456cdfd781021820a7da78ea40
asterinas/asterinas
"diff --git a/Makefile b/Makefile\n--- a/Makefile\n+++ b/Makefile\n@@ -226,6 +226,8 @@ ktest: initra(...TRUNCATED)
[ "1399", "919" ]
0.9
96efd620072a0cbdccc95b58901894111f17bb3a
"Silently failed ktest in OSTD: untracked_map_unmap\n<!-- Thank you for taking the time to report a (...TRUNCATED)
asterinas__asterinas-1372
1,372
"diff --git a/Makefile b/Makefile\n--- a/Makefile\n+++ b/Makefile\n@@ -226,6 +226,8 @@ ktest: initra(...TRUNCATED)
"\nI've already checked out your PR #918 addressing issues raised in this RFC, and find it convincin(...TRUNCATED)
2024-09-24T09:24:48Z
9da6af03943c15456cdfd781021820a7da78ea40
asterinas/asterinas
"diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs\n--- a/ostd/src/mm/pag(...TRUNCATED)
[ "919" ]
0.8
ae4ac384713e63232b74915593ebdef680049d31
"[RFC] Safety model about the page tables\n# Background\r\n\r\nThis issue discusses the internal API(...TRUNCATED)
asterinas__asterinas-1369
1,369
"diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs\n--- a/kernel/src/vm/vmar/mod.rs(...TRUNCATED)
"I've already checked out your PR #918 addressing issues raised in this RFC, and find it convincing.(...TRUNCATED)
2024-09-23T14:17:42Z
ae4ac384713e63232b74915593ebdef680049d31
asterinas/asterinas
"diff --git a/Makefile b/Makefile\n--- a/Makefile\n+++ b/Makefile\n@@ -16,7 +17,14 @@ LOG_LEVEL ?= e(...TRUNCATED)
[ "964" ]
0.8
f7932595125a0bba8230b5f8d3b110c687d6f3b2
"[Perf Guide] Flame graph scripts on Asterinas\n[Flame graph](https://github.com/brendangregg/FlameG(...TRUNCATED)
asterinas__asterinas-1362
1,362
"diff --git a/Makefile b/Makefile\n--- a/Makefile\n+++ b/Makefile\n@@ -1,13 +1,14 @@\n # SPDX-Licens(...TRUNCATED)
2024-09-21T13:48:03Z
ae4ac384713e63232b74915593ebdef680049d31
asterinas/asterinas
"diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs\n--- a/kernel/src/lib.rs\n+++ b/kernel/src/lib.r(...TRUNCATED)
[ "1244" ]
0.8
42e28763c59202486af4298d5305e5c5e5ab9b54
"Reachable unwrap panic in `read_clock()`\n### Describe the bug\r\nThere is a reachable unwrap panic(...TRUNCATED)
asterinas__asterinas-1328
1,328
"diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs\n--- a/kernel/src/lib.rs\n+++ b/kernel/src/lib.r(...TRUNCATED)
2024-09-12T06:03:09Z
ae4ac384713e63232b74915593ebdef680049d31
asterinas/asterinas
"diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs\n--- a/ostd/src/sync/mutex.rs\n+++ b/o(...TRUNCATED)
[ "1274" ]
0.8
963874471284ed014b76d268d933b6d13073c2cc
"Potential mutex lock bug leading to multiple threads entering critical section\n### Describe the bu(...TRUNCATED)
asterinas__asterinas-1279
1,279
"diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs\n--- a/ostd/src/sync/mutex.rs\n+++ b/o(...TRUNCATED)
"The bug introduced in this commit: https://github.com/asterinas/asterinas/commit/d15b4d9115cf334902(...TRUNCATED)
2024-09-02T06:56:20Z
ae4ac384713e63232b74915593ebdef680049d31
asterinas/asterinas
"diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs\n--- a/osdk/src/config/manif(...TRUNCATED)
[ "1237" ]
0.8
539984bbed414969b0c40cf181a10e9341ed2359
"OSDK should not check the options that have been overridden\n### Describe the bug\r\n\r\nOSDK will (...TRUNCATED)
asterinas__asterinas-1256
1,256
"diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock\n--- a/osdk/Cargo.lock\n+++ b/osdk/Cargo.lock\n@@ -1(...TRUNCATED)
2024-08-28T11:24:08Z
ae4ac384713e63232b74915593ebdef680049d31
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1