├── .gitignore ├── LICENSE ├── Makefile ├── Overrides.xcconfig ├── Package.swift ├── README.md ├── Sources └── Machismo │ ├── Extensions │ ├── Data+Extensions.swift │ └── String+Extensions.swift │ ├── FatHeader.swift │ ├── Graphing │ ├── AdjacencyList.swift │ ├── Edge.swift │ └── Vertex.swift │ ├── Header.swift │ ├── Load Commands │ ├── LoadDylib.swift │ ├── MinVersion.swift │ ├── RPath.swift │ ├── Segment.swift │ └── SymTab.swift │ ├── LoadCommand.swift │ ├── MachOFile.swift │ ├── MachOGraph.swift │ ├── Machismo.h │ ├── Machismo.swift │ ├── Parser.swift │ └── SemanticVersion.swift └── Tests ├── LinuxMain.swift └── MachismoTests ├── MachismoTests.swift └── XCTestManifests.swift /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SWIFTC_FLAGS = -Xswiftc "-target" -Xswiftc "x86_64-apple-macosx10.13" 2 | CONFIGURATION = debug 3 | 4 | debug: build 5 | 6 | build: 7 | swift build --configuration $(CONFIGURATION) $(SWIFTC_FLAGS) 8 | 9 | test: 10 | swift test $(SWIFTC_FLAGS) 11 | 12 | xcode: 13 | swift package generate-xcodeproj --xcconfig-overrides=Overrides.xcconfig 14 | xed . 15 | 16 | clean: 17 | swift package clean 18 | 19 | .PHONY: debug build test xcode clean 20 | -------------------------------------------------------------------------------- /Overrides.xcconfig: -------------------------------------------------------------------------------- 1 | MACOSX_DEPLOYMENT_TARGET = 10.13 2 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:4.2 2 | import PackageDescription 3 | 4 | let package = Package( 5 | name: "Machismo", 6 | products: [ 7 | .library(name: "Machismo", targets: ["Machismo"]), 8 | ], 9 | dependencies: [ 10 | // Dependencies declare other packages that this package depends on. 11 | // .package(url: /* package url */, from: "1.0.0"), 12 | ], 13 | targets: [ 14 | .target(name: "Machismo", dependencies: []), 15 | .testTarget(name: "MachismoTests", dependencies: ["Machismo"]), 16 | ] 17 | ) 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Machismo 2 | 3 | Parsing of Mach-O binaries. 4 | -------------------------------------------------------------------------------- /Sources/Machismo/Extensions/Data+Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Data+Extensions.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension Data { 12 | subscript(_ arch: FatHeader.Architecture) -> Data { 13 | return Data(self[arch.offset..<(arch.offset + arch.size)]) 14 | } 15 | 16 | func extract(_ type: T.Type, offset: Int = 0) -> T { 17 | // let ptr = UnsafeMutablePointer.allocate(capacity: 1) 18 | let data = self[offset...size] 19 | return data.withUnsafeBytes { (pointer: UnsafePointer) -> T in 20 | pointer.withMemoryRebound(to: T.self, capacity: 1, { (p) -> T in 21 | return p.pointee 22 | }) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Sources/Machismo/Extensions/String+Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // String+Extensions.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | extension String { 12 | init(_ rawCString: (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)) { 13 | var rawCString = rawCString 14 | let rawCStringSize = MemoryLayout.size(ofValue: rawCString) 15 | let string = withUnsafePointer(to: &rawCString) { (pointer) -> String in 16 | return pointer.withMemoryRebound(to: UInt8.self, capacity: rawCStringSize, { 17 | return String(cString: $0) 18 | }) 19 | } 20 | self.init(string) 21 | } 22 | 23 | /* 24 | * A variable length string in a load command is represented by an lc_str 25 | * union. The strings are stored just after the load command structure and 26 | * the offset is from the start of the load command structure. The size 27 | * of the string is reflected in the cmdsize field of the load command. 28 | * Once again any padded bytes to bring the cmdsize field to a multiple 29 | * of 4 bytes must be zero. 30 | */ 31 | init(data: Data, offset: Int, commandSize: Int, loadCommandString: lc_str) { 32 | let loadCommandStringOffset = Int(loadCommandString.offset) 33 | let stringOffset = offset + loadCommandStringOffset 34 | let length = commandSize - loadCommandStringOffset 35 | self = String(data: data[stringOffset..<(stringOffset + length)], encoding: .utf8)!.trimmingCharacters(in: .controlCharacters) 36 | } 37 | 38 | init(loadCommand: LoadCommand, string: lc_str) { 39 | let stringOffset = loadCommand.offset + Int(string.offset) 40 | self = String(data: loadCommand.data[stringOffset..<(loadCommand.offset + loadCommand.size)], encoding: .utf8)!.trimmingCharacters(in: .controlCharacters) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Sources/Machismo/FatHeader.swift: -------------------------------------------------------------------------------- 1 | // 2 | // FatHeader.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO.fat 11 | 12 | public struct FatHeader { 13 | public struct Architecture { 14 | public var cputype: cpu_type_t /* cpu specifier (int) */ 15 | public var cpusubtype: cpu_subtype_t /* machine specifier (int) */ 16 | public var offset: UInt64 /* file offset to this object file */ 17 | public var size: UInt64 /* size of this object file */ 18 | public var align: UInt32 /* alignment as a power of 2 */ 19 | 20 | init(arch: fat_arch_64) { 21 | self.cputype = arch.cputype 22 | self.cpusubtype = arch.cpusubtype 23 | self.offset = arch.offset 24 | self.size = arch.size 25 | self.align = arch.align 26 | } 27 | 28 | init(arch: fat_arch) { 29 | self.cputype = arch.cputype 30 | self.cpusubtype = arch.cpusubtype 31 | self.offset = UInt64(arch.offset) 32 | self.size = UInt64(arch.size) 33 | self.align = arch.align 34 | } 35 | } 36 | 37 | public let architectures: [Architecture] 38 | init?(data: Data) { 39 | let magic = data.extract(UInt32.self) 40 | guard [FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].contains(magic) else { return nil } 41 | 42 | var header = data.extract(fat_header.self) 43 | let is64Bit = [FAT_MAGIC_64, FAT_CIGAM_64].contains(magic) 44 | let byteSwapped = [FAT_CIGAM, FAT_CIGAM_64].contains(magic) 45 | if [FAT_CIGAM, FAT_CIGAM_64].contains(magic) { 46 | swap_fat_header(&header, byteSwappedOrder) 47 | } 48 | var offset = MemoryLayout.size(ofValue: header) 49 | var architectures: [Architecture] = [] 50 | if is64Bit { 51 | for _ in 0.. { 12 | private var adjacencyList: [Vertex: [Edge]] = [:] 13 | 14 | public init() { 15 | 16 | } 17 | 18 | func addVertex(_ data: T) -> Vertex { 19 | if let vertex = adjacencyList.first(where: { $0.key.data == data })?.key { 20 | return vertex 21 | } 22 | let vertex = Vertex(data: data) 23 | adjacencyList[vertex] = [] 24 | return vertex 25 | } 26 | 27 | func addEdge(from: Vertex, to: Vertex, weight: Double? = nil) { 28 | let edge = Edge(from: from, to: to, weight: weight) 29 | adjacencyList[from, default: []].append(edge) 30 | } 31 | 32 | func dotRepresentation(name: String) -> String { 33 | var lines: [String] = [] 34 | lines.append("digraph \(name) {") 35 | for (vertex, edges) in adjacencyList { 36 | lines.append("\t\"\(vertex)\";") 37 | for edge in edges { 38 | lines.append("\t\"\(edge.from)\" -> \"\(edge.to)\";") 39 | } 40 | } 41 | lines.append("}") 42 | return lines.joined(separator: "\n") 43 | } 44 | } 45 | 46 | extension AdjacencyListGraph { 47 | // var description: String { 48 | // var rows: [String] = [] 49 | // for edgeList in adjacencyList { 50 | // guard let edges = edgeList.edges else { 51 | // continue 52 | // } 53 | // 54 | // var row = [String]() 55 | // for edge in edges { 56 | // var value = "\(edge.to.data)" 57 | // if edge.weight != nil { 58 | // value = "(\(value): \(edge.weight!))" 59 | // } 60 | // row.append(value) 61 | // } 62 | // rows.append("\(edgeList.vertex.data) -> [\(row.joined(separator: ", "))]") 63 | // } 64 | // 65 | // return rows.joined(separator: "\n") 66 | // } 67 | } 68 | -------------------------------------------------------------------------------- /Sources/Machismo/Graphing/Edge.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Edge.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public struct Edge: Equatable where T: Hashable { 12 | public var from: Vertex 13 | public var to: Vertex 14 | public let weight: Double? 15 | } 16 | -------------------------------------------------------------------------------- /Sources/Machismo/Graphing/Vertex.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Vertex.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public struct Vertex: Hashable { 12 | var data: T 13 | } 14 | 15 | extension Vertex: CustomStringConvertible { 16 | public var description: String { 17 | return "\(data)" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Sources/Machismo/Header.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Header.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-05. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | 12 | public struct Header { 13 | public let magic: UInt32 /* mach magic number identifier */ 14 | public let cputype: cpu_type_t /* cpu specifier */ 15 | //public let cpusubtype: cpu_subtype_t /* machine specifier */ 16 | public let filetype: UInt32 /* type of file */ 17 | //public let ncmds: UInt32 /* number of load commands */ 18 | //public var sizeofcmds: UInt32 /* the size of all the load commands */ 19 | //public var flags: UInt32 /* flags */ 20 | 21 | public let loadCommandCount: UInt32 22 | public let loadCommandSize: UInt32 23 | 24 | public let size: Int 25 | 26 | public init(header: mach_header_64) { 27 | self.magic = header.magic 28 | self.cputype = header.cputype 29 | self.filetype = header.filetype 30 | self.loadCommandCount = header.ncmds 31 | self.loadCommandSize = header.sizeofcmds 32 | self.size = MemoryLayout.size(ofValue: header) 33 | } 34 | 35 | public init(header: mach_header) { 36 | self.magic = header.magic 37 | self.cputype = header.cputype 38 | self.filetype = header.filetype 39 | self.loadCommandCount = header.ncmds 40 | self.loadCommandSize = header.sizeofcmds 41 | self.size = MemoryLayout.size(ofValue: header) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Sources/Machismo/Load Commands/LoadDylib.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LoadDylib.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-12. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | 12 | struct Dylib { 13 | // public var name: lc_str /* library's path name */ 14 | // public var timestamp: UInt32 /* library's build time stamp */ 15 | // public var current_version: UInt32 /* library's current version number */ 16 | // public var compatibility_version: UInt32 /* library's compatibility vers number*/ 17 | 18 | public let name: String 19 | public let timestamp: Date 20 | public let currentVersion: SemanticVersion 21 | public let compatibilityVersion: SemanticVersion 22 | 23 | init(loadCommand: LoadCommand, dylib: dylib) { 24 | self.name = String(loadCommand: loadCommand, string: dylib.name) 25 | self.timestamp = Date(timeIntervalSince1970: Double(dylib.timestamp)) 26 | self.currentVersion = SemanticVersion(dylib.current_version) 27 | self.compatibilityVersion = SemanticVersion(dylib.compatibility_version) 28 | } 29 | } 30 | 31 | extension LoadCommand { 32 | public struct LoadDylib: LoadCommandType { 33 | public let dylib: Dylib 34 | 35 | init(loadCommand: LoadCommand) { 36 | var command = loadCommand.data.extract(dylib_command.self, offset: loadCommand.offset) 37 | if loadCommand.byteSwapped { 38 | swap_dylib_command(&command, byteSwappedOrder) 39 | } 40 | self.dylib = Dylib(loadCommand: loadCommand, dylib: command.dylib) 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Sources/Machismo/Load Commands/MinVersion.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MinVersion.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | 12 | extension LoadCommand { 13 | public struct MinVersion: LoadCommandType { 14 | public enum Platform { 15 | case iOS 16 | case macOS 17 | case tvOS 18 | case watchOS 19 | } 20 | let platform: Platform 21 | let version: SemanticVersion 22 | let sdk: SemanticVersion 23 | init(loadCommand: LoadCommand) { 24 | var command = loadCommand.data.extract(version_min_command.self, offset: loadCommand.offset) 25 | if loadCommand.byteSwapped { 26 | swap_version_min_command(&command, byteSwappedOrder) 27 | } 28 | self.platform = { 29 | switch Int32(command.cmd) { 30 | case LC_VERSION_MIN_IPHONEOS: 31 | return .iOS 32 | case LC_VERSION_MIN_MACOSX: 33 | return .macOS 34 | case LC_VERSION_MIN_TVOS: 35 | return .tvOS 36 | case LC_VERSION_MIN_WATCHOS: 37 | return .watchOS 38 | default: 39 | fatalError("Unknown Platform") 40 | } 41 | }() 42 | self.version = SemanticVersion(command.version) 43 | self.sdk = SemanticVersion(command.sdk) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Sources/Machismo/Load Commands/RPath.swift: -------------------------------------------------------------------------------- 1 | // 2 | // RPath.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-12. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | 12 | extension LoadCommand { 13 | public struct RPath: LoadCommandType { 14 | let path: String 15 | 16 | init(loadCommand: LoadCommand) { 17 | var command = loadCommand.data.extract(rpath_command.self, offset: loadCommand.offset) 18 | if loadCommand.byteSwapped { 19 | swap_rpath_command(&command, byteSwappedOrder) 20 | } 21 | self.path = String(data: loadCommand.data, offset: loadCommand.offset, commandSize: loadCommand.size, loadCommandString: command.path) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Sources/Machismo/Load Commands/Segment.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Segment.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-06. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | 12 | extension LoadCommand { 13 | public struct Segment: LoadCommandType { 14 | 15 | // public var cmd: UInt32 /* for 64-bit architectures */ /* LC_SEGMENT_64 */ 16 | // public var cmdsize: UInt32 /* includes sizeof section_64 structs */ 17 | // public var segname: (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8) /* segment name */ 18 | // public var vmaddr: UInt64 /* memory address of this segment */ 19 | // public var vmsize: UInt64 /* memory size of this segment */ 20 | // public var fileoff: UInt64 /* file offset of this segment */ 21 | // public var filesize: UInt64 /* amount to map from the file */ 22 | // public var maxprot: vm_prot_t /* maximum VM protection */ 23 | // public var initprot: vm_prot_t /* initial VM protection */ 24 | // public var nsects: UInt32 /* number of sections in segment */ 25 | // public var flags: UInt32 /* flags */ 26 | 27 | public let name: String 28 | 29 | init(command: segment_command_64) { 30 | self.name = String(command.segname) 31 | } 32 | 33 | init(command: segment_command) { 34 | self.name = String(command.segname) 35 | } 36 | 37 | init(loadCommand: LoadCommand) { 38 | if loadCommand.command == LC_SEGMENT_64 { 39 | var segmentCommand = loadCommand.data.extract(segment_command_64.self, offset: loadCommand.offset) 40 | if loadCommand.byteSwapped { 41 | swap_segment_command_64(&segmentCommand, byteSwappedOrder) 42 | } 43 | self.init(command: segmentCommand) 44 | } else { 45 | var segmentCommand = loadCommand.data.extract(segment_command.self, offset: loadCommand.offset) 46 | if loadCommand.byteSwapped { 47 | swap_segment_command(&segmentCommand, byteSwappedOrder) 48 | } 49 | self.init(command: segmentCommand) 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Sources/Machismo/Load Commands/SymTab.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SymTab.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-16. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | 12 | extension LoadCommand { 13 | public struct SymTab: LoadCommandType { 14 | 15 | init(loadCommand: LoadCommand) { 16 | var command = loadCommand.data.extract(symtab_command.self, offset: loadCommand.offset) 17 | if loadCommand.byteSwapped { 18 | swap_symtab_command(&command, byteSwappedOrder) 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Sources/Machismo/LoadCommand.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LoadCommand.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-06. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | protocol LoadCommandType { 12 | 13 | } 14 | 15 | struct LoadCommand { 16 | let command: UInt32 17 | let size: Int 18 | 19 | let data: Data 20 | let offset: Int 21 | let byteSwapped: Bool 22 | 23 | init(data: Data, offset: Int, byteSwapped: Bool) { 24 | var loadCommand = data.extract(load_command.self, offset: offset) 25 | if byteSwapped { 26 | swap_load_command(&loadCommand, byteSwappedOrder) 27 | } 28 | self.command = loadCommand.cmd 29 | self.size = Int(loadCommand.cmdsize) 30 | self.data = data 31 | self.offset = offset 32 | self.byteSwapped = byteSwapped 33 | } 34 | 35 | func command(from data: Data, offset: Int, byteSwapped: Bool) -> LoadCommandType? { 36 | switch Int(command) { 37 | case Int(LC_SEGMENT), Int(LC_SEGMENT_64): 38 | return Segment(loadCommand: self) 39 | case Int(LC_RPATH): 40 | return RPath(loadCommand: self) 41 | case Int(LC_LOAD_DYLIB): 42 | return LoadDylib(loadCommand: self) 43 | case Int(LC_VERSION_MIN_IPHONEOS), Int(LC_VERSION_MIN_MACOSX), Int(LC_VERSION_MIN_TVOS), Int(LC_VERSION_MIN_WATCHOS): 44 | return MinVersion(loadCommand: self) 45 | case Int(LC_SYMTAB): 46 | return SymTab(loadCommand: self) 47 | default: 48 | return nil 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Sources/Machismo/MachOFile.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MachO.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-12. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public struct MachOFile { 12 | public enum Architecture { 13 | case i386 14 | case x86_64 15 | } 16 | 17 | let url: URL 18 | let header: Header 19 | let commands: [LoadCommandType] 20 | 21 | public init(url: URL) throws { 22 | let data = try Data(contentsOf: url) 23 | try self.init(url: url, data: data) 24 | } 25 | 26 | public init(url: URL, data: Data) throws { 27 | self.url = url 28 | 29 | let dataSlice: Data 30 | if let fatHeader = FatHeader(data: data) { 31 | let arch = fatHeader.architectures.first { $0.cputype == CPU_TYPE_X86_64 }! 32 | dataSlice = data[arch] 33 | } else { 34 | dataSlice = data 35 | } 36 | 37 | let attributes = MachOFile.machAttributes(from: dataSlice) 38 | let header = MachOFile.header(from: dataSlice, attributes: attributes) 39 | 40 | self.header = header 41 | self.commands = MachOFile.segmentCommands(from: dataSlice, header: header, attributes: attributes) 42 | } 43 | 44 | private struct MachAttributes { 45 | let is64Bit: Bool 46 | let isByteSwapped: Bool 47 | } 48 | private static func machAttributes(from data: Data) -> MachAttributes { 49 | let magic = data.extract(UInt32.self) 50 | let is64Bit = magic == MH_MAGIC_64 || magic == MH_CIGAM_64 51 | let isByteSwapped = magic == MH_CIGAM || magic == MH_CIGAM_64 52 | return MachAttributes(is64Bit: is64Bit, isByteSwapped: isByteSwapped) 53 | } 54 | 55 | private static func header(from data: Data, attributes: MachAttributes) -> Header { 56 | if attributes.is64Bit { 57 | let header = data.extract(mach_header_64.self) 58 | return Header(header: header) 59 | } else { 60 | let header = data.extract(mach_header.self) 61 | return Header(header: header) 62 | } 63 | } 64 | 65 | private static func segmentCommands(from data: Data, header: Header, attributes: MachAttributes) -> [LoadCommandType] { 66 | var segmentCommands: [LoadCommandType] = [] 67 | var offset = header.size 68 | for _ in 0..() 16 | 17 | init(executableURL: URL) throws { 18 | self.executableURL = executableURL 19 | 20 | try load(url: executableURL) 21 | } 22 | 23 | func load(url: URL) throws { 24 | guard binaries[url] == nil else { return } 25 | let binary = try MachOFile(url: url) 26 | binaries[url] = binary 27 | 28 | let fromVertex = graph.addVertex(url) 29 | 30 | let loaderExecutablePath = "@executable_path/" 31 | let rpaths: [URL] = binary.rpaths.compactMap { 32 | if $0.hasPrefix(loaderExecutablePath) { 33 | let path = $0.dropFirst(loaderExecutablePath.count) 34 | return URL(fileURLWithPath: String(path), relativeTo: executableURL) 35 | } 36 | return nil 37 | } 38 | 39 | 40 | let dylibURLs: [URL] = binary.dylibs.compactMap { 41 | return path(for: $0, rpaths: rpaths) 42 | } 43 | 44 | try dylibURLs.forEach { 45 | let toVertex = graph.addVertex($0) 46 | graph.addEdge(from: fromVertex, to: toVertex) 47 | try load(url: $0) 48 | } 49 | } 50 | 51 | private func path(for dylib: Dylib, rpaths: [URL]) -> URL? { 52 | let loaderRPath = "@rpath/" 53 | if dylib.name.hasPrefix(loaderRPath) { 54 | for rpath in rpaths { 55 | let path = dylib.name.dropFirst(loaderRPath.count) 56 | let potentialURL = URL(fileURLWithPath: String(path), relativeTo: rpath) 57 | if let reachable = try? potentialURL.checkResourceIsReachable(), reachable { 58 | return potentialURL 59 | } 60 | } 61 | return nil 62 | } else { 63 | return URL(fileURLWithPath: dylib.name) 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Sources/Machismo/Machismo.h: -------------------------------------------------------------------------------- 1 | // 2 | // Machismo.h 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-04. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | //! Project version number for Machismo. 12 | FOUNDATION_EXPORT double MachismoVersionNumber; 13 | 14 | //! Project version string for Machismo. 15 | FOUNDATION_EXPORT const unsigned char MachismoVersionString[]; 16 | 17 | // In this header, you should import all the public headers of your framework using statements like #import 18 | 19 | 20 | -------------------------------------------------------------------------------- /Sources/Machismo/Machismo.swift: -------------------------------------------------------------------------------- 1 | struct Machismo { 2 | var text = "Hello, World!" 3 | } 4 | -------------------------------------------------------------------------------- /Sources/Machismo/Parser.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Parser.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-04. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import MachO 11 | import MachO.fat 12 | 13 | let byteSwappedOrder = NXByteOrder(rawValue: 0) 14 | -------------------------------------------------------------------------------- /Sources/Machismo/SemanticVersion.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SemanticVersion.swift 3 | // Machismo 4 | // 5 | // Created by Geoffrey Foster on 2018-05-13. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public struct SemanticVersion { 12 | public var majorVersion: Int 13 | public var minorVersion: Int 14 | public var patchVersion: Int 15 | public init() { 16 | self.init(majorVersion: 0, minorVersion: 0, patchVersion: 0) 17 | } 18 | 19 | public init(majorVersion: Int, minorVersion: Int, patchVersion: Int) { 20 | self.majorVersion = majorVersion 21 | self.minorVersion = minorVersion 22 | self.patchVersion = patchVersion 23 | } 24 | 25 | init(_ value: UInt32) { 26 | self.init( 27 | majorVersion: Int(value >> 16), 28 | minorVersion: Int(value >> 8) & 0xFF, 29 | patchVersion: Int(value) & 0xFF 30 | ) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Tests/LinuxMain.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | 3 | import MachismoTests 4 | 5 | var tests = [XCTestCaseEntry]() 6 | tests += MachismoTests.allTests() 7 | XCTMain(tests) -------------------------------------------------------------------------------- /Tests/MachismoTests/MachismoTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MachismoTests.swift 3 | // MachismoTests 4 | // 5 | // Created by Geoffrey Foster on 2018-05-04. 6 | // Copyright © 2018 g-Off.net. All rights reserved. 7 | // 8 | 9 | import XCTest 10 | @testable import Machismo 11 | 12 | class MachismoTests: XCTestCase { 13 | let url = URL(fileURLWithPath: "/Applications/Xcode.app/Contents/MacOS/Xcode") 14 | // func testRead() throws { 15 | // let parser = try Parser(url: url) 16 | // XCTAssertTrue(parser.is64Bit) 17 | // XCTAssertFalse(parser.byteSwapped) 18 | // parser.parseHeader() 19 | // //parser.parseSegmentCommands() 20 | // } 21 | 22 | func testFat() throws { 23 | //let machFile = try MachOFile(url: URL(fileURLWithPath: "/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa")) 24 | let machFile = try MachOFile(url: URL(fileURLWithPath: "/Applications/Xcode.app/Contents/MacOS/Xcode")) 25 | print("hello") 26 | } 27 | 28 | func testGraph() throws { 29 | var graph = try MachOGraph(executableURL: url) 30 | print("hello") 31 | let dot = graph.graph.dotRepresentation(name: "\"\(url.path)\"") 32 | print(dot) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Tests/MachismoTests/XCTestManifests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | 3 | #if !os(macOS) 4 | public func allTests() -> [XCTestCaseEntry] { 5 | return [ 6 | testCase(MachismoTests.allTests), 7 | ] 8 | } 9 | #endif --------------------------------------------------------------------------------