From 620386be4eccdc7f38a4bd58875be9329b22ebd2 Mon Sep 17 00:00:00 2001 From: Larry Ewing Date: Fri, 12 Apr 2024 19:46:33 -0500 Subject: [PATCH] Fix js string marshaling --- src/mono/browser/browser.proj | 1 + src/mono/browser/runtime/strings.ts | 15 ++++++++------- src/mono/browser/runtime/types/emscripten.ts | 1 + 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/mono/browser/browser.proj b/src/mono/browser/browser.proj index f7429193002a6..63eb3f9883f44 100644 --- a/src/mono/browser/browser.proj +++ b/src/mono/browser/browser.proj @@ -185,6 +185,7 @@ + diff --git a/src/mono/browser/runtime/strings.ts b/src/mono/browser/runtime/strings.ts index a596b4e35ef5a..0eda60ba850a0 100644 --- a/src/mono/browser/runtime/strings.ts +++ b/src/mono/browser/runtime/strings.ts @@ -39,19 +39,20 @@ export function strings_init (): void { export function stringToUTF8 (str: string): Uint8Array { if (_text_encoder_utf8 === undefined) { - const buffer = new Uint8Array(str.length * 2); - Module.stringToUTF8Array(str, buffer, 0, str.length * 2); + const len = Module.lengthBytesUTF8(str); + const buffer = new Uint8Array(len); + Module.stringToUTF8Array(str, buffer, 0, len); return buffer; } return _text_encoder_utf8.encode(str); } export function stringToUTF8Ptr (str: string): CharPtr { - const bytes = (str.length + 1) * 2; - const ptr = Module._malloc(bytes) as any; - _zero_region(ptr, str.length * 2); - const buffer = localHeapViewU8().subarray(ptr, ptr + bytes); - buffer.set(stringToUTF8(str)); + const size = Module.lengthBytesUTF8(str) + 1; + const ptr = Module._malloc(size) as any; + const buffer = localHeapViewU8().subarray(ptr, ptr + size); + Module.stringToUTF8Array(str, buffer, 0, size); + buffer[size - 1] = 0; return ptr; } diff --git a/src/mono/browser/runtime/types/emscripten.ts b/src/mono/browser/runtime/types/emscripten.ts index e2cc8e7c73ce6..bb630df0b32e8 100644 --- a/src/mono/browser/runtime/types/emscripten.ts +++ b/src/mono/browser/runtime/types/emscripten.ts @@ -40,6 +40,7 @@ export declare interface EmscriptenModule { UTF8ToString(ptr: CharPtr, maxBytesToRead?: number): string; UTF8ArrayToString(u8Array: Uint8Array, idx?: number, maxBytesToRead?: number): string; stringToUTF8Array(str: string, heap: Uint8Array, outIdx: number, maxBytesToWrite: number): void; + lengthBytesUTF8(str: string): number; FS_createPath(parent: string, path: string, canRead?: boolean, canWrite?: boolean): string; FS_createDataFile(parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; addFunction(fn: Function, signature: string): number;