Skip to content

WasmParser: Fix offset calculation for ExpressionParser #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 14, 2024
Merged
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
18 changes: 15 additions & 3 deletions Sources/WasmParser/WasmParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,19 @@ extension Code {
// TODO: Move `doParseInstruction` under `ExpressionParser` struct
@_documentation(visibility: internal)
public struct ExpressionParser {
/// The byte offset of the code in the module
let codeOffset: Int
/// The initial byte offset of the code buffer stream
/// NOTE: This might be different from `codeOffset` if the code buffer
/// is not a part of the initial `FileHandleStream` buffer
let initialStreamOffset: Int
@usableFromInline
let parser: Parser<StaticByteStream>
@usableFromInline
var lastCode: InstructionCode?

public var offset: Int {
self.parser.currentIndex
self.codeOffset + self.parser.currentIndex - self.initialStreamOffset
}

public init(code: Code) {
Expand All @@ -144,6 +150,8 @@ public struct ExpressionParser {
features: code.features,
hasDataCount: code.hasDataCount
)
self.codeOffset = code.offset
self.initialStreamOffset = self.parser.currentIndex
}

@inlinable
Expand Down Expand Up @@ -1055,10 +1063,14 @@ extension Parser {
let locals = localTypes.flatMap { (n: UInt32, type: ValueType) in
return Array(repeating: type, count: Int(n))
}
let expressionStart = stream.currentIndex
let expressionBytes = try stream.consume(
count: Int(size) - (stream.currentIndex - bodyStart)
count: Int(size) - (expressionStart - bodyStart)
)
return Code(
locals: locals, expression: expressionBytes,
offset: expressionStart, hasDataCount: hasDataCount, features: features
)
return Code(locals: locals, expression: expressionBytes, hasDataCount: hasDataCount, features: features)
}
}

Expand Down
2 changes: 2 additions & 0 deletions Sources/WasmParser/WasmTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ public struct Code {

// Parser state used to parse the expression body lazily
@usableFromInline
internal let offset: Int
@usableFromInline
internal let hasDataCount: Bool
@usableFromInline
internal let features: WasmFeatureSet
Expand Down