by MuffinFlavored · 2y ago · 0 comments
#![no_std]
#![no_main]
use core::panic::PanicInfo;
#[panic_handler]
fn panic_handler(_panic: &PanicInfo<'_>) -> ! {
// TODO: write panic message to stderr
write(2, "Panic occured\n".as_bytes()); // TODO: panic location + message
unsafe { sc::syscall!(EXIT, 255 as u32) };
loop {}
}
fn write(fd: usize, buf: &[u8]) {
unsafe {
sc::syscall!(WRITE, fd, buf.as_ptr(), buf.len());
}
}
#[no_mangle]
pub extern "C" fn main() -> u32 {
write(1, "Hello, world!\n".as_bytes());
return 0;
}
Then I inspected the ELF output in Ghidra. No matter what it was about ~16kb. I'm sure some code golf could be done to get it done (which has obviously been done + written about + documented before) rustc hello.rs -C panic=abort -C opt-level=3 -C link-arg=/entry:main
Here's the program: #![no_std]
#![no_main]
#[panic_handler]
fn panic_handler(_panic: &core::panic::PanicInfo<'_>) -> ! {
unsafe { ExitProcess(111) };
}
#[no_mangle]
pub extern "C" fn main() -> u32 {
let msg = b"Hello, world!\n";
unsafe {
let stdout = GetStdHandle(-11);
let mut written = 0;
WriteFile(
stdout,
msg.as_ptr(),
msg.len() as u32,
&mut written,
core::ptr::null_mut(),
);
}
0
}
#[link(name = "kernel32")]
extern "system" {
fn ExitProcess(uExitCode: u32) -> !;
fn GetStdHandle(nStdHandle: i32) -> isize;
fn WriteFile(
hFile: isize,
lpBuffer: *const u8,
nNumberOfBytesToWrite: u32,
lpNumberOfBytesWritten: *mut u32,
lpOverlapped: *mut (),
) -> i32;
}
I didn't bother much with the panic handler because there's no reason to in hello world. Though the binary contains a fair bit of padding still so it could have a few more things added to it without increasing the size. Alternatively I could shrink it a bit further by doing crimes but I'm not sure there's much point.It may be worth noting that the associated pdb (aka debug database) is 208,896 bytes.
rustc hello.rs -C panic=abort -C opt-level=3 -C link-args="/ENTRY:main /DEBUG:NONE /EMITPOGOPHASEINFO /EMITTOOLVERSIONINFO:NO /ALIGN:16"You can easily get around 500 bytes this way
(and if you're using a language with a stack, your executable probably ultimately loads as at least two pages: r/o and r/w)
I need roughly 24 bytes. 16kb means 16.384 bytes. I can think of better usage of $4000 space in memory, FLI for example.
In that sense, they are not "lost", just merely "unused".
So now it would be interesting to see how much of the 16kB were not padding, though. OP said they looked at it with Ghidra, so did they see 16kB of actual code?