Skip to content

Commit 91b4650

Browse files
Fix deinit against uninited InstanceEntity
1 parent e3f8a40 commit 91b4650

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Sources/WasmKit/Execution/StoreAllocator.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,15 @@ class BumpAllocator<T> {
5656
currentOffset += 1
5757
return pointer
5858
}
59+
60+
/// Deallocates a just-allocated pointer.
61+
///
62+
/// - Parameter pointer: The pointer to deallocate.
63+
/// - Precondition: The pointer must be the last allocated pointer.
64+
func deallocate(_ pointer: UnsafeMutablePointer<T>) {
65+
currentOffset -= 1
66+
assert(pointer == currentPage.baseAddress!.advanced(by: currentOffset), "Deallocating a pointer out of order.")
67+
}
5968
}
6069

6170
protocol ValidatableEntity {
@@ -256,6 +265,14 @@ extension StoreAllocator {
256265
let types = module.types
257266
// Uninitialized instance
258267
let instancePointer = instances.allocate()
268+
var instanceInitialized = false
269+
defer {
270+
// If the instance is not initialized due to an exception, deallocate the buffer but don't
271+
// deinitalize it.
272+
if !instanceInitialized {
273+
instances.deallocate(instancePointer)
274+
}
275+
}
259276
let instanceHandle = InternalInstance(unsafe: instancePointer)
260277
var importedFunctions: [InternalFunction] = []
261278
var importedTables: [InternalTable] = []
@@ -430,6 +447,7 @@ extension StoreAllocator {
430447
hasDataCount: module.hasDataCount
431448
)
432449
instancePointer.initialize(to: instanceEntity)
450+
instanceInitialized = true
433451
return instanceHandle
434452
}
435453

0 commit comments

Comments
 (0)