min-sized-rust icon indicating copy to clipboard operation
min-sized-rust copied to clipboard

Custom ld script

Open cbytensky opened this issue 3 years ago β€’ 3 comments

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 avatar Mar 30 '22 16:03 cbytensky

@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.

johnthagen avatar Mar 30 '22 16:03 johnthagen

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

xqdoo00o avatar Jul 25 '22 11:07 xqdoo00o

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).

jirutka avatar Jul 25 '22 16:07 jirutka

I wrote more detailed issue: https://github.com/johnthagen/min-sized-rust/issues/44 So closing this issue.

cbytensky avatar Sep 16 '22 18:09 cbytensky