Skip to content

Serve System.Security.Cryptography from the framework's IL on macOS and Windows - #531

Merged
jonathanperis merged 6 commits into
mainfrom
feat/crypto-il-macos-windows
Nov 29, 2026
Merged

jonathanperis merged 6 commits into
mainfrom
feat/crypto-il-macos-windows

Conversation

@jonathanperis

@jonathanperis jonathanperis commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Part of the roadmap flip list (#449).

What changed and why

On macOS and Windows, System.Security.Cryptography was mixed: X.509/RSA/TLS came from the framework's IL, but hashing, HMAC, AES, RNG, PBKDF2, SHA-3 and HashAlgorithmName were csharpc's managed copies, which lacked HMAC instances, KMAC, SHAKE, HKDF, AesGcm/AesCcm/ChaCha20Poly1305, TripleDES (compile-time "not supported yet") and were up to 135x slower than NativeAOT. Both System.Security.Cryptography and System.Net.Security are now the framework's IL whole on macOS and Windows, as on Linux and as under NativeAOT: CNG on Windows, the NativeAOT pack's Apple crypto shim on macOS.

  • Copies → WASI only. Hashing.cs, Crypto/Sha3.cs, Pbkdf2.cs, SymmetricCrypto.cs, RandomNumberGenerator.cs, HashAlgorithmName.cs, Rsa.cs, Cryptography.cs, Net/Tls.cs, Net/Negotiate.cs compile for WASI only. WASI keeps them: it has no OS crypto, NativeAOT does not target it, and the browser/WASI build of the assembly is not in the pinned framework (it throws PlatformNotSupportedException for most of this surface).
  • Dead code deleted. The CommonCrypto/BCrypt block-cipher glue in Crypto/AesNative.cs is gone (the helpers WASI uses remain, as Crypto/CryptoHelpers.cs). So are the Windows CNG error branch in Hashing.cs, the native-TLS shadow family (NativeTls prefixes, Apply), IlFirst's partial mechanism and the CSHARPC_NATIVE_TLS define. NativeTls now only decides which pack shims may be linked, and the framework index is keyed on it.
  • Swift calls (security fix). .NET 11's macOS crypto calls CryptoKit entry points with CallConvSwift, and csharpc ignored that attribute. The throwing ones (AES-GCM, ChaCha20-Poly1305, AES key wrap) return their error in Swift's error register (x21), so a C call would never have reported a forged tag. Every CallConvSwift P/Invoke now goes through an internal swiftcc thunk (CodeGen/ModuleCodeGen.SwiftCalls.cs). The thunk passes struct arguments as their fields and uses a swifterror slot that is stored back through the SwiftError*. It is written as textual IR parsed into the module's context, because LLVM's C API cannot mark a swifterror alloca. The thunk and its call are nounwind, because Swift functions report errors in a register and never unwind. They therefore stay plain calls inside try regions, which also avoids an LLVM 18 AArch64 bug found on the macOS runner: an invoke of a swifterror call whose landing pad doesn't resume loses its end-of-range EH label, and the exception table fails to assemble (.uleb128 expression is not absolute, 1491/1605 at -O2). CoreLib's Swift marker types are now served from IL (upstream-types/System.Runtime.InteropServices.Swift.txt).
  • OperatingSystem.Is{IOS,MacCatalyst,TvOS,WatchOS,Android,FreeBSD}VersionAtLeast now return false; the macOS crypto IL asks them.

Measurements (GitHub runners, benchmarks/tls/crypto_hash_aes.cs, best of 5; ratio = csharpc / NativeAOT)

The first commit added only the benchmark, so the first TLS-benchmark run measured the copies.

operation macOS before macOS after Windows before Windows after Linux (unchanged)
SHA-256 64 B 0.62x 0.98x 2.51x 0.78x 0.98x
HMAC-SHA256 64 B 5.17x 0.98x 4.94x 0.85x 1.00x
SHA-256 1 MiB 12.37x 1.00x 8.61x 1.00x 1.03x
SHA-512 1 MiB 5.07x 1.00x 1.77x 0.99x 1.01x
incremental SHA-256 97 B 1.00x 0.98x 4.75x 0.76x 0.97x
AES-CBC encrypt 1 MiB 0.98x 0.94x 1.08x 1.07x 1.27x
AES-CBC decrypt 1 MiB 1.22x 1.51x 1.59x 1.57x 1.92x
AES-ECB 16 B 7.60x 0.78x 13.99x 0.64x 0.92x
CryptoStream 256 KiB 1.15x 0.93x 1.35x 1.32x 0.88x
PBKDF2 10k 10.26x 0.99x 10.53x 0.89x 1.02x
RNG 4 KiB 9.51x 1.00x 135.07x 0.93x 1.00x

In absolute time every operation is at least as fast as with the copies. The one regression in ratio, macOS AES-CBC decrypt (1.22x → 1.51x), is still faster in absolute terms: 676 → 367 µs, because NativeAOT's own number moved between runs. AES-CBC decryption at 1.5x–1.9x NativeAOT on every OS, Linux included before this PR, is csharpc codegen in the framework's decryptor path; it is listed under "Run time against NativeAOT" in the roadmap. Checksums are equal everywhere.

Size (stripped): the benchmark program is 458 → 598 KiB on macOS and 481 → 560 KiB on Windows; NativeAOT builds it at 1,928 and 1,743 KiB. The new tests/size/crypto.cs (hashing, HMAC, AES-CBC) is budgeted from its first CI round: linux-x86_64 378,704 B, linux-aarch64 362,280, macos-arm64 446,440, windows-x86_64 396,288, wasi-wasm32 401,608. The existing budgets are unchanged (json's macOS/Windows budgets were already above the new sizes).

What the tests prove

  • New sample 1604 covers the OS version checks. New sample 1605 checks that AES-GCM and ChaCha20-Poly1305 reject a tampered tag, ciphertext or AAD and clear the output, and that a tampered key-wrap blob is refused. On macOS 1605 exercises the Swift error path; it must print the Linux recording on every OS (WASI: known gap, no cipher).
  • 1490 and 1522 are no longer known gaps on macOS and Windows, and 1491 no longer on macOS. They are live: where real .NET's output follows the OS: 1264, 1490 and 1491 on macOS (no SHA-3, SHAKE, KMAC or AES-CCM in Apple's crypto), 1490 on Windows (CNG's unknown-hash text, as in 467), 1522 on both (GSS.framework, SSPI).
  • Linux is unchanged: the touched crypto samples pass at -O0/-O2 (24 runs) and via IL (3), tests/slicer.sh passes 10/10, tests/size.sh passes, and macOS cross-compiles of 1605/1490/1491/1264/538/467/1522 have no diagnostics (the IR shows swiftcc + swifterror for the AEAD calls).

What stays an explicit diagnostic

Swift calls passing SwiftSelf or SwiftIndirectResult, structs other than up to two pointer-sized fields, struct results, non-Apple/non-arm64 targets, and delegate* unmanaged[Swift] function pointers. None of these is ever a C call.


Note

High Risk
Changes cryptography implementation and adds Swift P/Invoke lowering on a security-critical path; correctness is covered by sample 1605 and benchmark checksums, but AES-CBC decrypt remains slower than NativeAOT on all OSes.

Overview
macOS and Windows now compile the full System.Security.Cryptography and System.Net.Security stacks from the shared framework's IL (CNG / Apple crypto shim), matching Linux and NativeAOT instead of a mixed model where hashes, HMAC, AES, RNG, PBKDF2, and related types stayed on slow corelib shadows.

The large managed crypto implementations and platform cipher glue are removed or gated to WASI-only (Hashing.cs, SymmetricCrypto.cs, AesNative.cs deleted on desktop targets; helpers live in CryptoHelpers.cs for WASM). NativeTls no longer drops partial shadow families—it only controls which native shims link—and IlFirst.UsePartial / CSHARPC_NATIVE_TLS are removed from the driver.

Swift CallConv P/Invokes for macOS CryptoKit (AES-GCM, ChaCha20-Poly1305, key wrap) are lowered through a new swiftcc thunk (ModuleCodeGen.SwiftCalls.cs) so authentication failures surface correctly instead of bogus success. OperatingSystem.Is*VersionAtLeast for non-desktop platforms return false for framework IL.

Adds benchmarks/tls/crypto_hash_aes.cs, size test tests/size/crypto.cs, samples 1604 / 1605 (OS version checks and AEAD tamper rejection), and updates platform-skips and docs for #449.

Reviewed by Cursor Bugbot for commit 1c85512. Bugbot is set up for automated code reviews on this repo. Configure here.

Per-call cost on small inputs and throughput on 1 MiB for SHA-1/256/512,
MD5, HMAC-SHA256, IncrementalHash, AES-CBC/ECB, CryptoStream, PBKDF2 and
RandomNumberGenerator, csharpc against NativeAOT on Linux, macOS and
Windows. Committed before serving System.Security.Cryptography from the
framework's IL on macOS and Windows (#449), so the first run measures
csharpc's managed copies there.
@jonathanperis jonathanperis added this to the Drop-in for large apps milestone Nov 29, 2026
@jonathanperis jonathanperis added enhancement New feature or request area: bcl Library surface (corelib) platform: macos Specific to macOS / Apple platforms platform: windows Specific to Windows labels Nov 29, 2026
@jonathanperis jonathanperis self-assigned this Nov 29, 2026
…nd Windows

macOS and Windows compiled the X.509/RSA/TLS half of the assembly from the
framework's IL but kept csharpc's managed copies for hashing, HMAC, AES,
random numbers, PBKDF2, SHA-3 and HashAlgorithmName, which lacked HMAC
instances, KMAC, SHAKE, HKDF, AesGcm/AesCcm/ChaCha20Poly1305 and TripleDES
and were 5x to 135x slower than NativeAOT on several operations. Both
assemblies are now the framework's IL whole, as on Linux and as under
NativeAOT: CNG on Windows, the NativeAOT pack's Apple crypto shim on macOS.

- The copies (Hashing.cs, Sha3, Pbkdf2, SymmetricCrypto, RandomNumberGenerator,
  HashAlgorithmName, Rsa, RSAParameters, the TLS and Negotiate stand-ins) are
  compiled for WASI only, which has no OS crypto and no NativeAOT target. The
  macOS CommonCrypto and Windows BCrypt block-cipher glue is deleted
  (AesNative.cs keeps only the helpers WASI's copies use, as CryptoHelpers.cs).
- The native TLS mode no longer drops a hand-picked family of shadows: there is
  none left in those assemblies, so IlFirst's partial mechanism is deleted and
  the mode only decides which shims may be linked (framework index keyed on it).
- Swift calls: .NET 11's macOS crypto calls CryptoKit entry points with
  CallConvSwift, which csharpc ignored. The throwing ones (AES-GCM,
  ChaCha20-Poly1305, AES key wrap) return their error in Swift's error register,
  so a C call would never report a forged tag. P/Invokes with CallConvSwift now
  go through an internal swiftcc thunk (textual IR, since the C API cannot mark
  a swifterror alloca) that stores the error where the SwiftError* points;
  shapes it does not cover (SwiftSelf, indirect results, other structs, Swift
  function pointers) are explicit diagnostics. CoreLib's Swift marker types are
  served from IL.
- OperatingSystem.IsIOSVersionAtLeast and the other version checks for OSes
  csharpc never targets return false (the macOS crypto IL asks them).

Samples 1604 (the version checks) and 1605 (AEAD and key-wrap tamper
rejection) are new; 1490/1491/1522/1264 are live entries where .NET's own
output follows the OS (no SHA-3, SHAKE, KMAC or AES-CCM on macOS; SSPI and
GSS.framework statuses). tests/size/crypto.cs measures hashing, HMAC and AES.
Real .NET on Windows reports an unknown hash name with CNG's own error
text, so 1490 is compared with it there (a live entry, like 467). The new
crypto size program gets budgets from its first CI round on every platform,
and the il-first page, ADR 0022 and the roadmap record the flip's sizes and
timings against the copies and NativeAOT, with AES-CBC decryption (1.5x-1.9x
NativeAOT on every OS) as the remaining run-time gap.
@jonathanperis
jonathanperis marked this pull request as ready for review November 29, 2026 14:11
@cursor

cursor Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: 0f2c03ef-eb72-4be6-bcf9-6e0267c88ce5)

A Swift function reports failure in the error register and never unwinds,
so the Swift-call thunk and its call are nounwind: inlined into a try region
they stay plain calls. Emitting them as invokes also hit an LLVM 18 AArch64
bug: an invoke of a swifterror call whose landing pad does not resume loses
its end-of-range label, and the Mach-O exception table failed to assemble
(".uleb128 expression is not absolute") for samples 1491 and 1605 at -O2.
@jonathanperis
jonathanperis merged commit 53bc4ac into main Nov 29, 2026
94 of 98 checks passed
@jonathanperis

Copy link
Copy Markdown
Owner Author

Merged: the five test jobs and the Bootstrap checks are green on 1c85512 (the lost wasm32 shard was rerun); main gained only docs (#535) since. Roadmap flip #449 done for macOS and Windows; WASI keeps the copies (no OS crypto, no NativeAOT target).

@jonathanperis
jonathanperis deleted the feat/crypto-il-macos-windows branch November 29, 2026 18:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: bcl Library surface (corelib) enhancement New feature or request platform: macos Specific to macOS / Apple platforms platform: windows Specific to Windows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant