From cfe88fa66b1285735bd489e4729814e986ca5c6b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 2 Jul 2025 18:03:23 +0800 Subject: [PATCH 1/8] Fixes --- Package.swift | 1 + .../Enums/SwiftSymbolParseError.swift | 2 + Sources/Demangle/Interface.swift | 4 +- Sources/Demangle/Main/DemangleOptions.swift | 14 + Sources/Demangle/Main/Demangler.swift | 972 +----------------- Sources/Demangle/Main/NodePrinter.swift | 1 + .../Node/Node+CustomStringConvertible.swift | 2 +- Sources/Demangle/Node/Node+Kind.swift | 2 +- Sources/Demangle/Utils/Common.swift | 32 - Sources/Demangle/Utils/Extensions.swift | 21 +- Sources/MachOExtensions/MachOFile+.swift | 28 +- .../Models/Mangling/MangledName.swift | 8 +- .../Utils/MetadataReader.swift | 20 +- .../Utils/PrimitiveTypeMapping.swift | 12 +- Sources/MachOSymbols/SymbolCache.swift | 45 +- Sources/MachOSymbols/SymbolIndexStore.swift | 55 +- .../SwiftDump/Dumpable+/Class+Dumpable.swift | 8 +- .../SwiftDump/Dumpable+/Enum+Dumpable.swift | 2 +- .../Dumpable+/Protocol+Dumpable.swift | 2 +- .../ProtocolConformance+Dumpable.swift | 26 +- .../SwiftDump/Dumpable+/Struct+Dumpable.swift | 2 +- .../Extensions/GenericContext+Dump.swift | 6 +- .../Extensions/ResilientSuperclass+Dump.swift | 4 +- Sources/swift-section/DemangleCommand.swift | 2 +- .../SymbolDemangleTests.swift | 2 +- 25 files changed, 179 insertions(+), 1094 deletions(-) diff --git a/Package.swift b/Package.swift index 553f61db..1feb7b44 100644 --- a/Package.swift +++ b/Package.swift @@ -140,6 +140,7 @@ let package = Package( dependencies: [ .MachOKit, "MachOMacro", + .product(name: "AssociatedObject", package: "AssociatedObject"), ] ), diff --git a/Sources/Demangle/Enums/SwiftSymbolParseError.swift b/Sources/Demangle/Enums/SwiftSymbolParseError.swift index 76627371..19ebf274 100644 --- a/Sources/Demangle/Enums/SwiftSymbolParseError.swift +++ b/Sources/Demangle/Enums/SwiftSymbolParseError.swift @@ -25,4 +25,6 @@ public enum SwiftSymbolParseError: Error, Sendable { case unimplementedFeature case requiredNonOptional + + case invalidSwiftMangledName } diff --git a/Sources/Demangle/Interface.swift b/Sources/Demangle/Interface.swift index 1315fd98..d1884099 100644 --- a/Sources/Demangle/Interface.swift +++ b/Sources/Demangle/Interface.swift @@ -21,9 +21,9 @@ package func demangleAsNode(_ mangled: C, isType: Bool = false, s demangler.symbolicReferenceResolver = symbolicReferenceResolver if isType { return try demangler.demangleType() - } else if getManglingPrefixLength(mangled) != 0 { + } else if Demangler.getManglingPrefixLength(mangled) != 0 { return try demangler.demangleSymbol() } else { - return try demangler.demangleSwift3TopLevelSymbol() + throw SwiftSymbolParseError.invalidSwiftMangledName } } diff --git a/Sources/Demangle/Main/DemangleOptions.swift b/Sources/Demangle/Main/DemangleOptions.swift index f81e4907..e0d69530 100644 --- a/Sources/Demangle/Main/DemangleOptions.swift +++ b/Sources/Demangle/Main/DemangleOptions.swift @@ -26,6 +26,8 @@ public struct DemangleOptions: OptionSet, Codable, Sendable { public static let showModuleInDependentMemberType = DemangleOptions(rawValue: 1 << 21) package static let removeWeakPrefix = DemangleOptions(rawValue: 1 << 22) + package static let removeBoundGeneric = DemangleOptions(rawValue: 1 << 23) + public init(rawValue: Int) { self.rawValue = rawValue @@ -69,5 +71,17 @@ public struct DemangleOptions: OptionSet, Codable, Sendable { options.remove(.showModuleInDependentMemberType) return options }() + + public static let interfaceType: DemangleOptions = { + var options = DemangleOptions.default + options.remove(.displayObjCModule) + options.insert(.synthesizeSugarOnTypes) + options.remove(.displayWhereClauses) + options.remove(.displayExtensionContexts) + options.remove(.showPrivateDiscriminators) + options.remove(.showModuleInDependentMemberType) + options.insert(.removeBoundGeneric) + return options + }() } diff --git a/Sources/Demangle/Main/Demangler.swift b/Sources/Demangle/Main/Demangler.swift index b2e8bf1b..81fb763f 100644 --- a/Sources/Demangle/Main/Demangler.swift +++ b/Sources/Demangle/Main/Demangler.swift @@ -1,4 +1,4 @@ -package struct Demangler: Sendable where C: Collection, C.Iterator.Element == UnicodeScalar, C: Sendable, C.Index: Sendable { +struct Demangler: Sendable where C: Collection, C.Iterator.Element == UnicodeScalar, C: Sendable, C.Index: Sendable { private var scanner: ScalarScanner private var nameStack: [Node] = [] private var substitutions: [Node] = [] @@ -8,11 +8,24 @@ package struct Demangler: Sendable where C: Collection, C.Iterator.Element == private var flavor: ManglingFlavor = .default private var symbolicReferenceIndex: Int = 0 - package var symbolicReferenceResolver: SymbolicReferenceResolver? = nil + var symbolicReferenceResolver: SymbolicReferenceResolver? = nil - package init(scalars: C) { + init(scalars: C) { self.scanner = ScalarScanner(scalars: scalars) } + + static func getManglingPrefixLength(_ scalars: C) -> Int { + var scanner = ScalarScanner(scalars: scalars) + if scanner.conditional(string: "_T0") || scanner.conditional(string: "_$S") || scanner.conditional(string: "_$s") || scanner.conditional(string: "_$e") { + return 3 + } else if scanner.conditional(string: "$S") || scanner.conditional(string: "$s") || scanner.conditional(string: "$e") { + return 2 + } else if scanner.conditional(string: "@__swiftmacro_") { + return 14 + } + + return 0 + } } extension Demangler { @@ -114,7 +127,6 @@ extension Demangler { } private mutating func demangleSymbolicReference(rawValue: UInt8) throws -> Node { - guard let (kind, directness) = SymbolicReference.symbolicReference(for: rawValue) else { throw SwiftSymbolParseError.requiredNonOptional } @@ -1460,7 +1472,6 @@ extension Demangler { } private mutating func demangleGenericParamIndex() throws -> Node { - switch try scanner.readScalar() { case "d": let depth = try demangleIndex() + 1 @@ -1565,7 +1576,7 @@ extension Demangler { } else { nodeKind = c == "K" ? .keyPathGetterThunkHelper : .keyPathSetterThunkHelper } - + let isSerialized = scanner.conditional(string: "q") var types = [Node]() var node = pop(kind: .type) @@ -1575,7 +1586,7 @@ extension Demangler { } node = pop(kind: .type) } while node != nil && node?.kind == .type - + var result: Node if let n = pop() { if n.kind == .dependentGenericSignature { @@ -2056,7 +2067,7 @@ extension Demangler { assocTypePath.reverseChildren() return assocTypePath } - + private mutating func popAssocTypeName() -> Node? { var proto = pop(kind: .type) if let proto, !proto.isProtocol { @@ -2068,7 +2079,7 @@ extension Demangler { if proto == nil { proto = pop(kind: .objectiveCProtocolSymbolicReference) } - + guard let identifier = pop(kind: .identifier) else { return nil } let assocType = Node(kind: .dependentAssociatedTypeRef, child: identifier) if let proto { @@ -2076,7 +2087,7 @@ extension Demangler { } return assocType } - + private mutating func demangleSpecialType() throws -> Node { let specialChar = try scanner.readScalar() switch specialChar { @@ -2366,13 +2377,11 @@ extension Demangler { sig.insertChild(req, at: requirementsIndex) } return sig - /* - let count = sig.children.count - while let req = pop(where: { $0.isRequirement }) { - sig.addChild(req) - } - sig.reverseFirst(count) - */ + // let count = sig.children.count + // while let req = pop(where: { $0.isRequirement }) { + // sig.addChild(req) + // } + // sig.reverseFirst(count) } private mutating func demangleGenericRequirement() throws -> Node { @@ -2553,931 +2562,6 @@ extension Demangler { } } -// MARK: Demangle.cpp (Swift 3) - -extension Demangler { - package mutating func demangleSwift3TopLevelSymbol() throws -> Node { - reset() - - try scanner.match(string: "_T") - var children = [Node]() - - switch try (scanner.readScalar(), scanner.readScalar()) { - case ("T", "S"): - repeat { - try children.append(demangleSwift3SpecializedAttribute()) - nameStack.removeAll() - } while scanner.conditional(string: "_TTS") - try scanner.match(string: "_T") - case ("T", "o"): children.append(Node(kind: .objCAttribute)) - case ("T", "O"): children.append(Node(kind: .nonObjCAttribute)) - case ("T", "D"): children.append(Node(kind: .dynamicAttribute)) - case ("T", "d"): children.append(Node(kind: .directMethodReferenceAttribute)) - case ("T", "v"): children.append(Node(kind: .vTableAttribute)) - default: try scanner.backtrack(count: 2) - } - - try children.append(demangleSwift3Global()) - - let remainder = scanner.remainder() - if !remainder.isEmpty { - children.append(Node(kind: .suffix, contents: .name(remainder))) - } - - return Node(kind: .global, children: children) - } - - private mutating func demangleSwift3Global() throws -> Node { - let c1 = try scanner.readScalar() - let c2 = try scanner.readScalar() - switch (c1, c2) { - case ("M", "P"): return try Node(kind: .genericTypeMetadataPattern, children: [demangleSwift3Type()]) - case ("M", "a"): return try Node(kind: .typeMetadataAccessFunction, children: [demangleSwift3Type()]) - case ("M", "L"): return try Node(kind: .typeMetadataLazyCache, children: [demangleSwift3Type()]) - case ("M", "m"): return try Node(kind: .metaclass, children: [demangleSwift3Type()]) - case ("M", "n"): return try Node(kind: .nominalTypeDescriptor, children: [demangleSwift3Type()]) - case ("M", "f"): return try Node(kind: .fullTypeMetadata, children: [demangleSwift3Type()]) - case ("M", "p"): return try Node(kind: .protocolDescriptor, children: [demangleSwift3ProtocolName()]) - case ("M", _): - try scanner.backtrack() - return try Node(kind: .typeMetadata, children: [demangleSwift3Type()]) - case ("P", "A"): - return try Node(kind: scanner.conditional(scalar: "o") ? .partialApplyObjCForwarder : .partialApplyForwarder, children: scanner.conditional(string: "__T") ? [demangleSwift3Global()] : []) - case ("P", _): throw scanner.unexpectedError() - case ("t", _): - try scanner.backtrack() - return try Node(kind: .typeMangling, children: [demangleSwift3Type()]) - case ("w", _): - let c3 = try scanner.readScalar() - let value: UInt64 - switch (c2, c3) { - case ("a", "l"): value = ValueWitnessKind.allocateBuffer.rawValue - case ("c", "a"): value = ValueWitnessKind.assignWithCopy.rawValue - case ("t", "a"): value = ValueWitnessKind.assignWithTake.rawValue - case ("d", "e"): value = ValueWitnessKind.deallocateBuffer.rawValue - case ("x", "x"): value = ValueWitnessKind.destroy.rawValue - case ("X", "X"): value = ValueWitnessKind.destroyBuffer.rawValue - case ("C", "P"): value = ValueWitnessKind.initializeBufferWithCopyOfBuffer.rawValue - case ("C", "p"): value = ValueWitnessKind.initializeBufferWithCopy.rawValue - case ("c", "p"): value = ValueWitnessKind.initializeWithCopy.rawValue - case ("C", "c"): value = ValueWitnessKind.initializeArrayWithCopy.rawValue - case ("T", "K"): value = ValueWitnessKind.initializeBufferWithTakeOfBuffer.rawValue - case ("T", "k"): value = ValueWitnessKind.initializeBufferWithTake.rawValue - case ("t", "k"): value = ValueWitnessKind.initializeWithTake.rawValue - case ("T", "t"): value = ValueWitnessKind.initializeArrayWithTakeFrontToBack.rawValue - case ("t", "T"): value = ValueWitnessKind.initializeArrayWithTakeBackToFront.rawValue - case ("p", "r"): value = ValueWitnessKind.projectBuffer.rawValue - case ("X", "x"): value = ValueWitnessKind.destroyArray.rawValue - case ("x", "s"): value = ValueWitnessKind.storeExtraInhabitant.rawValue - case ("x", "g"): value = ValueWitnessKind.getExtraInhabitantIndex.rawValue - case ("u", "g"): value = ValueWitnessKind.getEnumTag.rawValue - case ("u", "p"): value = ValueWitnessKind.destructiveProjectEnumData.rawValue - default: throw scanner.unexpectedError() - } - return try Node(kind: .valueWitness, contents: .index(value), children: [demangleSwift3Type()]) - case ("W", "V"): return try Node(kind: .valueWitnessTable, children: [demangleSwift3Type()]) - case ("W", "v"): return try Node(kind: .fieldOffset, children: [Node(kind: .directness, contents: .index(scanner.readScalar() == "d" ? 0 : 1)), demangleSwift3Entity()]) - case ("W", "P"): return try Node(kind: .protocolWitnessTable, children: [demangleSwift3ProtocolConformance()]) - case ("W", "G"): return try Node(kind: .genericProtocolWitnessTable, children: [demangleSwift3ProtocolConformance()]) - case ("W", "I"): return try Node(kind: .genericProtocolWitnessTableInstantiationFunction, children: [demangleSwift3ProtocolConformance()]) - case ("W", "l"): return try Node(kind: .lazyProtocolWitnessTableAccessor, children: [demangleSwift3Type(), demangleSwift3ProtocolConformance()]) - case ("W", "L"): return try Node(kind: .lazyProtocolWitnessTableCacheVariable, children: [demangleSwift3Type(), demangleSwift3ProtocolConformance()]) - case ("W", "a"): return try Node(kind: .protocolWitnessTableAccessor, children: [demangleSwift3ProtocolConformance()]) - case ("W", "t"): return try Node(kind: .associatedTypeMetadataAccessor, children: [demangleSwift3ProtocolConformance(), demangleSwift3DeclName()]) - case ("W", "T"): return try Node(kind: .associatedTypeWitnessTableAccessor, children: [demangleSwift3ProtocolConformance(), demangleSwift3DeclName(), demangleSwift3ProtocolName()]) - case ("W", _): throw scanner.unexpectedError() - case ("T", "W"): return try Node(kind: .protocolWitness, children: [demangleSwift3ProtocolConformance(), demangleSwift3Entity()]) - case ("T", "R"): fallthrough - case ("T", "r"): return try Node(kind: c2 == "R" ? Node.Kind.reabstractionThunkHelper : Node.Kind.reabstractionThunk, children: scanner.conditional(scalar: "G") ? [demangleSwift3GenericSignature(), demangleSwift3Type(), demangleSwift3Type()] : [demangleSwift3Type(), demangleSwift3Type()]) - default: - try scanner.backtrack(count: 2) - return try demangleSwift3Entity() - } - } - - private mutating func demangleSwift3SpecializedAttribute() throws -> Node { - let c = try scanner.readScalar() - var children = [Node]() - if scanner.conditional(scalar: "q") { - children.append(Node(kind: .isSerialized)) - } - try children.append(Node(kind: .specializationPassID, contents: .index(UInt64(scanner.readScalar().value - 48)))) - switch c { - case "r": fallthrough - case "g": - while !scanner.conditional(scalar: "_") { - var parameterChildren = [Node]() - try parameterChildren.append(demangleSwift3Type()) - while !scanner.conditional(scalar: "_") { - try parameterChildren.append(demangleSwift3ProtocolConformance()) - } - children.append(Node(kind: .genericSpecializationParam, children: parameterChildren)) - } - return Node(kind: c == "r" ? .genericSpecializationNotReAbstracted : .genericSpecialization, children: children) - case "f": - var count: UInt64 = 0 - while !scanner.conditional(scalar: "_") { - var paramChildren = [Node]() - let c = try scanner.readScalar() - switch try (c, scanner.readScalar()) { - case ("n", "_"): break - case ("c", "p"): try paramChildren.append(contentsOf: demangleSwift3FuncSigSpecializationConstantProp()) - case ("c", "l"): - paramChildren.append(Node(kind: .functionSignatureSpecializationParamKind, contents: .index(FunctionSigSpecializationParamKind.closureProp.rawValue))) - try paramChildren.append(Node(kind: .functionSignatureSpecializationParamPayload, contents: demangleSwift3Identifier().contents)) - while !scanner.conditional(scalar: "_") { - try paramChildren.append(demangleSwift3Type()) - } - case ("i", "_"): fallthrough - case ("k", "_"): paramChildren.append(Node(kind: .functionSignatureSpecializationParamKind, contents: .index(c == "i" ? FunctionSigSpecializationParamKind.boxToValue.rawValue : FunctionSigSpecializationParamKind.boxToStack.rawValue))) - default: - try scanner.backtrack(count: 2) - var value: UInt64 = 0 - value |= scanner.conditional(scalar: "d") ? FunctionSigSpecializationParamKind.dead.rawValue : 0 - value |= scanner.conditional(scalar: "g") ? FunctionSigSpecializationParamKind.ownedToGuaranteed.rawValue : 0 - value |= scanner.conditional(scalar: "o") ? FunctionSigSpecializationParamKind.guaranteedToOwned.rawValue : 0 - value |= scanner.conditional(scalar: "s") ? FunctionSigSpecializationParamKind.sroa.rawValue : 0 - try scanner.match(scalar: "_") - paramChildren.append(Node(kind: .functionSignatureSpecializationParamKind, contents: .index(value))) - } - children.append(Node(kind: .functionSignatureSpecializationParam, contents: .index(count), children: paramChildren)) - count += 1 - } - return Node(kind: .functionSignatureSpecialization, children: children) - default: throw scanner.unexpectedError() - } - } - - private mutating func demangleSwift3FuncSigSpecializationConstantProp() throws -> [Node] { - switch try (scanner.readScalar(), scanner.readScalar()) { - case ("f", "r"): - let name = try Node(kind: .functionSignatureSpecializationParamPayload, contents: demangleSwift3Identifier().contents) - try scanner.match(scalar: "_") - let kind = Node(kind: .functionSignatureSpecializationParamKind, contents: .index(FunctionSigSpecializationParamKind.constantPropFunction.rawValue)) - return [kind, name] - case ("g", _): - try scanner.backtrack() - let name = try Node(kind: .functionSignatureSpecializationParamPayload, contents: demangleSwift3Identifier().contents) - try scanner.match(scalar: "_") - let kind = Node(kind: .functionSignatureSpecializationParamKind, contents: .index(FunctionSigSpecializationParamKind.constantPropGlobal.rawValue)) - return [kind, name] - case ("i", _): - try scanner.backtrack() - let string = try scanner.readUntil(scalar: "_") - try scanner.match(scalar: "_") - let name = Node(kind: .functionSignatureSpecializationParamPayload, contents: .name(string)) - let kind = Node(kind: .functionSignatureSpecializationParamKind, contents: .index(FunctionSigSpecializationParamKind.constantPropInteger.rawValue)) - return [kind, name] - case ("f", "l"): - let string = try scanner.readUntil(scalar: "_") - try scanner.match(scalar: "_") - let name = Node(kind: .functionSignatureSpecializationParamPayload, contents: .name(string)) - let kind = Node(kind: .functionSignatureSpecializationParamKind, contents: .index(FunctionSigSpecializationParamKind.constantPropFloat.rawValue)) - return [kind, name] - case ("s", "e"): - var string: String - switch try scanner.readScalar() { - case "0": string = "u8" - case "1": string = "u16" - default: throw scanner.unexpectedError() - } - try scanner.match(scalar: "v") - let name = try Node(kind: .functionSignatureSpecializationParamPayload, contents: demangleSwift3Identifier().contents) - let encoding = Node(kind: .functionSignatureSpecializationParamPayload, contents: .name(string)) - let kind = Node(kind: .functionSignatureSpecializationParamKind, contents: .index(FunctionSigSpecializationParamKind.constantPropString.rawValue)) - try scanner.match(scalar: "_") - return [kind, encoding, name] - default: throw scanner.unexpectedError() - } - } - - private mutating func demangleSwift3ProtocolConformance() throws -> Node { - let type = try demangleSwift3Type() - let prot = try demangleSwift3ProtocolName() - let context = try demangleSwift3Context() - return Node(kind: .protocolConformance, children: [type, prot, context]) - } - - private mutating func demangleSwift3ProtocolName() throws -> Node { - let name: Node - if scanner.conditional(scalar: "S") { - let index = try demangleSwift3SubstitutionIndex() - switch index.kind { - case .protocol: name = index - case .module: name = try demangleSwift3ProtocolNameGivenContext(context: index) - default: throw scanner.unexpectedError() - } - } else if scanner.conditional(scalar: "s") { - let stdlib = Node(kind: .module, contents: .name(stdlibName)) - name = try demangleSwift3ProtocolNameGivenContext(context: stdlib) - } else { - name = try demangleSwift3DeclarationName(kind: .protocol) - } - - return Node(kind: .type, children: [name]) - } - - private mutating func demangleSwift3ProtocolNameGivenContext(context: Node) throws -> Node { - let name = try demangleSwift3DeclName() - let result = Node(kind: .protocol, children: [context, name]) - nameStack.append(result) - return result - } - - private mutating func demangleSwift3NominalType() throws -> Node { - switch try scanner.readScalar() { - case "S": return try demangleSwift3SubstitutionIndex() - case "V": return try demangleSwift3DeclarationName(kind: .structure) - case "O": return try demangleSwift3DeclarationName(kind: .enum) - case "C": return try demangleSwift3DeclarationName(kind: .class) - case "P": return try demangleSwift3DeclarationName(kind: .protocol) - default: throw scanner.unexpectedError() - } - } - - private mutating func demangleSwift3BoundGenericArgs(nominalType initialNominal: Node) throws -> Node { - guard var parentOrModule = initialNominal.children.first else { throw scanner.unexpectedError() } - - let nominalType: Node - switch parentOrModule.kind { - case .module: fallthrough - case .function: fallthrough - case .extension: nominalType = initialNominal - default: - parentOrModule = try demangleSwift3BoundGenericArgs(nominalType: parentOrModule) - - guard initialNominal.children.count > 1 else { throw scanner.unexpectedError() } - nominalType = Node(kind: initialNominal.kind, children: [parentOrModule, initialNominal.children[1]]) - } +private let maxRepeatCount = 2048 - var children = [Node]() - while !scanner.conditional(scalar: "_") { - try children.append(demangleSwift3Type()) - } - if children.isEmpty { - return nominalType - } - let args = Node(kind: .typeList, children: children) - let unboundType = Node(kind: .type, children: [nominalType]) - switch nominalType.kind { - case .class: return Node(kind: .boundGenericClass, children: [unboundType, args]) - case .structure: return Node(kind: .boundGenericStructure, children: [unboundType, args]) - case .enum: return Node(kind: .boundGenericEnum, children: [unboundType, args]) - default: throw scanner.unexpectedError() - } - } - - private mutating func demangleSwift3Entity() throws -> Node { - let isStatic = scanner.conditional(scalar: "Z") - - let basicKind: Node.Kind - switch try scanner.readScalar() { - case "F": basicKind = .function - case "v": basicKind = .variable - case "I": basicKind = .initializer - case "i": basicKind = .subscript - default: - try scanner.backtrack() - return try demangleSwift3NominalType() - } - - let context = try demangleSwift3Context() - let kind: Node.Kind - let hasType: Bool - var name: Node? = nil - var wrapEntity = false - - let c = try scanner.readScalar() - switch c { - case "Z": (kind, hasType) = (.isolatedDeallocator, false) - case "D": (kind, hasType) = (.deallocator, false) - case "d": (kind, hasType) = (.destructor, false) - case "e": (kind, hasType) = (.iVarInitializer, false) - case "E": (kind, hasType) = (.iVarDestroyer, false) - case "C": (kind, hasType) = (.allocator, true) - case "c": (kind, hasType) = (.constructor, true) - case "a": fallthrough - case "l": - wrapEntity = true - switch try scanner.readScalar() { - case "O": (kind, hasType, name) = try (c == "a" ? .owningMutableAddressor : .owningAddressor, true, demangleSwift3DeclName()) - case "o": (kind, hasType, name) = try (c == "a" ? .nativeOwningMutableAddressor : .nativeOwningAddressor, true, demangleSwift3DeclName()) - case "p": (kind, hasType, name) = try (c == "a" ? .nativePinningMutableAddressor : .nativePinningAddressor, true, demangleSwift3DeclName()) - case "u": (kind, hasType, name) = try (c == "a" ? .unsafeMutableAddressor : .unsafeAddressor, true, demangleSwift3DeclName()) - default: throw scanner.unexpectedError() - } - case "g": (kind, hasType, name, wrapEntity) = try (.getter, true, demangleSwift3DeclName(), true) - case "G": (kind, hasType, name, wrapEntity) = try (.globalGetter, true, demangleSwift3DeclName(), true) - case "s": (kind, hasType, name, wrapEntity) = try (.setter, true, demangleSwift3DeclName(), true) - case "m": (kind, hasType, name, wrapEntity) = try (.materializeForSet, true, demangleSwift3DeclName(), true) - case "w": (kind, hasType, name, wrapEntity) = try (.willSet, true, demangleSwift3DeclName(), true) - case "W": (kind, hasType, name, wrapEntity) = try (.didSet, true, demangleSwift3DeclName(), true) - case "U": (kind, hasType, name) = try (.explicitClosure, true, Node(kind: .number, contents: .index(demangleSwift3Index()))) - case "u": (kind, hasType, name) = try (.implicitClosure, true, Node(kind: .number, contents: .index(demangleSwift3Index()))) - case "A" where basicKind == .initializer: (kind, hasType, name) = try (.defaultArgumentInitializer, false, Node(kind: .number, contents: .index(demangleSwift3Index()))) - case "i" where basicKind == .initializer: (kind, hasType) = (.initializer, false) - case _ where basicKind == .initializer: throw scanner.unexpectedError() - default: - try scanner.backtrack() - (kind, hasType, name) = try (basicKind, true, demangleSwift3DeclName()) - } - - let entity = Node(kind: kind) - if wrapEntity { - var isSubscript = false - switch name?.kind { - case .some(.identifier): - if name?.text == "subscript" { - isSubscript = true - name = nil - } - case .some(.privateDeclName): - if let n = name, let first = n.children.at(0), let second = n.children.at(1), second.text == "subscript" { - isSubscript = true - name = Node(kind: .privateDeclName, children: [first]) - } - default: break - } - var wrappedEntity: Node - if isSubscript { - wrappedEntity = Node(kind: .subscript, child: context) - } else { - wrappedEntity = Node(kind: .variable, child: context) - } - if !isSubscript, let n = name { - wrappedEntity.addChild(n) - } - if hasType { - try wrappedEntity.addChild(demangleSwift3Type()) - } - if isSubscript, let n = name { - wrappedEntity.addChild(n) - } - entity.addChild(wrappedEntity) - } else { - entity.addChild(context) - if let n = name { - entity.addChild(n) - } - if hasType { - try entity.addChild(demangleSwift3Type()) - } - } - - return isStatic ? Node(kind: .static, children: [entity]) : entity - } - - private mutating func demangleSwift3DeclarationName(kind: Node.Kind) throws -> Node { - let result = try Node(kind: kind, children: [demangleSwift3Context(), demangleSwift3DeclName()]) - nameStack.append(result) - return result - } - - private mutating func demangleSwift3Context() throws -> Node { - switch try scanner.readScalar() { - case "E": return try Node(kind: .extension, children: [demangleSwift3Module(), demangleSwift3Context()]) - case "e": - let module = try demangleSwift3Module() - let signature = try demangleSwift3GenericSignature() - let type = try demangleSwift3Context() - return Node(kind: .extension, children: [module, type, signature]) - case "S": return try demangleSwift3SubstitutionIndex() - case "s": return Node(kind: .module, contents: .name(stdlibName), children: []) - case "G": return try demangleSwift3BoundGenericArgs(nominalType: demangleSwift3NominalType()) - case "F": fallthrough - case "I": fallthrough - case "v": fallthrough - case "P": fallthrough - case "Z": fallthrough - case "C": fallthrough - case "V": fallthrough - case "O": - try scanner.backtrack() - return try demangleSwift3Entity() - default: - try scanner.backtrack() - return try demangleSwift3Module() - } - } - - private mutating func demangleSwift3Module() throws -> Node { - switch try scanner.readScalar() { - case "S": return try demangleSwift3SubstitutionIndex() - case "s": return Node(kind: .module, contents: .name("Swift"), children: []) - default: - try scanner.backtrack() - let module = try demangleSwift3Identifier(kind: .module) - nameStack.append(module) - return module - } - } - - private func swiftStdLibType(_ kind: Node.Kind, named: String) -> Node { - return Node(kind: kind, children: [Node(kind: .module, contents: .name(stdlibName)), Node(kind: .identifier, contents: .name(named))]) - } - - private mutating func demangleSwift3SubstitutionIndex() throws -> Node { - switch try scanner.readScalar() { - case "o": return Node(kind: .module, contents: .name(objcModule)) - case "C": return Node(kind: .module, contents: .name(cModule)) - case "a": return swiftStdLibType(.structure, named: "Array") - case "b": return swiftStdLibType(.structure, named: "Bool") - case "c": return swiftStdLibType(.structure, named: "UnicodeScalar") - case "d": return swiftStdLibType(.structure, named: "Double") - case "f": return swiftStdLibType(.structure, named: "Float") - case "i": return swiftStdLibType(.structure, named: "Int") - case "V": return swiftStdLibType(.structure, named: "UnsafeRawPointer") - case "v": return swiftStdLibType(.structure, named: "UnsafeMutableRawPointer") - case "P": return swiftStdLibType(.structure, named: "UnsafePointer") - case "p": return swiftStdLibType(.structure, named: "UnsafeMutablePointer") - case "q": return swiftStdLibType(.enum, named: "Optional") - case "Q": return swiftStdLibType(.enum, named: "ImplicitlyUnwrappedOptional") - case "R": return swiftStdLibType(.structure, named: "UnsafeBufferPointer") - case "r": return swiftStdLibType(.structure, named: "UnsafeMutableBufferPointer") - case "S": return swiftStdLibType(.structure, named: "String") - case "u": return swiftStdLibType(.structure, named: "UInt") - default: - try scanner.backtrack() - let index = try demangleSwift3Index() - if Int(index) >= nameStack.count { - throw scanner.unexpectedError() - } - return nameStack[Int(index)] - } - } - - private mutating func demangleSwift3GenericSignature(isPseudo: Bool = false) throws -> Node { - var children = [Node]() - var c = try scanner.requirePeek() - while c != "R" && c != "r" { - try children.append(Node(kind: .dependentGenericParamCount, contents: .index(scanner.conditional(scalar: "z") ? 0 : (demangleSwift3Index() + 1)))) - c = try scanner.requirePeek() - } - if children.isEmpty { - children.append(Node(kind: .dependentGenericParamCount, contents: .index(1))) - } - if !scanner.conditional(scalar: "r") { - try scanner.match(scalar: "R") - while !scanner.conditional(scalar: "r") { - try children.append(demangleSwift3GenericRequirement()) - } - } - return Node(kind: .dependentGenericSignature, children: children) - } - - private mutating func demangleSwift3GenericRequirement() throws -> Node { - let constrainedType = try demangleSwift3ConstrainedType() - if scanner.conditional(scalar: "z") { - return try Node(kind: .dependentGenericSameTypeRequirement, children: [constrainedType, demangleSwift3Type()]) - } - - if scanner.conditional(scalar: "l") { - let name: String - let kind: Node.Kind - var size = UInt64.max - var alignment = UInt64.max - switch try scanner.readScalar() { - case "U": (kind, name) = (.identifier, "U") - case "R": (kind, name) = (.identifier, "R") - case "N": (kind, name) = (.identifier, "N") - case "T": (kind, name) = (.identifier, "T") - case "E": - (kind, name) = (.identifier, "E") - size = try require(demangleNatural()) - try scanner.match(scalar: "_") - alignment = try require(demangleNatural()) - case "e": - (kind, name) = (.identifier, "e") - size = try require(demangleNatural()) - case "M": - (kind, name) = (.identifier, "M") - size = try require(demangleNatural()) - try scanner.match(scalar: "_") - alignment = try require(demangleNatural()) - case "m": - (kind, name) = (.identifier, "m") - size = try require(demangleNatural()) - default: throw failure - } - let second = Node(kind: kind, contents: .name(name)) - let reqt = Node(kind: .dependentGenericLayoutRequirement, children: [constrainedType, second]) - if size != UInt64.max { - reqt.addChild(Node(kind: .number, contents: .index(size))) - if alignment != UInt64.max { - reqt.addChild(Node(kind: .number, contents: .index(alignment))) - } - } - return reqt - } - - let c = try scanner.requirePeek() - let constraint: Node - if c == "C" { - constraint = try demangleSwift3Type() - } else if c == "S" { - try scanner.match(scalar: "S") - let index = try demangleSwift3SubstitutionIndex() - let typename: Node - switch index.kind { - case .protocol: fallthrough - case .class: typename = index - case .module: typename = try demangleSwift3ProtocolNameGivenContext(context: index) - default: throw scanner.unexpectedError() - } - constraint = Node(kind: .type, children: [typename]) - } else { - constraint = try demangleSwift3ProtocolName() - } - return Node(kind: .dependentGenericConformanceRequirement, children: [constrainedType, constraint]) - } - - private mutating func demangleSwift3ConstrainedType() throws -> Node { - if scanner.conditional(scalar: "w") { - return try demangleSwift3AssociatedTypeSimple() - } else if scanner.conditional(scalar: "W") { - return try demangleSwift3AssociatedTypeCompound() - } - return try demangleSwift3GenericParamIndex() - } - - private mutating func demangleSwift3AssociatedTypeSimple() throws -> Node { - let base = try demangleSwift3GenericParamIndex() - return try demangleSwift3DependentMemberTypeName(base: Node(kind: .type, children: [base])) - } - - private mutating func demangleSwift3AssociatedTypeCompound() throws -> Node { - var base = try demangleSwift3GenericParamIndex() - while !scanner.conditional(scalar: "_") { - let type = Node(kind: .type, children: [base]) - base = try demangleSwift3DependentMemberTypeName(base: type) - } - return base - } - - private mutating func demangleSwift3GenericParamIndex() throws -> Node { - let depth: UInt64 - let index: UInt64 - switch try scanner.readScalar() { - case "d": (depth, index) = try (demangleSwift3Index() + 1, demangleSwift3Index()) - case "x": (depth, index) = (0, 0) - default: - try scanner.backtrack() - (depth, index) = try (0, demangleSwift3Index() + 1) - } - return Node(kind: .dependentGenericParamType, contents: .name(archetypeName(index, depth)), children: [Node(kind: .index, contents: .index(depth)), Node(kind: .index, contents: .index(index))]) - } - - private mutating func demangleSwift3DependentMemberTypeName(base: Node) throws -> Node { - let associatedType: Node - if scanner.conditional(scalar: "S") { - associatedType = try demangleSwift3SubstitutionIndex() - } else { - var prot: Node? = nil - if scanner.conditional(scalar: "P") { - prot = try demangleSwift3ProtocolName() - } - let identifier = try demangleSwift3Identifier() - if let p = prot { - associatedType = Node(kind: .dependentAssociatedTypeRef, children: [identifier, p]) - } else { - associatedType = Node(kind: .dependentAssociatedTypeRef, children: [identifier]) - } - nameStack.append(associatedType) - } - - return Node(kind: .dependentMemberType, children: [base, associatedType]) - } - - private mutating func demangleSwift3DeclName() throws -> Node { - switch try scanner.readScalar() { - case "L": return try Node(kind: .localDeclName, children: [Node(kind: .number, contents: .index(demangleSwift3Index())), demangleSwift3Identifier()]) - case "P": return try Node(kind: .privateDeclName, children: [demangleSwift3Identifier(), demangleSwift3Identifier()]) - default: - try scanner.backtrack() - return try demangleSwift3Identifier() - } - } - - private mutating func demangleSwift3Index() throws -> UInt64 { - if scanner.conditional(scalar: "_") { - return 0 - } - let value = try UInt64(scanner.readInt()) + 1 - try scanner.match(scalar: "_") - return value - } - - private mutating func demangleSwift3Type() throws -> Node { - let type: Node - switch try scanner.readScalar() { - case "B": - switch try scanner.readScalar() { - case "b": type = Node(kind: .builtinTypeName, contents: .name("Builtin.BridgeObject")) - case "B": type = Node(kind: .builtinTypeName, contents: .name("Builtin.UnsafeValueBuffer")) - case "f": - let size = try scanner.readInt() - try scanner.match(scalar: "_") - type = Node(kind: .builtinTypeName, contents: .name("Builtin.FPIEEE\(size)")) - case "i": - let size = try scanner.readInt() - try scanner.match(scalar: "_") - type = Node(kind: .builtinTypeName, contents: .name("Builtin.Int\(size)")) - case "v": - let elements = try scanner.readInt() - try scanner.match(scalar: "B") - let name: String - let size: String - let c = try scanner.readScalar() - switch c { - case "p": (name, size) = ("xRawPointer", "") - case "i": fallthrough - case "f": - (name, size) = try (c == "i" ? "xInt" : "xFPIEEE", "\(scanner.readInt())") - try scanner.match(scalar: "_") - default: throw scanner.unexpectedError() - } - type = Node(kind: .builtinTypeName, contents: .name("Builtin.Vec\(elements)\(name)\(size)")) - case "O": type = Node(kind: .builtinTypeName, contents: .name("Builtin.UnknownObject")) - case "o": type = Node(kind: .builtinTypeName, contents: .name("Builtin.NativeObject")) - case "t": type = Node(kind: .builtinTypeName, contents: .name("Builtin.SILToken")) - case "p": type = Node(kind: .builtinTypeName, contents: .name("Builtin.RawPointer")) - case "w": type = Node(kind: .builtinTypeName, contents: .name("Builtin.Word")) - default: throw scanner.unexpectedError() - } - case "a": type = try demangleSwift3DeclarationName(kind: .typeAlias) - case "b": type = try demangleSwift3FunctionType(kind: .objCBlock) - case "c": type = try demangleSwift3FunctionType(kind: .cFunctionPointer) - case "D": type = try Node(kind: .dynamicSelf, children: [demangleSwift3Type()]) - case "E": - guard try scanner.readScalars(count: 2) == "RR" else { throw scanner.unexpectedError() } - type = Node(kind: .errorType, contents: .name(""), children: []) - case "F": type = try demangleSwift3FunctionType(kind: .functionType) - case "f": type = try demangleSwift3FunctionType(kind: .uncurriedFunctionType) - case "G": type = try demangleSwift3BoundGenericArgs(nominalType: demangleSwift3NominalType()) - case "X": - let c = try scanner.readScalar() - switch c { - case "b": type = try Node(kind: .silBoxType, children: [demangleSwift3Type()]) - case "B": - var signature: Node? = nil - if scanner.conditional(scalar: "G") { - signature = try demangleSwift3GenericSignature(isPseudo: false) - } - let layout = Node(kind: .silBoxLayout) - while !scanner.conditional(scalar: "_") { - let kind: Node.Kind - switch try scanner.readScalar() { - case "m": kind = .silBoxMutableField - case "i": kind = .silBoxImmutableField - default: throw failure - } - let type = try demangleType() - let field = Node(kind: kind, child: type) - layout.addChild(field) - } - var genericArgs: Node? = nil - if signature != nil { - let ga = Node(kind: .typeList) - while !scanner.conditional(scalar: "_") { - let type = try demangleType() - ga.addChild(type) - } - genericArgs = ga - } - let boxType = Node(kind: .silBoxTypeWithLayout, child: layout) - if let s = signature, let ga = genericArgs { - boxType.addChild(s) - boxType.addChild(ga) - } - return boxType - case "P" where scanner.conditional(scalar: "M"): fallthrough - case "M": - let value: String - switch try scanner.readScalar() { - case "t": value = "@thick" - case "T": value = "@thin" - case "o": value = "@objc_metatype" - default: throw scanner.unexpectedError() - } - type = try Node(kind: c == "P" ? .existentialMetatype : .metatype, children: [Node(kind: .metatypeRepresentation, contents: .name(value)), demangleSwift3Type()]) - case "P": - var children = [Node]() - while !scanner.conditional(scalar: "_") { - try children.append(demangleSwift3ProtocolName()) - } - type = Node(kind: .protocolList, children: [Node(kind: .typeList)]) - case "f": type = try demangleSwift3FunctionType(kind: .thinFunctionType) - case "o": type = try Node(kind: .unowned, children: [demangleSwift3Type()]) - case "u": type = try Node(kind: .unmanaged, children: [demangleSwift3Type()]) - case "w": type = try Node(kind: .weak, children: [demangleSwift3Type()]) - case "F": - var children = [Node]() - try children.append(Node(kind: .implConvention, contents: .name(demangleSwift3ImplConvention(kind: .implConvention)))) - if scanner.conditional(scalar: "C") { - let name: String - switch try scanner.readScalar() { - case "b": name = "@convention(block)" - case "c": name = "@convention(c)" - case "m": name = "@convention(method)" - case "O": name = "@convention(objc_method)" - case "w": name = "@convention(witness_method)" - default: throw scanner.unexpectedError() - } - children.append(Node(kind: .implFunctionAttribute, contents: .name(name))) - } - if scanner.conditional(scalar: "G") { - try children.append(demangleSwift3GenericSignature(isPseudo: false)) - } else if scanner.conditional(scalar: "g") { - try children.append(demangleSwift3GenericSignature(isPseudo: true)) - } - try scanner.match(scalar: "_") - while !scanner.conditional(scalar: "_") { - try children.append(demangleSwift3ImplParameterOrResult(kind: .implParameter)) - } - while !scanner.conditional(scalar: "_") { - try children.append(demangleSwift3ImplParameterOrResult(kind: .implResult)) - } - type = Node(kind: .implFunctionType, children: children) - default: throw scanner.unexpectedError() - } - case "K": type = try demangleSwift3FunctionType(kind: .autoClosureType) - case "M": type = try Node(kind: .metatype, children: [demangleSwift3Type()]) - case "P" where scanner.conditional(scalar: "M"): type = try Node(kind: .existentialMetatype, children: [demangleSwift3Type()]) - case "P": - var children = [Node]() - while !scanner.conditional(scalar: "_") { - try children.append(demangleSwift3ProtocolName()) - } - type = Node(kind: .protocolList, children: [Node(kind: .typeList, children: children)]) - case "Q": - if scanner.conditional(scalar: "u") { - type = Node(kind: .opaqueReturnType) - } else if scanner.conditional(scalar: "U") { - let index = try demangleIndex() - type = Node(kind: .opaqueReturnType, child: Node(kind: .opaqueReturnTypeIndex, contents: .index(index))) - } else { - type = try demangleSwift3ArchetypeType() - } - case "q": - let c = try scanner.requirePeek() - if c != "d" && c != "_" && c < "0" && c > "9" { - type = try demangleSwift3DependentMemberTypeName(base: demangleSwift3Type()) - } else { - type = try demangleSwift3GenericParamIndex() - } - case "x": type = Node(kind: .dependentGenericParamType, contents: .name(archetypeName(0, 0)), children: [Node(kind: .index, contents: .index(0)), Node(kind: .index, contents: .index(0))]) - case "w": type = try demangleSwift3AssociatedTypeSimple() - case "W": type = try demangleSwift3AssociatedTypeCompound() - case "R": type = try Node(kind: .inOut, children: demangleSwift3Type().children) - case "S": type = try demangleSwift3SubstitutionIndex() - case "T": type = try demangleSwift3Tuple(variadic: false) - case "t": type = try demangleSwift3Tuple(variadic: true) - case "u": type = try Node(kind: .dependentGenericType, children: [demangleSwift3GenericSignature(), demangleSwift3Type()]) - case "C": type = try demangleSwift3DeclarationName(kind: .class) - case "V": type = try demangleSwift3DeclarationName(kind: .structure) - case "O": type = try demangleSwift3DeclarationName(kind: .enum) - default: throw scanner.unexpectedError() - } - return Node(kind: .type, children: [type]) - } - - private mutating func demangleSwift3ArchetypeType() throws -> Node { - switch try scanner.readScalar() { - case "Q": - let result = try Node(kind: .associatedTypeRef, children: [demangleSwift3ArchetypeType(), demangleSwift3Identifier()]) - nameStack.append(result) - return result - case "S": - let index = try demangleSwift3SubstitutionIndex() - let result = try Node(kind: .associatedTypeRef, children: [index, demangleSwift3Identifier()]) - nameStack.append(result) - return result - case "s": - let root = Node(kind: .module, contents: .name(stdlibName)) - let result = try Node(kind: .associatedTypeRef, children: [root, demangleSwift3Identifier()]) - nameStack.append(result) - return result - default: throw scanner.unexpectedError() - } - } - - private mutating func demangleSwift3ImplConvention(kind: Node.Kind) throws -> String { - let scalar = try scanner.readScalar() - switch (scalar, kind == .implErrorResult ? .implResult : kind) { - case ("a", .implResult): return "@autoreleased" - case ("d", .implConvention): return "@callee_unowned" - case ("d", _): return "@unowned" - case ("D", .implResult): return "@unowned_inner_pointer" - case ("g", .implParameter): return "@guaranteed" - case ("e", .implParameter): return "@deallocating" - case ("g", .implConvention): return "@callee_guaranteed" - case ("i", .implParameter): return "@in" - case ("i", .implResult): return "@out" - case ("l", .implParameter): return "@inout" - case ("o", .implConvention): return "@callee_owned" - case ("o", _): return "@owned" - case ("t", .implConvention): return "@convention(thin)" - default: throw scanner.unexpectedError() - } - } - - private mutating func demangleSwift3ImplParameterOrResult(kind: Node.Kind) throws -> Node { - var k: Node.Kind - if scanner.conditional(scalar: "z") { - if case .implResult = kind { - k = .implErrorResult - } else { - throw scanner.unexpectedError() - } - } else { - k = kind - } - - let convention = try demangleSwift3ImplConvention(kind: k) - let type = try demangleSwift3Type() - let conventionNode = Node(kind: .implConvention, contents: .name(convention)) - return Node(kind: k, children: [conventionNode, type]) - } - - private mutating func demangleSwift3Tuple(variadic: Bool) throws -> Node { - var children = [Node]() - while !scanner.conditional(scalar: "_") { - var elementChildren = [Node]() - let peek = try scanner.requirePeek() - if (peek >= "0" && peek <= "9") || peek == "o" { - try elementChildren.append(demangleSwift3Identifier(kind: .tupleElementName)) - } - try elementChildren.append(demangleSwift3Type()) - children.append(Node(kind: .tupleElement, children: elementChildren)) - } - if variadic, let last = children.popLast() { - last.insertChild(Node(kind: .variadicMarker), at: 0) - children.append(last) - } - return Node(kind: .tuple, children: children) - } - - private mutating func demangleSwift3FunctionType(kind: Node.Kind) throws -> Node { - var children = [Node]() - if scanner.conditional(scalar: "z") { - children.append(Node(kind: .throwsAnnotation)) - } - try children.append(Node(kind: .argumentTuple, children: [demangleSwift3Type()])) - try children.append(Node(kind: .returnType, children: [demangleSwift3Type()])) - return Node(kind: kind, children: children) - } - - private mutating func demangleSwift3Identifier(kind: Node.Kind? = nil) throws -> Node { - let isPunycode = scanner.conditional(scalar: "X") - let k: Node.Kind - let isOperator: Bool - if scanner.conditional(scalar: "o") { - guard kind == nil else { throw scanner.unexpectedError() } - switch try scanner.readScalar() { - case "p": (isOperator, k) = (true, .prefixOperator) - case "P": (isOperator, k) = (true, .postfixOperator) - case "i": (isOperator, k) = (true, .infixOperator) - default: throw scanner.unexpectedError() - } - } else { - (isOperator, k) = (false, kind ?? Node.Kind.identifier) - } - - var identifier = try scanner.readScalars(count: Int(scanner.readInt())) - if isPunycode { - identifier = try decodeSwiftPunycode(identifier) - } - if isOperator { - let source = identifier - identifier = "" - for scalar in source.unicodeScalars { - switch scalar { - case "a": identifier.unicodeScalars.append("&" as UnicodeScalar) - case "c": identifier.unicodeScalars.append("@" as UnicodeScalar) - case "d": identifier.unicodeScalars.append("/" as UnicodeScalar) - case "e": identifier.unicodeScalars.append("=" as UnicodeScalar) - case "g": identifier.unicodeScalars.append(">" as UnicodeScalar) - case "l": identifier.unicodeScalars.append("<" as UnicodeScalar) - case "m": identifier.unicodeScalars.append("*" as UnicodeScalar) - case "n": identifier.unicodeScalars.append("!" as UnicodeScalar) - case "o": identifier.unicodeScalars.append("|" as UnicodeScalar) - case "p": identifier.unicodeScalars.append("+" as UnicodeScalar) - case "q": identifier.unicodeScalars.append("?" as UnicodeScalar) - case "r": identifier.unicodeScalars.append("%" as UnicodeScalar) - case "s": identifier.unicodeScalars.append("-" as UnicodeScalar) - case "t": identifier.unicodeScalars.append("~" as UnicodeScalar) - case "x": identifier.unicodeScalars.append("^" as UnicodeScalar) - case "z": identifier.unicodeScalars.append("." as UnicodeScalar) - default: - if scalar.value >= 128 { - identifier.unicodeScalars.append(scalar) - } else { - throw scanner.unexpectedError() - } - } - } - } - - return Node(kind: k, contents: .name(identifier), children: []) - } -} +private let maxNumWords = 26 diff --git a/Sources/Demangle/Main/NodePrinter.swift b/Sources/Demangle/Main/NodePrinter.swift index 4a4d0f27..5ab8c8dc 100644 --- a/Sources/Demangle/Main/NodePrinter.swift +++ b/Sources/Demangle/Main/NodePrinter.swift @@ -1858,6 +1858,7 @@ package struct NodePrinter: Sendable { } private mutating func printBoundGeneric(_ name: Node) { + guard !options.contains(.removeBoundGeneric) else { return } guard name.children.count >= 2 else { return } guard name.children.count == 2, options.contains(.synthesizeSugarOnTypes), name.kind != .boundGenericClass else { printBoundGenericNoSugar(name) diff --git a/Sources/Demangle/Node/Node+CustomStringConvertible.swift b/Sources/Demangle/Node/Node+CustomStringConvertible.swift index 97868ff0..3939e861 100644 --- a/Sources/Demangle/Node/Node+CustomStringConvertible.swift +++ b/Sources/Demangle/Node/Node+CustomStringConvertible.swift @@ -18,7 +18,7 @@ extension Node: CustomStringConvertible { private func printNode(output: inout String, node: Node, depth: Int = 0) { (0..<(depth * 2)).forEach { _ in output.append(" ") } - output.append("\(node.kind)") + output.append("kind=\(node.kind)") switch node.contents { case .none: break diff --git a/Sources/Demangle/Node/Node+Kind.swift b/Sources/Demangle/Node/Node+Kind.swift index 95811010..8920e389 100644 --- a/Sources/Demangle/Node/Node+Kind.swift +++ b/Sources/Demangle/Node/Node+Kind.swift @@ -542,6 +542,6 @@ extension Node.Kind { extension Node.Kind: CustomStringConvertible { public var description: String { - rawValue.capitalized + rawValue.capitalizingFirstLetter } } diff --git a/Sources/Demangle/Utils/Common.swift b/Sources/Demangle/Utils/Common.swift index c7f5a591..83575652 100644 --- a/Sources/Demangle/Utils/Common.swift +++ b/Sources/Demangle/Utils/Common.swift @@ -3,35 +3,3 @@ package let objcModule = "__C" package let cModule = "__C_Synthesized" package let lldbExpressionsModuleNamePrefix = "__lldb_expr_" -let maxRepeatCount = 2048 -let maxNumWords = 26 - -func archetypeName(_ index: UInt64, _ depth: UInt64) -> String { - var result = "" - var i = index - repeat { - result.unicodeScalars.append(UnicodeScalar(("A" as UnicodeScalar).value + UInt32(i % 26))!) - i /= 26 - } while i > 0 - if depth != 0 { - result += depth.description - } - return result -} - -// MARK: Punycode.h - - - -package func getManglingPrefixLength(_ scalars: C) -> Int where C.Iterator.Element == UnicodeScalar { - var scanner = ScalarScanner(scalars: scalars) - if scanner.conditional(string: "_T0") || scanner.conditional(string: "_$S") || scanner.conditional(string: "_$s") || scanner.conditional(string: "_$e") { - return 3 - } else if scanner.conditional(string: "$S") || scanner.conditional(string: "$s") || scanner.conditional(string: "$e") { - return 2 - } else if scanner.conditional(string: "@__swiftmacro_") { - return 14 - } - - return 0 -} diff --git a/Sources/Demangle/Utils/Extensions.swift b/Sources/Demangle/Utils/Extensions.swift index 473cff27..a17d6bd4 100644 --- a/Sources/Demangle/Utils/Extensions.swift +++ b/Sources/Demangle/Utils/Extensions.swift @@ -1,6 +1,6 @@ extension String { package var isSwiftSymbol: Bool { - getManglingPrefixLength(unicodeScalars) > 0 + Demangler.getManglingPrefixLength(unicodeScalars) > 0 } } @@ -72,3 +72,22 @@ extension BinaryInteger { String(self, radix: 16, uppercase: true) } } + +extension String { + // A computed property to capitalize the first letter of a string. + var capitalizingFirstLetter: String { + // 1. Get the first character. + guard let first = self.first else { + // Return an empty string if the original string is empty. + return "" + } + + // 2. Uppercase the first character and concatenate it with the rest of the string. + return first.uppercased() + self.dropFirst() + } + + // You can also create a mutating method if you want to change the string in place. + mutating func capitalizeFirstLetter() { + self = self.capitalizingFirstLetter + } +} diff --git a/Sources/MachOExtensions/MachOFile+.swift b/Sources/MachOExtensions/MachOFile+.swift index cc548478..e0bb1065 100644 --- a/Sources/MachOExtensions/MachOFile+.swift +++ b/Sources/MachOExtensions/MachOFile+.swift @@ -1,20 +1,30 @@ import Foundation import MachOKit +import AssociatedObject extension MachOFile { package var cache: DyldCache? { guard isLoadedFromDyldCache else { return nil } - guard let cache = try? DyldCache(url: url) else { - return nil - } - if let mainCache = cache.mainCache { - return try? .init( - subcacheUrl: cache.url, - mainCacheHeader: mainCache.header - ) + if let _cache { + return _cache + } else { + guard let cache = try? DyldCache(url: url) else { + return nil + } + var currentCache: DyldCache? = cache + if let mainCache = cache.mainCache { + currentCache = try? .init( + subcacheUrl: cache.url, + mainCacheHeader: mainCache.header + ) + } + _cache = currentCache + return currentCache } - return cache } + + @AssociatedObject(.retain(.nonatomic)) + private var _cache: DyldCache? package func cache(for address: UInt64) -> DyldCache? { cacheAndFileOffset(for: address)?.0 diff --git a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift b/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift index 4037045d..fdd7ae18 100644 --- a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift +++ b/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift @@ -52,18 +52,14 @@ public struct MangledName { package let startOffset: Int - package let endOffset: Int? + package let endOffset: Int - package init(elements: [Element], startOffset: Int, endOffset: Int?) { + package init(elements: [Element], startOffset: Int, endOffset: Int) { self.elements = elements self.startOffset = startOffset self.endOffset = endOffset } - package init(unsolvedSymbol: Symbol) { - self.init(elements: [.string(unsolvedSymbol.stringValue)], startOffset: unsolvedSymbol.offset, endOffset: nil) - } - package var lookupElements: [Element.Lookup] { elements.compactMap { if case .lookup(let lookup) = $0 { lookup } else { nil } } } diff --git a/Sources/MachOSwiftSection/Utils/MetadataReader.swift b/Sources/MachOSwiftSection/Utils/MetadataReader.swift index 09d5a952..e8192b15 100644 --- a/Sources/MachOSwiftSection/Utils/MetadataReader.swift +++ b/Sources/MachOSwiftSection/Utils/MetadataReader.swift @@ -14,12 +14,13 @@ public struct MetadataReader { return try demangle(for: mangledName, kind: .symbol, in: machOFile) } - public static func demangleType(for unsolvedSymbol: Symbol, in machOFile: MachOFile) throws -> Node { - return try required(buildContextManglingForSymbol(unsolvedSymbol, in: machOFile)) + public static func demangleType(for unsolvedSymbol: Symbol, in machOFile: MachOFile) throws -> Node? { + return try buildContextManglingForSymbol(unsolvedSymbol, in: machOFile) } - public static func demangleSymbol(for unsolvedSymbol: Symbol, in machOFile: MachOFile) throws -> Node { - return try demangle(for: .init(unsolvedSymbol: unsolvedSymbol), kind: .symbol, in: machOFile) + public static func demangleSymbol(for unsolvedSymbol: Symbol, in machOFile: MachOFile) throws -> Node? { +// return try demangle(for: .init(unsolvedSymbol: unsolvedSymbol), kind: .symbol, in: machOFile) + return SymbolCache.shared.demangledNode(for: unsolvedSymbol, in: machOFile) } public static func demangleContext(for context: ContextDescriptorWrapper, in machOFile: MachOFile) throws -> Node { @@ -33,8 +34,8 @@ public struct MetadataReader { case .symbol: mangledName.symbolStringValue() } - var demangler = Demangler(scalars: stringValue.unicodeScalars) - demangler.symbolicReferenceResolver = { kind, directness, index -> Node? in +// var demangler = Demangler(scalars: stringValue.unicodeScalars) + let symbolicReferenceResolver: SymbolicReferenceResolver = { kind, directness, index -> Node? in do { var result: Node? let lookup = mangledName.lookupElements[index] @@ -94,9 +95,9 @@ public struct MetadataReader { let result: Node switch kind { case .type: - result = try demangler.demangleType() + result = try demangleAsNode(stringValue, isType: true, symbolicReferenceResolver: symbolicReferenceResolver) case .symbol: - result = try demangler.demangleSymbol() + result = try demangleAsNode(stringValue, isType: false, symbolicReferenceResolver: symbolicReferenceResolver) } return result } @@ -290,8 +291,7 @@ public struct MetadataReader { } private static func buildContextManglingForSymbol(_ symbol: Symbol, in machOFile: MachOFile) throws -> Node? { - var demangler = Demangler(scalars: symbol.stringValue.unicodeScalars) - var demangledSymbol = try demangler.demangleSymbol() + var demangledSymbol = try demangleAsNode(symbol.stringValue) if demangledSymbol.kind == .global { demangledSymbol = demangledSymbol.children[0] } diff --git a/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift b/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift index 35b4a69d..ef00a5ad 100644 --- a/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift +++ b/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift @@ -13,6 +13,10 @@ package class PrimitiveTypeMapping { } } + package func hasPrimitiveType(for name: String) -> Bool { + return storage[name] != nil + } + package func primitiveType(for name: String) -> String? { return storage[name] } @@ -34,8 +38,12 @@ package class PrimitiveTypeMapping { guard let descriptor = try RelativeDirectPointer(relativeOffset: relativeReference.relativeOffset).resolve(from: descriptorLookup.offset, in: machO).namedContextDescriptor else { continue } let name = try descriptor.name(in: machO) let mangledName = try descriptor.mangledName(in: machO) - guard let endOffset = mangledName.endOffset else { continue } - storage[name] = try machO.readString(offset: endOffset) + let endOffset = mangledName.endOffset + let primitiveName = try machO.readString(offset: endOffset) + if let firstChar = primitiveName.first, firstChar == "N" { + storage[name] = String(primitiveName.dropFirst()) + } + case .indirect: continue } diff --git a/Sources/MachOSymbols/SymbolCache.swift b/Sources/MachOSymbols/SymbolCache.swift index a28ea80e..72889426 100644 --- a/Sources/MachOSymbols/SymbolCache.swift +++ b/Sources/MachOSymbols/SymbolCache.swift @@ -21,42 +21,71 @@ package final class SymbolCache { memoryPressureMonitor.startMonitoring() } - private typealias CacheEntry = OrderedDictionary + private struct CacheEntry { + var isLoaded: Bool = false + var symbolsByOffset: OrderedDictionary = [:] + var demangledNodeBySymbol: [Symbol: Node] = [:] + } private var cacheEntryByIdentifier: [AnyHashable: CacheEntry] = [:] @discardableResult package func createCacheIfNeeded(in machO: MachO, isForced: Bool = false) -> Bool { - guard isForced || (cacheEntryByIdentifier[machO.identifier]?.isEmpty ?? true) else { return false } - var cacheEntry: CacheEntry = [:] + guard isForced || ((cacheEntryByIdentifier[machO.identifier].map(\.isLoaded) ?? false) == false) else { return false } + var cacheEntry: CacheEntry = .init() var cachedSymbols: Set = [] for symbol in machO.symbols where symbol.name.isSwiftSymbol { var offset = symbol.offset - cacheEntry[offset, default: []].append(.init(offset: offset, stringValue: symbol.name)) + cacheEntry.symbolsByOffset[offset, default: []].append(.init(offset: offset, stringValue: symbol.name)) if let cache = machO.cache { offset -= cache.mainCacheHeader.sharedRegionStart.cast() - cacheEntry[offset, default: []].append(.init(offset: offset, stringValue: symbol.name)) + cacheEntry.symbolsByOffset[offset, default: []].append(.init(offset: offset, stringValue: symbol.name)) } cachedSymbols.insert(symbol.name) } for exportedSymbol in machO.exportedSymbols where exportedSymbol.name.isSwiftSymbol && !cachedSymbols.contains(exportedSymbol.name) { if var offset = exportedSymbol.offset { - cacheEntry[offset, default: []].append(.init(offset: offset, stringValue: exportedSymbol.name)) + cacheEntry.symbolsByOffset[offset, default: []].append(.init(offset: offset, stringValue: exportedSymbol.name)) offset += machO.startOffset - cacheEntry[offset, default: []].append(.init(offset: offset, stringValue: exportedSymbol.name)) + cacheEntry.symbolsByOffset[offset, default: []].append(.init(offset: offset, stringValue: exportedSymbol.name)) } } + +// for symbol in cacheEntry.symbolsByOffset.values.flatMap({ $0 }) { +// do { +// let node = try demangleAsNode(symbol.stringValue) +// cacheEntry.demangledNodeBySymbol[symbol] = node +// } catch { +// print(error) +// } +// } + + cacheEntry.isLoaded = true cacheEntryByIdentifier[machO.identifier] = cacheEntry return true } package func symbols(for offset: Int, in machO: MachO) -> Symbols? { createCacheIfNeeded(in: machO) - if let symbols = cacheEntryByIdentifier[machO.identifier, default: [:]][offset], !symbols.isEmpty { + if let symbols = cacheEntryByIdentifier[machO.identifier]?.symbolsByOffset[offset], !symbols.isEmpty { return .init(offset: offset, symbols: symbols) } else { return nil } } + + package func demangledNode(for symbol: Symbol, in machO: MachO) -> Node? { + createCacheIfNeeded(in: machO) + guard var cacheEntry = cacheEntryByIdentifier[machO.identifier] else { return nil } + if let node = cacheEntry.demangledNodeBySymbol[symbol] { + return node + } else if let node = try? demangleAsNode(symbol.stringValue) { + cacheEntry.demangledNodeBySymbol[symbol] = node + cacheEntryByIdentifier[machO.identifier] = cacheEntry + return node + } else { + return nil + } + } } diff --git a/Sources/MachOSymbols/SymbolIndexStore.swift b/Sources/MachOSymbols/SymbolIndexStore.swift index ee579626..918adef5 100644 --- a/Sources/MachOSymbols/SymbolIndexStore.swift +++ b/Sources/MachOSymbols/SymbolIndexStore.swift @@ -89,59 +89,8 @@ package final class SymbolIndexStore { for symbol in symbols.values { do { - var demangler = Demangler(scalars: symbol.stringValue.unicodeScalars) - let node = try demangler.demangleSymbol() -// func perform(_ node: Node, isStatic: Bool) { -// if let functionNode = node.children.first, functionNode.kind == .function { -// if let structureNode = functionNode.children.first, structureNode.kind == .structure { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: structureNode) -// } -// entry.symbolsByKind[isStatic ? .struct(.staticFunction) : .struct(.function), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } else if let enumNode = functionNode.children.first, enumNode.kind == .enum { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: enumNode) -// } -// entry.symbolsByKind[isStatic ? .enum(.staticFunction) : .enum(.function), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } else if let extensionNode = functionNode.children.first, extensionNode.kind == .extension { -// if let structureNode = extensionNode.children.at(1), structureNode.kind == .structure { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: structureNode) -// } -// entry.symbolsByKind[isStatic ? .struct(.staticFunctionInExtension) : .struct(.functionInExtension), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } else if let enumNode = extensionNode.children.at(1), enumNode.kind == .enum { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: enumNode) -// } -// entry.symbolsByKind[isStatic ? .enum(.staticFunctionInExtension) : .enum(.functionInExtension), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } -// } -// } else if let propertyNode = node.children.first, propertyNode.kind == .getter || propertyNode.kind == .setter || propertyNode.kind == .modifyAccessor, let variableNode = propertyNode.children.first, variableNode.kind == .variable { -// if let structureNode = variableNode.children.first, structureNode.kind == .structure { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: structureNode) -// } -// entry.symbolsByKind[isStatic ? .struct(.staticVariable) : .struct(.variable), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } else if let enumNode = variableNode.children.first, enumNode.kind == .enum { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: enumNode) -// } -// entry.symbolsByKind[isStatic ? .enum(.staticVariable) : .enum(.variable), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } else if let extensionNode = variableNode.children.first, extensionNode.kind == .extension { -// if let structureNode = extensionNode.children.at(1), structureNode.kind == .structure { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: structureNode) -// } -// entry.symbolsByKind[isStatic ? .struct(.staticVariableInExtension) : .struct(.variableInExtension), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } else if let enumNode = extensionNode.children.at(1), enumNode.kind == .enum { -// let typeNode = Node(kind: .global) { -// Node(kind: .type, child: enumNode) -// } -// entry.symbolsByKind[isStatic ? .enum(.staticVariableInExtension) : .enum(.variableInExtension), default: [:]][typeNode.print(using: .interface), default: []].append(symbol) -// } -// } -// } -// } + + let node = try demangleAsNode(symbol.stringValue) func perform(_ node: Node, isStatic: Bool) { guard let firstChild = node.children.first else { return } diff --git a/Sources/SwiftDump/Dumpable+/Class+Dumpable.swift b/Sources/SwiftDump/Dumpable+/Class+Dumpable.swift index 8bcb5e48..1df5a08c 100644 --- a/Sources/SwiftDump/Dumpable+/Class+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable+/Class+Dumpable.swift @@ -119,7 +119,7 @@ extension Class: NamedDumpable { case .symbol(let symbol): Keyword(.override) Space() - try MetadataReader.demangleSymbol(for: symbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) case .element(let element): dumpMethodKind(for: element) Keyword(.override) @@ -131,7 +131,7 @@ extension Class: NamedDumpable { Keyword(.override) Space() if let symbol = try? descriptor.implementationSymbol(in: machOFile) { - try MetadataReader.demangleSymbol(for: symbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) } else { @@ -154,7 +154,7 @@ extension Class: NamedDumpable { Space() if let symbol = try? descriptor.implementationSymbol(in: machOFile) { - try MetadataReader.demangleSymbol(for: symbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) } else { @@ -198,7 +198,7 @@ extension Class: NamedDumpable { @SemanticStringBuilder private func dumpMethodDeclaration(for descriptor: MethodDescriptor, using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { if let symbol = try? descriptor.implementationSymbol(in: machOFile) { - try MetadataReader.demangleSymbol(for: symbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) } else { diff --git a/Sources/SwiftDump/Dumpable+/Enum+Dumpable.swift b/Sources/SwiftDump/Dumpable+/Enum+Dumpable.swift index 410cfd32..aa64bfe0 100644 --- a/Sources/SwiftDump/Dumpable+/Enum+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable+/Enum+Dumpable.swift @@ -84,7 +84,7 @@ extension Enum: NamedDumpable { Indent(level: 1) - try MetadataReader.demangleSymbol(for: function, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: function, in: machOFile)?.printSemantic(using: options) if offset.isEnd { BreakLine() diff --git a/Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift b/Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift index 7376bd02..5be92f42 100644 --- a/Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift @@ -96,7 +96,7 @@ extension MachOSwiftSection.`Protocol`: NamedDumpable { @MachOImageGenerator private func validNode(for symbols: Symbols, in machOFile: MachOFile, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolNode = node.first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interface, in: machOFile)).string, !visitedNode.contains(node) { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolNode = node.first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interfaceType, in: machOFile)).string, !visitedNode.contains(node) { return node } } diff --git a/Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift b/Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift index 01a35a13..8bf252b4 100644 --- a/Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift @@ -18,7 +18,7 @@ extension ProtocolConformance: ConformedDumpable { case .indirectTypeDescriptor(let descriptor): switch descriptor { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() case .element(let element): try element.dumpName(using: options, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() case nil: @@ -29,7 +29,7 @@ extension ProtocolConformance: ConformedDumpable { case .indirectObjCClass(let objcClass): switch objcClass { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() case .element(let element): try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machOFile))), in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() case nil: @@ -43,7 +43,7 @@ extension ProtocolConformance: ConformedDumpable { public func dumpProtocolName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { switch `protocol` { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) case .element(let element): try MetadataReader.demangleContext(for: .protocol(element), in: machOFile).printSemantic(using: options) case .none: @@ -58,8 +58,12 @@ extension ProtocolConformance: ConformedDumpable { Space() - try dumpTypeName(using: options, in: machOFile) - + let typeName = try dumpTypeName(using: options, in: machOFile) + + typeName + + let interfaceTypeName = try dumpTypeName(using: .interfaceType, in: machOFile).string + Standard(":") Space() @@ -90,18 +94,18 @@ extension ProtocolConformance: ConformedDumpable { Indent(level: 1) - if let symbols = try resilientWitness.implementationSymbols(in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, visitedNode: visitedNodes) { + if let symbols = try resilientWitness.implementationSymbols(in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: interfaceTypeName, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) } else if let requirement = try resilientWitness.requirement(in: machOFile) { switch requirement { case .symbol(let symbol): - try MetadataReader.demangleSymbol(for: symbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) case .element(let element): - if let symbols = try Symbols.resolve(from: element.offset, in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, visitedNode: visitedNodes) { + if let symbols = try Symbols.resolve(from: element.offset, in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: interfaceTypeName, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) - } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machOFile), let validNode = try validNode(for: defaultImplementationSymbols, in: machOFile, visitedNode: visitedNodes) { + } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machOFile), let validNode = try validNode(for: defaultImplementationSymbols, in: machOFile, typeName: interfaceTypeName, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) } else if !element.defaultImplementation.isNull { @@ -124,9 +128,9 @@ extension ProtocolConformance: ConformedDumpable { } @MachOImageGenerator - private func validNode(for symbols: Symbols, in machOFile: MachOFile, visitedNode: borrowing OrderedSet = []) throws -> Node? { + private func validNode(for symbols: Symbols, in machOFile: MachOFile, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.first(where: { $0.kind == .protocolConformance }), protocolConformanceNode.children.at(0)?.print(using: .interface) == (try dumpTypeName(using: .interface, in: machOFile)).string { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.first(where: { $0.kind == .protocolConformance }), protocolConformanceNode.children.at(0)?.print(using: .interfaceType) == typeName { return node } } diff --git a/Sources/SwiftDump/Dumpable+/Struct+Dumpable.swift b/Sources/SwiftDump/Dumpable+/Struct+Dumpable.swift index 351f7d6d..49fa0ca4 100644 --- a/Sources/SwiftDump/Dumpable+/Struct+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable+/Struct+Dumpable.swift @@ -90,7 +90,7 @@ extension Struct: NamedDumpable { Indent(level: 1) - try MetadataReader.demangleSymbol(for: symbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) if offset.isEnd { BreakLine() diff --git a/Sources/SwiftDump/Extensions/GenericContext+Dump.swift b/Sources/SwiftDump/Extensions/GenericContext+Dump.swift index fb4df3b5..fd745272 100644 --- a/Sources/SwiftDump/Extensions/GenericContext+Dump.swift +++ b/Sources/SwiftDump/Extensions/GenericContext+Dump.swift @@ -71,7 +71,7 @@ extension GenericRequirementDescriptor { case .protocol(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) case .element(let element): switch element { case .objc(let objc): @@ -86,9 +86,9 @@ extension GenericRequirementDescriptor { TypeName(kind: .other, "AnyObject") } case .conformance /* (let protocolConformanceDescriptor) */: - Standard("") + Standard("SwiftDumpConformance") case .invertedProtocols/* (let invertedProtocols) */: - Standard("") + Standard("SwiftDumpInvertedProtocols") // if invertedProtocols.protocols.hasCopyable, invertedProtocols.protocols.hasEscapable { // // "Copyable, Escapable" diff --git a/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift b/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift index 43a45bcd..e98ed813 100644 --- a/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift +++ b/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift @@ -14,7 +14,7 @@ extension ResilientSuperclass { case .indirectTypeDescriptor(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machOFile).printSemantic(using: options) + return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) case .element(let element): return try element.dumpName(using: options, in: machOFile) case nil: @@ -25,7 +25,7 @@ extension ResilientSuperclass { case .indirectObjCClass(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machOFile).printSemantic(using: options) + return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) case .element(let element): return try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machOFile))), in: machOFile).printSemantic(using: options) case nil: diff --git a/Sources/swift-section/DemangleCommand.swift b/Sources/swift-section/DemangleCommand.swift index e3a58bac..7d5680e7 100644 --- a/Sources/swift-section/DemangleCommand.swift +++ b/Sources/swift-section/DemangleCommand.swift @@ -26,6 +26,6 @@ struct DemangleCommand: AsyncParsableCommand { let machOFile = try MachOFile.load(options: machOOptions) let demangledNode = try MetadataReader.demangleSymbol(for: .init(offset: fileOffset ?? 0, stringValue: mangledName), in: machOFile) let demangleOptions = demangleOptionGroup.buildSwiftDumpDemangleOptions() - print(mangledName, "--->", demangledNode.print(using: demangleOptions)) + print(mangledName, "--->", demangledNode?.print(using: demangleOptions) ?? mangledName) } } diff --git a/Tests/MachOSwiftSectionTests/SymbolDemangleTests.swift b/Tests/MachOSwiftSectionTests/SymbolDemangleTests.swift index 530901ab..5b06bc56 100644 --- a/Tests/MachOSwiftSectionTests/SymbolDemangleTests.swift +++ b/Tests/MachOSwiftSectionTests/SymbolDemangleTests.swift @@ -1,6 +1,6 @@ import Foundation import Testing -import Demangle +@testable import Demangle import MachOKit import MachOMacro import MachOFoundation From bda9d9efc99f8b70386b844b326f6b6a2a14cb8c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 3 Jul 2025 01:27:25 +0800 Subject: [PATCH 2/8] Add MachCaches target, optimize the effect of dump protocolConformance --- Package.swift | 43 +++-- Sources/Demangle/Main/NodePrinter.swift | 2 +- Sources/Demangle/Node/Node+Collection.swift | 121 +------------- Sources/MachOCaches/MachOCache.swift | 22 +++ .../Utils/PrimitiveTypeMapping.swift | 32 ++-- Sources/SwiftDump/Dumpable.swift | 22 --- .../AssociatedType+Dumpable.swift | 0 .../Class+Dumpable.swift | 12 -- .../Enum+Dumpable.swift | 0 .../Protocol+Dumpable.swift | 2 +- .../ProtocolConformance+Dumpable.swift | 29 ++-- .../Protocols/ConformedDumpable.swift | 9 ++ .../Dumpable/Protocols/Dumpable.swift | 14 ++ .../Dumpable/Protocols/NamedDumpable.swift | 7 + .../Struct+Dumpable.swift | 0 .../Dumper/ProtocolConformanceDumper.swift | 150 ++++++++++++++++++ .../Dumper/Protocols/ConformedDumper.swift | 6 + .../SwiftDump/Dumper/Protocols/Dumper.swift | 5 + ...{Node+SemanticString.swift => Node+.swift} | 6 + .../Extensions/SemanticString+.swift | 16 ++ Sources/SwiftDump/Extensions/String+.swift | 6 + 21 files changed, 302 insertions(+), 202 deletions(-) create mode 100644 Sources/MachOCaches/MachOCache.swift delete mode 100644 Sources/SwiftDump/Dumpable.swift rename Sources/SwiftDump/{Dumpable+ => Dumpable}/AssociatedType+Dumpable.swift (100%) rename Sources/SwiftDump/{Dumpable+ => Dumpable}/Class+Dumpable.swift (97%) rename Sources/SwiftDump/{Dumpable+ => Dumpable}/Enum+Dumpable.swift (100%) rename Sources/SwiftDump/{Dumpable+ => Dumpable}/Protocol+Dumpable.swift (93%) rename Sources/SwiftDump/{Dumpable+ => Dumpable}/ProtocolConformance+Dumpable.swift (90%) create mode 100644 Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift create mode 100644 Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift create mode 100644 Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift rename Sources/SwiftDump/{Dumpable+ => Dumpable}/Struct+Dumpable.swift (100%) create mode 100644 Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift create mode 100644 Sources/SwiftDump/Dumper/Protocols/ConformedDumper.swift create mode 100644 Sources/SwiftDump/Dumper/Protocols/Dumper.swift rename Sources/SwiftDump/Extensions/{Node+SemanticString.swift => Node+.swift} (92%) create mode 100644 Sources/SwiftDump/Extensions/SemanticString+.swift diff --git a/Package.swift b/Package.swift index 1feb7b44..97d7d7fe 100644 --- a/Package.swift +++ b/Package.swift @@ -134,7 +134,7 @@ let package = Package( .target( name: "Utilities" ), - + .target( name: "MachOExtensions", dependencies: [ @@ -144,6 +144,17 @@ let package = Package( ] ), + .target( + name: "MachOCaches", + dependencies: [ + .MachOKit, + "MachOExtensions", + "MachOMacro", + "Utilities", + .product(name: "AssociatedObject", package: "AssociatedObject"), + ] + ), + .target( name: "MachOReading", dependencies: [ @@ -154,7 +165,7 @@ let package = Package( .product(name: "AssociatedObject", package: "AssociatedObject"), ] ), - + .target( name: "MachOSymbols", dependencies: [ @@ -166,7 +177,7 @@ let package = Package( .product(name: "OrderedCollections", package: "swift-collections"), ] ), - + .target( name: "MachOPointer", dependencies: [ @@ -195,20 +206,10 @@ let package = Package( "Demangle", "MachOFoundation", "MachOMacro", - .product(name: "MemberwiseInit", package: "swift-memberwise-init-macro") + .product(name: "MemberwiseInit", package: "swift-memberwise-init-macro"), ] ), - .target( - name: "MachOTestingSupport", - dependencies: [ - .MachOKit, - "MachOExtensions", - "SwiftDump", - ], - swiftSettings: testSettings - ), - .target( name: "SwiftDump", dependencies: [ @@ -229,6 +230,8 @@ let package = Package( ] ), + // MARK: - Macros + .target( name: "MachOMacro", dependencies: [ @@ -246,6 +249,18 @@ let package = Package( ] ), + // MARK: - Testing + + .target( + name: "MachOTestingSupport", + dependencies: [ + .MachOKit, + "MachOExtensions", + "SwiftDump", + ], + swiftSettings: testSettings + ), + .testTarget( name: "DemangleTests", dependencies: [ diff --git a/Sources/Demangle/Main/NodePrinter.swift b/Sources/Demangle/Main/NodePrinter.swift index 5ab8c8dc..e2387dab 100644 --- a/Sources/Demangle/Main/NodePrinter.swift +++ b/Sources/Demangle/Main/NodePrinter.swift @@ -1822,6 +1822,7 @@ package struct NodePrinter: Sendable { private mutating func printBoundGenericNoSugar(_ name: Node) { guard let typeList = name.children.at(1) else { return } printFirstChild(name) + guard !options.contains(.removeBoundGeneric) else { return } printChildren(typeList, prefix: "<", suffix: ">", separator: ", ") } @@ -1858,7 +1859,6 @@ package struct NodePrinter: Sendable { } private mutating func printBoundGeneric(_ name: Node) { - guard !options.contains(.removeBoundGeneric) else { return } guard name.children.count >= 2 else { return } guard name.children.count == 2, options.contains(.synthesizeSugarOnTypes), name.kind != .boundGenericClass else { printBoundGenericNoSugar(name) diff --git a/Sources/Demangle/Node/Node+Collection.swift b/Sources/Demangle/Node/Node+Collection.swift index cb58d615..333f6402 100644 --- a/Sources/Demangle/Node/Node+Collection.swift +++ b/Sources/Demangle/Node/Node+Collection.swift @@ -1,135 +1,24 @@ // MARK: - Collection Support -extension Node: Collection { - public typealias Element = Node - - public struct Index: Comparable { - fileprivate let path: [Int] - fileprivate let traversalOrder: TraversalOrder - - fileprivate init(path: [Int], traversalOrder: TraversalOrder) { - self.path = path - self.traversalOrder = traversalOrder - } - - public static func < (lhs: Index, rhs: Index) -> Bool { - // Compare based on the actual traversal order - return lhs.path.lexicographicallyPrecedes(rhs.path) - } - } - - public enum TraversalOrder { - case preorder - case inorder - case postorder - case levelorder - } - - public var startIndex: Index { - Index(path: [], traversalOrder: .preorder) - } - - public var endIndex: Index { - Index(path: [-1], traversalOrder: .preorder) - } - - public subscript(position: Index) -> Node { - return nodeAt(path: position.path, traversalOrder: position.traversalOrder) - } - - public func index(after i: Index) -> Index { - let nextPath = nextPath(from: i.path, traversalOrder: i.traversalOrder) - return Index(path: nextPath, traversalOrder: i.traversalOrder) - } - +extension Node { // MARK: - Traversal Methods - public func preorderTraversal() -> PreorderSequence { + public func preorder() -> PreorderSequence { PreorderSequence(root: self) } - public func inorderTraversal() -> InorderSequence { + public func inorder() -> InorderSequence { InorderSequence(root: self) } - public func postorderTraversal() -> PostorderSequence { + public func postorder() -> PostorderSequence { PostorderSequence(root: self) } - public func levelorderTraversal() -> LevelorderSequence { + public func levelorder() -> LevelorderSequence { LevelorderSequence(root: self) } - // MARK: - Private Helper Methods - - private func nodeAt(path: [Int], traversalOrder: TraversalOrder) -> Node { - if path.isEmpty { - return self - } - - var current = self - for index in path { - guard index >= 0 && index < current.children.count else { - fatalError("Invalid path") - } - current = current.children[index] - } - return current - } - - private func nextPath(from currentPath: [Int], traversalOrder: TraversalOrder) -> [Int] { - switch traversalOrder { - case .preorder: - return nextPreorderPath(from: currentPath) - case .inorder: - return nextInorderPath(from: currentPath) - case .postorder: - return nextPostorderPath(from: currentPath) - case .levelorder: - return nextLevelorderPath(from: currentPath) - } - } - - private func nextPreorderPath(from path: [Int]) -> [Int] { - if path == [-1] { return [-1] } // End index - - let currentNode = nodeAt(path: path, traversalOrder: .preorder) - - // If current node has children, go to first child - if !currentNode.children.isEmpty { - return path + [0] - } - - // Otherwise, find next sibling or ancestor's sibling - var workingPath = path - while !workingPath.isEmpty { - let lastIndex = workingPath.removeLast() - let parentNode = workingPath.isEmpty ? self : nodeAt(path: workingPath, traversalOrder: .preorder) - - if lastIndex + 1 < parentNode.children.count { - return workingPath + [lastIndex + 1] - } - } - - return [-1] // End of traversal - } - - private func nextInorderPath(from path: [Int]) -> [Int] { - // Simplified inorder implementation - // For a more complete implementation, you'd need to track state - return nextPreorderPath(from: path) - } - - private func nextPostorderPath(from path: [Int]) -> [Int] { - // Simplified postorder implementation - return nextPreorderPath(from: path) - } - - private func nextLevelorderPath(from path: [Int]) -> [Int] { - // Simplified level-order implementation - return nextPreorderPath(from: path) - } - // MARK: - Sequence Types for Different Traversals public struct PreorderSequence: Sequence { diff --git a/Sources/MachOCaches/MachOCache.swift b/Sources/MachOCaches/MachOCache.swift new file mode 100644 index 00000000..cb0fa48f --- /dev/null +++ b/Sources/MachOCaches/MachOCache.swift @@ -0,0 +1,22 @@ +import Foundation +import MachOKit +import Utilities + +open class MachOCache { + private let memoryPressureMonitor = MemoryPressureMonitor() + + private init() { + memoryPressureMonitor.memoryWarningHandler = { [weak self] in + self?.cacheEntryByIdentifier.removeAll() + } + + memoryPressureMonitor.memoryCriticalHandler = { [weak self] in + self?.cacheEntryByIdentifier.removeAll() + } + + memoryPressureMonitor.startMonitoring() + } + + private var cacheEntryByIdentifier: [AnyHashable: Entry] = [:] + +} diff --git a/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift b/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift index ef00a5ad..34051c31 100644 --- a/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift +++ b/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift @@ -7,20 +7,6 @@ import MachOMacro package class PrimitiveTypeMapping { private var storage: [String: String] = [:] - package func dump() { - for (name, type) in storage { - print("\(name) ---> \(type)") - } - } - - package func hasPrimitiveType(for name: String) -> Bool { - return storage[name] != nil - } - - package func primitiveType(for name: String) -> String? { - return storage[name] - } - @MachOImageGenerator package init(machO: MachOFile) throws { let builtinTypes = try machO.swift.builtinTypeDescriptors.map { try BuiltinType(descriptor: $0, in: machO) } @@ -38,12 +24,12 @@ package class PrimitiveTypeMapping { guard let descriptor = try RelativeDirectPointer(relativeOffset: relativeReference.relativeOffset).resolve(from: descriptorLookup.offset, in: machO).namedContextDescriptor else { continue } let name = try descriptor.name(in: machO) let mangledName = try descriptor.mangledName(in: machO) - let endOffset = mangledName.endOffset + let endOffset = mangledName.endOffset let primitiveName = try machO.readString(offset: endOffset) if let firstChar = primitiveName.first, firstChar == "N" { storage[name] = String(primitiveName.dropFirst()) } - + case .indirect: continue } @@ -55,4 +41,18 @@ package class PrimitiveTypeMapping { } } } + + package func hasPrimitiveType(for name: String) -> Bool { + return storage[name] != nil + } + + package func primitiveType(for name: String) -> String? { + return storage[name] + } + + package func dump() { + for (name, type) in storage { + print("\(name) ---> \(type)") + } + } } diff --git a/Sources/SwiftDump/Dumpable.swift b/Sources/SwiftDump/Dumpable.swift deleted file mode 100644 index c1ecb7e4..00000000 --- a/Sources/SwiftDump/Dumpable.swift +++ /dev/null @@ -1,22 +0,0 @@ -import Demangle -import MachOKit -import Semantic - -public typealias DemangleOptions = Demangle.DemangleOptions - -public protocol Dumpable { - func dump(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dump(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString -} - -public protocol NamedDumpable: Dumpable { - func dumpName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dumpName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString -} - -public protocol ConformedDumpable: Dumpable { - func dumpTypeName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dumpProtocolName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dumpTypeName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString - func dumpProtocolName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString -} diff --git a/Sources/SwiftDump/Dumpable+/AssociatedType+Dumpable.swift b/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift similarity index 100% rename from Sources/SwiftDump/Dumpable+/AssociatedType+Dumpable.swift rename to Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift diff --git a/Sources/SwiftDump/Dumpable+/Class+Dumpable.swift b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift similarity index 97% rename from Sources/SwiftDump/Dumpable+/Class+Dumpable.swift rename to Sources/SwiftDump/Dumpable/Class+Dumpable.swift index 1df5a08c..bf64323f 100644 --- a/Sources/SwiftDump/Dumpable+/Class+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift @@ -206,15 +206,3 @@ extension Class: NamedDumpable { } } } - -extension Node { - var hasWeakNode: Bool { - first { $0.kind == .weak } != nil - } -} - -extension String { - var insertSubFunctionPrefix: String { - "sub_" + self - } -} diff --git a/Sources/SwiftDump/Dumpable+/Enum+Dumpable.swift b/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift similarity index 100% rename from Sources/SwiftDump/Dumpable+/Enum+Dumpable.swift rename to Sources/SwiftDump/Dumpable/Enum+Dumpable.swift diff --git a/Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift similarity index 93% rename from Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift rename to Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift index 5be92f42..63cea045 100644 --- a/Sources/SwiftDump/Dumpable+/Protocol+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift @@ -96,7 +96,7 @@ extension MachOSwiftSection.`Protocol`: NamedDumpable { @MachOImageGenerator private func validNode(for symbols: Symbols, in machOFile: MachOFile, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolNode = node.first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interfaceType, in: machOFile)).string, !visitedNode.contains(node) { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolNode = node.preorder().first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interfaceType, in: machOFile)).string, !visitedNode.contains(node) { return node } } diff --git a/Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift similarity index 90% rename from Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift rename to Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift index 8bf252b4..77be7f2f 100644 --- a/Sources/SwiftDump/Dumpable+/ProtocolConformance+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift @@ -59,11 +59,11 @@ extension ProtocolConformance: ConformedDumpable { Space() let typeName = try dumpTypeName(using: options, in: machOFile) - + typeName - + let interfaceTypeName = try dumpTypeName(using: .interfaceType, in: machOFile).string - + Standard(":") Space() @@ -88,7 +88,7 @@ extension ProtocolConformance: ConformedDumpable { Standard("{") var visitedNodes: OrderedSet = [] - + for resilientWitness in resilientWitnesses { BreakLine() @@ -110,6 +110,8 @@ extension ProtocolConformance: ConformedDumpable { validNode.printSemantic(using: options) } else if !element.defaultImplementation.isNull { FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machOFile).insertSubFunctionPrefix) + } else if !resilientWitness.implementation.isNull { + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) } else { Error("Symbol not found") } @@ -126,11 +128,11 @@ extension ProtocolConformance: ConformedDumpable { Standard("}") } } - + @MachOImageGenerator private func validNode(for symbols: Symbols, in machOFile: MachOFile, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.first(where: { $0.kind == .protocolConformance }), protocolConformanceNode.children.at(0)?.print(using: .interfaceType) == typeName { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { return node } } @@ -138,17 +140,4 @@ extension ProtocolConformance: ConformedDumpable { } } -extension SemanticString { - func replacingTypeNameOrOtherToTypeDeclaration() -> SemanticString { - replacing { - switch $0 { - case .type(let type, .name): - return .type(type, .declaration) - case .other: - return .type(.other, .declaration) - default: - return $0 - } - } - } -} + diff --git a/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift new file mode 100644 index 00000000..2d9ce347 --- /dev/null +++ b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift @@ -0,0 +1,9 @@ +import MachOKit +import Semantic + +public protocol ConformedDumpable: Dumpable { + func dumpTypeName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString + func dumpProtocolName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString + func dumpTypeName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString + func dumpProtocolName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString +} diff --git a/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift new file mode 100644 index 00000000..dd85f373 --- /dev/null +++ b/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift @@ -0,0 +1,14 @@ +import Demangle +import MachOKit +import Semantic + +public typealias DemangleOptions = Demangle.DemangleOptions + +public protocol Dumpable { + func dump(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString + func dump(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString +} + + + + diff --git a/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift new file mode 100644 index 00000000..3b4a637a --- /dev/null +++ b/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift @@ -0,0 +1,7 @@ +import MachOKit +import Semantic + +public protocol NamedDumpable: Dumpable { + func dumpName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString + func dumpName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString +} diff --git a/Sources/SwiftDump/Dumpable+/Struct+Dumpable.swift b/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift similarity index 100% rename from Sources/SwiftDump/Dumpable+/Struct+Dumpable.swift rename to Sources/SwiftDump/Dumpable/Struct+Dumpable.swift diff --git a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift b/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift new file mode 100644 index 00000000..45d71a2a --- /dev/null +++ b/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift @@ -0,0 +1,150 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import MachOMacro +import MachOFoundation +import Semantic +import Demangle +import Utilities +import OrderedCollections + +struct ProtocolConformanceDumper: ConformedDumper { + let protocolConformance: ProtocolConformance + + let options: DemangleOptions + + let machOFile: MachOFile + + var typeNameOptions: DemangleOptions { .interfaceType } + + var body: SemanticString { + get throws { + Keyword(.extension) + + Space() + + let typeName = try self.typeName + + let typeNameString = typeName.string + + typeName + + Standard(":") + + Space() + + try protocolName + + if !protocolConformance.conditionalRequirements.isEmpty { + Space() + Keyword(.where) + Space() + } + + for conditionalRequirement in protocolConformance.conditionalRequirements { + try conditionalRequirement.dump(using: options, in: machOFile) + } + + if protocolConformance.resilientWitnesses.isEmpty { + Space() + Standard("{}") + } else { + Space() + Standard("{") + + var visitedNodes: OrderedSet = [] + + for resilientWitness in protocolConformance.resilientWitnesses { + BreakLine() + + Indent(level: 1) + + if let symbols = try resilientWitness.implementationSymbols(in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: typeNameString, visitedNode: visitedNodes) { + _ = visitedNodes.append(validNode) + validNode.printSemantic(using: options) + } else if let requirement = try resilientWitness.requirement(in: machOFile) { + switch requirement { + case .symbol(let symbol): + try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + case .element(let element): + if let symbols = try Symbols.resolve(from: element.offset, in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: typeNameString, visitedNode: visitedNodes) { + _ = visitedNodes.append(validNode) + validNode.printSemantic(using: options) + } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machOFile), let validNode = try validNode(for: defaultImplementationSymbols, in: machOFile, typeName: typeNameString, visitedNode: visitedNodes) { + _ = visitedNodes.append(validNode) + validNode.printSemantic(using: options) + } else if !element.defaultImplementation.isNull { + FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machOFile).insertSubFunctionPrefix) + } else if !resilientWitness.implementation.isNull { + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + } else { + Error("Symbol not found") + } + } + } else if !resilientWitness.implementation.isNull { + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + } else { + Error("Symbol not found") + } + } + + BreakLine() + + Standard("}") + } + } + } + + @SemanticStringBuilder + var typeName: SemanticString { + get throws { + switch protocolConformance.typeReference { + case .directTypeDescriptor(let descriptor): + try descriptor?.dumpName(using: typeNameOptions, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() + case .indirectTypeDescriptor(let descriptor): + switch descriptor { + case .symbol(let unsolvedSymbol): + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + case .element(let element): + try element.dumpName(using: typeNameOptions, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() + case nil: + Standard("") + } + case .directObjCClassName(let objcClassName): + TypeDeclaration(kind: .class, objcClassName.valueOrEmpty) + case .indirectObjCClass(let objcClass): + switch objcClass { + case .symbol(let unsolvedSymbol): + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + case .element(let element): + try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machOFile))), in: machOFile).printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + case nil: + Standard("") + } + } + } + } + + @SemanticStringBuilder + var protocolName: SemanticString { + get throws { + switch protocolConformance.`protocol` { + case .symbol(let unsolvedSymbol): + try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) + case .element(let element): + try MetadataReader.demangleContext(for: .protocol(element), in: machOFile).printSemantic(using: options) + case .none: + Standard("") + } + } + } + + private func validNode(for symbols: Symbols, in machOFile: MachOFile, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { + for symbol in symbols { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { + return node + } + } + return nil + } +} diff --git a/Sources/SwiftDump/Dumper/Protocols/ConformedDumper.swift b/Sources/SwiftDump/Dumper/Protocols/ConformedDumper.swift new file mode 100644 index 00000000..56cc8a9d --- /dev/null +++ b/Sources/SwiftDump/Dumper/Protocols/ConformedDumper.swift @@ -0,0 +1,6 @@ +import Semantic + +protocol ConformedDumper: Dumper { + @SemanticStringBuilder var typeName: SemanticString { get throws } + @SemanticStringBuilder var protocolName: SemanticString { get throws } +} diff --git a/Sources/SwiftDump/Dumper/Protocols/Dumper.swift b/Sources/SwiftDump/Dumper/Protocols/Dumper.swift new file mode 100644 index 00000000..be7713c9 --- /dev/null +++ b/Sources/SwiftDump/Dumper/Protocols/Dumper.swift @@ -0,0 +1,5 @@ +import Semantic + +protocol Dumper { + @SemanticStringBuilder var body: SemanticString { get throws } +} diff --git a/Sources/SwiftDump/Extensions/Node+SemanticString.swift b/Sources/SwiftDump/Extensions/Node+.swift similarity index 92% rename from Sources/SwiftDump/Extensions/Node+SemanticString.swift rename to Sources/SwiftDump/Extensions/Node+.swift index 27314d13..83769b38 100644 --- a/Sources/SwiftDump/Extensions/Node+SemanticString.swift +++ b/Sources/SwiftDump/Extensions/Node+.swift @@ -38,3 +38,9 @@ extension Node { return printer.printRoot(self) } } + +extension Node { + var hasWeakNode: Bool { + preorder().first { $0.kind == .weak } != nil + } +} diff --git a/Sources/SwiftDump/Extensions/SemanticString+.swift b/Sources/SwiftDump/Extensions/SemanticString+.swift new file mode 100644 index 00000000..fd7dbeda --- /dev/null +++ b/Sources/SwiftDump/Extensions/SemanticString+.swift @@ -0,0 +1,16 @@ +import Semantic + +extension SemanticString { + func replacingTypeNameOrOtherToTypeDeclaration() -> SemanticString { + replacing { + switch $0 { + case .type(let type, .name): + return .type(type, .declaration) + case .other: + return .type(.other, .declaration) + default: + return $0 + } + } + } +} diff --git a/Sources/SwiftDump/Extensions/String+.swift b/Sources/SwiftDump/Extensions/String+.swift index 45ab25ef..8d93f50a 100644 --- a/Sources/SwiftDump/Extensions/String+.swift +++ b/Sources/SwiftDump/Extensions/String+.swift @@ -30,3 +30,9 @@ extension String? { self ?? "" } } + +extension String { + var insertSubFunctionPrefix: String { + "sub_" + self + } +} From 55f25930dd01a8f8aa88ccf3e89b184d5387a3b7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 3 Jul 2025 16:12:48 +0800 Subject: [PATCH 3/8] Generic refactoring --- Sources/MachOExtensions/MachOFile+.swift | 18 +-- .../MachORepresentableWithCache.swift | 26 +++- Sources/MachOPointer/Pointer.swift | 6 +- .../Protocol/PointerProtocol.swift | 36 ++---- .../RelativeDirectPointerProtocol.swift | 21 +-- .../RelativeIndirectPointerProtocol.swift | 28 ++-- .../Protocol/RelativeIndirectType.swift | 10 +- ...veIndirectablePointerIntPairProtocol.swift | 9 +- .../RelativeIndirectablePointerProtocol.swift | 30 ++--- .../Protocol/RelativePointerProtocol.swift | 6 +- .../Reading/MachOFile+Reading.swift | 14 +- .../Reading/MachOImage+Reading.swift | 14 +- .../MachOReading/Reading/MachOReadable.swift | 2 +- Sources/MachOReading/Resolvable.swift | 36 ++---- .../MachOSwiftSection/MachOFile+Swift.swift | 4 +- .../MachOSwiftSection/MachOImage+Swift.swift | 4 +- .../Models/Anonymous/AnonymousContext.swift | 3 +- .../AnonymousContextDescriptorProtocol.swift | 4 +- .../AssociatedType/AssociatedType.swift | 5 +- .../AssociatedTypeDescriptor.swift | 17 +-- .../AssociatedType/AssociatedTypeRecord.swift | 13 +- .../Models/BuiltinType/BuiltinType.swift | 4 +- .../BuiltinType/BuiltinTypeDescriptor.swift | 3 +- .../ContextDescriptorProtocol.swift | 17 +-- .../ContextDescriptorWrapper.swift | 66 +++++----- .../NamedContextDescriptorProtocol.swift | 9 +- .../ExtendedExistentialTypeShape.swift | 5 +- ...onUniqueExtendedExistentialTypeShape.swift | 5 +- .../Models/Extension/ExtensionContext.swift | 8 +- .../ExtensionContextDescriptor.swift | 5 +- .../FieldDescriptor/FieldDescriptor.swift | 9 +- .../Models/FieldRecord/FieldRecord.swift | 9 +- .../Models/Generic/GenericContext.swift | 29 ++--- .../Models/Generic/GenericRequirement.swift | 8 +- .../GenericRequirementDescriptor.swift | 22 ++-- .../Models/Mangling/MangledName.swift | 9 +- .../Models/OpaqueType/OpaqueType.swift | 11 +- .../Protocol/ObjC/ObjCProtocolPrefix.swift | 11 +- .../ObjC/RelativeObjCProtocolPrefix.swift | 5 +- .../Models/Protocol/Protocol.swift | 10 +- .../Models/Protocol/ProtocolDescriptor.swift | 5 +- .../Protocol/ProtocolDescriptorRef.swift | 17 +-- .../Models/Protocol/ProtocolRequirement.swift | 5 +- .../Models/Protocol/ResilientWitness.swift | 10 +- .../ProtocolConformance.swift | 25 ++-- .../ProtocolConformanceDescriptor.swift | 13 +- .../Models/Type/Class/Class.swift | 37 +++--- .../Models/Type/Class/ClassDescriptor.swift | 5 +- .../Metadata/ClassMetadataObjCInterop.swift | 7 +- .../MethodDefaultOverrideDescriptor.swift | 12 +- .../Type/Class/Method/MethodDescriptor.swift | 6 +- .../Method/MethodOverrideDescriptor.swift | 18 ++- .../Models/Type/Enum/Enum.swift | 19 ++- .../Models/Type/Struct/Struct.swift | 19 ++- .../Models/Type/Struct/StructMetadata.swift | 7 +- .../Models/Type/TypeContextDescriptor.swift | 14 +- .../Type/TypeContextDescriptorProtocol.swift | 34 +++-- .../Models/Type/TypeReference.swift | 11 +- .../RelativeProtocolDescriptorPointer.swift | 13 +- .../Pointer/SymbolOrElementPointer.swift | 63 +++------ ...hOSwiftSectionRepresentableWithCache.swift | 2 +- .../Utils/MetadataReader.swift | 121 +++++++++--------- .../Utils/PrimitiveTypeMapping.swift | 3 +- Sources/MachOSymbols/MachO+Symbol.swift | 8 +- Sources/MachOSymbols/Symbol.swift | 10 +- Sources/MachOSymbols/SymbolOrElement.swift | 20 +-- Sources/MachOSymbols/Symbols.swift | 10 +- Tests/SwiftDumpTests/DyldCacheDumpTests.swift | 2 +- 68 files changed, 455 insertions(+), 612 deletions(-) diff --git a/Sources/MachOExtensions/MachOFile+.swift b/Sources/MachOExtensions/MachOFile+.swift index e0bb1065..1beaca19 100644 --- a/Sources/MachOExtensions/MachOFile+.swift +++ b/Sources/MachOExtensions/MachOFile+.swift @@ -3,7 +3,7 @@ import MachOKit import AssociatedObject extension MachOFile { - package var cache: DyldCache? { + public var cache: DyldCache? { guard isLoadedFromDyldCache else { return nil } if let _cache { return _cache @@ -26,14 +26,14 @@ extension MachOFile { @AssociatedObject(.retain(.nonatomic)) private var _cache: DyldCache? - package func cache(for address: UInt64) -> DyldCache? { + public func cache(for address: UInt64) -> DyldCache? { cacheAndFileOffset(for: address)?.0 } /// Convert an address that is not slided into the actual cache it contains and the file offset in it. /// - Parameter address: address (unslid) /// - Returns: cache and file offset - package func cacheAndFileOffset(for address: UInt64) -> (DyldCache, UInt64)? { + public func cacheAndFileOffset(for address: UInt64) -> (DyldCache, UInt64)? { guard let cache else { return nil } if let offset = cache.fileOffset(of: address) { return (cache, offset) @@ -64,7 +64,7 @@ extension MachOFile { /// it contains and the file offset within that cache. /// - Parameter offset: Offset from the start of the main cache. /// - Returns: cache and file offset - package func cacheAndFileOffset(fromStart offset: UInt64) -> (DyldCache, UInt64)? { + public func cacheAndFileOffset(fromStart offset: UInt64) -> (DyldCache, UInt64)? { guard let cache else { return nil } return cacheAndFileOffset( for: cache.mainCacheHeader.sharedRegionStart + offset @@ -82,7 +82,7 @@ extension MachOFile { /// - machO: The `MachOFile` object representing the MachO file to resolve rebases from. /// - Returns: The resolved rebase value as a `UInt64`, or `nil` if the rebase cannot be resolved. - package func resolveRebase(fileOffset: Int) -> UInt64? { + public func resolveRebase(fileOffset: Int) -> UInt64? { let offset: UInt64 = numericCast(fileOffset) if let (cache, _offset) = resolveCacheStartOffsetIfNeeded(offset: offset), let resolved = cache.resolveOptionalRebase(at: _offset) { @@ -116,7 +116,7 @@ extension MachOFile { /// - machO: The `MachOFile` object representing the MachO file to analyze. /// - Returns: The resolved symbol name as a `String`, or `nil` if the bind operation cannot be resolved. - package func resolveBind(fileOffset: Int) -> String? { + public func resolveBind(fileOffset: Int) -> String? { guard !isLoadedFromDyldCache else { return nil } guard let fixup = dyldChainedFixups else { return nil } @@ -144,17 +144,17 @@ extension MachOFile { /// - machO: The `MachOFile` instance representing the file being analyzed. /// - Returns: A `Bool` indicating whether the specified offset represents a bind operation. - package func isBind(fileOffset: Int) -> Bool { + public func isBind(fileOffset: Int) -> Bool { guard !isLoadedFromDyldCache else { return false } let offset: UInt64 = numericCast(fileOffset) return isBind(numericCast(offset)) } - package func isBind(_ offset: Int) -> Bool { + public func isBind(_ offset: Int) -> Bool { resolveBind(at: numericCast(offset)) != nil } - package func resolveCacheStartOffsetIfNeeded( + public func resolveCacheStartOffsetIfNeeded( offset: UInt64) -> (DyldCache, UInt64)? { if let (cache, _offset) = cacheAndFileOffset( fromStart: offset diff --git a/Sources/MachOExtensions/MachORepresentableWithCache.swift b/Sources/MachOExtensions/MachORepresentableWithCache.swift index 79abee6b..d1748dce 100644 --- a/Sources/MachOExtensions/MachORepresentableWithCache.swift +++ b/Sources/MachOExtensions/MachORepresentableWithCache.swift @@ -1,25 +1,37 @@ import MachOKit -package protocol MachORepresentableWithCache: MachORepresentable { +public protocol MachORepresentableWithCache: MachORepresentable { associatedtype Cache: DyldCacheRepresentable associatedtype Identifier: Hashable var identifier: Identifier { get } var cache: Cache? { get } var startOffset: Int { get } + func resolveOffset(at address: UInt64) -> Int } -package enum MachOTargetIdentifier: Hashable { +public enum MachOTargetIdentifier: Hashable { case image(UnsafeRawPointer) case file(String) } +extension MachOFile { + public func resolveOffset(at address: UInt64) -> Int { + numericCast(fileOffset(of: address)) + } +} + +extension MachOImage { + public func resolveOffset(at address: UInt64) -> Int { + Int(address) - ptr.int + } +} extension MachOFile: MachORepresentableWithCache { - package var identifier: MachOTargetIdentifier { + public var identifier: MachOTargetIdentifier { .file(imagePath) } - package var startOffset: Int { + public var startOffset: Int { if let cache { headerStartOffsetInCache + cache.fileStartOffset.cast() } else { @@ -29,11 +41,11 @@ extension MachOFile: MachORepresentableWithCache { } extension MachOImage: MachORepresentableWithCache { - package var identifier: MachOTargetIdentifier { + public var identifier: MachOTargetIdentifier { .image(ptr) } - package var cache: DyldCacheLoaded? { + public var cache: DyldCacheLoaded? { guard let currentCache = DyldCacheLoaded.current else { return nil } if ptr.int - currentCache.mainCacheHeader.sharedRegionStart.cast() >= 0 { @@ -42,7 +54,7 @@ extension MachOImage: MachORepresentableWithCache { return nil } - package var startOffset: Int { + public var startOffset: Int { if let cache { return cache.mainCacheHeader.sharedRegionStart.cast() } else { diff --git a/Sources/MachOPointer/Pointer.swift b/Sources/MachOPointer/Pointer.swift index b25e1874..c6c89e5d 100644 --- a/Sources/MachOPointer/Pointer.swift +++ b/Sources/MachOPointer/Pointer.swift @@ -7,11 +7,11 @@ public struct Pointer: RelativeIndirectType, PointerProtoco public let address: UInt64 - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - if let rebase = machOFile.resolveRebase(fileOffset: fileOffset.cast()) { + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + if let machOFile = machO as? MachOFile, let rebase = machOFile.resolveRebase(fileOffset: fileOffset.cast()) { return .init(address: rebase) } else { - return try machOFile.readElement(offset: fileOffset) + return try machO.readElement(offset: fileOffset) } } diff --git a/Sources/MachOPointer/Protocol/PointerProtocol.swift b/Sources/MachOPointer/Protocol/PointerProtocol.swift index 87e22597..bb256ca7 100644 --- a/Sources/MachOPointer/Protocol/PointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/PointerProtocol.swift @@ -8,46 +8,28 @@ public protocol PointerProtocol: Resolvable, Sendable { var address: UInt64 { get } - func resolve(in machOFile: MachOFile) throws -> Pointee - func resolveAny(in machOFile: MachOFile) throws -> T - func resolveOffset(in machOFile: MachOFile) -> Int - - func resolve(in machOImage: MachOImage) throws -> Pointee - func resolveAny(in machOImage: MachOImage) throws -> T - func resolveOffset(in machOImage: MachOImage) -> Int + func resolve(in machO: MachO) throws -> Pointee + func resolveAny(in machO: MachO) throws -> T + func resolveOffset(in machO: MachO) -> Int } -@MachOImageAllMembersGenerator extension PointerProtocol { - public func resolveAny(in machOFile: MachOFile) throws -> T { + public func resolveAny(in machOFile: MachO) throws -> T { return try T.resolve(from: resolveOffset(in: machOFile), in: machOFile) } - public func resolve(in machOFile: MachOFile) throws -> Pointee { + public func resolve(in machOFile: MachO) throws -> Pointee { return try Pointee.resolve(from: resolveOffset(in: machOFile), in: machOFile) } -} - -extension PointerProtocol { - public func resolveOffset(in machOFile: MachOFile) -> Int { - numericCast(machOFile.fileOffset(of: address)) - } - public func resolveOffset(in machOImage: MachOImage) -> Int { - Int(address) - machOImage.ptr.int - } -} - -extension PointerProtocol where Pointee: OptionalProtocol { - func resolve(in machOFile: MachOFile) throws -> Pointee { - guard address != 0 else { return nil } - return try Pointee.resolve(from: resolveOffset(in: machOFile), in: machOFile) + public func resolveOffset(in machO: MachO) -> Int { + machO.resolveOffset(at: address) } } extension PointerProtocol where Pointee: OptionalProtocol { - func resolve(in machOImage: MachOImage) throws -> Pointee { + public func resolve(in machO: MachO) throws -> Pointee { guard address != 0 else { return nil } - return try Pointee.resolve(from: resolveOffset(in: machOImage), in: machOImage) + return try Pointee.resolve(from: resolveOffset(in: machO), in: machO) } } diff --git a/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift index 9390ef54..15f3e7f2 100644 --- a/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift @@ -5,35 +5,28 @@ import MachOExtensions public protocol RelativeDirectPointerProtocol: RelativePointerProtocol {} -@MachOImageAllMembersGenerator + extension RelativeDirectPointerProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { return try resolveDirect(from: fileOffset, in: machOFile) } - func resolveDirect(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + func resolveDirect(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { return try Pointee.resolve(from: resolveDirectOffset(from: fileOffset), in: machOFile) } - public func resolveAny(from fileOffset: Int, in machOFile: MachOFile) throws -> T { - return try resolveDirect(from: fileOffset, in: machOFile) + public func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T { + return try resolveDirectAny(from: fileOffset, in: machOFile) } - func resolveDirect(from fileOffset: Int, in machOFile: MachOFile) throws -> T { + func resolveDirectAny(from fileOffset: Int, in machOFile: MachO) throws -> T { return try T.resolve(from: resolveDirectOffset(from: fileOffset), in: machOFile) } } extension RelativeDirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { guard isValid else { return nil } return try resolve(from: fileOffset, in: machOFile) } } - -extension RelativeDirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> Pointee { - guard isValid else { return nil } - return try resolve(from: imageOffset, in: machOImage) - } -} diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift index 73135219..8dc6bd07 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift @@ -6,47 +6,37 @@ import MachOExtensions public protocol RelativeIndirectPointerProtocol: RelativePointerProtocol { associatedtype IndirectType: RelativeIndirectType where IndirectType.Resolved == Pointee - func resolveIndirectOffset(from fileOffset: Int, in machOFile: MachOFile) throws -> Int - - func resolveIndirectOffset(from imageOffset: Int, in machOImage: MachOImage) throws -> Int + func resolveIndirectOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int } -@MachOImageAllMembersGenerator extension RelativeIndirectPointerProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { return try resolveIndirect(from: fileOffset, in: machOFile) } - func resolveIndirect(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + func resolveIndirect(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { return try resolveIndirectType(from: fileOffset, in: machOFile).resolve(in: machOFile) } - public func resolveAny(from fileOffset: Int, in machOFile: MachOFile) throws -> T { - return try resolveIndirect(from: fileOffset, in: machOFile) + public func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T { + return try resolveIndirectAny(from: fileOffset, in: machOFile) } - func resolveIndirect(from fileOffset: Int, in machOFile: MachOFile) throws -> T { + func resolveIndirectAny(from fileOffset: Int, in machOFile: MachO) throws -> T { return try resolveIndirectType(from: fileOffset, in: machOFile).resolveAny(in: machOFile) } - public func resolveIndirectType(from fileOffset: Int, in machOFile: MachOFile) throws -> IndirectType { + public func resolveIndirectType(from fileOffset: Int, in machOFile: MachO) throws -> IndirectType { return try .resolve(from: resolveDirectOffset(from: fileOffset), in: machOFile) } - public func resolveIndirectOffset(from fileOffset: Int, in machOFile: MachOFile) throws -> Int { + public func resolveIndirectOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int { return try resolveIndirectType(from: fileOffset, in: machOFile).resolveOffset(in: machOFile) } } extension RelativeIndirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { - guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) - } -} - -extension RelativeIndirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOImage) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { guard isValid else { return nil } return try resolve(from: fileOffset, in: machOFile) } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectType.swift b/Sources/MachOPointer/Protocol/RelativeIndirectType.swift index 828098b9..10e4cc24 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectType.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectType.swift @@ -5,11 +5,7 @@ import MachOExtensions public protocol RelativeIndirectType: Resolvable { associatedtype Resolved: Resolvable - func resolve(in machOFile: MachOFile) throws -> Resolved - func resolveAny(in machOFile: MachOFile) throws -> T - func resolveOffset(in machOFile: MachOFile) -> Int - - func resolve(in machOImage: MachOImage) throws -> Resolved - func resolveAny(in machOImage: MachOImage) throws -> T - func resolveOffset(in machOImage: MachOImage) -> Int + func resolve(in machOFile: MachO) throws -> Resolved + func resolveAny(in machOFile: MachO) throws -> T + func resolveOffset(in machOFile: MachO) -> Int } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift index 9d85106b..f9f5e1a5 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift @@ -36,14 +36,7 @@ extension RelativeIndirectablePointerIntPairProtocol { } extension RelativeIndirectablePointerIntPairProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { - guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) - } -} - -extension RelativeIndirectablePointerIntPairProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOImage) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { guard isValid else { return nil } return try resolve(from: fileOffset, in: machOFile) } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift index 5344ac3f..160c33b4 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift @@ -6,8 +6,7 @@ import MachOExtensions public protocol RelativeIndirectablePointerProtocol: RelativeDirectPointerProtocol, RelativeIndirectPointerProtocol { var relativeOffsetPlusIndirect: Offset { get } var isIndirect: Bool { get } - func resolveIndirectableOffset(from fileOffset: Int, in machOFile: MachOFile) throws -> Int - func resolveIndirectableOffset(from imageOffset: Int, in machOFile: MachOImage) throws -> Int + func resolveIndirectableOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int } extension RelativeIndirectablePointerProtocol { @@ -20,17 +19,16 @@ extension RelativeIndirectablePointerProtocol { } } -@MachOImageAllMembersGenerator extension RelativeIndirectablePointerProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { return try resolveIndirectable(from: fileOffset, in: machOFile) } - public func resolveAny(from fileOffset: Int, in machOFile: MachOFile) throws -> T { + public func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T { return try resolveIndirectableAny(from: fileOffset, in: machOFile) } - func resolveIndirectable(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + func resolveIndirectable(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { if isIndirect { return try resolveIndirect(from: fileOffset, in: machOFile) } else { @@ -38,36 +36,28 @@ extension RelativeIndirectablePointerProtocol { } } - public func resolveIndirectableType(from fileOffset: Int, in machOFile: MachOFile) throws -> IndirectType? { + public func resolveIndirectableType(from fileOffset: Int, in machOFile: MachO) throws -> IndirectType? { guard isIndirect else { return nil } return try resolveIndirectableType(from: fileOffset, in: machOFile) } - func resolveIndirectableAny(from fileOffset: Int, in machOFile: MachOFile) throws -> T { + func resolveIndirectableAny(from fileOffset: Int, in machOFile: MachO) throws -> T { if isIndirect { - return try resolveIndirect(from: fileOffset, in: machOFile) + return try resolveIndirectAny(from: fileOffset, in: machOFile) } else { - return try resolveDirect(from: fileOffset, in: machOFile) + return try resolveDirectAny(from: fileOffset, in: machOFile) } } - public func resolveIndirectableOffset(from fileOffset: Int, in machOFile: MachOFile) throws -> Int { + public func resolveIndirectableOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int { guard let indirectType = try resolveIndirectableType(from: fileOffset, in: machOFile) else { return resolveDirectOffset(from: fileOffset) } return indirectType.resolveOffset(in: machOFile) } } extension RelativeIndirectablePointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee { + public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { guard isValid else { return nil } return try resolve(from: fileOffset, in: machOFile) } } - -extension RelativeIndirectablePointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachOImage) throws -> Pointee { - guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) - } -} - diff --git a/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift index 90e5adad..7980c702 100644 --- a/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift @@ -8,11 +8,9 @@ public protocol RelativePointerProtocol: Sendable { var relativeOffset: Offset { get } - func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Pointee - func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> Pointee + func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee - func resolveAny(from fileOffset: Int, in machOFile: MachOFile) throws -> T - func resolveAny(from imageOffset: Int, in machOImage: MachOImage) throws -> T + func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T func resolveDirectOffset(from offset: Int) -> Int } diff --git a/Sources/MachOReading/Reading/MachOFile+Reading.swift b/Sources/MachOReading/Reading/MachOFile+Reading.swift index e8060468..0e70c6e1 100644 --- a/Sources/MachOReading/Reading/MachOFile+Reading.swift +++ b/Sources/MachOReading/Reading/MachOFile+Reading.swift @@ -33,7 +33,7 @@ extension MachOFile { } extension MachOFile: MachOReadable { - package func readElement( + public func readElement( offset: Int ) throws -> Element { let originalOffset = offset @@ -46,13 +46,13 @@ extension MachOFile: MachOReadable { return try fileIO.machO.read(offset: numericCast(offset + headerStartOffset)) } - package func readElement( + public func readElement( offset: Int ) throws -> Element where Element: LocatableLayoutWrapper { return try readWrapperElement(offset: offset) } - package func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper { + public func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper { let originalOffset = offset var offset = originalOffset var fileIO = fileIO @@ -64,7 +64,7 @@ extension MachOFile: MachOReadable { return .init(layout: layout, offset: originalOffset) } - package func readElements( + public func readElements( offset: Int, numberOfElements: Int ) throws -> [Element] { @@ -83,14 +83,14 @@ extension MachOFile: MachOReadable { return elements } - package func readElements( + public func readElements( offset: Int, numberOfElements: Int ) throws -> [Element] where Element: LocatableLayoutWrapper { return try readWrapperElements(offset: offset, numberOfElements: numberOfElements) } - package func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { + public func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element: LocatableLayoutWrapper { let originalOffset = offset var offset = originalOffset var fileIO = fileIO @@ -107,7 +107,7 @@ extension MachOFile: MachOReadable { return elements } - package func readString(offset: Int) throws -> String { + public func readString(offset: Int) throws -> String { let originalOffset = offset var offset = originalOffset var fileIO = fileIO diff --git a/Sources/MachOReading/Reading/MachOImage+Reading.swift b/Sources/MachOReading/Reading/MachOImage+Reading.swift index 97d43847..992a559a 100644 --- a/Sources/MachOReading/Reading/MachOImage+Reading.swift +++ b/Sources/MachOReading/Reading/MachOImage+Reading.swift @@ -2,26 +2,26 @@ import MachOKit import MachOExtensions extension MachOImage: MachOReadable { - package func readElement( + public func readElement( offset: Int ) throws -> Element { let pointer = ptr + offset return pointer.assumingMemoryBound(to: Element.self).pointee } - package func readElement( + public func readElement( offset: Int ) throws -> Element where Element: LocatableLayoutWrapper { return try readWrapperElement(offset: offset) } - package func readWrapperElement(offset: Int) throws -> Element where Element : LocatableLayoutWrapper { + public func readWrapperElement(offset: Int) throws -> Element where Element : LocatableLayoutWrapper { let pointer = ptr + offset let layout: Element.Layout = pointer.assumingMemoryBound(to: Element.Layout.self).pointee return .init(layout: layout, offset: offset) } - package func readElements( + public func readElements( offset: Int, numberOfElements: Int ) throws -> [Element] { @@ -29,14 +29,14 @@ extension MachOImage: MachOReadable { return MemorySequence(basePointer: pointer.assumingMemoryBound(to: Element.self), numberOfElements: numberOfElements).map { $0 } } - package func readElements( + public func readElements( offset: Int, numberOfElements: Int ) throws -> [Element] where Element: LocatableLayoutWrapper { return try readWrapperElements(offset: offset, numberOfElements: numberOfElements) } - package func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element : LocatableLayoutWrapper { + public func readWrapperElements(offset: Int, numberOfElements: Int) throws -> [Element] where Element : LocatableLayoutWrapper { let pointer = ptr + offset var currentOffset = offset let elements = MemorySequence(basePointer: pointer.assumingMemoryBound(to: Element.Layout.self), numberOfElements: numberOfElements).map { (layout: Element.Layout) -> Element in @@ -47,7 +47,7 @@ extension MachOImage: MachOReadable { return elements } - package func readString(offset: Int) throws -> String { + public func readString(offset: Int) throws -> String { let pointer = ptr + offset return .init(cString: pointer.assumingMemoryBound(to: CChar.self)) } diff --git a/Sources/MachOReading/Reading/MachOReadable.swift b/Sources/MachOReading/Reading/MachOReadable.swift index 2e3ce6e5..0e086557 100644 --- a/Sources/MachOReading/Reading/MachOReadable.swift +++ b/Sources/MachOReading/Reading/MachOReadable.swift @@ -1,7 +1,7 @@ import MachOKit import MachOExtensions -package protocol MachOReadable { +public protocol MachOReadable { func readElement(offset: Int) throws -> Element func readWrapperElement(offset: Int) throws -> Element where Element: LocatableLayoutWrapper diff --git a/Sources/MachOReading/Resolvable.swift b/Sources/MachOReading/Resolvable.swift index 3120d56e..361ec61a 100644 --- a/Sources/MachOReading/Resolvable.swift +++ b/Sources/MachOReading/Resolvable.swift @@ -3,29 +3,24 @@ import MachOExtensions import MachOMacro public protocol Resolvable { - static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self - static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self? - - static func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> Self - static func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> Self? + static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self + static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? } -@MachOImageAllMembersGenerator extension Resolvable { - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - return try machOFile.readElement(offset: fileOffset) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + return try machO.readElement(offset: fileOffset) } - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self? { - let result: Self = try resolve(from: fileOffset, in: machOFile) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? { + let result: Self = try resolve(from: fileOffset, in: machO) return .some(result) } } -@MachOImageAllMembersGenerator extension Optional: Resolvable where Wrapped: Resolvable { - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - let result: Wrapped? = try Wrapped.resolve(from: fileOffset, in: machOFile) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + let result: Wrapped? = try Wrapped.resolve(from: fileOffset, in: machO) if let result { return .some(result) } else { @@ -34,22 +29,15 @@ extension Optional: Resolvable where Wrapped: Resolvable { } } -@MachOImageAllMembersGenerator extension String: Resolvable { - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - return try machOFile.readString(offset: fileOffset) - } -} - -extension Resolvable where Self: LocatableLayoutWrapper { - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - try machOFile.readElement(offset: fileOffset) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + return try machO.readString(offset: fileOffset) } } extension Resolvable where Self: LocatableLayoutWrapper { - public static func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> Self { - try machOImage.readElement(offset: imageOffset) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + try machO.readWrapperElement(offset: fileOffset) } } diff --git a/Sources/MachOSwiftSection/MachOFile+Swift.swift b/Sources/MachOSwiftSection/MachOFile+Swift.swift index aacdab8c..78590c63 100644 --- a/Sources/MachOSwiftSection/MachOFile+Swift.swift +++ b/Sources/MachOSwiftSection/MachOFile+Swift.swift @@ -60,7 +60,7 @@ extension MachOFile.Swift { var currentOffset = offset let endOffset = offset + section.size while currentOffset < endOffset { - let descriptor: Descriptor = try machOFile.readElement(offset: currentOffset) + let descriptor: Descriptor = try machOFile.readWrapperElement(offset: currentOffset) currentOffset += descriptor.actualSize descriptors.append(descriptor) } @@ -75,7 +75,7 @@ extension MachOFile.Swift { } else { section.offset } - let data: [AnyLocatableLayoutWrapper>] = try machO.readElements(offset: offset, numberOfElements: section.size / pointerSize) + let data: [AnyLocatableLayoutWrapper>] = try machO.readWrapperElements(offset: offset, numberOfElements: section.size / pointerSize) return try data.map { try $0.layout.resolve(from: $0.offset, in: machO) } } } diff --git a/Sources/MachOSwiftSection/MachOImage+Swift.swift b/Sources/MachOSwiftSection/MachOImage+Swift.swift index 8b5b2966..bee80f53 100644 --- a/Sources/MachOSwiftSection/MachOImage+Swift.swift +++ b/Sources/MachOSwiftSection/MachOImage+Swift.swift @@ -58,7 +58,7 @@ extension MachOImage.Swift { var currentOffset = offset let endOffset = offset + section.size while currentOffset < endOffset { - let descriptor: Descriptor = try machOImage.readElement(offset: currentOffset) + let descriptor: Descriptor = try machOImage.readWrapperElement(offset: currentOffset) currentOffset += descriptor.actualSize descriptors.append(descriptor) } @@ -71,7 +71,7 @@ extension MachOImage.Swift { let start = try required(UnsafeRawPointer(bitPattern: section.address + vmaddrSlide)) let offset = start.int - machO.ptr.int let pointerSize: Int = MemoryLayout>.size - let data: [AnyLocatableLayoutWrapper>] = try machO.readElements(offset: offset, numberOfElements: section.size / pointerSize) + let data: [AnyLocatableLayoutWrapper>] = try machO.readWrapperElements(offset: offset, numberOfElements: section.size / pointerSize) return try data.map { try $0.layout.resolve(from: $0.offset, in: machO) } } } diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift index 6790a5cb..0fb39fa8 100644 --- a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift +++ b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift @@ -8,8 +8,7 @@ public struct AnonymousContext { public let genericContext: GenericContext? public let mangledName: MangledName? - @MachOImageGenerator - public init(descriptor: AnonymousContextDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: AnonymousContextDescriptor, in machOFile: MachO) throws { self.descriptor = descriptor var currentOffset = descriptor.offset + descriptor.layoutSize diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift index 8e0dc607..4d41edca 100644 --- a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift +++ b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift @@ -4,9 +4,9 @@ import MachOMacro public protocol AnonymousContextDescriptorProtocol: ContextDescriptorProtocol where Layout: AnonymousContextDescriptorLayout {} -@MachOImageAllMembersGenerator + extension AnonymousContextDescriptorProtocol { - public func mangledName(in machOFile: MachOFile) throws -> MangledName? { + public func mangledName(in machOFile: MachO) throws -> MangledName? { guard hasMangledName else { return nil } diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift index 4b5152ca..99a45041 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift +++ b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift @@ -1,6 +1,7 @@ import Foundation import MachOKit import MachOMacro +import MachOFoundation public struct AssociatedType: TopLevelType { public let descriptor: AssociatedTypeDescriptor @@ -11,8 +12,8 @@ public struct AssociatedType: TopLevelType { public let records: [AssociatedTypeRecord] - @MachOImageGenerator - public init(descriptor: AssociatedTypeDescriptor, in machOFile: MachOFile) throws { + + public init(descriptor: AssociatedTypeDescriptor, in machOFile: MachO) throws { self.descriptor = descriptor self.conformingTypeName = try descriptor.conformingTypeName(in: machOFile) self.protocolTypeName = try descriptor.protocolTypeName(in: machOFile) diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift index db78c7a4..51183bf6 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift @@ -20,22 +20,17 @@ public struct AssociatedTypeDescriptor: ResolvableLocatableLayoutWrapper { } } - -@MachOImageAllMembersGenerator extension AssociatedTypeDescriptor { - - public func conformingTypeName(in machOFile: MachOFile) throws -> MangledName { + public func conformingTypeName(in machOFile: MachO) throws -> MangledName { return try layout.conformingTypeName.resolve(from: offset(of: \.conformingTypeName), in: machOFile) } - - //@MachOImageGenerator - public func protocolTypeName(in machOFile: MachOFile) throws -> MangledName { + + public func protocolTypeName(in machOFile: MachO) throws -> MangledName { return try layout.protocolTypeName.resolve(from: offset(of: \.protocolTypeName), in: machOFile) } - - //@MachOImageGenerator - public func associatedTypeRecords(in machOFile: MachOFile) throws -> [AssociatedTypeRecord] { - return try machOFile.readElements(offset: offset + layoutSize, numberOfElements: layout.numAssociatedTypes.cast()) + + public func associatedTypeRecords(in machOFile: MachO) throws -> [AssociatedTypeRecord] { + return try machOFile.readWrapperElements(offset: offset + layoutSize, numberOfElements: layout.numAssociatedTypes.cast()) } } diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift index bd85ea73..7129b95c 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift +++ b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift @@ -8,24 +8,23 @@ public struct AssociatedTypeRecord: ResolvableLocatableLayoutWrapper { public let name: RelativeDirectPointer public let substitutedTypeName: RelativeDirectPointer } - + public var layout: Layout - + public var offset: Int - + public init(layout: Layout, offset: Int) { self.layout = layout self.offset = offset } } -@MachOImageAllMembersGenerator extension AssociatedTypeRecord { - public func name(in machOFile: MachOFile) throws -> String { + public func name(in machOFile: MachO) throws -> String { return try layout.name.resolve(from: offset(of: \.name), in: machOFile) } - - public func substitutedTypeName(in machOFile: MachOFile) throws -> MangledName { + + public func substitutedTypeName(in machOFile: MachO) throws -> MangledName { return try layout.substitutedTypeName.resolve(from: offset(of: \.substitutedTypeName), in: machOFile) } } diff --git a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift b/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift index 57a18738..25b596f9 100644 --- a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift +++ b/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift @@ -2,14 +2,14 @@ import Foundation import MachOSymbols import MachOKit import MachOMacro +import MachOFoundation public struct BuiltinType: TopLevelType { public let descriptor: BuiltinTypeDescriptor public let typeName: MangledName? - @MachOImageGenerator - public init(descriptor: BuiltinTypeDescriptor, in machO: MachOFile) throws { + public init(descriptor: BuiltinTypeDescriptor, in machO: MachO) throws { self.descriptor = descriptor self.typeName = try descriptor.typeName(in: machO) } diff --git a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift b/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift index 43f27abe..e9eae3c8 100644 --- a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift @@ -23,8 +23,7 @@ public struct BuiltinTypeDescriptor: ResolvableLocatableLayoutWrapper, TopLevelD } extension BuiltinTypeDescriptor { - @MachOImageGenerator - public func typeName(in machOFile: MachOFile) throws -> MangledName? { + public func typeName(in machOFile: MachO) throws -> MangledName? { return try layout.typeName.resolve(from: offset(of: \.typeName), in: machOFile) } diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift index 5724ce6b..7561e79b 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift +++ b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift @@ -3,22 +3,19 @@ import MachOFoundation import MachOMacro public protocol ContextDescriptorProtocol: ResolvableLocatableLayoutWrapper where Layout: ContextDescriptorLayout { - func genericContext(in machO: MachOFile) throws -> GenericContext? - func parent(in machO: MachOFile) throws -> SymbolOrElement? - - func genericContext(in machO: MachOImage) throws -> GenericContext? - func parent(in machO: MachOImage) throws -> SymbolOrElement? + func genericContext(in machO: MachO) throws -> GenericContext? + func parent(in machO: MachO) throws -> SymbolOrElement? } -@MachOImageAllMembersGenerator + extension ContextDescriptorProtocol { - public func parent(in machOFile: MachOFile) throws -> SymbolOrElement? { + public func parent(in machO: MachO) throws -> SymbolOrElement? { guard layout.flags.kind != .module else { return nil } - return try layout.parent.resolve(from: offset + layout.offset(of: .parent), in: machOFile).asOptional + return try layout.parent.resolve(from: offset + layout.offset(of: .parent), in: machO).asOptional } - public func genericContext(in machOFile: MachOFile) throws -> GenericContext? { + public func genericContext(in machO: MachO) throws -> GenericContext? { guard layout.flags.isGeneric else { return nil } - return try GenericContext(contextDescriptor: self, in: machOFile) + return try GenericContext(contextDescriptor: self, in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift index e86abb00..fdacaf50 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift +++ b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift @@ -12,7 +12,7 @@ public enum ContextDescriptorWrapper { case opaqueType(OpaqueTypeDescriptor) public var protocolDescriptor: ProtocolDescriptor? { - if case .protocol(let descriptor) = self { + if case let .protocol(descriptor) = self { return descriptor } else { return nil @@ -20,7 +20,7 @@ public enum ContextDescriptorWrapper { } public var extensionContextDescriptor: ExtensionContextDescriptor? { - if case .extension(let descriptor) = self { + if case let .extension(descriptor) = self { return descriptor } else { return nil @@ -28,7 +28,7 @@ public enum ContextDescriptorWrapper { } public var opaqueTypeDescriptor: OpaqueTypeDescriptor? { - if case .opaqueType(let descriptor) = self { + if case let .opaqueType(descriptor) = self { return descriptor } else { return nil @@ -36,7 +36,7 @@ public enum ContextDescriptorWrapper { } public var moduleContextDescriptor: ModuleContextDescriptor? { - if case .module(let descriptor) = self { + if case let .module(descriptor) = self { return descriptor } else { return nil @@ -44,7 +44,7 @@ public enum ContextDescriptorWrapper { } public var anonymousContextDescriptor: AnonymousContextDescriptor? { - if case .anonymous(let descriptor) = self { + if case let .anonymous(descriptor) = self { return descriptor } else { return nil @@ -69,35 +69,34 @@ public enum ContextDescriptorWrapper { } } - @MachOImageGenerator - public func parent(in machOFile: MachOFile) throws -> SymbolOrElement? { + public func parent(in machOFile: MachO) throws -> SymbolOrElement? { return try contextDescriptor.parent(in: machOFile) } public var contextDescriptor: any ContextDescriptorProtocol { switch self { - case .type(let typeContextDescriptor): + case let .type(typeContextDescriptor): return typeContextDescriptor.contextDescriptor - case .protocol(let protocolDescriptor): + case let .protocol(protocolDescriptor): return protocolDescriptor - case .anonymous(let anonymousContextDescriptor): + case let .anonymous(anonymousContextDescriptor): return anonymousContextDescriptor - case .extension(let extensionContextDescriptor): + case let .extension(extensionContextDescriptor): return extensionContextDescriptor - case .module(let moduleContextDescriptor): + case let .module(moduleContextDescriptor): return moduleContextDescriptor - case .opaqueType(let opaqueTypeDescriptor): + case let .opaqueType(opaqueTypeDescriptor): return opaqueTypeDescriptor } } public var namedContextDescriptor: (any NamedContextDescriptorProtocol)? { switch self { - case .type(let typeContextDescriptor): + case let .type(typeContextDescriptor): return typeContextDescriptor.namedContextDescriptor - case .protocol(let protocolDescriptor): + case let .protocol(protocolDescriptor): return protocolDescriptor - case .module(let moduleContextDescriptor): + case let .module(moduleContextDescriptor): return moduleContextDescriptor case .anonymous, .extension, @@ -107,21 +106,20 @@ public enum ContextDescriptorWrapper { } public var typeContextDescriptor: (any TypeContextDescriptorProtocol)? { - if case .type(let typeContextDescriptor) = self { + if case let .type(typeContextDescriptor) = self { switch typeContextDescriptor { - case .enum(let enumDescriptor): + case let .enum(enumDescriptor): return enumDescriptor - case .struct(let structDescriptor): + case let .struct(structDescriptor): return structDescriptor - case .class(let classDescriptor): + case let .class(classDescriptor): return classDescriptor } } else { return nil } } - - + public subscript(dynamicMember keyPath: KeyPath) -> Property { return contextDescriptor[keyPath: keyPath] } @@ -132,33 +130,31 @@ extension ContextDescriptorWrapper: Resolvable { case invalidContextDescriptor } - @MachOImageGenerator - public static func resolve(from offset: Int, in machOFile: MachOFile) throws -> Self { - let contextDescriptor: ContextDescriptor = try machOFile.readElement(offset: offset) + public static func resolve(from offset: Int, in machOFile: MachO) throws -> Self { + let contextDescriptor: ContextDescriptor = try machOFile.readWrapperElement(offset: offset) switch contextDescriptor.flags.kind { case .class: - return try .type(.class(machOFile.readElement(offset: offset))) + return try .type(.class(machOFile.readWrapperElement(offset: offset))) case .enum: - return try .type(.enum(machOFile.readElement(offset: offset))) + return try .type(.enum(machOFile.readWrapperElement(offset: offset))) case .struct: - return try .type(.struct(machOFile.readElement(offset: offset))) + return try .type(.struct(machOFile.readWrapperElement(offset: offset))) case .protocol: - return try .protocol(machOFile.readElement(offset: offset)) + return try .protocol(machOFile.readWrapperElement(offset: offset)) case .anonymous: - return try .anonymous(machOFile.readElement(offset: offset)) + return try .anonymous(machOFile.readWrapperElement(offset: offset)) case .extension: - return try .extension(machOFile.readElement(offset: offset)) + return try .extension(machOFile.readWrapperElement(offset: offset)) case .module: - return try .module(machOFile.readElement(offset: offset)) + return try .module(machOFile.readWrapperElement(offset: offset)) case .opaqueType: - return try .opaqueType(machOFile.readElement(offset: offset)) + return try .opaqueType(machOFile.readWrapperElement(offset: offset)) default: throw ResolutionError.invalidContextDescriptor } } - @MachOImageGenerator - public static func resolve(from offset: Int, in machOFile: MachOFile) throws -> Self? { + public static func resolve(from offset: Int, in machOFile: MachO) throws -> Self? { do { return try resolve(from: offset, in: machOFile) as Self } catch { diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift b/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift index d0156003..75186200 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift +++ b/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift @@ -4,13 +4,12 @@ import MachOFoundation public protocol NamedContextDescriptorProtocol: ContextDescriptorProtocol where Layout: NamedContextDescriptorLayout {} -@MachOImageAllMembersGenerator extension NamedContextDescriptorProtocol { - public func name(in machOFile: MachOFile) throws -> String { - try layout.name.resolve(from: offset + layout.offset(of: .name), in: machOFile) + public func name(in machO: MachO) throws -> String { + try layout.name.resolve(from: offset + layout.offset(of: .name), in: machO) } - public func mangledName(in machOFile: MachOFile) throws -> MangledName { - try layout.name.resolveAny(from: offset + layout.offset(of: .name), in: machOFile) + public func mangledName(in machO: MachO) throws -> MangledName { + try layout.name.resolveAny(from: offset + layout.offset(of: .name), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift b/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift index 26e24eb6..1618ffc7 100644 --- a/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift +++ b/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift @@ -21,9 +21,8 @@ public struct ExtendedExistentialTypeShape: ResolvableLocatableLayoutWrapper { } extension ExtendedExistentialTypeShape { - @MachOImageGenerator - public func existentialType(in machOFile: MachOFile) throws -> MangledName { - try layout.existentialType.resolve(from: offset(of: \.existentialType), in: machOFile) + public func existentialType(in machO: MachO) throws -> MangledName { + try layout.existentialType.resolve(from: offset(of: \.existentialType), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift b/Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift index 3894bfd7..90ce8a97 100644 --- a/Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift +++ b/Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift @@ -20,8 +20,7 @@ public struct NonUniqueExtendedExistentialTypeShape: ResolvableLocatableLayoutWr } extension NonUniqueExtendedExistentialTypeShape { - @MachOImageGenerator - public func existentialType(in machOFile: MachOFile) throws -> MangledName { - try layout.localCopy.existentialType.resolve(from: offset(of: \.localCopy.existentialType), in: machOFile) + public func existentialType(in machO: MachO) throws -> MangledName { + try layout.localCopy.existentialType.resolve(from: offset(of: \.localCopy.existentialType), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift b/Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift index 7505dcf1..46f7890d 100644 --- a/Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift +++ b/Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift @@ -1,6 +1,7 @@ import Foundation import MachOKit import MachOMacro +import MachOFoundation public struct ExtensionContext { public let descriptor: ExtensionContextDescriptor @@ -9,10 +10,9 @@ public struct ExtensionContext { public let extendedContextMangledName: MangledName? - @MachOImageGenerator - public init(descriptor: ExtensionContextDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: ExtensionContextDescriptor, in machO: MachO) throws { self.descriptor = descriptor - self.extendedContextMangledName = try descriptor.extendedContext(in: machOFile) - self.genericContext = try descriptor.genericContext(in: machOFile) + self.extendedContextMangledName = try descriptor.extendedContext(in: machO) + self.genericContext = try descriptor.genericContext(in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift b/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift index bb2849ca..dc3d9994 100644 --- a/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift @@ -20,10 +20,9 @@ public struct ExtensionContextDescriptor: ExtensionContextDescriptorProtocol { } } -@MachOImageAllMembersGenerator extension ExtensionContextDescriptorProtocol { - public func extendedContext(in machOFile: MachOFile) throws -> MangledName? { - try layout.extendedContext.resolve(from: offset + 8, in: machOFile) + public func extendedContext(in machO: MachO) throws -> MangledName? { + try layout.extendedContext.resolve(from: offset + 8, in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift b/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift index bdd92d22..4d9c3155 100644 --- a/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift @@ -22,18 +22,17 @@ public struct FieldDescriptor: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension FieldDescriptor { public var kind: FieldDescriptorKind { .init(rawValue: layout.kind)! } - public func mangledTypeName(in machOFile: MachOFile) throws -> MangledName { - return try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machOFile) + public func mangledTypeName(in machO: MachO) throws -> MangledName { + return try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machO) } - public func records(in machOFile: MachOFile) throws -> [FieldRecord] { + public func records(in machO: MachO) throws -> [FieldRecord] { guard layout.fieldRecordSize != 0 else { return [] } let offset = offset + MemoryLayout.size - return try machOFile.readElements(offset: offset, numberOfElements: layout.numFields.cast()) + return try machO.readWrapperElements(offset: offset, numberOfElements: layout.numFields.cast()) } } diff --git a/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift b/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift index 00f71c4c..13747334 100644 --- a/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift +++ b/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift @@ -20,13 +20,12 @@ public struct FieldRecord: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension FieldRecord { - public func mangledTypeName(in machOFile: MachOFile) throws -> MangledName { - return try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machOFile) + public func mangledTypeName(in machO: MachO) throws -> MangledName { + return try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machO) } - public func fieldName(in machOFile: MachOFile) throws -> String { - return try layout.fieldName.resolve(from: offset(of: \.fieldName), in: machOFile) + public func fieldName(in machO: MachO) throws -> String { + return try layout.fieldName.resolve(from: offset(of: \.fieldName), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericContext.swift b/Sources/MachOSwiftSection/Models/Generic/GenericContext.swift index d1e02f01..46529103 100644 --- a/Sources/MachOSwiftSection/Models/Generic/GenericContext.swift +++ b/Sources/MachOSwiftSection/Models/Generic/GenericContext.swift @@ -79,18 +79,17 @@ public struct TargetGenericContext(contextDescriptor: any ContextDescriptorProtocol, in machO: MachO) throws { var currentOffset = contextDescriptor.offset + contextDescriptor.layoutSize let genericContextOffset = currentOffset - let header: Header = try machOFile.readElement(offset: currentOffset) + let header: Header = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: Header.self) self.offset = genericContextOffset self.header = header if header.numParams > 0 { - let parameters: [GenericParamDescriptor] = try machOFile.readElements(offset: currentOffset, numberOfElements: Int(header.numParams)) + let parameters: [GenericParamDescriptor] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: Int(header.numParams)) currentOffset.offset(of: GenericParamDescriptor.self, numbersOfElements: Int(header.numParams)) currentOffset = numericCast(align(address: numericCast(currentOffset), alignment: 4)) self.parameters = parameters @@ -99,7 +98,7 @@ public struct TargetGenericContext 0 { - let requirements: [GenericRequirementDescriptor] = try machOFile.readElements(offset: currentOffset, numberOfElements: Int(header.numRequirements)) + let requirements: [GenericRequirementDescriptor] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: Int(header.numRequirements)) currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: Int(header.numRequirements)) self.requirements = requirements } else { @@ -107,11 +106,11 @@ public struct TargetGenericContext(descriptor: GenericRequirementDescriptor, in machO: MachO) throws { self.descriptor = descriptor - self.paramManagledName = try descriptor.paramManagedName(in: machOFile) - self.content = try descriptor.resolvedContent(in: machOFile) + self.paramManagledName = try descriptor.paramManagedName(in: machO) + self.content = try descriptor.resolvedContent(in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift b/Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift index d41079c7..d2b6fe90 100644 --- a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift @@ -20,17 +20,14 @@ public struct GenericRequirementDescriptor: ResolvableLocatableLayoutWrapper { } } - -@MachOImageAllMembersGenerator extension GenericRequirementDescriptor { - //@MachOImageGenerator - public func paramManagedName(in machOFile: MachOFile) throws -> MangledName { - return try layout.param.resolve(from: offset(of: \.param), in: machOFile) + + public func paramManagedName(in machO: MachO) throws -> MangledName { + return try layout.param.resolve(from: offset(of: \.param), in: machO) } - //@MachOImageGenerator - public func type(in machOFile: MachOFile) throws -> MangledName { - return try RelativeDirectPointer(relativeOffset: layout.content).resolve(from: offset(of: \.content), in: machOFile) + public func type(in machO: MachO) throws -> MangledName { + return try RelativeDirectPointer(relativeOffset: layout.content).resolve(from: offset(of: \.content), in: machO) } public var content: GenericRequirementContent { @@ -58,18 +55,17 @@ extension GenericRequirementDescriptor { } } - //@MachOImageGenerator - public func resolvedContent(in machOFile: MachOFile) throws -> ResolvedGenericRequirementContent { + public func resolvedContent(in machO: MachO) throws -> ResolvedGenericRequirementContent { let offset = offset(of: \.content) switch content { case .type(let relativeDirectPointer): - return try .type(relativeDirectPointer.resolve(from: offset, in: machOFile)) + return try .type(relativeDirectPointer.resolve(from: offset, in: machO)) case .protocol(let relativeProtocolDescriptorPointer): - return try .protocol(relativeProtocolDescriptorPointer.resolve(from: offset, in: machOFile)) + return try .protocol(relativeProtocolDescriptorPointer.resolve(from: offset, in: machO)) case .layout(let genericRequirementLayoutKind): return .layout(genericRequirementLayoutKind) case .conformance(let relativeIndirectablePointer): - return try .conformance(relativeIndirectablePointer.resolve(from: offset, in: machOFile)) + return try .conformance(relativeIndirectablePointer.resolve(from: offset, in: machO)) case .invertedProtocols(let invertedProtocols): return .invertedProtocols(invertedProtocols) } diff --git a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift b/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift index fdd7ae18..f0ac5998 100644 --- a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift +++ b/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift @@ -109,13 +109,12 @@ public struct MangledName { } extension MangledName: Resolvable { - @MachOImageGenerator - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> MangledName { + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> MangledName { var elements: [MangledName.Element] = [] var currentOffset = fileOffset var currentString = "" while true { - let value: UInt8 = try machOFile.readElement(offset: currentOffset) + let value: UInt8 = try machO.readElement(offset: currentOffset) if value == 0xFF {} else if value == 0 { if currentString.count > 0 { @@ -129,7 +128,7 @@ extension MangledName: Resolvable { elements.append(.string(currentString)) currentString = "" } - let reference: Int32 = try machOFile.readElement(offset: currentOffset + 1) + let reference: Int32 = try machO.readElement(offset: currentOffset + 1) let offset = Int(fileOffset + (currentOffset - fileOffset)) elements.append(.lookup(.init(offset: offset, reference: .relative(.init(kind: value, relativeOffset: reference + 1))))) currentOffset.offset(of: Int32.self) @@ -138,7 +137,7 @@ extension MangledName: Resolvable { elements.append(.string(currentString)) currentString = "" } - let reference: UInt64 = try machOFile.readElement(offset: currentOffset + 1) + let reference: UInt64 = try machO.readElement(offset: currentOffset + 1) let offset = Int(fileOffset + (currentOffset - fileOffset)) elements.append(.lookup(.init(offset: offset, reference: .absolute(.init(kind: value, reference: reference))))) currentOffset.offset(of: UInt64.self) diff --git a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift b/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift index 1510fe76..d80c0659 100644 --- a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift +++ b/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift @@ -12,12 +12,11 @@ public struct OpaqueType: TopLevelType { public let invertedProtocols: InvertibleProtocolSet? - @MachOImageGenerator - public init(descriptor: OpaqueTypeDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: OpaqueTypeDescriptor, in machO: MachO) throws { self.descriptor = descriptor var currentOffset = descriptor.offset + descriptor.layoutSize - let genericContext = try descriptor.genericContext(in: machOFile) + let genericContext = try descriptor.genericContext(in: machO) if let genericContext { currentOffset += genericContext.size @@ -25,10 +24,10 @@ public struct OpaqueType: TopLevelType { self.genericContext = genericContext if descriptor.numUnderlyingTypeArugments > 0 { - let underlyingTypeArgumentMangledNamePointers: [RelativeDirectPointer] = try machOFile.readElements(offset: currentOffset, numberOfElements: descriptor.numUnderlyingTypeArugments) + let underlyingTypeArgumentMangledNamePointers: [RelativeDirectPointer] = try machO.readElements(offset: currentOffset, numberOfElements: descriptor.numUnderlyingTypeArugments) var underlyingTypeArgumentMangledNames: [MangledName] = [] for underlyingTypeArgumentMangledNamePointer in underlyingTypeArgumentMangledNamePointers { - try underlyingTypeArgumentMangledNames.append(underlyingTypeArgumentMangledNamePointer.resolve(from: currentOffset, in: machOFile)) + try underlyingTypeArgumentMangledNames.append(underlyingTypeArgumentMangledNamePointer.resolve(from: currentOffset, in: machO)) currentOffset += MemoryLayout>.size } self.underlyingTypeArgumentMangledNames = underlyingTypeArgumentMangledNames @@ -37,7 +36,7 @@ public struct OpaqueType: TopLevelType { } if descriptor.flags.contains(.hasInvertibleProtocols) { - self.invertedProtocols = try machOFile.readElement(offset: currentOffset) + self.invertedProtocols = try machO.readElement(offset: currentOffset) as InvertibleProtocolSet currentOffset.offset(of: InvertibleProtocolSet.self) } else { self.invertedProtocols = nil diff --git a/Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift b/Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift index 64158ba3..38a9546f 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift @@ -19,15 +19,12 @@ public struct ObjCProtocolPrefix: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension ObjCProtocolPrefix { - //@MachOImageGenerator - public func name(in machOFile: MachOFile) throws -> String { - try layout.name.resolve(in: machOFile) + public func name(in machO: MachO) throws -> String { + try layout.name.resolve(in: machO) } - //@MachOImageGenerator - public func mangledName(in machOFile: MachOFile) throws -> MangledName { - try Pointer(address: layout.name.address).resolve(in: machOFile) + public func mangledName(in machO: MachO) throws -> MangledName { + try Pointer(address: layout.name.address).resolve(in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift b/Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift index f8ae4d21..fa3986e8 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift @@ -19,10 +19,9 @@ public struct RelativeObjCProtocolPrefix: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension RelativeObjCProtocolPrefix { - func mangledName(in machOFile: MachOFile) throws -> MangledName { - return try layout.mangledName.resolve(from: offset(of: \.mangledName), in: machOFile) + func mangledName(in machO: MachO) throws -> MangledName { + return try layout.mangledName.resolve(from: offset(of: \.mangledName), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift b/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift index 39522b88..2aac4c11 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift @@ -1,6 +1,7 @@ import Foundation import MachOKit import MachOMacro +import MachOFoundation // using TrailingObjects // = swift::ABI::TrailingObjects< @@ -31,18 +32,17 @@ public struct `Protocol`: TopLevelType { descriptor.numRequirementsInSignature.cast() } - @MachOImageGenerator - public init(descriptor: ProtocolDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: ProtocolDescriptor, in machO: MachO) throws { guard let protocolFlags = descriptor.flags.kindSpecificFlags?.protocolFlags else { throw Error.invalidProtocolDescriptor } self.descriptor = descriptor self.protocolFlags = protocolFlags - self.name = try descriptor.name(in: machOFile) + self.name = try descriptor.name(in: machO) var currentOffset = descriptor.offset + descriptor.layoutSize if descriptor.numRequirementsInSignature > 0 { - self.requirementInSignatures = try machOFile.readElements(offset: currentOffset, numberOfElements: descriptor.numRequirementsInSignature.cast()) + self.requirementInSignatures = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirementsInSignature.cast()) currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.numRequirementsInSignature.cast()) currentOffset = align(address: currentOffset.cast(), alignment: 4).cast() } else { @@ -50,7 +50,7 @@ public struct `Protocol`: TopLevelType { } if descriptor.numRequirements > 0 { - self.requirements = try machOFile.readElements(offset: currentOffset, numberOfElements: descriptor.numRequirements.cast()) + self.requirements = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirements.cast()) currentOffset.offset(of: ProtocolRequirement.self, numbersOfElements: descriptor.numRequirements.cast()) } else { self.requirements = [] diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift b/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift index 79d5adf8..d61f7055 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift @@ -35,11 +35,10 @@ public struct ProtocolDescriptor: ProtocolDescriptorProtocol { } } -@MachOImageAllMembersGenerator extension ProtocolDescriptor { - public func associatedTypes(in machOFile: MachOFile) throws -> [String] { + public func associatedTypes(in machO: MachO) throws -> [String] { guard layout.associatedTypes.isValid else { return [] } - return try layout.associatedTypes.resolve(from: offset(of: \.associatedTypes), in: machOFile).components(separatedBy: " ") + return try layout.associatedTypes.resolve(from: offset(of: \.associatedTypes), in: machO).components(separatedBy: " ") } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift b/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift index dcc864b7..bb2770d2 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift @@ -18,26 +18,23 @@ public struct ProtocolDescriptorRef { } } - @MachOImageGenerator - public func swiftProtocol(in machOFile: MachOFile) throws -> ProtocolDescriptor { - try Pointer(address: storage).resolve(in: machOFile) + public func swiftProtocol(in machO: MachO) throws -> ProtocolDescriptor { + try Pointer(address: storage).resolve(in: machO) } - @MachOImageGenerator - public func objcProtocol(in machOFile: MachOFile) throws -> ObjCProtocolPrefix { - try Pointer(address: storage & ~Bits.isObjC).resolve(in: machOFile) + public func objcProtocol(in machO: MachO) throws -> ObjCProtocolPrefix { + try Pointer(address: storage & ~Bits.isObjC).resolve(in: machO) } public var isObjC: Bool { storage & Bits.isObjC != 0 } - @MachOImageGenerator - public func name(in machOFile: MachOFile) throws -> String { + public func name(in machO: MachO) throws -> String { if isObjC { - return try objcProtocol(in: machOFile).name(in: machOFile) + return try objcProtocol(in: machO).name(in: machO) } else { - return try swiftProtocol(in: machOFile).name(in: machOFile) + return try swiftProtocol(in: machO).name(in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift b/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift index bc0ff65a..9c2c63db 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift @@ -18,10 +18,9 @@ public struct ProtocolRequirement: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension ProtocolRequirement { - public func defaultImplementationSymbols(in machOFile: MachOFile) throws -> Symbols? { + public func defaultImplementationSymbols(in machO: MachO) throws -> Symbols? { guard layout.defaultImplementation.isValid else { return nil } - return try layout.defaultImplementation.resolve(from: offset(of: \.defaultImplementation), in: machOFile) + return try layout.defaultImplementation.resolve(from: offset(of: \.defaultImplementation), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift b/Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift index ac0e5188..71b48593 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift @@ -19,14 +19,12 @@ public struct ResilientWitness: ResolvableLocatableLayoutWrapper { } } - -@MachOImageAllMembersGenerator extension ResilientWitness { - public func requirement(in machOFile: MachOFile) throws -> SymbolOrElement? { - return try layout.requirement.resolve(from: offset(of: \.requirement), in: machOFile).asOptional + public func requirement(in machO: MachO) throws -> SymbolOrElement? { + return try layout.requirement.resolve(from: offset(of: \.requirement), in: machO).asOptional } - public func implementationSymbols(in machOFile: MachOFile) throws -> Symbols? { - return try layout.implementation.resolve(from: offset(of: \.implementation), in: machOFile) + public func implementationSymbols(in machO: MachO) throws -> Symbols? { + return try layout.implementation.resolve(from: offset(of: \.implementation), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift b/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift index 13ca23f0..ae106de6 100644 --- a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift +++ b/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift @@ -43,38 +43,37 @@ public struct ProtocolConformance: TopLevelType { public let genericWitnessTable: GenericWitnessTable? - @MachOImageGenerator - public init(descriptor: ProtocolConformanceDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: ProtocolConformanceDescriptor, in machO: MachO) throws { self.descriptor = descriptor - self.protocol = try descriptor.protocolDescriptor(in: machOFile) + self.protocol = try descriptor.protocolDescriptor(in: machO) - self.typeReference = try descriptor.resolvedTypeReference(in: machOFile) + self.typeReference = try descriptor.resolvedTypeReference(in: machO) - self.witnessTablePattern = try descriptor.witnessTablePattern(in: machOFile) + self.witnessTablePattern = try descriptor.witnessTablePattern(in: machO) var currentOffset = descriptor.offset + descriptor.layoutSize if descriptor.flags.isRetroactive { - let retroactiveContextPointer: RelativeContextPointer = try machOFile.readElement(offset: currentOffset) - self.retroactiveContextDescriptor = try retroactiveContextPointer.resolve(from: currentOffset, in: machOFile).asOptional + let retroactiveContextPointer: RelativeContextPointer = try machO.readElement(offset: currentOffset) + self.retroactiveContextDescriptor = try retroactiveContextPointer.resolve(from: currentOffset, in: machO).asOptional currentOffset.offset(of: RelativeIndirectablePointer>.self) } else { self.retroactiveContextDescriptor = nil } if descriptor.flags.numConditionalRequirements > 0 { - self.conditionalRequirements = try machOFile.readElements(offset: currentOffset, numberOfElements: descriptor.flags.numConditionalRequirements.cast()) + self.conditionalRequirements = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.flags.numConditionalRequirements.cast()) currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.flags.numConditionalRequirements.cast()) } else { self.conditionalRequirements = [] } if descriptor.flags.numConditionalPackShapeDescriptors > 0 { - let header: GenericPackShapeHeader = try machOFile.readElement(offset: currentOffset) + let header: GenericPackShapeHeader = try machO.readWrapperElement(offset: currentOffset) self.conditionalPackShapeHeader = header currentOffset.offset(of: GenericPackShapeHeader.self) - self.conditionalPackShapeDescriptors = try machOFile.readWrapperElements(offset: currentOffset, numberOfElements: header.numPacks.cast()) + self.conditionalPackShapeDescriptors = try machO.readWrapperElements(offset: currentOffset, numberOfElements: header.numPacks.cast()) currentOffset.offset(of: GenericPackShapeDescriptor.self, numbersOfElements: header.numPacks.cast()) } else { self.conditionalPackShapeHeader = nil @@ -82,10 +81,10 @@ public struct ProtocolConformance: TopLevelType { } if descriptor.flags.hasResilientWitnesses { - let header: ResilientWitnessesHeader = try machOFile.readElement(offset: currentOffset) + let header: ResilientWitnessesHeader = try machO.readWrapperElement(offset: currentOffset) self.resilientWitnessesHeader = header currentOffset.offset(of: ResilientWitnessesHeader.self) - self.resilientWitnesses = try machOFile.readElements(offset: currentOffset, numberOfElements: header.numWitnesses.cast()) + self.resilientWitnesses = try machO.readWrapperElements(offset: currentOffset, numberOfElements: header.numWitnesses.cast()) currentOffset.offset(of: ResilientWitness.self, numbersOfElements: header.numWitnesses.cast()) } else { self.resilientWitnessesHeader = nil @@ -93,7 +92,7 @@ public struct ProtocolConformance: TopLevelType { } if descriptor.flags.hasGenericWitnessTable { - let genericWitnessTable: GenericWitnessTable = try machOFile.readElement(offset: currentOffset) + let genericWitnessTable: GenericWitnessTable = try machO.readWrapperElement(offset: currentOffset) self.genericWitnessTable = genericWitnessTable currentOffset.offset(of: GenericWitnessTable.self) } else { diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift b/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift index 206f75cf..621ee2f2 100644 --- a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift @@ -21,22 +21,21 @@ public struct ProtocolConformanceDescriptor: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension ProtocolConformanceDescriptor { - public func protocolDescriptor(in machOFile: MachOFile) throws -> SymbolOrElement? { - try layout.protocolDescriptor.resolve(from: offset(of: \.protocolDescriptor), in: machOFile).asOptional + public func protocolDescriptor(in machO: MachO) throws -> SymbolOrElement? { + try layout.protocolDescriptor.resolve(from: offset(of: \.protocolDescriptor), in: machO).asOptional } public var typeReference: TypeReference { return .forKind(layout.flags.typeReferenceKind, at: layout.typeReference) } - public func resolvedTypeReference(in machOFile: MachOFile) throws -> ResolvedTypeReference { + public func resolvedTypeReference(in machO: MachO) throws -> ResolvedTypeReference { let offset = offset(of: \.typeReference) - return try typeReference.resolve(at: offset, in: machOFile) + return try typeReference.resolve(at: offset, in: machO) } - public func witnessTablePattern(in machOFile: MachOFile) throws -> ProtocolWitnessTable? { - try layout.witnessTablePattern.resolve(from: offset(of: \.witnessTablePattern), in: machOFile) + public func witnessTablePattern(in machO: MachO) throws -> ProtocolWitnessTable? { + try layout.witnessTablePattern.resolve(from: offset(of: \.witnessTablePattern), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Class.swift b/Sources/MachOSwiftSection/Models/Type/Class/Class.swift index 208396e2..28ab5043 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Class.swift +++ b/Sources/MachOSwiftSection/Models/Type/Class/Class.swift @@ -47,17 +47,16 @@ public struct Class: TopLevelType { public let methodDefaultOverrideTableHeader: MethodDefaultOverrideTableHeader? public let methodDefaultOverrideDescriptors: [MethodDefaultOverrideDescriptor] - @MachOImageGenerator - public init(descriptor: ClassDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: ClassDescriptor, in machO: MachO) throws { self.descriptor = descriptor - let genericContext = try descriptor.typeGenericContext(in: machOFile) + let genericContext = try descriptor.typeGenericContext(in: machO) self.genericContext = genericContext var currentOffset = descriptor.offset + descriptor.layoutSize if let genericContext { currentOffset += genericContext.size } if descriptor.hasResilientSuperclass { - let resilientSuperclass: ResilientSuperclass = try machOFile.readWrapperElement(offset: currentOffset) + let resilientSuperclass: ResilientSuperclass = try machO.readWrapperElement(offset: currentOffset) self.resilientSuperclass = resilientSuperclass currentOffset.offset(of: ResilientSuperclass.self) } else { @@ -65,7 +64,7 @@ public struct Class: TopLevelType { } if descriptor.hasForeignMetadataInitialization { - let foreignMetadataInitialization: ForeignMetadataInitialization = try machOFile.readWrapperElement(offset: currentOffset) + let foreignMetadataInitialization: ForeignMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) self.foreignMetadataInitialization = foreignMetadataInitialization currentOffset.offset(of: ForeignMetadataInitialization.self) } else { @@ -73,7 +72,7 @@ public struct Class: TopLevelType { } if descriptor.hasSingletonMetadataInitialization { - let singletonMetadataInitialization: SingletonMetadataInitialization = try machOFile.readWrapperElement(offset: currentOffset) + let singletonMetadataInitialization: SingletonMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) self.singletonMetadataInitialization = singletonMetadataInitialization currentOffset.offset(of: SingletonMetadataInitialization.self) } else { @@ -81,10 +80,10 @@ public struct Class: TopLevelType { } if descriptor.hasVTable { - let vTableDescriptorHeader: VTableDescriptorHeader = try machOFile.readElement(offset: currentOffset) + let vTableDescriptorHeader: VTableDescriptorHeader = try machO.readWrapperElement(offset: currentOffset) self.vTableDescriptorHeader = vTableDescriptorHeader currentOffset.offset(of: VTableDescriptorHeader.self) - let methodDescriptors: [MethodDescriptor] = try machOFile.readWrapperElements(offset: currentOffset, numberOfElements: vTableDescriptorHeader.vTableSize.cast()) + let methodDescriptors: [MethodDescriptor] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: vTableDescriptorHeader.vTableSize.cast()) self.methodDescriptors = methodDescriptors currentOffset.offset(of: MethodDescriptor.self, numbersOfElements: vTableDescriptorHeader.vTableSize.cast()) } else { @@ -93,10 +92,10 @@ public struct Class: TopLevelType { } if descriptor.hasOverrideTable { - let overrideTableHeader: OverrideTableHeader = try machOFile.readWrapperElement(offset: currentOffset) + let overrideTableHeader: OverrideTableHeader = try machO.readWrapperElement(offset: currentOffset) self.overrideTableHeader = overrideTableHeader currentOffset.offset(of: OverrideTableHeader.self) - let methodOverrideDescriptors: [MethodOverrideDescriptor] = try machOFile.readWrapperElements(offset: currentOffset, numberOfElements: overrideTableHeader.numEntries.cast()) + let methodOverrideDescriptors: [MethodOverrideDescriptor] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: overrideTableHeader.numEntries.cast()) self.methodOverrideDescriptors = methodOverrideDescriptors currentOffset.offset(of: MethodOverrideDescriptor.self, numbersOfElements: overrideTableHeader.numEntries.cast()) } else { @@ -105,7 +104,7 @@ public struct Class: TopLevelType { } if descriptor.hasObjCResilientClassStub { - let objcResilientClassStubInfo: ObjCResilientClassStubInfo = try machOFile.readWrapperElement(offset: currentOffset) + let objcResilientClassStubInfo: ObjCResilientClassStubInfo = try machO.readWrapperElement(offset: currentOffset) self.objcResilientClassStubInfo = objcResilientClassStubInfo currentOffset.offset(of: ObjCResilientClassStubInfo.self) } else { @@ -113,17 +112,17 @@ public struct Class: TopLevelType { } if descriptor.hasCanonicalMetadataPrespecializations { - let count: CanonicalSpecializedMetadatasListCount = try machOFile.readElement(offset: currentOffset) + let count: CanonicalSpecializedMetadatasListCount = try machO.readElement(offset: currentOffset) self.canonicalSpecializedMetadatasListCount = count currentOffset.offset(of: CanonicalSpecializedMetadatasListCount.self) let countValue = count.rawValue - let canonicalSpecializedMetadatas: [CanonicalSpecializedMetadatasListEntry] = try machOFile.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) + let canonicalSpecializedMetadatas: [CanonicalSpecializedMetadatasListEntry] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) self.canonicalSpecializedMetadatas = canonicalSpecializedMetadatas currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) - let canonicalSpecializedMetadataAccessors: [CanonicalSpecializedMetadataAccessorsListEntry] = try machOFile.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) + let canonicalSpecializedMetadataAccessors: [CanonicalSpecializedMetadataAccessorsListEntry] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) self.canonicalSpecializedMetadataAccessors = canonicalSpecializedMetadataAccessors currentOffset.offset(of: CanonicalSpecializedMetadataAccessorsListEntry.self, numbersOfElements: countValue.cast()) - let canonicalSpecializedMetadatasCachingOnceToken: CanonicalSpecializedMetadatasCachingOnceToken = try machOFile.readWrapperElement(offset: currentOffset) + let canonicalSpecializedMetadatasCachingOnceToken: CanonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) self.canonicalSpecializedMetadatasCachingOnceToken = canonicalSpecializedMetadatasCachingOnceToken currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) } else { @@ -134,7 +133,7 @@ public struct Class: TopLevelType { } if descriptor.flags.contains(.hasInvertibleProtocols) { - let invertibleProtocolSet: InvertibleProtocolSet = try machOFile.readElement(offset: currentOffset) + let invertibleProtocolSet: InvertibleProtocolSet = try machO.readElement(offset: currentOffset) self.invertibleProtocolSet = invertibleProtocolSet currentOffset.offset(of: InvertibleProtocolSet.self) } else { @@ -142,7 +141,7 @@ public struct Class: TopLevelType { } if descriptor.hasSingletonMetadataPointer { - let singletonMetadataPointer: SingletonMetadataPointer = try machOFile.readWrapperElement(offset: currentOffset) + let singletonMetadataPointer: SingletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) self.singletonMetadataPointer = singletonMetadataPointer currentOffset.offset(of: SingletonMetadataPointer.self) } else { @@ -150,10 +149,10 @@ public struct Class: TopLevelType { } if descriptor.hasDefaultOverrideTable { - let methodDefaultOverrideTableHeader: MethodDefaultOverrideTableHeader = try machOFile.readWrapperElement(offset: currentOffset) + let methodDefaultOverrideTableHeader: MethodDefaultOverrideTableHeader = try machO.readWrapperElement(offset: currentOffset) self.methodDefaultOverrideTableHeader = methodDefaultOverrideTableHeader currentOffset.offset(of: MethodDefaultOverrideTableHeader.self) - let methodDefaultOverrideDescriptors: [MethodDefaultOverrideDescriptor] = try machOFile.readWrapperElements(offset: currentOffset, numberOfElements: methodDefaultOverrideTableHeader.numEntries.cast()) + let methodDefaultOverrideDescriptors: [MethodDefaultOverrideDescriptor] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: methodDefaultOverrideTableHeader.numEntries.cast()) self.methodDefaultOverrideDescriptors = methodDefaultOverrideDescriptors currentOffset.offset(of: MethodDefaultOverrideDescriptor.self, numbersOfElements: methodDefaultOverrideTableHeader.numEntries.cast()) } else { diff --git a/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift b/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift index 623dbc0e..7bdc54a2 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift @@ -81,8 +81,7 @@ extension ClassDescriptor { return ExtraClassDescriptorFlags(rawValue: layout.metadataPositiveSizeInWordsOrExtraClassFlags).hasObjCResilientClassStub } - @MachOImageGenerator - public func superclassTypeMangledName(in machOFile: MachOFile) throws -> MangledName? { - try layout.superclassType.resolve(from: offset(of: \.superclassType), in: machOFile) + public func superclassTypeMangledName(in machO: MachO) throws -> MangledName? { + try layout.superclassType.resolve(from: offset(of: \.superclassType), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop.swift b/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop.swift index 77d529dc..472e4966 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop.swift +++ b/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop.swift @@ -32,12 +32,11 @@ public struct ClassMetadataObjCInterop: TypeMetadataProtocol { public static var descriptorOffset: Int { Layout.offset(of: .descriptor) } } -@MachOImageAllMembersGenerator extension ClassMetadataObjCInterop { - public func fieldOffsets(for descriptor: ClassDescriptor? = nil, in machOFile: MachOFile) throws -> [StoredPointer] { - let descriptor = try descriptor ?? layout.descriptor.resolve(in: machOFile) + public func fieldOffsets(for descriptor: ClassDescriptor? = nil, in machO: MachO) throws -> [StoredPointer] { + let descriptor = try descriptor ?? layout.descriptor.resolve(in: machO) guard descriptor.fieldOffsetVectorOffset != .zero else { return [] } let offset = offset + descriptor.fieldOffsetVectorOffset.cast() * MemoryLayout.size - return try machOFile.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) + return try machO.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift b/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift index 09f9395f..c865c464 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift @@ -9,21 +9,19 @@ public struct MethodDefaultOverrideDescriptor: ResolvableLocatableLayoutWrapper public let original: RelativeMethodDescriptorPointer public let implementation: RelativeDirectPointer } - + public var layout: Layout - + public let offset: Int - + public init(layout: Layout, offset: Int) { self.layout = layout self.offset = offset } } -@MachOImageAllMembersGenerator extension MethodDefaultOverrideDescriptor { - //@MachOImageGenerator - public func implementationSymbol(in machOFile: MachOFile) throws -> Symbol? { - return try layout.implementation.resolve(from: offset(of: \.implementation), in: machOFile) + public func implementationSymbol(in machO: MachO) throws -> Symbol? { + return try layout.implementation.resolve(from: offset(of: \.implementation), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift b/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift index 8f62c40a..a26b7cb4 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift @@ -19,10 +19,8 @@ public struct MethodDescriptor: ResolvableLocatableLayoutWrapper { } } -@MachOImageAllMembersGenerator extension MethodDescriptor { - //@MachOImageGenerator - public func implementationSymbol(in machOFile: MachOFile) throws -> Symbol? { - return try layout.implementation.resolve(from: offset(of: \.implementation), in: machOFile) + public func implementationSymbol(in machO: MachO) throws -> Symbol? { + return try layout.implementation.resolve(from: offset(of: \.implementation), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift b/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift index 35a01e91..a16e4600 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift @@ -9,25 +9,23 @@ public struct MethodOverrideDescriptor: ResolvableLocatableLayoutWrapper { public let method: RelativeMethodDescriptorPointer public let implementation: RelativeDirectPointer } - + public var layout: Layout - + public let offset: Int - + public init(layout: Layout, offset: Int) { self.layout = layout self.offset = offset } } -@MachOImageAllMembersGenerator extension MethodOverrideDescriptor { - - public func methodDescriptor(in machOFile: MachOFile) throws -> SymbolOrElement? { - return try layout.method.resolve(from: offset(of: \.method), in: machOFile).asOptional + public func methodDescriptor(in machO: MachO) throws -> SymbolOrElement? { + return try layout.method.resolve(from: offset(of: \.method), in: machO).asOptional } - - public func implementationSymbol(in machOFile: MachOFile) throws -> Symbol? { - return try layout.implementation.resolve(from: offset(of: \.implementation), in: machOFile) + + public func implementationSymbol(in machO: MachO) throws -> Symbol? { + return try layout.implementation.resolve(from: offset(of: \.implementation), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift b/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift index dd836324..baf70692 100644 --- a/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift +++ b/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift @@ -29,13 +29,12 @@ public struct Enum: TopLevelType { public let invertibleProtocolSet: InvertibleProtocolSet? public let singletonMetadataPointer: SingletonMetadataPointer? - @MachOImageGenerator - public init(descriptor: EnumDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: EnumDescriptor, in machO: MachO) throws { self.descriptor = descriptor var currentOffset = descriptor.offset + descriptor.layoutSize - let genericContext = try descriptor.typeGenericContext(in: machOFile) + let genericContext = try descriptor.typeGenericContext(in: machO) if let genericContext { currentOffset += genericContext.size @@ -46,28 +45,28 @@ public struct Enum: TopLevelType { let typeFlags = try required(descriptor.flags.kindSpecificFlags?.typeFlags) if typeFlags.hasForeignMetadataInitialization { - self.foreignMetadataInitialization = try machOFile.readElement(offset: currentOffset) + self.foreignMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) as ForeignMetadataInitialization currentOffset.offset(of: ForeignMetadataInitialization.self) } else { self.foreignMetadataInitialization = nil } if typeFlags.hasSingletonMetadataInitialization { - self.singletonMetadataInitialization = try machOFile.readElement(offset: currentOffset) + self.singletonMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) as SingletonMetadataInitialization currentOffset.offset(of: SingletonMetadataInitialization.self) } else { self.singletonMetadataInitialization = nil } if descriptor.hasCanonicalMetadataPrespecializations { - let count: CanonicalSpecializedMetadatasListCount = try machOFile.readElement(offset: currentOffset) + let count: CanonicalSpecializedMetadatasListCount = try machO.readElement(offset: currentOffset) currentOffset.offset(of: CanonicalSpecializedMetadatasListCount.self) let countValue = count.rawValue - let canonicalMetadataPrespecializations: [CanonicalSpecializedMetadatasListEntry] = try machOFile.readElements(offset: currentOffset, numberOfElements: countValue.cast()) + let canonicalMetadataPrespecializations: [CanonicalSpecializedMetadatasListEntry] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) self.canonicalSpecializedMetadatas = canonicalMetadataPrespecializations self.canonicalSpecializedMetadatasListCount = count - self.canonicalSpecializedMetadatasCachingOnceToken = try machOFile.readElement(offset: currentOffset) + self.canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) } else { self.canonicalSpecializedMetadatas = [] @@ -76,14 +75,14 @@ public struct Enum: TopLevelType { } if descriptor.flags.hasInvertibleProtocols { - self.invertibleProtocolSet = try machOFile.readElement(offset: currentOffset) + self.invertibleProtocolSet = try machO.readElement(offset: currentOffset) currentOffset.offset(of: InvertibleProtocolSet.self) } else { self.invertibleProtocolSet = nil } if descriptor.hasSingletonMetadataPointer { - self.singletonMetadataPointer = try machOFile.readElement(offset: currentOffset) + self.singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: SingletonMetadataPointer.self) } else { self.singletonMetadataPointer = nil diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift b/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift index 4d96a9e4..b526506d 100644 --- a/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift +++ b/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift @@ -14,13 +14,12 @@ public struct Struct: TopLevelType { public let invertibleProtocolSet: InvertibleProtocolSet? public let singletonMetadataPointer: SingletonMetadataPointer? - @MachOImageGenerator - public init(descriptor: StructDescriptor, in machOFile: MachOFile) throws { + public init(descriptor: StructDescriptor, in machO: MachO) throws { self.descriptor = descriptor var currentOffset = descriptor.offset + descriptor.layoutSize - let genericContext = try descriptor.typeGenericContext(in: machOFile) + let genericContext = try descriptor.typeGenericContext(in: machO) if let genericContext { currentOffset += genericContext.size @@ -31,28 +30,28 @@ public struct Struct: TopLevelType { let typeFlags = try required(descriptor.flags.kindSpecificFlags?.typeFlags) if typeFlags.hasForeignMetadataInitialization { - self.foreignMetadataInitialization = try machOFile.readElement(offset: currentOffset) + self.foreignMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: ForeignMetadataInitialization.self) } else { self.foreignMetadataInitialization = nil } if typeFlags.hasSingletonMetadataInitialization { - self.singletonMetadataInitialization = try machOFile.readElement(offset: currentOffset) + self.singletonMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: SingletonMetadataInitialization.self) } else { self.singletonMetadataInitialization = nil } if descriptor.hasCanonicalMetadataPrespecializations { - let count: CanonicalSpecializedMetadatasListCount = try machOFile.readElement(offset: currentOffset) + let count: CanonicalSpecializedMetadatasListCount = try machO.readElement(offset: currentOffset) currentOffset.offset(of: CanonicalSpecializedMetadatasListCount.self) let countValue = count.rawValue - let canonicalMetadataPrespecializations: [CanonicalSpecializedMetadatasListEntry] = try machOFile.readElements(offset: currentOffset, numberOfElements: countValue.cast()) + let canonicalMetadataPrespecializations: [CanonicalSpecializedMetadatasListEntry] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) self.canonicalSpecializedMetadatas = canonicalMetadataPrespecializations self.canonicalSpecializedMetadatasListCount = count - self.canonicalSpecializedMetadatasCachingOnceToken = try machOFile.readElement(offset: currentOffset) + self.canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) } else { self.canonicalSpecializedMetadatas = [] @@ -61,14 +60,14 @@ public struct Struct: TopLevelType { } if descriptor.flags.hasInvertibleProtocols { - self.invertibleProtocolSet = try machOFile.readElement(offset: currentOffset) + self.invertibleProtocolSet = try machO.readElement(offset: currentOffset) currentOffset.offset(of: InvertibleProtocolSet.self) } else { self.invertibleProtocolSet = nil } if descriptor.hasSingletonMetadataPointer { - self.singletonMetadataPointer = try machOFile.readElement(offset: currentOffset) + self.singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) currentOffset.offset(of: SingletonMetadataPointer.self) } else { self.singletonMetadataPointer = nil diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift b/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift index e3f98e4a..293c7f2f 100644 --- a/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift +++ b/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift @@ -20,12 +20,11 @@ public struct StructMetadata: TypeMetadataProtocol { public static var descriptorOffset: Int { Layout.offset(of: .descriptor) } } -@MachOImageAllMembersGenerator extension StructMetadata { - public func fieldOffsets(for descriptor: StructDescriptor? = nil, in machOFile: MachOFile) throws -> [UInt32] { - let descriptor = try descriptor ?? layout.descriptor.resolve(in: machOFile) + public func fieldOffsets(for descriptor: StructDescriptor? = nil, in machO: MachO) throws -> [UInt32] { + let descriptor = try descriptor ?? layout.descriptor.resolve(in: machO) guard descriptor.fieldOffsetVector != .zero else { return [] } let offset = offset + descriptor.fieldOffsetVector.cast() * MemoryLayout.size - return try machOFile.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) + return try machO.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) } } diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift b/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift index 05c1d010..e1cb0c0b 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift @@ -22,21 +22,19 @@ public struct TypeContextDescriptor: TypeContextDescriptorProtocol { } } - -@MachOImageAllMembersGenerator extension TypeContextDescriptor { - public func enumDescriptor(in machOFile: MachOFile) throws -> EnumDescriptor? { + public func enumDescriptor(in machO: MachO) throws -> EnumDescriptor? { guard layout.flags.kind == .enum else { return nil } - return try machOFile.readElement(offset: offset) as EnumDescriptor + return try machO.readWrapperElement(offset: offset) as EnumDescriptor } - public func structDescriptor(in machOFile: MachOFile) throws -> StructDescriptor? { + public func structDescriptor(in machO: MachO) throws -> StructDescriptor? { guard layout.flags.kind == .struct else { return nil } - return try machOFile.readElement(offset: offset) as StructDescriptor + return try machO.readWrapperElement(offset: offset) as StructDescriptor } - public func classDescriptor(in machOFile: MachOFile) throws -> ClassDescriptor? { + public func classDescriptor(in machO: MachO) throws -> ClassDescriptor? { guard layout.flags.kind == .class else { return nil } - return try machOFile.readElement(offset: offset) as ClassDescriptor + return try machO.readWrapperElement(offset: offset) as ClassDescriptor } } diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift b/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift index e0d49768..58165601 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift +++ b/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift @@ -4,52 +4,50 @@ import MachOFoundation public protocol TypeContextDescriptorProtocol: NamedContextDescriptorProtocol where Layout: TypeContextDescriptorLayout {} -@MachOImageAllMembersGenerator extension TypeContextDescriptorProtocol { - - public func accessFunction(in machOFile: MachOFile) throws -> Symbol? { + public func accessFunction(in machO: MachO) throws -> Symbol? { let ptr = RelativeDirectPointer(relativeOffset: layout.accessFunctionPtr) - return try ptr.resolve(from: offset + layout.offset(of: .accessFunctionPtr), in: machOFile) + return try ptr.resolve(from: offset + layout.offset(of: .accessFunctionPtr), in: machO) } - - public func fieldDescriptor(in machOFile: MachOFile) throws -> FieldDescriptor { - try layout.fieldDescriptor.resolve(from: offset + layout.offset(of: .fieldDescriptor), in: machOFile) + + public func fieldDescriptor(in machO: MachO) throws -> FieldDescriptor { + try layout.fieldDescriptor.resolve(from: offset + layout.offset(of: .fieldDescriptor), in: machO) } - public func genericContext(in machO: MachOFile) throws -> GenericContext? { + public func genericContext(in machO: MachO) throws -> GenericContext? { guard layout.flags.isGeneric else { return nil } return try typeGenericContext(in: machO)?.asGenericContext() } - - public func typeGenericContext(in machOFile: MachOFile) throws -> TypeGenericContext? { + + public func typeGenericContext(in machO: MachO) throws -> TypeGenericContext? { guard layout.flags.isGeneric else { return nil } - return try .init(contextDescriptor: self, in: machOFile) + return try .init(contextDescriptor: self, in: machO) } - + public var hasSingletonMetadataInitialization: Bool { return layout.flags.kindSpecificFlags?.typeFlags?.hasSingletonMetadataInitialization ?? false } - + public var hasForeignMetadataInitialization: Bool { return layout.flags.kindSpecificFlags?.typeFlags?.hasForeignMetadataInitialization ?? false } - + public var hasImportInfo: Bool { return layout.flags.kindSpecificFlags?.typeFlags?.hasImportInfo ?? false } - + public var hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer: Bool { return layout.flags.kindSpecificFlags?.typeFlags?.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer ?? false } - + public var hasLayoutString: Bool { return layout.flags.kindSpecificFlags?.typeFlags?.hasLayoutString ?? false } - + public var hasCanonicalMetadataPrespecializations: Bool { return layout.flags.contains(.isGeneric) && hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer } - + public var hasSingletonMetadataPointer: Bool { return !layout.flags.contains(.isGeneric) && hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer } diff --git a/Sources/MachOSwiftSection/Models/Type/TypeReference.swift b/Sources/MachOSwiftSection/Models/Type/TypeReference.swift index f0f81053..de42abf4 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeReference.swift +++ b/Sources/MachOSwiftSection/Models/Type/TypeReference.swift @@ -22,17 +22,16 @@ public enum TypeReference { } - @MachOImageGenerator - public func resolve(at fileOffset: Int, in machOFile: MachOFile) throws -> ResolvedTypeReference { + public func resolve(at fileOffset: Int, in machO: MachO) throws -> ResolvedTypeReference { switch self { case let .directTypeDescriptor(relativeDirectPointer): - return try .directTypeDescriptor(relativeDirectPointer.resolve(from: fileOffset, in: machOFile)) + return try .directTypeDescriptor(relativeDirectPointer.resolve(from: fileOffset, in: machO)) case let .indirectTypeDescriptor(relativeIndirectPointer): - return try .indirectTypeDescriptor(relativeIndirectPointer.resolve(from: fileOffset, in: machOFile).resolve(in: machOFile).asOptional) + return try .indirectTypeDescriptor(relativeIndirectPointer.resolve(from: fileOffset, in: machO).resolve(in: machO).asOptional) case let .directObjCClassName(relativeDirectPointer): - return try .directObjCClassName(relativeDirectPointer.resolve(from: fileOffset, in: machOFile)) + return try .directObjCClassName(relativeDirectPointer.resolve(from: fileOffset, in: machO)) case let .indirectObjCClass(relativeIndirectPointer): - return try .indirectObjCClass(relativeIndirectPointer.resolve(from: fileOffset, in: machOFile).resolve(in: machOFile).asOptional) + return try .indirectObjCClass(relativeIndirectPointer.resolve(from: fileOffset, in: machO).resolve(in: machO).asOptional) } } } diff --git a/Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift b/Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift index b5e4175b..c017e185 100644 --- a/Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift +++ b/Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift @@ -24,9 +24,9 @@ public enum RelativeProtocolDescriptorPointer { } } - @MachOImageGenerator - public func protocolDescriptorRef(from offset: Int, in machOFile: MachOFile) throws -> ProtocolDescriptorRef { - let storedPointer = try rawPointer.resolveIndirectType(from: offset, in: machOFile).address + + public func protocolDescriptorRef(from offset: Int, in machO: MachO) throws -> ProtocolDescriptorRef { + let storedPointer = try rawPointer.resolveIndirectType(from: offset, in: machO).address if isObjC { return .forObjC(storedPointer) } else { @@ -34,13 +34,12 @@ public enum RelativeProtocolDescriptorPointer { } } - @MachOImageGenerator - public func resolve(from offset: Int, in machOFile: MachOFile) throws -> SymbolOrElement { + public func resolve(from offset: Int, in machO: MachO) throws -> SymbolOrElement { switch self { case .objcPointer(let relativeIndirectablePointerIntPair): - return try relativeIndirectablePointerIntPair.resolve(from: offset, in: machOFile).map { .objc($0) } + return try relativeIndirectablePointerIntPair.resolve(from: offset, in: machO).map { .objc($0) } case .swiftPointer(let relativeContextPointerIntPair): - return try relativeContextPointerIntPair.resolve(from: offset, in: machOFile).map { .swift($0) } + return try relativeContextPointerIntPair.resolve(from: offset, in: machO).map { .swift($0) } } } } diff --git a/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift b/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift index 3fa2b041..149d2f0c 100644 --- a/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift +++ b/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift @@ -2,6 +2,7 @@ import MachOKit import MachOReading import MachOPointer import MachOSymbols +import MachOExtensions public typealias RelativeSymbolOrElementPointer = RelativeIndirectablePointer, SymbolOrElementPointer> @@ -15,64 +16,42 @@ public enum SymbolOrElementPointer: RelativeIndirectType { case symbol(Symbol) case address(UInt64) - public func resolveOffset(in machOFile: MachOFile) -> Int { + public func resolve(in machOFile: MachO) throws -> Resolved { switch self { - case .symbol(let unsolvedSymbol): - return unsolvedSymbol.offset - case .address(let address): - return numericCast(machOFile.fileOffset(of: address)) - } - } - - public func resolve(in machOFile: MachOFile) throws -> Resolved { - switch self { - case .symbol(let unsolvedSymbol): + case let .symbol(unsolvedSymbol): return .symbol(unsolvedSymbol) case .address: return try .element(Context.resolve(from: resolveOffset(in: machOFile), in: machOFile)) } } - public func resolveOffset(in machOImage: MachOImage) -> Int { + public func resolveOffset(in machOFile: MachO) -> Int { switch self { - case .symbol(let unsolvedSymbol): - unsolvedSymbol.offset - case .address(let address): - Int(address) - machOImage.ptr.int - } - } - - public func resolve(in machOImage: MachOImage) throws -> Resolved { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .address: - return try .element(Context.resolve(from: resolveOffset(in: machOImage), in: machOImage)) + case let .symbol(unsolvedSymbol): + return unsolvedSymbol.offset + case let .address(address): + return numericCast(machOFile.resolveOffset(at: address)) } } - public func resolveAny(in machOFile: MachOFile) throws -> T { - fatalError() - } - - public func resolveAny(in machOImage: MachOImage) throws -> T { + public func resolveAny(in machOFile: MachO) throws -> T { fatalError() } - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - if let symbol = machOFile.resolveBind(fileOffset: fileOffset) { - return .symbol(.init(offset: fileOffset, stringValue: symbol)) - } else { - let resolvedFileOffset = fileOffset - if let rebase = machOFile.resolveRebase(fileOffset: resolvedFileOffset) { - return .address(rebase) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + if let machOFile = machO as? MachOFile { + if let symbol = machOFile.resolveBind(fileOffset: offset) { + return .symbol(.init(offset: offset, stringValue: symbol)) } else { - return try .address(machOFile.readElement(offset: resolvedFileOffset)) + let resolvedFileOffset = offset + if let rebase = machOFile.resolveRebase(fileOffset: resolvedFileOffset) { + return .address(rebase) + } else { + return try .address(machOFile.readElement(offset: resolvedFileOffset)) + } } + } else { + return try .address(machO.readElement(offset: offset)) } } - - public static func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> Self { - return try .address(machOImage.readElement(offset: imageOffset)) - } } diff --git a/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift b/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift index 6a300618..8a8268b3 100644 --- a/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift +++ b/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift @@ -1,7 +1,7 @@ import MachOKit import MachOExtensions -protocol MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache { +package protocol MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache { associatedtype SwiftSection: SwiftSectionRepresentable var swift: SwiftSection { get } diff --git a/Sources/MachOSwiftSection/Utils/MetadataReader.swift b/Sources/MachOSwiftSection/Utils/MetadataReader.swift index e8192b15..9c4bbde0 100644 --- a/Sources/MachOSwiftSection/Utils/MetadataReader.swift +++ b/Sources/MachOSwiftSection/Utils/MetadataReader.swift @@ -4,30 +4,29 @@ import Demangle import MachOFoundation import MachOMacro -@MachOImageAllMembersGenerator public struct MetadataReader { - public static func demangleType(for mangledName: MangledName, in machOFile: MachOFile) throws -> Node { - return try demangle(for: mangledName, kind: .type, in: machOFile) + public static func demangleType(for mangledName: MangledName, in machO: MachO) throws -> Node { + return try demangle(for: mangledName, kind: .type, in: machO) } - public static func demangleSymbol(for mangledName: MangledName, in machOFile: MachOFile) throws -> Node { - return try demangle(for: mangledName, kind: .symbol, in: machOFile) + public static func demangleSymbol(for mangledName: MangledName, in machO: MachO) throws -> Node { + return try demangle(for: mangledName, kind: .symbol, in: machO) } - public static func demangleType(for unsolvedSymbol: Symbol, in machOFile: MachOFile) throws -> Node? { - return try buildContextManglingForSymbol(unsolvedSymbol, in: machOFile) + public static func demangleType(for unsolvedSymbol: Symbol, in machO: MachO) throws -> Node? { + return try buildContextManglingForSymbol(unsolvedSymbol, in: machO) } - public static func demangleSymbol(for unsolvedSymbol: Symbol, in machOFile: MachOFile) throws -> Node? { + public static func demangleSymbol(for unsolvedSymbol: Symbol, in machO: MachO) throws -> Node? { // return try demangle(for: .init(unsolvedSymbol: unsolvedSymbol), kind: .symbol, in: machOFile) - return SymbolCache.shared.demangledNode(for: unsolvedSymbol, in: machOFile) + return SymbolCache.shared.demangledNode(for: unsolvedSymbol, in: machO) } - public static func demangleContext(for context: ContextDescriptorWrapper, in machOFile: MachOFile) throws -> Node { - return try required(buildContextMangling(context: context, in: machOFile)) + public static func demangleContext(for context: ContextDescriptorWrapper, in machO: MachO) throws -> Node { + return try required(buildContextMangling(context: context, in: machO)) } - private static func demangle(for mangledName: MangledName, kind: MangledNameKind, useOpaqueTypeSymbolicReferences: Bool = false, in machOFile: MachOFile) throws -> Node { + private static func demangle(for mangledName: MangledName, kind: MangledNameKind, useOpaqueTypeSymbolicReferences: Bool = false, in machO: MachO) throws -> Node { let stringValue = switch kind { case .type: mangledName.typeStringValue() @@ -46,45 +45,45 @@ public struct MetadataReader { case .context: switch directness { case .direct: - if let context = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(from: offset, in: machOFile) { + if let context = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(from: offset, in: machO) { if context.opaqueTypeDescriptor != nil { // Try to preserve a reference to an OpaqueTypeDescriptor // symbolically, since we'd like to read out and resolve the type ref // to the underlying type if available. result = .init(kind: .opaqueTypeDescriptorSymbolicReference, contents: .index(context.offset.cast())) } else { - result = try buildContextMangling(context: .element(context), in: machOFile) + result = try buildContextMangling(context: .element(context), in: machO) } } case .indirect: let relativePointer = RelativeIndirectSymbolOrElementPointer(relativeOffset: relativeOffset) - if let resolvableElement = try relativePointer.resolve(from: offset, in: machOFile).asOptional { + if let resolvableElement = try relativePointer.resolve(from: offset, in: machO).asOptional { if case let .element(element) = resolvableElement, element.opaqueTypeDescriptor != nil { // Try to preserve a reference to an OpaqueTypeDescriptor // symbolically, since we'd like to read out and resolve the type ref // to the underlying type if available. result = .init(kind: .opaqueTypeDescriptorSymbolicReference, contents: .index(element.offset.cast())) } else { - result = try buildContextMangling(context: resolvableElement, in: machOFile) + result = try buildContextMangling(context: resolvableElement, in: machO) } } } case .accessorFunctionReference: // The symbolic reference points at a resolver function, but we can't // execute code in the target process to resolve it from here. - result = .init(kind: .accessorFunctionReference, contents: .index(address(of: RelativeDirectRawPointer(relativeOffset: relativeOffset).resolveDirectOffset(from: offset), in: machOFile))) + result = .init(kind: .accessorFunctionReference, contents: .index(address(of: RelativeDirectRawPointer(relativeOffset: relativeOffset).resolveDirectOffset(from: offset), in: machO))) case .uniqueExtendedExistentialTypeShape: - let extendedExistentialTypeShape = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(from: offset, in: machOFile) - let existentialType = try extendedExistentialTypeShape.existentialType(in: machOFile).symbolStringValue() + let extendedExistentialTypeShape = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(from: offset, in: machO) + let existentialType = try extendedExistentialTypeShape.existentialType(in: machO).symbolStringValue() result = try .init(kind: .uniqueExtendedExistentialTypeShapeSymbolicReference, children: demangleAsNode(existentialType.insertManglePrefix).children) case .nonUniqueExtendedExistentialTypeShape: - let nonUniqueExtendedExistentialTypeShape = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(from: offset, in: machOFile) - let existentialType = try nonUniqueExtendedExistentialTypeShape.existentialType(in: machOFile).symbolStringValue() + let nonUniqueExtendedExistentialTypeShape = try RelativeDirectPointer(relativeOffset: relativeOffset).resolve(from: offset, in: machO) + let existentialType = try nonUniqueExtendedExistentialTypeShape.existentialType(in: machO).symbolStringValue() result = try .init(kind: .nonUniqueExtendedExistentialTypeShapeSymbolicReference, children: demangleAsNode(existentialType.insertManglePrefix).children) case .objectiveCProtocol: let relativePointer = RelativeDirectPointer(relativeOffset: relativeOffset) - let objcProtocol = try relativePointer.resolve(from: offset, in: machOFile) - let name = try objcProtocol.mangledName(in: machOFile).symbolStringValue() + let objcProtocol = try relativePointer.resolve(from: offset, in: machO) + let name = try objcProtocol.mangledName(in: machO).symbolStringValue() result = try demangleAsNode(name).typeSymbol } return result @@ -102,17 +101,17 @@ public struct MetadataReader { return result } - private static func buildContextMangling(context: SymbolOrElement, in machOFile: MachOFile) throws -> Node? { + private static func buildContextMangling(context: SymbolOrElement, in machO: MachO) throws -> Node? { switch context { case let .symbol(symbol): - return try buildContextManglingForSymbol(symbol, in: machOFile) + return try buildContextManglingForSymbol(symbol, in: machO) case let .element(contextDescriptorProtocol): - return try buildContextMangling(context: contextDescriptorProtocol, in: machOFile) + return try buildContextMangling(context: contextDescriptorProtocol, in: machO) } } - private static func buildContextMangling(context: ContextDescriptorWrapper, in machOFile: MachOFile) throws -> Node? { - guard let demangling = try buildContextDescriptorMangling(context: context, recursionLimit: 50, in: machOFile) else { + private static func buildContextMangling(context: ContextDescriptorWrapper, in machO: MachO) throws -> Node? { + guard let demangling = try buildContextDescriptorMangling(context: context, recursionLimit: 50, in: machO) else { return nil } let top: Node @@ -128,13 +127,13 @@ public struct MetadataReader { return top } - private static func buildContextDescriptorMangling(context: SymbolOrElement, recursionLimit: Int, in machOFile: MachOFile) throws -> Node? { + private static func buildContextDescriptorMangling(context: SymbolOrElement, recursionLimit: Int, in machO: MachO) throws -> Node? { guard recursionLimit > 0 else { return nil } switch context { case let .symbol(symbol): - return try buildContextManglingForSymbol(symbol, in: machOFile) + return try buildContextManglingForSymbol(symbol, in: machO) case let .element(contextDescriptor): - var demangleSymbol = try buildContextDescriptorMangling(context: contextDescriptor, recursionLimit: recursionLimit, in: machOFile) + var demangleSymbol = try buildContextDescriptorMangling(context: contextDescriptor, recursionLimit: recursionLimit, in: machO) if demangleSymbol?.kind == .type { demangleSymbol = demangleSymbol?.children.first @@ -143,16 +142,16 @@ public struct MetadataReader { } } - private static func buildContextDescriptorMangling(context: ContextDescriptorWrapper, recursionLimit: Int, in machOFile: MachOFile) throws -> Node? { + private static func buildContextDescriptorMangling(context: ContextDescriptorWrapper, recursionLimit: Int, in machO: MachO) throws -> Node? { guard recursionLimit > 0 else { return nil } - var parentDescriptorResult = try context.parent(in: machOFile) + var parentDescriptorResult = try context.parent(in: machO) var demangledParentNode: Node? - var nameNode = try adoptAnonymousContextName(context: context, parentContextRef: &parentDescriptorResult, outSymbol: &demangledParentNode, in: machOFile) + var nameNode = try adoptAnonymousContextName(context: context, parentContextRef: &parentDescriptorResult, outSymbol: &demangledParentNode, in: machO) // guard let parentDescriptorResult else { return nil } var parentDemangling: Node? if let parentDescriptor = parentDescriptorResult { - parentDemangling = try buildContextDescriptorMangling(context: parentDescriptor, recursionLimit: recursionLimit - 1, in: machOFile) + parentDemangling = try buildContextDescriptorMangling(context: parentDescriptor, recursionLimit: recursionLimit - 1, in: machO) if parentDemangling == nil, demangledParentNode == nil { return nil } @@ -168,7 +167,7 @@ public struct MetadataReader { if nameNode != nil { return true } else if let namedContext = context.namedContextDescriptor { - nameNode = try .init(kind: .identifier, contents: .name(namedContext.name(in: machOFile))) + nameNode = try .init(kind: .identifier, contents: .name(namedContext.name(in: machO))) return true } else { return false @@ -191,29 +190,29 @@ public struct MetadataReader { case .extension: guard let parentDemangling else { return nil } guard let extensionContext = context.extensionContextDescriptor else { return nil } - guard let extendedContext = try extensionContext.extendedContext(in: machOFile) else { return nil } - guard let demangledExtendedContext = try demangle(for: extendedContext, kind: .type, in: machOFile).extensionSymbol else { return nil } + guard let extendedContext = try extensionContext.extendedContext(in: machO) else { return nil } + guard let demangledExtendedContext = try demangle(for: extendedContext, kind: .type, in: machO).extensionSymbol else { return nil } let demangling = Node(kind: .extension, children: [parentDemangling, demangledExtendedContext]) - if let requirements = try extensionContext.genericContext(in: machOFile)?.requirements { + if let requirements = try extensionContext.genericContext(in: machO)?.requirements { let signatureNode = Node(kind: .dependentGenericSignature) var failed = false for requirement in requirements { if failed { break } - let subject = try demangle(for: requirement.paramManagedName(in: machOFile), kind: .type, in: machOFile) + let subject = try demangle(for: requirement.paramManagedName(in: machO), kind: .type, in: machO) let offset = requirement.offset(of: \.content) switch requirement.content { case let .protocol(relativeProtocolDescriptorPointer): - guard let proto = try? readProtocol(offset: offset, pointer: relativeProtocolDescriptorPointer, in: machOFile) else { + guard let proto = try? readProtocol(offset: offset, pointer: relativeProtocolDescriptorPointer, in: machO) else { failed = true break } let requirementNode = Node(kind: .dependentGenericConformanceRequirement, children: [subject, proto]) signatureNode.addChild(requirementNode) case let .type(relativeDirectPointer): - let mangledName = try relativeDirectPointer.resolve(from: offset, in: machOFile) - guard let type = try? demangle(for: mangledName, kind: .type, in: machOFile) else { + let mangledName = try relativeDirectPointer.resolve(from: offset, in: machO) + guard let type = try? demangle(for: mangledName, kind: .type, in: machO) else { failed = true break } @@ -258,11 +257,11 @@ public struct MetadataReader { return nil } guard let moduleContext = context.moduleContextDescriptor else { return nil } - return try .init(kind: .module, contents: .name(moduleContext.name(in: machOFile))) + return try .init(kind: .module, contents: .name(moduleContext.name(in: machO))) case .opaqueType: guard let parentDescriptorResult else { return nil } if parentDemangling?.kind == .anonymousContext { - guard var mangledNode = try demangleAnonymousContextName(context: parentDescriptorResult, in: machOFile) else { + guard var mangledNode = try demangleAnonymousContextName(context: parentDescriptorResult, in: machO) else { return nil } if mangledNode.kind == .global { @@ -290,7 +289,7 @@ public struct MetadataReader { return demangling } - private static func buildContextManglingForSymbol(_ symbol: Symbol, in machOFile: MachOFile) throws -> Node? { + private static func buildContextManglingForSymbol(_ symbol: Symbol, in machO: MachO) throws -> Node? { var demangledSymbol = try demangleAsNode(symbol.stringValue) if demangledSymbol.kind == .global { demangledSymbol = demangledSymbol.children[0] @@ -307,13 +306,13 @@ public struct MetadataReader { return demangledSymbol } - private static func adoptAnonymousContextName(context: ContextDescriptorWrapper, parentContextRef: inout SymbolOrElement?, outSymbol: inout Node?, in machOFile: MachOFile) throws -> Node? { + private static func adoptAnonymousContextName(context: ContextDescriptorWrapper, parentContextRef: inout SymbolOrElement?, outSymbol: inout Node?, in machO: MachO) throws -> Node? { outSymbol = nil guard let parentContextLocalRef = parentContextRef else { return nil } guard case let .element(parentContext) = parentContextRef else { return nil } guard context.isType || context.isProtocol else { return nil } // guard case let .anonymous(anonymousParent) = parentContext else { return nil } - guard var mangledNode = try demangleAnonymousContextName(context: parentContextLocalRef, in: machOFile) else { return nil } + guard var mangledNode = try demangleAnonymousContextName(context: parentContextLocalRef, in: machO) else { return nil } if mangledNode.kind == .global { mangledNode = mangledNode.children[0] } @@ -328,32 +327,32 @@ public struct MetadataReader { guard identifierNode.kind == .identifier, identifierNode.contents.hasName else { return nil } guard let namedContext = context.namedContextDescriptor else { return nil } - guard try namedContext.name(in: machOFile) == identifierNode.contents.name else { return nil } + guard try namedContext.name(in: machO) == identifierNode.contents.name else { return nil } - parentContextRef = try parentContext.parent(in: machOFile) + parentContextRef = try parentContext.parent(in: machO) outSymbol = mangledNode.children[0] return nameChild } - private static func demangleAnonymousContextName(context: SymbolOrElement, in machOFile: MachOFile) throws -> Node? { - guard case let .element(.anonymous(context)) = context, let mangledName = try context.mangledName(in: machOFile) else { return nil } - return try demangle(for: mangledName, kind: .symbol, in: machOFile) + private static func demangleAnonymousContextName(context: SymbolOrElement, in machO: MachO) throws -> Node? { + guard case let .element(.anonymous(context)) = context, let mangledName = try context.mangledName(in: machO) else { return nil } + return try demangle(for: mangledName, kind: .symbol, in: machO) } - private static func readProtocol(offset: Int, pointer: RelativeProtocolDescriptorPointer, in machOFile: MachOFile) throws -> Node? { + private static func readProtocol(offset: Int, pointer: RelativeProtocolDescriptorPointer, in machO: MachO) throws -> Node? { switch pointer { case let .objcPointer(objcPointer): - let objcPrefixElement = try objcPointer.resolve(from: offset, in: machOFile) + let objcPrefixElement = try objcPointer.resolve(from: offset, in: machO) switch objcPrefixElement { case let .symbol(symbol): - return try buildContextManglingForSymbol(symbol, in: machOFile) + return try buildContextManglingForSymbol(symbol, in: machO) case let .element(objcPrefix): - let mangledName = try objcPrefix.mangledName(in: machOFile) + let mangledName = try objcPrefix.mangledName(in: machO) let name = mangledName.symbolStringValue() if name.starts(with: "_TtP") { - var demangled = try demangle(for: mangledName, kind: .symbol, in: machOFile) + var demangled = try demangle(for: mangledName, kind: .symbol, in: machO) while demangled.kind == .global || demangled.kind == .typeMangling || demangled.kind == .type || @@ -371,12 +370,12 @@ public struct MetadataReader { } } case let .swiftPointer(swiftPointer): - let resolvableProtocolDescriptor = try swiftPointer.resolve(from: offset, in: machOFile) + let resolvableProtocolDescriptor = try swiftPointer.resolve(from: offset, in: machO) switch resolvableProtocolDescriptor { case let .symbol(symbol): - return try buildContextManglingForSymbol(symbol, in: machOFile) + return try buildContextManglingForSymbol(symbol, in: machO) case let .element(context): - return try buildContextMangling(context: .protocol(context), in: machOFile) + return try buildContextMangling(context: .protocol(context), in: machO) } } } diff --git a/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift b/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift index 34051c31..68a6792f 100644 --- a/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift +++ b/Sources/MachOSwiftSection/Utils/PrimitiveTypeMapping.swift @@ -7,8 +7,7 @@ import MachOMacro package class PrimitiveTypeMapping { private var storage: [String: String] = [:] - @MachOImageGenerator - package init(machO: MachOFile) throws { + package init(machO: MachO) throws { let builtinTypes = try machO.swift.builtinTypeDescriptors.map { try BuiltinType(descriptor: $0, in: machO) } for builtinType in builtinTypes { guard let typeName = builtinType.typeName else { continue } diff --git a/Sources/MachOSymbols/MachO+Symbol.swift b/Sources/MachOSymbols/MachO+Symbol.swift index 3f34c387..a337b62e 100644 --- a/Sources/MachOSymbols/MachO+Symbol.swift +++ b/Sources/MachOSymbols/MachO+Symbol.swift @@ -1,13 +1,7 @@ import MachOKit import MachOExtensions -extension MachOFile { - package func symbols(offset: Int) -> MachOSymbols.Symbols? { - return SymbolCache.shared.symbols(for: offset, in: self) - } -} - -extension MachOImage { +extension MachORepresentableWithCache { package func symbols(offset: Int) -> MachOSymbols.Symbols? { return SymbolCache.shared.symbols(for: offset, in: self) } diff --git a/Sources/MachOSymbols/Symbol.swift b/Sources/MachOSymbols/Symbol.swift index ef1efaf1..85d8bc3e 100644 --- a/Sources/MachOSymbols/Symbol.swift +++ b/Sources/MachOSymbols/Symbol.swift @@ -13,14 +13,12 @@ public struct Symbol: Resolvable, Hashable { self.stringValue = stringValue } - @MachOImageGenerator - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - try required(resolve(from: fileOffset, in: machOFile)) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + try required(resolve(from: fileOffset, in: machO)) } - @MachOImageGenerator - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self? { - if let symbol = machOFile.symbols(offset: fileOffset)?.first { + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? { + if let symbol = machO.symbols(offset: fileOffset)?.first { return symbol } return nil diff --git a/Sources/MachOSymbols/SymbolOrElement.swift b/Sources/MachOSymbols/SymbolOrElement.swift index b2d29d2d..bdcb91f2 100644 --- a/Sources/MachOSymbols/SymbolOrElement.swift +++ b/Sources/MachOSymbols/SymbolOrElement.swift @@ -33,30 +33,22 @@ public enum SymbolOrElement: Resolvable { } } - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> SymbolOrElement { - if let symbol = machOFile.resolveBind(fileOffset: fileOffset) { + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> SymbolOrElement { + if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: fileOffset) { return .symbol(.init(offset: fileOffset, stringValue: symbol)) } else { - return try .element(.resolve(from: fileOffset, in: machOFile)) + return try .element(.resolve(from: fileOffset, in: machO)) } } - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> SymbolOrElement? { - if let symbol = machOFile.resolveBind(fileOffset: fileOffset) { + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> SymbolOrElement? { + if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: fileOffset) { return .symbol(.init(offset: fileOffset, stringValue: symbol)) } else { - return try Element.resolve(from: fileOffset, in: machOFile).map { .element($0) } + return try Element.resolve(from: fileOffset, in: machO).map { .element($0) } } } - public static func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> SymbolOrElement { - return try .element(.resolve(from: imageOffset, in: machOImage)) - } - - public static func resolve(from imageOffset: Int, in machOImage: MachOImage) throws -> SymbolOrElement? { - return try Element.resolve(from: imageOffset, in: machOImage).map { .element($0) } - } - public func map(_ transform: (Element) throws -> T) rethrows -> SymbolOrElement { switch self { case .symbol(let unsolvedSymbol): diff --git a/Sources/MachOSymbols/Symbols.swift b/Sources/MachOSymbols/Symbols.swift index 711c0f61..e8d84d5c 100644 --- a/Sources/MachOSymbols/Symbols.swift +++ b/Sources/MachOSymbols/Symbols.swift @@ -13,14 +13,12 @@ public struct Symbols: Resolvable { self._storage = symbols } - @MachOImageGenerator - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self { - try required(resolve(from: fileOffset, in: machOFile)) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { + try required(resolve(from: fileOffset, in: machO)) } - @MachOImageGenerator - public static func resolve(from fileOffset: Int, in machOFile: MachOFile) throws -> Self? { - return machOFile.symbols(offset: fileOffset) + public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? { + return machO.symbols(offset: fileOffset) } } diff --git a/Tests/SwiftDumpTests/DyldCacheDumpTests.swift b/Tests/SwiftDumpTests/DyldCacheDumpTests.swift index 5ca03dbe..6099ec7f 100644 --- a/Tests/SwiftDumpTests/DyldCacheDumpTests.swift +++ b/Tests/SwiftDumpTests/DyldCacheDumpTests.swift @@ -9,7 +9,7 @@ import MachOFoundation @Suite(.serialized) final class DyldCacheDumpTests: DyldCacheTests, DumpableTests { - override class var cacheImageName: MachOImageName { .SwiftUI } +// override class var cacheImageName: MachOImageName { .SwiftUI } } extension DyldCacheDumpTests { From 0cf6370b7880d869f42e3644c3cd210fa9750797 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 3 Jul 2025 17:53:59 +0800 Subject: [PATCH 4/8] Renaming --- .../LocatableLayoutWrapper.swift | 2 +- Sources/MachOExtensions/MachONamespace.swift | 12 ++-- .../MachOExtensions/MachORepresentable+.swift | 4 +- .../MachORepresentableWithCache.swift | 1 + Sources/MachOMacro/MachOMacro.swift | 10 ++-- Sources/MachOPointer/Pointer.swift | 16 +++--- .../Protocol/PointerProtocol.swift | 8 +-- .../RelativeDirectPointerProtocol.swift | 20 +++---- .../RelativeIndirectPointerProtocol.swift | 30 +++++----- .../Protocol/RelativeIndirectType.swift | 6 +- ...veIndirectablePointerIntPairProtocol.swift | 4 +- .../RelativeIndirectablePointerProtocol.swift | 36 ++++++------ .../Protocol/RelativePointerProtocol.swift | 6 +- Sources/MachOReading/Reading/DyldCache+.swift | 2 - Sources/MachOReading/Resolvable.swift | 24 ++++---- .../Models/Anonymous/AnonymousContext.swift | 8 +-- .../AnonymousContextDescriptorProtocol.swift | 8 +-- .../AssociatedType/AssociatedType.swift | 8 +-- .../AssociatedTypeDescriptor.swift | 12 ++-- .../AssociatedType/AssociatedTypeRecord.swift | 8 +-- .../BuiltinType/BuiltinTypeDescriptor.swift | 4 +- .../ContextDescriptorWrapper.swift | 28 +++++----- .../Models/Mangling/MangledName.swift | 14 ++--- .../Models/Protocol/Protocol.swift | 4 +- .../ProtocolConformance.swift | 6 +- .../Models/Type/Enum/Enum.swift | 6 +- .../Models/Type/Struct/Struct.swift | 10 ++-- .../Models/Type/TypeReference.swift | 10 ++-- .../Pointer/SymbolOrElementPointer.swift | 10 ++-- Sources/MachOSymbols/Symbol.swift | 8 +-- Sources/MachOSymbols/SymbolOrElement.swift | 16 +++--- Sources/MachOSymbols/Symbols.swift | 8 +-- .../Dumpable/AssociatedType+Dumpable.swift | 22 ++++---- .../SwiftDump/Dumpable/Class+Dumpable.swift | 55 +++++++++---------- .../SwiftDump/Dumpable/Enum+Dumpable.swift | 27 +++++---- .../Dumpable/Protocol+Dumpable.swift | 23 ++++---- .../ProtocolConformance+Dumpable.swift | 52 ++++++++---------- .../Protocols/ConformedDumpable.swift | 7 +-- .../Dumpable/Protocols/Dumpable.swift | 4 +- .../Dumpable/Protocols/NamedDumpable.swift | 4 +- .../SwiftDump/Dumpable/Struct+Dumpable.swift | 25 ++++----- .../Dumper/ProtocolConformanceDumper.swift | 40 +++++++------- .../ContextDescriptorWrapper+Dump.swift | 6 +- .../Extensions/GenericContext+Dump.swift | 37 ++++++------- .../Extensions/ResilientSuperclass+Dump.swift | 16 +++--- 45 files changed, 322 insertions(+), 345 deletions(-) diff --git a/Sources/MachOExtensions/LocatableLayoutWrapper.swift b/Sources/MachOExtensions/LocatableLayoutWrapper.swift index fc68b24b..66925457 100644 --- a/Sources/MachOExtensions/LocatableLayoutWrapper.swift +++ b/Sources/MachOExtensions/LocatableLayoutWrapper.swift @@ -7,7 +7,7 @@ public protocol LocatableLayoutWrapper: LayoutWrapper, Sendable { } extension LocatableLayoutWrapper { - public func offset(of keyPath: KeyPath) -> Int { + package func offset(of keyPath: KeyPath) -> Int { return offset + MemoryLayout.offset(of: keyPath)! } } diff --git a/Sources/MachOExtensions/MachONamespace.swift b/Sources/MachOExtensions/MachONamespace.swift index 62a767c8..0c4f6598 100644 --- a/Sources/MachOExtensions/MachONamespace.swift +++ b/Sources/MachOExtensions/MachONamespace.swift @@ -1,22 +1,22 @@ import Foundation -package struct MachONamespace { - package let base: Base +public struct MachONamespace { + public let base: Base - package init(_ base: Base) { + public init(_ base: Base) { self.base = base } } -package protocol MachONamespacing {} +public protocol MachONamespacing {} extension MachONamespacing { - package var machO: MachONamespace { + public var machO: MachONamespace { set {} get { MachONamespace(self) } } - package static var machO: MachONamespace.Type { + public static var machO: MachONamespace.Type { set {} get { MachONamespace.self } } diff --git a/Sources/MachOExtensions/MachORepresentable+.swift b/Sources/MachOExtensions/MachORepresentable+.swift index 3f0f472a..56928d6c 100644 --- a/Sources/MachOExtensions/MachORepresentable+.swift +++ b/Sources/MachOExtensions/MachORepresentable+.swift @@ -2,11 +2,9 @@ import Foundation import MachOKit import MachOMacro -@MachOImageAllMembersGenerator extension MachORepresentable { package func _section( - for name: String, - in machOFile: MachOFile + for name: String ) -> (any SectionProtocol)? { sections.first( where: { diff --git a/Sources/MachOExtensions/MachORepresentableWithCache.swift b/Sources/MachOExtensions/MachORepresentableWithCache.swift index d1748dce..f1db0141 100644 --- a/Sources/MachOExtensions/MachORepresentableWithCache.swift +++ b/Sources/MachOExtensions/MachORepresentableWithCache.swift @@ -26,6 +26,7 @@ extension MachOImage { Int(address) - ptr.int } } + extension MachOFile: MachORepresentableWithCache { public var identifier: MachOTargetIdentifier { .file(imagePath) diff --git a/Sources/MachOMacro/MachOMacro.swift b/Sources/MachOMacro/MachOMacro.swift index b3309464..61b52923 100644 --- a/Sources/MachOMacro/MachOMacro.swift +++ b/Sources/MachOMacro/MachOMacro.swift @@ -3,8 +3,8 @@ @attached(extension, names: named(offset)) public macro Layout() = #externalMacro(module: "MachOMacroPlugin", type: "LayoutMacro") -@attached(peer, names: arbitrary) -public macro MachOImageGenerator() = #externalMacro(module: "MachOMacroPlugin", type: "MachOImageGeneratorMacro") - -@attached(member, names: arbitrary) -public macro MachOImageAllMembersGenerator() = #externalMacro(module: "MachOMacroPlugin", type: "MachOImageAllMembersGeneratorMacro") +//@attached(peer, names: arbitrary) +//public macro MachOImageGenerator() = #externalMacro(module: "MachOMacroPlugin", type: "MachOImageGeneratorMacro") +// +//@attached(member, names: arbitrary) +//public macro MachOImageAllMembersGenerator() = #externalMacro(module: "MachOMacroPlugin", type: "MachOImageAllMembersGeneratorMacro") diff --git a/Sources/MachOPointer/Pointer.swift b/Sources/MachOPointer/Pointer.swift index c6c89e5d..72e61f68 100644 --- a/Sources/MachOPointer/Pointer.swift +++ b/Sources/MachOPointer/Pointer.swift @@ -4,20 +4,20 @@ import MachOExtensions public struct Pointer: RelativeIndirectType, PointerProtocol { public typealias Resolved = Pointee - + public let address: UInt64 - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - if let machOFile = machO as? MachOFile, let rebase = machOFile.resolveRebase(fileOffset: fileOffset.cast()) { + public init(address: UInt64) { + self.address = address + } + + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + if let machOFile = machO as? MachOFile, let rebase = machOFile.resolveRebase(fileOffset: offset.cast()) { return .init(address: rebase) } else { - return try machO.readElement(offset: fileOffset) + return try machO.readElement(offset: offset) } } - - public init(address: UInt64) { - self.address = address - } } public typealias RawPointer = Pointer diff --git a/Sources/MachOPointer/Protocol/PointerProtocol.swift b/Sources/MachOPointer/Protocol/PointerProtocol.swift index bb256ca7..4c109205 100644 --- a/Sources/MachOPointer/Protocol/PointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/PointerProtocol.swift @@ -14,12 +14,12 @@ public protocol PointerProtocol: Resolvable, Sendable { } extension PointerProtocol { - public func resolveAny(in machOFile: MachO) throws -> T { - return try T.resolve(from: resolveOffset(in: machOFile), in: machOFile) + public func resolveAny(in machO: MachO) throws -> T { + return try T.resolve(from: resolveOffset(in: machO), in: machO) } - public func resolve(in machOFile: MachO) throws -> Pointee { - return try Pointee.resolve(from: resolveOffset(in: machOFile), in: machOFile) + public func resolve(in machO: MachO) throws -> Pointee { + return try Pointee.resolve(from: resolveOffset(in: machO), in: machO) } public func resolveOffset(in machO: MachO) -> Int { diff --git a/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift index 15f3e7f2..9b77a4b3 100644 --- a/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift @@ -7,26 +7,26 @@ public protocol RelativeDirectPointerProtocol: RelativePointerProtocol extension RelativeDirectPointerProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { - return try resolveDirect(from: fileOffset, in: machOFile) + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { + return try resolveDirect(from: offset, in: machO) } - func resolveDirect(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { - return try Pointee.resolve(from: resolveDirectOffset(from: fileOffset), in: machOFile) + func resolveDirect(from offset: Int, in machO: MachO) throws -> Pointee { + return try Pointee.resolve(from: resolveDirectOffset(from: offset), in: machO) } - public func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T { - return try resolveDirectAny(from: fileOffset, in: machOFile) + public func resolveAny(from offset: Int, in machO: MachO) throws -> T { + return try resolveDirectAny(from: offset, in: machO) } - func resolveDirectAny(from fileOffset: Int, in machOFile: MachO) throws -> T { - return try T.resolve(from: resolveDirectOffset(from: fileOffset), in: machOFile) + func resolveDirectAny(from offset: Int, in machO: MachO) throws -> T { + return try T.resolve(from: resolveDirectOffset(from: offset), in: machO) } } extension RelativeDirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) + return try resolve(from: offset, in: machO) } } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift index 8dc6bd07..0e15b305 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift @@ -6,38 +6,38 @@ import MachOExtensions public protocol RelativeIndirectPointerProtocol: RelativePointerProtocol { associatedtype IndirectType: RelativeIndirectType where IndirectType.Resolved == Pointee - func resolveIndirectOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int + func resolveIndirectOffset(from offset: Int, in machO: MachO) throws -> Int } extension RelativeIndirectPointerProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { - return try resolveIndirect(from: fileOffset, in: machOFile) + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { + return try resolveIndirect(from: offset, in: machO) } - func resolveIndirect(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { - return try resolveIndirectType(from: fileOffset, in: machOFile).resolve(in: machOFile) + func resolveIndirect(from offset: Int, in machO: MachO) throws -> Pointee { + return try resolveIndirectType(from: offset, in: machO).resolve(in: machO) } - public func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T { - return try resolveIndirectAny(from: fileOffset, in: machOFile) + public func resolveAny(from offset: Int, in machO: MachO) throws -> T { + return try resolveIndirectAny(from: offset, in: machO) } - func resolveIndirectAny(from fileOffset: Int, in machOFile: MachO) throws -> T { - return try resolveIndirectType(from: fileOffset, in: machOFile).resolveAny(in: machOFile) + func resolveIndirectAny(from offset: Int, in machO: MachO) throws -> T { + return try resolveIndirectType(from: offset, in: machO).resolveAny(in: machO) } - public func resolveIndirectType(from fileOffset: Int, in machOFile: MachO) throws -> IndirectType { - return try .resolve(from: resolveDirectOffset(from: fileOffset), in: machOFile) + public func resolveIndirectType(from offset: Int, in machO: MachO) throws -> IndirectType { + return try .resolve(from: resolveDirectOffset(from: offset), in: machO) } - public func resolveIndirectOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int { - return try resolveIndirectType(from: fileOffset, in: machOFile).resolveOffset(in: machOFile) + public func resolveIndirectOffset(from offset: Int, in machO: MachO) throws -> Int { + return try resolveIndirectType(from: offset, in: machO).resolveOffset(in: machO) } } extension RelativeIndirectPointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) + return try resolve(from: offset, in: machO) } } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectType.swift b/Sources/MachOPointer/Protocol/RelativeIndirectType.swift index 10e4cc24..cf0fb973 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectType.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectType.swift @@ -5,7 +5,7 @@ import MachOExtensions public protocol RelativeIndirectType: Resolvable { associatedtype Resolved: Resolvable - func resolve(in machOFile: MachO) throws -> Resolved - func resolveAny(in machOFile: MachO) throws -> T - func resolveOffset(in machOFile: MachO) -> Int + func resolve(in machO: MachO) throws -> Resolved + func resolveAny(in machO: MachO) throws -> T + func resolveOffset(in machO: MachO) -> Int } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift index f9f5e1a5..f20fb436 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift @@ -36,8 +36,8 @@ extension RelativeIndirectablePointerIntPairProtocol { } extension RelativeIndirectablePointerIntPairProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) + return try resolve(from: offset, in: machO) } } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift index 160c33b4..8078beac 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift @@ -6,7 +6,7 @@ import MachOExtensions public protocol RelativeIndirectablePointerProtocol: RelativeDirectPointerProtocol, RelativeIndirectPointerProtocol { var relativeOffsetPlusIndirect: Offset { get } var isIndirect: Bool { get } - func resolveIndirectableOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int + func resolveIndirectableOffset(from offset: Int, in machO: MachO) throws -> Int } extension RelativeIndirectablePointerProtocol { @@ -20,44 +20,44 @@ extension RelativeIndirectablePointerProtocol { } extension RelativeIndirectablePointerProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { - return try resolveIndirectable(from: fileOffset, in: machOFile) + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { + return try resolveIndirectable(from: offset, in: machO) } - public func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T { - return try resolveIndirectableAny(from: fileOffset, in: machOFile) + public func resolveAny(from offset: Int, in machO: MachO) throws -> T { + return try resolveIndirectableAny(from: offset, in: machO) } - func resolveIndirectable(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { + func resolveIndirectable(from offset: Int, in machO: MachO) throws -> Pointee { if isIndirect { - return try resolveIndirect(from: fileOffset, in: machOFile) + return try resolveIndirect(from: offset, in: machO) } else { - return try resolveDirect(from: fileOffset, in: machOFile) + return try resolveDirect(from: offset, in: machO) } } - public func resolveIndirectableType(from fileOffset: Int, in machOFile: MachO) throws -> IndirectType? { + public func resolveIndirectableType(from offset: Int, in machO: MachO) throws -> IndirectType? { guard isIndirect else { return nil } - return try resolveIndirectableType(from: fileOffset, in: machOFile) + return try resolveIndirectableType(from: offset, in: machO) } - func resolveIndirectableAny(from fileOffset: Int, in machOFile: MachO) throws -> T { + func resolveIndirectableAny(from offset: Int, in machO: MachO) throws -> T { if isIndirect { - return try resolveIndirectAny(from: fileOffset, in: machOFile) + return try resolveIndirectAny(from: offset, in: machO) } else { - return try resolveDirectAny(from: fileOffset, in: machOFile) + return try resolveDirectAny(from: offset, in: machO) } } - public func resolveIndirectableOffset(from fileOffset: Int, in machOFile: MachO) throws -> Int { - guard let indirectType = try resolveIndirectableType(from: fileOffset, in: machOFile) else { return resolveDirectOffset(from: fileOffset) } - return indirectType.resolveOffset(in: machOFile) + public func resolveIndirectableOffset(from offset: Int, in machO: MachO) throws -> Int { + guard let indirectType = try resolveIndirectableType(from: offset, in: machO) else { return resolveDirectOffset(from: offset) } + return indirectType.resolveOffset(in: machO) } } extension RelativeIndirectablePointerProtocol where Pointee: OptionalProtocol { - public func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee { + public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { guard isValid else { return nil } - return try resolve(from: fileOffset, in: machOFile) + return try resolve(from: offset, in: machO) } } diff --git a/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift index 7980c702..82c6ee87 100644 --- a/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift @@ -8,10 +8,8 @@ public protocol RelativePointerProtocol: Sendable { var relativeOffset: Offset { get } - func resolve(from fileOffset: Int, in machOFile: MachO) throws -> Pointee - - func resolveAny(from fileOffset: Int, in machOFile: MachO) throws -> T - + func resolve(from offset: Int, in machO: MachO) throws -> Pointee + func resolveAny(from offset: Int, in machO: MachO) throws -> T func resolveDirectOffset(from offset: Int) -> Int } diff --git a/Sources/MachOReading/Reading/DyldCache+.swift b/Sources/MachOReading/Reading/DyldCache+.swift index cc3d7ef7..0fe1a89a 100644 --- a/Sources/MachOReading/Reading/DyldCache+.swift +++ b/Sources/MachOReading/Reading/DyldCache+.swift @@ -29,6 +29,4 @@ extension DyldCache { return fileIO } } - - } diff --git a/Sources/MachOReading/Resolvable.swift b/Sources/MachOReading/Resolvable.swift index 361ec61a..34fcf710 100644 --- a/Sources/MachOReading/Resolvable.swift +++ b/Sources/MachOReading/Resolvable.swift @@ -3,24 +3,24 @@ import MachOExtensions import MachOMacro public protocol Resolvable { - static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self - static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? + static func resolve(from offset: Int, in machO: MachO) throws -> Self + static func resolve(from offset: Int, in machO: MachO) throws -> Self? } extension Resolvable { - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - return try machO.readElement(offset: fileOffset) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + return try machO.readElement(offset: offset) } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? { - let result: Self = try resolve(from: fileOffset, in: machO) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self? { + let result: Self = try resolve(from: offset, in: machO) return .some(result) } } extension Optional: Resolvable where Wrapped: Resolvable { - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - let result: Wrapped? = try Wrapped.resolve(from: fileOffset, in: machO) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + let result: Wrapped? = try Wrapped.resolve(from: offset, in: machO) if let result { return .some(result) } else { @@ -30,14 +30,14 @@ extension Optional: Resolvable where Wrapped: Resolvable { } extension String: Resolvable { - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - return try machO.readString(offset: fileOffset) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + return try machO.readString(offset: offset) } } extension Resolvable where Self: LocatableLayoutWrapper { - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - try machO.readWrapperElement(offset: fileOffset) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + try machO.readWrapperElement(offset: offset) } } diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift index 0fb39fa8..c8a99143 100644 --- a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift +++ b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift @@ -8,11 +8,11 @@ public struct AnonymousContext { public let genericContext: GenericContext? public let mangledName: MangledName? - public init(descriptor: AnonymousContextDescriptor, in machOFile: MachO) throws { + public init(descriptor: AnonymousContextDescriptor, in machO: MachO) throws { self.descriptor = descriptor var currentOffset = descriptor.offset + descriptor.layoutSize - let genericContext = try descriptor.genericContext(in: machOFile) + let genericContext = try descriptor.genericContext(in: machO) if let genericContext { currentOffset += genericContext.size @@ -20,8 +20,8 @@ public struct AnonymousContext { self.genericContext = genericContext if descriptor.hasMangledName { - let mangledNamePointer: RelativeDirectPointer = try machOFile.readElement(offset: currentOffset) - self.mangledName = try mangledNamePointer.resolve(from: currentOffset, in: machOFile) + let mangledNamePointer: RelativeDirectPointer = try machO.readElement(offset: currentOffset) + self.mangledName = try mangledNamePointer.resolve(from: currentOffset, in: machO) currentOffset += MemoryLayout>.size } else { self.mangledName = nil diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift index 4d41edca..3abd903b 100644 --- a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift +++ b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift @@ -6,16 +6,16 @@ public protocol AnonymousContextDescriptorProtocol: ContextDescriptorProtocol wh extension AnonymousContextDescriptorProtocol { - public func mangledName(in machOFile: MachO) throws -> MangledName? { + public func mangledName(in machO: MachO) throws -> MangledName? { guard hasMangledName else { return nil } var currentOffset = offset + layoutSize - if let genericContext = try genericContext(in: machOFile) { + if let genericContext = try genericContext(in: machO) { currentOffset += genericContext.size } - let mangledNamePointer: RelativeDirectPointer = try machOFile.readElement(offset: currentOffset) - return try mangledNamePointer.resolve(from: currentOffset, in: machOFile) + let mangledNamePointer: RelativeDirectPointer = try machO.readElement(offset: currentOffset) + return try mangledNamePointer.resolve(from: currentOffset, in: machO) } public var hasMangledName: Bool { diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift index 99a45041..44c9c750 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift +++ b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift @@ -13,11 +13,11 @@ public struct AssociatedType: TopLevelType { public let records: [AssociatedTypeRecord] - public init(descriptor: AssociatedTypeDescriptor, in machOFile: MachO) throws { + public init(descriptor: AssociatedTypeDescriptor, in machO: MachO) throws { self.descriptor = descriptor - self.conformingTypeName = try descriptor.conformingTypeName(in: machOFile) - self.protocolTypeName = try descriptor.protocolTypeName(in: machOFile) - self.records = try descriptor.associatedTypeRecords(in: machOFile) + self.conformingTypeName = try descriptor.conformingTypeName(in: machO) + self.protocolTypeName = try descriptor.protocolTypeName(in: machO) + self.records = try descriptor.associatedTypeRecords(in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift index 51183bf6..41e3bbd7 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift @@ -21,16 +21,16 @@ public struct AssociatedTypeDescriptor: ResolvableLocatableLayoutWrapper { } extension AssociatedTypeDescriptor { - public func conformingTypeName(in machOFile: MachO) throws -> MangledName { - return try layout.conformingTypeName.resolve(from: offset(of: \.conformingTypeName), in: machOFile) + public func conformingTypeName(in machO: MachO) throws -> MangledName { + return try layout.conformingTypeName.resolve(from: offset(of: \.conformingTypeName), in: machO) } - public func protocolTypeName(in machOFile: MachO) throws -> MangledName { - return try layout.protocolTypeName.resolve(from: offset(of: \.protocolTypeName), in: machOFile) + public func protocolTypeName(in machO: MachO) throws -> MangledName { + return try layout.protocolTypeName.resolve(from: offset(of: \.protocolTypeName), in: machO) } - public func associatedTypeRecords(in machOFile: MachO) throws -> [AssociatedTypeRecord] { - return try machOFile.readWrapperElements(offset: offset + layoutSize, numberOfElements: layout.numAssociatedTypes.cast()) + public func associatedTypeRecords(in machO: MachO) throws -> [AssociatedTypeRecord] { + return try machO.readWrapperElements(offset: offset + layoutSize, numberOfElements: layout.numAssociatedTypes.cast()) } } diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift index 7129b95c..1609df25 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift +++ b/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift @@ -20,11 +20,11 @@ public struct AssociatedTypeRecord: ResolvableLocatableLayoutWrapper { } extension AssociatedTypeRecord { - public func name(in machOFile: MachO) throws -> String { - return try layout.name.resolve(from: offset(of: \.name), in: machOFile) + public func name(in machO: MachO) throws -> String { + return try layout.name.resolve(from: offset(of: \.name), in: machO) } - public func substitutedTypeName(in machOFile: MachO) throws -> MangledName { - return try layout.substitutedTypeName.resolve(from: offset(of: \.substitutedTypeName), in: machOFile) + public func substitutedTypeName(in machO: MachO) throws -> MangledName { + return try layout.substitutedTypeName.resolve(from: offset(of: \.substitutedTypeName), in: machO) } } diff --git a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift b/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift index e9eae3c8..84c58802 100644 --- a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift +++ b/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift @@ -23,8 +23,8 @@ public struct BuiltinTypeDescriptor: ResolvableLocatableLayoutWrapper, TopLevelD } extension BuiltinTypeDescriptor { - public func typeName(in machOFile: MachO) throws -> MangledName? { - return try layout.typeName.resolve(from: offset(of: \.typeName), in: machOFile) + public func typeName(in machO: MachO) throws -> MangledName? { + return try layout.typeName.resolve(from: offset(of: \.typeName), in: machO) } public var isBitwiseTakable: Bool { diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift index fdacaf50..1e7cecf7 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift +++ b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift @@ -69,8 +69,8 @@ public enum ContextDescriptorWrapper { } } - public func parent(in machOFile: MachO) throws -> SymbolOrElement? { - return try contextDescriptor.parent(in: machOFile) + public func parent(in machO: MachO) throws -> SymbolOrElement? { + return try contextDescriptor.parent(in: machO) } public var contextDescriptor: any ContextDescriptorProtocol { @@ -130,33 +130,33 @@ extension ContextDescriptorWrapper: Resolvable { case invalidContextDescriptor } - public static func resolve(from offset: Int, in machOFile: MachO) throws -> Self { - let contextDescriptor: ContextDescriptor = try machOFile.readWrapperElement(offset: offset) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + let contextDescriptor: ContextDescriptor = try machO.readWrapperElement(offset: offset) switch contextDescriptor.flags.kind { case .class: - return try .type(.class(machOFile.readWrapperElement(offset: offset))) + return try .type(.class(machO.readWrapperElement(offset: offset))) case .enum: - return try .type(.enum(machOFile.readWrapperElement(offset: offset))) + return try .type(.enum(machO.readWrapperElement(offset: offset))) case .struct: - return try .type(.struct(machOFile.readWrapperElement(offset: offset))) + return try .type(.struct(machO.readWrapperElement(offset: offset))) case .protocol: - return try .protocol(machOFile.readWrapperElement(offset: offset)) + return try .protocol(machO.readWrapperElement(offset: offset)) case .anonymous: - return try .anonymous(machOFile.readWrapperElement(offset: offset)) + return try .anonymous(machO.readWrapperElement(offset: offset)) case .extension: - return try .extension(machOFile.readWrapperElement(offset: offset)) + return try .extension(machO.readWrapperElement(offset: offset)) case .module: - return try .module(machOFile.readWrapperElement(offset: offset)) + return try .module(machO.readWrapperElement(offset: offset)) case .opaqueType: - return try .opaqueType(machOFile.readWrapperElement(offset: offset)) + return try .opaqueType(machO.readWrapperElement(offset: offset)) default: throw ResolutionError.invalidContextDescriptor } } - public static func resolve(from offset: Int, in machOFile: MachO) throws -> Self? { + public static func resolve(from offset: Int, in machO: MachO) throws -> Self? { do { - return try resolve(from: offset, in: machOFile) as Self + return try resolve(from: offset, in: machO) as Self } catch { print("Error resolving ContextDescriptorWrapper: \(error)") return nil diff --git a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift b/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift index f0ac5998..6467006d 100644 --- a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift +++ b/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift @@ -37,9 +37,9 @@ public struct MangledName { package var description: String { switch reference { case .relative(let relative): - "[Relative] FileOffset: \(offset) \(relative)" + "[Relative] Offset: \(offset) \(relative)" case .absolute(let absolute): - "[Absolute] FileOffset: \(offset) \(absolute)" + "[Absolute] Offset: \(offset) \(absolute)" } } } @@ -109,9 +109,9 @@ public struct MangledName { } extension MangledName: Resolvable { - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> MangledName { + public static func resolve(from offset: Int, in machO: MachO) throws -> MangledName { var elements: [MangledName.Element] = [] - var currentOffset = fileOffset + var currentOffset = offset var currentString = "" while true { let value: UInt8 = try machO.readElement(offset: currentOffset) @@ -129,7 +129,7 @@ extension MangledName: Resolvable { currentString = "" } let reference: Int32 = try machO.readElement(offset: currentOffset + 1) - let offset = Int(fileOffset + (currentOffset - fileOffset)) + let offset = Int(offset + (currentOffset - offset)) elements.append(.lookup(.init(offset: offset, reference: .relative(.init(kind: value, relativeOffset: reference + 1))))) currentOffset.offset(of: Int32.self) } else if value >= 0x18, value <= 0x1F { @@ -138,7 +138,7 @@ extension MangledName: Resolvable { currentString = "" } let reference: UInt64 = try machO.readElement(offset: currentOffset + 1) - let offset = Int(fileOffset + (currentOffset - fileOffset)) + let offset = Int(offset + (currentOffset - offset)) elements.append(.lookup(.init(offset: offset, reference: .absolute(.init(kind: value, reference: reference))))) currentOffset.offset(of: UInt64.self) } else { @@ -147,7 +147,7 @@ extension MangledName: Resolvable { currentOffset.offset(of: UInt8.self) } - return .init(elements: elements, startOffset: fileOffset, endOffset: currentOffset) + return .init(elements: elements, startOffset: offset, endOffset: currentOffset) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift b/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift index 2aac4c11..d7b4123a 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift +++ b/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift @@ -42,7 +42,7 @@ public struct `Protocol`: TopLevelType { var currentOffset = descriptor.offset + descriptor.layoutSize if descriptor.numRequirementsInSignature > 0 { - self.requirementInSignatures = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirementsInSignature.cast()) + self.requirementInSignatures = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirementsInSignature.cast()) as [GenericRequirementDescriptor] currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.numRequirementsInSignature.cast()) currentOffset = align(address: currentOffset.cast(), alignment: 4).cast() } else { @@ -50,7 +50,7 @@ public struct `Protocol`: TopLevelType { } if descriptor.numRequirements > 0 { - self.requirements = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirements.cast()) + self.requirements = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirements.cast()) as [ProtocolRequirement] currentOffset.offset(of: ProtocolRequirement.self, numbersOfElements: descriptor.numRequirements.cast()) } else { self.requirements = [] diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift b/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift index ae106de6..4c479159 100644 --- a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift +++ b/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift @@ -63,7 +63,7 @@ public struct ProtocolConformance: TopLevelType { } if descriptor.flags.numConditionalRequirements > 0 { - self.conditionalRequirements = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.flags.numConditionalRequirements.cast()) + self.conditionalRequirements = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.flags.numConditionalRequirements.cast()) as [GenericRequirementDescriptor] currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.flags.numConditionalRequirements.cast()) } else { self.conditionalRequirements = [] @@ -73,7 +73,7 @@ public struct ProtocolConformance: TopLevelType { let header: GenericPackShapeHeader = try machO.readWrapperElement(offset: currentOffset) self.conditionalPackShapeHeader = header currentOffset.offset(of: GenericPackShapeHeader.self) - self.conditionalPackShapeDescriptors = try machO.readWrapperElements(offset: currentOffset, numberOfElements: header.numPacks.cast()) + self.conditionalPackShapeDescriptors = try machO.readWrapperElements(offset: currentOffset, numberOfElements: header.numPacks.cast()) as [GenericPackShapeDescriptor] currentOffset.offset(of: GenericPackShapeDescriptor.self, numbersOfElements: header.numPacks.cast()) } else { self.conditionalPackShapeHeader = nil @@ -84,7 +84,7 @@ public struct ProtocolConformance: TopLevelType { let header: ResilientWitnessesHeader = try machO.readWrapperElement(offset: currentOffset) self.resilientWitnessesHeader = header currentOffset.offset(of: ResilientWitnessesHeader.self) - self.resilientWitnesses = try machO.readWrapperElements(offset: currentOffset, numberOfElements: header.numWitnesses.cast()) + self.resilientWitnesses = try machO.readWrapperElements(offset: currentOffset, numberOfElements: header.numWitnesses.cast()) as [ResilientWitness] currentOffset.offset(of: ResilientWitness.self, numbersOfElements: header.numWitnesses.cast()) } else { self.resilientWitnessesHeader = nil diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift b/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift index baf70692..260c9b01 100644 --- a/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift +++ b/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift @@ -66,7 +66,7 @@ public struct Enum: TopLevelType { currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) self.canonicalSpecializedMetadatas = canonicalMetadataPrespecializations self.canonicalSpecializedMetadatasListCount = count - self.canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) + self.canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) as CanonicalSpecializedMetadatasCachingOnceToken currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) } else { self.canonicalSpecializedMetadatas = [] @@ -75,14 +75,14 @@ public struct Enum: TopLevelType { } if descriptor.flags.hasInvertibleProtocols { - self.invertibleProtocolSet = try machO.readElement(offset: currentOffset) + self.invertibleProtocolSet = try machO.readElement(offset: currentOffset) as InvertibleProtocolSet currentOffset.offset(of: InvertibleProtocolSet.self) } else { self.invertibleProtocolSet = nil } if descriptor.hasSingletonMetadataPointer { - self.singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) + self.singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) as SingletonMetadataPointer currentOffset.offset(of: SingletonMetadataPointer.self) } else { self.singletonMetadataPointer = nil diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift b/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift index b526506d..f4ec216e 100644 --- a/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift +++ b/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift @@ -30,14 +30,14 @@ public struct Struct: TopLevelType { let typeFlags = try required(descriptor.flags.kindSpecificFlags?.typeFlags) if typeFlags.hasForeignMetadataInitialization { - self.foreignMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) + self.foreignMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) as ForeignMetadataInitialization currentOffset.offset(of: ForeignMetadataInitialization.self) } else { self.foreignMetadataInitialization = nil } if typeFlags.hasSingletonMetadataInitialization { - self.singletonMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) + self.singletonMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) as SingletonMetadataInitialization currentOffset.offset(of: SingletonMetadataInitialization.self) } else { self.singletonMetadataInitialization = nil @@ -51,7 +51,7 @@ public struct Struct: TopLevelType { currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) self.canonicalSpecializedMetadatas = canonicalMetadataPrespecializations self.canonicalSpecializedMetadatasListCount = count - self.canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) + self.canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) as CanonicalSpecializedMetadatasCachingOnceToken currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) } else { self.canonicalSpecializedMetadatas = [] @@ -60,14 +60,14 @@ public struct Struct: TopLevelType { } if descriptor.flags.hasInvertibleProtocols { - self.invertibleProtocolSet = try machO.readElement(offset: currentOffset) + self.invertibleProtocolSet = try machO.readElement(offset: currentOffset) as InvertibleProtocolSet currentOffset.offset(of: InvertibleProtocolSet.self) } else { self.invertibleProtocolSet = nil } if descriptor.hasSingletonMetadataPointer { - self.singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) + self.singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) as SingletonMetadataPointer currentOffset.offset(of: SingletonMetadataPointer.self) } else { self.singletonMetadataPointer = nil diff --git a/Sources/MachOSwiftSection/Models/Type/TypeReference.swift b/Sources/MachOSwiftSection/Models/Type/TypeReference.swift index de42abf4..cc9e16a4 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeReference.swift +++ b/Sources/MachOSwiftSection/Models/Type/TypeReference.swift @@ -22,16 +22,16 @@ public enum TypeReference { } - public func resolve(at fileOffset: Int, in machO: MachO) throws -> ResolvedTypeReference { + public func resolve(at offset: Int, in machO: MachO) throws -> ResolvedTypeReference { switch self { case let .directTypeDescriptor(relativeDirectPointer): - return try .directTypeDescriptor(relativeDirectPointer.resolve(from: fileOffset, in: machO)) + return try .directTypeDescriptor(relativeDirectPointer.resolve(from: offset, in: machO)) case let .indirectTypeDescriptor(relativeIndirectPointer): - return try .indirectTypeDescriptor(relativeIndirectPointer.resolve(from: fileOffset, in: machO).resolve(in: machO).asOptional) + return try .indirectTypeDescriptor(relativeIndirectPointer.resolve(from: offset, in: machO).resolve(in: machO).asOptional) case let .directObjCClassName(relativeDirectPointer): - return try .directObjCClassName(relativeDirectPointer.resolve(from: fileOffset, in: machO)) + return try .directObjCClassName(relativeDirectPointer.resolve(from: offset, in: machO)) case let .indirectObjCClass(relativeIndirectPointer): - return try .indirectObjCClass(relativeIndirectPointer.resolve(from: fileOffset, in: machO).resolve(in: machO).asOptional) + return try .indirectObjCClass(relativeIndirectPointer.resolve(from: offset, in: machO).resolve(in: machO).asOptional) } } } diff --git a/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift b/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift index 149d2f0c..cb316747 100644 --- a/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift +++ b/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift @@ -16,25 +16,25 @@ public enum SymbolOrElementPointer: RelativeIndirectType { case symbol(Symbol) case address(UInt64) - public func resolve(in machOFile: MachO) throws -> Resolved { + public func resolve(in machO: MachO) throws -> Resolved { switch self { case let .symbol(unsolvedSymbol): return .symbol(unsolvedSymbol) case .address: - return try .element(Context.resolve(from: resolveOffset(in: machOFile), in: machOFile)) + return try .element(Context.resolve(from: resolveOffset(in: machO), in: machO)) } } - public func resolveOffset(in machOFile: MachO) -> Int { + public func resolveOffset(in machO: MachO) -> Int { switch self { case let .symbol(unsolvedSymbol): return unsolvedSymbol.offset case let .address(address): - return numericCast(machOFile.resolveOffset(at: address)) + return numericCast(machO.resolveOffset(at: address)) } } - public func resolveAny(in machOFile: MachO) throws -> T { + public func resolveAny(in machO: MachO) throws -> T { fatalError() } diff --git a/Sources/MachOSymbols/Symbol.swift b/Sources/MachOSymbols/Symbol.swift index 85d8bc3e..9e67801b 100644 --- a/Sources/MachOSymbols/Symbol.swift +++ b/Sources/MachOSymbols/Symbol.swift @@ -13,12 +13,12 @@ public struct Symbol: Resolvable, Hashable { self.stringValue = stringValue } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - try required(resolve(from: fileOffset, in: machO)) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + try required(resolve(from: offset, in: machO)) } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? { - if let symbol = machO.symbols(offset: fileOffset)?.first { + public static func resolve(from offset: Int, in machO: MachO) throws -> Self? { + if let symbol = machO.symbols(offset: offset)?.first { return symbol } return nil diff --git a/Sources/MachOSymbols/SymbolOrElement.swift b/Sources/MachOSymbols/SymbolOrElement.swift index bdcb91f2..a345cfd8 100644 --- a/Sources/MachOSymbols/SymbolOrElement.swift +++ b/Sources/MachOSymbols/SymbolOrElement.swift @@ -33,19 +33,19 @@ public enum SymbolOrElement: Resolvable { } } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> SymbolOrElement { - if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: fileOffset) { - return .symbol(.init(offset: fileOffset, stringValue: symbol)) + public static func resolve(from offset: Int, in machO: MachO) throws -> SymbolOrElement { + if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: offset) { + return .symbol(.init(offset: offset, stringValue: symbol)) } else { - return try .element(.resolve(from: fileOffset, in: machO)) + return try .element(.resolve(from: offset, in: machO)) } } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> SymbolOrElement? { - if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: fileOffset) { - return .symbol(.init(offset: fileOffset, stringValue: symbol)) + public static func resolve(from offset: Int, in machO: MachO) throws -> SymbolOrElement? { + if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: offset) { + return .symbol(.init(offset: offset, stringValue: symbol)) } else { - return try Element.resolve(from: fileOffset, in: machO).map { .element($0) } + return try Element.resolve(from: offset, in: machO).map { .element($0) } } } diff --git a/Sources/MachOSymbols/Symbols.swift b/Sources/MachOSymbols/Symbols.swift index e8d84d5c..6234ed77 100644 --- a/Sources/MachOSymbols/Symbols.swift +++ b/Sources/MachOSymbols/Symbols.swift @@ -13,12 +13,12 @@ public struct Symbols: Resolvable { self._storage = symbols } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self { - try required(resolve(from: fileOffset, in: machO)) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self { + try required(resolve(from: offset, in: machO)) } - public static func resolve(from fileOffset: Int, in machO: MachO) throws -> Self? { - return machO.symbols(offset: fileOffset) + public static func resolve(from offset: Int, in machO: MachO) throws -> Self? { + return machO.symbols(offset: offset) } } diff --git a/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift b/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift index a04dd1ae..b7907a97 100644 --- a/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift @@ -4,34 +4,32 @@ import MachOSwiftSection import MachOMacro import Semantic import Utilities +import MachOFoundation extension AssociatedType: ConformedDumpable { - @MachOImageGenerator @SemanticStringBuilder - public func dumpTypeName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleSymbol(for: conformingTypeName, in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + public func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleSymbol(for: conformingTypeName, in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() } - @MachOImageGenerator @SemanticStringBuilder - public func dumpProtocolName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleSymbol(for: protocolTypeName, in: machOFile).printSemantic(using: options) + public func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleSymbol(for: protocolTypeName, in: machO).printSemantic(using: options) } - @MachOImageGenerator @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { Keyword(.extension) Space() - try dumpTypeName(using: options, in: machOFile) + try dumpTypeName(using: options, in: machO) Standard(":") Space() - try dumpProtocolName(using: options, in: machOFile) + try dumpProtocolName(using: options, in: machO) Space() @@ -46,7 +44,7 @@ extension AssociatedType: ConformedDumpable { Space() - try TypeDeclaration(kind: .other, record.name(in: machOFile)) + try TypeDeclaration(kind: .other, record.name(in: machO)) Space() @@ -54,7 +52,7 @@ extension AssociatedType: ConformedDumpable { Space() - try MetadataReader.demangleSymbol(for: record.substitutedTypeName(in: machOFile), in: machOFile).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: record.substitutedTypeName(in: machO), in: machO).printSemantic(using: options) if offset.isEnd { BreakLine() diff --git a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift index bf64323f..1f122599 100644 --- a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift @@ -7,14 +7,12 @@ import MachOSwiftSection import Utilities extension Class: NamedDumpable { - @MachOImageGenerator - public func dumpName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleContext(for: .type(.class(descriptor)), in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleContext(for: .type(.class(descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() } - @MachOImageGenerator @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { if descriptor.isActor { Keyword(.actor) } else { @@ -23,19 +21,19 @@ extension Class: NamedDumpable { Space() - try dumpName(using: options, in: machOFile) + try dumpName(using: options, in: machO) if let genericContext { if genericContext.currentParameters.count > 0 { - try genericContext.dumpGenericParameters(in: machOFile) + try genericContext.dumpGenericParameters(in: machO) } } - if let superclassMangledName = try descriptor.superclassTypeMangledName(in: machOFile) { + if let superclassMangledName = try descriptor.superclassTypeMangledName(in: machO) { Standard(":") Space() - try MetadataReader.demangleType(for: superclassMangledName, in: machOFile).printSemantic(using: options) - } else if let resilientSuperclass, let kind = descriptor.resilientSuperclassReferenceKind, let superclass = try resilientSuperclass.dumpSuperclass(using: options, for: kind, in: machOFile) { + try MetadataReader.demangleType(for: superclassMangledName, in: machO).printSemantic(using: options) + } else if let resilientSuperclass, let kind = descriptor.resilientSuperclassReferenceKind, let superclass = try resilientSuperclass.dumpSuperclass(using: options, for: kind, in: machO) { Standard(":") Space() superclass @@ -45,20 +43,20 @@ extension Class: NamedDumpable { Space() Keyword(.where) Space() - try genericContext.dumpGenericRequirements(using: options, in: machOFile) + try genericContext.dumpGenericRequirements(using: options, in: machO) } Space() Standard("{") - for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machOFile).records(in: machOFile).offsetEnumerated() { + for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { BreakLine() Indent(level: 1) - let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machOFile), in: machOFile) + let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machO), in: machO) - let fieldName = try fieldRecord.fieldName(in: machOFile) + let fieldName = try fieldRecord.fieldName(in: machO) if fieldRecord.flags.contains(.isVariadic) { if demangledTypeNode.hasWeakNode { @@ -102,7 +100,7 @@ extension Class: NamedDumpable { dumpMethodKeyword(for: descriptor) - try dumpMethodDeclaration(for: descriptor, using: options, in: machOFile) + try dumpMethodDeclaration(for: descriptor, using: options, in: machO) if offset.isEnd { BreakLine() @@ -114,26 +112,26 @@ extension Class: NamedDumpable { Indent(level: 1) - if let methodDescriptor = try descriptor.methodDescriptor(in: machOFile) { + if let methodDescriptor = try descriptor.methodDescriptor(in: machO) { switch methodDescriptor { case .symbol(let symbol): Keyword(.override) Space() - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) case .element(let element): dumpMethodKind(for: element) Keyword(.override) Space() dumpMethodKeyword(for: element) - try? dumpMethodDeclaration(for: element, using: options, in: machOFile) + try? dumpMethodDeclaration(for: element, using: options, in: machO) } } else { Keyword(.override) Space() - if let symbol = try? descriptor.implementationSymbol(in: machOFile) { - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + if let symbol = try? descriptor.implementationSymbol(in: machO) { + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { - FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } @@ -153,10 +151,10 @@ extension Class: NamedDumpable { Space() - if let symbol = try? descriptor.implementationSymbol(in: machOFile) { - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + if let symbol = try? descriptor.implementationSymbol(in: machO) { + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { - FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } @@ -194,13 +192,12 @@ extension Class: NamedDumpable { } } - @MachOImageGenerator @SemanticStringBuilder - private func dumpMethodDeclaration(for descriptor: MethodDescriptor, using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - if let symbol = try? descriptor.implementationSymbol(in: machOFile) { - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + private func dumpMethodDeclaration(for descriptor: MethodDescriptor, using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + if let symbol = try? descriptor.implementationSymbol(in: machO) { + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { - FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } diff --git a/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift b/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift index aa64bfe0..620548ba 100644 --- a/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift @@ -1,5 +1,6 @@ import Foundation import MachOKit +import MachOFoundation import MachOSwiftSection import MachOMacro import Semantic @@ -7,34 +8,32 @@ import MachOSymbols import Utilities extension Enum: NamedDumpable { - @MachOImageGenerator - public func dumpName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleContext(for: .type(.enum(descriptor)), in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleContext(for: .type(.enum(descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() } - @MachOImageGenerator @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { Keyword(.enum) Space() - try dumpName(using: options, in: machOFile) + try dumpName(using: options, in: machO) if let genericContext { if genericContext.currentParameters.count > 0 { - try genericContext.dumpGenericParameters(in: machOFile) + try genericContext.dumpGenericParameters(in: machO) } if genericContext.currentRequirements.count > 0 { Space() Keyword(.where) Space() - try genericContext.dumpGenericRequirements(using: options, in: machOFile) + try genericContext.dumpGenericRequirements(using: options, in: machO) } } Space() Standard("{") - for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machOFile).records(in: machOFile).offsetEnumerated() { + for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { BreakLine() Indent(level: 1) @@ -49,12 +48,12 @@ extension Enum: NamedDumpable { Space() } - try MemberDeclaration("\(fieldRecord.fieldName(in: machOFile))") + try MemberDeclaration("\(fieldRecord.fieldName(in: machO))") - let mangledName = try fieldRecord.mangledTypeName(in: machOFile) + let mangledName = try fieldRecord.mangledTypeName(in: machO) if !mangledName.isEmpty { - let demangledName = try MetadataReader.demangleType(for: mangledName, in: machOFile).printSemantic(using: options) + let demangledName = try MetadataReader.demangleType(for: mangledName, in: machO).printSemantic(using: options) let demangledNameString = demangledName.string if demangledNameString.hasPrefix("("), demangledNameString.hasSuffix(")") { demangledName @@ -71,7 +70,7 @@ extension Enum: NamedDumpable { } for kind in SymbolIndexStore.IndexKind.allCases { - for (offset, function) in try SymbolIndexStore.shared.symbols(of: kind, for: dumpName(using: .interface, in: machOFile).string, in: machOFile).offsetEnumerated() { + for (offset, function) in try SymbolIndexStore.shared.symbols(of: kind, for: dumpName(using: .interface, in: machO).string, in: machO).offsetEnumerated() { if offset.isStart { BreakLine() @@ -84,7 +83,7 @@ extension Enum: NamedDumpable { Indent(level: 1) - try MetadataReader.demangleSymbol(for: function, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleSymbol(for: function, in: machO)?.printSemantic(using: options) if offset.isEnd { BreakLine() diff --git a/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift index 63cea045..08f21ed0 100644 --- a/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift @@ -9,19 +9,17 @@ import Demangle import OrderedCollections extension MachOSwiftSection.`Protocol`: NamedDumpable { - @MachOImageGenerator - public func dumpName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleContext(for: .protocol(descriptor), in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleContext(for: .protocol(descriptor), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() } - @MachOImageGenerator @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { Keyword(.protocol) Space() - try dumpName(using: options, in: machOFile) + try dumpName(using: options, in: machO) if numberOfRequirementsInSignature > 0 { Space() @@ -29,7 +27,7 @@ extension MachOSwiftSection.`Protocol`: NamedDumpable { Space() for (offset, requirement) in requirementInSignatures.offsetEnumerated() { - try requirement.dump(using: options, in: machOFile) + try requirement.dump(using: options, in: machO) if !offset.isEnd { Standard(",") Space() @@ -39,7 +37,7 @@ extension MachOSwiftSection.`Protocol`: NamedDumpable { Space() Standard("{") - let associatedTypes = try descriptor.associatedTypes(in: machOFile) + let associatedTypes = try descriptor.associatedTypes(in: machO) if !associatedTypes.isEmpty { for (offset, associatedType) in associatedTypes.offsetEnumerated() { @@ -59,13 +57,13 @@ extension MachOSwiftSection.`Protocol`: NamedDumpable { for (offset, requirement) in requirements.offsetEnumerated() { BreakLine() Indent(level: 1) - if let symbols = try Symbols.resolve(from: requirement.offset, in: machOFile), let validNode = try validNode(for: symbols, in: machOFile) { + if let symbols = try Symbols.resolve(from: requirement.offset, in: machO), let validNode = try validNode(for: symbols, in: machO) { validNode.printSemantic(using: options) } else { InlineComment("[Stripped Symbol]") } - if let symbols = try requirement.defaultImplementationSymbols(in: machOFile), let defaultImplementation = try validNode(for: symbols, in: machOFile, visitedNode: defaultImplementations) { + if let symbols = try requirement.defaultImplementationSymbols(in: machO), let defaultImplementation = try validNode(for: symbols, in: machO, visitedNode: defaultImplementations) { _ = defaultImplementations.append(defaultImplementation) } @@ -93,10 +91,9 @@ extension MachOSwiftSection.`Protocol`: NamedDumpable { Standard("}") } - @MachOImageGenerator - private func validNode(for symbols: Symbols, in machOFile: MachOFile, visitedNode: borrowing OrderedSet = []) throws -> Node? { + private func validNode(for symbols: Symbols, in machO: MachO, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolNode = node.preorder().first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interfaceType, in: machOFile)).string, !visitedNode.contains(node) { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolNode = node.preorder().first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interfaceType, in: machO)).string, !visitedNode.contains(node) { return node } } diff --git a/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift index 77be7f2f..2edab1f3 100644 --- a/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift @@ -9,18 +9,17 @@ import Utilities import OrderedCollections extension ProtocolConformance: ConformedDumpable { - @MachOImageGenerator @SemanticStringBuilder - public func dumpTypeName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { switch typeReference { case .directTypeDescriptor(let descriptor): - try descriptor?.dumpName(using: options, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() + try descriptor?.dumpName(using: options, in: machO).replacingTypeNameOrOtherToTypeDeclaration() case .indirectTypeDescriptor(let descriptor): switch descriptor { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() case .element(let element): - try element.dumpName(using: options, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() + try element.dumpName(using: options, in: machO).replacingTypeNameOrOtherToTypeDeclaration() case nil: Standard("") } @@ -29,46 +28,44 @@ extension ProtocolConformance: ConformedDumpable { case .indirectObjCClass(let objcClass): switch objcClass { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() case .element(let element): - try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machOFile))), in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machO))), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() case nil: Standard("") } } } - @MachOImageGenerator @SemanticStringBuilder - public func dumpProtocolName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { switch `protocol` { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) case .element(let element): - try MetadataReader.demangleContext(for: .protocol(element), in: machOFile).printSemantic(using: options) + try MetadataReader.demangleContext(for: .protocol(element), in: machO).printSemantic(using: options) case .none: Standard("") } } - @MachOImageGenerator @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { Keyword(.extension) Space() - let typeName = try dumpTypeName(using: options, in: machOFile) + let typeName = try dumpTypeName(using: options, in: machO) typeName - let interfaceTypeName = try dumpTypeName(using: .interfaceType, in: machOFile).string + let interfaceTypeName = try dumpTypeName(using: .interfaceType, in: machO).string Standard(":") Space() - try dumpProtocolName(using: options, in: machOFile) + try dumpProtocolName(using: options, in: machO) if !conditionalRequirements.isEmpty { Space() @@ -77,7 +74,7 @@ extension ProtocolConformance: ConformedDumpable { } for conditionalRequirement in conditionalRequirements { - try conditionalRequirement.dump(using: options, in: machOFile) + try conditionalRequirement.dump(using: options, in: machO) } if resilientWitnesses.isEmpty { @@ -94,30 +91,30 @@ extension ProtocolConformance: ConformedDumpable { Indent(level: 1) - if let symbols = try resilientWitness.implementationSymbols(in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: interfaceTypeName, visitedNode: visitedNodes) { + if let symbols = try resilientWitness.implementationSymbols(in: machO), let validNode = try validNode(for: symbols, in: machO, typeName: interfaceTypeName, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) - } else if let requirement = try resilientWitness.requirement(in: machOFile) { + } else if let requirement = try resilientWitness.requirement(in: machO) { switch requirement { case .symbol(let symbol): - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) case .element(let element): - if let symbols = try Symbols.resolve(from: element.offset, in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: interfaceTypeName, visitedNode: visitedNodes) { + if let symbols = try Symbols.resolve(from: element.offset, in: machO), let validNode = try validNode(for: symbols, in: machO, typeName: interfaceTypeName, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) - } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machOFile), let validNode = try validNode(for: defaultImplementationSymbols, in: machOFile, typeName: interfaceTypeName, visitedNode: visitedNodes) { + } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machO), let validNode = try validNode(for: defaultImplementationSymbols, in: machO, typeName: interfaceTypeName, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) } else if !element.defaultImplementation.isNull { - FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machO).insertSubFunctionPrefix) } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } } } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } @@ -129,10 +126,9 @@ extension ProtocolConformance: ConformedDumpable { } } - @MachOImageGenerator - private func validNode(for symbols: Symbols, in machOFile: MachOFile, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { + private func validNode(for symbols: Symbols, in machO: MachO, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { return node } } diff --git a/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift index 2d9ce347..172d1ec6 100644 --- a/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift @@ -1,9 +1,8 @@ import MachOKit import Semantic +import MachOFoundation public protocol ConformedDumpable: Dumpable { - func dumpTypeName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dumpProtocolName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dumpTypeName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString - func dumpProtocolName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString + func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString + func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString } diff --git a/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift index dd85f373..ab325f10 100644 --- a/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift @@ -1,12 +1,12 @@ import Demangle import MachOKit import Semantic +import MachOFoundation public typealias DemangleOptions = Demangle.DemangleOptions public protocol Dumpable { - func dump(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dump(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString + func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString } diff --git a/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift index 3b4a637a..e91ddb00 100644 --- a/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift @@ -1,7 +1,7 @@ import MachOKit import Semantic +import MachOFoundation public protocol NamedDumpable: Dumpable { - func dumpName(using options: DemangleOptions, in machO: MachOFile) throws -> SemanticString - func dumpName(using options: DemangleOptions, in machO: MachOImage) throws -> SemanticString + func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString } diff --git a/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift b/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift index 49fa0ca4..f9b6da02 100644 --- a/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift @@ -5,31 +5,30 @@ import MachOMacro import Semantic import MachOSymbols import Utilities +import MachOFoundation extension Struct: NamedDumpable { - @MachOImageGenerator - public func dumpName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleContext(for: .type(.struct(descriptor)), in: machOFile).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleContext(for: .type(.struct(descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() } - @MachOImageGenerator @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { Keyword(.struct) Space() - try dumpName(using: options, in: machOFile) + try dumpName(using: options, in: machO) if let genericContext { if genericContext.currentParameters.count > 0 { - try genericContext.dumpGenericParameters(in: machOFile) + try genericContext.dumpGenericParameters(in: machO) } if genericContext.currentRequirements.count > 0 { Space() Keyword(.where) Space() - try genericContext.dumpGenericRequirements(using: options, in: machOFile) + try genericContext.dumpGenericRequirements(using: options, in: machO) } } @@ -37,14 +36,14 @@ extension Struct: NamedDumpable { Standard("{") - for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machOFile).records(in: machOFile).offsetEnumerated() { + for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { BreakLine() Indent(level: 1) - let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machOFile), in: machOFile) + let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machO), in: machO) - let fieldName = try fieldRecord.fieldName(in: machOFile) + let fieldName = try fieldRecord.fieldName(in: machO) if fieldRecord.flags.contains(.isVariadic) { if demangledTypeNode.hasWeakNode { @@ -77,7 +76,7 @@ extension Struct: NamedDumpable { } for kind in SymbolIndexStore.IndexKind.allCases { - for (offset, symbol) in try SymbolIndexStore.shared.symbols(of: kind, for: dumpName(using: .interface, in: machOFile).string, in: machOFile).offsetEnumerated() { + for (offset, symbol) in try SymbolIndexStore.shared.symbols(of: kind, for: dumpName(using: .interface, in: machO).string, in: machO).offsetEnumerated() { if offset.isStart { BreakLine() @@ -90,7 +89,7 @@ extension Struct: NamedDumpable { Indent(level: 1) - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) if offset.isEnd { BreakLine() diff --git a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift b/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift index 45d71a2a..d1e05a6a 100644 --- a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift +++ b/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift @@ -8,12 +8,12 @@ import Demangle import Utilities import OrderedCollections -struct ProtocolConformanceDumper: ConformedDumper { +struct ProtocolConformanceDumper: ConformedDumper { let protocolConformance: ProtocolConformance let options: DemangleOptions - let machOFile: MachOFile + let machO: MachO var typeNameOptions: DemangleOptions { .interfaceType } @@ -42,7 +42,7 @@ struct ProtocolConformanceDumper: ConformedDumper { } for conditionalRequirement in protocolConformance.conditionalRequirements { - try conditionalRequirement.dump(using: options, in: machOFile) + try conditionalRequirement.dump(using: options, in: machO) } if protocolConformance.resilientWitnesses.isEmpty { @@ -59,30 +59,30 @@ struct ProtocolConformanceDumper: ConformedDumper { Indent(level: 1) - if let symbols = try resilientWitness.implementationSymbols(in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: typeNameString, visitedNode: visitedNodes) { + if let symbols = try resilientWitness.implementationSymbols(in: machO), let validNode = try validNode(for: symbols, typeName: typeNameString, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) - } else if let requirement = try resilientWitness.requirement(in: machOFile) { + } else if let requirement = try resilientWitness.requirement(in: machO) { switch requirement { case .symbol(let symbol): - try MetadataReader.demangleSymbol(for: symbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) case .element(let element): - if let symbols = try Symbols.resolve(from: element.offset, in: machOFile), let validNode = try validNode(for: symbols, in: machOFile, typeName: typeNameString, visitedNode: visitedNodes) { + if let symbols = try Symbols.resolve(from: element.offset, in: machO), let validNode = try validNode(for: symbols, typeName: typeNameString, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) - } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machOFile), let validNode = try validNode(for: defaultImplementationSymbols, in: machOFile, typeName: typeNameString, visitedNode: visitedNodes) { + } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machO), let validNode = try validNode(for: defaultImplementationSymbols, typeName: typeNameString, visitedNode: visitedNodes) { _ = visitedNodes.append(validNode) validNode.printSemantic(using: options) } else if !element.defaultImplementation.isNull { - FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machO).insertSubFunctionPrefix) } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } } } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machOFile).insertSubFunctionPrefix) + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) } else { Error("Symbol not found") } @@ -100,13 +100,13 @@ struct ProtocolConformanceDumper: ConformedDumper { get throws { switch protocolConformance.typeReference { case .directTypeDescriptor(let descriptor): - try descriptor?.dumpName(using: typeNameOptions, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() + try descriptor?.dumpName(using: typeNameOptions, in: machO).replacingTypeNameOrOtherToTypeDeclaration() case .indirectTypeDescriptor(let descriptor): switch descriptor { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() case .element(let element): - try element.dumpName(using: typeNameOptions, in: machOFile).replacingTypeNameOrOtherToTypeDeclaration() + try element.dumpName(using: typeNameOptions, in: machO).replacingTypeNameOrOtherToTypeDeclaration() case nil: Standard("") } @@ -115,9 +115,9 @@ struct ProtocolConformanceDumper: ConformedDumper { case .indirectObjCClass(let objcClass): switch objcClass { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() case .element(let element): - try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machOFile))), in: machOFile).printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machO))), in: machO).printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() case nil: Standard("") } @@ -130,18 +130,18 @@ struct ProtocolConformanceDumper: ConformedDumper { get throws { switch protocolConformance.`protocol` { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) case .element(let element): - try MetadataReader.demangleContext(for: .protocol(element), in: machOFile).printSemantic(using: options) + try MetadataReader.demangleContext(for: .protocol(element), in: machO).printSemantic(using: options) case .none: Standard("") } } } - private func validNode(for symbols: Symbols, in machOFile: MachOFile, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { + private func validNode(for symbols: Symbols, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machOFile), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { return node } } diff --git a/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift b/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift index d01482f7..d66dd781 100644 --- a/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift +++ b/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift @@ -1,11 +1,11 @@ import MachOKit import MachOMacro +import MachOFoundation import MachOSwiftSection import Semantic extension ContextDescriptorWrapper { - @MachOImageGenerator - package func dumpName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try MetadataReader.demangleContext(for: self, in: machOFile).printSemantic(using: options) + package func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try MetadataReader.demangleContext(for: self, in: machO).printSemantic(using: options) } } diff --git a/Sources/SwiftDump/Extensions/GenericContext+Dump.swift b/Sources/SwiftDump/Extensions/GenericContext+Dump.swift index fd745272..db8f9643 100644 --- a/Sources/SwiftDump/Extensions/GenericContext+Dump.swift +++ b/Sources/SwiftDump/Extensions/GenericContext+Dump.swift @@ -6,9 +6,8 @@ import MachOSwiftSection import Utilities extension TargetGenericContext { - @MachOImageGenerator @SemanticStringBuilder - package func dumpGenericParameters(in machOFile: MachOFile) throws -> SemanticString { + package func dumpGenericParameters(in machO: MachO) throws -> SemanticString { Standard("<") for (offset, _) in currentParameters.offsetEnumerated() { Standard(try genericParameterName(depth: depth, index: offset.index)) @@ -32,11 +31,10 @@ extension TargetGenericContext { return name } - @MachOImageGenerator @SemanticStringBuilder - package func dumpGenericRequirements(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { + package func dumpGenericRequirements(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { for (offset, requirement) in currentRequirements.offsetEnumerated() { - try requirement.dump(using: options, in: machOFile) + try requirement.dump(using: options, in: machO) if !offset.isEnd { Standard(",") Space() @@ -45,12 +43,11 @@ extension TargetGenericContext { } } -@MachOImageAllMembersGenerator extension GenericRequirementDescriptor { - package func dumpInheritedProtocol(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString? { - if try paramManagedName(in: machOFile).rawStringValue() == "A" { - return try dumpParameterName(using: options, in: machOFile) + package func dumpInheritedProtocol(using options: DemangleOptions, in machO: MachO) throws -> SemanticString? { + if try paramManagedName(in: machO).rawStringValue() == "A" { + return try dumpParameterName(using: options, in: machO) } else { return nil } @@ -58,26 +55,26 @@ extension GenericRequirementDescriptor { @SemanticStringBuilder - package func dumpParameterName(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - let node = try MetadataReader.demangleType(for: paramManagedName(in: machOFile), in: machOFile) + package func dumpParameterName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + let node = try MetadataReader.demangleType(for: paramManagedName(in: machO), in: machO) node.printSemantic(using: options) } @SemanticStringBuilder - package func dumpContent(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - switch try resolvedContent(in: machOFile) { + package func dumpContent(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + switch try resolvedContent(in: machO) { case .type(let mangledName): - try MetadataReader.demangleType(for: mangledName, in: machOFile).printSemantic(using: options) + try MetadataReader.demangleType(for: mangledName, in: machO).printSemantic(using: options) case .protocol(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) case .element(let element): switch element { case .objc(let objc): - TypeName(kind: .protocol, try objc.mangledName(in: machOFile).rawStringValue()) + TypeName(kind: .protocol, try objc.mangledName(in: machO).rawStringValue()) case .swift(let protocolDescriptor): - try MetadataReader.demangleContext(for: .protocol(protocolDescriptor), in: machOFile).printSemantic(using: options) + try MetadataReader.demangleContext(for: .protocol(protocolDescriptor), in: machO).printSemantic(using: options) } } case .layout(let genericRequirementLayoutKind): @@ -110,8 +107,8 @@ extension GenericRequirementDescriptor { } @SemanticStringBuilder - package func dump(using options: DemangleOptions, in machOFile: MachOFile) throws -> SemanticString { - try dumpParameterName(using: options, in: machOFile) + package func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try dumpParameterName(using: options, in: machO) if layout.flags.kind == .sameType { Space() @@ -122,7 +119,7 @@ extension GenericRequirementDescriptor { Space() } - try dumpContent(using: options, in: machOFile) + try dumpContent(using: options, in: machO) } } diff --git a/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift b/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift index e98ed813..eafd67f4 100644 --- a/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift +++ b/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift @@ -1,22 +1,22 @@ import MachOKit import MachOMacro +import MachOFoundation import MachOSwiftSection import Semantic extension ResilientSuperclass { - @MachOImageGenerator - package func dumpSuperclass(using options: DemangleOptions, for kind: TypeReferenceKind, in machOFile: MachOFile) throws -> SemanticString? { + package func dumpSuperclass(using options: DemangleOptions, for kind: TypeReferenceKind, in machO: MachO) throws -> SemanticString? { let typeReference = TypeReference.forKind(kind, at: layout.superclass.relativeOffset) - let resolvedTypeReference = try typeReference.resolve(at: offset(of: \.superclass), in: machOFile) + let resolvedTypeReference = try typeReference.resolve(at: offset(of: \.superclass), in: machO) switch resolvedTypeReference { case .directTypeDescriptor(let contextDescriptorWrapper): - return try contextDescriptorWrapper?.dumpName(using: options, in: machOFile) + return try contextDescriptorWrapper?.dumpName(using: options, in: machO) case .indirectTypeDescriptor(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) + return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) case .element(let element): - return try element.dumpName(using: options, in: machOFile) + return try element.dumpName(using: options, in: machO) case nil: return nil } @@ -25,9 +25,9 @@ extension ResilientSuperclass { case .indirectObjCClass(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machOFile)?.printSemantic(using: options) + return try MetadataReader.demangleSymbol(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) case .element(let element): - return try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machOFile))), in: machOFile).printSemantic(using: options) + return try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machO))), in: machO).printSemantic(using: options) case nil: return nil } From b1bf4866474f1dd0e7b84f21fc10a25410848099 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 4 Jul 2025 00:32:30 +0800 Subject: [PATCH 5/8] Refactor SwiftDump target --- Package.swift | 1 + Sources/MachOCaches/MachOCache.swift | 33 ++- ...hOSwiftSectionRepresentableWithCache.swift | 2 +- Sources/MachOSymbols/SymbolCache.swift | 49 +--- Sources/MachOSymbols/SymbolIndexStore.swift | 43 +-- .../MachOTestingSupport/DumpableTests.swift | 18 +- .../Dumpable/AssociatedType+Dumpable.swift | 87 +++--- .../SwiftDump/Dumpable/Class+Dumpable.swift | 255 ++++++++++-------- .../SwiftDump/Dumpable/Enum+Dumpable.swift | 155 ++++++----- .../Dumpable/Protocol+Dumpable.swift | 145 +++++----- .../ProtocolConformance+Dumpable.swift | 217 ++++++++------- .../Protocols/ConformedDumpable.swift | 5 +- .../Protocols/ConformedDumper.swift | 0 .../Dumpable/Protocols/Dumpable.swift | 3 +- .../Protocols/Dumper.swift | 0 .../Dumpable/Protocols/NamedDumpable.swift | 3 +- .../Dumpable/Protocols/NamedDumper.swift | 5 + .../SwiftDump/Dumpable/Struct+Dumpable.swift | 157 ++++++----- .../Dumper/ProtocolConformanceDumper.swift | 150 ----------- .../ContextDescriptorWrapper+Dump.swift | 2 +- .../Extensions/GenericContext+Dump.swift | 12 +- .../Extensions/ResilientSuperclass+Dump.swift | 2 +- .../SwiftDump/PrimitiveTypeMappingCache.swift | 20 ++ .../MetadataFinderTests.swift | 1 - Tests/SwiftDumpTests/DyldCacheDumpTests.swift | 10 + 25 files changed, 700 insertions(+), 675 deletions(-) rename Sources/SwiftDump/{Dumper => Dumpable}/Protocols/ConformedDumper.swift (100%) rename Sources/SwiftDump/{Dumper => Dumpable}/Protocols/Dumper.swift (100%) create mode 100644 Sources/SwiftDump/Dumpable/Protocols/NamedDumper.swift delete mode 100644 Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift create mode 100644 Sources/SwiftDump/PrimitiveTypeMappingCache.swift diff --git a/Package.swift b/Package.swift index 97d7d7fe..cd97c3ff 100644 --- a/Package.swift +++ b/Package.swift @@ -174,6 +174,7 @@ let package = Package( "MachOMacro", "Demangle", "Utilities", + "MachOCaches", .product(name: "OrderedCollections", package: "swift-collections"), ] ), diff --git a/Sources/MachOCaches/MachOCache.swift b/Sources/MachOCaches/MachOCache.swift index cb0fa48f..0cb4b7c9 100644 --- a/Sources/MachOCaches/MachOCache.swift +++ b/Sources/MachOCaches/MachOCache.swift @@ -1,22 +1,43 @@ import Foundation import MachOKit +import MachOExtensions import Utilities +// Internal use only. open class MachOCache { private let memoryPressureMonitor = MemoryPressureMonitor() - private init() { + package init() { memoryPressureMonitor.memoryWarningHandler = { [weak self] in - self?.cacheEntryByIdentifier.removeAll() + self?.entryByIdentifier.removeAll() } memoryPressureMonitor.memoryCriticalHandler = { [weak self] in - self?.cacheEntryByIdentifier.removeAll() + self?.entryByIdentifier.removeAll() } memoryPressureMonitor.startMonitoring() } - - private var cacheEntryByIdentifier: [AnyHashable: Entry] = [:] - + + private var entryByIdentifier: [AnyHashable: Entry] = [:] + + @discardableResult + private func createEntryIfNeeded(in machO: MachO, isForced: Bool = false) -> Bool { + guard isForced || (entryByIdentifier[machO.identifier] == nil) else { return false } + entryByIdentifier[machO.identifier] = buildEntry(for: machO) + return true + } + + open func buildEntry(for machO: MachO) -> Entry? { + return nil + } + + package func entry(in machO: MachO) -> Entry? { + createEntryIfNeeded(in: machO) + if let cacheEntry = entryByIdentifier[machO.identifier] { + return cacheEntry + } else { + return nil + } + } } diff --git a/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift b/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift index 8a8268b3..a99e5465 100644 --- a/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift +++ b/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift @@ -1,7 +1,7 @@ import MachOKit import MachOExtensions -package protocol MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache { +public protocol MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache { associatedtype SwiftSection: SwiftSectionRepresentable var swift: SwiftSection { get } diff --git a/Sources/MachOSymbols/SymbolCache.swift b/Sources/MachOSymbols/SymbolCache.swift index 72889426..c46a6b9d 100644 --- a/Sources/MachOSymbols/SymbolCache.swift +++ b/Sources/MachOSymbols/SymbolCache.swift @@ -3,36 +3,20 @@ import MachOExtensions import Demangle import OrderedCollections import Utilities +import MachOCaches -package final class SymbolCache { +package final class SymbolCache: MachOCache { package static let shared = SymbolCache() - private let memoryPressureMonitor = MemoryPressureMonitor() + private override init() { super.init() } - private init() { - memoryPressureMonitor.memoryWarningHandler = { [weak self] in - self?.cacheEntryByIdentifier.removeAll() - } - - memoryPressureMonitor.memoryCriticalHandler = { [weak self] in - self?.cacheEntryByIdentifier.removeAll() - } - - memoryPressureMonitor.startMonitoring() - } - - private struct CacheEntry { - var isLoaded: Bool = false - var symbolsByOffset: OrderedDictionary = [:] - var demangledNodeBySymbol: [Symbol: Node] = [:] + package final class Entry { + fileprivate var symbolsByOffset: OrderedDictionary = [:] + fileprivate var demangledNodeBySymbol: [Symbol: Node] = [:] } - private var cacheEntryByIdentifier: [AnyHashable: CacheEntry] = [:] - - @discardableResult - package func createCacheIfNeeded(in machO: MachO, isForced: Bool = false) -> Bool { - guard isForced || ((cacheEntryByIdentifier[machO.identifier].map(\.isLoaded) ?? false) == false) else { return false } - var cacheEntry: CacheEntry = .init() + package override func buildEntry(for machO: MachO) -> Entry? where MachO: MachORepresentableWithCache { + let cacheEntry = Entry() var cachedSymbols: Set = [] for symbol in machO.symbols where symbol.name.isSwiftSymbol { var offset = symbol.offset @@ -51,7 +35,7 @@ package final class SymbolCache { cacheEntry.symbolsByOffset[offset, default: []].append(.init(offset: offset, stringValue: exportedSymbol.name)) } } - + // for symbol in cacheEntry.symbolsByOffset.values.flatMap({ $0 }) { // do { // let node = try demangleAsNode(symbol.stringValue) @@ -60,29 +44,24 @@ package final class SymbolCache { // print(error) // } // } - - cacheEntry.isLoaded = true - cacheEntryByIdentifier[machO.identifier] = cacheEntry - return true + + return cacheEntry } package func symbols(for offset: Int, in machO: MachO) -> Symbols? { - createCacheIfNeeded(in: machO) - if let symbols = cacheEntryByIdentifier[machO.identifier]?.symbolsByOffset[offset], !symbols.isEmpty { + if let symbols = entry(in: machO)?.symbolsByOffset[offset], !symbols.isEmpty { return .init(offset: offset, symbols: symbols) } else { return nil } } - + package func demangledNode(for symbol: Symbol, in machO: MachO) -> Node? { - createCacheIfNeeded(in: machO) - guard var cacheEntry = cacheEntryByIdentifier[machO.identifier] else { return nil } + guard let cacheEntry = entry(in: machO) else { return nil } if let node = cacheEntry.demangledNodeBySymbol[symbol] { return node } else if let node = try? demangleAsNode(symbol.stringValue) { cacheEntry.demangledNodeBySymbol[symbol] = node - cacheEntryByIdentifier[machO.identifier] = cacheEntry return node } else { return nil diff --git a/Sources/MachOSymbols/SymbolIndexStore.swift b/Sources/MachOSymbols/SymbolIndexStore.swift index 918adef5..a3703607 100644 --- a/Sources/MachOSymbols/SymbolIndexStore.swift +++ b/Sources/MachOSymbols/SymbolIndexStore.swift @@ -4,8 +4,9 @@ import MachOExtensions import Demangle import OrderedCollections import Utilities +import MachOCaches -package final class SymbolIndexStore { +package final class SymbolIndexStore: MachOCache { package enum IndexKind: Hashable, CaseIterable, CustomStringConvertible { case allocator case allocatorInExtension @@ -17,7 +18,7 @@ package final class SymbolIndexStore { case variableInExtension case staticVariable case staticVariableInExtension - + package var description: String { switch self { case .allocator: @@ -46,34 +47,16 @@ package final class SymbolIndexStore { package static let shared = SymbolIndexStore() - private let memoryPressureMonitor = MemoryPressureMonitor() - - private init() { - memoryPressureMonitor.memoryWarningHandler = { [weak self] in - self?.indexEntryByIdentifier.removeAll() - } - - memoryPressureMonitor.memoryCriticalHandler = { [weak self] in - self?.indexEntryByIdentifier.removeAll() - } - - memoryPressureMonitor.startMonitoring() + private override init() { + super.init() } - private struct IndexEntry { - var isIndexed: Bool = false - var symbolsByKind: [IndexKind: [String: [Symbol]]] = [:] + package struct Entry { + fileprivate var symbolsByKind: [IndexKind: [String: [Symbol]]] = [:] } - private var indexEntryByIdentifier: [AnyHashable: IndexEntry] = [:] - - - @discardableResult - package func startIndexingIfNeeded(in machO: MachO) -> Bool { - if let existedEntry = indexEntryByIdentifier[machO.identifier], existedEntry.isIndexed { - return true - } - var entry = IndexEntry() + package override func buildEntry(for machO: MachO) -> Entry? where MachO: MachORepresentableWithCache { + var entry = Entry() var symbols: OrderedDictionary = [:] @@ -89,7 +72,6 @@ package final class SymbolIndexStore { for symbol in symbols.values { do { - let node = try demangleAsNode(symbol.stringValue) func perform(_ node: Node, isStatic: Bool) { @@ -159,14 +141,11 @@ package final class SymbolIndexStore { print(error) } } - entry.isIndexed = true - indexEntryByIdentifier[machO.identifier] = entry - return true + return entry } package func symbols(of kind: IndexKind, for name: String, in machO: MachO) -> [Symbol] { - startIndexingIfNeeded(in: machO) - if let symbol = indexEntryByIdentifier[machO.identifier]?.symbolsByKind[kind]?[name] { + if let symbol = entry(in: machO)?.symbolsByKind[kind]?[name] { return symbol } else { return [] diff --git a/Sources/MachOTestingSupport/DumpableTests.swift b/Sources/MachOTestingSupport/DumpableTests.swift index d908599d..def11c2a 100644 --- a/Sources/MachOTestingSupport/DumpableTests.swift +++ b/Sources/MachOTestingSupport/DumpableTests.swift @@ -12,18 +12,16 @@ package protocol DumpableTests { extension DumpableTests { package var isEnabledSearchMetadata: Bool { false } - @MachOImageGenerator @MainActor - package func dumpProtocols(for machO: MachOFile) async throws { + package func dumpProtocols(for machO: MachO) async throws { let protocolDescriptors = try machO.swift.protocolDescriptors for protocolDescriptor in protocolDescriptors { try Protocol(descriptor: protocolDescriptor, in: machO).dump(using: .test, in: machO).string.print() } } - @MachOImageGenerator @MainActor - package func dumpProtocolConformances(for machO: MachOFile) async throws { + package func dumpProtocolConformances(for machO: MachO) async throws { let protocolConformanceDescriptors = try machO.swift.protocolConformanceDescriptors for protocolConformanceDescriptor in protocolConformanceDescriptors { @@ -31,11 +29,10 @@ extension DumpableTests { } } - @MachOImageGenerator @MainActor - package func dumpTypes(for machO: MachOFile) async throws { + package func dumpTypes(for machO: MachO) async throws { let typeContextDescriptors = try machO.swift.typeContextDescriptors - var metadataFinder: MetadataFinder? + var metadataFinder: MetadataFinder? if isEnabledSearchMetadata { metadataFinder = MetadataFinder(machO: machO) } @@ -77,19 +74,16 @@ extension DumpableTests { } } - @MachOImageGenerator @MainActor - package func dumpAssociatedTypes(for machO: MachOFile) async throws { + package func dumpAssociatedTypes(for machO: MachO) async throws { let associatedTypeDescriptors = try machO.swift.associatedTypeDescriptors for associatedTypeDescriptor in associatedTypeDescriptors { try AssociatedType(descriptor: associatedTypeDescriptor, in: machO).dump(using: .test, in: machO).string.print() } } - - @MachOImageGenerator @MainActor - package func dumpBuiltinTypes(for machO: MachOFile) async throws { + package func dumpBuiltinTypes(for machO: MachO) async throws { let descriptors = try machO.swift.builtinTypeDescriptors for descriptor in descriptors { print(try BuiltinType(descriptor: descriptor, in: machO)) diff --git a/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift b/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift index b7907a97..14559f2d 100644 --- a/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift @@ -6,59 +6,80 @@ import Semantic import Utilities import MachOFoundation -extension AssociatedType: ConformedDumpable { - @SemanticStringBuilder - public func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - try MetadataReader.demangleSymbol(for: conformingTypeName, in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - } - - @SemanticStringBuilder - public func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - try MetadataReader.demangleSymbol(for: protocolTypeName, in: machO).printSemantic(using: options) - } +private struct AssociatedTypeDumper: ConformedDumper { + let associatedType: AssociatedType + let options: DemangleOptions + let machO: MachO - @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - Keyword(.extension) + var body: SemanticString { + get throws { + Keyword(.extension) - Space() + Space() - try dumpTypeName(using: options, in: machO) + try typeName - Standard(":") + Standard(":") - Space() + Space() - try dumpProtocolName(using: options, in: machO) + try protocolName - Space() + Space() - Standard("{") + Standard("{") - for (offset, record) in records.offsetEnumerated() { - BreakLine() + for (offset, record) in associatedType.records.offsetEnumerated() { + BreakLine() - Indent(level: 1) + Indent(level: 1) - Keyword(.typealias) + Keyword(.typealias) - Space() + Space() - try TypeDeclaration(kind: .other, record.name(in: machO)) + try TypeDeclaration(kind: .other, record.name(in: machO)) - Space() + Space() - Standard("=") + Standard("=") - Space() + Space() - try MetadataReader.demangleSymbol(for: record.substitutedTypeName(in: machO), in: machO).printSemantic(using: options) + try MetadataReader.demangleSymbol(for: record.substitutedTypeName(in: machO), in: machO).printSemantic(using: options) - if offset.isEnd { - BreakLine() + if offset.isEnd { + BreakLine() + } } + + Standard("}") } + } + + var typeName: SemanticString { + get throws { + try MetadataReader.demangleSymbol(for: associatedType.conformingTypeName, in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + } + } + + var protocolName: SemanticString { + get throws { + try MetadataReader.demangleSymbol(for: associatedType.protocolTypeName, in: machO).printSemantic(using: options) + } + } +} + +extension AssociatedType: ConformedDumpable { + public func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try AssociatedTypeDumper(associatedType: self, options: options, machO: machO).typeName + } + + public func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try AssociatedTypeDumper(associatedType: self, options: options, machO: machO).protocolName + } - Standard("}") + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try AssociatedTypeDumper(associatedType: self, options: options, machO: machO).body } } diff --git a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift index 1f122599..fccaa938 100644 --- a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift @@ -6,128 +6,155 @@ import MachOFoundation import MachOSwiftSection import Utilities -extension Class: NamedDumpable { - public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - try MetadataReader.demangleContext(for: .type(.class(descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - } +private struct ClassDumper: NamedDumper { + let `class`: Class + let options: DemangleOptions + let machO: MachO + + var body: SemanticString { + get throws { + if `class`.descriptor.isActor { + Keyword(.actor) + } else { + Keyword(.class) + } - @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - if descriptor.isActor { - Keyword(.actor) - } else { - Keyword(.class) - } + Space() - Space() + let name = try self.name - try dumpName(using: options, in: machO) + let interfaceNameString = try interfaceName.string - if let genericContext { - if genericContext.currentParameters.count > 0 { - try genericContext.dumpGenericParameters(in: machO) + name + + if let genericContext = `class`.genericContext { + if genericContext.currentParameters.count > 0 { + try genericContext.dumpGenericParameters(in: machO) + } } - } - if let superclassMangledName = try descriptor.superclassTypeMangledName(in: machO) { - Standard(":") - Space() - try MetadataReader.demangleType(for: superclassMangledName, in: machO).printSemantic(using: options) - } else if let resilientSuperclass, let kind = descriptor.resilientSuperclassReferenceKind, let superclass = try resilientSuperclass.dumpSuperclass(using: options, for: kind, in: machO) { - Standard(":") - Space() - superclass - } + if let superclassMangledName = try `class`.descriptor.superclassTypeMangledName(in: machO) { + Standard(":") + Space() + try MetadataReader.demangleType(for: superclassMangledName, in: machO).printSemantic(using: options) + } else if let resilientSuperclass = `class`.resilientSuperclass, let kind = `class`.descriptor.resilientSuperclassReferenceKind, let superclass = try resilientSuperclass.dumpSuperclass(using: options, for: kind, in: machO) { + Standard(":") + Space() + superclass + } - if let genericContext, genericContext.currentRequirements.count > 0 { - Space() - Keyword(.where) + if let genericContext = `class`.genericContext, genericContext.currentRequirements.count > 0 { + Space() + Keyword(.where) + Space() + try genericContext.dumpGenericRequirements(using: options, in: machO) + } Space() - try genericContext.dumpGenericRequirements(using: options, in: machO) - } - Space() - - Standard("{") - - for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { - BreakLine() - - Indent(level: 1) - let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machO), in: machO) + Standard("{") - let fieldName = try fieldRecord.fieldName(in: machO) + for (offset, fieldRecord) in try `class`.descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { + BreakLine() - if fieldRecord.flags.contains(.isVariadic) { - if demangledTypeNode.hasWeakNode { - Keyword(.weak) - Space() - Keyword(.var) - Space() - } else if fieldName.hasLazyPrefix { - Keyword(.lazy) - Space() - Keyword(.var) - Space() + Indent(level: 1) + + let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machO), in: machO) + + let fieldName = try fieldRecord.fieldName(in: machO) + + if fieldRecord.flags.contains(.isVariadic) { + if demangledTypeNode.hasWeakNode { + Keyword(.weak) + Space() + Keyword(.var) + Space() + } else if fieldName.hasLazyPrefix { + Keyword(.lazy) + Space() + Keyword(.var) + Space() + } else { + Keyword(.var) + Space() + } } else { - Keyword(.var) + Keyword(.let) Space() } - } else { - Keyword(.let) - Space() - } - MemberDeclaration(fieldName.stripLazyPrefix) + MemberDeclaration(fieldName.stripLazyPrefix) - Standard(":") + Standard(":") - Space() + Space() - demangledTypeNode.printSemantic(using: options.union(.removeWeakPrefix)) + demangledTypeNode.printSemantic(using: options.union(.removeWeakPrefix)) - if offset.isEnd { - BreakLine() + if offset.isEnd { + BreakLine() + } } - } - for (offset, descriptor) in methodDescriptors.offsetEnumerated() { - BreakLine() + for (offset, descriptor) in `class`.methodDescriptors.offsetEnumerated() { + BreakLine() - Indent(level: 1) + Indent(level: 1) - dumpMethodKind(for: descriptor) + dumpMethodKind(for: descriptor) - dumpMethodKeyword(for: descriptor) + dumpMethodKeyword(for: descriptor) - try dumpMethodDeclaration(for: descriptor, using: options, in: machO) + try dumpMethodDeclaration(for: descriptor) - if offset.isEnd { - BreakLine() + if offset.isEnd { + BreakLine() + } } - } - - for (offset, descriptor) in methodOverrideDescriptors.offsetEnumerated() { - BreakLine() - Indent(level: 1) + for (offset, descriptor) in `class`.methodOverrideDescriptors.offsetEnumerated() { + BreakLine() - if let methodDescriptor = try descriptor.methodDescriptor(in: machO) { - switch methodDescriptor { - case .symbol(let symbol): - Keyword(.override) - Space() - try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) - case .element(let element): - dumpMethodKind(for: element) + Indent(level: 1) + + if let methodDescriptor = try descriptor.methodDescriptor(in: machO) { + switch methodDescriptor { + case .symbol(let symbol): + Keyword(.override) + Space() + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) + case .element(let element): + dumpMethodKind(for: element) + Keyword(.override) + Space() + dumpMethodKeyword(for: element) + try? dumpMethodDeclaration(for: element) + } + } else { Keyword(.override) Space() - dumpMethodKeyword(for: element) - try? dumpMethodDeclaration(for: element, using: options, in: machO) + if let symbol = try? descriptor.implementationSymbol(in: machO) { + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) + } else if !descriptor.implementation.isNull { + FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) + } else { + Error("Symbol not found") + } } - } else { + + if offset.isEnd { + BreakLine() + } + } + + for (offset, descriptor) in `class`.methodDefaultOverrideDescriptors.offsetEnumerated() { + BreakLine() + + Indent(level: 1) + Keyword(.override) + Space() + if let symbol = try? descriptor.implementationSymbol(in: machO) { try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { @@ -135,36 +162,30 @@ extension Class: NamedDumpable { } else { Error("Symbol not found") } - } - if offset.isEnd { - BreakLine() + if offset.isEnd { + BreakLine() + } } - } - - for (offset, descriptor) in methodDefaultOverrideDescriptors.offsetEnumerated() { - BreakLine() - - Indent(level: 1) - Keyword(.override) - - Space() + Standard("}") + } + } - if let symbol = try? descriptor.implementationSymbol(in: machO) { - try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) - } else if !descriptor.implementation.isNull { - FunctionDeclaration(addressString(of: descriptor.implementation.resolveDirectOffset(from: descriptor.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) - } else { - Error("Symbol not found") - } + var name: SemanticString { + get throws { + try _name(using: options) + } + } - if offset.isEnd { - BreakLine() - } + private var interfaceName: SemanticString { + get throws { + try _name(using: .interface) } + } - Standard("}") + private func _name(using options: DemangleOptions) throws -> SemanticString { + try MetadataReader.demangleContext(for: .type(.class(`class`.descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() } @SemanticStringBuilder @@ -193,7 +214,7 @@ extension Class: NamedDumpable { } @SemanticStringBuilder - private func dumpMethodDeclaration(for descriptor: MethodDescriptor, using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + private func dumpMethodDeclaration(for descriptor: MethodDescriptor) throws -> SemanticString { if let symbol = try? descriptor.implementationSymbol(in: machO) { try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) } else if !descriptor.implementation.isNull { @@ -203,3 +224,13 @@ extension Class: NamedDumpable { } } } + +extension Class: NamedDumpable { + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ClassDumper(class: self, options: options, machO: machO).name + } + + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ClassDumper(class: self, options: options, machO: machO).body + } +} diff --git a/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift b/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift index 620548ba..4e7a7971 100644 --- a/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift @@ -7,90 +7,121 @@ import Semantic import MachOSymbols import Utilities -extension Enum: NamedDumpable { - public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - try MetadataReader.demangleContext(for: .type(.enum(descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - } +private struct EnumDumper: NamedDumper { + let `enum`: Enum + let options: DemangleOptions + let machO: MachO - @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - Keyword(.enum) + var body: SemanticString { + get throws { + Keyword(.enum) - Space() + Space() - try dumpName(using: options, in: machO) + let name = try self.name - if let genericContext { - if genericContext.currentParameters.count > 0 { - try genericContext.dumpGenericParameters(in: machO) - } - if genericContext.currentRequirements.count > 0 { - Space() - Keyword(.where) - Space() - try genericContext.dumpGenericRequirements(using: options, in: machO) - } - } - Space() - Standard("{") - for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { - BreakLine() - - Indent(level: 1) - - if fieldRecord.flags.contains(.isIndirectCase) { - Keyword(.indirect) - Space() - Keyword(.case) - Space() - } else { - Keyword(.case) - Space() - } + let interfaceNameString = try interfaceName.string - try MemberDeclaration("\(fieldRecord.fieldName(in: machO))") + name + + if let genericContext = `enum`.genericContext { + if genericContext.currentParameters.count > 0 { + try genericContext.dumpGenericParameters(in: machO) + } + if genericContext.currentRequirements.count > 0 { + Space() + Keyword(.where) + Space() + try genericContext.dumpGenericRequirements(using: options, in: machO) + } + } + Space() + Standard("{") + for (offset, fieldRecord) in try `enum`.descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { + BreakLine() - let mangledName = try fieldRecord.mangledTypeName(in: machO) + Indent(level: 1) - if !mangledName.isEmpty { - let demangledName = try MetadataReader.demangleType(for: mangledName, in: machO).printSemantic(using: options) - let demangledNameString = demangledName.string - if demangledNameString.hasPrefix("("), demangledNameString.hasSuffix(")") { - demangledName + if fieldRecord.flags.contains(.isIndirectCase) { + Keyword(.indirect) + Space() + Keyword(.case) + Space() } else { - Standard("(") - demangledName - Standard(")") + Keyword(.case) + Space() } - } - if offset.isEnd { - BreakLine() - } - } + try MemberDeclaration("\(fieldRecord.fieldName(in: machO))") - for kind in SymbolIndexStore.IndexKind.allCases { - for (offset, function) in try SymbolIndexStore.shared.symbols(of: kind, for: dumpName(using: .interface, in: machO).string, in: machO).offsetEnumerated() { - if offset.isStart { - BreakLine() + let mangledName = try fieldRecord.mangledTypeName(in: machO) - Indent(level: 1) + if !mangledName.isEmpty { + let demangledName = try MetadataReader.demangleType(for: mangledName, in: machO).printSemantic(using: options) + let demangledNameString = demangledName.string + if demangledNameString.hasPrefix("("), demangledNameString.hasSuffix(")") { + demangledName + } else { + Standard("(") + demangledName + Standard(")") + } + } - InlineComment(kind.description) + if offset.isEnd { + BreakLine() } + } - BreakLine() + for kind in SymbolIndexStore.IndexKind.allCases { + for (offset, function) in SymbolIndexStore.shared.symbols(of: kind, for: interfaceNameString, in: machO).offsetEnumerated() { + if offset.isStart { + BreakLine() - Indent(level: 1) + Indent(level: 1) - try MetadataReader.demangleSymbol(for: function, in: machO)?.printSemantic(using: options) + InlineComment(kind.description) + } - if offset.isEnd { BreakLine() + + Indent(level: 1) + + try MetadataReader.demangleSymbol(for: function, in: machO)?.printSemantic(using: options) + + if offset.isEnd { + BreakLine() + } } } + + Standard("}") + } + } + + var name: SemanticString { + get throws { + try _name(using: options) } + } + + private var interfaceName: SemanticString { + get throws { + try _name(using: .interface) + } + } + + private func _name(using options: DemangleOptions) throws -> SemanticString { + try MetadataReader.demangleContext(for: .type(.enum(`enum`.descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + } +} + +extension Enum: NamedDumpable { + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try EnumDumper(enum: self, options: options, machO: machO).name + } - Standard("}") + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try EnumDumper(enum: self, options: options, machO: machO).body } } diff --git a/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift index 08f21ed0..c4baef26 100644 --- a/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift @@ -8,95 +8,118 @@ import Utilities import Demangle import OrderedCollections -extension MachOSwiftSection.`Protocol`: NamedDumpable { - public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - try MetadataReader.demangleContext(for: .protocol(descriptor), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - } +private struct ProtocolDumper: NamedDumper { + let `protocol`: MachOSwiftSection.`Protocol` - @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - Keyword(.protocol) + let options: DemangleOptions - Space() + let machO: MachO - try dumpName(using: options, in: machO) + var body: SemanticString { + get throws { + Keyword(.protocol) - if numberOfRequirementsInSignature > 0 { Space() - Keyword(.where) + + try name + + if `protocol`.numberOfRequirementsInSignature > 0 { + Space() + Keyword(.where) + Space() + + for (offset, requirement) in `protocol`.requirementInSignatures.offsetEnumerated() { + try requirement.dump(using: options, in: machO) + if !offset.isEnd { + Standard(",") + Space() + } + } + } Space() + Standard("{") - for (offset, requirement) in requirementInSignatures.offsetEnumerated() { - try requirement.dump(using: options, in: machO) - if !offset.isEnd { - Standard(",") + let associatedTypes = try `protocol`.descriptor.associatedTypes(in: machO) + + if !associatedTypes.isEmpty { + for (offset, associatedType) in associatedTypes.offsetEnumerated() { + BreakLine() + Indent(level: 1) + Keyword(.associatedtype) Space() + TypeDeclaration(kind: .other, associatedType) + if offset.isEnd { + BreakLine() + } } } - } - Space() - Standard("{") - let associatedTypes = try descriptor.associatedTypes(in: machO) + var defaultImplementations: OrderedSet = [] - if !associatedTypes.isEmpty { - for (offset, associatedType) in associatedTypes.offsetEnumerated() { + for (offset, requirement) in `protocol`.requirements.offsetEnumerated() { BreakLine() Indent(level: 1) - Keyword(.associatedtype) - Space() - TypeDeclaration(kind: .other, associatedType) + if let symbols = try Symbols.resolve(from: requirement.offset, in: machO), let validNode = try validNode(for: symbols) { + validNode.printSemantic(using: options) + } else { + InlineComment("[Stripped Symbol]") + } + + if let symbols = try requirement.defaultImplementationSymbols(in: machO), let defaultImplementation = try validNode(for: symbols, visitedNode: defaultImplementations) { + _ = defaultImplementations.append(defaultImplementation) + } + if offset.isEnd { BreakLine() } } - } - var defaultImplementations: OrderedSet = [] - - for (offset, requirement) in requirements.offsetEnumerated() { - BreakLine() - Indent(level: 1) - if let symbols = try Symbols.resolve(from: requirement.offset, in: machO), let validNode = try validNode(for: symbols, in: machO) { - validNode.printSemantic(using: options) - } else { - InlineComment("[Stripped Symbol]") - } - - if let symbols = try requirement.defaultImplementationSymbols(in: machO), let defaultImplementation = try validNode(for: symbols, in: machO, visitedNode: defaultImplementations) { - _ = defaultImplementations.append(defaultImplementation) - } - - if offset.isEnd { - BreakLine() - } - } - - for (offset, defaultImplementation) in defaultImplementations.offsetEnumerated() { - - if offset.isStart { + for (offset, defaultImplementation) in defaultImplementations.offsetEnumerated() { + if offset.isStart { + BreakLine() + Indent(level: 1) + InlineComment("[Default Implementation]") + } + BreakLine() Indent(level: 1) - InlineComment("[Default Implementation]") - } - - BreakLine() - Indent(level: 1) - defaultImplementation.printSemantic(using: options) - - if offset.isEnd { - BreakLine() + defaultImplementation.printSemantic(using: options) + + if offset.isEnd { + BreakLine() + } } + Standard("}") + } + } + + var name: SemanticString { + get throws { + try _name(using: options) } - Standard("}") } - - private func validNode(for symbols: Symbols, in machO: MachO, visitedNode: borrowing OrderedSet = []) throws -> Node? { + + private func _name(using options: DemangleOptions) throws -> SemanticString { + try MetadataReader.demangleContext(for: .protocol(`protocol`.descriptor), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + } + + private func validNode(for symbols: Symbols, visitedNode: borrowing OrderedSet = []) throws -> Node? { + let currentInterfaceName = try _name(using: .interfaceType).string for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolNode = node.preorder().first(where: { $0.kind == .protocol }), protocolNode.print(using: .interface) == (try dumpName(using: .interfaceType, in: machO)).string, !visitedNode.contains(node) { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolNode = node.preorder().first(where: { $0.kind == .protocol }), protocolNode.print(using: .interfaceType) == currentInterfaceName, !visitedNode.contains(node) { return node } } return nil } } + +extension MachOSwiftSection.`Protocol`: NamedDumpable { + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ProtocolDumper(protocol: self, options: options, machO: machO).name + } + + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ProtocolDumper(protocol: self, options: options, machO: machO).body + } +} diff --git a/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift index 2edab1f3..a650f966 100644 --- a/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift @@ -8,127 +8,140 @@ import Demangle import Utilities import OrderedCollections -extension ProtocolConformance: ConformedDumpable { - @SemanticStringBuilder - public func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - switch typeReference { - case .directTypeDescriptor(let descriptor): - try descriptor?.dumpName(using: options, in: machO).replacingTypeNameOrOtherToTypeDeclaration() - case .indirectTypeDescriptor(let descriptor): - switch descriptor { - case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - case .element(let element): - try element.dumpName(using: options, in: machO).replacingTypeNameOrOtherToTypeDeclaration() - case nil: - Standard("") - } - case .directObjCClassName(let objcClassName): - TypeDeclaration(kind: .class, objcClassName.valueOrEmpty) - case .indirectObjCClass(let objcClass): - switch objcClass { - case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - case .element(let element): - try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machO))), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - case nil: - Standard("") - } - } - } +private struct ProtocolConformanceDumper: ConformedDumper { + let protocolConformance: ProtocolConformance - @SemanticStringBuilder - public func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - switch `protocol` { - case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) - case .element(let element): - try MetadataReader.demangleContext(for: .protocol(element), in: machO).printSemantic(using: options) - case .none: - Standard("") - } - } + let options: DemangleOptions - @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - Keyword(.extension) + let machO: MachO - Space() + var typeNameOptions: DemangleOptions { .interfaceType } - let typeName = try dumpTypeName(using: options, in: machO) + var body: SemanticString { + get throws { + Keyword(.extension) - typeName + Space() - let interfaceTypeName = try dumpTypeName(using: .interfaceType, in: machO).string + let typeName = try self.typeName - Standard(":") + let typeNameString = typeName.string - Space() + typeName - try dumpProtocolName(using: options, in: machO) + Standard(":") - if !conditionalRequirements.isEmpty { - Space() - Keyword(.where) Space() - } - - for conditionalRequirement in conditionalRequirements { - try conditionalRequirement.dump(using: options, in: machO) - } - if resilientWitnesses.isEmpty { - Space() - Standard("{}") - } else { - Space() - Standard("{") + try protocolName - var visitedNodes: OrderedSet = [] + if !protocolConformance.conditionalRequirements.isEmpty { + Space() + Keyword(.where) + Space() + } - for resilientWitness in resilientWitnesses { - BreakLine() + for conditionalRequirement in protocolConformance.conditionalRequirements { + try conditionalRequirement.dump(using: options, in: machO) + } - Indent(level: 1) - - if let symbols = try resilientWitness.implementationSymbols(in: machO), let validNode = try validNode(for: symbols, in: machO, typeName: interfaceTypeName, visitedNode: visitedNodes) { - _ = visitedNodes.append(validNode) - validNode.printSemantic(using: options) - } else if let requirement = try resilientWitness.requirement(in: machO) { - switch requirement { - case .symbol(let symbol): - try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) - case .element(let element): - if let symbols = try Symbols.resolve(from: element.offset, in: machO), let validNode = try validNode(for: symbols, in: machO, typeName: interfaceTypeName, visitedNode: visitedNodes) { - _ = visitedNodes.append(validNode) - validNode.printSemantic(using: options) - } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machO), let validNode = try validNode(for: defaultImplementationSymbols, in: machO, typeName: interfaceTypeName, visitedNode: visitedNodes) { - _ = visitedNodes.append(validNode) - validNode.printSemantic(using: options) - } else if !element.defaultImplementation.isNull { - FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machO).insertSubFunctionPrefix) - } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) - } else { - Error("Symbol not found") + if protocolConformance.resilientWitnesses.isEmpty { + Space() + Standard("{}") + } else { + Space() + Standard("{") + + var visitedNodes: OrderedSet = [] + + for resilientWitness in protocolConformance.resilientWitnesses { + BreakLine() + + Indent(level: 1) + + if let symbols = try resilientWitness.implementationSymbols(in: machO), let validNode = try validNode(for: symbols, typeName: typeNameString, visitedNode: visitedNodes) { + _ = visitedNodes.append(validNode) + validNode.printSemantic(using: options) + } else if let requirement = try resilientWitness.requirement(in: machO) { + switch requirement { + case .symbol(let symbol): + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) + case .element(let element): + if let symbols = try Symbols.resolve(from: element.offset, in: machO), let validNode = try validNode(for: symbols, typeName: typeNameString, visitedNode: visitedNodes) { + _ = visitedNodes.append(validNode) + validNode.printSemantic(using: options) + } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machO), let validNode = try validNode(for: defaultImplementationSymbols, typeName: typeNameString, visitedNode: visitedNodes) { + _ = visitedNodes.append(validNode) + validNode.printSemantic(using: options) + } else if !element.defaultImplementation.isNull { + FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machO).insertSubFunctionPrefix) + } else if !resilientWitness.implementation.isNull { + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) + } else { + Error("Symbol not found") + } } + } else if !resilientWitness.implementation.isNull { + FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) + } else { + Error("Symbol not found") } - } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) - } else { - Error("Symbol not found") } + + BreakLine() + + Standard("}") } + } + } - BreakLine() + @SemanticStringBuilder + var typeName: SemanticString { + get throws { + switch protocolConformance.typeReference { + case .directTypeDescriptor(let descriptor): + try descriptor?.dumpName(using: typeNameOptions, in: machO).replacingTypeNameOrOtherToTypeDeclaration() + case .indirectTypeDescriptor(let descriptor): + switch descriptor { + case .symbol(let unsolvedSymbol): + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + case .element(let element): + try element.dumpName(using: typeNameOptions, in: machO).replacingTypeNameOrOtherToTypeDeclaration() + case nil: + Standard("") + } + case .directObjCClassName(let objcClassName): + TypeDeclaration(kind: .class, objcClassName.valueOrEmpty) + case .indirectObjCClass(let objcClass): + switch objcClass { + case .symbol(let unsolvedSymbol): + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + case .element(let element): + try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machO))), in: machO).printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + case nil: + Standard("") + } + } + } + } - Standard("}") + @SemanticStringBuilder + var protocolName: SemanticString { + get throws { + switch protocolConformance.`protocol` { + case .symbol(let unsolvedSymbol): + try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) + case .element(let element): + try MetadataReader.demangleContext(for: .protocol(element), in: machO).printSemantic(using: options) + case .none: + Standard("") + } } } - private func validNode(for symbols: Symbols, in machO: MachO, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { + private func validNode(for symbols: Symbols, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { + if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), (symbolTypeName == typeName || PrimitiveTypeMappingCache.shared.entry(in: machO)?.primitiveType(for: typeName) == symbolTypeName) { return node } } @@ -136,4 +149,16 @@ extension ProtocolConformance: ConformedDumpable { } } +extension ProtocolConformance: ConformedDumpable { + public func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ProtocolConformanceDumper(protocolConformance: self, options: options, machO: machO).typeName + } + + public func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ProtocolConformanceDumper(protocolConformance: self, options: options, machO: machO).protocolName + } + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try ProtocolConformanceDumper(protocolConformance: self, options: options, machO: machO).body + } +} diff --git a/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift index 172d1ec6..d45f3031 100644 --- a/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumpable.swift @@ -1,8 +1,9 @@ import MachOKit import Semantic import MachOFoundation +import MachOSwiftSection public protocol ConformedDumpable: Dumpable { - func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString - func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString + func dumpTypeName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString + func dumpProtocolName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString } diff --git a/Sources/SwiftDump/Dumper/Protocols/ConformedDumper.swift b/Sources/SwiftDump/Dumpable/Protocols/ConformedDumper.swift similarity index 100% rename from Sources/SwiftDump/Dumper/Protocols/ConformedDumper.swift rename to Sources/SwiftDump/Dumpable/Protocols/ConformedDumper.swift diff --git a/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift index ab325f10..f361f2bc 100644 --- a/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocols/Dumpable.swift @@ -2,11 +2,12 @@ import Demangle import MachOKit import Semantic import MachOFoundation +import MachOSwiftSection public typealias DemangleOptions = Demangle.DemangleOptions public protocol Dumpable { - func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString + func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString } diff --git a/Sources/SwiftDump/Dumper/Protocols/Dumper.swift b/Sources/SwiftDump/Dumpable/Protocols/Dumper.swift similarity index 100% rename from Sources/SwiftDump/Dumper/Protocols/Dumper.swift rename to Sources/SwiftDump/Dumpable/Protocols/Dumper.swift diff --git a/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift b/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift index e91ddb00..77ae3200 100644 --- a/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift +++ b/Sources/SwiftDump/Dumpable/Protocols/NamedDumpable.swift @@ -1,7 +1,8 @@ import MachOKit import Semantic import MachOFoundation +import MachOSwiftSection public protocol NamedDumpable: Dumpable { - func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString + func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString } diff --git a/Sources/SwiftDump/Dumpable/Protocols/NamedDumper.swift b/Sources/SwiftDump/Dumpable/Protocols/NamedDumper.swift new file mode 100644 index 00000000..fb4e7232 --- /dev/null +++ b/Sources/SwiftDump/Dumpable/Protocols/NamedDumper.swift @@ -0,0 +1,5 @@ +import Semantic + +protocol NamedDumper: Dumper { + @SemanticStringBuilder var name: SemanticString { get throws } +} diff --git a/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift b/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift index f9b6da02..c08e9834 100644 --- a/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift @@ -7,96 +7,129 @@ import MachOSymbols import Utilities import MachOFoundation -extension Struct: NamedDumpable { - public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - try MetadataReader.demangleContext(for: .type(.struct(descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() - } +private struct StructDumper: NamedDumper { + let `struct`: Struct - @SemanticStringBuilder - public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { - Keyword(.struct) + let options: DemangleOptions - Space() + let machO: MachO - try dumpName(using: options, in: machO) + var body: SemanticString { + get throws { + Keyword(.struct) - if let genericContext { - if genericContext.currentParameters.count > 0 { - try genericContext.dumpGenericParameters(in: machO) - } - if genericContext.currentRequirements.count > 0 { - Space() - Keyword(.where) - Space() - try genericContext.dumpGenericRequirements(using: options, in: machO) - } - } - - Space() - - Standard("{") - - for (offset, fieldRecord) in try descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { - BreakLine() + Space() - Indent(level: 1) + let name = try self.name - let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machO), in: machO) + let interfaceNameString = try interfaceName.string - let fieldName = try fieldRecord.fieldName(in: machO) + name - if fieldRecord.flags.contains(.isVariadic) { - if demangledTypeNode.hasWeakNode { - Keyword(.weak) - Space() - Keyword(.var) - Space() - } else if fieldName.hasLazyPrefix { - Keyword(.lazy) - Space() - Keyword(.var) + if let genericContext = `struct`.genericContext { + if genericContext.currentParameters.count > 0 { + try genericContext.dumpGenericParameters(in: machO) + } + if genericContext.currentRequirements.count > 0 { Space() - } else { - Keyword(.var) + Keyword(.where) Space() + try genericContext.dumpGenericRequirements(using: options, in: machO) } - } else { - Keyword(.let) - Space() } - MemberDeclaration(fieldName.stripLazyPrefix) - Standard(":") Space() - demangledTypeNode.printSemantic(using: options.union(.removeWeakPrefix)) - if offset.isEnd { + Standard("{") + + for (offset, fieldRecord) in try `struct`.descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { BreakLine() - } - } - for kind in SymbolIndexStore.IndexKind.allCases { - for (offset, symbol) in try SymbolIndexStore.shared.symbols(of: kind, for: dumpName(using: .interface, in: machO).string, in: machO).offsetEnumerated() { - if offset.isStart { - BreakLine() + Indent(level: 1) - Indent(level: 1) + let demangledTypeNode = try MetadataReader.demangleType(for: fieldRecord.mangledTypeName(in: machO), in: machO) + + let fieldName = try fieldRecord.fieldName(in: machO) + + if fieldRecord.flags.contains(.isVariadic) { + if demangledTypeNode.hasWeakNode { + Keyword(.weak) + Space() + Keyword(.var) + Space() + } else if fieldName.hasLazyPrefix { + Keyword(.lazy) + Space() + Keyword(.var) + Space() + } else { + Keyword(.var) + Space() + } + } else { + Keyword(.let) + Space() + } - InlineComment(kind.description) + MemberDeclaration(fieldName.stripLazyPrefix) + Standard(":") + Space() + demangledTypeNode.printSemantic(using: options.union(.removeWeakPrefix)) + + if offset.isEnd { + BreakLine() } + } - BreakLine() + for kind in SymbolIndexStore.IndexKind.allCases { + for (offset, symbol) in SymbolIndexStore.shared.symbols(of: kind, for: interfaceNameString, in: machO).offsetEnumerated() { + if offset.isStart { + BreakLine() - Indent(level: 1) + Indent(level: 1) - try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) + InlineComment(kind.description) + } - if offset.isEnd { BreakLine() + + Indent(level: 1) + + try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) + + if offset.isEnd { + BreakLine() + } } } + + Standard("}") } + } + + var name: SemanticString { + get throws { + try _name(using: options) + } + } + + private var interfaceName: SemanticString { + get throws { + try _name(using: .interface) + } + } + + private func _name(using options: DemangleOptions) throws -> SemanticString { + try MetadataReader.demangleContext(for: .type(.struct(`struct`.descriptor)), in: machO).printSemantic(using: options).replacingTypeNameOrOtherToTypeDeclaration() + } +} + +extension Struct: NamedDumpable { + public func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try StructDumper(struct: self, options: options, machO: machO).name + } - Standard("}") + public func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + try StructDumper(struct: self, options: options, machO: machO).body } } diff --git a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift b/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift deleted file mode 100644 index d1e05a6a..00000000 --- a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift +++ /dev/null @@ -1,150 +0,0 @@ -import Foundation -import MachOKit -import MachOSwiftSection -import MachOMacro -import MachOFoundation -import Semantic -import Demangle -import Utilities -import OrderedCollections - -struct ProtocolConformanceDumper: ConformedDumper { - let protocolConformance: ProtocolConformance - - let options: DemangleOptions - - let machO: MachO - - var typeNameOptions: DemangleOptions { .interfaceType } - - var body: SemanticString { - get throws { - Keyword(.extension) - - Space() - - let typeName = try self.typeName - - let typeNameString = typeName.string - - typeName - - Standard(":") - - Space() - - try protocolName - - if !protocolConformance.conditionalRequirements.isEmpty { - Space() - Keyword(.where) - Space() - } - - for conditionalRequirement in protocolConformance.conditionalRequirements { - try conditionalRequirement.dump(using: options, in: machO) - } - - if protocolConformance.resilientWitnesses.isEmpty { - Space() - Standard("{}") - } else { - Space() - Standard("{") - - var visitedNodes: OrderedSet = [] - - for resilientWitness in protocolConformance.resilientWitnesses { - BreakLine() - - Indent(level: 1) - - if let symbols = try resilientWitness.implementationSymbols(in: machO), let validNode = try validNode(for: symbols, typeName: typeNameString, visitedNode: visitedNodes) { - _ = visitedNodes.append(validNode) - validNode.printSemantic(using: options) - } else if let requirement = try resilientWitness.requirement(in: machO) { - switch requirement { - case .symbol(let symbol): - try MetadataReader.demangleSymbol(for: symbol, in: machO)?.printSemantic(using: options) - case .element(let element): - if let symbols = try Symbols.resolve(from: element.offset, in: machO), let validNode = try validNode(for: symbols, typeName: typeNameString, visitedNode: visitedNodes) { - _ = visitedNodes.append(validNode) - validNode.printSemantic(using: options) - } else if let defaultImplementationSymbols = try element.defaultImplementationSymbols(in: machO), let validNode = try validNode(for: defaultImplementationSymbols, typeName: typeNameString, visitedNode: visitedNodes) { - _ = visitedNodes.append(validNode) - validNode.printSemantic(using: options) - } else if !element.defaultImplementation.isNull { - FunctionDeclaration(addressString(of: element.defaultImplementation.resolveDirectOffset(from: element.offset(of: \.defaultImplementation)), in: machO).insertSubFunctionPrefix) - } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) - } else { - Error("Symbol not found") - } - } - } else if !resilientWitness.implementation.isNull { - FunctionDeclaration(addressString(of: resilientWitness.implementation.resolveDirectOffset(from: resilientWitness.offset(of: \.implementation)), in: machO).insertSubFunctionPrefix) - } else { - Error("Symbol not found") - } - } - - BreakLine() - - Standard("}") - } - } - } - - @SemanticStringBuilder - var typeName: SemanticString { - get throws { - switch protocolConformance.typeReference { - case .directTypeDescriptor(let descriptor): - try descriptor?.dumpName(using: typeNameOptions, in: machO).replacingTypeNameOrOtherToTypeDeclaration() - case .indirectTypeDescriptor(let descriptor): - switch descriptor { - case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() - case .element(let element): - try element.dumpName(using: typeNameOptions, in: machO).replacingTypeNameOrOtherToTypeDeclaration() - case nil: - Standard("") - } - case .directObjCClassName(let objcClassName): - TypeDeclaration(kind: .class, objcClassName.valueOrEmpty) - case .indirectObjCClass(let objcClass): - switch objcClass { - case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() - case .element(let element): - try MetadataReader.demangleContext(for: .type(.class(element.descriptor.resolve(in: machO))), in: machO).printSemantic(using: typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() - case nil: - Standard("") - } - } - } - } - - @SemanticStringBuilder - var protocolName: SemanticString { - get throws { - switch protocolConformance.`protocol` { - case .symbol(let unsolvedSymbol): - try MetadataReader.demangleType(for: unsolvedSymbol, in: machO)?.printSemantic(using: options) - case .element(let element): - try MetadataReader.demangleContext(for: .protocol(element), in: machO).printSemantic(using: options) - case .none: - Standard("") - } - } - } - - private func validNode(for symbols: Symbols, typeName: String, visitedNode: borrowing OrderedSet = []) throws -> Node? { - for symbol in symbols { - if let node = try? MetadataReader.demangleSymbol(for: symbol, in: machO), let protocolConformanceNode = node.preorder().first(where: { $0.kind == .protocolConformance }), let symbolTypeName = protocolConformanceNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName { - return node - } - } - return nil - } -} diff --git a/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift b/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift index d66dd781..0f0a00a6 100644 --- a/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift +++ b/Sources/SwiftDump/Extensions/ContextDescriptorWrapper+Dump.swift @@ -5,7 +5,7 @@ import MachOSwiftSection import Semantic extension ContextDescriptorWrapper { - package func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + package func dumpName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { try MetadataReader.demangleContext(for: self, in: machO).printSemantic(using: options) } } diff --git a/Sources/SwiftDump/Extensions/GenericContext+Dump.swift b/Sources/SwiftDump/Extensions/GenericContext+Dump.swift index db8f9643..f28107cd 100644 --- a/Sources/SwiftDump/Extensions/GenericContext+Dump.swift +++ b/Sources/SwiftDump/Extensions/GenericContext+Dump.swift @@ -7,7 +7,7 @@ import Utilities extension TargetGenericContext { @SemanticStringBuilder - package func dumpGenericParameters(in machO: MachO) throws -> SemanticString { + package func dumpGenericParameters(in machO: MachO) throws -> SemanticString { Standard("<") for (offset, _) in currentParameters.offsetEnumerated() { Standard(try genericParameterName(depth: depth, index: offset.index)) @@ -32,7 +32,7 @@ extension TargetGenericContext { } @SemanticStringBuilder - package func dumpGenericRequirements(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + package func dumpGenericRequirements(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { for (offset, requirement) in currentRequirements.offsetEnumerated() { try requirement.dump(using: options, in: machO) if !offset.isEnd { @@ -45,7 +45,7 @@ extension TargetGenericContext { extension GenericRequirementDescriptor { - package func dumpInheritedProtocol(using options: DemangleOptions, in machO: MachO) throws -> SemanticString? { + package func dumpInheritedProtocol(using options: DemangleOptions, in machO: MachO) throws -> SemanticString? { if try paramManagedName(in: machO).rawStringValue() == "A" { return try dumpParameterName(using: options, in: machO) } else { @@ -55,13 +55,13 @@ extension GenericRequirementDescriptor { @SemanticStringBuilder - package func dumpParameterName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + package func dumpParameterName(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { let node = try MetadataReader.demangleType(for: paramManagedName(in: machO), in: machO) node.printSemantic(using: options) } @SemanticStringBuilder - package func dumpContent(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + package func dumpContent(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { switch try resolvedContent(in: machO) { case .type(let mangledName): try MetadataReader.demangleType(for: mangledName, in: machO).printSemantic(using: options) @@ -107,7 +107,7 @@ extension GenericRequirementDescriptor { } @SemanticStringBuilder - package func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { + package func dump(using options: DemangleOptions, in machO: MachO) throws -> SemanticString { try dumpParameterName(using: options, in: machO) if layout.flags.kind == .sameType { diff --git a/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift b/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift index eafd67f4..505610fe 100644 --- a/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift +++ b/Sources/SwiftDump/Extensions/ResilientSuperclass+Dump.swift @@ -5,7 +5,7 @@ import MachOSwiftSection import Semantic extension ResilientSuperclass { - package func dumpSuperclass(using options: DemangleOptions, for kind: TypeReferenceKind, in machO: MachO) throws -> SemanticString? { + package func dumpSuperclass(using options: DemangleOptions, for kind: TypeReferenceKind, in machO: MachO) throws -> SemanticString? { let typeReference = TypeReference.forKind(kind, at: layout.superclass.relativeOffset) let resolvedTypeReference = try typeReference.resolve(at: offset(of: \.superclass), in: machO) switch resolvedTypeReference { diff --git a/Sources/SwiftDump/PrimitiveTypeMappingCache.swift b/Sources/SwiftDump/PrimitiveTypeMappingCache.swift new file mode 100644 index 00000000..cf1e7be3 --- /dev/null +++ b/Sources/SwiftDump/PrimitiveTypeMappingCache.swift @@ -0,0 +1,20 @@ +import Foundation +import MachOCaches +import MachOFoundation +import MachOSwiftSection + +package final class PrimitiveTypeMappingCache: MachOCache { + package static let shared = PrimitiveTypeMappingCache() + + private override init() { + super.init() + } + + package override func buildEntry(for machO: MachO) -> PrimitiveTypeMapping? where MachO: MachORepresentableWithCache { + if let machO = machO as? (any(MachOSwiftSectionRepresentableWithCache & MachOReadable)) { + return try? .init(machO: machO) + } else { + return nil + } + } +} diff --git a/Tests/MachOSwiftSectionTests/MetadataFinderTests.swift b/Tests/MachOSwiftSectionTests/MetadataFinderTests.swift index 841cb928..3daeb2b3 100644 --- a/Tests/MachOSwiftSectionTests/MetadataFinderTests.swift +++ b/Tests/MachOSwiftSectionTests/MetadataFinderTests.swift @@ -23,7 +23,6 @@ struct MetadataFinderTests { try await dumpMetadatas(for: #require(mainCache.machOFile(named: .SwiftUI))) } - @MachOImageGenerator private func dumpMetadatas(for machO: MachOFile) async throws { let finder: MetadataFinder = .init(machO: machO) diff --git a/Tests/SwiftDumpTests/DyldCacheDumpTests.swift b/Tests/SwiftDumpTests/DyldCacheDumpTests.swift index 6099ec7f..746d87f7 100644 --- a/Tests/SwiftDumpTests/DyldCacheDumpTests.swift +++ b/Tests/SwiftDumpTests/DyldCacheDumpTests.swift @@ -13,6 +13,8 @@ final class DyldCacheDumpTests: DyldCacheTests, DumpableTests { } extension DyldCacheDumpTests { + // MARK: - Types + @Test func typesInCacheFile() async throws { try await dumpTypes(for: machOFileInCache) } @@ -25,6 +27,8 @@ extension DyldCacheDumpTests { try await dumpTypes(for: machOFileInSubCache) } + // MARK: - Protocols + @Test func protocolsInCacheFile() async throws { try await dumpProtocols(for: machOFileInCache) } @@ -37,6 +41,8 @@ extension DyldCacheDumpTests { try await dumpProtocols(for: machOFileInSubCache) } + // MARK: - ProtocolConformances + @Test func protocolConformancesInCacheFile() async throws { try await dumpProtocolConformances(for: machOFileInCache) } @@ -49,6 +55,8 @@ extension DyldCacheDumpTests { try await dumpProtocolConformances(for: machOFileInSubCache) } + // MARK: - AssociatedTypes + @Test func associatedTypesInCacheFile() async throws { try await dumpAssociatedTypes(for: machOFileInCache) } @@ -61,6 +69,8 @@ extension DyldCacheDumpTests { try await dumpAssociatedTypes(for: machOFileInSubCache) } + // MARK: - BuiltinTypes + @Test func builtinTypesInCacheFile() async throws { try await dumpBuiltinTypes(for: machOFileInCache) } From 8abcf3fa0e766412b9e7b76e3ef18a50179876bc Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 4 Jul 2025 01:00:32 +0800 Subject: [PATCH 6/8] Format --- Sources/SwiftDump/PrimitiveTypeMappingCache.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/SwiftDump/PrimitiveTypeMappingCache.swift b/Sources/SwiftDump/PrimitiveTypeMappingCache.swift index cf1e7be3..25bb13fd 100644 --- a/Sources/SwiftDump/PrimitiveTypeMappingCache.swift +++ b/Sources/SwiftDump/PrimitiveTypeMappingCache.swift @@ -11,7 +11,7 @@ package final class PrimitiveTypeMappingCache: MachOCache } package override func buildEntry(for machO: MachO) -> PrimitiveTypeMapping? where MachO: MachORepresentableWithCache { - if let machO = machO as? (any(MachOSwiftSectionRepresentableWithCache & MachOReadable)) { + if let machO = machO as? any MachOSwiftSectionRepresentableWithCache & MachOReadable { return try? .init(machO: machO) } else { return nil From 008f92b2818003b72ef9b646688a5dc558967205 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 4 Jul 2025 18:00:49 +0800 Subject: [PATCH 7/8] Add MachOResolving, MachOSymbolPointer targets --- Package.swift | 25 +++++++++++++++++++ Sources/Demangle/Main/DemangleOptions.swift | 9 ++----- Sources/MachOFoundation/Exported.swift | 2 ++ Sources/MachOPointer/Pointer.swift | 1 + .../Protocol/PointerProtocol.swift | 3 ++- .../RelativeDirectPointerProtocol.swift | 2 +- .../RelativeIndirectPointerProtocol.swift | 3 ++- .../Protocol/RelativeIndirectType.swift | 3 ++- ...veIndirectablePointerIntPairProtocol.swift | 2 +- .../RelativeIndirectablePointerProtocol.swift | 3 ++- .../Protocol/RelativePointerProtocol.swift | 3 ++- Sources/MachOPointer/RelativePointers.swift | 1 + .../TargetRelativeDirectPointer.swift | 1 + .../TargetRelativeIndirectPointer.swift | 1 + .../TargetRelativeIndirectablePointer.swift | 1 + .../AnyResolvable.swift | 0 .../Resolvable.swift | 2 +- .../SymbolOrElementPointer.swift | 1 + Sources/MachOSymbols/Symbol.swift | 1 + Sources/MachOSymbols/SymbolOrElement.swift | 1 + Sources/MachOSymbols/Symbols.swift | 1 + .../MachOTestingSupport/DemangleOptions.swift | 11 +------- .../SwiftDump/Dumpable/Class+Dumpable.swift | 22 ++++++++++++++++ Tests/SwiftDumpTests/DyldCacheDumpTests.swift | 4 +-- .../XcodeMachOFileDumpTests.swift | 5 +++- 25 files changed, 79 insertions(+), 29 deletions(-) rename Sources/{MachOReading => MachOResolving}/AnyResolvable.swift (100%) rename Sources/{MachOReading => MachOResolving}/Resolvable.swift (99%) rename Sources/{MachOSwiftSection/Pointer => MachOSymbolPointer}/SymbolOrElementPointer.swift (99%) diff --git a/Package.swift b/Package.swift index cd97c3ff..2f0e489f 100644 --- a/Package.swift +++ b/Package.swift @@ -166,11 +166,21 @@ let package = Package( ] ), + .target( + name: "MachOResolving", + dependencies: [ + .MachOKit, + "MachOExtensions", + "MachOReading", + ] + ), + .target( name: "MachOSymbols", dependencies: [ .MachOKit, "MachOReading", + "MachOResolving", "MachOMacro", "Demangle", "Utilities", @@ -184,7 +194,20 @@ let package = Package( dependencies: [ .MachOKit, "MachOReading", + "MachOResolving", + "MachOMacro", + ] + ), + + .target( + name: "MachOSymbolPointer", + dependencies: [ + .MachOKit, + "MachOReading", + "MachOResolving", "MachOMacro", + "MachOPointer", + "MachOSymbols", ] ), @@ -197,6 +220,8 @@ let package = Package( "MachOMacro", "MachOPointer", "MachOSymbols", + "MachOResolving", + "MachOSymbolPointer", ] ), diff --git a/Sources/Demangle/Main/DemangleOptions.swift b/Sources/Demangle/Main/DemangleOptions.swift index e0d69530..f57c0ded 100644 --- a/Sources/Demangle/Main/DemangleOptions.swift +++ b/Sources/Demangle/Main/DemangleOptions.swift @@ -69,17 +69,12 @@ public struct DemangleOptions: OptionSet, Codable, Sendable { options.remove(.displayExtensionContexts) options.remove(.showPrivateDiscriminators) options.remove(.showModuleInDependentMemberType) + options.remove(.displayUnmangledSuffix) return options }() public static let interfaceType: DemangleOptions = { - var options = DemangleOptions.default - options.remove(.displayObjCModule) - options.insert(.synthesizeSugarOnTypes) - options.remove(.displayWhereClauses) - options.remove(.displayExtensionContexts) - options.remove(.showPrivateDiscriminators) - options.remove(.showModuleInDependentMemberType) + var options = DemangleOptions.interface options.insert(.removeBoundGeneric) return options }() diff --git a/Sources/MachOFoundation/Exported.swift b/Sources/MachOFoundation/Exported.swift index 8db2c066..39e5a1f8 100644 --- a/Sources/MachOFoundation/Exported.swift +++ b/Sources/MachOFoundation/Exported.swift @@ -2,3 +2,5 @@ @_exported import MachOReading @_exported import MachOPointer @_exported import MachOSymbols +@_exported import MachOResolving +@_exported import MachOSymbolPointer diff --git a/Sources/MachOPointer/Pointer.swift b/Sources/MachOPointer/Pointer.swift index 72e61f68..8bb821ec 100644 --- a/Sources/MachOPointer/Pointer.swift +++ b/Sources/MachOPointer/Pointer.swift @@ -1,5 +1,6 @@ import MachOKit import MachOReading +import MachOResolving import MachOExtensions public struct Pointer: RelativeIndirectType, PointerProtocol { diff --git a/Sources/MachOPointer/Protocol/PointerProtocol.swift b/Sources/MachOPointer/Protocol/PointerProtocol.swift index 4c109205..54bbc0fa 100644 --- a/Sources/MachOPointer/Protocol/PointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/PointerProtocol.swift @@ -1,9 +1,10 @@ import MachOKit import MachOMacro import MachOReading +import MachOResolving import MachOExtensions -public protocol PointerProtocol: Resolvable, Sendable { +public protocol PointerProtocol: Resolvable, Sendable { associatedtype Pointee: Resolvable var address: UInt64 { get } diff --git a/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift index 9b77a4b3..efeba245 100644 --- a/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeDirectPointerProtocol.swift @@ -2,10 +2,10 @@ import MachOKit import MachOMacro import MachOReading import MachOExtensions +import MachOResolving public protocol RelativeDirectPointerProtocol: RelativePointerProtocol {} - extension RelativeDirectPointerProtocol { public func resolve(from offset: Int, in machO: MachO) throws -> Pointee { return try resolveDirect(from: offset, in: machO) diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift index 0e15b305..deda8b5f 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectPointerProtocol.swift @@ -1,9 +1,10 @@ import MachOKit import MachOMacro import MachOReading +import MachOResolving import MachOExtensions -public protocol RelativeIndirectPointerProtocol: RelativePointerProtocol { +public protocol RelativeIndirectPointerProtocol: RelativePointerProtocol { associatedtype IndirectType: RelativeIndirectType where IndirectType.Resolved == Pointee func resolveIndirectOffset(from offset: Int, in machO: MachO) throws -> Int diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectType.swift b/Sources/MachOPointer/Protocol/RelativeIndirectType.swift index cf0fb973..df5d31d2 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectType.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectType.swift @@ -1,8 +1,9 @@ import MachOKit import MachOReading +import MachOResolving import MachOExtensions -public protocol RelativeIndirectType: Resolvable { +public protocol RelativeIndirectType: Resolvable { associatedtype Resolved: Resolvable func resolve(in machO: MachO) throws -> Resolved diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift index f20fb436..ecb1fe88 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerIntPairProtocol.swift @@ -2,7 +2,7 @@ import MachOKit import MachOReading import MachOExtensions -public protocol RelativeIndirectablePointerIntPairProtocol: RelativeIndirectablePointerProtocol { +public protocol RelativeIndirectablePointerIntPairProtocol: RelativeIndirectablePointerProtocol { typealias Integer = Value.RawValue associatedtype Value: RawRepresentable where Value.RawValue: FixedWidthInteger var relativeOffsetPlusIndirectAndInt: Offset { get } diff --git a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift index 8078beac..ce10d1b6 100644 --- a/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativeIndirectablePointerProtocol.swift @@ -1,9 +1,10 @@ import MachOKit import MachOMacro import MachOReading +import MachOResolving import MachOExtensions -public protocol RelativeIndirectablePointerProtocol: RelativeDirectPointerProtocol, RelativeIndirectPointerProtocol { +public protocol RelativeIndirectablePointerProtocol: RelativeDirectPointerProtocol, RelativeIndirectPointerProtocol { var relativeOffsetPlusIndirect: Offset { get } var isIndirect: Bool { get } func resolveIndirectableOffset(from offset: Int, in machO: MachO) throws -> Int diff --git a/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift b/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift index 82c6ee87..cbb2fede 100644 --- a/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift +++ b/Sources/MachOPointer/Protocol/RelativePointerProtocol.swift @@ -1,8 +1,9 @@ import MachOKit import MachOReading +import MachOResolving import MachOExtensions -public protocol RelativePointerProtocol: Sendable { +public protocol RelativePointerProtocol: Sendable { associatedtype Pointee: Resolvable associatedtype Offset: FixedWidthInteger & SignedInteger diff --git a/Sources/MachOPointer/RelativePointers.swift b/Sources/MachOPointer/RelativePointers.swift index 276a5d67..73bd8f23 100644 --- a/Sources/MachOPointer/RelativePointers.swift +++ b/Sources/MachOPointer/RelativePointers.swift @@ -1,4 +1,5 @@ import MachOReading +import MachOResolving import MachOExtensions public typealias RelativeOffset = Int32 diff --git a/Sources/MachOPointer/TargetRelativeDirectPointer.swift b/Sources/MachOPointer/TargetRelativeDirectPointer.swift index c0cfdd22..99cf8170 100644 --- a/Sources/MachOPointer/TargetRelativeDirectPointer.swift +++ b/Sources/MachOPointer/TargetRelativeDirectPointer.swift @@ -1,4 +1,5 @@ import MachOReading +import MachOResolving import MachOExtensions public struct TargetRelativeDirectPointer: RelativeDirectPointerProtocol { diff --git a/Sources/MachOPointer/TargetRelativeIndirectPointer.swift b/Sources/MachOPointer/TargetRelativeIndirectPointer.swift index 3856997a..64bd9eaa 100644 --- a/Sources/MachOPointer/TargetRelativeIndirectPointer.swift +++ b/Sources/MachOPointer/TargetRelativeIndirectPointer.swift @@ -1,4 +1,5 @@ import MachOReading +import MachOResolving import MachOExtensions public struct TargetRelativeIndirectPointer: RelativeIndirectPointerProtocol where Pointee == IndirectType.Resolved { diff --git a/Sources/MachOPointer/TargetRelativeIndirectablePointer.swift b/Sources/MachOPointer/TargetRelativeIndirectablePointer.swift index ef4f8472..6eecdf22 100644 --- a/Sources/MachOPointer/TargetRelativeIndirectablePointer.swift +++ b/Sources/MachOPointer/TargetRelativeIndirectablePointer.swift @@ -1,4 +1,5 @@ import MachOReading +import MachOResolving import MachOExtensions public struct TargetRelativeIndirectablePointer: RelativeIndirectablePointerProtocol where Pointee == IndirectType.Resolved { diff --git a/Sources/MachOReading/AnyResolvable.swift b/Sources/MachOResolving/AnyResolvable.swift similarity index 100% rename from Sources/MachOReading/AnyResolvable.swift rename to Sources/MachOResolving/AnyResolvable.swift diff --git a/Sources/MachOReading/Resolvable.swift b/Sources/MachOResolving/Resolvable.swift similarity index 99% rename from Sources/MachOReading/Resolvable.swift rename to Sources/MachOResolving/Resolvable.swift index 34fcf710..7fa8f84a 100644 --- a/Sources/MachOReading/Resolvable.swift +++ b/Sources/MachOResolving/Resolvable.swift @@ -1,6 +1,6 @@ import MachOKit +import MachOReading import MachOExtensions -import MachOMacro public protocol Resolvable { static func resolve(from offset: Int, in machO: MachO) throws -> Self diff --git a/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift b/Sources/MachOSymbolPointer/SymbolOrElementPointer.swift similarity index 99% rename from Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift rename to Sources/MachOSymbolPointer/SymbolOrElementPointer.swift index cb316747..027878e6 100644 --- a/Sources/MachOSwiftSection/Pointer/SymbolOrElementPointer.swift +++ b/Sources/MachOSymbolPointer/SymbolOrElementPointer.swift @@ -2,6 +2,7 @@ import MachOKit import MachOReading import MachOPointer import MachOSymbols +import MachOResolving import MachOExtensions public typealias RelativeSymbolOrElementPointer = RelativeIndirectablePointer, SymbolOrElementPointer> diff --git a/Sources/MachOSymbols/Symbol.swift b/Sources/MachOSymbols/Symbol.swift index 9e67801b..283b9dd1 100644 --- a/Sources/MachOSymbols/Symbol.swift +++ b/Sources/MachOSymbols/Symbol.swift @@ -1,6 +1,7 @@ import MachOKit import MachOMacro import MachOReading +import MachOResolving import MachOExtensions public struct Symbol: Resolvable, Hashable { diff --git a/Sources/MachOSymbols/SymbolOrElement.swift b/Sources/MachOSymbols/SymbolOrElement.swift index a345cfd8..5822f9c8 100644 --- a/Sources/MachOSymbols/SymbolOrElement.swift +++ b/Sources/MachOSymbols/SymbolOrElement.swift @@ -1,5 +1,6 @@ import MachOKit import MachOReading +import MachOResolving import MachOExtensions public enum SymbolOrElement: Resolvable { diff --git a/Sources/MachOSymbols/Symbols.swift b/Sources/MachOSymbols/Symbols.swift index 6234ed77..4517ccd9 100644 --- a/Sources/MachOSymbols/Symbols.swift +++ b/Sources/MachOSymbols/Symbols.swift @@ -1,6 +1,7 @@ import MachOKit import MachOMacro import MachOReading +import MachOResolving import MachOExtensions public struct Symbols: Resolvable { diff --git a/Sources/MachOTestingSupport/DemangleOptions.swift b/Sources/MachOTestingSupport/DemangleOptions.swift index 2cb25a75..0eded267 100644 --- a/Sources/MachOTestingSupport/DemangleOptions.swift +++ b/Sources/MachOTestingSupport/DemangleOptions.swift @@ -3,14 +3,5 @@ import MachOSwiftSection import SwiftDump extension DemangleOptions { - package static let test: DemangleOptions = { - var options = DemangleOptions.default - options.remove(.displayObjCModule) - options.insert(.synthesizeSugarOnTypes) - options.remove(.displayWhereClauses) - options.remove(.displayExtensionContexts) - options.remove(.showPrivateDiscriminators) - options.remove(.showModuleInDependentMemberType) - return options - }() + package static let test: DemangleOptions = .interface } diff --git a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift index fccaa938..8f72897b 100644 --- a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift +++ b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift @@ -168,6 +168,28 @@ private struct ClassDumper Date: Fri, 4 Jul 2025 22:56:54 +0800 Subject: [PATCH 8/8] Update Testing --- .../DemangleSwiftProjectDerivedTests.swift | 2892 ++--------------- .../GenericContextTests.swift | 35 - .../XcodeMachOFileDumpTests.swift | 2 +- 3 files changed, 223 insertions(+), 2706 deletions(-) delete mode 100644 Tests/MachOSwiftSectionTests/GenericContextTests.swift diff --git a/Tests/DemangleTests/DemangleSwiftProjectDerivedTests.swift b/Tests/DemangleTests/DemangleSwiftProjectDerivedTests.swift index 4fdef255..8a934832 100644 --- a/Tests/DemangleTests/DemangleSwiftProjectDerivedTests.swift +++ b/Tests/DemangleTests/DemangleSwiftProjectDerivedTests.swift @@ -3,54 +3,6 @@ import Testing @Suite struct DemangleSwiftProjectDerivedTests { - @Test func TtBf32_() { - let input = "_TtBf32_" - let output = "Builtin.FPIEEE32" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtBf64_() { - let input = "_TtBf64_" - let output = "Builtin.FPIEEE64" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtBf80_() { - let input = "_TtBf80_" - let output = "Builtin.FPIEEE80" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtBi32_() { - let input = "_TtBi32_" - let output = "Builtin.Int32" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - @Test func _$sBf32_() { let input = "$sBf32_" let output = "Builtin.FPIEEE32" @@ -99,9 +51,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBw() { - let input = "_TtBw" - let output = "Builtin.Word" + @Test func _$sBi8_Bv4_() { + let input = "$sBi8_Bv4_" + let output = "Builtin.Vec4xInt8" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -111,9 +63,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBO() { - let input = "_TtBO" - let output = "Builtin.UnknownObject" + @Test func _$sBf16_Bv4_() { + let input = "$sBf16_Bv4_" + let output = "Builtin.Vec4xFPIEEE16" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -123,9 +75,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBo() { - let input = "_TtBo" - let output = "Builtin.NativeObject" + @Test func _$sBpBv4_() { + let input = "$sBpBv4_" + let output = "Builtin.Vec4xRawPointer" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -135,9 +87,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBp() { - let input = "_TtBp" - let output = "Builtin.RawPointer" + @Test func T03foo3barC3basyAA3zimCAE_tFTo() { + let input = "_T03foo3barC3basyAA3zimCAE_tFTo" + let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -147,9 +99,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBt() { - let input = "_TtBt" - let output = "Builtin.SILToken" + @Test func T0SC3fooS2d_SdtFTO() { + let input = "_T0SC3fooS2d_SdtFTO" + let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -159,9 +111,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBv4Bi8_() { - let input = "_TtBv4Bi8_" - let output = "Builtin.Vec4xInt8" + @Test func _$s3foo3barC3bas3zimyAaEC_tFTo() { + let input = "_$s3foo3barC3bas3zimyAaEC_tFTo" + let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -171,9 +123,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBv4Bf16_() { - let input = "_TtBv4Bf16_" - let output = "Builtin.Vec4xFPIEEE16" + @Test func _$sSC3fooyS2d_SdtFTO() { + let input = "_$sSC3fooyS2d_SdtFTO" + let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -183,9 +135,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtBv4Bp() { - let input = "_TtBv4Bp" - let output = "Builtin.Vec4xRawPointer" + @Test func _$S3foo3barC3bas3zimyAaEC_tFTo() { + let input = "_$S3foo3barC3bas3zimyAaEC_tFTo" + let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -195,9 +147,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func _$sBi8_Bv4_() { - let input = "$sBi8_Bv4_" - let output = "Builtin.Vec4xInt8" + @Test func _$SSC3fooyS2d_SdtFTO() { + let input = "_$SSC3fooyS2d_SdtFTO" + let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -207,9 +159,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func _$sBf16_Bv4_() { - let input = "$sBf16_Bv4_" - let output = "Builtin.Vec4xFPIEEE16" + @Test func _$sTAdot123() { + let input = "_$sTA.123" + let output = "partial apply forwarder with unmangled suffix \".123\"" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -219,9 +171,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func _$sBpBv4_() { - let input = "$sBpBv4_" - let output = "Builtin.Vec4xRawPointer" + @Test func _$s4main3fooyySiFyyXEfU_TAdot1() { + let input = "$s4main3fooyySiFyyXEfU_TA.1" + let output = "partial apply forwarder for closure #1 () -> () in main.foo(Swift.Int) -> () with unmangled suffix \".1\"" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -231,9 +183,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtSa() { - let input = "_TtSa" - let output = "Swift.Array" + @Test func _$s4main8MyStructV3fooyyFAA1XV_Tg5dotfoo() { + let input = "$s4main8MyStructV3fooyyFAA1XV_Tg5.foo" + let output = "generic specialization of main.MyStruct.foo() -> () with unmangled suffix \".foo\"" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -243,2521 +195,225 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TtSb() { - let input = "_TtSb" - let output = "Swift.Bool" + @Test func TtZZ() { + let input = "_TtZZ" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSc() { - let input = "_TtSc" - let output = "Swift.UnicodeScalar" + @Test func TtB() { + let input = "_TtB" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSd() { - let input = "_TtSd" - let output = "Swift.Double" + @Test func TtBSi() { + let input = "_TtBSi" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSf() { - let input = "_TtSf" - let output = "Swift.Float" + @Test func TtBx() { + let input = "_TtBx" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSi() { - let input = "_TtSi" - let output = "Swift.Int" + @Test func TtC() { + let input = "_TtC" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSq() { - let input = "_TtSq" - let output = "Swift.Optional" + @Test func TtT() { + let input = "_TtT" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSS() { - let input = "_TtSS" - let output = "Swift.String" + @Test func TtTSi() { + let input = "_TtTSi" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSu() { - let input = "_TtSu" - let output = "Swift.UInt" + @Test func TtQd_() { + let input = "_TtQd_" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtGSPSi_() { - let input = "_TtGSPSi_" - let output = "Swift.UnsafePointer" + @Test func TtU__FQo_Si() { + let input = "_TtU__FQo_Si" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtGSpSi_() { - let input = "_TtGSpSi_" - let output = "Swift.UnsafeMutablePointer" + @Test func TtU__FQD__Si() { + let input = "_TtU__FQD__Si" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSV() { - let input = "_TtSV" - let output = "Swift.UnsafeRawPointer" + @Test func TtU___FQ_U____FQd0__T_() { + let input = "_TtU___FQ_U____FQd0__T_" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtSv() { - let input = "_TtSv" - let output = "Swift.UnsafeMutableRawPointer" + @Test func TtU___FQ_U____FQd_1_T_() { + let input = "_TtU___FQ_U____FQd_1_T_" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtGSaSS_() { - let input = "_TtGSaSS_" - let output = "[Swift.String]" + @Test func TtU___FQ_U____FQ2_T_() { + let input = "_TtU___FQ_U____FQ2_T_" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtGSqSS_() { - let input = "_TtGSqSS_" - let output = "Swift.String?" + @Test func Tw() { + let input = "_Tw" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtGVs10DictionarySSSi_() { - let input = "_TtGVs10DictionarySSSi_" - let output = "[Swift.String : Swift.Int]" + @Test func TWa() { + let input = "_TWa" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TtVs7CString() { - let input = "_TtVs7CString" - let output = "Swift.CString" + @Test func Twal() { + let input = "_Twal" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtCSo8NSObject() { - let input = "_TtCSo8NSObject" - let output = "__C.NSObject" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtO6Monads6Either() { - let input = "_TtO6Monads6Either" - let output = "Monads.Either" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtbSiSu() { - let input = "_TtbSiSu" - let output = "@convention(block) (Swift.Int) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtcSiSu() { - let input = "_TtcSiSu" - let output = "@convention(c) (Swift.Int) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtbTSiSc_Su() { - let input = "_TtbTSiSc_Su" - let output = "@convention(block) (Swift.Int, Swift.UnicodeScalar) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtcTSiSc_Su() { - let input = "_TtcTSiSc_Su" - let output = "@convention(c) (Swift.Int, Swift.UnicodeScalar) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtFSiSu() { - let input = "_TtFSiSu" - let output = "(Swift.Int) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtKSiSu() { - let input = "_TtKSiSu" - let output = "@autoclosure (Swift.Int) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtFSiFScSu() { - let input = "_TtFSiFScSu" - let output = "(Swift.Int) -> (Swift.UnicodeScalar) -> Swift.UInt" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtMSi() { - let input = "_TtMSi" - let output = "Swift.Int.Type" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtP_() { - let input = "_TtP_" - let output = "Any" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtP3foo3bar_() { - let input = "_TtP3foo3bar_" - let output = "foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtP3foo3barS_3bas_() { - let input = "_TtP3foo3barS_3bas_" - let output = "foo.bar & foo.bas" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtTP3foo3barS_3bas_PS1__PS1_S_3zimS0___() { - let input = "_TtTP3foo3barS_3bas_PS1__PS1_S_3zimS0___" - let output = "(foo.bar & foo.bas, foo.bas, foo.bas & foo.zim & foo.bar)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtRSi() { - let input = "_TtRSi" - let output = "inout Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtTSiSu_() { - let input = "_TtTSiSu_" - let output = "(Swift.Int, Swift.UInt)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TttSiSu_() { - let input = "_TttSiSu_" - let output = "(Swift.Int, Swift.UInt...)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtT3fooSi3barSu_() { - let input = "_TtT3fooSi3barSu_" - let output = "(foo: Swift.Int, bar: Swift.UInt)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TturFxx() { - let input = "_TturFxx" - let output = "(A) -> A" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuzrFT_T_() { - let input = "_TtuzrFT_T_" - let output = "<>() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Ttu__rFxqd__() { - let input = "_Ttu__rFxqd__" - let output = "(A) -> A1" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Ttu_z_rFxqd0__() { - let input = "_Ttu_z_rFxqd0__" - let output = "<>(A) -> A2" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Ttu0_rFxq_() { - let input = "_Ttu0_rFxq_" - let output = "(A) -> B" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxs8RunciblerFxwx5Mince() { - let input = "_TtuRxs8RunciblerFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxle64xs8RunciblerFxwx5Mince() { - let input = "_TtuRxle64xs8RunciblerFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlE64_16rFxwx5Mince() { - let input = "_TtuRxlE64_16rFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlE64_32xs8RunciblerFxwx5Mince() { - let input = "_TtuRxlE64_32xs8RunciblerFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlM64_16rFxwx5Mince() { - let input = "_TtuRxlM64_16rFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxle64rFxwx5Mince() { - let input = "_TtuRxle64rFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlm64rFxwx5Mince() { - let input = "_TtuRxlm64rFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlNrFxwx5Mince() { - let input = "_TtuRxlNrFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlRrFxwx5Mince() { - let input = "_TtuRxlRrFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxlUrFxwx5Mince() { - let input = "_TtuRxlUrFxwx5Mince" - let output = "(A) -> A.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxs8RunciblerFxWx5Mince6Quince_() { - let input = "_TtuRxs8RunciblerFxWx5Mince6Quince_" - let output = "(A) -> A.Mince.Quince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxs8Runciblexs8FungiblerFxwxPS_5Mince() { - let input = "_TtuRxs8Runciblexs8FungiblerFxwxPS_5Mince" - let output = "(A) -> A.Swift.Runcible.Mince" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxCs22AbstractRuncingFactoryrFxx() { - let input = "_TtuRxCs22AbstractRuncingFactoryrFxx" - let output = "(A) -> A" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxs8Runciblewx5MincezxrFxx() { - let input = "_TtuRxs8Runciblewx5MincezxrFxx" - let output = "(A) -> A" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtuRxs8RuncibleWx5Mince6Quince_zxrFxx() { - let input = "_TtuRxs8RuncibleWx5Mince6Quince_zxrFxx" - let output = "(A) -> A" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Ttu0_Rxs8Runcible_S_wx5Minces8Fungiblew_S0_S1_rFxq_() { - let input = "_Ttu0_Rxs8Runcible_S_wx5Minces8Fungiblew_S0_S1_rFxq_" - let output = "(A) -> B" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Ttu0_Rx3Foo3BarxCS_3Bas_S0__S1_rT_() { - let input = "_Ttu0_Rx3Foo3BarxCS_3Bas_S0__S1_rT_" - let output = " ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Tv3foo3barSi() { - let input = "_Tv3foo3barSi" - let output = "foo.bar : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3fooau3barSi() { - let input = "_TF3fooau3barSi" - let output = "foo.bar.unsafeMutableAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foolu3barSi() { - let input = "_TF3foolu3barSi" - let output = "foo.bar.unsafeAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3fooaO3barSi() { - let input = "_TF3fooaO3barSi" - let output = "foo.bar.owningMutableAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foolO3barSi() { - let input = "_TF3foolO3barSi" - let output = "foo.bar.owningAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3fooao3barSi() { - let input = "_TF3fooao3barSi" - let output = "foo.bar.nativeOwningMutableAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foolo3barSi() { - let input = "_TF3foolo3barSi" - let output = "foo.bar.nativeOwningAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3fooap3barSi() { - let input = "_TF3fooap3barSi" - let output = "foo.bar.nativePinningMutableAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foolp3barSi() { - let input = "_TF3foolp3barSi" - let output = "foo.bar.nativePinningAddressor : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foog3barSi() { - let input = "_TF3foog3barSi" - let output = "foo.bar.getter : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foos3barSi() { - let input = "_TF3foos3barSi" - let output = "foo.bar.setter : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC3foo3bar3basfT3zimCS_3zim_T_() { - let input = "_TFC3foo3bar3basfT3zimCS_3zim_T_" - let output = "foo.bar.bas(zim: foo.zim) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TToFC3foo3bar3basfT3zimCS_3zim_T_() { - let input = "_TToFC3foo3bar3basfT3zimCS_3zim_T_" - let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTOFSC3fooFTSdSd_Sd() { - let input = "_TTOFSC3fooFTSdSd_Sd" - let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func T03foo3barC3basyAA3zimCAE_tFTo() { - let input = "_T03foo3barC3basyAA3zimCAE_tFTo" - let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func T0SC3fooS2d_SdtFTO() { - let input = "_T0SC3fooS2d_SdtFTO" - let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$s3foo3barC3bas3zimyAaEC_tFTo() { - let input = "_$s3foo3barC3bas3zimyAaEC_tFTo" - let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$sSC3fooyS2d_SdtFTO() { - let input = "_$sSC3fooyS2d_SdtFTO" - let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$S3foo3barC3bas3zimyAaEC_tFTo() { - let input = "_$S3foo3barC3bas3zimyAaEC_tFTo" - let output = "@objc foo.bar.bas(zim: foo.zim) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$SSC3fooyS2d_SdtFTO() { - let input = "_$SSC3fooyS2d_SdtFTO" - let output = "@nonobjc __C_Synthesized.foo(Swift.Double, Swift.Double) -> Swift.Double" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$sTAdot123() { - let input = "_$sTA.123" - let output = "partial apply forwarder with unmangled suffix \".123\"" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$s4main3fooyySiFyyXEfU_TAdot1() { - let input = "$s4main3fooyySiFyyXEfU_TA.1" - let output = "partial apply forwarder for closure #1 () -> () in main.foo(Swift.Int) -> () with unmangled suffix \".1\"" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func _$s4main8MyStructV3fooyyFAA1XV_Tg5dotfoo() { - let input = "$s4main8MyStructV3fooyyFAA1XV_Tg5.foo" - let output = "generic specialization of main.MyStruct.foo() -> () with unmangled suffix \".foo\"" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTDFC3foo3bar3basfT3zimCS_3zim_T_() { - let input = "_TTDFC3foo3bar3basfT3zimCS_3zim_T_" - let output = "dynamic foo.bar.bas(zim: foo.zim) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foooi1pFTCS_3barVS_3bas_OS_3zim() { - let input = "_TF3foooi1pFTCS_3barVS_3bas_OS_3zim" - let output = "foo.+ infix(foo.bar, foo.bas) -> foo.zim" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF3foooP1xFTCS_3barVS_3bas_OS_3zim() { - let input = "_TF3foooP1xFTCS_3barVS_3bas_OS_3zim" - let output = "foo.^ postfix(foo.bar, foo.bas) -> foo.zim" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC3foo3barCfT_S0_() { - let input = "_TFC3foo3barCfT_S0_" - let output = "foo.bar.__allocating_init() -> foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC3foo3barcfT_S0_() { - let input = "_TFC3foo3barcfT_S0_" - let output = "foo.bar.init() -> foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC3foo3barD() { - let input = "_TFC3foo3barD" - let output = "foo.bar.__deallocating_deinit" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC3foo3barZ() { - let input = "_TFC3foo3barZ" - let output = "foo.bar.__isolated_deallocating_deinit" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC3foo3bard() { - let input = "_TFC3foo3bard" - let output = "foo.bar.deinit" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TMPC3foo3bar() { - let input = "_TMPC3foo3bar" - let output = "generic type metadata pattern for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TMnC3foo3bar() { - let input = "_TMnC3foo3bar" - let output = "nominal type descriptor for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TMmC3foo3bar() { - let input = "_TMmC3foo3bar" - let output = "metaclass for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TMC3foo3bar() { - let input = "_TMC3foo3bar" - let output = "type metadata for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TMfC3foo3bar() { - let input = "_TMfC3foo3bar" - let output = "full type metadata for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwalC3foo3bar() { - let input = "_TwalC3foo3bar" - let output = "allocateBuffer value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwcaC3foo3bar() { - let input = "_TwcaC3foo3bar" - let output = "assignWithCopy value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwtaC3foo3bar() { - let input = "_TwtaC3foo3bar" - let output = "assignWithTake value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwdeC3foo3bar() { - let input = "_TwdeC3foo3bar" - let output = "deallocateBuffer value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwxxC3foo3bar() { - let input = "_TwxxC3foo3bar" - let output = "destroy value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwXXC3foo3bar() { - let input = "_TwXXC3foo3bar" - let output = "destroyBuffer value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwCPC3foo3bar() { - let input = "_TwCPC3foo3bar" - let output = "initializeBufferWithCopyOfBuffer value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwCpC3foo3bar() { - let input = "_TwCpC3foo3bar" - let output = "initializeBufferWithCopy value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwcpC3foo3bar() { - let input = "_TwcpC3foo3bar" - let output = "initializeWithCopy value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwTKC3foo3bar() { - let input = "_TwTKC3foo3bar" - let output = "initializeBufferWithTakeOfBuffer value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwTkC3foo3bar() { - let input = "_TwTkC3foo3bar" - let output = "initializeBufferWithTake value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwtkC3foo3bar() { - let input = "_TwtkC3foo3bar" - let output = "initializeWithTake value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TwprC3foo3bar() { - let input = "_TwprC3foo3bar" - let output = "projectBuffer value witness for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWVC3foo3bar() { - let input = "_TWVC3foo3bar" - let output = "value witness table for foo.bar" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWvdvC3foo3bar3basSi() { - let input = "_TWvdvC3foo3bar3basSi" - let output = "direct field offset for foo.bar.bas : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWvivC3foo3bar3basSi() { - let input = "_TWvivC3foo3bar3basSi" - let output = "indirect field offset for foo.bar.bas : Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWPC3foo3barS_8barrables() { - let input = "_TWPC3foo3barS_8barrables" - let output = "protocol witness table for foo.bar : foo.barrable in Swift" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWaC3foo3barS_8barrableS_() { - let input = "_TWaC3foo3barS_8barrableS_" - let output = "protocol witness table accessor for foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWlC3foo3barS0_S_8barrableS_() { - let input = "_TWlC3foo3barS0_S_8barrableS_" - let output = "lazy protocol witness table accessor for type foo.bar and conformance foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWLC3foo3barS0_S_8barrableS_() { - let input = "_TWLC3foo3barS0_S_8barrableS_" - let output = "lazy protocol witness table cache variable for type foo.bar and conformance foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWGC3foo3barS_8barrableS_() { - let input = "_TWGC3foo3barS_8barrableS_" - let output = "generic protocol witness table for foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWIC3foo3barS_8barrableS_() { - let input = "_TWIC3foo3barS_8barrableS_" - let output = "instantiation function for generic protocol witness table for foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWtC3foo3barS_8barrableS_4fred() { - let input = "_TWtC3foo3barS_8barrableS_4fred" - let output = "associated type metadata accessor for fred in foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TWTC3foo3barS_8barrableS_4fredS_6thomas() { - let input = "_TWTC3foo3barS_8barrableS_4fredS_6thomas" - let output = "associated type witness table accessor for fred : foo.thomas in foo.bar : foo.barrable in foo" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFSCg5greenVSC5Color() { - let input = "_TFSCg5greenVSC5Color" - let output = "__C_Synthesized.green.getter : __C_Synthesized.Color" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TIF1t1fFT1iSi1sSS_T_A_() { - let input = "_TIF1t1fFT1iSi1sSS_T_A_" - let output = "default argument 0 of t.f(i: Swift.Int, s: Swift.String) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TIF1t1fFT1iSi1sSS_T_A0_() { - let input = "_TIF1t1fFT1iSi1sSS_T_A0_" - let output = "default argument 1 of t.f(i: Swift.Int, s: Swift.String) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFSqcfT_GSqx_() { - let input = "_TFSqcfT_GSqx_" - let output = "Swift.Optional.init() -> A?" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF21class_bound_protocols32class_bound_protocol_compositionFT1xPS_10ClassBoundS_13NotClassBound__PS0_S1__() { - let input = "_TF21class_bound_protocols32class_bound_protocol_compositionFT1xPS_10ClassBoundS_13NotClassBound__PS0_S1__" - let output = "class_bound_protocols.class_bound_protocol_composition(x: class_bound_protocols.ClassBound & class_bound_protocols.NotClassBound) -> class_bound_protocols.ClassBound & class_bound_protocols.NotClassBound" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtZZ() { - let input = "_TtZZ" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtB() { - let input = "_TtB" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtBSi() { - let input = "_TtBSi" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtBx() { - let input = "_TtBx" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtC() { - let input = "_TtC" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtT() { - let input = "_TtT" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtTSi() { - let input = "_TtTSi" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtQd_() { - let input = "_TtQd_" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtU__FQo_Si() { - let input = "_TtU__FQo_Si" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtU__FQD__Si() { - let input = "_TtU__FQD__Si" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtU___FQ_U____FQd0__T_() { - let input = "_TtU___FQ_U____FQd0__T_" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtU___FQ_U____FQd_1_T_() { - let input = "_TtU___FQ_U____FQd_1_T_" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtU___FQ_U____FQ2_T_() { - let input = "_TtU___FQ_U____FQ2_T_" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func Tw() { - let input = "_Tw" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWa() { - let input = "_TWa" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func Twal() { - let input = "_Twal" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func T() { - let input = "_T" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTo() { - let input = "_TTo" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TC() { - let input = "_TC" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TM() { - let input = "_TM" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TW() { - let input = "_TW" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWV() { - let input = "_TWV" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWo() { - let input = "_TWo" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWv() { - let input = "_TWv" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWvd() { - let input = "_TWvd" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWvi() { - let input = "_TWvi" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TWvx() { - let input = "_TWvx" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TtVCC4main3Foo4Ding3Str() { - let input = "_TtVCC4main3Foo4Ding3Str" - let output = "main.Foo.Ding.Str" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFVCC6nested6AClass12AnotherClass7AStruct9aFunctionfT1aSi_S2_() { - let input = "_TFVCC6nested6AClass12AnotherClass7AStruct9aFunctionfT1aSi_S2_" - let output = "nested.AClass.AnotherClass.AStruct.aFunction(a: Swift.Int) -> nested.AClass.AnotherClass.AStruct" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtXwC10attributes10SwiftClass() { - let input = "_TtXwC10attributes10SwiftClass" - let output = "weak attributes.SwiftClass" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtXoC10attributes10SwiftClass() { - let input = "_TtXoC10attributes10SwiftClass" - let output = "unowned attributes.SwiftClass" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtERR() { - let input = "_TtERR" - let output = "" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtGSqGSaC5sugar7MyClass__() { - let input = "_TtGSqGSaC5sugar7MyClass__" - let output = "[sugar.MyClass]?" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtGSaGSqC5sugar7MyClass__() { - let input = "_TtGSaGSqC5sugar7MyClass__" - let output = "[sugar.MyClass?]" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtaC9typealias5DWARF9DIEOffset() { - let input = "_TtaC9typealias5DWARF9DIEOffset" - let output = "typealias.DWARF.DIEOffset" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Tta1t5Alias() { - let input = "_Tta1t5Alias" - let output = "t.Alias" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func Ttas3Int() { - let input = "_Ttas3Int" - let output = "Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTRXFo_dSc_dSb_XFo_iSc_iSb_() { - let input = "_TTRXFo_dSc_dSb_XFo_iSc_iSb_" - let output = "reabstraction thunk helper from @callee_owned (@in Swift.UnicodeScalar) -> (@out Swift.Bool) to @callee_owned (@unowned Swift.UnicodeScalar) -> (@unowned Swift.Bool)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTRXFo_dSi_dGSqSi__XFo_iSi_iGSqSi__() { - let input = "_TTRXFo_dSi_dGSqSi__XFo_iSi_iGSqSi__" - let output = "reabstraction thunk helper from @callee_owned (@in Swift.Int) -> (@out Swift.Int?) to @callee_owned (@unowned Swift.Int) -> (@unowned Swift.Int?)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTRGrXFo_iV18switch_abstraction1A_ix_XFo_dS0__ix_() { - let input = "_TTRGrXFo_iV18switch_abstraction1A_ix_XFo_dS0__ix_" - let output = "reabstraction thunk helper from @callee_owned (@unowned switch_abstraction.A) -> (@out A) to @callee_owned (@in switch_abstraction.A) -> (@out A)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFCF5types1gFT1bSb_T_L0_10Collection3zimfT_T_() { - let input = "_TFCF5types1gFT1bSb_T_L0_10Collection3zimfT_T_" - let output = "zim() -> () in Collection #2 in types.g(b: Swift.Bool) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFF17capture_promotion22test_capture_promotionFT_FT_SiU_FT_Si_promote0() { - let input = "_TFF17capture_promotion22test_capture_promotionFT_FT_SiU_FT_Si_promote0" - let output = "closure #1 () -> Swift.Int in capture_promotion.test_capture_promotion() -> () -> Swift.Int with unmangled suffix \"_promote0\"" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFIVs8_Processi10_argumentsGSaSS_U_FT_GSaSS_() { - let input = "_TFIVs8_Processi10_argumentsGSaSS_U_FT_GSaSS_" - let output = "_arguments : [Swift.String] in variable initialization expression of Swift._Process with unmangled suffix \"U_FT_GSaSS_\"" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFIvVs8_Process10_argumentsGSaSS_iU_FT_GSaSS_() { - let input = "_TFIvVs8_Process10_argumentsGSaSS_iU_FT_GSaSS_" - let output = "closure #1 () -> [Swift.String] in variable initialization expression of Swift._Process._arguments : [Swift.String]" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFCSo1AE() { - let input = "_TFCSo1AE" - let output = "__C.A.__ivar_destroyer" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFCSo1Ae() { - let input = "_TFCSo1Ae" - let output = "__C.A.__ivar_initializer" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTWC13call_protocol1CS_1PS_FS1_3foofT_Si() { - let input = "_TTWC13call_protocol1CS_1PS_FS1_3foofT_Si" - let output = "protocol witness for call_protocol.P.foo() -> Swift.Int in conformance call_protocol.C : call_protocol.P in call_protocol" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func T013call_protocol1CCAA1PA2aDP3fooSiyFTW() { - let input = "_T013call_protocol1CCAA1PA2aDP3fooSiyFTW" - let output = "protocol witness for call_protocol.P.foo() -> Swift.Int in conformance call_protocol.C : call_protocol.P in call_protocol" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFC12dynamic_self1X1ffT_DS0_() { - let input = "_TFC12dynamic_self1X1ffT_DS0_" - let output = "dynamic_self.X.f() -> Self" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSg5Si___TFSqcfT_GSqx_() { - let input = "_TTSg5Si___TFSqcfT_GSqx_" - let output = "generic specialization of Swift.Optional.init() -> A?" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSgq5Si___TFSqcfT_GSqx_() { - let input = "_TTSgq5Si___TFSqcfT_GSqx_" - let output = "generic specialization of Swift.Optional.init() -> A?" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSg5SiSis3Foos_Sf___TFSqcfT_GSqx_() { - let input = "_TTSg5SiSis3Foos_Sf___TFSqcfT_GSqx_" - let output = "generic specialization of Swift.Optional.init() -> A?" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSg5Si_Sf___TFSqcfT_GSqx_() { - let input = "_TTSg5Si_Sf___TFSqcfT_GSqx_" - let output = "generic specialization of Swift.Optional.init() -> A?" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSgS() { - let input = "_TTSgS" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSg5S() { - let input = "_TTSg5S" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSgSi() { - let input = "_TTSgSi" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSg5Si() { - let input = "_TTSg5Si" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSgSi_() { - let input = "_TTSgSi_" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSgSi__() { - let input = "_TTSgSi__" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSgSiS_() { - let input = "_TTSgSiS_" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSgSi__xyz() { - let input = "_TTSgSi__xyz" - do { - let demangled = try demangleAsNode(input).description - Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") - } catch {} - } - - @Test func TTSr5Si___TF4test7genericurFxx() { - let input = "_TTSr5Si___TF4test7genericurFxx" - let output = "generic not re-abstracted specialization of test.generic(A) -> A" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSrq5Si___TF4test7genericurFxx() { - let input = "_TTSrq5Si___TF4test7genericurFxx" - let output = "generic not re-abstracted specialization of test.generic(A) -> A" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TPA__TTRXFo_oSSoSS_dSb_XFo_iSSiSS_dSb_() { - let input = "_TPA__TTRXFo_oSSoSS_dSb_XFo_iSSiSS_dSb_" - let output = "partial apply forwarder for reabstraction thunk helper from @callee_owned (@in Swift.String, @in Swift.String) -> (@unowned Swift.Bool) to @callee_owned (@owned Swift.String, @owned Swift.String) -> (@unowned Swift.Bool)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TPAo__TTRGrXFo_dGSPx__dGSPx_zoPs5Error__XFo_iGSPx__iGSPx_zoPS___() { - let input = "_TPAo__TTRGrXFo_dGSPx__dGSPx_zoPs5Error__XFo_iGSPx__iGSPx_zoPS___" - let output = "partial apply ObjC forwarder for reabstraction thunk helper from @callee_owned (@in Swift.UnsafePointer) -> (@out Swift.UnsafePointer, @error @owned Swift.Error) to @callee_owned (@unowned Swift.UnsafePointer) -> (@unowned Swift.UnsafePointer, @error @owned Swift.Error)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func T0S2SSbIxxxd_S2SSbIxiid_TRTA() { - let input = "_T0S2SSbIxxxd_S2SSbIxiid_TRTA" - let output = "partial apply forwarder for reabstraction thunk helper from @callee_owned (@owned Swift.String, @owned Swift.String) -> (@unowned Swift.Bool) to @callee_owned (@in Swift.String, @in Swift.String) -> (@unowned Swift.Bool)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func T0SPyxGAAs5Error_pIxydzo_A2AsAB_pIxirzo_lTRTa() { - let input = "_T0SPyxGAAs5Error_pIxydzo_A2AsAB_pIxirzo_lTRTa" - let output = "partial apply ObjC forwarder for reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafePointer) -> (@unowned Swift.UnsafePointer, @error @owned Swift.Error) to @callee_owned (@in Swift.UnsafePointer) -> (@out Swift.UnsafePointer, @error @owned Swift.Error)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TiC4Meow5MyCls9subscriptFT1iSi_Sf() { - let input = "_TiC4Meow5MyCls9subscriptFT1iSi_Sf" - let output = "Meow.MyCls.subscript(i: Swift.Int) -> Swift.Float" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF8manglingX22egbpdajGbuEbxfgehfvwxnFT_T_() { - let input = "_TF8manglingX22egbpdajGbuEbxfgehfvwxnFT_T_" - let output = "mangling.ليهمابتكلموشعربي؟() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF8manglingX24ihqwcrbEcvIaIdqgAFGpqjyeFT_T_() { - let input = "_TF8manglingX24ihqwcrbEcvIaIdqgAFGpqjyeFT_T_" - let output = "mangling.他们为什么不说中文() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF8manglingX27ihqwctvzcJBfGFJdrssDxIboAybFT_T_() { - let input = "_TF8manglingX27ihqwctvzcJBfGFJdrssDxIboAybFT_T_" - let output = "mangling.他們爲什麽不說中文() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF8manglingX30Proprostnemluvesky_uybCEdmaEBaFT_T_() { - let input = "_TF8manglingX30Proprostnemluvesky_uybCEdmaEBaFT_T_" - let output = "mangling.Pročprostěnemluvíčesky() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF8manglingXoi7p_qcaDcFTSiSi_Si() { - let input = "_TF8manglingXoi7p_qcaDcFTSiSi_Si" - let output = "mangling.«+» infix(Swift.Int, Swift.Int) -> Swift.Int" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF8manglingoi2qqFTSiSi_T_() { - let input = "_TF8manglingoi2qqFTSiSi_T_" - let output = "mangling.?? infix(Swift.Int, Swift.Int) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFE11ext_structAV11def_structA1A4testfT_T_() { - let input = "_TFE11ext_structAV11def_structA1A4testfT_T_" - let output = "(extension in ext_structA):def_structA.A.test() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF13devirt_accessP5_DISC15getPrivateClassFT_CS_P5_DISC12PrivateClass() { - let input = "_TF13devirt_accessP5_DISC15getPrivateClassFT_CS_P5_DISC12PrivateClass" - let output = "devirt_access.(getPrivateClass in _DISC)() -> devirt_access.(PrivateClass in _DISC)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF4mainP5_mainX3wxaFT_T_() { - let input = "_TF4mainP5_mainX3wxaFT_T_" - let output = "main.(λ in _main)() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TF4mainP5_main3abcFT_aS_P5_DISC3xyz() { - let input = "_TF4mainP5_main3abcFT_aS_P5_DISC3xyz" - let output = "main.(abc in _main)() -> main.(xyz in _DISC)" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TtPMP_() { - let input = "_TtPMP_" - let output = "Any.Type" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFCs13_NSSwiftArray29canStoreElementsOfDynamicTypefPMP_Sb() { - let input = "_TFCs13_NSSwiftArray29canStoreElementsOfDynamicTypefPMP_Sb" - let output = "Swift._NSSwiftArray.canStoreElementsOfDynamicType(Any.Type) -> Swift.Bool" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFCs13_NSSwiftArrayg17staticElementTypePMP_() { - let input = "_TFCs13_NSSwiftArrayg17staticElementTypePMP_" - let output = "Swift._NSSwiftArray.staticElementType.getter : Any.Type" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TFCs17_DictionaryMirrorg9valueTypePMP_() { - let input = "_TFCs17_DictionaryMirrorg9valueTypePMP_" - let output = "Swift._DictionaryMirror.valueType.getter : Any.Type" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TF7specgen12take_closureFFTSiSi_T_T_() { - let input = "_TTSf1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TF7specgen12take_closureFFTSiSi_T_T_" - let output = "function signature specialization () in specgen.caller(Swift.Int) -> (), Argument Types : [Swift.Int]> of specgen.take_closure((Swift.Int, Swift.Int) -> ()) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSfq1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TF7specgen12take_closureFFTSiSi_T_T_() { - let input = "_TTSfq1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TF7specgen12take_closureFFTSiSi_T_T_" - let output = "function signature specialization () in specgen.caller(Swift.Int) -> (), Argument Types : [Swift.Int]> of specgen.take_closure((Swift.Int, Swift.Int) -> ()) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TTSg5Si___TF7specgen12take_closureFFTSiSi_T_T_() { - let input = "_TTSf1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TTSg5Si___TF7specgen12take_closureFFTSiSi_T_T_" - let output = "function signature specialization () in specgen.caller(Swift.Int) -> (), Argument Types : [Swift.Int]> of generic specialization of specgen.take_closure((Swift.Int, Swift.Int) -> ()) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSg5Si___TTSf1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TF7specgen12take_closureFFTSiSi_T_T_() { - let input = "_TTSg5Si___TTSf1cl35_TFF7specgen6callerFSiT_U_FTSiSi_T_Si___TF7specgen12take_closureFFTSiSi_T_T_" - let output = "generic specialization of function signature specialization () in specgen.caller(Swift.Int) -> (), Argument Types : [Swift.Int]> of specgen.take_closure((Swift.Int, Swift.Int) -> ()) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf1cpfr24_TF8capturep6helperFSiT__n___TTRXFo_dSi_dT__XFo_iSi_dT__() { - let input = "_TTSf1cpfr24_TF8capturep6helperFSiT__n___TTRXFo_dSi_dT__XFo_iSi_dT__" - let output = "function signature specialization ()]> of reabstraction thunk helper from @callee_owned (@in Swift.Int) -> (@unowned ()) to @callee_owned (@unowned Swift.Int) -> (@unowned ())" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf1cpfr24_TF8capturep6helperFSiT__n___TTRXFo_dSi_DT__XFo_iSi_DT__() { - let input = "_TTSf1cpfr24_TF8capturep6helperFSiT__n___TTRXFo_dSi_DT__XFo_iSi_DT__" - let output = "function signature specialization ()]> of reabstraction thunk helper from @callee_owned (@in Swift.Int) -> (@unowned_inner_pointer ()) to @callee_owned (@unowned Swift.Int) -> (@unowned_inner_pointer ())" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf1cpi0_cpfl0_cpse0v4u123_cpg53globalinit_33_06E7F1D906492AE070936A9B58CBAE1C_token8_cpfr36_TFtest_capture_propagation2_closure___TF7specgen12take_closureFFTSiSi_T_T_() { - let input = "_TTSf1cpi0_cpfl0_cpse0v4u123_cpg53globalinit_33_06E7F1D906492AE070936A9B58CBAE1C_token8_cpfr36_TFtest_capture_propagation2_closure___TF7specgen12take_closureFFTSiSi_T_T_" - let output = "function signature specialization of specgen.take_closure((Swift.Int, Swift.Int) -> ()) -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTSf0gs___TFVs17_LegacyStringCore15_invariantCheckfT_T_() { - let input = "_TTSf0gs___TFVs17_LegacyStringCore15_invariantCheckfT_T_" - let output = "function signature specialization of Swift._LegacyStringCore._invariantCheck() -> ()" + @Test func T() { + let input = "_T" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTSf2g___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf2g___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" + @Test func TTo() { + let input = "_TTo" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTSf2dg___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf2dg___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" + @Test func TC() { + let input = "_TC" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTSf2dgs___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf2dgs___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" + @Test func TM() { + let input = "_TM" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTSf3d_i_d_i_d_i___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf3d_i_d_i_d_i___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" + @Test func TW() { + let input = "_TW" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTSf3d_i_n_i_d_i___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf3d_i_n_i_d_i___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" + @Test func TWV() { + let input = "_TWV" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFIZvV8mangling10HasVarInit5stateSbiu_KT_Sb() { - let input = "_TFIZvV8mangling10HasVarInit5stateSbiu_KT_Sb" - let output = "implicit closure #1 : @autoclosure () -> Swift.Bool in variable initialization expression of static mangling.HasVarInit.state : Swift.Bool" + @Test func TWo() { + let input = "_TWo" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFFV23interface_type_mangling18GenericTypeContext23closureInGenericContexturFqd__T_L_3fooFTqd__x_T_() { - let input = "_TFFV23interface_type_mangling18GenericTypeContext23closureInGenericContexturFqd__T_L_3fooFTqd__x_T_" - let output = "foo #1 (A1, A) -> () in interface_type_mangling.GenericTypeContext.closureInGenericContext(A1) -> ()" + @Test func TWv() { + let input = "_TWv" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFFV23interface_type_mangling18GenericTypeContextg31closureInGenericPropertyContextxL_3fooFT_x() { - let input = "_TFFV23interface_type_mangling18GenericTypeContextg31closureInGenericPropertyContextxL_3fooFT_x" - let output = "foo #1 () -> A in interface_type_mangling.GenericTypeContext.closureInGenericPropertyContext.getter : A" + @Test func TWvd() { + let input = "_TWvd" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTWurGV23interface_type_mangling18GenericTypeContextx_S_18GenericWitnessTestS_FS1_23closureInGenericContextuRxS1_rfqd__T_() { - let input = "_TTWurGV23interface_type_mangling18GenericTypeContextx_S_18GenericWitnessTestS_FS1_23closureInGenericContextuRxS1_rfqd__T_" - let output = "protocol witness for interface_type_mangling.GenericWitnessTest.closureInGenericContext(A1) -> () in conformance interface_type_mangling.GenericTypeContext : interface_type_mangling.GenericWitnessTest in interface_type_mangling" + @Test func TWvi() { + let input = "_TWvi" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTWurGV23interface_type_mangling18GenericTypeContextx_S_18GenericWitnessTestS_FS1_g31closureInGenericPropertyContextwx3Tee() { - let input = "_TTWurGV23interface_type_mangling18GenericTypeContextx_S_18GenericWitnessTestS_FS1_g31closureInGenericPropertyContextwx3Tee" - let output = "protocol witness for interface_type_mangling.GenericWitnessTest.closureInGenericPropertyContext.getter : A.Tee in conformance interface_type_mangling.GenericTypeContext : interface_type_mangling.GenericWitnessTest in interface_type_mangling" + @Test func TWvx() { + let input = "_TWvx" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTWurGV23interface_type_mangling18GenericTypeContextx_S_18GenericWitnessTestS_FS1_16twoParamsAtDepthu0_RxS1_rfTqd__1yqd_0__T_() { - let input = "_TTWurGV23interface_type_mangling18GenericTypeContextx_S_18GenericWitnessTestS_FS1_16twoParamsAtDepthu0_RxS1_rfTqd__1yqd_0__T_" - let output = "protocol witness for interface_type_mangling.GenericWitnessTest.twoParamsAtDepth(A1, y: B1) -> () in conformance interface_type_mangling.GenericTypeContext : interface_type_mangling.GenericWitnessTest in interface_type_mangling" + @Test func T013call_protocol1CCAA1PA2aDP3fooSiyFTW() { + let input = "_T013call_protocol1CCAA1PA2aDP3fooSiyFTW" + let output = "protocol witness for call_protocol.P.foo() -> Swift.Int in conformance call_protocol.C : call_protocol.P in call_protocol" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -2767,101 +423,73 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TFC3red11BaseClassEHcfzT1aSi_S0_() { - let input = "_TFC3red11BaseClassEHcfzT1aSi_S0_" - let output = "red.BaseClassEH.init(a: Swift.Int) throws -> red.BaseClassEH" + @Test func TTSgS() { + let input = "_TTSgS" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFe27mangling_generic_extensionsRxS_8RunciblerVS_3Foog1aSi() { - let input = "_TFe27mangling_generic_extensionsRxS_8RunciblerVS_3Foog1aSi" - let output = "(extension in mangling_generic_extensions):mangling_generic_extensions.Foo.a.getter : Swift.Int" + @Test func TTSg5S() { + let input = "_TTSg5S" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFe27mangling_generic_extensionsRxS_8RunciblerVS_3Foog1bx() { - let input = "_TFe27mangling_generic_extensionsRxS_8RunciblerVS_3Foog1bx" - let output = "(extension in mangling_generic_extensions):mangling_generic_extensions.Foo.b.getter : A" + @Test func TTSgSi() { + let input = "_TTSgSi" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TTRXFo_iT__iT_zoPs5Error__XFo__dT_zoPS___() { - let input = "_TTRXFo_iT__iT_zoPs5Error__XFo__dT_zoPS___" - let output = "reabstraction thunk helper from @callee_owned () -> (@unowned (), @error @owned Swift.Error) to @callee_owned (@in ()) -> (@out (), @error @owned Swift.Error)" + @Test func TTSg5Si() { + let input = "_TTSg5Si" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFE1a() { - let input = "_TFE1a" + @Test func TTSgSi_() { + let input = "_TTSgSi_" do { let demangled = try demangleAsNode(input).description Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") } catch {} } - @Test func TF21$__lldb_module_for_E0au3$E0Ps5Error_() { - let input = "_TF21$__lldb_module_for_E0au3$E0Ps5Error_" - let output = "$__lldb_module_for_E0.$E0.unsafeMutableAddressor : Swift.Error" + @Test func TTSgSi__() { + let input = "_TTSgSi__" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TMps10Comparable() { - let input = "_TMps10Comparable" - let output = "protocol descriptor for Swift.Comparable" + @Test func TTSgSiS_() { + let input = "_TTSgSiS_" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFC4testP33_83378C430F65473055F1BD53F3ADCDB71C5doFoofT_T_() { - let input = "_TFC4testP33_83378C430F65473055F1BD53F3ADCDB71C5doFoofT_T_" - let output = "test.(C in _83378C430F65473055F1BD53F3ADCDB7).doFoo() -> ()" + @Test func TTSgSi__xyz() { + let input = "_TTSgSi__xyz" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } - @Test func TFVV15nested_generics5Lunch6DinnerCfT11firstCoursex12secondCourseGSqqd___9leftoversx14transformationFxqd___GS1_x_qd___() { - let input = "_TFVV15nested_generics5Lunch6DinnerCfT11firstCoursex12secondCourseGSqqd___9leftoversx14transformationFxqd___GS1_x_qd___" - let output = "nested_generics.Lunch.Dinner.init(firstCourse: A, secondCourse: A1?, leftovers: A, transformation: (A) -> A1) -> nested_generics.Lunch.Dinner" + @Test func T0S2SSbIxxxd_S2SSbIxiid_TRTA() { + let input = "_T0S2SSbIxxxd_S2SSbIxiid_TRTA" + let output = "partial apply forwarder for reabstraction thunk helper from @callee_owned (@owned Swift.String, @owned Swift.String) -> (@unowned Swift.Bool) to @callee_owned (@in Swift.String, @in Swift.String) -> (@unowned Swift.Bool)" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -2871,9 +499,9 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TFVFC15nested_generics7HotDogs11applyRelishFT_T_L_6RelishCfT8materialx_GS1_x_() { - let input = "_TFVFC15nested_generics7HotDogs11applyRelishFT_T_L_6RelishCfT8materialx_GS1_x_" - let output = "init(material: A) -> Relish #1 in nested_generics.HotDogs.applyRelish() -> () in Relish #1 in nested_generics.HotDogs.applyRelish() -> ()" + @Test func T0SPyxGAAs5Error_pIxydzo_A2AsAB_pIxirzo_lTRTa() { + let input = "_T0SPyxGAAs5Error_pIxydzo_A2AsAB_pIxirzo_lTRTa" + let output = "partial apply ObjC forwarder for reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafePointer) -> (@unowned Swift.UnsafePointer, @error @owned Swift.Error) to @callee_owned (@in Swift.UnsafePointer) -> (@out Swift.UnsafePointer, @error @owned Swift.Error)" do { let parsed = try demangleAsNode(input) let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) @@ -2883,16 +511,12 @@ struct DemangleSwiftProjectDerivedTests { } } - @Test func TFVFE15nested_genericsSS3fooFT_T_L_6CheeseCfT8materialx_GS0_x_() { - let input = "_TFVFE15nested_genericsSS3fooFT_T_L_6CheeseCfT8materialx_GS0_x_" - let output = "init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> () in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()" + @Test func TFE1a() { + let input = "_TFE1a" do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } + let demangled = try demangleAsNode(input).description + Issue.record("Invalid input \(input) should throw an error, instead returned \(demangled)") + } catch {} } @Test func TTWOE5imojiCSo5Imoji14ImojiMatchRankS_9RankValueS_FS2_g9rankValueqq_Ss16RawRepresentable8RawValue() { @@ -3703,54 +1327,6 @@ struct DemangleSwiftProjectDerivedTests { } catch {} } - @Test func TTSf0os___TFVs17_LegacyStringCore15_invariantCheckfT_T_() { - let input = "_TTSf0os___TFVs17_LegacyStringCore15_invariantCheckfT_T_" - let output = "function signature specialization of Swift._LegacyStringCore._invariantCheck() -> ()" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf2o___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf2o___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf2do___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf2do___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - - @Test func TTSf2dos___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_() { - let input = "_TTSf2dos___TTSf2s_d___TFVs17_LegacyStringCoreCfVs13_StringBufferS_" - let output = "function signature specialization of function signature specialization of Swift._LegacyStringCore.init(Swift._StringBuffer) -> Swift._LegacyStringCore" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - @Test func TTSf() { let input = "_TTSf" do { @@ -3791,18 +1367,6 @@ struct DemangleSwiftProjectDerivedTests { } catch {} } - @Test func Ttu4222222222222222222222222_rW_2T_2TJ_() { - let input = "_Ttu4222222222222222222222222_rW_2T_2TJ_" - let output = " B.T_.TJ" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - @Test func _$S3BBBBf0602365061_() { let input = "_$S3BBBBf0602365061_" do { @@ -3835,18 +1399,6 @@ struct DemangleSwiftProjectDerivedTests { } catch {} } - @Test func TtCF4test11doNotCrash1FT_QuL_8MyClass1() { - let input = "_TtCF4test11doNotCrash1FT_QuL_8MyClass1" - let output = "MyClass1 #1 in test.doNotCrash1() -> some" - do { - let parsed = try demangleAsNode(input) - let result = parsed.print(using: .default.union(.synthesizeSugarOnTypes)) - #expect(result == output, "Failed to demangle \(input).\nGot\n \(result)\nexpected\n \(output)") - } catch { - Issue.record("Failed to demangle \(input). Got \(error), expected \(output)") - } - } - @Test func _$s3Bar3FooVAA5DrinkVyxGs5Error_pSeRzSERzlyShy4AbcdAHO6MemberVGALSeHPAKSeAAyHC_HCg_ALSEHPAKSEAAyHC_HCg0_Iseggozo_SgWOe() { let input = "$s3Bar3FooVAA5DrinkVyxGs5Error_pSeRzSERzlyShy4AbcdAHO6MemberVGALSeHPAKSeAAyHC_HCg_ALSEHPAKSEAAyHC_HCg0_Iseggozo_SgWOe" let output = "outlined consume of (@escaping @callee_guaranteed @substituted (@guaranteed Bar.Foo) -> (@owned Bar.Drink, @error @owned Swift.Error) for >)?" diff --git a/Tests/MachOSwiftSectionTests/GenericContextTests.swift b/Tests/MachOSwiftSectionTests/GenericContextTests.swift deleted file mode 100644 index 6ff5da90..00000000 --- a/Tests/MachOSwiftSectionTests/GenericContextTests.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Foundation -import Testing -@testable import MachOSwiftSection -@testable import MachOTestingSupport - - -final class GenericContextTests: DyldCacheTests { - override class var cacheImageName: MachOImageName { .SwiftUI } - - - - @Test func genericContexts() async throws { - let typeDescriptors = try machOFileInCache.swift.typeContextDescriptors - - for typeDescriptor in typeDescriptors { - guard case .type(let type) = typeDescriptor else { - continue - } - switch type { - case .enum(let descriptor): - if let genericContext = try descriptor.typeGenericContext(in: machOFileInCache) { - print(genericContext.parameters) - } - case .struct(let descriptor): - if let genericContext = try descriptor.typeGenericContext(in: machOFileInCache) { - print(genericContext.parameters) - } - case .class(let descriptor): - if let genericContext = try descriptor.typeGenericContext(in: machOFileInCache) { - print(genericContext.parameters) - } - } - } - } -} diff --git a/Tests/SwiftDumpTests/XcodeMachOFileDumpTests.swift b/Tests/SwiftDumpTests/XcodeMachOFileDumpTests.swift index fe39b449..3aacc06b 100644 --- a/Tests/SwiftDumpTests/XcodeMachOFileDumpTests.swift +++ b/Tests/SwiftDumpTests/XcodeMachOFileDumpTests.swift @@ -10,7 +10,7 @@ import MachOFoundation @Suite(.serialized) final class XcodeMachOFileDumpTests: XcodeMachOFileTests, DumpableTests { - override class var fileName: XcodeMachOFileName { .sharedFrameworks(.DNTDocumentationSupport) } + override class var fileName: XcodeMachOFileName { .sharedFrameworks(.DNTSourceKitSupport) } } extension XcodeMachOFileDumpTests {