Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as Sentry from '@sentry/browser';
import { wasmIntegration } from '@sentry/wasm';

window.Sentry = Sentry;

Sentry.init({
traceLifecycle: 'static',
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [wasmIntegration()],
beforeSend: event => {
window.events.push(event);
return null;
},
});
window.events = [];
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
function leb128(n) {
const out = [];
do {
let byte = n & 0x7f;
n >>>= 7;
if (n !== 0) {
byte |= 0x80;
}
out.push(byte);
} while (n !== 0);
return out;
}

// Appends a custom section with `padding` payload bytes so the module wire
// bytes cross V8's 16383-byte content-hashing cutoff.
function pad(bytes, padding) {
const payload = new Uint8Array(padding);
for (let i = 0; i < padding; i++) {
payload[i] = (i * 31 + 7) & 0xff;
}
const content = [1, 0x70, ...leb128(payload.length)];
const header = [0x00, ...leb128(2 + payload.length)];
const out = new Uint8Array(bytes.length + header.length + 2 + payload.length);
out.set(bytes, 0);
out.set(header, bytes.length);
out.set([1, 0x70], bytes.length + header.length);
out.set(payload, bytes.length + header.length + 2);
return out;
}

window.getEvent = async padding => {
function crash() {
throw new Error('whoops');
}

const response = await fetch('https://localhost:5887/simple.wasm');
const buffer = await response.arrayBuffer();
const bytes = padding ? pad(new Uint8Array(buffer), padding) : new Uint8Array(buffer);

const { instance } = await WebAssembly.instantiate(bytes, {
env: {
external_func: crash,
},
});

try {
instance.exports.internal_func();
} catch (err) {
Sentry.captureException(err);
return { event: window.events.pop(), byteLength: bytes.byteLength };
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import type { Page, Route } from '@playwright/test';
import { expect } from '@playwright/test';
import fs from 'fs';
import path from 'path';
import { sentryTest } from '../../../utils/fixtures';
import { shouldSkipWASMTests } from '../../../utils/wasmHelpers';

function serveWasmFixture(page: Page): Promise<void> {
return page.route('**/simple.wasm', (route: Route) => {
const wasmModule = fs.readFileSync(path.resolve(__dirname, '..', 'simple.wasm'));

return route.fulfill({
status: 200,
body: wasmModule,
headers: {
'Content-Type': 'application/wasm',
},
});
});
}

const IMAGE_MATCHER = {
code_file: expect.stringMatching(/^wasm:\/\/wasm\/[0-9a-f]{8}$/),
code_id: '0ba020cdd2444f7eafdd25999a8e9010',
debug_file: null,
debug_id: '0ba020cdd2444f7eafdd25999a8e90100',
type: 'wasm',
};

const FRAME_MATCHER = {
function: 'internal_func',
in_app: true,
instruction_addr: '0x8c',
addr_mode: 'rel:0',
platform: 'native',
};

sentryTest(
'exactly matches the length-derived synthetic name for modules above the content-hash cutoff',
async ({ getLocalTestUrl, page, browserName }) => {
if (shouldSkipWASMTests(browserName) || browserName === 'firefox') {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });
await serveWasmFixture(page);
await page.goto(url);

const { event, byteLength } = await page.evaluate(async () => {
// @ts-expect-error this function exists
return window.getEvent(17000);
});

// V8 does not content-hash modules above 16383 bytes; the synthetic name
// derives from the byte length alone on every V8 version.
expect(byteLength).toBeGreaterThan(16383);
const expectedUrl = `wasm://wasm/${(byteLength * 4 + 2).toString(16).padStart(8, '0')}`;

expect(event.exception.values[0].stacktrace.frames).toEqual(
expect.arrayContaining([
expect.objectContaining({
...FRAME_MATCHER,
filename: expectedUrl,
}),
]),
);

expect(event.debug_meta).toMatchObject({
images: [{ ...IMAGE_MATCHER, code_file: expectedUrl }],
});
},
);
31 changes: 21 additions & 10 deletions packages/wasm/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { DebugImage, Event, IntegrationFn, StackFrame } from '@sentry/core';
import { defineIntegration, GLOBAL_OBJ } from '@sentry/core';
import { patchWebAssembly } from './patchWebAssembly';
import type { WasmDebugImage } from './registry';
import { getImage, getImages, registerModule } from './registry';

const INTEGRATION_NAME = 'Wasm';
Expand Down Expand Up @@ -32,7 +33,7 @@ interface WasmIntegrationOptions {

// Access WINDOW with proper typing for _sentryWasmImages
const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
_sentryWasmImages?: Array<DebugImage>;
_sentryWasmImages?: Array<WasmDebugImage>;
};

const _wasmIntegration = ((options: WasmIntegrationOptions = {}) => {
Expand All @@ -59,8 +60,12 @@ const _wasmIntegration = ((options: WasmIntegrationOptions = {}) => {
if (hasAtLeastOneWasmFrameWithImage) {
event.debug_meta = event.debug_meta || {};
const mainThreadImages = getImages();
const workerImages = WINDOW._sentryWasmImages || [];
event.debug_meta.images = [...(event.debug_meta.images || []), ...mainThreadImages, ...workerImages];
const workerImages = getWorkerImages();
event.debug_meta.images = [
...(event.debug_meta.images || []),
...mainThreadImages.map(stripInternalFields),
...workerImages.map(stripInternalFields),
];
}

return event;
Expand Down Expand Up @@ -137,29 +142,35 @@ export function patchFrames(
return hasAtLeastOneWasmFrameWithImage;
}

function getWorkerImages(): Array<WasmDebugImage> {
return WINDOW._sentryWasmImages || [];
}

function stripInternalFields(image: WasmDebugImage): DebugImage {
const { _fromBuffer, ...rest } = image;
return rest;
}

/**
* Looks up an image by URL in worker images.
*/
function getWorkerImage(url: string): number {
const workerImages = WINDOW._sentryWasmImages || [];
Comment thread
andreiborza marked this conversation as resolved.
return workerImages.findIndex(image => {
return image.type === 'wasm' && image.code_file === url;
});
return getWorkerImages().findIndex(image => image.type === 'wasm' && image.code_file === url);
}

/**
* Use this function to register WASM support in a web worker.
*
* This function will:
* - Patch WebAssembly.instantiateStreaming and WebAssembly.compileStreaming in the worker
* - Patch the WebAssembly compilation APIs in the worker
* - Forward WASM debug images to the parent thread for symbolication
*
* @param options {RegisterWebWorkerWasmOptions} Options:
* - `self`: The worker's global scope (self).
*/
export function registerWebWorkerWasm({ self }: RegisterWebWorkerWasmOptions): void {
patchWebAssembly((module, url) => {
const image = registerModule(module, url);
patchWebAssembly((module, url, fromBuffer) => {
const image = registerModule(module, url, fromBuffer);

if (image) {
self.postMessage({
Expand Down
78 changes: 72 additions & 6 deletions packages/wasm/src/patchWebAssembly.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
export type RegisterModuleCallback = (module: WebAssembly.Module, url: string) => void;
import { getSyntheticUrl, toByteView } from './syntheticUrl';

export type RegisterModuleCallback = (module: WebAssembly.Module, url: string, fromBuffer?: boolean) => void;

/**
* Patches the WebAssembly streaming APIs so that every compiled module gets
* registered as a debug image under the URL of the response it was compiled
* from.
* Patches the WebAssembly APIs that compile modules so that every compiled
* module gets registered as a debug image.
*
* Streaming APIs register the module under the response URL. Non-streaming
* APIs receive raw bytes without any URL, so those modules are registered
* under the synthetic `wasm://wasm/<hash>` script name the engine uses in
* stack frames (see `syntheticUrl.ts`).
*
* @param registerModule callback invoked for every successfully compiled module
*/
Expand Down Expand Up @@ -47,11 +53,71 @@ export function patchWebAssembly(registerModule: RegisterModuleCallback): void {
});
};
}

const registerFromBuffer = (module: WebAssembly.Module, byteLength: number): void => {
registerSafely(registerModule, module, getSyntheticUrl(module, byteLength), true);
};

// Double-cast, because the overloaded native signature (buffer vs. module
// first argument) cannot be widened to a pass-through shape in one step.
const origInstantiate = WebAssembly.instantiate as unknown as (
source: unknown,
...rest: unknown[]
) => Promise<WebAssembly.WebAssemblyInstantiatedSource>;
WebAssembly.instantiate = function instantiate(source: unknown, ...rest: unknown[]): Promise<unknown> {
const bytes = toByteView(source);
// The length must be read before calling the original function, since the
// caller is free to mutate or transfer the buffer afterwards.
const byteLength = bytes?.byteLength;
const result = origInstantiate(source, ...rest);
if (byteLength !== undefined) {
// Chaining (instead of attaching a side listener) keeps rejections of
// fire-and-forget calls observable as unhandledrejection events.
return result.then(rv => {
registerFromBuffer(rv.module, byteLength);
return rv;
});
}
return result;
} as typeof WebAssembly.instantiate;

const origCompile = WebAssembly.compile as (source: unknown, ...rest: unknown[]) => Promise<WebAssembly.Module>;
WebAssembly.compile = function compile(source: unknown, ...rest: unknown[]): Promise<WebAssembly.Module> {
const bytes = toByteView(source);
const byteLength = bytes?.byteLength;
const result = origCompile(source, ...rest);
if (byteLength !== undefined) {
return result.then(module => {
registerFromBuffer(module, byteLength);
return module;
});
}
return result;
};

// `new WebAssembly.Module(bytes)` compiles synchronously. The Proxy keeps
// statics (customSections, exports, imports), prototype, and instanceof
// behavior intact.
WebAssembly.Module = new Proxy(WebAssembly.Module, {
construct(target, args: unknown[], newTarget) {
const byteLength = toByteView(args[0])?.byteLength;
const module = Reflect.construct(target, args, newTarget) as WebAssembly.Module;
if (byteLength !== undefined) {
registerFromBuffer(module, byteLength);
}
return module;
},
});
}

function registerSafely(registerModule: RegisterModuleCallback, module: WebAssembly.Module, url: string): void {
function registerSafely(
registerModule: RegisterModuleCallback,
module: WebAssembly.Module,
url: string,
fromBuffer?: boolean,
): void {
try {
registerModule(module, url);
registerModule(module, url, fromBuffer);
} catch {
// a registration failure must never break the user's WebAssembly call
}
Expand Down
46 changes: 34 additions & 12 deletions packages/wasm/src/registry.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import type { DebugImage } from '@sentry/core';

export const IMAGES: Array<DebugImage> = [];
/**
* A debug image with a marker for modules that were compiled from raw bytes.
* The engine names those modules itself, so their `code_file` is only a
* prediction and frames may have to be matched against them by elimination.
* The field crosses worker boundaries via postMessage and is stripped before
* images are attached to an event.
*/
export type WasmDebugImage = Extract<DebugImage, { type: 'wasm' }> & { _fromBuffer?: true };

export const IMAGES: Array<WasmDebugImage> = [];

export interface ModuleInfo {
buildId: string | null;
Expand Down Expand Up @@ -39,8 +48,13 @@ export function getModuleInfo(module: WebAssembly.Module): ModuleInfo {

/**
* Records a module and returns the created debug image.
*
* @param module the compiled module
* @param url the URL the module was loaded from, or the engine's synthetic
* script name for modules compiled from raw bytes
* @param fromBuffer whether the module was compiled from raw bytes
*/
export function registerModule(module: WebAssembly.Module, url: string): DebugImage | null {
export function registerModule(module: WebAssembly.Module, url: string, fromBuffer?: boolean): DebugImage | null {
const { buildId, debugFile } = getModuleInfo(module);
if (!buildId) {
return null;
Expand All @@ -53,30 +67,40 @@ export function registerModule(module: WebAssembly.Module, url: string): DebugIm

let debugFileUrl = null;
if (debugFile) {
try {
debugFileUrl = new URL(debugFile, url).href;
} catch {
// debugFile could be a blob URL which causes the URL constructor to throw
// for now we just ignore this case
if (url.startsWith('wasm://')) {
// A synthetic script name is no meaningful base to resolve against, so
// keep the raw value from the external_debug_info section.
debugFileUrl = debugFile;
} else {
try {
debugFileUrl = new URL(debugFile, url).href;
} catch {
// debugFile could be a blob URL which causes the URL constructor to throw
// for now we just ignore this case
}
}
}

const image: DebugImage = {
const image: WasmDebugImage = {
type: 'wasm',
code_id: buildId,
code_file: url,
debug_file: debugFileUrl,
debug_id: `${buildId.padEnd(32, '0').slice(0, 32)}0`,
};

if (fromBuffer) {
image._fromBuffer = true;
}

IMAGES.push(image);
return image;
}

/**
* Returns all known images.
*/
export function getImages(): Array<DebugImage> {
export function getImages(): Array<WasmDebugImage> {
return IMAGES;
}

Expand All @@ -86,7 +110,5 @@ export function getImages(): Array<DebugImage> {
* @param url the URL of the WebAssembly module.
*/
export function getImage(url: string): number {
return IMAGES.findIndex(image => {
return image.type === 'wasm' && image.code_file === url;
});
return IMAGES.findIndex(image => image.type === 'wasm' && image.code_file === url);
}
Loading
Loading