min-sized-rust
min-sized-rust copied to clipboard
Custom ld script
I created a custom ld script that makes elf64 binary smaller.
It is possible to add this script to build sequence by creating build.rs file:
fn main() {
println!("cargo:rustc-link-arg=-Wl,-T,elf64-min.ld");
}
Here is elf64-min.ld:
OUTPUT_FORMAT("elf64-x86-64")
ENTRY(_start)
PHDRS {
text PT_LOAD FILEHDR PHDRS;
/*tls PT_TLS;*/ /* uncomment this if you use std or pthreads */
interp PT_INTERP;
dynamic PT_DYNAMIC;
}
SECTIONS
{
. = SIZEOF_HEADERS;
t : {
KEEP (*(.init))
*(.text*)
KEEP (*(.fini))
*(.rodata*)
*(.data*)
*(.bss*)
} :text
.init_array : {
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT_BY_INIT_PRIORITY(.init_array*)))
PROVIDE_HIDDEN (__init_array_end = .);
} :text
.rel : { *(.data.rel*) } :text
td : { *(.tdata*) } :text :tls
tb : { *(.tbss*) } :text :tls
i : {
*(.interp)
} :text :interp
d : {
*(.dynamic)
*(.got)
*(.got.*)
*(.gnu.*)
*(.dynsym)
} :dynamic :text
/DISCARD/ : { *(.note*) }
}
@cbytensky This looks cool. I think the proper format for min-sized-rust itself would be for this to be put into a blog post that we reference. Optionally, it could probably be a GitHub Gist with some explanation text and the code above.
Hi, is the ld script working for target x86_64-unknown-linux-musl, I tried shows the error. thanks!
/target/x86_64-unknown-linux-musl/release/deps/sd-51a80456a558079f: The first section in the PT_DYNAMIC segment is not the .dynamic section
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status
The first section in the PT_DYNAMIC segment is not the .dynamic section
As this error message suggests, itβs designed for dynamically linked binaries, not static; x86_64-unknown-linux-musl target is for static linking. You can try it with -C target-feature=-crt-static to force dynamic linking (with native libraries, not rust libraries).
I wrote more detailed issue: https://github.com/johnthagen/min-sized-rust/issues/44 So closing this issue.