Repository navigation
[NativeAOT] Split large arm64 code sections so the linker can place range-extension thunks (COFF and ELF) - #137130
SHAZAM-Analytics wants to merge 12 commits into
Conversation
link.exe places range-extension thunks only between section contributions, so once the single managed code section passes 128 MB a BL to a target beyond its reach fails to link with LNK2013. When writing a COFF object for arm64, start a new section with the same name once the current non-COMDAT code section would grow past 64 MB, half the B/BL reach. The linker merges the sections in order and can place thunks at each boundary. The PE writer opts out because it lays out the image without a linker.
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
Tagging subscribers to this area: @agocke, @dotnet/ilc-contrib |
|
@dotnet-policy-service agree company="SHAZAM Analytics Ltd" |
|
This fix is needed in servicing too: shipped .NET 10 and 11 NativeAOT apps hit it on arm64 today. Once it merges, could an area owner backport it to release/10.0 and release/11.0? I opened backport PRs earlier by mistake and they were rightly closed. |
The object writer opts in with LinkerPlacesRangeExtensionThunks, and the split size is half the direct-call reach of the target architecture. x64 has no reach limit to work around and stays unsplit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Splitting managed code into several COFF sections lets link.exe place range extension thunks between them, inside the managed code range. LookupUnwindInfoForMethod matched an address in a thunk to the preceding function, so IsSafePoint decoded GC info past that function's end and the return address hijack unwound with the wrong unwind info. The lookup now checks the function's end, so an address between two functions has no method, and HijackCallback leaves a thread without a method running so suspension tries again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HijackCallback already looks the method up to rule out code outside any method, so IsSafePoint takes that MethodInfo instead of finding it again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
ARM64 unboxing stubs routed through linker thunks can register thunk addresses instead of method entry points, breaking reflection-based stack-frame resolution and delegate diagnostic-name lookup.
1 open issue
What changed in this PR
This PR addresses the Windows ARM64 branch-range overflow case in #103073 by splitting large NativeAOT COFF code sections, allowing link.exe to insert range-extension thunks.
Changes:
- Split eligible non-COMDAT executable sections at half the target’s direct-call reach.
- Enable splitting for NativeAOT COFF output while keeping crossgen2 PE output unchanged.
- Reject addresses between methods during unwind lookup and defer GC hijacking when a thread stops there.
| File | Description |
|---|---|
src/coreclr/tools/Common/Compiler/ObjectWriter/PEObjectWriter.cs |
Explicitly disables linker-thunk section splitting for PE images. |
src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs |
Adds architecture-specific thresholds and same-name section splitting. |
src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ObjectWriter/CoffObjectWriter.Aot.cs |
Enables splitting for NativeAOT COFF output. |
src/coreclr/nativeaot/Runtime/windows/CoffNativeCodeManager.cpp |
Checks function ends to exclude gaps from method lookup. |
src/coreclr/nativeaot/Runtime/thread.cpp |
Defers hijacking when the interrupted address has no method information. |
Review effort: Balanced
| sectionWriter.Position > 0 && | ||
| sectionWriter.Position + nodeContents.Data.Length > codeSectionSplitSize) | ||
| { | ||
| sectionWriter = StartNewSection(section); |
There was a problem hiding this comment.
Fixed in 2b55f0f. When an arm64 unboxing stub's b reaches its target through a range extension thunk (adrp xip0; add xip0, xip0, #imm12; br xip0), RhGetCodeTarget now decodes the thunk and returns the method itself.
Reproduced and verified on win-arm64, and on linux-arm64 with GNU ld and lld. The test image puts 4096 unboxing stubs about 239 MB from their methods.
- With reflection metadata disabled: without the fix,
DiagnosticMethodInfo.Createon delegates over the stubs returned null for all 4096. With the fix, all 4096 resolved. - With reflection metadata present: the result was correct either way. The lookup falls back to the invoke map, which passes both sides of its comparison through the same thunk.
In a large arm64 image the linker can reach an unboxing stub's target through a range extension thunk (adrp xip0; add xip0; br xip0). RhGetCodeTarget now decodes that thunk and returns the method itself rather than the thunk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GNU ld and lld place arm64 range extension thunks only between input sections, so a single code section over 128 MB cannot reach targets beyond the BL range. The NativeAOT ELF writer now opts in to the code section split for arm64. 32-bit Arm and LoongArch64 are not split. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When .eh_frame_hdr has no FDE for an address, libunwind falls back to a linear scan of the whole .eh_frame. A thread interrupted in a linker range extension thunk hit that scan inside the activation signal handler, which stalled GC suspension. GetUnwindProcInfo now trusts the .eh_frame_hdr table when it is present, as libgcc does, and passes the FDE it finds as the hint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Updated so this PR also covers linux-arm64, where the same limit applies. There, on 10.0.14, an app over 128 MB links cleanly and crashes at startup; with #137129 it fails to link.
The description has the full validation: GC suspension stress and an unboxing stub check on Windows 11 Arm64 (link.exe) and Ubuntu 24.04 arm64 (GNU ld and lld), all passing, with A/B runs showing that each runtime change is needed. |
There was a problem hiding this comment.
🟡 Changes recommended
ARM64 ELF section splitting reuses relocation anchors across chunks, causing DWARF addresses for earlier chunks to resolve against the last chunk and corrupt method ranges, source lines, and breakpoint addresses.
2 open issues
Review effort: Balanced
|
This is getting complicated enough to require a test. To make the test reasonably fast, we may want to add an option to the compiler to produce the code bloat required to exercise the effected paths. |
A split code section repeats its name, and the ELF writer registered one section symbol per name, so the DWARF relocations of every part resolved against the last part. Each part after the first now keys its section symbol by name and section index; the section header names are unchanged. The comment on the arm64 opt-in now says why only arm64 splits. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
--methodpadding:<bytes> pads each method body so a test can build an image whose code spans more than the reach of a direct branch without compiling that much code. RangeExtensionThunks pads 8192 bodies so they span more than 128 MB on arm64, which puts every far call and unboxing stub behind a linker thunk. It resolves DiagnosticMethodInfo through the stubs, runs threads through the thunks under back-to-back collections, and on Linux checks that the debug information locates Main. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
|
Added in 9d02698. Verified on arm64 VMs (Ubuntu 24.04 with GNU ld, Windows 11) by reverting each change in turn:
Two of the runtime changes are not distinguishable by this test, and the final run exercises them only positively: the COFF hijack fix, because with standard frames the wrong unwind info still reads the caller's own saved return address, and the |
|
/azp run runtime-nativeaot-outerloop |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
LGTM. @MichalStrehovsky Could you please take a look as well? |
--function-alignment:<bytes> overrides TargetDetails.OptimumFunctionAlignment, so the object writer and the compilation need no padding option. The test aligns method bodies to 4 KB, the largest section alignment link.exe accepts without /ALIGN, and uses 21952 instantiations so the code still spans more than the reach of a direct branch. Co-Authored-By: Claude <noreply@anthropic.com>
| } | ||
| // The default matches the choice in the C++ compiler. | ||
| // We want a number that is optimized for micro-op caches in the processor. | ||
| public int OptimumFunctionAlignment { get; set; } = 16; |
There was a problem hiding this comment.
No mutable state please.
There was a problem hiding this comment.
Done in ef8996d: OptimumFunctionAlignment is get-only again, and the --function-alignment value goes through the TargetDetails constructor.
| // is the jump to a range extension thunk the linker placed for a target out of branch range? | ||
| // adrp xip0,#imm21; add xip0,xip0,#imm12; br xip0 | ||
| if ((pTarget[0] & 0x9f00001f) == 0x90000010 && | ||
| (pTarget[1] & 0xffc003ff) == 0x91000210 && | ||
| pTarget[2] == 0xd61f0200) | ||
| { | ||
| // add: imm = ZeroExtend(imm12, 64); | ||
| return GetArm64AdrpPage(pTarget) + ((pTarget[1] >> 10) & 0xfff); | ||
| } |
There was a problem hiding this comment.
I assume we're fine relying on linkers always emitting this sequence.
Would an alternative be to not split the section and insert the range extension thunks in the object writer instead? There is some advantage in knowing all code addresses relative to .managedcode in the compiler - e.g. in case we would want to start emitting stack trace metadata as a hashtable like Jan suggested in the past.
Not sure how ugly that would turn out to be.
There was a problem hiding this comment.
It was not safe as pushed. I read the linkers' sources to answer this and found a case the test had missed; it is fixed in ef8996d.
| Linker | Thunk it places |
|---|---|
| link.exe (VS 2022) | adrp; add; br in every image I built. Not documented. |
| GNU ld | adrp; add; br whenever the target is within 4 GB of the thunk (aarch64_adrp_branch_stub in elfnn-aarch64.c), so in any image under 4 GB. |
| lld | adrp; add; br in a PIE (AArch64ADRPThunk), and ldr x16, #8; br x16; .xword target when the image is not position independent (AArch64ABSLongThunk). Either one is written as a bare b target when the thunk itself is in branch range of the target. |
lld also lets every caller in range reuse a thunk. An unboxing stub can therefore share the short thunk that a direct call to the same method created, and the pushed code resolved that stub to the thunk, so DiagnosticMethodInfo.Create returned null for it. The test missed it because nothing called Work directly, so no stub had a call's thunk to share. Work now calls the next instantiation directly: with lld, 224 stubs land on a b thunk, and the pushed runtime fails the test.
RhGetCodeTarget now decodes all three forms (+11 lines). It follows the bare b only when that address is not part of a method, because a method could itself start with a branch. RyuJIT does not emit such a method today, so the test covers that check from the thunk side only. A form we do not decode costs the reverse lookup for that stub and nothing else: the stub still runs.
Retested on arm64 VMs:
- Linux, lld 18.1.3: passes with 448 direct calls and 4,091 stubs through thunks, 224 of them on a shared
bthunk. - Linux, lld, not position independent (ad hoc, the test is not built that way): every thunk is the
ldrform and every delegate resolves; with the pushed runtime none did. - Linux, GNU ld 2.42: passes, and all 6,166 veneers are
adrp; add; br. - Windows, link.exe: passes with 448 calls and 4,086 stubs through thunks, all
adrp; add; br, none shared. - Each fix reverted in turn gives the same outcomes as before. Without the two lld forms the Linux run fails and the Windows run passes, as expected.
On placing the thunks in the object writer: it can be done, but I think it is a much larger change than the split. The writer would need a branch relaxation pass for COFF and ELF that places islands inside the section and iterates, since each island moves the code after it. It would also have to cover every call that leaves the section, such as the runtime helpers in .text, because the linker cannot reach those from the middle of a section over 128 MB either. The runtime side of this PR would stay, since a thread can still be stopped in an island. With the split, nothing changes below 64 MB of code: it is one section and every address is known relative to it, as today. Above that, addresses are known within each piece. If you would rather have the thunks in the writer, I would suggest doing it as a follow-up, so that large arm64 apps link in the meantime.
The runtime-nativeaot-outerloop run that was requested earlier was cancelled by my previous push, so it needs to be queued again to run this test.
…etDetails lld lets every caller in range reuse a thunk, and writes a thunk that is itself in branch range of its target as a bare "b target". An unboxing stub that shared such a thunk with a direct call resolved to the thunk, not the method. When the image is not position independent, lld writes "ldr xip0, #8; br xip0; .xword target". RhGetCodeTarget now decodes both, and follows the bare branch only when it is not part of a method. In the test, Work now calls the rotated instantiation directly, and 19683 instantiations put the stubs in reach of the thunks lld places for those calls, so some stubs share one. OptimumFunctionAlignment is get-only again: the --function-alignment value goes through the TargetDetails constructor. Co-Authored-By: Claude <noreply@anthropic.com>
|
/azp run runtime-nativeaot-outerloop |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
| public partial class TargetDetails | ||
| { | ||
| public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi, SimdVectorLength simdVectorLength) | ||
| public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi, SimdVectorLength simdVectorLength, int optimumFunctionAlignment = 0) |
There was a problem hiding this comment.
| public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi, SimdVectorLength simdVectorLength, int optimumFunctionAlignment = 0) | |
| public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi, SimdVectorLength simdVectorLength, int optimumFunctionAlignment = 16) |
And delete the optimumFunctionAlignment != 0 if check and = 16; elsewhere?
There was a problem hiding this comment.
We would have to hardcode the default in Program.cs (or call the constructor with different set of arguments depending on whether the alignment was specified).
A few alternatives (none of them is particularly great):
int? optimumFunctionAlignment = nullconstructor argument - avoids magic0withpattern - requires a lot of boiler plate code
There was a problem hiding this comment.
Ah. The int? sounds okay to me.
There was a problem hiding this comment.
Done in 97fc055: the constructor takes int? optimumFunctionAlignment = null and --function-alignment is an Option<int?>, so no value stands for "not given". --function-alignment:0 is now refused like any other value that is not a power of two.
| } | ||
| // lld, when the thunk itself is in branch range of the target: b target | ||
| // A method can start with a branch as well; a thunk is not part of any method. | ||
| else if ((pTarget[0] >> 26) == 0x5 && GetRuntimeInstance()->FindMethodStartAddress(pTarget) == NULL) |
There was a problem hiding this comment.
Why does this branch have GetRuntimeInstance()->FindMethodStartAddress(pTarget) == NULL condition and the ones above don't?
There was a problem hiding this comment.
There was no good reason for the difference, so the check now covers all three forms (97fc055).
The check is there because a thunk is recognized by its instructions, and a method could start with the same ones. I had put it on the bare b only, as the one form a compiled method could plausibly start with (a method that is nothing but a tail call). The same argument applies to the other two, only less likely, so treating them differently was not justified.
RhGetCodeTarget now decodes the form first and does the lookup only when one matched, so a stub that reaches its method directly does no lookup.
Retested on arm64 VMs, with the same outcomes as before:
- Linux, lld 18.1.3: passes; 4,091 stubs go through thunks, 224 of them on a shared
bthunk. - Linux, lld, not position independent (ad hoc): every long thunk is the
ldrform and every delegate resolves. - Linux, GNU ld 2.42: passes; all 6,166 veneers are
adrp; add; br. - Windows, link.exe: passes; 4,086 stubs go through thunks, all
adrp; add; br. - With the thunk decoding reverted, the test fails on both.
As before, the test covers the check from the thunk side only: RyuJIT sets up a frame before a tail call today, so I could not produce a method that starts with any of the three forms.
…on alignment argument nullable RhGetCodeTarget follows a thunk only when its address is not part of a method. That check covered the bare branch only; it now covers all three forms, and runs only after one of them matched. TargetDetails takes the function alignment as int?, so no value stands for "not given", and --function-alignment:0 is refused. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
@SHAZAM-Analytics Did you happen to close this by accident? |

