-Ttext is a bit wierd feature and gold/bfd are inconsistent here.
I took loader reproduce from PR31295, which has:
--omagic -Ttext 0x0
LLD crashed before this patch, beacause tried to calculate offset with:
return First->Offset + Sec->Addr - First->Addr; where First->Offset == 0x0, Sec->Addr == 0x0 (-Ttext), First->Addr = 0x10000 (Header)
gold linker ignores setting -Ttext to specified value. For example for case above it do:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .text PROGBITS 00000080 000080 00ba74 00 AX 0 0 16 [ 2] .rodata PROGBITS 0000bb00 00bb00 0035fc 00 A 0 0 16 [ 3] .got PROGBITS 0000f0fc 00f0fc 000000 00 WA 0 0 4
So noticable that address of .text is not what user specified. It is shifted by size of headers.
Also file offsets are aligned.
bfd instead in the same situation looks ignores file offset aligning and do exactly what user asked:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .text PROGBITS 00000000 000080 00ba74 00 WAX 0 0 16 [ 2] .rodata PROGBITS 0000ba80 00bb00 0035f4 00 A 0 0 16 [ 3] .got.plt PROGBITS 0000f074 00f0f4 00000c 04 WA 0 0 4
I think we can try to do the same for now, that what this patch do.
This fixes crash of PR31295.