litex icon indicating copy to clipboard operation
litex copied to clipboard

Solved linker.ld issue causing unaligned access

Open pratipm opened this issue 2 months ago • 0 comments

Not sure if this is already known issue. I was having program hang right after load. Turned out to be linker alignment issue. I was using linker.ld from the litex demo program. That script does not protect from crt0.S doing 4 byte transfers causing the issue. Actually I did not detect or solve the issue, ChatGPT did. After a fairly length conversation, together we came to a solution which is a modified linker script. This is the final verdict from ChatGPT:

The real root cause was that your startup (crt0.S) performs the .data copy using word-sized (4-byte) loads/stores. That’s perfectly normal for most bare-metal toolchains, because copying in 32-bit words is faster and simpler.

But in your original linker script:

The ROM load address (LMA) of .data was placed immediately after .rodata.

.rodata ended on an odd address (for example, 0x…1C93) because of a 1-byte-aligned object like a 6-byte MAC array.

When the CRT started copying .data 4 bytes at a time from that unaligned LMA, the very first lw caused a bus error or misaligned access trap (depending on core).

So yes — it wasn’t the presence of a 6-byte object that’s “illegal”; it was the combination of:

unaligned LMA (.data starts at odd address)

  • 4-byte copy loop in crt0 → misaligned fetch before main()

The final linker script we built fixed it by rounding the ROM cursor up to a 4-byte boundary (.rompad) before assigning .data’s LMA, so the startup’s word copy is now safe no matter what .rodata contains.

Attaching the fixed linker script (change the .txt to .ld)

linker.txt

pratipm avatar Nov 12 '25 07:11 pratipm