Skip to content

Commit 9a70a86

Browse files
committed
[lld][macho] Error out gracefully when offset is outside literal section
We typically shouldn't get this, but when we do (e.g. in #139439) we should error out gracefully instead of crashing. Note that we are stricter than ld64 here; ld64 appears to be able to handle section offsets that point outside literal sections if the end result is a valid pointer to another section in the input object file. Supporting this would probably be a pain given our current design, and it seems like enough of an edge case that it's onot worth it.
1 parent 405f30f commit 9a70a86

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lld/MachO/InputSection.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,9 @@ WordLiteralInputSection::WordLiteralInputSection(const Section &section,
348348
}
349349

350350
uint64_t WordLiteralInputSection::getOffset(uint64_t off) const {
351+
if (off >= data.size())
352+
fatal(toString(this) + ": offset is outside the section");
353+
351354
auto *osec = cast<WordLiteralSection>(parent);
352355
const uintptr_t buf = reinterpret_cast<uintptr_t>(data.data());
353356
switch (sectionType(getFlags())) {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
## Test that we properly detect and report out-of-bounds offsets in literal sections.
2+
## We're intentionally testing fatal errors (for malformed input files), and
3+
## fatal errors aren't supported for testing when main is run twice.
4+
# XFAIL: main-run-twice
5+
6+
# REQUIRES: x86
7+
# RUN: rm -rf %t; split-file %s %t
8+
9+
## Test WordLiteralInputSection bounds checking
10+
# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %t/word-literal.s -o %t/word-literal.o
11+
# RUN: not %lld -dylib %t/word-literal.o -o /dev/null 2>&1 | FileCheck %s --check-prefix=WORD
12+
13+
## Test CStringInputSection bounds checking
14+
# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %t/cstring.s -o %t/cstring.o
15+
# RUN: not %lld -dylib %t/cstring.o -o /dev/null 2>&1 | FileCheck %s --check-prefix=CSTRING
16+
17+
# WORD: error: {{.*}}word-literal.o:(__literal4): offset is outside the section
18+
# CSTRING: error: {{.*}}cstring.o:(__cstring): offset is outside the section
19+
20+
#--- word-literal.s
21+
## Create a 4-byte literal section with a reference that points past the end
22+
.section __TEXT,__literal4,4byte_literals
23+
_literal:
24+
.word 0x01020304
25+
26+
.text
27+
.globl _main
28+
_main:
29+
.long _literal + 4
30+
31+
#--- cstring.s
32+
## Create a cstring section with a reference that points past the end
33+
.cstring
34+
_str:
35+
.asciz "foo"
36+
37+
.text
38+
.globl _main
39+
_main:
40+
## Reference past the null terminator (offset 4 in a 4-byte string including null)
41+
.long _str + 4

0 commit comments

Comments
 (0)