Mount umount2 linux compat#1059
Conversation
# Conflicts: # components/axfs-ng-vfs/src/mount.rs
…e-os#887) * fix(axcpu): save SP in aarch64 TrapFrame for kprobe correctness - trap.S: SAVE_REGS saves original SP (sp_before_sub) into offset 33*8 - context.rs: rename __pad to sp with documentation - uspace.rs: initialize sp to 0, remove PAD_MAGIC - kprobe.rs: use tf.sp instead of hardcoded 0 for aarch64 PtRegs Before this fix, aarch64 TrapFrame did not store SP, causing all kprobe handlers relying on SP to get 0. Now the original SP at the time of exception is properly preserved in the TrapFrame structure. * fix(axcpu): address review feedback for PR rcore-os#887 - Remove kprobe.rs dead code (not integrated, missing mod declaration and kprobe crate dependency; will be submitted in a separate PR) - Add documentation comment on TrapFrame.sp explaining it is read-only: the actual SP is restored by RESTORE_REGS via 'add sp, sp, #trapframe_size', not from this field - Add missing doc comment on UserContext::new() to satisfy missing_docs lint
* feat(starry): add userspace test for prlimit64 syscall - Fix error priority: check pid before resource, matching Linux (ESRCH before EINVAL for invalid pid + bad resource). - Add hard-limit raise protection via CAP_SYS_RESOURCE. Unprivileged processes can no longer raise rlim_max arbitrarily. - Add has_cap_sys_resource() to Cred, following the existing has_cap_* pattern. Document that all capability checks are euid==0 placeholders until a fine-grained bitmap is added. - Add comprehensive prlimit64 test covering all 14 RLIMIT_* resources * fix: add the test that was mistakenly deleted * fix: add the riscv tests that were mistakenly deleted --------- Co-authored-by: 周睿 <zrufo747@outlook.com>
* feat(starry-kernel): add inotifywait support * feat(starry-kernel): expand inotify events
* 5.19 * style(starry): format sendfile changes * 完善了建议 * 改 * chore(starry): ignore generated sendfile test artifacts * 1 * 2 * again * 1 * finish-sendfile * fixed pipe * 完善了建议 * fix(starry): remove generated qemu logs * 删除了let src = ... * 格式问题,删除一个空行 * 完成了splic * 把 warning 当 error * 格式问题 * 还是格式问题 * 补充了测试,删除了测试数据 * 修改了测试路径,补充了测试 * copy file range没有bug * 改了一下copyfilerange * 格式问题 * 还是格式问题 * 增加了注释,检查了格式问题
* test(syscall): add sys_membarrier test for StarryOS * feat(starryos): Implement sys_membarrier and rseq syscall enhancements in StarryOS - Added support for sys_membarrier with various commands including global and private expedited registration. - Introduced rseq syscall with argument validation and lifecycle management for per-thread restartable sequences. - Updated Thread and ProcessData structures to maintain rseq and membarrier states. - Enhanced test suite for sys_membarrier and rseq to ensure compliance with expected behaviors. This commit improves synchronization mechanisms in StarryOS, aligning with Linux semantics. --------- Co-authored-by: Ya2yo <yayoy0015@gmail.com>
…ore-os#903) * fix(starry-kernel): align file sync syscalls with Linux semantics * test(starryos): resolve syscall grouped runner conflict
…ory writes (rcore-os#909) Several syscall sites still obtain a direct `&mut` reference into user memory through get_as_mut / get_as_mut_slice and write through it outside of access_user_memory(). Examples that remain on the current upstream/dev tree include sys_select (io_mpx/select.rs), the network sendmsg / recvmsg path (net/io.rs), event-device ioctls (pseudofs/dev/event.rs) and the file-lock ioctls (fs/lock.rs). When a concurrent fork(clone_map) re-marks the underlying COW pages read-only between check_region() and the kernel-mode write, the write triggers a #PF (present + WRITE bit set) whose RIP is in kernel text and has no fixup-table entry. The previous handler returned early on !is_accessing_user_memory(), turning this into an unrecoverable panic. Extend handle_page_fault so a kernel-mode fault on a user-space address goes through the regular aspace.handle_page_fault() path (which invokes the COW backend) just like a user-mode write would. Two guards keep the extension safe: 1. Reject fault addresses outside USER_SPACE_BASE..USER_SPACE_END so genuine kernel-text / kernel-stack faults still bubble up unchanged. 2. Bail out if the current thread already holds the aspace lock, which prevents a recursive lock acquisition / deadlock when a fault occurs inside aspace.lock().handle_page_fault() itself. Co-authored-by: StarryOS Fix <fix@starryos.dev>
* feat(docs): 添加 rdrive + rdif 驱动框架文档,记录宿主物理设备重构目标 * Add RK3588 PCIe driver support and related components - Implemented the RK3588 PCIe host driver in `resources.rs`, handling GPIO resets, memory mapping, and configuration. - Created slot drivers for multiple PCIe slots in `slots.rs`, enabling dynamic probing of PCIe devices. - Added memory window programming logic in `windows.rs`, including configuration window detection and logging of resources. - Introduced a new `PlatformVsockDevice` in `vsock.rs` for managing Virtio socket devices, with registration and device handling. - Updated `virtio.rs` to use the new Virtio driver interface. - Modified the Clippy crates list to include new dependencies for the added components. - Adjusted build configuration to remove unnecessary Virtio net feature for the AArch64 platform. * Add DMA and MMIO support to axklib - Updated Cargo.lock and Cargo.toml to include dma-api and mmio-api dependencies. - Implemented DMA operations in axklib with a new dma.rs file, providing functionality for allocating and managing DMA pages. - Created mmio.rs to handle memory-mapped I/O operations, including ioremap and iounmap functionalities. - Refactored axruntime and various platform drivers to utilize the new DMA and MMIO abstractions, replacing previous implementations. - Removed obsolete DmaImpl struct and related code from drivers, streamlining the DMA handling process. - Ensured compatibility with existing driver interfaces by adapting to the new DMA and MMIO APIs. * Refactor static device management and remove deprecated components - Consolidated static device initialization logic into `devices.rs`. - Introduced `StaticBlockDevice` to handle block device operations. - Removed old static device modules (`block.rs`, `dma.rs`, `virtio.rs`, `virtio_block.rs`) and their associated functionality. - Updated `Cargo.toml` files to remove unused driver dependencies. - Adjusted build configurations to reflect the removal of static device drivers. - Enhanced error handling and device probing for static devices. * Refactor axdriver module structure and update dependencies - Removed the `virtio/input.rs`, `virtio/vsock.rs`, and `vsock.rs` files as they are no longer needed. - Updated `Cargo.toml` files to change dependencies from `ax-driver` to `ax-drivers` for better modularization. - Refactored device initialization in `devices.rs` to utilize the new `ax-drivers` bindings for display, input, net, and vsock devices. - Simplified PCI driver implementations by using the new `ax-drivers` functions for transport and IRQ registration. - Cleaned up the `virtio` and `pci` driver implementations to align with the new structure and removed legacy code. - Updated the `clippy_crates.csv` to include `ax-driver` and `ax-drivers` for linting checks. * Refactor and streamline driver registration and initialization - Removed static driver registration and initialization functions from `init.rs`, `registers.rs`, and `source.rs`. - Updated `ramdisk.rs`, `sdmmc.rs`, `fxmac.rs`, and other driver files to use a simplified registration approach. - Introduced `register_mmio` and `register_ecam_controller` functions for dynamic device registration. - Enhanced the `probe_pci` functions across various drivers to focus solely on PCI device registration. - Removed unnecessary static device descriptors and streamlined the initialization process for static devices. - Updated Cargo.toml files to reflect changes in dependencies and features, including the addition of `sdmmc` and `cvsd`. - Added new driver registration logic in the `riscv64-visionfive2` platform to support SD/MMC devices. * Refactor: Remove obsolete drivers and consolidate functionality - Deleted the `virtio.rs`, `virtio_pci.rs`, `display.rs`, `input.rs`, `serial/mod.rs`, `net/mod.rs`, `usb/mod.rs`, `vsock.rs`, and `pci.rs` files to streamline the driver architecture. - Moved relevant functionality to `ax_drivers` for better modularity and maintainability. - Updated `mod.rs` to reflect the removal of unused modules and adjusted the driver registration process. - Enhanced the `generic_timer.rs` by making `try_init_epoch_offset` public for broader access. - Cleaned up the `lib.rs` to expose necessary components while removing deprecated references. * Refactor: Update dependencies and remove obsolete driver modules * Refactor driver bindings and module structure - Removed the `bindings` module and integrated its contents directly into the respective driver modules (block, display, input, net, vsock). - Created new binding files for block, display, input, net, and vsock drivers to encapsulate their platform-specific device structures and functionalities. - Updated references throughout the codebase to reflect the new module structure, ensuring that all driver implementations correctly utilize the new bindings. - Improved organization and clarity of the driver code by separating concerns and enhancing modularity. * Add PCI and Virtio support across multiple platforms - Updated linker scripts to define driver registration sections for various architectures (x86, RISC-V, Loongarch). - Refactored driver initialization in axplat crates to conditionally include PCI and Virtio drivers based on feature flags. - Introduced new driver modules for RISC-V and x86 platforms to handle Virtio block devices. - Enhanced Cargo.toml files to include necessary dependencies for PCI and Virtio drivers. - Modified initialization routines to ensure proper setup of drivers during platform initialization. - Updated configuration files for QEMU boards to enable PCI and Virtio features. * Refactor driver initialization and static device registration - Removed the `registers.rs` files from various platforms, consolidating the register handling into a new `registers.rs` in the `axruntime` module. - Updated the `init.rs` files across platforms to eliminate direct driver initialization calls, instead relying on a unified `probe_all_devices` function. - Introduced static device registration for various drivers (SD/MMC, PCIe ECAM, VirtIO) using the new static device registration mechanism. - Enhanced the `StaticDeviceDesc` structure to support additional properties like `regs` and `pci_ecam`. - Updated the build scripts to include new static features for drivers. - Adjusted the `DriversIf` trait implementation to provide static device descriptions for platforms. * Enhance feature sets across various build configurations - Updated feature lists in multiple TOML files for aarch64, loongarch64, riscv64gc, and x86_64 architectures to include new hardware abstraction layer (HAL) and driver features. - Added support for PCI, VirtIO block, VirtIO net, and other drivers to improve hardware compatibility and performance. - Adjusted features in the axvisor and starryos test suites to ensure consistency and leverage new capabilities. - Ensured that all configurations now utilize the latest HAL and driver features for enhanced functionality and stability. * 为 virtio-net 驱动添加 ax-kernel-guard 依赖并重构 IRQ 处理逻辑 * 重构 PCI 设备 IRQ 处理逻辑,更新相关驱动以支持新的 IRQ 路由机制 * Refactor feature names in configuration files from "ax-drivers" to "ax-driver" - Updated multiple TOML configuration files across various test suites to change the feature prefix from "ax-drivers" to "ax-driver" for consistency and clarity. - This change affects configurations for platforms including x86_64, aarch64, loongarch64, and riscv64 in both normal and stress test scenarios. - Ensured that all relevant files reflect this naming convention to maintain uniformity across the codebase. * 更新 ax-driver 版本至 0.6.0,并相应修改 CHANGELOG * 在构建配置中添加对 "ax-hal/riscv64-qemu-virt-hv" 的支持 * 重构特性解析逻辑,添加平台特性检查并优化特性列表生成 * 优化文件系统块设备的条件编译,支持非动态平台和特定操作系统 * 移除 qemu 特性中的动态平台支持,优化特性列表 * 优化 Tty 设备的会话管理逻辑,确保终端与会话的正确关联;增加 JobControl 的会话设置错误处理;调整 QEMU 测试超时时间至 120 秒 * fix(axbuild): preserve driver features for C tests * 优化 pass_std_build_nested_features 函数以支持可变特性列表,并添加单元测试验证功能 * Update QEMU configurations and dependencies for various architectures - Added virtio-net-pci and netdev configurations to QEMU arguments for aarch64, loongarch64, riscv64, and x86_64 test cases to enable networking capabilities. - Removed unnecessary PCI and virtio driver features from build configurations for aarch64, loongarch64, riscv64, and x86_64. - Updated hello world, HTTP client, IO test, thread test, and Tokio test configurations to include virtio-blk-pci for disk access. - Adjusted Cargo.toml files to streamline dependencies by removing unused features related to multitasking and IRQ handling. * fix: 增加 QEMU 配置中的内存大小至 512M * Refactor driver-related documentation and code structure - Replaced instances of `ax-driver-base`, `axdriver_*` with new naming conventions: `rdrive`, `rd-*`, and `rdif-*` across various documentation files. - Updated dependency references in `ax-hal`, `ax-input`, `ax-net-ng`, `ax-posix-api`, `ax-runtime`, and `axplat-dyn` to reflect the new driver structure. - Removed references to deprecated driver crates in `layers.md`, `overview.md`, and `components.md`. - Adjusted the driver subsystem section in the documentation to align with the new driver architecture. - Modified the repository management script to remove specific handling for `axdriver_crates` due to structural changes. * fix(starryos): relax x86_64 qemu test timeouts * 优化块设备的读写操作,合并块读取和写入方法,提升性能 * 重构块设备读写方法,移除合并操作,简化代码逻辑 * 为 DmaPages 结构体添加 DMA 统一页面分配方法,并移除 SyncBlockOps 中的 flush 方法实现 * 为 PCI 和 USB 驱动程序添加 IRQ 解析功能,重构相关方法以提高可读性和可维护性 * 移除不再使用的 simple-sdmmc 驱动相关代码,更新文档以反映当前驱动栈状态 * 重构设备初始化逻辑,使用 cfg_if 宏简化条件编译,提升可读性 * 重构平台特性管理,简化条件编译逻辑,移除冗余代码 * 添加对 rk3588-pcie 的支持到 Orange Pi 5 Plus 的构建配置 * 为 UsbKernel 实现 DmaOp 特性,添加 prepare_read 和 confirm_write 方法 * refactor(root): simplify partition selection logic and add helper functions * refactor(driver): replace crate::register_driver! with module_driver! macro for driver registration * refactor(driver): remove unused device feature constants and simplify configuration logic * refactor(ci): rename required_repository_owner to limit_to_owner for clarity * refactor: replace ax-kspin with spin in various drivers and update dependencies * refactor: remove ax-kspin dependency and update mutex usage in USB driver * refactor: add ax-hal dependency to arceos-stack-guard-page * refactor: update UVC stream parameters and change Mutex to BlockingMutex for submitted URBs * refactor: enhance std feature normalization and add test for runtime feature propagation
…core-os#910) Two related bugs in the EPOLLET delivery path broke event-driven runtimes on Tokio-style applications (jcode TUI, reqwest, etc.). 1. NoEvent path busy-loop on connected TCP sockets When InterestWaker fires but consume() reports no matching events (a spurious wake, e.g. a shared PollSet wake on an interest registered only for EPOLLIN while the underlying socket has EPOLLOUT-ready), the old code called check_and_register_waker(). That helper polls the file and immediately calls waker.wake_by_ref() if file.poll() is non-empty. Connected TCP sockets always advertise EPOLLOUT, so every spurious NoEvent reissued the waker and re-queued the interest: NoEvent -> check_and_register_waker -> EPOLLOUT present -> wake_by_ref -> re-queued -> NoEvent -> ... The ready_queue filled with phantom entries and epoll_wait returned maxevents (up to 1024) of duplicate notifications, which kept tokio spinning without ever confirming the TCP handshake. Fix: use register_waker_only on the NoEvent path so the interest is re-armed and only fires on a genuine state transition, matching the EPOLLET contract. 2. EventAndRemove race window between mark_not_in_queue() and re-arm After delivering an EPOLLET event, mark_not_in_queue() clears the in-queue flag and then register_waker_only() installs a new InterestWaker. The previous InterestWaker had already been consumed by the wake that delivered the first chunk, leaving the underlying PollSet empty in the gap between the two calls. If the peer writes a second chunk inside that window, poll_update.wake() hits the empty PollSet and the notification is silently dropped. The fresh waker is then installed only after the data has already arrived; no further write occurs and EPOLLET never fires again. The visible symptom was jcode TUI hanging after the first AI response chunk. Fix: after register_waker_only(), re-check the file for IN/RDHUP/HUP events. If data is already present, CAS the in-queue flag back to true and re-push the interest onto the ready queue directly (without going through waker.wake_by_ref(), which would reintroduce the bug-1 busy-loop). EPOLLOUT is intentionally excluded: writable sockets are normally always OUT-ready and a check there would spin. Add bug-epollet-second-chunk regression test covering both paths: an idle EPOLLET interest must not return phantom events from an always-OUT socket, and 32 back-to-back chunk-A/chunk-B rounds must each be reported by their own epoll_wait() call. Co-authored-by: StarryOS Fix <fix@starryos.dev>
…o netpoll EFAULT) (rcore-os#914) ## 问题 Go runtime 在 StarryOS 上 netpoll 失败:`runtime: netpoll failed` + `fd N failed with 14`(EFAULT),Go 程序无法正常网络轮询。 ## 根因 Go runtime 的 `epollevent` 以 `[8]byte data` 布局,只有 4 字节对齐,传给 `epoll_ctl` 的 `&ev` 可能落在 `4 (mod 8)` 的地址。StarryOS 的 `sys_epoll_ctl` 经类型化 `*const epoll_event`(`get_as_ref`)读取用户内存,VM helper 对非自然对齐(8 字节)的指针返回 `EFAULT`。Linux 内核用 `copy_from_user` 逐字节拷贝、无对齐要求,因此同样的 Go 程序在 Linux 正常、在 StarryOS `EFAULT`;`epoll_wait` 向用户 `events` 数组写回时同理。 ## 修复 新增 `read_epoll_event` / `write_epoll_event`,以字节粒度的 `vm_read_slice` / `vm_write_slice`(经 `*u8`)拷贝 `epoll_event`,不要求其自然对齐,镜像 Linux 的 `copy_from_user` / `__put_user` 语义。`sys_epoll_ctl` 的输入与 `do_epoll_wait` 的输出两条路径均改用。`epoll_event` 是 POD,任意位模式合法,字节拷贝安全。 ## 测试 本地 `cargo xtask starry build --arch x86_64` 通过;对齐路径(既有 `test-epoll`/`test-epoll-eventfd`/`test-epoll-lt`/`test-epoll-pwait2` 回归)行为不变——字节拷贝是对齐读写的超集。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
…ment /proc/[pid]/statm (rcore-os#915) ## 问题 psutil(及基于它的 glances/常见监控)在 StarryOS 上遍历进程即崩溃:`psutil ... num_threads → IndexError: list index out of range`;修掉后又 `FileNotFoundError: /proc/<pid>/statm`。 ## 根因 1. psutil `Process.num_threads()` 读 `/proc/<pid>/status`、用正则 `br'Threads:\t(\d+)'` 取值并直接 `[0]` 索引。StarryOS 的 `render_task_status_fields` 渲染了 Tgid/Pid/Uid/Gid/Cpus_allowed* 等,但**缺 `Threads:` 行** → `findall()` 为空 → `[0]` 抛 `IndexError`。psutil `Process.as_dict` 只吞 AccessDenied/ZombieProcess/NotImplementedError,故该异常逐层上抛、令整个 `process_iter` 崩溃。 2. 紧随其后 `memory_info()` 打开 `/proc/<pid>/statm`,StarryOS procfs **未提供该文件** → `FileNotFoundError`,同样未被 as_dict 吞掉。 ## 修复 1. `render_task_status_fields` 增加 `Threads:\t<n>`(TAB 分隔,匹配 psutil 正则),`<n>` 取自 `proc.threads().len()`,并将 `num_threads` 串入 `render_task_status`/`task_status`/procfs_pid 分支。 2. 新增 `/proc/<pid>/statm` 节点(`render_thread_statm`):`size`(VSS)由 `aspace.areas()` 求和,`resident` 取 VSS(诚实上界),`text`/`data` 据 EXECUTE/WRITE 标志,`shared`/`lib`/`dirty` 为 0。 二者均为通用 `/proc` ABI 补全,惠及任何读 `num_threads`/进程内存的工具(psutil/ps/top/htop)。 ## 测试 `cargo xtask starry build --arch x86_64` 通过;新增渲染单测断言 TAB 分隔的 `Threads:` 行;glances 头less 监控用例在 x86_64 实测通过(此前因本 bug 崩溃/超时)。 ## 对照 Linux(验证) Linux 内核 fs/proc 为每个 /proc/<pid>/status 输出 `Threads:\t<n>` 行、并提供 /proc/<pid>/statm(标准格式,arch 无关);host Linux 上 glances/psutil 据此正常工作。故崩溃非测例/依赖问题,而是 StarryOS procfs 与 Linux 的语义差异;本修使 StarryOS 对齐 Linux。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
…core-os#916) ## 问题 x86-64 上,依赖 raw ABI 偏移读写信号上下文的运行时会损坏寄存器。最典型是 Go 的异步抢占(SIGURG):其 signal handler 读写 `uc_mcontext.gregs[REG_RSP/REG_RIP]` 并指望 `rt_sigreturn` 按这些写回恢复;在 StarryOS 上 `RSP` 被错位 8 字节、载入相邻的非指针字节 → `unsafe.Slice: len out of range` panic。 ## 根因 `MContext`(对应 Linux `struct sigcontext` / `mcontext_t`)被标注 `#[repr(C, align(16))]`。但 Linux 的 `mcontext_t` 是**自然 8 字节对齐**,且在 `ucontext_t` 里 `uc_mcontext` 位于结构体**中部**(偏移 40,紧随 `uc_flags`/`uc_link`/`uc_stack`)。强制 16 对齐会在 `uc_stack`(@16..40)之后插入 8 字节填充,把 `uc_mcontext` 推到偏移 48 → 其内每个通用寄存器(RSP@160、RIP@168)、fpregs 指针、以及随后的 `uc_sigmask` 全部相对 Linux ABI 偏移 8 字节。Go 按裸偏移访问即错位。 ## 修复 - `MContext`:`#[repr(C, align(16))]` → `#[repr(C)]`(恢复自然 8 对齐 → `uc_mcontext`@40)。 - `UContext`:`#[repr(C)]` → `#[repr(C, align(16))]`。信号帧本身要求落在用户栈 16 对齐处(handler 入口须 `RSP%16==8`);该对齐改由**外层** `UContext` 提供,既保帧对齐、又不再扰动 `uc_mcontext` 的偏移。 - 新增编译期 `const _` 断言锁定 `offset_of!(UContext, mcontext)==40 && offset_of!(UContext, sigmask)==296`,作为 ABI 回归守卫(偏移再被改错即编译失败)。 仅改 `components/starry-signal/src/arch/x86_64.rs`,不触其它 arch/调用方。 ## 对照 Linux(验证) Linux/musl x86-64 `ucontext_t`:`uc_flags`@0、`uc_link`@8、`uc_stack`@16、`uc_mcontext`@40、`uc_sigmask`@296(`struct sigcontext` 256 字节)。本修后 StarryOS 偏移与之逐一吻合(const-assert 编译期证实)。Go runtime 在 host Linux 正常异步抢占即依赖此布局。 ## 测试 `cargo xtask starry build --arch x86_64` 通过(含上述 const-assert);openjdk17(信号密集:GC safepoint/SIGSEGV null-check)x86_64 实测无回归。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
…nicking (rcore-os#919) ## 问题 当 QEMU 以 `-smp M` 启动、而内核按 `MAX_CPU_NUM == N`(`N < M`)编译时,第 N..M 个 hart 进入 `rust_main_secondary` 后内核 panic(`percpu::init_secondary(cpu_id)` / `AxCpuMask::one_shot(cpu_id)` / `RUN_QUEUES[cpu_id]` 均断言 `index < MAX_CPU_NUM`),启动失败。 ## 根因 `rust_main_secondary(cpu_id)` 未对 `cpu_id` 设上界即去索引按 `MAX_CPU_NUM` 定容的 per-CPU 结构。超额 hart 的 `cpu_id >= MAX_CPU_NUM` 越界。 ## 修复 对齐 Linux 的做法(用前 N 个 CPU、park 多余的):在 `init_secondary` 之前,若 `cpu_id >= MAX_CPU_NUM` 则该 hart 进入 `wait_for_irqs()` 永久 park,绝不触碰按 `MAX_CPU_NUM` 定容的结构。`cpu_id < MAX_CPU_NUM` 的 hart 行为不变。 ## 测试 `cargo xtask starry build --arch x86_64` 通过;`-smp` 与 `MAX_CPU_NUM` 匹配时行为不变(park 分支不触发),`-smp` 超额时多余 hart 安全 park 而非 panic。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
…ared across split file mappings (rcore-os#920) ## 问题 loongarch64 上 JVM 启动偶发野指针崩溃(读取 jimage 时拿到另一页的数据)。根因是文件页缓存逐出路径的 use-after-free。 ## 根因 文件页缓存按 `CachedFile` 在所有映射同一文件的 area 间共享。`mprotect` 拆分一个文件映射后,`split` 会创建同享该 `CachedFile`、但 `start`/`offset_page` 不同的兄弟 `FileBackendInner`。当对其中一个子 area 做 populate 触发逐出时: 1. 逐出回调原先只覆盖发起 populate 的那个 `inner` 自己的页范围(`on_evict` 的 `checked_sub` 对其它范围返回 `None`),于是**兄弟 area 的 PTE 仍指向已被逐出/即将释放的物理帧**; 2. 且释放帧(drop page)与解除映射的次序不当——若先释放帧,被逐出的 VA 仍映射到一个可被重新分配的帧,被抢占进用户态的兄弟线程就能透过这条 stale 映射读到别页数据。 ## 修复 - `populate` 不再在持有地址空间锁时直接逐出,而是返回一个延迟回调;`AddrSpace::populate` 在释放页表 cursor 借用后再执行 `cb(self)`(`aspace/mod.rs`)。 - 逐出回调中:先 unmap 被逐出的 VA(经 cursor 解除映射并 flush TLB),**再** drop page 释放帧——绝不颠倒次序。 - 将被逐出页路由到**所有**共享该 cache 的 area(遍历 `aspace.areas()` 按 `cache.ptr_eq` 过滤),每个 area 的 `on_evict` 自校验(范围 + area 指针),只有真正的 owner 解除其映射。 ## 对照 Linux(验证) Linux 的 page cache 逐出在解除所有映射该页的 PTE(rmap)后才释放帧;本修使 StarryOS 的逐出遵循同样的"先 unmap 全部 owner、后释放帧"次序。loongarch64 JVM jimage 读取不再出现野指针。 ## 测试 `cargo xtask starry build --arch x86_64` 通过;openjdk17 在 loongarch64 实测稳定(此前因本 UAF 偶发崩溃)。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
…AM region (rcore-os#922) ## 问题 loongarch64 上大内存负载(如 gradle 构建的 JVM)即使系统有数 GB 空闲内存仍 OOM,用户态分配被莫名钳制在 ~248 MB。 ## 根因 撑起用户态页填充(`alloc_pages`)的页分配器由 `global_init` 从**单个连续空闲区**初始化;其余空闲区交给 byte/heap 分配器(bitmap 页分配器不支持 `global_add_memory`)。因此 `global_init` 选中的那个区**就是**用户内存的全部来源。原启发式取"`.bss` 之后的第一个空闲区";而 loongarch64 qemu-virt 的物理内存**不连续**——MMIO 洞下方一个 ~248 MB 的低区,外加 `0x8000_0000` 起的多 GB 高区——第一个空闲区恰是小的低区,于是无论总 RAM 多大,用户态分配都被钳在 ~248 MB。 ## 修复 改为选**最大**的空闲区初始化页分配器。单连续 RAM 区的平台(x86/aarch64/riscv64 qemu-virt)不受影响(最大区==唯一区)。 ## 对照 Linux(验证) Linux 经 memblock 使用全部物理 RAM(跨不连续区);本修使 StarryOS 至少把最大区完整供给用户态,消除 loongarch 上"有内存却 OOM"。 ## 测试 `cargo xtask starry build --arch x86_64` 通过;loongarch64 上大内存 JVM 负载不再因 ~248 MB 上限 OOM。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
## 问题 `getcpu(2)` 未实现,返回 ENOSYS。glibc `sched_getcpu()` 及 NUMA 感知代码(分配器/线程亲和)依赖它。 ## 修复(纯增量) - `syscall/task/thread.rs` 实现 `sys_getcpu(cpu, node, tcache)`:`cpu` 写当前 `this_cpu_id()`、`node` 写 0(单 NUMA 节点),两指针均可为 NULL;`tcache`(已废弃)忽略。 - `syscall/mod.rs` 接入分发 `Sysno::getcpu`。 ## 测试 - `cargo xtask starry build --arch x86_64` 通过。 - 新增 `test-suit/starryos/normal/qemu-smp1/syscall/test-getcpu/`(应 review 要求,仿 test-clock-gettime 框架):`syscall(SYS_getcpu, ...)` 验证返回值=0、cpu ∈ [0, nproc)、node==0、NULL 指针(cpu/node/全 NULL)安全、已废弃 tcache 被忽略;由 syscall 层 combined toml 4-arch 自动发现运行。 ## 对照 Linux(验证) 对齐 `sys_getcpu` 语义(写 CPU id 与 NUMA node);单节点系统 node 恒 0。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
…rcore-os#925) ## 问题 在 origin/dev 上,`check_signals` 把 `SignalOSAction::Stop` 处理成 `do_exit(1, true)`:进程收到 SIGSTOP/SIGTSTP/SIGTTIN/SIGTTOU 时不是被挂起,而是被直接退出(杀死)。`SignalOSAction::Continue` 则是空实现,SIGCONT 不做任何事。父进程的 `waitpid(WUNTRACED/WCONTINUED)` 也无从得知子进程的停止/继续。这破坏了 shell 作业控制、`killall5 -STOP/-CONT` 以及 busybox 等依赖作业控制的工具。 ## 根因 缺少真正的作业控制状态机:没有"已停止"标志,没有让停止线程在内核里挂起、等待 SIGCONT(或 SIGKILL)唤醒的机制,也没有把停止/继续状态报告给父进程 `waitpid` 的通道。 ## 修复 - `task/mod.rs`:新增 `enum JobStatus {Stopped(Signo), Continued}` 与受单锁保护的 `struct JobControl {stopped, status, continue_generation}`,作为 `ProcessData` 的字段;并新增 `cont_event: Arc<PollSet>`。配套方法:`is_job_stopped` / `set_job_stopped` / `continue_generation` / `set_job_continued`(唤醒 cont_event) / `clear_job_stop_for_kill` / `cont_event` / `peek_job_status_if` / `take_job_status_if`。 - `task/signal.rs`:`SignalOSAction::Stop` 改为调用 `do_job_stop(thr, signo)` —— 记录停止、向父进程发 SIGCHLD(CLD_STOPPED)、然后 `block_on(poll_fn(...))` 在 cont_event 上挂起(非 interruptible:普通信号不得唤醒已停止进程,只有 continue/kill 才清除停止标志)。`send_signal_to_process` 在发送时处理 SIGCONT(丢弃挂起停止、置 continued、报告 CLD_CONTINUED)与 SIGKILL(强制清除停止以便被杀死)。 - `syscall/task/wait.rs`:`sys_waitpid` 在僵尸回收之外,按 `WUNTRACED`/`WCONTINUED` 经 `peek/take_job_status_if` 报告停止/继续状态,编码为 `(signo<<8)|0x7f`(W_STOPCODE)与 `0xffff`。 为不修改 `starry-signal`(本 PR 仅触及上述三个内核文件),用 `continue_generation` 计数关闭 "STOP 后紧接 CONT" 竞态:停止前快照该计数,若期间有 SIGCONT 递增了它,`set_job_stopped` 返回 false 从而不挂起,等价于上游参考实现里在发送端 `discard_pending` 的效果。 ## 对照 Linux(验证) - SIGSTOP/SIGTSTP/SIGTTIN/SIGTTOU 挂起进程而非退出;SIGCONT 恢复;SIGKILL 即使对已停止进程也能终止。 - `waitpid(WUNTRACED)` 报告 `WIFSTOPPED` 且 `WSTOPSIG == 停止信号`;`waitpid(WCONTINUED)` 报告 `WIFCONTINUED`;状态字编码与 Linux 一致(停止 `(signo<<8)|0x7f`,继续 `0xffff`)。 - 父进程在子进程停止/继续时收到 SIGCHLD(CLD_STOPPED / CLD_CONTINUED)。 ## 测试 新增 `test-suit/starryos/normal/qemu-smp1/test-job-control-stop`(四架构 toml + C 测例):fork 一个忙等子进程,父进程 `kill(SIGSTOP)` → `waitpid(WUNTRACED)` 期望 `WIFSTOPPED`,确认子进程未退出且仍存在;`kill(SIGCONT)` → `waitpid(WCONTINUED)` 期望 `WIFCONTINUED`;`kill(SIGKILL)` 回收,期望 `WIFSIGNALED && WTERMSIG==SIGKILL`。在 starry x86_64(smp=1)实跑:15/15 断言通过,success 模式匹配。`cargo xtask starry build --arch x86_64` 与 `cargo fmt --all -- --check` 均通过。 Signed-off-by: Leo Cheng <chengkelfan@qq.com>
* Refactor DMA API usage across various drivers - Updated DMA allocation and deallocation methods to use ContiguousBuffer and CoherentArray types for better memory management. - Replaced deprecated DArray and DBuff types with their new counterparts in the rd-block, net, and usb drivers. - Enhanced memory synchronization methods to ensure proper data handling between CPU and device. - Improved error handling in DMA mapping functions to accommodate new constraints and layout requirements. - Adjusted driver implementations to align with the updated DMA API, ensuring compatibility and performance improvements. * Refactor DMA API for improved coherence and memory management - Updated `CoherentBox` and `ContiguousBox` to use `DmaAllocation` instead of `DCommon` for better memory handling. - Renamed methods in `CoherentBox` and `ContiguousBox` from `as_buff_mut` to `as_bytes_mut` for clarity. - Changed `DmaMapHandle` to use `bounce_ptr` instead of `map_alloc_virt` to better reflect its purpose. - Introduced a new module `op` to handle architecture-specific DMA operations, with aarch64 implementation for cache operations. - Updated `DeviceDma` to use the new `DmaOp` trait for DMA operations, replacing previous OSAL references. - Refactored buffer pool creation methods to use `contiguous_buffer_pool` instead of `new_pool` for consistency. - Removed deprecated code and comments related to previous memory allocation strategies. - Updated tests and driver implementations to align with the new API structure and naming conventions.
…ore-os#928) * chore(ci): update axvisor test jobs to use self-hosted runners * ci: migrate starry QEMU tests to self-hosted runners * fix(ci): enable container usage for starry tests on ubuntu-latest * fix(ci): update CI configuration for starry tests to use ubuntu-latest
rcore-os#965) - Deleted the ARM PL011 UART driver files including README, source code, and related documentation. - Introduced a new DesignWare APB UART backend for NS16550-compatible core in the `some-serial` module. - Updated the `some-serial` module to support DesignWare APB UART alongside existing NS16550 implementations. - Modified the kernel and device drivers to utilize the new `some-serial` module instead of the removed ARM PL011 driver. - Adjusted Cargo.toml dependencies to reflect the removal of `dw_apb_uart` and the addition of `some-serial`.
…ore-os#966) * Refactor FDT handling and improve error handling - Updated CPU node filtering logic in `create.rs` to pass node path directly. - Modified `build_node_path` function in `device.rs` to only compile for tests. - Enhanced error handling in FDT operations in `mod.rs`, returning `AxResult` for better error propagation. - Improved FDT parsing and setup functions in `parser.rs` to return results instead of panicking on errors. - Refactored image loading logic in `images/mod.rs` to use `AxResult` for error handling and removed unsafe static mut usage. - Updated vCPU task management in `vcpus.rs` to use thread-safe structures and improved error handling. - Enhanced command-line argument normalization in `xtask/src/main.rs` for better path resolution across platforms. * Refactor FDT handling and error management - Updated FDT creation functions to return AxResult for better error handling. - Introduced fdt_write_err function to standardize error reporting for FDT write operations. - Enhanced error handling in various FDT-related functions to ensure proper error propagation. - Modified the VM list management to simplify the structure and improve thread safety. - Replaced the custom VMList struct with a direct BTreeMap for global VM management. - Adjusted memory image handling to utilize the updated configuration access methods. - Improved the handling of IVC channels to ensure proper memory management and error checking. - Refined timer token management for better atomic operations. - Updated vCPU task management to use a BTreeMap for more efficient task retrieval and management. * refactor: streamline flag handling and improve code clarity across multiple commands * refactor: integrate startup banner into main kernel entry point * feat: add get_or_init method for LazyInit and implement DTB cache initialization
…ts) (rcore-os#848) * feat(starry-kernel): add eBPF subsystem (maps, prog, VM, helpers, perf events) - ebpf.rs: complete eBPF infrastructure - BpfInsn: full instruction encoding/decoding - BpfMapOps trait + ArrayMap + HashMap implementations - UnifiedMap: trait-object polymorphic map dispatch - BpfFdTable: fd-based map/prog management - BpfVm: instruction interpreter (ALU/JMP/ST/LD, 512B stack, 1M insn limit) - 11 helper functions (map ops, probe_read, ktime, smp, pid, perf_output) - BPF_MAP_CREATE/LOOKUP/UPDATE/DELETE/GET_NEXT_KEY/PROG_LOAD syscalls - BPF_PROG_ATTACH/BPF_LINK_CREATE for kprobe/tracepoint attach - perf_event.rs: perf event ring buffer infrastructure - RingBuffer with wrap-around write + perf_event_mmap_page header - PERF_RECORD_SAMPLE and PERF_RECORD_LOST record types - perf_event_open syscall implementation - perf_event_write/enable/disable/attach_prog public APIs - test-ebpf-basics: 9 test modules, 20+ checks * fix(starry-kernel): address eBPF PR review blocking issues 1. Fix test install path: usr/bin -> usr/bin/starry-test-suit (tests were silently skipped by qemu toml wildcard) 2. Add BPF_EXIT instruction handling in BpfVm::execute: opcode 0x90 now returns Ok(regs[0]) instead of falling through 3. Fix pointer truncation in handle_prog_load: read u64 fields correctly using *const u64 instead of *const u32 (was losing high 32 bits on 64-bit architectures) 4. Add BPF_CALL instruction handling (opcode 0x85): looks up helper by insn.imm, calls with regs[1..5] as args, stores result in regs[0] * fix(starry-kernel): correct bpf_attr field offsets in handle_prog_load Previous fix changed *const u32 to *const u64 which was wrong because Linux bpf_attr is a mixed u32/u64 layout. Use byte-offset helpers: read_u32(0) = prog_type (+0, u32) read_u32(4) = insn_cnt (+4, u32) read_u64(8) = insns (+8, u64 ptr) read_u64(16) = license (+16, u64 ptr) read_u32(24) = log_level (+24, u32) read_u32(28) = log_size (+28, u32) read_u64(32) = log_buf (+32, u64 ptr) read_u32(40) = kern_version (+40, u32) read_u32(44) = prog_flags (+44, u32) Verified: clippy 11 features, loongarch64 + x86_64 build. * fix(starry-kernel): improve eBPF helper safety per review suggestions 1. helper_map_lookup_elem: return pointer to cached value instead of map fd. Uses BPF_LOOKUP_CACHE global Vec to store the lookup result and returns its raw pointer, matching Linux bpf_map_lookup_elem semantics where BPF programs can directly read the value. 2. helper_probe_read: add safety improvements - Size limit: reject reads > 4096 bytes - User/kernel address detection: for addresses below 0x8000_0000_0000 (likely userspace), try vm_read_slice first; fall back to direct copy for kernel addresses - Prevents arbitrary kernel memory reads from unvalidated addresses 3. Add SAFETY comment for BPF_LOOKUP_CACHE explaining pointer lifetime Verified: clippy 11 features, x86_64/loongarch64 build. * feat(starry-kernel): add BPF/perf_event fd close and resource release BpfFdTable: - remove_map(fd): remove and drop a BPF map by fd - remove_prog(fd): remove and drop a BPF prog by fd - close_fd(fd): close either map or prog fd - fd_exists(fd): check if fd is a valid BPF fd - get_prog(fd): get mutable reference to BpfProg by fd Perf events: - perf_event_close(fd): remove and drop a perf event entry by fd - perf_event_fd_exists(fd): check if fd is a valid perf event fd Syscall routing: - Add BPF_OBJ_CLOSE (cmd=11) handler in sys_bpf - handle_obj_close reads fd from uattr and calls close_fd Public API: - bpf_close_fd(fd) / bpf_fd_exists(fd) for external callers - perf_event_close(fd) / perf_event_fd_exists(fd) for external callers Verified: clippy 11 features, x86_64/riscv64/aarch64/loongarch64 build. * fix(starry-kernel): improve eBPF handle_link_create and helper_get_current_uid_gid 1. handle_link_create: return newly allocated link fd instead of target_fd, matching Linux BPF_LINK_CREATE semantics 2. helper_get_current_uid_gid: read actual uid/gid from current thread credentials via AsThread trait instead of hardcoding 0 Returns (gid << 32) | uid as per Linux eBPF convention Verified: clippy 12 features, x86_64/loongarch64 build. * fix(starry-kernel): remove hardcoded user/kernel address boundary in helper_probe_read Instead of using a hardcoded 0x8000_0000_0000 boundary (x86_64-specific), always try vm_read_slice first for safe access, falling back to direct copy on failure. This works correctly on all architectures without platform-specific constants. Verified: clippy 12 features passed. * fix(starry-kernel): add fd reuse via free list in BpfFdTable Previously, BpfFdTable used a simple counter that never reused freed fd numbers, potentially exhausting fd space over long runs. Now uses a free_fds Vec as a LIFO free list: - alloc_fd() pops from free_fds if available, otherwise increments counter - close_fd() pushes the released fd back to free_fds - Verified: clippy 12 features passed * docs(starry-kernel): add module-level documentation for eBPF and perf_event the subsystem components, syscall interface, and public API. * fix(starry-kernel): address eBPF PR review non-blocking feedback 1. BpfFdTable: add links field to track link_fd -> (prog_fd, target_fd) mapping, enabling proper link lifecycle management 2. handle_link_create: record link in BpfFdTable.links so the returned fd is tracked and can be closed via OBJ_CLOSE 3. close_fd: handle links cleanup alongside maps and progs 4. handle_prog_attach: rename prog_fd to attach_prog_fd to match Linux bpf_attr PROG_ATTACH semantics (attach_prog_fd at offset 0) * fix(starry-kernel): correct bpf_attr field read order in handle_link_create and handle_prog_attach * fix(starry-kernel): improve eBPF code quality and close(2) integration - Fix BPF_ALU 32-bit truncation: all ALU ops now apply correct mask when is_64=false, not just RSH/ARSH - Define BPF_CALL_OP named constant for magic number 0x80 - Fix alloc_perf_fd TOCTOU: fd allocation and Vec push now atomic under same lock via new PerfFdTable with fd reuse support - Unify fd namespace: perf_event fd now starts from 3 (was 100) - Integrate perf_event_close/bpf_close_fd into close(2) syscall path and close_all_fds for process exit cleanup - Convert BPF_LOOKUP_CACHE from global SpinNoIrq to per-CPU via ax_percpu::def_percpu for SMP safety - Add perf event trigger mechanism: run_bpf_prog is called when perf events fire, enabling end-to-end BPF program execution - Wire kprobe breakpoint/debug handlers to trigger KPROBE perf events * fix(starry-kernel): correct BPF source operand check in ALU and JMP interpreters Use opcode bit check (insn.code & BPF_X) instead of incorrectly comparing register number (insn.src_reg()) with the BPF_X flag value. The old code caused all register-source ALU/JMP instructions to incorrectly use the immediate field instead of the source register. * fix(starry-kernel): correct JMP32 JA unconditional jump check in eBPF interpreter Use explicit opcode comparison (BPF_JMP32 | BPF_JA) instead of checking src_reg() == 0, which incorrectly matches any BPF_K conditional jump instruction (JEQ32, JGT32, etc.) as an unconditional jump. * fix(starry-kernel): add ebpf feature gate for conditional compilation - Cargo.toml: add "ebpf" feature (default enabled) - lib.rs: gate mod ebpf and mod perf_event behind #[cfg(feature = "ebpf")] - syscall/mod.rs: route bpf/perf_event_open to dummy_fd when ebpf disabled - file/mod.rs: gate perf_event_close/bpf_close_fd behind #[cfg(feature = "ebpf")] - kprobe.rs: gate perf_event_trigger_by_type behind #[cfg(feature = "ebpf")] - Verified: clippy 13 features all pass * feat(starry-kernel): add eBPF verifier, PERF_EVENT_ARRAY map, more helpers and prog type validation - Add basic eBPF verifier: instruction count limit (1M), BPF_EXIT existence check, PC jump boundary validation - Add PERF_EVENT_ARRAY map type with full BpfMapOps implementation - Register 3 new helpers: trace_printk (id=6), get_current_task (id=35), get_current_comm (id=16) - Add prog_type whitelist validation in handle_prog_load - Verified: clippy 13/13 features pass * fix(starry-kernel): rebase onto dev with kprobe merged, resolve conflicts
…-os#823) * fsync first commit * fsync second commit * Parameter Validation * fsync third commit * fsync fourth commit * harden shm-deadlock watchdog * Resolve the conflict * Fix Memfd fd * Avoid holding SHM_MANAGER during shmat mapping * Avoid false shm deadlock timeout * chore: rerun CI * chore: rerun CI
* test(starry): add sqlite3 smoke test config * test(starry): add sqlite3 CLI stress tests (all 4 architectures) Add sqlite3-smoke (S0-S4) and sqlite3-deep (S5-S8) test configs for: - aarch64 (baseline) - x86_64 - riscv64 - loongarch64 Test results (QEMU 10.2.1): - aarch64: smoke PASS, deep PASS - x86_64: smoke PASS, deep PASS - riscv64: smoke PASS, deep PASS - loongarch64: smoke PASS, deep PASS (timeout=600s) sqlite3-deep tests cover: - S5: DELETE journal + COMMIT + ROLLBACK - S6: WAL mode + reopen query - S7: 500-row bulk insert + integrity_check - S8: 64KiB BLOB + reopen query * fix: address review feedback - Fix loongarch64 timeout 300→600 for smoke and deep tests - Change apk add sqlite to apk add --no-cache sqlite - Scripts already consistent across architectures (verified) * ci: increase loongarch64 apk-curl qemu memory to 2G * fix: revert loongarch64 memory to 512M per reviewer feedback Reviewer ZR233 noted 2G is unnecessary. Verified 512M passes on all 4 architectures: - aarch64: PASS (32.41s) - x86_64: PASS (32.80s) - riscv64: PASS (35.38s) - loongarch64: PASS (30.14s) * fix(starry): align sqlite3 stress build features with stress-ng-0 baseline sqlite3-smoke/sqlite3-deep build configs had only features=["qemu"], which enables defplat but not virtio-blk/virtio-net drivers. The guest kernel could not detect the rootfs block device, causing panic: "failed to determine root device from available block devices". This patch aligns all 8 build configs (smoke+deep, 4 architectures) with the passing stress-ng-0 baseline: explicit arch-specific platform feature + ax-driver/virtio-blk/virtio-net/pci/etc, plat_dyn=false. --------- Co-authored-by: root <root@DESKTOP-GK445T5>
* Adds support for kernel symbol dumping via kallsyms Introduces infrastructure to extract, store, and expose kernel symbol information, enabling access via a dedicated procfs file. Integrates kallsyms section in the linker script, a build script for symbol extraction, and updates the build process to automate symbol generation. Signed-off-by: Godones <chenlinfeng25@outlook.com> * fix(starry): avoid qemu panic matcher for kallsyms output Upgrade ostool to 0.19 so empty QEMU fail_regex no longer gets default panic patterns injected, then clear the default Starry QEMU fail_regex entries to avoid terminating interactive QEMU sessions when /proc/kallsyms prints symbols containing "panic". Adjust axbuild for the new ostool Cargo fields, and refine pseudofs helpers so static string content can be exposed without overlapping trait impls while keeping read-only write failures as BadFileDescriptor. Signed-off-by: Godones <chenlinfeng25@outlook.com> * fix: Updates kallsyms handling and bumps ksym dependency. Signed-off-by: Godones <chenlinfeng25@outlook.com> * Improves kallsyms reading and initialization logic. Signed-off-by: Godones <chenlinfeng25@outlook.com> * fix: add memory config for util-linux test Signed-off-by: Godones <chenlinfeng25@outlook.com> --------- Signed-off-by: Godones <chenlinfeng25@outlook.com>
…e-os#979) * Implement platform-specific interrupt handling and setup for various architectures - Added `PlatOp` trait in `common.rs` to define platform operations for IRQ handling. - Implemented `PlatOp` for `loongarch64`, `riscv64`, and `x86_64` architectures in their respective modules. - Introduced `rdrive_setup` function in `driver.rs` to initialize the rdrive with FDT. - Created `irq.rs` to manage IRQ setup and handling, including inter-processor interrupts (IPI). - Developed `setup.rs` to define kernel operations and manage MMIO mappings. - Updated `lib.rs` to include new modules and initialize the platform. - Refactored platform package handling in `build.rs` to accommodate new metadata structure. - Adjusted paths in various reports and scripts to reflect the new directory structure for platforms. * feat(build): add workspace fallback for platform package resolution * Remove hello-kernel, irq-kernel, and smp-kernel examples This commit deletes the hello-kernel, irq-kernel, and smp-kernel example projects from the repository. The following files and directories were removed: - platforms/examples/hello-kernel/ - platforms/examples/irq-kernel/ - platforms/examples/smp-kernel/ These examples included build scripts, linker scripts, source code, and documentation files. The removal is part of a restructuring effort to streamline the project and focus on core components.
…core-os#982) * Add range allocator tests and implement range operations - Introduced tests for the RangeAllocator including simple allocation, out of memory scenarios, fragmentation and merging, and alignment gaps. - Created a CHANGELOG.md for the ranges-ext module to document notable changes. - Added Cargo.toml for the ranges-ext module with dependencies and features. - Implemented VecOp trait for heapless::Vec and alloc::vec::Vec to support range operations. - Developed the core functionality for merging overlapping ranges and handling conflicts in the ranges-ext module. - Added comprehensive tests for merging ranges, ensuring correct behavior for various scenarios including overlaps and conflicts. * Refactor code structure for improved readability and maintainability * Refactor workspace dependencies and update component paths for consistency * refactor: restructure axplat-dyn platform module - Remove obsolete files related to platform initialization, IRQ handling, memory management, power management, and generic timer. - Introduce new files for boot, console, drivers, and memory management with updated implementations. - Implement a new build script and linker script for dynamic platform support. - Update Cargo.toml to reflect the new structure and dependencies. - Add CHANGELOG.md to document changes and versioning. - Ensure compatibility with the latest spin crate version.
* chore(deps): update spin 0.10→0.12, ostool 0.19→0.21 - Update workspace spin from 0.10 to 0.12, rename Lazy→LazyLock across all usage sites to match spin 0.11+ API - Migrate 16 crates from pinned `spin = "0.10"` to `workspace = true` - Update `lazy` feature to `lazylock` for spin 0.12 compatibility - Update ostool from 0.19 to 0.21 (no code changes needed) * chore: format static LazyLock initializations for consistency * chore: replace Mutex with SpinMutex in IrqLock for improved performance * chore: remove ax-plat-dyn package and update spin dependency version
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
…le parent references (rcore-os#938) * fix(axfs-ng-vfs): skip children cache transfer on rename to avoid stale parent references * update * 修改时限 * 再次修改时限 * 移动测试目录 * test ci --------- Co-authored-by: zyc107109102 <zhouyucong2019@163.com> Co-authored-by: 周睿 <zrufo747@outlook.com>
…re-os#849) * feat(starry-kernel): add LKM support via kmod-loader integration - kmod_loader.rs: StarryKmodHelper (KernelModuleHelper trait impl) - KmodSectionMem: page-aligned memory with SectionMemOps, R/W/X perms - vmalloc: page-aligned kernel memory allocation - resolve_symbol: stub (depends on PR rcore-os#837 kallsyms) - flsuh_cache: icache/dcache flush for loaded module code - sys_init_module: load .ko ELF from user memory, call init - sys_delete_module / sys_finit_module: syscall stubs - test-kmod-loader: 7 test modules for error path validation - Depends on: feat/starry-kprobe, feat/starry-ebpf * fix(starry-kernel): address LKM PR rcore-os#849 review blocking issues 1. Fix test install path: usr/bin -> usr/bin/starry-test-suit (tests were silently skipped by qemu toml wildcard) 2. Fix KmodSectionMem null-pointer Drop UB: - Add null check in Drop before calling dealloc - Replace null-ptr KmodSectionMem fallback with safe NullSectionMem (no-op SectionMemOps implementation) to avoid UB entirely 3. Add comment explaining core::mem::forget(owner) intent: module must remain in memory; future delete_module will recover owner via global registry Verified: clippy 11 features, x86_64/riscv64/aarch64/loongarch64 build. * docs(starry-kernel): add module-level documentation for kmod_loader Add module doc comments describing LKM support, key components (KmodSectionMem, NullSectionMem, StarryKmodHelper), and known limitations. Fix module ordering in lib.rs for rustfmt. * fix(starry-kernel): address kmod review non-blocking suggestions - resolve_symbol stub: use AtomicBool to warn only once, avoid log spam - add test cases for valid ET_REL header, fd=0, and large junk input * fix(starry-kernel): use literal 0x80 for BPF_CALL opcode in verifier BPF_CALL_OP constant does not exist in bpf_insn module. BPF_CALL opcode is 0x85, so the high nibble is 0x80. * fix(starry-kernel): rebase onto dev with kprobe+eBPF merged, resolve conflicts - Skip kprobe and eBPF commits (already in dev via rcore-os#847 + rcore-os#848) - Resolve lib.rs, syscall/mod.rs, Cargo.toml conflicts - Update ax_hal -> ax_runtime::hal paths in kmod_loader.rs - Remove dw_apb_uart (not in workspace dependencies) * fix(starry-kernel): add cfg(ebpf) gate for perf_event module and trigger perf_event.rs references crate::ebpf::run_bpf_prog which is only available under the ebpf feature. Add cfg gates to prevent compilation failure when ebpf feature is disabled. * ci: rebase onto latest dev, resolve Cargo.lock conflict
…ce test suites (rcore-os#874) * test(starry-kernel): add eBPF advanced and attach/perf_event user-space test suites Add two comprehensive eBPF user-space test programs that exercise the full BPF subsystem beyond the existing basic tests. test-ebpf-advanced (26 test modules): - BPF instruction coverage: conditional jumps (JEQ/JGT/JGE/JNE/JSET), JMP32 comparisons, unconditional JA, LD_DW_IMM 64-bit immediates - Stack operations: ST/LDX with DW/W/B/H widths, STX register-to-stack - ALU operations: ADD/SUB/MUL/DIV/MOD/AND/OR/XOR/LSH/RSH/ARSH/NEG/MOV with ALU32 truncation verification - Helper function programs: ktime_get_ns, get_current_pid_tgid, get_current_uid_gid, get_smp_processor_id, get_prandom_u32, map_lookup_elem - Map operations: OBJ_CLOSE for maps and progs, stress tests (256-entry array, 100-entry hash), BPF_EXISTS/BPF_ANY flags, fd reuse, hash get_next_key iteration test-ebpf-attach (16 test modules): - perf_event_open: SOFTWARE/KPROBE types, null attr, invalid type - BPF_PROG_ATTACH/DETACH: basic attach-detach, invalid fd, kprobe perf - BPF_LINK_CREATE: basic link creation, invalid fd - BPF_OBJ_CLOSE: map fd, prog fd, invalid fd, fd=0 - Full lifecycle: load prog -> open perf -> link_create -> close all - Multi-resource: 8 prog load+close, 4 perf event open - Size validation: BPF_LINK_CREATE/PROG_ATTACH/OBJ_CLOSE with too-small size * ci: rebase onto dev with kprobe+eBPF merged
…re-os#985) alloc is needed by every consumer of axruntime. Remove the alloc feature entirely and make ax-alloc a required dependency. Propagating changes to axfeat to remove the now-unnecessary alloc forwarding from 15 features. Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
- Deleted LICENSE, LICENSE.APACHE, LICENSE.MIT, README.md, README_CN.md, and src/lib.rs files. - Removed tests and examples related to the range allocator functionality.
* refactor(linker-scripts): remove unused linker scripts for hello, irq, and smp kernels * refactor(ci): switch clippy and std tests to self-hosted runners
…ng during init (rcore-os#964) * cvi_usb_camera: replace SpinNoIrq with ax_sync::Mutex to allow sleeping during init * cvi_usb_camera: replace SpinNoIrq with ax_sync::Mutex to allow sleeping during init * fmt change * fmt change
) * Add RISC-V support and IRQ handling improvements - Implemented IRQ handling for RISC-V architecture, including local IRQ registration and handling. - Introduced a virtual IRQ injector for hypervisor support. - Enhanced the IRQ interface to accommodate RISC-V specific requirements. - Added PLIC (Platform-Level Interrupt Controller) support for RISC-V, including initialization and IRQ management. - Updated the build system to support RISC-V targets and dynamic platform features. - Modified various configuration files to enable RISC-V features and ensure compatibility with existing systems. - Improved QEMU configuration for RISC-V to handle dynamic root filesystem patches. * fix(axvisor): enable riscv64 qemu platform feature in CI * fix(axvisor): boot riscv64 dynamic hv * feat(riscv64): support dynamic platform drivers * fix(ax-driver): correct feature handling for plat-static and plat-dyn * fix(somehal): use runtime CPU id for riscv64 PLIC context * fix(build): replace pci driver feature with plat-dyn in configuration * Refactor platform feature configurations across various board TOML files - Removed "plat-dyn" features from multiple configurations to streamline platform feature management. - Updated related build scripts to ensure compatibility with the new feature structure. - Adjusted tests to reflect the removal of deprecated features and ensure proper functionality. - Consolidated platform feature handling in build scripts to improve clarity and maintainability. * fix(build): remove unnecessary parameter from build_cargo_args call * feat: add riscv_goldfish dependency and support for Goldfish RTC * refactor(smp): replace cpu_idx with early_current_cpu_idx for better boot-time CPU identification * feat(build): add starry-kernel/input feature to the build configuration * refactor(axruntime): remove alloc feature, make it unconditional (rcore-os#985) alloc is needed by every consumer of axruntime. Remove the alloc feature entirely and make ax-alloc a required dependency. Propagating changes to axfeat to remove the now-unnecessary alloc forwarding from 15 features. Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> * Remove range-alloc-arceos crate and its associated files (rcore-os#991) - Deleted LICENSE, LICENSE.APACHE, LICENSE.MIT, README.md, README_CN.md, and src/lib.rs files. - Removed tests and examples related to the range allocator functionality. * Refactor linker scripts and CI configuration (rcore-os#992) * refactor(linker-scripts): remove unused linker scripts for hello, irq, and smp kernels * refactor(ci): switch clippy and std tests to self-hosted runners * feat(deps): update spin to version 0.12.0 and bump other dependencies * feat: remove riscv64-qemu-virt references and update platform support in configuration --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: ZCShou <72115@163.com>
* feat(starry-kernel): add initial GDB ptrace support * ci: trigger starry gdb checks * ci: trigger starry gdb checks * ci: trigger starry gdb checks * fix(starry-kernel): correct ptrace waitid uid and hwcap * fix(starry-kernel): stabilize self-signal ptrace stops * fix(starry-kernel): preserve kill pid zero existence check * fix(starry-kernel): validate ptrace resume state * test(starry): tolerate apk-curl mirror outages * Revert "test(starry): tolerate apk-curl mirror outages" This reverts commit b5bd45b. * test(starry): move gdb smoke scenarios to apps
* docs(axvisor): add x86_64 Linux guest support plan and phased breakdown * feat(axvisor): add x86_64 Linux SMP1 guest config and initramfs build script * feat(axvisor): add x86_64 Linux bzImage header detection and parsing * feat(axvisor): load x86_64 Linux bzImage payload and initramfs into guest memory * feat(axvisor): construct x86_64 Linux boot_params and reorganize x86 image modules * feat(axvisor): add x86_64 Linux boot stub for direct-boot protected-mode entry * feat(axvisor): add x86_64 Linux command line support and complete initramfs boot * feat(axvisor): enable x86_64 APIC virtualization, PCI passthrough, and MP table for Linux guest * fix(axvisor): improve x86 vLAPIC timer, APIC MMIO write decoding, and IO APIC setup * feat(axvisor): add vIOAPIC emulation and EPT MMIO decode for x86_64 Linux guest * feat(axvisor): switch x86_64 Linux to real ext4 rootfs with default boot params * feat(axvisor): add x86 PIT/serial emulation, VMX virtual interrupt delivery, and generalize IOAPIC IRQ routing * feat(axvisor): replace RefCell with Mutex in axvcpu, consolidate x86 pending events, and add IRQ hook for IOAPIC forwarding * feat(axvisor): unmount host filesystem before guest passthrough and switch to Linux guest smoke test * fix(axvisor): harden filesystem release gate, clean up IOAPIC teardown, and tighten timer lock scope * docs(axvisor): remove completed x86_64 Linux guest support phase documents * chore(axvisor): clean up x86 linux rebase artifacts * refactor(axvisor): extract x86 device IRQ forwarding into dedicated devices module * test(axdevice): add mock axvisor_api implementations for x86_64 unit tests * fix(axvisor): resolve x86 linux review feedback * fix(axvisor): enable raw_apic_id under irq feature in addition to smp * refactor(axvisor): introduce InterruptTriggerMode enum and rename VTimer to PreemptionTimer * fix(axvisor): repair x86 linux rebase fallout
Add the Slice 0 cgroup-basic StarryOS QEMU case across x86_64, aarch64, riscv64, and loongarch64. Implement the Slice 1 minimum cgroup2 root filesystem: explicit cgroup2 mount support, root cgroup.procs, empty cgroup.controllers, empty cgroup.subtree_control, and errno-preserving write failures for unsupported operations. Keep cgroup v1 mounts unsupported with ENODEV and avoid hierarchy, controller, procfs cgroup, and clone cgroup semantics.
…ng entries (rcore-os#1001) * fix(rsext4): use physical byte offset in readdir to fix rm -rf skipping entries * test ci * test ci * test ci --------- Co-authored-by: zyc107109102 <zhouyucong2019@163.com>
…buddy-slab backends (rcore-os#987) * refactor(ax-alloc): remove ax-allocator dependency, simplify to TLSF/buddy-slab backends Remove the two-level allocation architecture (byte allocator + bitmap page allocator from ax-allocator). TLSF now uses rlsf directly as a single-level allocator. buddy-slab remains unchanged. - Remove ax-allocator dependency, add rlsf directly - Remove slab/buddy/page-alloc-4g/page-alloc-64g features - tlsf and buddy-slab are mutually exclusive, neither enabled by default - Add build.rs for cfg(tlsf)/cfg(buddy_slab) generation - Add stub_impl.rs with unimplemented!() when no backend is selected - Clean up downstream Cargo.toml feature propagation * fix(starry): separate allocator feature selection from static features Remove hardcoded `alloc-tlsf` from starry-kernel's static ax-feat features to avoid conflicting with buddy-slab. Add `tlsf` feature to starry-kernel and starryos crates. Add `starryos/tlsf` to all non-buddy-slab StarryOS test configurations. * Refactor memory allocator configuration and implementation - Updated `Cargo.toml` files to remove unused allocator features and streamline dependencies. - Replaced `alloc-slab` and `alloc-buddy` with `alloc-tlsf` in the kernel and API configurations. - Removed the default implementation of the memory allocator and introduced a stub implementation for cases where no backend is enabled. - Implemented a TLSF (Two-Level Segregate Fit) memory allocator using the `rlsf` crate, providing efficient memory management. - Added a build script to enforce mutually exclusive feature selection between `tlsf` and `buddy-slab`. - Cleaned up the allocator's API to ensure proper usage statistics tracking and memory management. * fix(ax-alloc): select allocator backend from platforms * fix(starryos): give x86 dhcp test enough memory * refactor: remove optional dependency on axklib for paging feature
… support 补齐 x86_64 ptrace 主干功能: ## Kernel changes (os/StarryOS/kernel) ### ptrace.rs: x86_64 register read/write + singlestep - 新增 `X8664UserRegs` 结构体 (repr(C)),对应 Linux `user_regs_struct`,含 r15..rsp/ss/fs_base/gs_base 全部 27 个字段 - 实现 `From<UserContext> for X8664UserRegs` 和 `write_to()` - 补齐 x86_64 上之前缺失的 ptrace opcode: GETREGS / SETREGS / GETREGSET(NT_PRSTATUS) / SETREGSET(NT_PRSTATUS) / GETSIGINFO / SETSIGINFO - 将 `ptrace_getregset_prstatus` 中 `regs` 局部变量从内部 block 提升到 函数级作用域,修复 reg_bytes slice 的 use-after-free bug(regs 出 block 后被栈复用覆盖,导致用户态读到随机值,表现为 RSP=0x1) - 新增 `ptrace_setup_singlestep` for x86_64:设置 RFLAGS 的 TF (bit 8) 触发 CPU 单步执行 ### user.rs: SINGLESTEP + #DB 异常路由 - 为 x86_64 添加 singlestep setup 调用(之前仅 riscv64) - 新增 `ExceptionKind::Debug` 处理分支:命中 traced task 的 #DB 异常时,清除 TF 并调用 ptrace_stop_current(SIGTRAP) - Intel SDM 规定 CPU 在交付 TF 诱导的 #DB 时会清除 pushed RFLAGS 中的 TF,但 QEMU 不完全遵守,故显式清除防止 resume 后再次单步 ## Test cases (test-suit/starryos/normal/qemu-smp1) | 测试 | 验证内容 | |------|----------| | test-ptrace-x86-regs | TRACEME -> GETREGS/GETREGSET/SETREGS/SETREGSET 闭环 | | test-ptrace-exec-stop | TRACEME + execve -> SIGTRAP + DETACH | | test-ptrace-x86-breakpoint | 双测试:software int3 最小闭环 + SINGLESTEP 基础验证 | | test-ptrace-x86-singlestep | PTRACE_SINGLESTEP 执行一条指令后以 SIGTRAP stop | | test-ptrace-x86-breakpoint-reinsert | gdb 风格断点恢复:rewind RIP -> 恢复原字节 -> SINGLESTEP -> 重新插入断点 -> 再次命中 | | test-gdb-native-batch | gdb -q -batch 端到端:break native_marker / run / bt / info registers / continue | 所有 6 个 x86_64 ptrace case 全部通过。
There was a problem hiding this comment.
Review 总结:PR #1059 — Mount umount2 Linux 兼容
PR 变更概述
本 PR 核心目标是将 StarryOS 的 sys_mount() / sys_umount2() 语义对齐 Linux,包括:
sys_mount()按操作类型分派:propagation flags → remount → move → bind → 普通挂载,不再将所有调用都当成新建普通挂载。- Mount propagation 支持:MS_SHARED / MS_PRIVATE / MS_SLAVE / MS_UNBINDABLE 的合法组合校验和状态管理,包括 peer group、slave/master 关系的完整实现。
- Bind mount:MS_BIND(非递归)和 MS_BIND|MS_REC(递归),通过
childrenmap 控制子挂载是否可见。 - MS_MOVE:移动已有挂载到新路径,正确更新 mount tree 父子关系。
- MS_REMOUNT / MS_RDONLY:按 mountpoint 设置只读,在 open/write/create/rename/unlink/mkdir 路径上检查并返回 EROFS。
- umount2 增强:MNT_EXPIRE 两阶段过期、UMOUNT_NOFOLLOW 不跟踪符号链接、MNT_DETACH lazy detach、invalid flags 组合校验。
resolve_mountpoint()修改:改为检查 mountpoint children map 而非 entry 上的 mountpoint,使非递归 bind mount 正确隐藏子挂载。
实现逻辑评价
核心 mount/umount2 实现质量很高:
Mountpoint结构体正确地将 readonly、expired、propagation 状态绑定到挂载实例上,符合 Linux 语义。resolve_mountpoint()的修改是关键创新点:用 children map 替代 DirEntry 上的 mountpoint 字段来决定是否跨入子挂载,这使递归/非递归 bind 的区分真正体现在 mount tree 而非共享的目录节点上。- propagation 的 peers/slaves/masters 结构实现完整,包括
propagate_new_child()用于 shared peer 之间的子挂载传播。 - 文档
mount-umount2-linux-compat.md写得非常详尽,覆盖了每个语义矩阵和实现决策。
测试覆盖
测试文件 test-suit/starryos/normal/qemu-smp1/util-linux/c/src/main.c(2407 行)覆盖非常全面:
- mount/losetup/blkid/fdisk 工具可用性
- Loop 设备完整生命周期(attach/detach/read-only)
- ext4 mount/unmount、写入持久化、writeback 验证
- EBUSY 检测(cwd 在挂载点内、open fd 在挂载点内)
- pivot_root EINVAL 语义
- propagation flags 非法组合校验和无副作用验证
- MS_SHARED/MS_PRIVATE/MS_SLAVE/MS_UNBINDABLE 语义验证
- Bind mount(非递归/递归/子目录 bind/unbindable prune)
- MS_MOVE / MS_REMOUNT / MS_RDONLY / MS_REMOUNT|MS_RDONLY
- umount2: invalid flags、invalid combo、MNT_EXPIRE、UMOUNT_NOFOLLOW、MNT_DETACH
- QEMU 配置覆盖 4 个架构(aarch64/loongarch64/riscv64/x86_64)
QEMU 验证说明:本 review 环境无法直接运行 QEMU 来验证 cargo xtask starry test qemu。测试代码逻辑正确,qemu 配置合理(success_regex/fail_regex 设置正确),但需要在 CI 或可运行 QEMU 的环境中确认所有 Tier 测试通过。
⚠️ 阻塞问题
1. 合并冲突(blocking)
PR 当前 merge state 为 dirty,与 dev 分支存在合并冲突。需要作者 rebase 或合并最新 dev 分支后重新推送,确保冲突已解决且 CI 通过。
2. PR 描述缺失(blocking)
PR body 为空。对于包含 74 个 commit、2124 个变更文件的大型 PR,需要一个清晰的描述说明:
- PR 的核心目标和动机
- 关键实现决策
- 验证方法和结果
- 已知限制
文档 mount-umount2-linux-compat.md 写得很好,建议将关键内容整合到 PR body 中。
3. PR 范围过大(non-blocking 但建议)
PR 包含大量来自其他贡献者的合并提交(如 kprobe、cgroup2、eBPF、inotify、prlimit64、splice、membarrier/rseq、epoll/sigmask 修复、驱动重构、CI 迁移等)。建议作者将核心 mount/umount2 改动单独提交,减少 review 负担和合并风险。
重复/重叠分析
- 未发现与当前 open PR 直接重复 mount/umount2 功能的 PR。
- PR #1057(rsext4 fine-grained locking)修改了 rsext4 缓存层,与本 PR 的 ext4 mount 路径相关但不冲突。
- PR #1058(K230 NNCase runtime demo)与本 PR 完全无关。
审查结论
核心 mount/umount2 实现逻辑正确、测试覆盖全面、文档详尽。当前需要解决合并冲突和补充 PR 描述后才能批准。
Powered by mimo-v2.5-pro
There was a problem hiding this comment.
Review 总结:PR #1059 — 实际唯一新增内容为 x86_64 ptrace 支持
PR 变更概述
本 PR 包含 4 个作者独特 commit,实际涵盖两个独立功能:
功能 A — mount/umount2 Linux 兼容(3 个 commit):
506660cbefix(starry): reject invalid umount2 flagsa3310abfcfix sys_mount and umount22fb2283e2fix(starry): align mount and umount2 semantics with Linux
功能 B — x86_64 ptrace 寄存器读写 + SINGLESTEP 支持(1 个 commit):
97348e1d0feat(starry-kernel): x86_64 ptrace register r/w and PTRACE_SINGLESTEP support
⚠️ 阻塞问题
1. mount/umount2 功能已被 dev 分支完全包含(blocking)
经对比 dev 分支 bbf8e941,功能 A 的所有变更已完全存在于 dev 上:
components/axfs-ng-vfs/src/mount.rs:readonly、expired、propagation(Private/Shared/Slave/Unbindable)、peers/slaves/masters、bind_mount、move_mount、detach_mount 等全部已合并os/StarryOS/kernel/src/syscall/fs/mount.rs:MS_BIND/MS_MOVE/MS_RDONLY/MS_REMOUNT/propagation flags 处理、MNT_DETACH/MNT_EXPIRE/UMOUNT_NOFOLLOW 已合并os/arceos/modules/axfs-ng/src/highlevel/file.rs:readonly 检查已合并test-suit/starryos/normal/qemu-smp1/util-linux/c/src/main.c:所有 Tier 4k* 测试用例(共 30 个)已合并
因此 mount/umount2 部分不会引入任何新代码,合并后为空操作。建议从 PR 中移除这些 commit,或仅保留 ptrace commit。
2. 合并冲突(blocking)
PR 当前 mergeable_state 为 dirty,mergeable 为 false。分支与 dev 存在严重偏离(74 commits,2124 changed files)。需要 rebase 到最新 dev 分支并解决冲突。
3. PR 描述为空(blocking)
PR body 为 null。对于包含 ptrace x86_64 支持的 PR,需要说明:
- 核心目标(补齐 x86_64 ptrace 主干功能)
- 关键实现决策(TF 单步、#DB 异常路由、use-after-free 修复)
- 验证方法和结果
commit message 97348e1d0 写得很好,建议将关键内容整合到 PR body 中。
4. PR 标题与实际内容不匹配(blocking)
标题为 "Mount umount2 linux compat",但唯一新增内容是 x86_64 ptrace 支持。建议更新标题为类似 "feat(starry-kernel): x86_64 ptrace register r/w and PTRACE_SINGLESTEP support"。
功能 B 代码审查:x86_64 ptrace 支持
实现质量评价
ptrace.rs 变更质量较高:
X8664UserRegs结构体(repr(C))正确映射 Linuxuser_regs_struct的全部 27 个字段,字段顺序与arch/x86/include/uapi/asm/user.h一致。From<UserContext>实现正确映射 r15..rsp/ss/fs_base/gs_base,orig_rax设为u64::MAX作为哨兵值,ds/es/fs/gs 设为 0(64 位模式下合理)。write_to()正确回写核心寄存器,未回写 orig_rax/ds/es/fs/gs(正确,这些不应通过 SETREGS 修改)。- use-after-free 修复:
ptrace_getregset_prstatus中将regs提升到函数级作用域,使reg_bytesslice 不会悬空——这是关键 bug 修复(此前 regs 在内部 block 结束后被栈复用,导致用户态读到随机值)。 - 所有
#[cfg(target_arch)]门控正确,从仅 riscv64 扩展为any(riscv64, x86_64)。
user.rs 变更正确:
- x86_64 singlestep setup 通过 RFLAGS TF bit 8 触发,符合 Intel SDM 规范。
ExceptionKind::Debug处理正确:检测 traced task → 清除 TF →ptrace_stop_current(SIGTRAP)。- 注释解释了 QEMU 不完全遵守 SDM 的 TF 清除行为,显式清除防止 resume 后再次单步——这是正确的防御性编程。
关注点
orig_rax设为u64::MAX:GDB 等工具可能会检查此字段。建议添加注释说明这是哨兵值,或在后续 PR 中实现 syscall 跟踪时设置正确的 orig_rax。- ds/es/fs/gs 硬编码为 0:64 位模式下通常不需要这些段寄存器,但某些工具可能期望非零值。建议在代码注释中说明理由。
测试覆盖分析
6 个 x86_64 ptrace 测试用例,均正确放置在 test-suit/starryos/normal/qemu-smp1/ 下:
| 测试用例 | 验证内容 | 期望结果 |
|---|---|---|
| test-ptrace-x86-regs | TRACEME → GETREGS/GETREGSET/SETREGS/SETREGSET 闭环 + GETSIGINFO | DONE: 1 pass, 0 fail |
| test-ptrace-exec-stop | TRACEME + execve → SIGTRAP + DETACH | DONE: 3 pass, 0 fail |
| test-ptrace-x86-breakpoint | software int3 最小闭环 + SINGLESTEP 基础验证 | DONE: 2 pass, 0 fail |
| test-ptrace-x86-singlestep | PTRACE_SINGLESTEP 执行一条指令后以 SIGTRAP stop | DONE: 1 pass, 0 fail |
| test-ptrace-x86-breakpoint-reinsert | gdb 风格断点恢复:rewind RIP → 恢复原字节 → SINGLESTEP → 重新插入断点 | DONE: 1 pass, 0 fail |
| test-gdb-native-batch | gdb -q -batch 端到端:break/run/bt/info registers/continue | GDB_NATIVE_BATCH_DONE |
QEMU 配置正确:使用 x86_64 rootfs image,success_regex/fail_regex 设置合理,timeout=120s 适当。
测试代码审查(test-ptrace-x86-regs/c/src/main.c):
- 正确的 fork + TRACEME + SIGSTOP 流程
- GETREGS 和 GETREGSET 一致性检查
- SETREGSET 写入后 GETREGS 验证
- SETREGS 写入后 GETREGSET 验证
- 恢复原始寄存器后 PTRACE_CONT,验证子进程正常退出
- 使用
check()模式输出 PASS/FAIL,与 regex 匹配
无法在当前环境运行 QEMU 验证。PR 作者声称所有 6 个 case 通过,需在 CI 或可运行 QEMU 的环境中确认。
重复/重叠分析
- 未发现其他 open PR 与 x86_64 ptrace 功能重复。
- dev 上已有的 ptrace 测试(test-ptrace-exec-stop、test-ptrace-gdb、test-ptrace-traceme-stop)使用 riscv64 配置,与本 PR 的 x86_64 测试不冲突。
- mount/umount2 部分已被 dev 完全包含,属于重复提交。
修改建议
- Rebase 到最新 dev,移除与 dev 重复的 mount/umount2 commit,仅保留 ptrace commit
- 更新 PR 标题为反映实际内容(ptrace x86_64 支持)
- 补充 PR 描述,包含实现决策、验证结果
- 添加注释说明
orig_rax = u64::MAX和ds/es/fs/gs = 0的设计决策 - 解决冲突后在 CI 中运行
cargo xtask starry test qemu --arch x86_64 -c test-ptrace-x86-regs等全部 6 个 case
Powered by mimo-v2.5-pro
No description provided.