Skip to content

[NativeAOT] Remove libc++ from libNativeAOT.so #12139

Closed

Description

@simonrozsival

Summary

Remove the link-time dependency on libc++_static.a and libc++abi.a from Android NativeAOT's final libNativeAOT.so.

This is valuable independently for:

  1. App size — the previous prototype reduced APK size by about 12% and libNativeAOT.so by about 15%.
  2. Startup performance — fewer native pages, relocations, C++ runtime initializers, TLS/runtime setup, and page faults.
  3. Linker robustness — removing libc++ removes the primary reason the Android NDK's libunwind.a gets extracted, avoiding collisions with NativeAOT's private libunwind implementation.

Previous feasibility work: #11311.

Motivation

App-size results

PR #11311 measured the following using samples/NativeAOT/NativeAOT.csproj in Release with the trimmable typemap:

Artifact libc++ baseline Without libc++ Reduction
arm64 APK 1,575,849 B 1,382,336 B 193,513 B (12.28%)
x64 APK 1,639,459 B 1,439,677 B 199,782 B (12.19%)
arm64 libNativeAOT.so 3,481,880 B 2,943,232 B 538,648 B (15.47%)
x64 libNativeAOT.so 3,404,896 B 2,866,728 B 538,168 B (15.81%)

This removes roughly 540 KB per ABI from the native shared library.

Startup impact

Statically linking libc++ increases startup work through:

  • additional mapped/decompressed native pages;
  • additional relocations;
  • C++ runtime and static-initializer execution;
  • thread-local/runtime exception infrastructure;
  • increased page faults and resident memory.

The exact startup improvement still needs measurement, but removing this dependency reduces work on the application startup path by construction.

libunwind collisions

There are currently two distinct unwind implementations involved:

  1. NativeAOT contains a private LLVM libunwind implementation in libRuntime.WorkstationGC.a. It is used by UnixNativeCodeManager and UnwindHelpers to parse DWARF/compact-unwind information and virtually unwind managed frames for GC stack walking, exception handling, stack traces, profiling, and related runtime services.
  2. libc++abi.a references the _Unwind_* ABI, causing the final Android link to extract objects from the Android NDK's libunwind.a.

With NDK r29, these copies can define the same global symbols, producing the duplicate-symbol failure tracked by dotnet/runtime#121172.

The runtime-side fix, dotnet/runtime#128927, privatizes NativeAOT's libunwind symbols in .NET 11 Preview 7. That is still valuable defense-in-depth, especially for third-party native libraries.

Removing libc++ solves a different layer of the problem: it removes the main built-in consumer that causes NDK libunwind to be pulled into our application link at all.

Current dependency inventory

The Android NativeAOT host currently compiles the sources listed in:

src/native/nativeaot/host/CMakeLists.txt

The major libc++ dependency groups in the resulting libnaot-android.*.a are:

Dependency group Current source
charconv, locale, owning strings and formatting std::format-based logging
thread, atomic wait, chrono and system errors std::thread and std::binary_semaphore
hashing and allocation std::unordered_map and owning std::string state
C++ ABI new/delete, static guards, pure virtual and terminate

std::string_view, std::array, and simple atomics are generally header-only and are not by themselves reasons to remove code. The work should be driven by the final archive's unresolved symbols rather than by a blanket ban on all std::* types.

Main source areas

Formatting and logging

  • src/native/clr/include/shared/log_types.hh
  • src/native/clr/shared/log_functions.cc
  • src/native/common/include/shared/helpers.hh
  • src/native/clr/shared/helpers.cc
  • src/native/nativeaot/host/bridge-processing.cc
  • src/native/nativeaot/host/host.cc
  • src/native/clr/host/bridge-processing.cc
  • src/native/clr/host/host-shared.cc
  • src/native/clr/host/os-bridge.cc
  • src/native/clr/runtime-base/android-system-shared.cc
  • src/native/clr/runtime-base/util.cc
  • src/native/clr/include/runtime-base/util.hh

Threading

  • src/native/clr/include/host/gc-bridge.hh
  • src/native/clr/host/gc-bridge.cc

Containers and owning state

  • src/native/clr/include/host/bridge-processing-shared.hh
  • src/native/common/include/shared/cpp-util.hh
  • src/native/clr/include/runtime-base/android-system.hh
  • src/native/clr/runtime-base/android-system.cc
  • src/native/clr/runtime-base/android-system-shared.cc
  • src/native/clr/runtime-base/logger.cc

Linker and packaging

  • src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.NativeAOT.targets
  • src/Xamarin.Android.Build.Tasks/Utilities/NativeRuntimeComponents.cs
  • src/androidsdk/androidsdk.targets
  • build-tools/create-packs/Microsoft.Android.Runtime.proj
  • src/native/nativeaot/host/CMakeLists.txt

