Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions os/StarryOS/kernel/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ sg200x-bsp = { workspace = true, optional = true }
# because Writeable trait must come from the same version as sg200x-bsp's types.
tock-registers = { version = "0.9", optional = true }
ktracepoint = "0.6"
ksym = "0.6"

[target.'cfg(target_arch = "x86_64")'.dependencies]
x86 = "0.52"
Expand Down
2 changes: 1 addition & 1 deletion os/StarryOS/kernel/src/pseudofs/dev/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ fn builder(fs: Arc<SimpleFs>) -> DirMaker {
#[cfg(feature = "dev-log")]
root.add(
"log",
crate::pseudofs::SimpleFile::new(fs.clone(), NodeType::Socket, || Ok(b"")),
crate::pseudofs::SimpleFile::new(fs.clone(), NodeType::Socket, || Ok("")),
);

#[cfg(feature = "memtrack")]
Expand Down
47 changes: 37 additions & 10 deletions os/StarryOS/kernel/src/pseudofs/file.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use alloc::{borrow::Cow, sync::Arc, vec::Vec};
use alloc::{borrow::Cow, string::String, sync::Arc, vec::Vec};
use core::{any::Any, cmp::Ordering, task::Context};

use ax_sync::Mutex;
Expand All @@ -16,7 +16,9 @@ pub trait SimpleFileOps: Send + Sync + 'static {
/// Reads all content in the file.
fn read_all(&self) -> VfsResult<Cow<'_, [u8]>>;
/// Replaces the file's content with `data`.
fn write_all(&self, data: &[u8]) -> VfsResult<()>;
fn write_all(&self, _data: &[u8]) -> VfsResult<()> {
Err(VfsError::BadFileDescriptor)
}
}

/// Type representing operation applied to a simple file.
Expand Down Expand Up @@ -56,17 +58,42 @@ where
}
}

pub trait SimpleFileContent {
/// Converts the content into bytes.
fn into_content(self) -> Cow<'static, [u8]>;
}

impl SimpleFileContent for Vec<u8> {
fn into_content(self) -> Cow<'static, [u8]> {
Cow::Owned(self)
}
}

impl SimpleFileContent for String {
fn into_content(self) -> Cow<'static, [u8]> {
Cow::Owned(self.into_bytes())
}
}

impl SimpleFileContent for &'static str {
fn into_content(self) -> Cow<'static, [u8]> {
Cow::Borrowed(self.as_bytes())
}
}

impl SimpleFileContent for &'static [u8] {
fn into_content(self) -> Cow<'static, [u8]> {
Cow::Borrowed(self)
}
}

impl<F, R> SimpleFileOps for F
where
F: Fn() -> VfsResult<R> + Send + Sync + 'static,
R: Into<Vec<u8>>,
R: SimpleFileContent,
{
fn read_all(&self) -> VfsResult<Cow<'_, [u8]>> {
(self)().map(|it| Cow::Owned(it.into()))
}

fn write_all(&self, _data: &[u8]) -> VfsResult<()> {
Err(VfsError::BadFileDescriptor)
Ok((self)()?.into_content())
}
}

Expand Down Expand Up @@ -262,8 +289,8 @@ impl<T: DirectRwFsFileOps> FileNodeOps for SpecialFsFile<T> {
}

fn append(&self, buf: &[u8]) -> VfsResult<(usize, u64)> {
self.ops.write_at(buf, 0)?;
Ok((buf.len(), 0))
let w = self.ops.write_at(buf, 0)?;
Ok((w, 0))
}