Contributes to #103073 (the
LNK2013: BRANCH26 fixup overflowcase in #103073 (comment))Problem
ILC writes all managed code into one code section. The linkers place arm64 range-extension thunks only between sections (link.exe between section contributions, GNU ld and lld between input sections), never inside one. Once managed code passes 128 MB, a
BLfrom inside that section to a target beyond its reach cannot be fixed up.win-arm64: the link fails:
linux-arm64: on 10.0.14 the app links without error and crashes at startup, because ILC resolves the out-of-range
BLitself and truncates it. With [NativeAOT] Do not resolve an out-of-range arm64 BRANCH26 within a section #137129 the link fails with "relocation truncated" instead.Fix
ILC
When the object writer's linker places range-extension thunks between sections (
LinkerPlacesRangeExtensionThunks), ILC starts a new section with the same name once the current code section would grow past half the target's direct-call reach: 64 MB on arm64 and loongarch64, 8 MB on arm. The linker merges same-named sections into one output section in order and can insert thunks at each boundary. A branch within one section therefore always fits, and every call site is within reach of a boundary where a thunk can go.PEObjectWriter(crossgen2): it lays out the image itself without a linker, so nothing could place thunks.Runtime
The linker places each thunk (usually
adrp xip0; add xip0, xip0, #imm; br xip0) between two of those sections: inside the managed code range, but outside any method.Thread::HijackCallbackreturns whenFindMethodInfofails, so a thread interrupted for GC suspension inside a thunk keeps running and suspension tries again.ICodeManager::IsSafePointtakes theMethodInfoits caller already has.CoffNativeCodeManager::LookupUnwindInfoForMethodchecks the end of the function it finds:EndAddresson x64 and x86,FunctionLengthfrom the xdata on arm64. An address past a function's end resolves to no method rather than to the one before it.UnwindHelpers::GetUnwindProcInfo(Unix) trusts the.eh_frame_hdrbinary search table when it is present, as libgcc does, and reports no method when the table has no FDE for the address. On a hit it passes that FDE as the hint, so the common path does no extra work..eh_frame. That scan ran inside the activation signal handler, so threads that kept being interrupted in thunks stalled GC suspension.UnixNativeCodeManageritself needs no change: a thunk address is outside every FDE range.RhGetCodeTargetfollows a thunk between an arm64 unboxing stub and its target. It returns the method rather than the thunk, soDiagnosticMethodInfoand the other lookups that map a stub to its method get the right answer.adrpform it decodes the two other forms lld writes:ldr xip0, #8; br xip0; .xword targetwhen the image is not position independent, and a bareb targetwhen the thunk is itself in branch range of the method, which a stub reaches by sharing the thunk of a direct call. A thunk is followed only when it is not part of a method.Testing
nativeaot/SmokeTests/RangeExtensionThunkscovers the split in CI. It aligns method bodies to 4 KB with--function-alignment, so 19,683 generic instantiations span more than the reach of a direct branch. It checks that out-of-range calls and unboxing stubs go through linker thunks, thatDiagnosticMethodInforesolves through the stubs, including the ones that share a short thunk with a direct call under lld, that threads calling through thunks survive back-to-back collections, and on Linux that the debug info locatesMain.Ad-hoc validation with this PR's changes on .NET 10.0.14. The test image has about 246 MB of managed code, 64 call targets reached through linker thunks, and 4096 unboxing stubs about 239 MB from their methods. Thunk placement was verified from the map and the disassembly.
HijackCallbackearly return.eh_frame_hdrlookupDiagnosticMethodInfo.Createon 4096 delegates over unboxing stubs, reflection metadata disabledRhGetCodeTargetchangeAll machines are Azure Cobalt 100. We hit the LNK2013 failure building a large NativeAOT application for win-arm64 and carry this change in those builds.