Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ let DarwinPlatforms: [Platform] = [.macOS, .iOS, .watchOS, .tvOS, .visionOS]
let cliCommandsTarget = Target.target(
name: "CLICommands",
dependencies: [
"SystemExtras",
"WAT",
"WasmKit",
"WasmKitWASI",
Expand Down Expand Up @@ -99,6 +100,7 @@ let package = Package(
.target(
name: "WasmParser",
dependencies: [
"SystemExtras",
"WasmTypes",
.product(name: "SystemPackage", package: "swift-system"),
.target(
Expand Down
2 changes: 1 addition & 1 deletion Sources/CLICommands/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ add_wasmkit_library(CLICommands
)

target_link_wasmkit_libraries(CLICommands PUBLIC
WAT WasmKitWASI)
SystemExtras WAT WasmKitWASI)

add_dependencies(
CLICommands
Expand Down
15 changes: 9 additions & 6 deletions Sources/CLICommands/Run.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ArgumentParser
import SystemExtras
import SystemPackage
import WAT
import WasmKit
Expand Down Expand Up @@ -353,14 +354,16 @@ package struct Run: AsyncParsableCommand {
func parseWasm(filePath: FilePath) throws -> Module {
if filePath.extension == "wat", #available(macOS 11.0, iOS 14.0, macCatalyst 14.0, tvOS 14.0, visionOS 1.0, watchOS 7.0, *) {
let fileHandle = try FileDescriptor.open(filePath, .readOnly)
defer { try? fileHandle.close() }
return try withThrowing {
let size = try fileHandle.seek(offset: 0, from: .end)

let size = try fileHandle.seek(offset: 0, from: .end)

let wat = try String(unsafeUninitializedCapacity: Int(size)) {
try fileHandle.read(fromAbsoluteOffset: 0, into: .init($0))
let wat = try String(unsafeUninitializedCapacity: Int(size)) {
try fileHandle.read(fromAbsoluteOffset: 0, into: .init($0))
}
return try WasmKit.parseWasm(bytes: wat2wasm(wat))
} defer: {
try fileHandle.close()
}
return try WasmKit.parseWasm(bytes: wat2wasm(wat))
} else {
return try WasmKit.parseWasm(filePath: filePath)
}
Expand Down
69 changes: 37 additions & 32 deletions Sources/CLICommands/Wat2wasm.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ArgumentParser
import SystemExtras
import SystemPackage
import WAT

Expand Down Expand Up @@ -81,45 +82,49 @@ package struct Wat2wasm: ParsableCommand {
let filePath = FilePath(path)
guard filePath.extension == "wat" else { throw Error.unknownFileExtension(filePath.extension) }
let fileHandle = try FileDescriptor.open(filePath, .readOnly)
defer { try? fileHandle.close() }
try withThrowing {
let size = try fileHandle.seek(offset: 0, from: .end)

let size = try fileHandle.seek(offset: 0, from: .end)

let wat: String
if #available(macOS 11.0, iOS 14.0, macCatalyst 14.0, tvOS 14.0, visionOS 1.0, watchOS 7.0, *) {
wat = try String(unsafeUninitializedCapacity: Int(size)) {
try fileHandle.read(fromAbsoluteOffset: 0, into: .init($0))
}
} else {
let watBuffer = try [UInt8](unsafeUninitializedCapacity: Int(size)) { buffer, count in
count = try fileHandle.read(fromAbsoluteOffset: 0, into: .init(buffer))
let wat: String
if #available(macOS 11.0, iOS 14.0, macCatalyst 14.0, tvOS 14.0, visionOS 1.0, watchOS 7.0, *) {
wat = try String(unsafeUninitializedCapacity: Int(size)) {
try fileHandle.read(fromAbsoluteOffset: 0, into: .init($0))
}
} else {
let watBuffer = try [UInt8](unsafeUninitializedCapacity: Int(size)) { buffer, count in
count = try fileHandle.read(fromAbsoluteOffset: 0, into: .init(buffer))
}
wat = String(decoding: watBuffer, as: UTF8.self)
}
wat = String(decoding: watBuffer, as: UTF8.self)
}

let wasm = try wat2wasm(wat, options: EncodeOptions(nameSection: nameSection))
let wasm = try wat2wasm(wat, options: EncodeOptions(nameSection: nameSection))

var outputPath: FilePath
var outputPath: FilePath

if let output {
outputPath = FilePath(output)
} else {
outputPath = filePath
outputPath.extension = "wasm"
if let output {
outputPath = FilePath(output)
} else {
outputPath = filePath
outputPath.extension = "wasm"

guard (try? FileDescriptor.open(outputPath, .readOnly)) == nil else {
throw Error.fileAlreadyExists(outputPath.string)
guard (try? FileDescriptor.open(outputPath, .readOnly)) == nil else {
throw Error.fileAlreadyExists(outputPath.string)
}
}
}

let outputHandle = try FileDescriptor.open(
outputPath,
.writeOnly,
options: [.create],
permissions: [.ownerReadWrite, .groupRead, .otherRead]
)
defer { try? outputHandle.close() }

try outputHandle.writeAll(wasm)
let outputHandle = try FileDescriptor.open(
outputPath,
.writeOnly,
options: [.create],
permissions: [.ownerReadWrite, .groupRead, .otherRead]
)
try withThrowing {
try outputHandle.writeAll(wasm)
} defer: {
try outputHandle.close()
}
} defer: {
try fileHandle.close()
}
}
}
1 change: 1 addition & 0 deletions Sources/SystemExtras/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ add_wasmkit_library(SystemExtras
FileAtOperations.swift
FileOperations.swift
Syscalls.swift
ThrowingDefer.swift
)

set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS")
Expand Down
61 changes: 61 additions & 0 deletions Sources/SystemExtras/ThrowingDefer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

/// Runs a cleanup closure (`deferred`) after a given `work` closure,
/// making sure `deferred` is run also when `work` throws an error.
/// - Parameters:
/// - work: The work that should be performed. Will always be executed.
/// - deferred: The cleanup that needs to be done in any case.
/// - Throws: Any error thrown by `deferred` or `work` (in that order).
/// - Returns: The result of `work`.
/// - Note: If `work` **and** `deferred` throw an error,
/// the one thrown by `deferred` is thrown from this function.
/// - SeeAlso: ``withAsyncThrowing(do:defer:)``
@discardableResult
package func withThrowing<T>(
do work: () throws -> T,
defer deferred: () throws -> Void
) throws -> T {
do {
let result = try work()
try deferred()
return result
} catch {
try deferred()
throw error
}
}

/// Runs an async cleanup closure (`deferred`) after a given async `work` closure,
/// making sure `deferred` is run also when `work` throws an error.
/// - Parameters:
/// - work: The work that should be performed. Will always be executed.
/// - deferred: The cleanup that needs to be done in any case.
/// - Throws: Any error thrown by `deferred` or `work` (in that order).
/// - Returns: The result of `work`.
/// - Note: If `work` **and** `deferred` throw an error,
/// the one thrown by `deferred` is thrown from this function.
/// - SeeAlso: ``withThrowing(do:defer:)``
@discardableResult
package func withAsyncThrowing<T: Sendable>(
do work: @Sendable () async throws -> T,
defer deferred: @Sendable () async throws -> Void
) async throws -> T {
do {
let result = try await work()
try await deferred()
return result
} catch {
try await deferred()
throw error
}
}
16 changes: 10 additions & 6 deletions Sources/WASI/Platform/Directory.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import SystemExtras
import SystemPackage

struct DirEntry {
Expand Down Expand Up @@ -90,12 +91,15 @@ extension DirEntry: WASIDir, FdWASIEntry {
symlinkFollow: symlinkFollow, path: path,
oflags: [], accessMode: .write, fdflags: []
)
defer { try? fd.close() }
let (access, modification) = try WASIAbi.Timestamp.platformTimeSpec(
atim: atim, mtim: mtim, fstFlags: fstFlags
)
try WASIAbi.Errno.translatingPlatformErrno {
try fd.setTimes(access: access, modification: modification)
try withThrowing {
let (access, modification) = try WASIAbi.Timestamp.platformTimeSpec(
atim: atim, mtim: mtim, fstFlags: fstFlags
)
try WASIAbi.Errno.translatingPlatformErrno {
try fd.setTimes(access: access, modification: modification)
}
} defer: {
try fd.close()
}
}

Expand Down
10 changes: 7 additions & 3 deletions Sources/WasmKit/Execution/ParsedComponentBuilder.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#if ComponentModel
import ComponentModel
import SystemExtras
import SystemPackage
import WasmParser

Expand All @@ -19,9 +20,12 @@
features: WasmFeatureSet = .default
) throws -> ParsedComponent {
let fileHandle = try FileDescriptor.open(filePath, .readOnly)
defer { try? fileHandle.close() }
let stream = try FileHandleStream(fileHandle: fileHandle)
return try parseComponent(stream: stream, features: features)
return try withThrowing {
let stream = try FileHandleStream(fileHandle: fileHandle)
return try parseComponent(stream: stream, features: features)
} defer: {
try fileHandle.close()
}
}

/// Parse a component binary into a `ParsedComponent` ready for instantiation.
Expand Down
12 changes: 8 additions & 4 deletions Sources/WasmKit/ModuleParser.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import SystemExtras
import SystemPackage
import WasmParser

Expand All @@ -17,10 +18,13 @@ public func parseWasm(filePath: FilePath, features: WasmFeatureSet = .default) t
let accessMode: FileDescriptor.AccessMode = .readOnly
#endif
let fileHandle = try FileDescriptor.open(filePath, accessMode)
defer { try? fileHandle.close() }
let stream = try FileHandleStream(fileHandle: fileHandle)
let module = try parseModule(stream: stream, features: features)
return module
return try withThrowing {
let stream = try FileHandleStream(fileHandle: fileHandle)
let module = try parseModule(stream: stream, features: features)
return module
} defer: {
try fileHandle.close()
}
}

/// Parse a given byte array as a WebAssembly binary format file
Expand Down
2 changes: 1 addition & 1 deletion Sources/WasmParser/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ add_wasmkit_library(WasmParser
)

target_link_wasmkit_libraries(WasmParser PUBLIC
WasmTypes SystemPackage)
SystemExtras WasmTypes SystemPackage)
67 changes: 35 additions & 32 deletions Sources/WasmParser/WasmParser.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import SystemExtras
import WasmTypes

import struct SystemPackage.FileDescriptor
Expand Down Expand Up @@ -1284,37 +1285,39 @@ public enum WasmFileType: Equatable, Sendable {
/// - Throws: If the file cannot be opened or read
public func detectWasmFileType(filePath: FilePath) throws -> WasmFileType {
let fileHandle = try FileDescriptor.open(filePath, .readOnly)
defer { try? fileHandle.close() }

// Use a tuple to avoid heap allocation - 8 bytes on stack
// TODO: needs a `SmallArray` abstraction until `InlineArray` becomes available after dropping support for macOS 15.
var header: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0, 0, 0, 0, 0)
let bytesRead = try withUnsafeMutableBytes(of: &header) { buffer in
try fileHandle.read(into: buffer)
}

// Need at least 8 bytes for a valid header
guard bytesRead >= 8 else {
return .unknown
}

// Check magic number: \0asm (uses WASM_MAGIC as source of truth)
guard
header.0 == WASM_MAGIC[0] && header.1 == WASM_MAGIC[1]
&& header.2 == WASM_MAGIC[2] && header.3 == WASM_MAGIC[3]
else {
return .unknown
}

// Check version and layer bytes:
// - Core module: version=0x01, 0x00 and layer=0x00, 0x00
// - Component: version=0x0d, 0x00 and layer=0x01, 0x00
switch (header.4, header.5, header.6, header.7) {
case (0x01, 0x00, 0x00, 0x00):
return .coreModule
case (0x0d, 0x00, 0x01, 0x00):
return .component
default:
return .unknown
return try withThrowing {
// Use a tuple to avoid heap allocation - 8 bytes on stack
// TODO: needs a `SmallArray` abstraction until `InlineArray` becomes available after dropping support for macOS 15.
var header: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0, 0, 0, 0, 0)
let bytesRead = try withUnsafeMutableBytes(of: &header) { buffer in
try fileHandle.read(into: buffer)
}

// Need at least 8 bytes for a valid header
guard bytesRead >= 8 else {
return .unknown
}

// Check magic number: \0asm (uses WASM_MAGIC as source of truth)
guard
header.0 == WASM_MAGIC[0] && header.1 == WASM_MAGIC[1]
&& header.2 == WASM_MAGIC[2] && header.3 == WASM_MAGIC[3]
else {
return .unknown
}

// Check version and layer bytes:
// - Core module: version=0x01, 0x00 and layer=0x00, 0x00
// - Component: version=0x0d, 0x00 and layer=0x01, 0x00
switch (header.4, header.5, header.6, header.7) {
case (0x01, 0x00, 0x00, 0x00):
return .coreModule
case (0x0d, 0x00, 0x01, 0x00):
return .component
default:
return .unknown
}
} defer: {
try fileHandle.close()
}
}
Loading