Skip to content

Commit

Permalink
Fix use-after-free in DatabaseConnection._run
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Keller committed Nov 2, 2017
1 parent 119bfc0 commit a7fc3ad
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
21 changes: 11 additions & 10 deletions Sources/SwiftChatSE/DatabaseConnection.swift
Expand Up @@ -249,22 +249,23 @@ open class DatabaseConnection {
//cache miss; compile the query
var tail: UnsafePointer<Int8>?
var stmt: OpaquePointer?
let result = query.utf8CString.withUnsafeBufferPointer {
sqlite3_prepare_v2(
try query.utf8CString.withUnsafeBufferPointer {
let result = sqlite3_prepare_v2(
db,
$0.baseAddress,
Int32($0.count),
&stmt,
&tail
)
}

guard result == SQLITE_OK, stmt != nil else {
try throwSQLiteError(code: result, db: db)
}
if tail != nil && tail!.pointee != 0 {
//programmer error, so crash instead of throwing
fatalError("\(#function) does not accept multiple statements: '\(query)' (tail: \(String(cString: tail!)))")


guard result == SQLITE_OK, stmt != nil else {
try throwSQLiteError(code: result, db: db)
}
if tail != nil && tail!.pointee != 0 {
//programmer error, so crash instead of throwing
fatalError("\(#function) does not accept multiple statements: '\(query)' (tail: \(String(cString: tail!)))")
}
}

statement = stmt!
Expand Down
9 changes: 5 additions & 4 deletions Tests/SwiftChatSETests/DatabaseTests.swift
Expand Up @@ -34,17 +34,18 @@ class DatabaseTests: XCTestCase {

func testRepeatedAsynchronousQuery() throws {
let iterations = 1000
let expectation = self.expectation(description: "Finished iterations")
let sema = DispatchSemaphore(value: 0)

expectation.expectedFulfillmentCount = iterations
for _ in 0..<iterations {
DispatchQueue.global().async {
_ = try! self.db.run("SELECT 1", cache: false)
expectation.fulfill()
sema.signal()
}
}

waitForExpectations(timeout: 10)
for _ in 0..<iterations {
sema.wait()
}
}

func testOnDiskDatabase() {
Expand Down

0 comments on commit a7fc3ad

Please sign in to comment.