Skip to content

Commit

Permalink
init: Adopt opendir() and readdir() syscalls
Browse files Browse the repository at this point in the history
Use opendir() and readdir() for dm discovery. Currently, it naively runs
the first file discovered under /bin.

Co-developed-by: Vijay Dhanraj <[email protected]>
Signed-off-by: Peter Fang <[email protected]>
  • Loading branch information
peterfang authored and vijaydhanraj committed Oct 27, 2024
1 parent 3b272b7 commit 4bd9aa2
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions init/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@

extern crate alloc;
use alloc::ffi::CString;
use alloc::string::String;
use buddy_system_allocator::*;
use core::ffi::CStr;
use core::panic::PanicInfo;
use syscall::{exec, exit, SysCallError};
use syscall::{exec, exit, opendir, readdir, DirEnt, FileType, SysCallError};

const HEAP_SIZE: usize = 64 * 1024;
static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
Expand All @@ -27,13 +29,41 @@ pub extern "C" fn init_start() -> ! {
.init(core::ptr::addr_of!(HEAP) as usize, HEAP_SIZE);
}

let file = CString::new("/dummy").expect("Failed to create new string");
let root = CString::new("/").expect("Failed to create new string");
let bin = CString::new("/bin/").unwrap();
let Ok(obj) = opendir(&bin) else {
exit(0);
};
let mut dirents: [DirEnt; 8] = Default::default();
let mut binfile: Option<CString> = None;

loop {
let n = readdir(&obj, &mut dirents).unwrap();
if let Some(d) = dirents
.iter()
.take(n)
.find(|d| d.file_type == FileType::File)
{
binfile = Some(CString::from(
CStr::from_bytes_until_nul(&d.file_name).unwrap(),
));
break;
}
if n < dirents.len() {
break;
}
}
let binfile = binfile.unwrap_or_else(|| exit(0));

let mut file = String::from(bin.as_c_str().to_str().unwrap());
file.push_str(binfile.as_c_str().to_str().unwrap());

let file = CString::new(file).unwrap();
let root = CString::new("/").unwrap();

match exec(&file, &root, 0) {
Ok(_) => exit(0),
Err(SysCallError::ENOTFOUND) => exit(1),
_ => panic!("exec launch failed"),
_ => panic!("{} launch failed", file.to_str().unwrap()),
};
}

Expand Down

0 comments on commit 4bd9aa2

Please sign in to comment.