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,108 @@
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(
'captured exception should include modified frames and debug_meta for non-streaming instantiation',
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 } = await page.evaluate(async () => {
// @ts-expect-error this function exists
return window.getEvent();
});

expect(event.exception.values[0].stacktrace.frames).toEqual(
expect.arrayContaining([
expect.objectContaining({
...FRAME_MATCHER,
filename: expect.stringMatching(/^wasm:\/\/wasm\/[0-9a-f]{8}$/),
}),
]),
);

expect(event.debug_meta).toMatchObject({ images: [IMAGE_MATCHER] });

// On V8 the small-module (content-hashed) synthetic name must match
// exactly, frames and image alike.
const wasmFrame = event.exception.values[0].stacktrace.frames.find(
(frame: { platform?: string }) => frame.platform === 'native',
);
expect(event.debug_meta.images[0].code_file).toBe(wasmFrame.filename);
},
);

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 }],
});
},
);
33 changes: 22 additions & 11 deletions packages/wasm/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { DebugImage, Event, IntegrationFn, StackFrame } from '@sentry/core';
import { defineIntegration, GLOBAL_OBJ } from '@sentry/core';
import { patchWebAssembly } from './patchWebAssembly';
import { getImage, getImages, registerModule } from './registry';
import type { WasmDebugImage } from './registry';
import { getImage, getImages, imageMatchesUrl, 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(stripMatchUrls),
...workerImages.map(stripMatchUrls),
];
}

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

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

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

/**
* Looks up an image by URL in worker images.
*/
function getWorkerImage(url: string): number {
const workerImages = WINDOW._sentryWasmImages || [];
return workerImages.findIndex(image => {
return image.type === 'wasm' && image.code_file === url;
});
return getWorkerImages().findIndex(image => imageMatchesUrl(image, 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, matchUrls) => {
const image = registerModule(module, url, matchUrls);

if (image) {
self.postMessage({
Expand Down
83 changes: 77 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 { getHashCandidates, getSyntheticUrls, toByteView } from './syntheticUrl';

export type RegisterModuleCallback = (module: WebAssembly.Module, url: string, matchUrls?: string[]) => 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,76 @@ export function patchWebAssembly(registerModule: RegisterModuleCallback): void {
});
};
}

const registerFromBuffer = (module: WebAssembly.Module, hashCandidates: string[]): void => {
const urls = getSyntheticUrls(module, hashCandidates);
const url = urls[0];
if (url) {
registerSafely(registerModule, module, url, urls);
}
};

// 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);
// Hash candidates must be captured before calling the original function,
// since the caller is free to mutate or transfer the buffer afterwards.
const hashCandidates = bytes && getHashCandidates(bytes);
const result = origInstantiate(source, ...rest);
if (hashCandidates) {
// 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, hashCandidates);
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 hashCandidates = bytes && getHashCandidates(bytes);
const result = origCompile(source, ...rest);
if (hashCandidates) {
return result.then(module => {
registerFromBuffer(module, hashCandidates);
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 bytes = toByteView(args[0]);
const hashCandidates = bytes && getHashCandidates(bytes);
const module = Reflect.construct(target, args, newTarget) as WebAssembly.Module;
if (hashCandidates) {
registerFromBuffer(module, hashCandidates);
}
return module;
},
});
}

function registerSafely(registerModule: RegisterModuleCallback, module: WebAssembly.Module, url: string): void {
function registerSafely(
registerModule: RegisterModuleCallback,
module: WebAssembly.Module,
url: string,
matchUrls?: string[],
): void {
try {
registerModule(module, url);
registerModule(module, url, matchUrls);
} catch {
// a registration failure must never break the user's WebAssembly call
}
Expand Down
Loading
Loading