Proposed small PR sequence

  • Introduce printf-style logging primitives (#12140)

    • Add log_writev, printf-style log_* helpers, and Helpers::abort_applicationf.
    • Preserve the existing std::format path for Mono/CoreCLR.
    • Do not migrate call sites in the same PR.
  • Migrate NativeAOT-specific formatting call sites (#12140)

    • Convert src/native/nativeaot/host/*.cc from {} formatting to bounded printf-style formatting.
    • Use %.*s for std::string_view; never assume .data() is NUL-terminated.
  • Migrate NativeAOT-reachable shared logging (#12148, #12150, #12153, #12155, #12210, #12211, #12218)

    • Move reference logging (os-bridge, logger) to the printf-style API.
    • Move bridge/runtime-base/util logging to the printf-style API.
    • Split these by subsystem if needed to keep reviews focused.
  • Remove std::format from the NativeAOT compilation

    • Stop including <format> for XA_HOST_NATIVEAOT.
    • Confirm charconv, locale, floating-point to_chars, and formatting-related symbols disappear from libnaot-android.*.a.
  • Replace GC bridge C++ threading primitives (#12141)

    • Replace std::thread and std::binary_semaphore with pthread/POSIX primitives.
    • Keep this separate because concurrency changes need focused validation.
  • Replace NativeAOT-reachable owning containers and strings (#12142, #12145)

    • Replace std::unordered_map temporary-peer storage with a lightweight/vendored alternative.
    • Replace static/owning logger and AndroidSystem strings with fixed, bounded, or explicitly allocated buffers.
    • Replace ranges/vector/string parsing in cpp-util.hh with direct bounded parsing.
  • Eliminate remaining C++ ABI roots (#12523)

    • Remove nontrivial function-local/static objects that require __cxa_guard_*.
    • Remove pure-virtual/terminate dependencies where possible.
    • Add minimal malloc/free-backed new/delete/nothrow shims in src/native/nativeaot/host/cxx-shims.cc. Not needed. The ILC SDK already ships libstdc++compat.a, which defines the five allocation-ABI symbols the NativeAOT runtime itself references (operator delete, operator delete[], both nothrow operator new overloads, and std::nothrow). Our targets were unconditionally removing that archive because it conflicts with static libc++; with libc++ gone there is no conflict, so we simply keep it. No shim file exists.
    • The only allocation-ABI use in our own sources was a dead new char[] path in monodroid__system_property_get, removed in [NativeAOT] Stop linking and shipping libc++ and libunwind #12523.
    • llvm-nm --undefined-only on libnaot-android.release-static-release.a now reports no __cxa_*, _ZTV/_ZTI, _Unwind_* or terminate references.
  • Add an opt-in no-libc++ NativeAOT build — skipped deliberately. A temporary _AndroidNativeAotDropLibCxx property was used during prototyping, but once the link proved clean with zero shims there was no reason to ship a second configuration, so [NativeAOT] Stop linking and shipping libc++ and libunwind #12523 makes the removal unconditional instead.

  • Remove libc++ from NativeAOT link inputs by default (#12523)

    • Removed libc++_static.a and libc++abi.a from both the legacy NDK/clang path and the workload NativeLinker path.
    • libclang_rt.builtins is kept. NDK libunwind.a was dropped at the same time (see below).
    • Add -nostdlib++ — not applicable. The final .so is linked by LinkNativeAotSharedLibrary using ld.lld directly, with fully explicit inputs and AllowUndefinedSymbols = false. No compiler driver is in a position to add libc++ implicitly, and ld.lld would reject a driver flag. LinkStandardCPlusPlusLibrary=false remains as belt-and-braces for the ILC/SDK path.
  • Remove libc++ archives from NativeAOT runtime packs (#12524)

    • Stop copying and packaging libc++_static.a, libc++abi.a and libunwind.a for NativeAOT.
    • Adds a CplusPlus item kind so CoreCLR keeps them while NativeAOT still gets crtbegin_so.o, crtend_so.o and libclang_rt.builtins-*.a.
    • Removes 18,398,848 B per ABI, roughly 55 MB across the three shipped ABIs.
  • Audit whether NDK libunwind.a remains necessary (#12523)

    • libc++abi.a was the only consumer pulling it in. With libc++ gone the archive links with zero unresolved symbols under -Wl,--no-undefined and -Wl,--error-unresolved-symbols.
    • The published .so no longer contains any _Unwind_Resume reference, whereas the libc++ baseline did.
  • Measure and lock in size/startup improvements

    • Application size measured on a default MAUI app (arm64, Release, PublishAot): .so −199,592 B (−0.79%), APK −69,632 B (−0.47%).
    • This is well below Drop libc++ from Android NativeAOT linking #11311's −538,648 B per ABI. Likely because the earlier PRs in this sequence already removed the std::format/charconv/locale payload, so the final cut only harvests what was left. Re-measuring samples/NativeAOT against the Drop libc++ from Android NativeAOT linking #11311 baseline would let us state the cumulative win.
    • Startup timing, page faults, mapped native pages, relocations and working set are still unmeasured.
    • APK/native-library baselines not yet updated.

Validation requirements

For every supported ABI and both Debug/Release:

  • link response contains no libc++_static.a or libc++abi.a;
  • final libNativeAOT.so has no unresolved std::__ndk1::* symbols;
  • final libNativeAOT.so has no unresolved C++ exception/personality machinery;
  • APK contains no libc++ payload;
  • NativeAOT startup succeeds;
  • GC bridge processing succeeds repeatedly;
  • managed exceptions, stack walking, and crash handling continue to work;
  • third-party native-library scenarios continue to link;
  • both workload NativeLinker and legacy NDK linker paths are covered.

Runtime validation should include arm64 and x64. Where local emulator architecture is unavailable, use Helix rather than leaving the configuration untested.

Status: validated locally on arm64 (workload NativeLinker, Release) — links with no unresolved symbols, no libc++ payload in the APK, and a default MAUI app starts and runs. Remaining ABIs, Debug, and the legacy NDK linker path are covered by CI.

Lessons from previous attempts

PR #11311 proved that removal is feasible, but it touched roughly 34 files and combined:

  • linker changes;
  • shared logging redesign;
  • GC bridge threading changes;
  • container replacements;
  • NativeAOT-specific startup workarounds;
  • unrelated Java peer-shape concerns.

This made the PR difficult to review and caused repeated merge conflicts as NativeAOT work continued landing.

For this effort:

  • each PR should remove one measurable symbol cluster;
  • archive symbols should be inspected after every PR;
  • unrelated typemap/startup/Java peer work should remain separate;
  • every PR should build and validate independently;
  • human review should happen incrementally rather than after a single large rewrite.

The previous review also found unsafe %s usage with std::string_view::data(). All replacements must use bounded formatting.

Non-goals

Related work

Activity

  1. added
    drop-libcppWork to remove the libc++ dependency from Android NativeAOT
    on Jul 16, 2026
  2. simonrozsival commented on Jul 17, 2026

    @simonrozsival
    MemberAuthor

    Additional CI and incremental-size evidence

    Two independent PR builds now reproduce the exact .NET 10/NDK r29 libunwind collision:

    In both builds, MSBuild+Emulator 9 fails the same test:

    DotNetInstallAndRunMinorAPILevels(True, "net10.0-android36.1", NativeAOT)
    

    The failing link combines:

    • .NET 10.0.9 libRuntime.WorkstationGC.a, which defines NativeAOT's LLVM-libunwind symbols;
    • NDK 29.0.14206865 libunwind.a, which defines the same global symbols.

    ld.lld reports duplicates including __unw_init_local, __unw_get_reg, __unw_step, __unw_resume, and unw_local_addr_space.

    These PRs modify different native subsystems and neither changes the final NativeAOT linker inputs, so the independent reproductions strengthen the evidence that this is a systemic link-closure problem rather than a regression in either PR. Removing libc++/libc++abi removes the built-in _Unwind_* consumer that currently causes the NDK copy to be extracted, while NativeAOT's private copy remains available for managed unwinding.

    There is also incremental size evidence from #12142 before the final libc++ removal:

    • arm64 NativeAOT static archive: 70,304 bytes smaller (3.59%);
    • arm64 NativeAOT shared library: 3,024 bytes smaller (0.93%);
    • direct std::__ndk1::__next_prime and owning basic_string destructor roots removed;
    • direct __cxa_* references reduced from 10 to 7.

    This complements the full prototype's roughly 540 KB-per-ABI result: even the first isolated symbol-cluster cleanup produces a measurable reduction.

  3. 10 remaining items

  4. simonrozsival commented on Aug 27, 2026

    @simonrozsival
    MemberAuthor

    Opened #12533 to track the same work for the CoreCLR host.

    The audit found that the mechanism we need already exists: each lane gets its own shared/log_types.hh via XA_RUNTIME_INCLUDE_DIR, and NativeAOT's is a 5-line stub while CoreCLR's is 119 lines of std::format wrappers. bridge-processing.cc — the same file compiled into both lanes — has zero libc++ dependencies under NativeAOT and the full std::format payload under CoreCLR.

    std::format is the dominant blocker (21 sites), and 18 of them are Helpers::abort_application (...) error paths, so they convert to fixed buffers cheaply. The gating unknown is whether libcoreclr_static.a itself needs libc++ — CoreCLR has no libstdc++compat.a equivalent to lean on.

  5. added 2 commits that reference this issue on Sep 2, 2026
    89fd67c
    9f9c972
  6. locked and limited conversation to collaborators on Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: App+Library BuildIssues when building Library projects or Application projects.Area: NativeAOTIssues that only occur when using NativeAOT.drop-libcppWork to remove the libc++ dependency from Android NativeAOTneeds-triageIssues that need to be assigned.

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions