-
Notifications
You must be signed in to change notification settings - Fork 6
/
MachOPrintTests.swift
707 lines (632 loc) · 22.1 KB
/
MachOPrintTests.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//
// MachOPrintTests.swift
//
//
// Created by p-x9 on 2023/12/19.
//
//
import XCTest
@testable import MachOKit
#if canImport(Darwin)
final class MachOPrintTests: XCTestCase {
private var machO: MachOImage!
override func setUp() {
machO = MachOImage(name: "MachOKitTests")
}
func testHeader() throws {
let header = machO.header
print("----")
print("Magic:", header.magic!)
print("CPU:", header.cpu)
print("FileType:", header.fileType?.description ?? "unknown")
print("Flags:", header.flags.bits.map(\.description).joined(separator: ", "))
}
func testLoadCommands() throws {
for command in machO.loadCommands {
print("----")
print(command.type)
print(command.info)
}
}
func testSegments() throws {
for segment in machO.segments {
print("----")
print("Name:", segment.segmentName)
print(
"InitProt:",
segment.initialProtection.bits
.map(\.description)
.joined(separator: ", ")
)
print(
"MaxProt:",
segment.maxProtection.bits
.map(\.description)
.joined(separator: ", ")
)
if !segment.flags.bits.isEmpty {
print(
"Flags:",
segment.flags.bits
.map(\.description)
.joined(separator: ", ")
)
}
}
}
func testSections() throws {
for section in machO.sections {
print("----")
print("Name:", "\(section.segmentName).\(section.sectionName)")
print("Type:", section.flags.type?.description ?? "unknown")
print(
"Attributes:",
section.flags.attributes.bits
.map(\.description).joined(separator: ", ")
)
}
}
func testExternalRelocations() {
guard let relocations = machO.externalRelocations else {
return
}
let symbols = machO.symbols
for relocation in relocations {
print("--")
switch relocation.info {
case let .general(info):
print("Offset:", "0x" + String(info.r_address, radix: 16))
if let length = info.length {
print("Length:", length)
}
print("isExternal:", info.isExternal)
print("isScatted:", info.isScattered)
print("pcRelative:", info.isRelocatedPCRelative)
if let symbolIndex = info.symbolIndex {
print("SymbolIndex:", symbolIndex)
print("SymbolName:", symbols[AnyIndex(symbolIndex)].name)
}
if let sectionOrdinal = info.sectionOrdinal {
print("SectionOrdinal:", sectionOrdinal)
}
if let cpuType = machO.header.cpuType,
let type = info.type(for: cpuType) {
print("Type:", type)
}
case let .scattered(info):
print("Offset:", "0x" + String(info.layout.r_address, radix: 16))
if let length = info.length {
print("Length:", length)
}
print("isScatted:", info.isScattered)
print("pcRelative:", info.isRelocatedPCRelative)
if let cpuType = machO.header.cpuType,
let type = info.type(for: cpuType) {
print("Type:", type)
}
print("Value:", "0x" + String(info.r_value, radix: 16))
}
}
}
func testDependencies() throws {
for dependency in machO.dependencies {
let dependency = dependency.dylib
print("----")
print("Name:", dependency.name)
print("CurrentVersion:", dependency.currentVersion)
print("CompatibilityVersion:", dependency.compatibilityVersion)
print("TimeStamp:", dependency.timestamp)
}
}
func testRPaths() throws {
for rpath in machO.rpaths {
print(rpath)
}
}
func testSymbols() throws {
for symbol in machO.symbols {
print("----")
print("0x" + String(symbol.offset, radix: 16), symbol.name)
if let flags = symbol.nlist.flags {
print("Flags:", flags.bits)
if let type = flags.type {
print("Type:", type)
}
if let stab = flags.stab {
print("Stab:", stab)
}
}
if let sectionNumber = symbol.nlist.sectionNumber {
let section = machO.sections[sectionNumber - 1]
print("Section:", "\(section.segmentName).\(section.sectionName)")
}
if let description = symbol.nlist.symbolDescription {
print("SymbolDescription:", description.bits)
if let referenceFlag = description.referenceFlag {
print("ReferenceFlag:", referenceFlag)
}
let libraryOrdinal = Int(description.libraryOrdinal) - 1
if libraryOrdinal == -1,
let info = machO.loadCommands.info(of: LoadCommand.idDylib) {
print("LibraryOrdinal:", info.dylib(cmdsStart: machO.cmdsStartPtr).name)
} else if machO.dependencies.indices.contains(libraryOrdinal) {
print("LibraryOrdinal:", machO.dependencies[libraryOrdinal].dylib.name)
}
}
}
}
func testIndirectSymbols() throws {
guard let _indirectSymbols = machO.indirectSymbols else { return }
let symbols = Array(machO.symbols)
let indirectSymbols = Array(_indirectSymbols)
for section in machO.sections {
guard let index = section.indirectSymbolIndex,
let size = section.numberOfIndirectSymbols else {
continue
}
print(section.segmentName + "." + section.sectionName)
let indirectSymbols = indirectSymbols[index..<index + size]
for symbol in indirectSymbols {
print(" ", symbol._value, terminator: " ")
if let index = symbol.index {
print(symbols[index].name)
} else {
print(symbol)
}
}
}
}
func testSymbolStrings() throws {
guard let cstrings = machO.symbolStrings else { return }
for (i, cstring) in cstrings.enumerated() {
let ptr = cstrings.basePointer.advanced(by: cstring.offset)
print(i, "0x" + String(Int(bitPattern: ptr), radix: 16), cstring.string)
}
}
func testCStrings() throws {
guard let cstrings = machO.cStrings else { return }
for (i, cstring) in cstrings.enumerated() {
let ptr = cstrings.basePointer.advanced(by: cstring.offset)
print(i, "0x" + String(Int(bitPattern: ptr), radix: 16), cstring.string)
}
}
func testAllCStrings() throws {
for (i, cstring) in machO.allCStrings.enumerated() {
print(i, cstring)
}
}
}
extension MachOPrintTests {
func testRebaseOperations() throws {
guard let rebaseOperations = machO.rebaseOperations else { return }
for operation in rebaseOperations {
print(operation)
}
}
func testBindOperations() throws {
guard let bindOperations = machO.bindOperations else { return }
for operation in bindOperations {
print(operation)
}
}
func testWeakBindOperations() throws {
guard let bindOperations = machO.weakBindOperations else { return }
for operation in bindOperations {
print(operation)
}
}
func testLazyBindOperations() throws {
guard let bindOperations = machO.lazyBindOperations else { return }
for operation in bindOperations {
print(operation)
}
}
func testExportTries() throws {
guard let exportTrieEntries = machO.exportTrieEntries else { return }
for entry in exportTrieEntries {
print(entry)
}
}
}
extension MachOPrintTests {
func testRebases() throws {
for rebase in machO.rebases {
guard let segment = rebase.segment64(in: machO),
let section = rebase.section64(in: machO),
let address = rebase.address(in: machO) else {
continue
}
print(
segment.segmentName,
section.sectionName,
"0x" + String(address, radix: 16).uppercased(),
rebase.type
)
}
}
func testBindingSymbols() throws {
for binding in machO.bindingSymbols {
guard let segment = binding.segment64(in: machO),
let section = binding.section64(in: machO),
let address = binding.address(in: machO) else {
continue
}
print(
segment.segmentName,
section.sectionName,
"0x" + String(address, radix: 16).uppercased(),
binding.type,
binding.addend,
binding.library(in: machO)?.name ?? "\(binding.bindSpecial!)",
binding.symbolName
)
}
}
func testExportedSymbols() throws {
for symbol in machO.exportedSymbols {
print("----")
print("0x" + String(symbol.offset, radix: 16), symbol.name)
print("Flags:", symbol.flags.bits)
if let kind = symbol.flags.kind {
print("Kind:", kind)
}
if let ordinal = symbol.ordinal {
let libraryOrdinal = Int(ordinal) - 1
if libraryOrdinal == -1,
let info = machO.loadCommands.info(of: LoadCommand.idDylib) {
print("LibraryOrdinal:", info.dylib(cmdsStart: machO.cmdsStartPtr).name)
} else if machO.dependencies.indices.contains(libraryOrdinal) {
print("LibraryOrdinal:", machO.dependencies[libraryOrdinal].dylib.name)
}
}
if let importedName = symbol.importedName {
print("Imported Name:", importedName)
}
if let stub = symbol.stub, let resolver = symbol.resolver {
print("Stub:", stub)
print("Resolver:", resolver)
}
}
}
}
extension MachOPrintTests {
func testLoadDylinkerCommand() {
for info in machO.loadCommands.infos(of: LoadCommand.loadDylinker) {
print(info.name(cmdsStart: machO.cmdsStartPtr))
}
}
func testVersionMinCommand() {
// macOS
for info in machO.loadCommands.infos(of: LoadCommand.versionMinMacosx) {
print("version: \(info.version), sdk: \(info.sdk)")
}
// iOS
for info in machO.loadCommands.infos(of: LoadCommand.versionMinIphoneos) {
print("version: \(info.version), sdk: \(info.sdk)")
}
// watchOS
for info in machO.loadCommands.infos(of: LoadCommand.versionMinWatchos) {
print("version: \(info.version), sdk: \(info.sdk)")
}
// tvOS
for info in machO.loadCommands.infos(of: LoadCommand.versionMinWatchos) {
print("version: \(info.version), sdk: \(info.sdk)")
}
}
func testBuildVersionCommand() {
for info in machO.loadCommands.infos(of: LoadCommand.buildVersion) {
print("----")
print(info.platform)
let tools = info.tools(cmdsStart: machO.cmdsStartPtr)
for tool in Array(tools) {
print(" ", tool.tool ?? "\(tool.layout.tool)", tool.version)
}
}
}
func testUUIDCommand() {
for info in machO.loadCommands.infos(of: LoadCommand.uuid) {
print(info.uuid)
}
}
func testMainCommand() {
machO.loadCommands.infos(of: LoadCommand.main)
.forEach {
let offset = $0.layout.entryoff
print("0x" + String(offset, radix: 16))
}
}
func testLinkerOptionCommand() {
machO.loadCommands.infos(of: LoadCommand.linkerOption)
.forEach {
print($0.count, $0.options(cmdsStart: machO.cmdsStartPtr))
}
}
func testThreadCommand() {
let commands = Array(machO.loadCommands.infos(of: LoadCommand.thread))
+ Array(machO.loadCommands.infos(of: LoadCommand.unixthread))
for command in commands {
print("Flavor:",
command.flavor(
cmdsStart: machO.cmdsStartPtr,
cpuType: machO.header.cpuType!
)?.description ?? "unknown"
)
print("Count:", command.count(cmdsStart: machO.cmdsStartPtr) ?? 0)
if let state = command.state(cmdsStart: machO.cmdsStartPtr) {
print(
"State:",
state.withUnsafeBytes {
[UInt64]($0.bindMemory(to: UInt64.self))
}.map { "0x" + String($0, radix: 16) }
.joined(separator: ", ")
)
}
}
}
}
extension MachOPrintTests {
func testClosestSymbol() {
for symbol in machO.symbols.shuffled().prefix(100) {
let offset = symbol.offset + Int.random(in: 0..<100)
guard let best = machO.closestSymbol(
at: offset
) else {
continue
}
let diff = best.offset - offset
var info = Dl_info()
let isSucceeded = dladdr(machO.ptr.advanced(by: offset), &info) != 0
if !isSucceeded { print("failed") }
guard let dli_saddr = info.dli_saddr,
let dli_sname = info.dli_sname else {
print("[dladdr is nil]", best.name, diff)
continue
}
XCTAssertEqual(
dli_saddr,
machO.ptr.advanced(by: best.offset)
)
print(
offset == best.offset,
dli_saddr == machO.ptr.advanced(by: offset),
dli_saddr == machO.ptr.advanced(by: best.offset),
strcmp(best.nameC + 1, dli_sname),
best.name,
diff
)
}
}
}
extension MachOPrintTests {
func testFindSymbolByName() {
let name = "$s13MachOKitTests0a10OFilePrintC0C11testSymbolsyyKF0aB011LoadCommandOAE05DylibI0VcAGmcfu_AgIcfu0_"
let demangledName = "MachOKitTests.MachOFilePrintTests.testLinkerOptionCommand() -> ()"
guard let symbol = machO.symbol(named: name) else {
XCTFail("not found symbol named \"\(name)\"")
return
}
print("found", symbol.name)
XCTAssert(
name == symbol.name ||
"_" + name == symbol.name
)
guard let symbol2 = machO.symbol(named: demangledName, mangled: false) else {
XCTFail("not found symbol named \"\(demangledName)\"")
return
}
print("found", symbol2.name)
XCTAssert(
demangledName == symbol2.demangledName
)
}
}
extension MachOPrintTests {
func testFunctionStarts() {
guard let functionStarts = machO.functionStarts else { return }
let starts = Array(functionStarts)
var lastOffset: UInt = functionStarts.functionStartBase
for start in starts {
print(
"+\(start.offset - lastOffset)",
String(start.offset, radix: 16)
)
lastOffset = start.offset
let address = machO.ptr
.advanced(by: numericCast(start.offset))
var info = Dl_info()
dladdr(address, &info)
// Not always matched.
let diff = UInt(bitPattern: address) - UInt(bitPattern: info.dli_saddr)
if diff != 0 {
print("dladdr diff", diff)
}
}
}
}
extension MachOPrintTests {
func testDataInCode() {
// x86_64 `Foundation`
if let dataInCode = machO.dataInCode {
for data in dataInCode {
print(String(data.offset, radix: 16), data.length, data.kind?.description ?? "unknown")
}
}
}
}
extension MachOPrintTests {
func testChainedFixUps() {
guard let chainedFixups = machO.dyldChainedFixups else {
return
}
guard let header = chainedFixups.header else { return }
print("Header:", header.layout)
guard let startsInImage = chainedFixups.startsInImage else { return }
print("Image:", startsInImage.layout)
let segments = chainedFixups.startsInSegments(of: startsInImage)
for segment in segments {
print("Segment:", segment.layout)
let pages = chainedFixups.pages(of: segment)
print(
"pages: ",
"[" +
pages.map {
String($0.offset, radix: 16)
}.joined(separator: ", ")
+ "]"
)
}
}
func testChainedFixUpsImports() {
guard let chainedFixups = machO.dyldChainedFixups else {
return
}
let libraries = machO.dependencies
let imports = chainedFixups.imports
for (i, `import`) in imports.enumerated() {
print("----")
print("0x" + String(i, radix: 16))
let info = `import`.info
if let libraryOrdinalType = info.libraryOrdinalType {
print("Library:", libraryOrdinalType)
} else if libraries.indices.contains(info.libraryOrdinal - 1) {
print("Library:", libraries[info.libraryOrdinal - 1].dylib.name)
}
let name = chainedFixups.symbolName(
for: info.nameOffset
)
if let name { print("Name:", name) }
}
}
}
extension MachOPrintTests {
func testStaticSymbolSearch() {
let f: @convention(c) (Int) -> String = { "\($0)" }
let ptr = unsafeBitCast(f, to: UnsafeRawPointer.self)
guard let (machO, symbol) = MachOImage.symbol(for: ptr) else {
return
}
if let path = machO.path {
print(path)
}
print(symbol.demangledName)
}
func testStaticClosestSymbolSearch() {
let f: @convention(c) (Int) -> String = { "\($0)" }
var ptr = unsafeBitCast(f, to: UnsafeRawPointer.self)
ptr = ptr.advanced(by: 1)
guard let (machO, symbol) = MachOImage.closestSymbol(at: ptr) else {
return
}
if let path = machO.path {
print(path)
}
print(symbol.demangledName)
}
func testStaticSymbolSearchByName() {
let name = "$ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtF"
let symbols = MachOImage.symbols(named: name, mangled: true)
for (image, symbol) in symbols {
if let path = image.path {
print(path, symbol.nlist.sectionNumber?.description ?? "NO_SECT")
}
}
}
}
extension MachOPrintTests {
func testCodeSign() {
guard let machO = MachOImage(name: "xctest"),
let codeSign = machO.codeSign else {
return
}
guard let superBlob = codeSign.superBlob else {
return
}
let indices = superBlob.blobIndices(in: codeSign)
print(
indices.compactMap(\.type)
)
}
func testCodeSignEntitlements() {
guard let machO = MachOImage(name: "xctest"),
let codeSign = machO.codeSign else {
return
}
guard let entitlements = codeSign.embeddedEntitlements else {
return
}
print(entitlements)
}
func testCodeSignCodeDirectories() {
guard let machO = MachOImage(name: "xctest"),
let codeSign = machO.codeSign else {
return
}
let directories = codeSign.codeDirectories
/* Path */
print("Path:", machO.path ?? "unknown")
/* Identifier */
let identifiers = directories
.compactMap {
$0.identifier(in: codeSign)
}
print(
"identifier:",
identifiers
)
/* CD Hash */
let cdHashes = directories
.compactMap {
$0.hash(in: codeSign)
}.map {
$0.map { String(format: "%02x", $0) }.joined()
}
print(
"CDHash:",
cdHashes
)
/* Page Hashes*/
// let pageHashes = directories
// .map { directory in
// (-Int(directory.nSpecialSlots)..<Int(directory.nCodeSlots))
// .map {
// if let hash = directory.hash(forSlot: $0, in: codeSign) {
// return "\($0) " + hash.map { String(format: "%02x", $0) }.joined()
// } else {
// return "\($0) unknown"
// }
// }
// }
// print(
// "PageHashes:",
// pageHashes
// )
/* Team IDs */
let teamIDs = directories
.compactMap {
$0.teamId(in: codeSign)
}
print(
"TeamID:",
teamIDs
)
/* Exec Segment */
let execSeg = directories
.compactMap {
$0.executableSegment(in: codeSign)
}
print(
"ExecSeg:",
execSeg
)
/* Runtime */
let runtime = directories
.compactMap {
$0.runtime(in: codeSign)
}
print(
"Runtime:",
runtime
)
}
}
#endif