Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Windows app launch (#124): bytes become a string a 32 KB slice at a time, not String.fromCharCode(...bytes), which passed every byte as an argument and overflowed the stack on a blob of a few hundred KB (FileReader's readAsDataURL and readAsBinaryString, fetch's request body, a WebSocket's binary send, and the node shim's Buffer toString latin1); @raea/ui's platform has one latin1() for all of them, with a test of a 4 MB buffer. A frame's root-absolute script (/artifact.js) is found under the page's roots on Windows too: against a page at file:///C:/... it is C:\artifact.js, which only a leading / was taken for

shinyobjectze05cee0c73c8
diff --git a/engine/native/src/node.js b/engine/native/src/node.js
index 4e48d243..840ffe71 100644
--- a/engine/native/src/node.js
+++ b/engine/native/src/node.js
@@ -76,7 +76,12 @@
if (encoding === "base64") return toB64(u);
if (encoding === "base64url") return toB64(u).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
if (encoding === "hex") return Array.from(u, (b) => b.toString(16).padStart(2, "0")).join("");
- if (encoding === "latin1" || encoding === "binary") return String.fromCharCode(...u);
+ if (encoding === "latin1" || encoding === "binary") {
+ // a slice at a time: a spread of a whole buffer passes each byte as an argument and overflows the stack (#124)
+ let s = "";
+ for (let i = 0; i < u.length; i += 0x8000) s += String.fromCharCode.apply(null, u.subarray(i, i + 0x8000));
+ return s;
+ }
return dec.decode(u);
}
toJSON() { return { type: "Buffer", data: Array.from(this) }; }
diff --git a/sdk/ui/src/platform/audio.ts b/sdk/ui/src/platform/audio.ts
index 371aff44..918b8919 100644
--- a/sdk/ui/src/platform/audio.ts
+++ b/sdk/ui/src/platform/audio.ts
@@ -1,6 +1,6 @@
// Web Audio (AudioBuffer, OfflineAudioContext.decodeAudioData) and WebSocket (the host's sockets).
import { call, on } from "../wire";
-import { B64, Blob_, DOMEx, DOMException_, EventTarget_, TOKEN, URL_, b64bytes, baseHref, btoa_, bytesOf, event, g, named, put, tag, utf8 } from "./all";
+import { B64, Blob_, DOMEx, DOMException_, EventTarget_, TOKEN, URL_, b64bytes, baseHref, btoa_, bytesOf, event, g, latin1, named, put, tag, utf8 } from "./all";
// ---------------------------------------------------------------- Web Audio: AudioBuffer, OfflineAudioContext.decodeAudioData
// The part of Web Audio a page reads a file's sound through (a waveform's peaks): decodeAudioData, decoded by the host
@@ -26,11 +26,7 @@ const b64decode = (s: string) => {
return out;
};
-const b64encode = (x: Uint8Array) => {
- let s = "";
- for (let i = 0; i < x.length; i += 0x8000) s += String.fromCharCode.apply(null, x.subarray(i, i + 0x8000) as unknown as number[]);
- return btoa_(s);
-};
+const b64encode = (x: Uint8Array) => btoa_(latin1(x));
class AudioBuffer_ {
readonly sampleRate: number;
@@ -195,7 +191,7 @@ class WebSocket_ extends EventTarget_ {
if (typeof data === "string") call("net.ws.send", { id: this._id, data }).catch(() => {});
else {
const b = data instanceof Blob_ ? data._b : bytesOf(data);
- call("net.ws.send", { id: this._id, data: btoa_(String.fromCharCode(...b)), binary: true }).catch(() => {});
+ call("net.ws.send", { id: this._id, data: b64encode(b), binary: true }).catch(() => {});
}
}
close(code?: number, reason = "") {
diff --git a/sdk/ui/src/platform/blob.ts b/sdk/ui/src/platform/blob.ts
index b8da62c3..5865acfb 100644
--- a/sdk/ui/src/platform/blob.ts
+++ b/sdk/ui/src/platform/blob.ts
@@ -1,5 +1,5 @@
// crypto (not cryptographic), performance, Blob, File, FileReader, FormData and ReadableStream.
-import { DOMEx, EventTarget_, TextDecoder_, at, btoa_, bytesOf, entries, event, fromUtf8, g, named, put, tag, utf8 } from "./all";
+import { DOMEx, EventTarget_, TextDecoder_, at, btoa_, bytesOf, entries, event, fromUtf8, g, latin1, named, put, tag, utf8 } from "./all";
// ---------------------------------------------------------------- crypto (not cryptographic: no secure source here)
@@ -164,10 +164,10 @@ class FileReader_ extends EventTarget_ {
this._read(b, (x) => x.slice().buffer);
}
readAsBinaryString(b: Blob_) {
- this._read(b, (x) => String.fromCharCode(...x));
+ this._read(b, (x) => latin1(x));
}
readAsDataURL(b: Blob_) {
- this._read(b, (x) => `data:${b.type || "application/octet-stream"};base64,${btoa_(String.fromCharCode(...x))}`);
+ this._read(b, (x) => `data:${b.type || "application/octet-stream"};base64,${btoa_(latin1(x))}`);
}
abort() {
if (this.readyState !== 1) return;
diff --git a/sdk/ui/src/platform/fetch.ts b/sdk/ui/src/platform/fetch.ts
index a52e324b..00e1d203 100644
--- a/sdk/ui/src/platform/fetch.ts
+++ b/sdk/ui/src/platform/fetch.ts
@@ -1,6 +1,6 @@
// Headers, Request, Response and fetch.
import { call } from "../wire";
-import { AbortSignal_, Blob_, File_, FormData_, URLSearchParams_, URL_, b64bytes, blobs, btoa_, bytesOf, fromUtf8, g, named, put, streamOf, tag, utf8, uuid } from "./all";
+import { AbortSignal_, Blob_, File_, FormData_, URLSearchParams_, URL_, b64bytes, blobs, btoa_, bytesOf, fromUtf8, g, latin1, named, put, streamOf, tag, utf8, uuid } from "./all";
// ---------------------------------------------------------------- Headers, Request, Response, fetch
@@ -328,7 +328,7 @@ function fetch_(input: unknown, init?: any): Promise<Response_> {
}
if (u.protocol !== "http:" && u.protocol !== "https:") return Promise.reject(new TypeError("Failed to fetch"));
const headers: [string, string][] = [...req.headers];
- const body = req._body ? btoa_(String.fromCharCode(...req._body)) : null;
+ const body = req._body ? btoa_(latin1(req._body)) : null;
return abortable(
call<{ status: number; statusText?: string; headers: [string, string][]; body: string; url: string; redirected?: boolean }>("net.fetch", { url: req.url, method: req.method, headers, body, redirect: req.redirect }).then(
(a) => {
diff --git a/sdk/ui/src/platform/text.ts b/sdk/ui/src/platform/text.ts
index 1b70b7d2..614d6fa9 100644
--- a/sdk/ui/src/platform/text.ts
+++ b/sdk/ui/src/platform/text.ts
@@ -157,6 +157,14 @@ put("TextDecoder", named(TextDecoder_, "TextDecoder"));
export const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+/** Bytes as a binary string, one char per byte, 0x8000 bytes at a time: `String.fromCharCode(...bytes)` passes each
+ * byte as an argument, which overflows the stack on a blob of a few hundred KB (#124, Windows). */
+export function latin1(b: Uint8Array): string {
+ let s = "";
+ for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode.apply(null, b.subarray(i, i + 0x8000) as unknown as number[]);
+ return s;
+}
+
export function btoa_(s: string) {
s = String(s);
let out = "";
diff --git a/sdk/ui/test/platform-bytes.test.ts b/sdk/ui/test/platform-bytes.test.ts
new file mode 100644
index 00000000..47848598
--- /dev/null
+++ b/sdk/ui/test/platform-bytes.test.ts
@@ -0,0 +1,24 @@
+// #124: bytes become a binary string a slice at a time, so a blob of a few MB doesn't overflow the stack the way
+// `String.fromCharCode(...bytes)` does (it passes every byte as an argument; the Windows app crashed at launch).
+import { expect, test } from "bun:test";
+import { btoa_, latin1 } from "../src/platform/all";
+
+const bytes = (n: number) => {
+ const b = new Uint8Array(n);
+ for (let i = 0; i < n; i++) b[i] = (i * 31 + (i >> 9)) & 255;
+ return b;
+};
+
+test("a 4 MB buffer is one char per byte, where the spread overflows", () => {
+ const b = bytes(4 << 20);
+ expect(() => String.fromCharCode(...b)).toThrow(RangeError);
+ const s = latin1(b);
+ expect(s.length).toBe(b.length);
+ for (const i of [0, 1, 0x7fff, 0x8000, 0x8001, b.length - 1]) expect(s.charCodeAt(i)).toBe(b[i]);
+});
+
+test("its base64 is the bytes' base64, across a slice boundary", () => {
+ const b = bytes(0x8000 + 5);
+ expect(btoa_(latin1(b))).toBe(Buffer.from(b).toString("base64"));
+ expect(latin1(new Uint8Array(0))).toBe("");
+});
diff --git a/systems/page-net/src/lib.rs b/systems/page-net/src/lib.rs
index 4a9f24aa..dede0c86 100644
--- a/systems/page-net/src/lib.rs
+++ b/systems/page-net/src/lib.rs
@@ -37,6 +37,19 @@ mod tests {
assert_eq!(p, std::path::PathBuf::from("/media/a b.jpg"));
assert_eq!(p.strip_prefix("/").unwrap(), std::path::Path::new("media/a b.jpg"));
}
+
+ /// "/artifact.js" from a page's file URL is the same file under a root on every OS: on Windows the URL keeps its
+ /// drive, so the path is C:\artifact.js, which a leading "/" alone didn't take for root-absolute (#124)
+ #[test]
+ fn a_root_absolute_path_is_relative_after_its_root() {
+ use std::path::Path;
+ assert_eq!(super::root_relative(Path::new("/artifact.js")).unwrap(), Path::new("artifact.js"));
+ assert_eq!(super::root_relative(Path::new("/media/a.jpg")).unwrap(), Path::new("media/a.jpg"));
+ assert_eq!(super::root_relative(Path::new("media/a.jpg")), None);
+ let page = url::Url::parse(if cfg!(windows) { "file:///C:/app/feed/page/index.html" } else { "file:///app/feed/page/index.html" }).unwrap();
+ let script = page.join("/artifact.js").unwrap().to_file_path().unwrap();
+ assert_eq!(super::root_relative(&script).unwrap(), Path::new("artifact.js"));
+ }
}
/// RAEA_PAGE_ROOT's roots, a list as PATH is (an app's Blitz build, then its public/)
@@ -50,8 +63,8 @@ impl NetProvider for FileNet {
let bytes = match url.scheme() {
"file" => file_path(&url).and_then(|p| {
std::fs::read(&p).ok().or_else(|| {
- let rel = p.strip_prefix("/").ok()?;
- self.roots.iter().find_map(|r| std::fs::read(r.join(rel)).ok())
+ let rel = root_relative(&p)?;
+ self.roots.iter().find_map(|r| std::fs::read(r.join(&rel)).ok())
})
}),
"data" => raea_io_net::data_url(url.as_str()).map(|(_, b)| b),
@@ -95,11 +108,18 @@ impl FrameNet {
pub fn confined(&self, path: &std::path::Path) -> Option<std::path::PathBuf> {
self.roots.iter().filter_map(|r| r.canonicalize().ok()).find_map(|root| {
let at = |p: std::path::PathBuf| p.canonicalize().ok().filter(|c| c.starts_with(&root));
- at(path.to_path_buf()).or_else(|| at(root.join(path.strip_prefix("/").ok()?)))
+ at(path.to_path_buf()).or_else(|| at(root.join(root_relative(path)?)))
})
}
}
+/// A root-absolute path's part after its root: "/artifact.js" is "artifact.js", and so is Windows' "C:\artifact.js",
+/// which is what "/artifact.js" against a page at file:///C:/... comes to (a leading "/" alone missed it there, #124)
+fn root_relative(path: &std::path::Path) -> Option<std::path::PathBuf> {
+ use std::path::Component::{Prefix, RootDir};
+ path.has_root().then(|| path.components().skip_while(|c| matches!(c, Prefix(_) | RootDir)).collect())
+}
+
impl NetProvider for FrameNet {
fn fetch(&self, doc_id: usize, request: Request, handler: Box<dyn NetHandler>) {
if request.url.scheme() != "file" {