Skip to content

Commit 69c136c

Browse files
authored
Merge pull request #223 from p-x9/feature/endianness
Add property to get byte-order of the binary
2 parents 37ce6ce + 4e17c00 commit 69c136c

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

Sources/MachOKit/MachOFile.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
//
77
//
88

9+
import CoreFoundation // for CFByteOrderGetCurrent (Linux)
910
import Foundation
1011
#if compiler(>=6.0) || (compiler(>=5.10) && hasFeature(AccessLevelOnImport))
1112
internal import FileIO
@@ -118,6 +119,15 @@ public class MachOFile: MachORepresentable {
118119
}
119120
}
120121

122+
extension MachOFile {
123+
public var endian: Endian {
124+
let hostIsLittleEndian = CFByteOrderGetCurrent() == CFByteOrderLittleEndian.rawValue
125+
return hostIsLittleEndian
126+
? (isSwapped ? .big : .little)
127+
: (isSwapped ? .little : .big)
128+
}
129+
}
130+
121131
extension MachOFile {
122132
public var rpaths: [String] {
123133
loadCommands

Sources/MachOKit/MachOImage.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
//
77
//
88

9+
import CoreFoundation // for CFByteOrderGetCurrent (Linux)
910
import Foundation
1011

1112
/// Structure for `MachO` representation loaded from memory.
@@ -145,6 +146,19 @@ extension MachOImage {
145146
}
146147
}
147148

149+
extension MachOImage {
150+
public var endian: Endian {
151+
switch CFByteOrderGetCurrent() {
152+
case numericCast(CFByteOrderLittleEndian.rawValue):
153+
return .little
154+
case numericCast(CFByteOrderBigEndian.rawValue):
155+
return .big
156+
default:
157+
fatalError("Unexpected byte order value: \(CFByteOrderGetCurrent())")
158+
}
159+
}
160+
}
161+
148162
extension MachOImage {
149163
public var dependencies: [DependedDylib] {
150164
var dependencies = [DependedDylib]()

Sources/MachOKit/Model/Endian.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
//
2+
// Endian.swift
3+
// MachOKit
4+
//
5+
// Created by p-x9 on 2025/07/09
6+
//
7+
//
8+
9+
public enum Endian {
10+
case little
11+
case big
12+
}

Sources/MachOKit/Protocol/MachORepresentable.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ public protocol MachORepresentable {
3939
/// Sequence of load commands
4040
var loadCommands: LoadCommands { get }
4141

42+
/// Byte Order of this binary
43+
var endian: Endian { get }
44+
4245
/// List of runpaths
4346
var rpaths: [String] { get }
4447
/// List of depended dynamic libraries

0 commit comments

Comments
 (0)