running the ld command through rust only works 50% of the time

49 Views Asked by At

I'm trying to create a compiler in rust. I'm now at a point where I want to link the outputted object file into an executable with this command ld test.o -o test. When I run this command manually in the shell, it always works. Though, when I let rust do it, it sometimes works and sometimes gives this error: ld: warning: cannot find entry symbol _start; not setting start address

It's truly 50/50 and I have no idea what is causing this.

This is how I run the command:

process::Command::new("ld")
    .arg(format!("{}.o", outputfile))
    .arg("-o")
    .arg(&outputfile)
    .spawn()
    .expect("Failed to link");

I've tried to debug this by checking what rust actually runs by printing out the command like this:

println!(
    "{:?}",
    process::Command::new("ld")
        .arg(format!("{}.o", outputfile))
        .arg("-o")
        .arg(&outputfile)
);

This will print out: "ld" "test.o" "-o" "test" which I copied directly into my shell which worked without any issue.

It's very weird and I've been trying to fix this for way too long now. Please help if you know what might be causing this.

Edit: In case there is any extra information you need in order to help, you can find all of the code on my GitHub: https://github.com/sten-code/rlangc The issue is about the code all the way at the bottom of main.rs inside the build function. Please note that I started learning rust yesterday so the code might suck.

1

There are 1 best solutions below

0
GHOST On

Fixed Issue

The issue was that I was running a nasm command right before the linker command. The linker relies on the output of the nasm command. Command::spawn in Rust runs commands asynchronous, so when I was running the linker command there was a 50% chance that the nasm command wasn't done creating the object file resulting it in a crash. Thanks to @cafce25 for pointing this out to me.