From 940db64bbc44efcc334bfb0509533bff84af7ebc Mon Sep 17 00:00:00 2001 From: Cr <60964294+Chr0mium24@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:51:41 +0800 Subject: [PATCH] Decode Swift witness table accessor symbols (R3.12) (#1545) Four kinds of Swift symbol end in W and a letter (Wl, Wb, WT, WI), each a function that finds or builds a protocol witness table. The demangler read the W but not the letter and reported every one invalid ("unsupported witness kind"). They now read as swift-demangle prints them: lazy protocol witness table accessors, base witness table accessors, associated type witness table accessors and instantiation functions for generic protocol witness tables. Operands that aren't the expected type, protocol or module are refused. --- crates/formats/src/swift_demangle.rs | 88 +++++++++++ .../tests/swift_demangle_witness_accessors.rs | 144 ++++++++++++++++++ docs/ROADMAP.md | 5 + docs/STATUS.md | 1 + 4 files changed, 238 insertions(+) create mode 100644 crates/formats/tests/swift_demangle_witness_accessors.rs diff --git a/crates/formats/src/swift_demangle.rs b/crates/formats/src/swift_demangle.rs index 7e6c1bbc7..4849f0851 100644 --- a/crates/formats/src/swift_demangle.rs +++ b/crates/formats/src/swift_demangle.rs @@ -773,6 +773,73 @@ impl<'a> D<'a> { self.push(N::Global { prefix: "enum case for".into(), inner: Box::new(inner), suffix: String::new() }) } + /// A whole type as the operand of a witness accessor. A module, a name, a member or another + /// global (a metadata or witness symbol) before it is not one. + fn witness_type(&mut self) -> R { + if matches!(self.stack.last(), Some(N::Global { .. } | N::Entity { .. } | N::Conformance { .. } | N::Extension { .. })) { + return Err("witness operand is not a type".into()); + } + self.pop_type() + } + + /// A conformance as the new witness accessors read it: the module that declares it, then the + /// protocol (a protocol type, or a name inside a module or a type), then a whole type. Unlike + /// `conformance`, a type, a member or a global is not accepted as the module. + fn witness_conformance(&mut self) -> R { + if matches!(self.stack.last(), Some(N::Sig { .. })) { + return Err("a conformance with generic requirements is not supported".into()); + } + let module = self.witness_module()?; + let proto = match self.pop()? { + n @ N::Nominal { kind: 'P', .. } => n, + N::Ident(name) | N::Private(name) => { + let ctx = match self.pop()? { + N::Ident(parent) => N::Module(parent), + parent @ (N::Module(_) | N::Nominal { .. }) => parent, + _ => return Err("expected a context".into()), + }; + N::Nominal { kind: 'P', ctx: Box::new(ctx), name } + } + _ => return Err("expected a protocol".into()), + }; + let ty = self.witness_type()?; + Ok(N::Conformance { ty: Box::new(ty), proto: Box::new(proto), module: Box::new(module) }) + } + + fn witness_module(&mut self) -> R { + match self.pop()? { + N::Ident(name) => Ok(N::Module(name)), + module @ N::Module(_) => Ok(module), + _ => Err("expected a module".into()), + } + } + + /// `WT`: a conformance, the path of an associated type, and the protocol that type conforms + /// to. The path is a first element, then `_`, then any further elements; an element is a name, + /// optionally followed by the protocol that declares it. + fn associated_type_witness_accessor(&mut self) -> R<()> { + let proto = self.witness_type()?; + let mut parts = Vec::new(); + let mut closed = false; + while !closed { + let mut node = self.pop()?; + if matches!(node, N::FirstMarker) { + closed = true; + node = self.pop()?; + } + let part = match node { + N::Ident(name) => name, + owner @ N::Nominal { kind: 'P', .. } => format!("{}.{}", path(&owner, 0), self.pop_name()?), + _ => return Err("expected an associated type name".into()), + }; + parts.push(part); + } + parts.reverse(); + let conf = self.witness_conformance()?; + let prefix = format!("associated type witness table accessor for {} : {} in", parts.join("."), render(&proto, 0)); + self.push(N::Global { prefix, inner: Box::new(conf), suffix: String::new() }) + } + fn note_param(&mut self, idx: u64) { self.max_param = Some(self.max_param.map_or(idx, |m| m.max(idx))); } @@ -1047,6 +1114,27 @@ impl<'a> D<'a> { } b'L' => self.global("lazy protocol witness table cache variable for"), b'C' => self.enum_case(), + b'I' => { + let conf = self.witness_conformance()?; + self.push(N::Global { + prefix: "instantiation function for generic protocol witness table for".into(), + inner: Box::new(conf), + suffix: String::new(), + }) + } + b'l' => { + let conf = self.witness_conformance()?; + let ty = self.witness_type()?; + let prefix = format!("lazy protocol witness table accessor for type {} and conformance", render(&ty, 0)); + self.push(N::Global { prefix, inner: Box::new(conf), suffix: String::new() }) + } + b'b' => { + let base = self.witness_type()?; + let conf = self.witness_conformance()?; + let prefix = format!("base witness table accessor for {} in", render(&base, 0)); + self.push(N::Global { prefix, inner: Box::new(conf), suffix: String::new() }) + } + b'T' => self.associated_type_witness_accessor(), _ => Err("unsupported witness kind".into()), } } diff --git a/crates/formats/tests/swift_demangle_witness_accessors.rs b/crates/formats/tests/swift_demangle_witness_accessors.rs new file mode 100644 index 000000000..5ea28f21e --- /dev/null +++ b/crates/formats/tests/swift_demangle_witness_accessors.rs @@ -0,0 +1,144 @@ +use craft_anything_formats::swift_demangle::{Status, demangle}; + +fn dm(symbol: &str) -> String { + let d = demangle(symbol); + assert_eq!(d.status, Status::Demangled, "{symbol}: {:?}", d.reason); + d.demangled.unwrap_or_default() +} + +// Symbols from macOS 15.7.4 and Xcode 26.0 beta system binaries, expected text from `swift-demangle`. + +/// `Wl` names a type and then a conformance, which may be of another type or of a generic one. +#[test] +fn a_lazy_accessor_names_its_type_and_its_conformance() { + assert_eq!( + dm("_$s7SwiftUI4EdgeO3SetVAESQAAWl"), + "lazy protocol witness table accessor for type SwiftUI.Edge.Set and conformance SwiftUI.Edge.Set : Swift.Equatable in SwiftUI" + ); + assert_eq!( + dm("_$s11SWBProtocol28BuildTaskStyleMessagePayloadOACSYAAWl"), + "lazy protocol witness table accessor for type SWBProtocol.BuildTaskStyleMessagePayload and conformance SWBProtocol.BuildTaskStyleMessagePayload : Swift.RawRepresentable in SWBProtocol" + ); + assert_eq!( + dm("_$s9ACPAPIKit26RetryableRequestErrorAllOfV10CodingKeys33_352B664ED4F40B0BFFFCE9A65F6DAFCALLOAFs23CustomStringConvertibleAAWl"), + "lazy protocol witness table accessor for type ACPAPIKit.RetryableRequestErrorAllOf.(CodingKeys in _352B664ED4F40B0BFFFCE9A65F6DAFCA) and conformance ACPAPIKit.RetryableRequestErrorAllOf.(CodingKeys in _352B664ED4F40B0BFFFCE9A65F6DAFCA) : Swift.CustomStringConvertible in ACPAPIKit" + ); +} + +/// The type before the conformance need not be the conformance's own type, and a generic type prints its parameters. +#[test] +fn the_type_and_the_conformance_may_differ() { + // Constructed with `swiftc` and checked with `swift-demangle`. + assert_eq!(dm("_$s1m2SQVSiAA1PAAWl"), "lazy protocol witness table accessor for type m.SQ and conformance Swift.Int : m.P in m"); + assert_eq!(dm("_$s1m1HVySiGACyxGAA1RAAWl"), "lazy protocol witness table accessor for type m.H and conformance m.H : m.R in m"); +} + +/// `Wb` names a base protocol and then the conformance that inherits it. +#[test] +fn a_base_accessor_names_a_protocol_and_a_conformance() { + assert_eq!( + dm("_$s16PreviewsPipeline24ExecutionPointPropertiesV10UpdateModeOSHAASQWb"), + "base witness table accessor for Swift.Equatable in PreviewsPipeline.ExecutionPointProperties.UpdateMode : Swift.Hashable in PreviewsPipeline" + ); + assert_eq!( + dm("_$s13SwiftPackages5DequeVyxGSkAASKWb"), + "base witness table accessor for Swift.BidirectionalCollection in SwiftPackages.Deque : Swift.RandomAccessCollection in SwiftPackages" + ); + assert_eq!( + dm("_$s9ACPAPIKit25CKDBRecordChangesResponseV10CodingKeys33_E0431BA88FC7738BFAA921A9F433610FLLOSHAASQWb"), + "base witness table accessor for Swift.Equatable in ACPAPIKit.CKDBRecordChangesResponse.(CodingKeys in _E0431BA88FC7738BFAA921A9F433610F) : Swift.Hashable in ACPAPIKit" + ); + assert_eq!(dm("_$s1m1HVyxGSHAASQWb"), "base witness table accessor for Swift.Equatable in m.H : Swift.Hashable in m"); +} + +/// `WT` names the path of an associated type, the protocol it must conform to, and a conformance. The path can have several elements, and an element does not have to name its protocol. +#[test] +fn an_associated_type_accessor_names_a_path_a_protocol_and_a_conformance() { + assert_eq!( + dm("_$sSu12SIMD4StorageVs11SIMDStorages6ScalarsACP_SEWT"), + "associated type witness table accessor for Swift.SIMDStorage.Scalar : Swift.Encodable in Swift.UInt.SIMD4Storage : Swift.SIMDStorage in Swift" + ); + assert_eq!( + dm("_$s10Foundation10POSIXErrorVAA21_BridgedStoredNSErrorAA4CodeAaDP_AA06_ErrorF8ProtocolPWT"), + "associated type witness table accessor for Foundation._BridgedStoredNSError.Code : Foundation._ErrorCodeProtocol in Foundation.POSIXError : Foundation._BridgedStoredNSError in Foundation" + ); + assert_eq!( + dm("_$s10Foundation10CocoaErrorVAA21_BridgedStoredNSErrorAA4CodeAaDP_8RawValueSYs17FixedWidthIntegerPWT"), + "associated type witness table accessor for Foundation._BridgedStoredNSError.Code.Swift.RawRepresentable.RawValue : Swift.FixedWidthInteger in Foundation.CocoaError : Foundation._BridgedStoredNSError in Foundation" + ); + assert_eq!( + dm("_$s10Foundation27_JSONKeyedDecodingContainer33_12768CA107A31EF2DCE034FD75B541C9LLVyxGs05KeyedcD8ProtocolAA3Key_s06CodingN0PWT"), + "associated type witness table accessor for Key : Swift.CodingKey in Foundation.(_JSONKeyedDecodingContainer in _12768CA107A31EF2DCE034FD75B541C9) : Swift.KeyedDecodingContainerProtocol in Foundation" + ); +} + +/// Constructed paths: one element with and without its protocol, and elements before and after the `_`. +#[test] +fn associated_type_paths_read_as_swift_demangle_reads_them() { + // Constructed and checked with `swift-demangle`. + assert_eq!(dm("_$s1m2SQVAA1PAA1AAaDP_AA1QPWT"), "associated type witness table accessor for m.P.A : m.Q in m.SQ : m.P in m"); + assert_eq!(dm("_$s1m2SQVAA1PAA1A_AA1QPWT"), "associated type witness table accessor for A : m.Q in m.SQ : m.P in m"); + assert_eq!(dm("_$s1m2SQVAA1PAA1A_1BSQWT"), "associated type witness table accessor for A.B : Swift.Equatable in m.SQ : m.P in m"); + assert_eq!(dm("_$s1m2SQVAA1PAA1AAaDP_1BAaDPAA1QPWT"), "associated type witness table accessor for m.P.A.m.P.B : m.Q in m.SQ : m.P in m"); + assert_eq!(dm("_$s1m2SQVAA1PAA1AAaDP_1B1CSQWT"), "associated type witness table accessor for m.P.A.B.C : Swift.Equatable in m.SQ : m.P in m"); +} + +/// `WI` is the function that builds a generic conformance's witness table. It takes the same conformance as `WP`. +#[test] +fn an_instantiation_function_names_a_conformance() { + assert_eq!( + dm("_$s19CompilerSwiftSyntax019SameTypeRequirementC0V04LeftE0OAA0C8ProtocolAAWI"), + "instantiation function for generic protocol witness table for CompilerSwiftSyntax.SameTypeRequirementSyntax.LeftType : CompilerSwiftSyntax.SyntaxProtocol in CompilerSwiftSyntax" + ); + assert_eq!( + dm("_$s13XcodeCloudKit27TransformingObservableValue33_84B04509D109AA156A0BE9068F54C453LLCyxq_GAA0eF8ProtocolAAWI"), + "instantiation function for generic protocol witness table for XcodeCloudKit.(TransformingObservableValue in _84B04509D109AA156A0BE9068F54C453) : XcodeCloudKit.ObservableValueProtocol in XcodeCloudKit" + ); + assert_eq!(dm("_$s1m1HVyxGAA1RAAWI"), "instantiation function for generic protocol witness table for m.H : m.R in m"); +} + +/// `swift-demangle` prints `(extension in M):` before a type declared in an extension, which this demangler leaves out by design. +#[test] +fn a_type_declared_in_an_extension_leaves_out_the_extension_prefix() { + assert_eq!( + dm("_$s10Foundation15AttributeScopesO14XCUIAutomationE28SyntaxHighlightingAttributesVAfA0B5ScopeADWl"), + "lazy protocol witness table accessor for type Foundation.AttributeScopes.SyntaxHighlightingAttributes and conformance Foundation.AttributeScopes.SyntaxHighlightingAttributes : Foundation.AttributeScope in XCUIAutomation" + ); + assert_eq!( + dm("_$s10Foundation3URLV21XCSchemaSerializationE0D5ErrorOAA09LocalizedE0ADs0E0PWb"), + "base witness table accessor for Swift.Error in Foundation.URL.SerializationError : Foundation.LocalizedError in XCSchemaSerialization" + ); + assert_eq!( + dm("_$s10RealityKit12MeshResourceC0A10FoundationE4PartVs12IdentifiableAD2IDsAGP_SHWT"), + "associated type witness table accessor for Swift.Identifiable.ID : Swift.Hashable in RealityKit.MeshResource.Part : Swift.Identifiable in RealityFoundation" + ); +} + +/// `swift-demangle` decodes none of these. A conformance needs a type, a protocol and a module, and each +/// accessor needs its own further operands: a type for `Wl`, a base type for `Wb`, a path ending in `_` for +/// `WT`. A metadata symbol is not a type, and a type is not a module. +#[test] +fn malformed_operands_are_invalid() { + for symbol in [ + "$s4mainWl", + "$s4mainWb", + "$s4mainWI", + "$s4mainWT", + "_$s1m2SQVAA1PAAWl", + "_$s1m2SQVACAA1PAAWb", + "_$s1m2SQVAA1PAAWT", + "_$s1m2SQVMaACSHAAWl", + "_$s1m2SQVMaSHAAWI", + "_$s1m2SQVMaSHAAWb", + "_$s1m2SQVSHAAMaWb", + "_$s1m2SQVSHSQWI", + "_$s1m2SQVSHSiWI", + "_$s1m2SQVAA1PAA1ASQWT", + "_$s1m2SQVAA1PAA_SQWT", + "_$s1m2SQVAA1PAA1A_1B_SQWT", + "_$s1m2SQVAA1PAA1ASi_SQWT", + "_$s1m2SQVAA1PAA1A_AaDPSQWT", + ] { + assert_eq!(demangle(symbol).status, Status::Invalid, "{symbol}"); + } +} diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 5bbca4b5d..1ec6ef74c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1861,6 +1861,11 @@ Owner: open · Status: in progress `Foundation.__DataStorage.append(Swift.UnsafeRawPointer, length: Swift.Int) -> ()` where `swift-demangle` prints `append(_: Swift.UnsafeRawPointer, length: Swift.Int) -> ()`. — claimed: Chr0mium24, branch bugfix/r3.12-swift-demangle-unlabeled-args +- [x] Swift witness table accessors decode. The demangler read `Wl`, `Wb`, `WT` and `WI` as unknown + witness kinds and reported them invalid ("unsupported witness kind"): + `_$s7SwiftUI4EdgeO3SetVAESQAAWl` is `lazy protocol witness table accessor for type + SwiftUI.Edge.Set and conformance SwiftUI.Edge.Set : Swift.Equatable in SwiftUI`. + — claimed: Chr0mium24, branch bugfix/r3.12-swift-demangle-witness-accessors - [x] Apply the extracted-string limit in file-offset order across UTF-16LE and narrow strings, so an early wide string is not hidden by later ASCII. — claimed: Afloat16, branch bugfix/r3.12-earliest-extracted-strings - [x] Visit XML plist values only inside a complete, correctly encoded document. diff --git a/docs/STATUS.md b/docs/STATUS.md index f1cf26e30..4555689f5 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -165,6 +165,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie | Apple app graphs | Selecting a macOS bundle recognises its root-relative `Contents/Info.plist` and retains its service/extension type; nested XPC bundles appear in `services` and as `xpc-service` graph nodes, including their executables when hosted in frameworks | Synthetic inventory tests, including parent-directory and flat bundle layouts, selected services/extensions, framework-hosted service executables, and bare-program controls. Ordinary selected directories with `Contents/Info.plist` need an Apple bundle suffix; archives retain layout-based recognition. Framework libraries and dylibs stay excluded from executables. Real app bundles were not checked for this correction | | Apple asset catalog directories | A BOM block index and its named variables must fit inside their declared table ranges. Bytes belonging to the next section cannot complete a truncated entry. | A valid two-variable store and shortened or oversized directory lengths. | | Swift associated type parameters (`apple_swift_symbols_demangle`) | `Qy` numbers its generic parameter the way `q` does, so `Qy_` names an associated type of `B` and `Qy0_` one of `C`, as `swift-demangle` reads them; `Qz` still names one of `A`. The depth form (`Qyd__`) is still reported invalid, as `qd__` is | Integration test on three symbols from macOS system binaries and six constructed ones checked with `swift-demangle`. 133,643 distinct Swift symbols from the system apps, frameworks and `/usr/libexec` of macOS 15.7 compared with `swift-demangle`: the 6 that named `A` for `B` now match exactly, and no other symbol's output changed | +| Swift witness table accessors (`apple_swift_symbols_demangle`) | A symbol ending `Wl`, `Wb`, `WT` or `WI` reads as the accessor `swift-demangle` prints: `lazy protocol witness table accessor for type T and conformance C`, `base witness table accessor for P in C`, `associated type witness table accessor for P.A : Q in C` (the path may have several elements) and `instantiation function for generic protocol witness table for C`, where `C` is `type : protocol in module`. A metadata or witness symbol, an entity or a type where the module belongs, a missing operand or an associated type path without its `_` is reported invalid, as `swift-demangle` does. A conformance with generic requirements (`…Rzl`) and the other manglings in the operands stay unsupported and are reported invalid. Other rendering (no `(extension in …)` prefix) is unchanged | Integration test on 15 symbols from macOS system binaries, nine constructed ones and 18 constructed invalid ones, checked with `swift-demangle`. 2,361,216 distinct Swift symbols from `nm -j` on 4,113 Mach-O files of macOS 15.7.4 and Xcode 26.0 beta compared with `swift-demangle`: of the 102,757 ending `Wl`, `Wb`, `WT` or `WI` (with or without `Tm`) and reported invalid, 99,778 now match exactly and 1,832 differ only in the `(extension in …)` prefix; 1,143 stay invalid (1,142 conformances with generic requirements, one symbol whose leftover nodes `swift-demangle` prints in front) and 4 are symbols `swift-demangle` rejects too. No symbol that matched before changed, and none that `swift-demangle` rejects decodes | | Asset catalog key formats (`apple_assets_list`) | A catalog built for a system older than one of its key attributes, which actool marks with a stand-in in KEYFORMAT and the real attribute in KEYFORMATWORKAROUND, takes the real one, so display gamut is named `display-gamut` in the key format and rendition keys instead of `placeholder` | Hand-built fixture; 738 catalogs on macOS 15.7 and one built by actool for macOS 10.11 compared with `assetutil --info`. iOS catalogs were not checked | | Chinese UI | Simplified (`zh-hans`) and Traditional (`zh-hant`) Chinese in Settings → General → Language; System chooses a supported OS language, otherwise English. Both catalogs cover UI controls and tool titles; translated titles are searchable. Raw tool data, AI text, logs, CLI/MCP and the separate browser viewer keep their original text. See [localisation](localization.md). | Catalog integrity and locale-resolution tests; `cargo xtask i18n-coverage`; isolated UI language-switch test. Platform visual checks are recorded separately. | | Dart snapshot metadata extent | An adjacent record can no longer supply a snapshot version hash or feature string. | Serialized length fixtures cover the end of the fixed header and hash. |