`link_section` contents is not correct for slices and strings

Very simple example:

#[link_section = "hello"]
static HELLO: &str = "world";

When dumping contents with objdump --full-contents -j hello I'm getting this:

Contents of section hello:
 57060 00700400 00000000 05000000 00000000  .p..............

And the same with readelf -x hello:

Hex dump of section 'hello':
  0x00057060 00700400 00000000 05000000 00000000 .p..............

But those hex bytes are clearly not text that I want :thinking:

I tried &[u8] with the same result, making text longer sometimes changes some bytes, but ultimately doesn't change the size of the section and doesn't result in the correct text. Using a single u32 or u8 number I can see the number in hex output though.

Tried both default linker and mold with rustc 1.83.0 on Ubuntu 24.04.

Am I doing something wrong?

I assume the string (world) is placed in a read-only section and a reference to that string is being stored in the hello section. If you want the string to be placed in the hello section you will probably have to make HELLO an array instead of a reference.

2 Likes

e.g.

#[link_section = "hello"]
pub static HELLO: [u8; 5] = *b"world";

Slice/str pointers are wide pointers; the second usize is the length. That's what the 05000000 00000000 is.

3 Likes

Yep, that was it :sweat_smile:
Thanks a lot!

1 Like