Skip to content

Commit 518bf42

Browse files
authored
Fixes misaligned pointer by reading from the buffer instead of loading the memory separately (#8649)
1 parent 575d616 commit 518bf42

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

swift/Sources/FlatBuffers/FlatBufferBuilder.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -303,12 +303,12 @@ public struct FlatBufferBuilder {
303303
var isAlreadyAdded: Int?
304304

305305
let vt2 = _bb.memory.advanced(by: _bb.writerIndex)
306-
let len2 = vt2.load(fromByteOffset: 0, as: Int16.self)
306+
let len2 = vt2.bindMemory(to: Int16.self, capacity: 1).pointee
307307

308308
for index in stride(from: 0, to: _vtables.count, by: 1) {
309309
let position = _bb.capacity &- Int(_vtables[index])
310310
let vt1 = _bb.memory.advanced(by: position)
311-
let len1 = _bb.read(def: Int16.self, position: position)
311+
let len1 = vt1.bindMemory(to: Int16.self, capacity: 1).pointee
312312
if len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2)) { continue }
313313

314314
isAlreadyAdded = Int(_vtables[index])

tests/swift/Tests/Flatbuffers/FlatBuffersTests.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,22 @@ final class FlatBuffersTests: XCTestCase {
120120
XCTAssertEqual(scalarTable.justEnum, .one)
121121
XCTAssertNil(scalarTable.maybeEnum)
122122
}
123+
124+
func testAlignmentCrash() {
125+
var builder = FlatBufferBuilder(initialSize: 256)
126+
127+
// Create two identical tables to trigger vtable deduplication
128+
let str1 = builder.create(string: "test")
129+
let start1 = builder.startTable(with: 1)
130+
builder.add(offset: str1, at: 0)
131+
_ = builder.endTable(at: start1)
132+
133+
// Second table triggers vtable comparison where crash occurs
134+
let str2 = builder.create(string: "crash")
135+
let start2 = builder.startTable(with: 1)
136+
builder.add(offset: str2, at: 0)
137+
_ = builder.endTable(at: start2) // ← Crashes here on ARM64
138+
}
123139
}
124140

125141
class Country {

0 commit comments

Comments
 (0)