knurling-rs / flip-link

Adds zero-cost stack overflow protection to your embedded programs
Apache License 2.0
271 stars 6 forks source link

flip-link does not respect `memory.x` overrides #43

Closed japaric closed 2 years ago

japaric commented 3 years ago

Steps to reproduce

  1. Instantiate the app-template for the nRF52840 (add nrf52840-hal as a dependency).

  2. Create a memory.x override

$ # run hal crate build script -> puts memory.x in target
$ cargo check --lib

$ cp `fd memory.x target` .

$ # halve the amount of RAM
$ $EDIT memory.x
$ bat memory.x
MEMORY
{
  FLASH : ORIGIN = 0x00000000, LENGTH = 1024K
  RAM : ORIGIN = 0x20000000, LENGTH = 128K
}
  1. Inspect produced binaries
$ # `touch` = force relinking; or use `cargo clean`
$ touch src/bin/hello.rs
$ cargo size --bin hello -- -A -x
hello  :
section                size         addr
.vector_table         0x100          0x0
.text                0x145c        0x100
.rodata               0x4ac       0x155c
.data                  0x30   0x2003fbc8
.bss                    0x8   0x2003fbf8
.uninit               0x400   0x2003fc00

$ cargo nm --bin hello -- --demangle --numeric-sort | rg stack
2003fbc8 A _stack_start

Both binary tools indicate that flip-link thinks the RAM size is 256 KiB (0x4_0000) even though the memory.x override indicates 128 KiB

  1. Compare against rust-lld (disable flip-link)
$ $EDIT .cargo/config.toml
$ bat .cargo/config.toml
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
runner = "probe-run --chip nrf52840"
rustflags = [
  # "-C", "linker=flip-link", # <- disabled
  "-C", "link-arg=-Tlink.x",
  "-C", "link-arg=-Tdefmt.x",
  "-C", "link-arg=--nmagic",
]

$ cargo size --bin hello -- -A -x
hello  :
section                size         addr
.vector_table         0x100          0x0
.text                0x145c        0x100
.rodata               0x4ac       0x155c
.data                  0x30   0x20000000
.bss                    0x8   0x20000030
.uninit               0x400   0x20000038

$ cargo nm --bin hello -- --demangle --numeric-sort | rg stack
20020000 A _stack_start

rust-lld respects the memory.x override and uses 128 KiB as the size of the RAM region

Meta

flip-link version

$ cargo install --list | rg ^flip-link
flip-link v0.1.4:
japaric commented 3 years ago

I don't know if this is documented in LD/LLD docs but from what I've seen linker scripts are searched for in the "linker search path". The first (highest precedence) entry in the linker search path is the current directory; other entries are specified via the -L flag.

When looking for the MEMORY entry in linker scripts, flip-link should follow the above (MEMORY.x in current directory should take precedence over the one in the target directory)

japaric commented 2 years ago

update: fixed in #63 but not in latest crates.io release (v0.1.5)

japaric commented 2 years ago

flip-link v0.1.6 has been released and includes this fix