fn set_len(&self, len: u64) -> VfsResult<()> {
Expand Down
49 changes: 49 additions & 0 deletions os/StarryOS/kernel/src/pseudofs/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ use core::{
sync::atomic::{AtomicUsize, Ordering},
};

use ax_lazyinit::LazyInit;
use ax_memory_addr::PAGE_SIZE_4K;
use ax_runtime::hal::{
paging::MappingFlags,
time::{monotonic_time, wall_time},
};
use ax_task::{AxCpuMask, AxTaskRef, TaskState, WeakAxTaskRef, current};
use axfs_ng_vfs::{DeviceId, Filesystem, NodePermission, NodeType, VfsError, VfsResult};
use ksym::KallsymsMapped;
use starry_process::{Pid, Process};

use crate::{
Expand All @@ -41,6 +43,36 @@ use crate::{
static IRQ_CNT: AtomicUsize = AtomicUsize::new(0);
const PROCFS_INIT_PID: Pid = 1;

pub static KALLSYMS: LazyInit<KallsymsMapped<'static>> = LazyInit::new();

fn read_kallsyms() -> KallsymsMapped<'static> {
unsafe extern "C" {
fn _stext();
fn _etext();
fn __kallsyms_start();
fn __kallsyms_end();
}

let kallsyms_start = __kallsyms_start as *const () as usize;
let kallsyms_end = __kallsyms_end as *const () as usize;
let kallsyms_sec_size = kallsyms_end - kallsyms_start;
let kallsyms_sec =
unsafe { core::slice::from_raw_parts(__kallsyms_start as *const u8, kallsyms_sec_size) };

Comment thread
Godones marked this conversation as resolved.
let total_size =
Comment thread
Godones marked this conversation as resolved.
KallsymsMapped::check_total_bytes(kallsyms_sec).expect("Invalid kallsyms format");
Comment thread
Godones marked this conversation as resolved.

let kallsyms = &kallsyms_sec[..total_size as usize];
// TODO: recycle unused space in .kallsyms section
info!("Read kallsyms, size: {}KB", kallsyms.len() / 1024);
Comment thread
Godones marked this conversation as resolved.
KallsymsMapped::from_blob(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 非阻塞建议:此处 expect("Invalid kallsyms format") 在 kallsyms 数据格式无效时会导致内核 panic。建议改为 graceful degradation:记录 warn! 日志并让 read_kallsyms() 返回 Option<KallsymsMapped>,在调用方跳过 /proc/kallsyms 注册。

kallsyms,
Comment thread
Godones marked this conversation as resolved.
_stext as *const () as u64,
_etext as *const () as u64,
)
.expect("Failed to create KallsymsMapped")
Comment thread
Godones marked this conversation as resolved.
Comment thread
Godones marked this conversation as resolved.
}

fn procfs_visible_pid(proc: &Arc<Process>) -> Pid {
if proc.is_init() {
PROCFS_INIT_PID
Expand Down Expand Up @@ -961,6 +993,23 @@ fn builder(fs: Arc<SimpleFs>) -> DirMaker {
SimpleDir::new_maker(fs.clone(), Arc::new(dynamic_debug))
});

static ALL_SYMS: LazyInit<String> = LazyInit::new();

let ksym = read_kallsyms();
KALLSYMS.init_once(ksym);

root.add("kallsyms", {
if !ALL_SYMS.is_inited() {
ALL_SYMS.init_once(KALLSYMS.dump_all_symbols());
}
let seq_obj = SeqObject::new(|| Ok(ALL_SYMS.as_str()));
SpecialFsFile::new_regular_with_perm(
fs.clone(),
seq_obj,
NodePermission::from_bits_truncate(0o444),
)
});

Comment thread
Godones marked this conversation as resolved.
let proc_dir = ProcFsHandler(fs.clone());
SimpleDir::new_maker(fs, Arc::new(proc_dir.chain(root)))
}
Expand Down
8 changes: 7 additions & 1 deletion os/StarryOS/starryos/ext_linker.ld
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ SECTIONS {
KEEP(*(.tracepoint .tracepoint.*))
__stop_tracepoint = .;
}

.kallsyms : ALIGN(4K) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.kallsyms 固定预留 8MiB 且不是 NOLOAD,会进入内核镜像布局并改变 _ekernel/free memory 边界。结合运行时又把整段交给 heap 回收,既扩大镜像/常驻内存,又把链接脚本保留区当普通 heap 使用。请改成明确的非加载/只保留实际 blob 的设计,或拆成单独可验证的保留区,并配套检查实际大小和对齐后再回收。

__kallsyms_start = .;
. += 8M; /* reserve space for kallsyms, can be recycled */
__kallsyms_end = .;
}
Comment thread
Godones marked this conversation as resolved.
}

INSERT AFTER .data;
INSERT AFTER .data;
104 changes: 104 additions & 0 deletions scripts/axbuild/scripts/starry-kallsyms.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env sh
set -eu

auto_install_enabled() {
case "${AXBUILD_STARRY_KALLSYMS_AUTO_INSTALL:-1}" in
0 | n | no | false | off) return 1 ;;
*) return 0 ;;
esac
Comment thread
Godones marked this conversation as resolved.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 非阻塞建议:auto_install_enabled 默认为启用(:-1),可能在 CI/开发者环境中意外触发 cargo install ksymcargo install cargo-binutils。建议默认禁用(改为 :-0),仅在 AXBUILD_STARRY_KALLSYMS_AUTO_INSTALL=1 显式启用时安装。

}

install_rust_binutils() {
if ! auto_install_enabled; then
echo "rust-nm and rust-objcopy are required for Starry kallsyms generation" >&2
echo "install them with: rustup component add llvm-tools-preview && cargo install cargo-binutils" >&2
exit 1
fi

echo "Installing rust-nm and rust-objcopy (cargo-binutils)..." >&2
if command -v rustup >/dev/null 2>&1; then
rustup component add llvm-tools-preview
fi
cargo install cargo-binutils
}

ensure_llvm_tools() {
if command -v rust-nm >/dev/null 2>&1 \
&& command -v rust-objcopy >/dev/null 2>&1 \
&& rust-nm --version >/dev/null 2>&1 \
&& rust-objcopy --version >/dev/null 2>&1; then
return
fi

if ! command -v rustup >/dev/null 2>&1; then
return
fi
if rustup component list --installed | grep -q '^llvm-tools'; then
return
fi

if ! auto_install_enabled; then
echo "llvm-tools-preview is required for rust-nm and rust-objcopy" >&2
echo "install it with: rustup component add llvm-tools-preview" >&2
exit 1
fi

echo "Installing llvm-tools-preview via rustup..." >&2
rustup component add llvm-tools-preview
}

install_ksym() {
if ! auto_install_enabled; then
echo "gen_ksym is required for Starry kallsyms generation" >&2
echo "install it with: cargo install ksym" >&2
exit 1
fi

echo "Installing ksym (gen_ksym) via cargo..." >&2
cargo install ksym
}

ensure_tools() {
ensure_llvm_tools

if ! command -v rust-nm >/dev/null 2>&1 || ! command -v rust-objcopy >/dev/null 2>&1; then
install_rust_binutils
fi
if ! command -v gen_ksym >/dev/null 2>&1; then
install_ksym
fi

command -v rust-nm >/dev/null 2>&1
command -v rust-objcopy >/dev/null 2>&1
command -v gen_ksym >/dev/null 2>&1
}

generate_kallsyms() {
symbols=$(mktemp "${KERNEL_ELF}.symbols.XXXXXX")
kallsyms=$(mktemp "${KERNEL_ELF}.kallsyms.XXXXXX")
trap 'rm -f "$symbols" "$kallsyms"' EXIT

rust-nm -n "$KERNEL_ELF" > "$symbols"
grep ' [TtDBR] ' "$symbols" \
| awk '$3 !~ /^\.L/' \
| awk '$3 != "$x"' \
Comment thread
Godones marked this conversation as resolved.
Comment thread
Godones marked this conversation as resolved.
Comment thread
Godones marked this conversation as resolved.
Comment thread
Godones marked this conversation as resolved.
Comment thread
Godones marked this conversation as resolved.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 非阻塞建议:awk '$3 != "$x"'$x 在 awk 单引号内被当作字面字符串,该条件几乎恒为真,等于无过滤。如果目的是去重,建议改为 awk '!seen[$3]++';如果不需要额外过滤,可直接移除此行管道。

| gen_ksym > "$kallsyms"
Comment thread
Godones marked this conversation as resolved.

rust-objcopy --update-section .kallsyms="$kallsyms" "$KERNEL_ELF"
}

refresh_bin_if_present() {
bin="${KERNEL_ELF%.elf}.bin"
if [ -f "$bin" ]; then
rust-objcopy --strip-all -O binary "$KERNEL_ELF" "$bin"
fi
}

if [ -z "${KERNEL_ELF:-}" ]; then
echo "KERNEL_ELF is required for Starry kallsyms generation" >&2
exit 1
fi

ensure_tools
generate_kallsyms
refresh_bin_if_present
2 changes: 1 addition & 1 deletion scripts/axbuild/src/arceos/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1634,7 +1634,6 @@ mod tests {
env: Default::default(),
target: "x86_64-unknown-none".to_string(),
package: package.to_string(),
bin: None,
features: Vec::new(),
log: None,
extra_config: None,
Expand All @@ -1644,6 +1643,7 @@ mod tests {
pre_build_cmds: Vec::new(),
post_build_cmds: Vec::new(),
to_bin: false,
bin: None,
},
qemu: QemuConfig::default(),
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/axbuild/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@ impl BuildInfo {
env: self.env,
target,
package,
bin: None,
features: self.features,
log: Some(self.log),
extra_config: None,
Expand All @@ -169,6 +168,7 @@ impl BuildInfo {
pre_build_cmds: vec![],
post_build_cmds: vec![],
to_bin,
bin: None,
}
}

Expand Down
Loading