4550 Commits

Author SHA1 Message Date
Brian Cain
62d018b87a
[lld][Hexagon] Fix R_HEX_TPREL_11_X relocation on duplex instructions (#179860)
findMaskR11() was missing handling for duplex instructions. This caused
incorrect encoding when R_HEX_TPREL_11_X relocations were applied to
duplex instructions with large TLS offsets.

For duplex instructions, the immediate bits are located at positions
20-25 (mask 0x03f00000), not in the standard positions used for
non-duplex instructions.

This fix adds the isDuplex() check to findMaskR11() to return the
correct mask for duplex instruction encodings.
2026-02-09 14:45:36 -06:00
Fangrui Song
0d52536b04 [ELF][test] Consolidate .eh_frame FDE encoding tests
Merge eh-frame-value-format{1..9}.s into eh-frame-fde-encoding.s
(encoding is the DWARF term) using split-file. Add .eh_frame and
.eh_frame_hdr content verification for absptr, udata2, sdata4, udata4.
Move error test (9) to eh-frame-invalid-fde-encoding.s.
2026-02-05 23:41:45 -08:00
Fangrui Song
2d8ce3a313 [ELF][test] Consolidate invalid-eh-frame tests
Merge 9 individual invalid-eh-frame test files into 2 categorized files
using split-file:

- eh-frame-invalid-cie.s: CIE structure errors (too small, unexpected
  end, failed string/LEB128 reads)
- eh-frame-invalid-fde-encoding.s: EhReader::getFdeEncoding errors
  (unknown augmentation string, unknown FDE encoding, unsupported
  aligned encoding, corrupted CIE)
2026-02-05 21:30:45 -08:00
Fangrui Song
adf7dbc2a8 [ELF,test] Improve error message tests
They have multiple `not ld.lld` commands or they test multiple error
messages. Add --implicit-check-not=error: to catch unexpected errors.
While updating them, use directory isolation pattern and simplify
filenames where appropriate.

Rename abs-conflict.s to conflict-abs.s to be consistent with other
conflict*.s tests.
2026-02-04 20:29:54 -08:00
Fangrui Song
d53bf41395
[ELF] Support DW_EH_PE_sdata8 encoding in .eh_frame_hdr (#179089)
Currently, both GNU ld and lld only support
`table_enc = DW_EH_PE_datarel | DW_EH_PE_sdata4` for .eh_frame_hdr.
When a table entry exceeds the 32-bit range, we can use
`DW_EH_PE_sdata8` instead of reporting an error
(https://reviews.llvm.org/D49607 introduced the "PC offset is too large"
error). This is useful for certain large executables.

This patch auto-detects when 64-bit encoding is needed and upgrades
the encoding accordingly. We use DW_EH_PE_sdata8 when either a table
entry or eh_frame_ptr exceeds the 32-bit range.

Technically, eh_frame_ptr could remain sdata4 when only table entries
require sdata8, but there is little value in this flexibility since
.eh_frame/.eh_frame_hdr distance is a much less strict constraint than
.text/.eh_frame_hdr distance.

The implementation caches FDE data in EhFrameHeader during
updateAllocSize and reuses it in writeTo.

Previously, `EhFrameSection::getFdePc` was used to read the
`initial_location` value from .eh_frame FDEs. Since the value equals the
relocated symbol's VA for all cases that matter, we now obtain the value
directly and simplify the implementation.

Also update the outdated comment about sorting the FDE list; the ICF
case mentioned there no longer applies after
https://reviews.llvm.org/D116093.

In the new test eh-frame-hdr-sdata8.s, 3.lds is carefully crafted to
ensure that .eh_frame_hdr size requires fixed-point iteration (to test
`updateAllocSize`). This is also groundwork for compact unwind support
similar to Mach-O `__unwind_info`.

Close #172777
2026-02-03 19:58:52 -08:00
Fangrui Song
6a18039298 [ELF,test] Improve riscv and aarch64 relocation error tests
Adopt modern test patterns for relocation overflow and alignment error
tests:

* Use `rm -rf %t && mkdir %t && cd %t` pattern for isolation. Use simple
  filenames (32.o, 64.o, out.32) instead of %t-prefixed names
* Use `--defsym` instead of external input files where possible
* Omit `-o /dev/null` for negative tests (implicit when errors occur)
* Add `--implicit-check-not=error:` to catch unexpected errors
2026-02-01 14:56:19 -08:00
Fangrui Song
2f09bd2fc2 [ELF,test] Improve error/warning message checks
Update tests to include proper `error:` or `warning:` prefixes and
file/section information in CHECK patterns. Add
--implicit-check-not=error: to ensure no unexpected errors are produced.
2026-02-01 11:25:22 -08:00
Fangrui Song
9065730178 [ELF,test] Improve error message checks with proper format
Update tests to use the canonical error message format with `error:`
prefix and file:section information. Add `--implicit-check-not=error:`
to ensure no unexpected errors are produced.

This commit focuses on "out of range" and "not aligned" errors.
2026-02-01 10:27:59 -08:00
Fangrui Song
bc45ea2c4f
[ELF] Fix IRELATIVE addend if the resolver address is updated by linker relaxation (#179063)
For a non-preemptible ifunc, `handleNonPreemptibleIfunc` creates a
cloned
symbol (`directSym`) to compute the addend of the IRELATIVE dynamic
relocation.
This cloned symbol wasn't tracked by `initSymbolAnchors`, so its value
wasn't adjusted during RISC-V/LoongArch linker relaxation.
This caused IRELATIVE addends to point to pre-relaxation addresses.

Fix this by:

- Tracking cloned IRELATIVE symbols in `ctx.irelativeSyms`
- Adding these symbols to `relaxAux->anchors` in `initSymbolAnchors`
2026-01-31 21:51:03 +00:00
Jessica Clarke
859d3b8e9c
[ELF][AArch64][PAC][MTE] Handle Memtag globals for R_AARCH64_AUTH_ABS64
Currently, R_AARCH64_AUTH_ABS64 against a tagged global just ignores the
tagging and so, if out of the symbol's bounds, does not write the
negated original addend for the loader to determine which granule's tag
to use for it. Handle the composition of the two.

Note that R_AARCH64_AUTH_ABS64/RELATIVE encode the signing schema in the
upper 32 bits of the value at the relocation target, and so only the
lower 32 bits are available for use as an addend, including for Memtag's
disambiguation, and so if a wildly out-of-bounds PAuth relocation
against a tagged global is used we have no choice but to error out with
the current ABI.

Reviewers: MaskRay, kovdan01, smithp35, asl

Reviewed By: smithp35

Pull Request: https://github.com/llvm/llvm-project/pull/173291
2026-01-31 18:06:31 +00:00
Fangrui Song
7dfa132936
[ELF,RISCV] Fix code style after #169273 (#178365) 2026-01-28 20:13:17 -08:00
Zachary Yedidia
fcd609762c
[lld] Fill section gaps with trap instructions (#176845)
Fills unused parts of code segments with trap instructions instead of
zeroes. This is especially useful on x86-64 since 0x00 0x00 is a
two-byte instruction that performs a memory access. Benefits:

- Provides an explicit trap when executing invalid code.
- Required for security reasons when targeting LFI.
- Makes disassembling easier, especially without symbol information.
Previously an odd number of zero bytes between sections could cause a
disassembler to incorrectly disassemble the remainder of the program.
2026-01-28 15:32:29 -08:00
Rose Hudson
e45ea95dbe
[DTLTO] support distributing bitcode from FatLTO objects (#176928)
We already have code to extract bitcode files from archives so they can
be distributed. Extend this code to extract bitcode from FatLTO objects
too, which otherwise cannot be used with DTLTO.
2026-01-28 17:45:58 +00:00
Fangrui Song
e34651fa55
[ELF] Set vna_flags to VER_FLG_WEAK if all references are weak (#176673)
When all undefined references to a version are weak, set vna_flags to
VER_FLG_WEAK in the .gnu.version_r section. This enables glibc ld.so to
report a warning instead of an error when the required version is not
found at runtime, supporting optional dependencies.

Per https://sourceware.org/bugzilla/show_bug.cgi?id=24718#c20 ,
glibc rtld since 2.30 (BZ #24741) tolerates missing versioned symbols
when the runtime shared object defines the required version. With this
vna_flags VER_FLG_WEAK change, rtld can also tolerate a completely
missing version, printing a message like:

```
% LD_PRELOAD=c2.so ./a
./a: /tmp/t/v2/c2.so: weak version `v1' not found (required by /tmp/t/v2/b.so)
a
```

instead of a fatal error.

In addition, add a comment about `vn.vernaxus.size() == 1`.
2026-01-23 20:43:52 -08:00
Fangrui Song
1869b15a05
[ELF] --why-live: Skip symbol at index 0 and section symbols, handle .eh_frame symbols (#177099)
Symbols of empty names can be matched by `--why-live='*'`, which are
generally not useful.

* The first entry in a symbol table (STB_LOCAL and undefined)
* `STT_SECTION` symbols (emitted by LLVM integrated assembler when
  needed by relocations). These input section symbols will be demoted by
  `demoteAndCopyLocalSymbols`, so technically not really live.
  In addition, such symbols of non-allocable sections currently lead to
  crashes: `whyLive` does not record the section, causing the second
  iteration of the `while (true)` loop in printWhyLive to call
  `std::get<Symbol *>(cur)` when `cur` is an `InputSectionBase *`.

In addition, handle GCC crtendS.o `__FRAME_END__`, which is defined
relative to a `.eh_frame` section created with
`__attribute__((used, section(".eh_frame")))`.

Fix #176890
2026-01-22 02:58:35 +00:00
Ben Dunbobbin
31f5be4ce5
[DTLTO] Add DTLTO-specific LTO input handling time-trace scopes (#175799)
Add time-trace scopes to the DTLTO-specific input-handling code to
improve observability and debugging.

These scopes are tested via LLD, as the primary purpose of this code is
to support member files of non-thin archives as DTLTO inputs.
`llvm-lto2` does not currently support archives. Adding archive support
to `llvm-lto2` solely for testing these scopes does not appear to be
worthwhile.

As part of this change, the deletion of temporary DTLTO input files has
been moved. Cleanup now occurs after LTO has completed, rather than
during destruction of the LTO object. This is required since by the time
the LTO object is destroyed, time-traces have already been finalized, so
no additional trace data can be recorded.

Recording time-trace data for temporary file deletion is important, as
this has been a source of performance issues in the past and an area
where we expect to make further performance improvements if supported by
the data.

SIE internal tracker: TOOLCHAIN-21021
2026-01-19 14:06:58 +00:00
Jessica Clarke
9b409e3651
[ELF][Mips] Fix addend for preemptible static TLS
If the symbol is preemptible the addend should be 0, not our
definition's VA. Note that by using addAddendOnlyRelocIfNonPreemptible
the generic Elf_Rel code will ensure the VA is written out as the addend
if the symbol is non-preemptible, and so writeTo only needs to write out
the VA in the case that we don't call it (so long as we make sure to
call relocateAlloc to actually apply any such relocations).

Reviewers: MaskRay

Pull Request: https://github.com/llvm/llvm-project/pull/150729
2026-01-16 18:50:43 +00:00
hev
019bf03697
[lld][LoongArch] Support reloc types for LA32R/LA32S (#172618)
This patch adds support for processing the relocation types introduced
in la-abi-specs v2.50.

Link: https://github.com/loongson/la-abi-specs/pull/16
Link:
https://sourceware.org/pipermail/binutils/2025-December/146091.html
2026-01-15 19:54:52 +08:00
WANG Rui
2b260c665c [lld][LoongArch][NFC] Explicitly enable LA32S in LA32 test cases 2026-01-10 22:58:25 +08:00
Tarcísio Fischer
e91447f44d
Fix lld crash using --fix-cortex-a53-843419 (#170495)
Original crash was observed in Chromium, in [1]. The problem occurs in
elf::isAArch64BTILandingPad because it didn't handle synthetic sections,
which can have a nullptr as a buf, so it crashed while trying to read
that buf.

After fixing that, a second issue occurs: When the patched code grows
too
much, it gets far away from the short jump, and the current
implementation
assumes a R_AARCH64_JUMP26 will be enough.

This PR changes the implementation to:
(a) In isAArch64BTILandingPad, checks if a section is synthetic, and
assumes that it'll NOT contain a landing pad, avoiding the buffer check;
(b) Suppress the size rounding for thunks that preceeds section
(Making the situation less likely to happen);
(c) Reimplements the patch by using a R_AARCH64_ABS64 in case the
patched code is still far away.

[1] https://issues.chromium.org/issues/440019454

---------

Co-authored-by: Tarcisio Fischer <tarcisio.fischer@arm.com>
2026-01-09 11:08:09 +00:00
Fangrui Song
16be2c0555
[ELF] Add VersionNode lexer state for better version script parsing
... so that `local:*;` will be lexed as three tokens instead of a single
one in a version node. This is used by both version scripts and dynamic
lists. Fix #174363

In addition, clean up special code for space-separated `local :` and `global :`.

This patch brings our lexer behavior closer to GNU ld. While GNU ld
additionally rejects more characters like `~/+,=`, we don't implement
this additional validation.

Pull Request: https://github.com/llvm/llvm-project/pull/174530
2026-01-06 22:19:44 -08:00
Jessica Clarke
85ec904b0e
[ELF] Include sharded relocations in RelocationBaseSection::getSize
Although mergeRels is called prior to using this size for final layout,
Writer::setReservedSymbolSections uses this in order to set the value of
__rel[a]_iplt_end and, downstream in Morello LLVM, __rel[a]_dyn_end.
Currently none of the relocations that can exist when static linking (as
the case when these symbols are defined) are sharded, but a future
commit will change this for R_AARCH64_AUTH_RELATIVE, and similarly
R_MORELLO_RELATIVE is sharded downstream in Morello LLVM. Make sure we
compute the right size when called prior to mergeRels, and add a
regression test to demonstrate that R_AARCH64_AUTH_RELATIVE still gets
the right __rel[a]_ipt_end in future even when sharding is adopted.

Reviewers: MaskRay

Reviewed By: MaskRay

Pull Request: https://github.com/llvm/llvm-project/pull/173285
2025-12-24 11:04:25 +00:00
Nikita Popov
4fbbdb4f6b
[lld] Adjust compressed-debug-level test for s390x with DFLTCC (#172972)
After enabling DFLTCC in zlib-ng for s390x this test starts failing,
because slightly better compression is produced at level 1. Add 1c as a
permissible output.
2025-12-19 17:02:24 +01:00
Owen Anderson
0c6d7a4018
[LLD] Add support for statically resolved vendor-specific RISCV relocations. (#169273)
This is achieved by using some of the bits of RelType to tag vendor namespaces. This change also adds a relocation iterator for RISCV that folds vendor namespaces into the RelType of the following relocation.

This patch is extracted from the implementation of RISCV vendor-specific relocations in the CHERIoT LLVM downstream: 3d6d6f7d94
2025-11-27 21:34:07 -06:00
Fangrui Song
d96a93ff00
ELF: Use index 0 for unversioned undefined symbols (#168189)
The GNU documentation is ambiguous about the version index for
unversioned undefined symbols. The current specification at
https://sourceware.org/gnu-gabi/program-loading-and-dynamic-linking.txt
defines VER_NDX_LOCAL (0) as "The symbol is private, and is not
available outside this object."

However, this naming is misleading for undefined symbols. As suggested
in
discussions, VER_NDX_LOCAL should conceptually be VER_NDX_NONE and apply
to unversioned undefined symbols as well.

GNU ld has used index 0 for unversioned undefined symbols both before
version 2.35 (see https://sourceware.org/PR26002) and in the upcoming
2.46 release (see https://sourceware.org/PR33577). This change aligns
with GNU ld's behavior by switching from index 1 to index 0.

While here, add a test to dso-undef-extract-lazy.s that undefined
symbols of index 0 in DSO are treated as unversioned symbols.
2025-11-22 20:54:50 +00:00
Peter Collingbourne
13e09ebe2d
ELF: Add support for relocating R_AARCH64_FUNCINIT64.
R_AARCH64_FUNCINIT64 is a dynamic relocation type for relocating
word-sized data in the output file using the return value of
a function. An R_AARCH64_FUNCINIT64 shall be relocated as an
R_AARCH64_IRELATIVE with the target symbol address if the target
symbol is non-preemptible, and it shall be a usage error to relocate an
R_AARCH64_FUNCINIT64 with a preemptible or STT_GNU_IFUNC target symbol.

The initial use case for this relocation type shall be for emitting
global variable field initializers for structure protection. With
structure protection, the relocation value computation is tied to the
compiler implementation in such a way that it would not be reasonable to
define a relocation type for it (for example, it may involve computing
a hash using a compiler-determined algorithm), hence the need for the
computation to be implemented as code in the binary.

Part of the AArch64 psABI extension:
https://github.com/ARM-software/abi-aa/issues/340

Reviewers: smithp35, fmayer, MaskRay

Reviewed By: fmayer

Pull Request: https://github.com/llvm/llvm-project/pull/156564
2025-11-19 11:44:09 -08:00
Fangrui Song
ed1c8d7a57 ELF,test: Test unversioned undefined symbols of index 0 and 1
My 2020 change that added versioned symbol recognition
(reviews.llvm.org/D80059) checks both VER_NDX_LOCAL and VER_NDX_GLOBAL,
though test coverage was missing. lld/test/ELF/dso-undef-extract-lazy.s
checks that the undefined symbol is indeed considered unversioned.
2025-11-18 22:13:34 -08:00
David Spickett
a831c3fda7
[lld][test] Fix file cleanup in aarch64-build-attributes.s (#164396)
This test seems to have taken the lit documentation at its word:
https://llvm.org/docs/CommandGuide/lit.html#substitutions

"%t temporary file name unique to the test"

%t is in fact the **path** of a file. As suggested by the line below
that describing %basename_t.

This test (I assume) assumed it was just the filename itself and so left
a layout of:
```
$ tree tools/lld/test/
tools/lld/test/
├── CMakeFiles
├── ELF
│   └── Output
│       ├── aarch64-build-attributes.s.tmp
│       │   ├── pauth-bti-gcs.s
│       │   └── pauth-bti-pac.s
│       ├── aarch64-build-attributes.s.tmp.merged.o
│       ├── aarch64-build-attributes.s.tmp1.o
│       ├── aarch64-build-attributes.s.tmp2.o
│       └── aarch64-build-attributes.s.tmp3.o
├── Unit
│   └── lit.site.cfg.py
├── cmake_install.cmake
└── lit.site.cfg.py
```

Note how the 2 .s files are in the temp dir but the .o files are not.
This is fine, it works, but it's going to cost someone time to unpick
when this test actually does fail.

To fix this, remove %t from all the temp file names so they are created
in the temp dir, which is cleaned before each run.

New layout:
```
$ tree tools/lld/test/
tools/lld/test/
├── CMakeFiles
├── ELF
│   └── Output
│       └── aarch64-build-attributes.s.tmp
│           ├── 1.o
│           ├── 2.o
│           ├── 3.o
│           ├── merged.o
│           ├── pauth-bti-gcs.s
│           └── pauth-bti-pac.s
├── Unit
│   └── lit.site.cfg.py
├── cmake_install.cmake
└── lit.site.cfg.py
```
2025-10-31 11:32:37 +00:00
Simon Tatham
f2443861d7
[lld][ARM] Don't emit veneers for wraparound branches. (#165263)
If an instruction at the high end of the 32-bit address space branches
to one at the low end, then the branch can be within range for a B or BL
instruction, and doesn't need a veneer. `ARM::inBranchRange` was failing
to detect this because it calculated the offset as an int64_t, so that
the offset was a small value ± 2^32 instead of just the small value.

Fixes #165211.
2025-10-31 09:31:18 +00:00
Owen Anderson
9e7a3ee5ff [lld] Fix RISCV vendor relocation testcase to require RISCV
Fixes test issue introduced in 357b030f5e62a5891fd6120c02aa28d0874f0a06
2025-10-24 20:50:54 +09:00
Matt Arsenault
853760bca6
AMDGPU: Use ELF mangling in data layout (#163011)
Closes #95219
2025-10-13 03:01:45 +00:00
Fangrui Song
d30fe62cf1 ELF: Test .eh_frame relocation
EhInputSection currently uses scanSection path, getting ignored marker
relocations and undefined symbol diagnostics for free. This might change
in the future. Add test coverage.
2025-09-28 10:15:08 -07:00
Ivan Tadeu Ferreira Antunes Filho
61a535a2cd
[lld][ELF] Fix gc-sections-print.s failure in read-only directories (#160204)
If ld.lld is invoked without the `-o` option, it defaults to writing its
output to `a.out` in the current directory. This can cause 'Permission
denied' errors if a test is executed in a directory without write
permissions, as can happen in some build environments.

Add `-o %t2` to this command, consistent with other commands in the same
test file, to prevent this failure by ensuring ld.lld writes to a
temporary file instead of `a.out`.
2025-09-22 21:33:53 +00:00
mykouHW
507f394d03
[ELF] -r/--emit-relocs: Fix crash when processing .rela.text before .text (#156354)
fixes #156417 

When the relocation section is placed before the relocated section and
the relocated section is not defined in the linker script, an error will
occur during the linking process.

**Issue Cause:**  
In a.ro, `.rela.text` precedes its relocated `InputSection` `.text`.
`addOrphanSections` doesn't handle this scenario.
When it processes `.rela.text`, in the called `getOutputSectionName`,
`rel->getOutputSection()` is nullptr (input `.text` doesn't yet have a
parent output section), leading to an assertion failure.

**Solution:**  
For --emit-relocs and -r, ensure the output section for `.text.foo` is
created before the output section for `.rela.text.foo`.

---------

Co-authored-by: Fangrui Song <i@maskray.me>
2025-09-20 16:41:54 +00:00
Fangrui Song
cbb60a32d7
[ELF] Add --print-gc-sections=<file> (#159706)
Add `--print-gc-sections=<file>` to redirect garbage collection section
listing to a file, avoiding contamination of stdout with other linker
output. mold has recently added the option.
GNU ld feature request:
https://sourceware.org/bugzilla/show_bug.cgi?id=33331
2025-09-19 16:22:37 +00:00
Ádám Kallai
e11092824b
[llvm-readobj][ELF] Prints hex format values in lower-case mode (#156683)
Previously, llvm-readelf dumped hex format values in different ways.
Some of them were printed in upper-case, while the others were in
lower-case format. This change switches the format to lower-case in all
cases.

Why is this useful? As an example, FileCheck comparisons are
case-sensitive by default. This change means it's easier to compare
those values, because they have the same format.
2025-09-05 14:11:13 +01:00
Aiden Grossman
efbf5f50f4 [lld] Prefer printf over echo -e
Otherwise we break some MacOS bots when using the lit internal shell
because /bin/echo on MacOS does not support -e. Using the external shell
we end up using the echo builtin to /bin/bash, which does support this.

The echo builtin implementation in lit does support this, but that is
currently not enabled in pipelines. Might be worth looking into fixing
at some point.
2025-09-04 01:38:46 +00:00
Aiden Grossman
303bea8e63
[lld] Make cache-warning* tests work with internal shell
These tests were using subexpressions to change the cache size. Change
them up to write out the necessary commands to a response file and then
load that on the lld command line.

Towards #102700.

Reviewers: ilovepi, cmtice, mysterymath, MaskRay, petrhosek

Reviewed By: MaskRay

Pull Request: https://github.com/llvm/llvm-project/pull/156537
2025-09-03 09:41:19 -07:00
Aiden Grossman
55ec6373f9
[lld] Update tests redirecting multiple commands to FileCheck
This patch updates two LLD tests that were redirecting multiple commands
to the same FileCheck invocation to not use this strategy. This
construction is not supported by lit's internal shell and given its
rarirty, it does not make sense to add support. The workaround is to
dump the contents of multiple commands into a file and then run
FileCheck on that.

Towards #102700.

Reviewers: petrhosek, mysterymath, cmtice, ilovepi, carlocab, MaskRay

Reviewed By: carlocab, cmtice

Pull Request: https://github.com/llvm/llvm-project/pull/156526
2025-09-03 09:21:55 -07:00
Aiden Grossman
df9965cb5a
[lld] Remove shell requirements from tests
These tests all pass inside the lit internal shell. A couple were marked
as requiring a shell to exclude them on Windows. Update those tests to
explicitly carve out Windows rather than any configuration that does not
provide the shell feature.

Towards #102700.

Reviewers: petrhosek, cmtice, mysterymath, MaskRay, ilovepi

Reviewed By: cmtice

Pull Request: https://github.com/llvm/llvm-project/pull/156510
2025-09-03 09:12:12 -07:00
ZhaoQi
e3eb4077a0
Reland "[sancov][LoongArch] Resolve pcaddu18i+jirl in evaluateBranch and teach sancov (#155371)" (#155964)
Reland 9c994f5 after fixing ubsan bots failures.

This commit overrides `updateState` and `resetState` hooks in
`MCInstrAnalysis` in order to be able to analyze pcaddu18i+jirl pairs
inside `evaluateBranch`.

After this commit, `llvm-objdump` is able to correctly analyze and print
detailed information. `lld/test/ELF/loongarch-call36.s` shows the
changes.

Besides, this commit also teaches sancov to resolve such call sequences.
Without this commit, some tests in compiler-rt failed:

```
Failed Tests :
  SanitizerCommon-asan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard-dso.cpp
  SanitizerCommon-asan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard.cpp
  SanitizerCommon-lsan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard-dso.cpp
  SanitizerCommon-lsan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard.cpp
  SanitizerCommon-msan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard-dso.cpp
  SanitizerCommon-msan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard.cpp
```

The reason is that sancov could not resolve pcaddu18i+jirl call sequence
correctly and caused mismatches between coverage points in the binary
and the .sancov file:

```
ERROR: Coverage points in binary and .sancov file do not match.
```

NOTE: A similar issue might also occur on RISC-V when relaxation is
disabled (not verified). This commit can also fix for it.
2025-08-29 11:46:17 +08:00
Vitaly Buka
8f482d5271
Revert "[sancov][LoongArch] Resolve pcaddu18i+jirl in evaluateBranch and teach sancov" (#155879)
Reverts llvm/llvm-project#155371

Breaks ubsan bots.
2025-08-28 16:44:30 +00:00
ZhaoQi
9c994f5449
[sancov][LoongArch] Resolve pcaddu18i+jirl in evaluateBranch and teach sancov (#155371)
This commit overrides `updateState` and `resetState` hooks in
`MCInstrAnalysis` in order to be able to analyze pcaddu18i+jirl pairs
inside `evaluateBranch`.

After this commit, `llvm-objdump` is able to correctly analyze and print
detailed information. `lld/test/ELF/loongarch-call36.s` shows the
changes.

Besides, this commit also teaches sancov to resolve such call sequences.
Without this commit, some tests in compiler-rt failed:

```
Failed Tests :
  SanitizerCommon-asan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard-dso.cpp
  SanitizerCommon-asan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard.cpp
  SanitizerCommon-lsan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard-dso.cpp
  SanitizerCommon-lsan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard.cpp
  SanitizerCommon-msan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard-dso.cpp
  SanitizerCommon-msan-loongarch64-Linux :: sanitizer_coverage_trace_pc_guard.cpp
```

The reason is that sancov could not resolve pcaddu18i+jirl call sequence
correctly and caused mismatches between coverage points in the binary
and the .sancov file:

```
ERROR: Coverage points in binary and .sancov file do not match.
```

NOTE: A similar issue might also occur on RISC-V when relaxation is
disabled (not verified). This commit can also fix for it.
2025-08-28 09:25:30 +08:00
Zhaoxin Yang
149d9a38e1
[ELF][LoongArch] -r: Synthesize R_LARCH_ALIGN at input section start (#153935)
Similay to

94655dc8ae

The difference is that in LoongArch, the ALIGN is synthesized when the
alignment is >4, (instead of >=4), and the number of bytes inserted is
`sec->addralign - 4`.
2025-08-22 16:02:41 +08:00
Fangrui Song
04eb5e0cd4 test: Add REQUIRES: riscv 2025-08-12 22:39:57 -07:00
Fangrui Song
94655dc8ae [ELF] -r: Synthesize R_RISCV_ALIGN at input section start" (#151639)
Clear `synthesizedAligns` to prevent stray relocations to an unrelated
text section. Enhance the test to check llvm-readelf -r output.

---

Without linker relaxation enabled for a particular relocatable file or
section (e.g., using .option norelax), the assembler will not generate
R_RISCV_ALIGN relocations for alignment directives. This becomes
problematic in a two-stage linking process:

```
ld -r a.o b.o -o ab.o
// b.o is norelax. Its alignment information is lost in ab.o.
ld ab.o -o ab
```

When ab.o is linked into an executable, the preceding relaxed section
(a.o's content) might shrink. Since there's no R_RISCV_ALIGN relocation
in b.o for the linker to act upon, the `.word 0x3a393837` data in b.o
may end up unaligned in the final executable.

To address the issue, this patch inserts NOP bytes and synthesizes an
R_RISCV_ALIGN relocation at the beginning of a text section when the
alignment >= 4.

For simplicity, when RVC is disabled, we synthesize an ALIGN relocation
(addend: 2) for a 4-byte aligned section, allowing the linker to trim
the excess 2 bytes.

See also https://sourceware.org/bugzilla/show_bug.cgi?id=33236
2025-08-12 22:38:17 -07:00
Fangrui Song
98164d4706 Revert "[ELF] -r: Synthesize R_RISCV_ALIGN at input section start" (#151639)
This reverts commit 6f53f1c8d2bdd13e30da7d1b85ed6a3ae4c4a856.

synthesiedAligns is not cleared, leading to stray relocations for
unrelated sections. Revert for now.
2025-08-12 22:18:15 -07:00
Fangrui Song
856290d1c1 Revert "Add REQUIRES: riscv to test added in 151639 to skip the test when riscv is not built. (#152858)"
This reverts commit d1827f040f6e056e62cf4158bdf90d0acdf3d287.
2025-08-12 22:18:14 -07:00
Peter Collingbourne
e3d8616836 Add missing REQUIRES: aarch64. 2025-08-11 12:43:46 -07:00
Peter Collingbourne
53c41f19e3
ELF: Add support for R_AARCH64_PATCHINST relocation type.
The R_AARCH64_PATCHINST relocation type is to support deactivation
symbols. For more information, see the RFC:
https://discourse.llvm.org/t/rfc-deactivation-symbols/85556

Part of the AArch64 psABI extension:
https://github.com/ARM-software/abi-aa/issues/340

Reviewers: smithp35, davemgreen, MaskRay

Reviewed By: MaskRay, davemgreen, smithp35

Pull Request: https://github.com/llvm/llvm-project/pull/133534
2025-08-11 11:33:08 -07:00