Преглед изворни кода

browser: fix google.com's script errors and click navigation

- dataset: a missing data-* attribute is no longer a property.  The has
  hook answered undefined for every name, so `"x" in el.dataset` was
  always true; google.com's document click handler looks for the nearest
  element with `"cthref" in dataset` and navigated every click to
  https://www.google.com/null.
- performance: page-relative now(), timeOrigin, timing.navigationStart,
  User Timing (mark/measure/clearMarks/clearMeasures, getEntries*()) and
  an inert PerformanceObserver; google.com's scripts threw "not a
  function" on mark() and getEntriesByType().
- CSS.escape and CSS.supports (answering like @supports).
- Promise rejections are reported at the microtask checkpoint, only if
  still unhandled: Promise.reject(e).then(f).catch(g) printed
  "Uncaught (in promise)".
- The status bar shows "Link" only for elements with an href, not for
  script-clickable wrappers around a search field.
Johannes Zellner пре 2 дана
родитељ
комит
dd31c1cb3c

+ 11 - 3
AGENTS.md

@@ -1817,7 +1817,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `getAttribute`/`setAttribute`/`hasAttribute`, `appendChild`/
   `insertBefore`/`removeChild`/`replaceChild`/`cloneNode`/`remove`,
   `querySelector(All)`/`getElementsByTagName`/`getElementsByClassName`,
-  `classList` (including `toggle`'s force argument), `dataset`, inline
+  `classList` (including `toggle`'s force argument), `dataset` (`in` is
+  true only for an existing `data-*` attribute), inline
   `style` (`cssText`, property get/set and `getPropertyValue`/
   `setProperty`/`removeProperty`), `innerHTML` (fragment parser in
   `browser_html.c`), `textContent`/`nodeValue`, child/sibling/parent
@@ -1865,7 +1866,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   script runs.  The 20 s budget restarts after every blocking fetch, so it
   measures script time, not the network.  Unhandled promise rejections are
   reported (`JS_SetHostPromiseRejectionTracker`), as Vite apps boot from an
-  async IIFE.  `js_prelude.js` (embedded by `js_prelude.S`, run once per
+  async IIFE; like a browser, a rejection is held until the end of the job
+  run (the microtask checkpoint, `mu_do_jobs`) and reported only if no
+  handler was attached by then (`Promise.reject(e).then(f).catch(g)` used
+  to print "Uncaught").  `js_prelude.js` (embedded by `js_prelude.S`, run once per
   state before the page's scripts) implements the Web APIs in JavaScript on
   three C primitives (`__nb_http`, `__nb_storage`, `__nb_resolve`):
   `fetch`/`Request`/`Response`/`Headers`, `XMLHttpRequest`, `URL`/
@@ -1876,7 +1880,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (PKCE; `queueMicrotask` uses the engine's Promise captured at startup,
   because core-js swaps in a Promise polyfill that schedules through
   `queueMicrotask`, and `PromiseRejectionEvent` exists so it keeps the
-  native one), `NodeFilter` and `document.createNodeIterator` (a document-
+  native one), `performance` with a page-relative `now()`, `timeOrigin`,
+  `timing.navigationStart`, User Timing (`mark`/`measure`/`clearMarks`/
+  `clearMeasures`, `getEntries*()`; no resource or navigation entries) and
+  an inert `PerformanceObserver`, the `CSS` namespace (`CSS.escape`, and
+  `CSS.supports` answering like the cascade's `@supports`), `NodeFilter` and `document.createNodeIterator` (a document-
   order snapshot that skips nodes removed meanwhile; DOMPurify), real
   accessors on the shared node prototype for `nodeName`/`nodeType`/
   `parentNode`/`nextSibling`/`childNodes`/`attributes` and the

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
docs/userland.html


+ 4 - 3
user/apps/browser/browser.c

@@ -12747,9 +12747,10 @@ static void draw_status(struct ngui_rect r)
 	ngui_fill_rect(&ui, r, ui.theme.panel);
 	ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
 		       ui.theme.border);
-	/* A form control under the pointer is not a link. */
-	if (hover && !br_href(&doc, (unsigned int)hover) &&
-	    form_is_control((unsigned int)hover))
+	/* Only a real link target is shown: a form control, or an element
+	 * that is merely clickable through a script listener (google.com's
+	 * jsaction wrapper around its search field), is not a link. */
+	if (hover && !br_href(&doc, (unsigned int)hover))
 		hover = 0;
 	if (hover) {
 		const char *href = br_href(&doc, (unsigned int)hover);

+ 7 - 4
user/apps/browser/js_browser.c

@@ -1281,10 +1281,13 @@ static int dataset_has(js_State *state, void *p, const char *name)
 		return 0;
 	data_name(name, attr, sizeof(attr));
 	value = br_find_attr(D, node, attr);
-	if (value)
-		js_pushstring(state, value);
-	else
-		js_pushundefined(state);
+	/* A missing data-* attribute is not a property: answering with
+	 * undefined made `"x" in el.dataset` true for every name, and
+	 * google.com's click handler, which looks for the nearest element
+	 * with `"cthref" in dataset`, navigated every click to "null". */
+	if (!value)
+		return 0;
+	js_pushstring(state, value);
 	return 1;
 }
 

+ 61 - 5
user/apps/browser/js_mu.c

@@ -23,6 +23,7 @@ static unsigned int u_ticks_ms(void)
 #include "js_mu.h"
 
 #define MU_TRIES      64
+#define MU_REJ_MAX    32       /* unhandled rejections held per job run */
 #define MU_STACK_INIT 256
 /* QuickJS recurses on the C stack for every JavaScript call, and the ring-3
  * stack is only 128 KB (USER_STACK_PAGES).  Outermost entries into the
@@ -87,6 +88,10 @@ struct js_State {
 	void *jsstack;          /* private engine stack (MU_OWN_STACK) */
 	js_ModuleResolve mod_resolve;
 	js_ModuleLoad mod_load;
+	/* Rejections with no handler yet; reported at the end of the job
+	 * run if still unhandled (see mu_rejection). */
+	JSValue rej_promise[MU_REJ_MAX], rej_reason[MU_REJ_MAX];
+	int nrej;
 };
 
 struct mu_ud {
@@ -691,16 +696,14 @@ static int mu_interrupt(JSRuntime *rt, void *opaque)
  * trace.  The error goes to the report hook, like an uncaught exception.
  * A handler attached later in the same job cannot be detected here, so a
  * rejection that is handled late is still reported once. */
-static void mu_rejection(JSContext *ctx, JSValueConst promise,
-			 JSValueConst reason, int is_handled, void *opaque)
+static void mu_report_rejection(js_State *J, JSValueConst reason)
 {
-	js_State *J = (js_State *)opaque;
+	JSContext *ctx = J->ctx;
 	const char *msg, *stack = 0;
 	JSValue st = JS_UNDEFINED;
 	char buf[768];
 
-	(void)promise;
-	if (is_handled || !J->report)
+	if (!J->report)
 		return;
 	msg = JS_ToCString(ctx, reason);
 	if (JS_IsObject(reason)) {
@@ -720,6 +723,53 @@ static void mu_rejection(JSContext *ctx, JSValueConst promise,
 		JS_FreeValue(ctx, JS_GetException(ctx));
 }
 
+/* QuickJS calls this when a promise is rejected with no handler, and again
+ * (is_handled) once one is attached.  `Promise.reject(e).then(f).catch(g)`
+ * -- google's gbar does exactly that -- rejects before the handlers exist,
+ * so reporting at once printed "Uncaught (in promise)" for errors that
+ * were caught.  Like a browser, keep the rejection until the microtask
+ * checkpoint (the end of mu_do_jobs) and report it only if no handler
+ * turned up by then. */
+static void mu_rejection(JSContext *ctx, JSValueConst promise,
+			 JSValueConst reason, int is_handled, void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	int i;
+
+	if (is_handled) {
+		for (i = 0; i < J->nrej; i++) {
+			if (JS_VALUE_GET_PTR(J->rej_promise[i]) !=
+			    JS_VALUE_GET_PTR(promise))
+				continue;
+			JS_FreeValue(ctx, J->rej_promise[i]);
+			JS_FreeValue(ctx, J->rej_reason[i]);
+			J->nrej--;
+			J->rej_promise[i] = J->rej_promise[J->nrej];
+			J->rej_reason[i] = J->rej_reason[J->nrej];
+			break;
+		}
+		return;
+	}
+	if (J->nrej >= MU_REJ_MAX) {
+		mu_report_rejection(J, reason);
+		return;
+	}
+	J->rej_promise[J->nrej] = JS_DupValue(ctx, promise);
+	J->rej_reason[J->nrej] = JS_DupValue(ctx, reason);
+	J->nrej++;
+}
+
+static void mu_flush_rejections(js_State *J)
+{
+	while (J->nrej > 0) {
+		int i = --J->nrej;
+
+		mu_report_rejection(J, J->rej_reason[i]);
+		JS_FreeValue(J->ctx, J->rej_promise[i]);
+		JS_FreeValue(J->ctx, J->rej_reason[i]);
+	}
+}
+
 js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
 {
 	js_State *J;
@@ -765,6 +815,11 @@ void js_freestate(js_State *J)
 		return;
 	J->bot = 0;
 	mu_popto(J, 0);
+	while (J->nrej > 0) {
+		J->nrej--;
+		JS_FreeValue(J->ctx, J->rej_promise[J->nrej]);
+		JS_FreeValue(J->ctx, J->rej_reason[J->nrej]);
+	}
 	JS_FreeValue(J->ctx, J->registry);
 	JS_FreeContext(J->ctx);
 	JS_FreeRuntime(J->rt);
@@ -873,6 +928,7 @@ static void mu_do_jobs(struct mu_entry *e)
 			js_pop(J, 1);
 		}
 	}
+	mu_flush_rejections(J);
 }
 
 void js_runjobs(js_State *J)

+ 135 - 0
user/apps/browser/js_prelude.js

@@ -1509,6 +1509,141 @@ nav.clipboard = {
 };
 nav.sendBeacon = function () { return true; };
 
+/* ---- performance: a page-relative clock, User Timing, no resources ----
+ * The C side's now() counts from boot; pages expect milliseconds since the
+ * navigation (google.com adds it to timing.navigationStart).  mark()/
+ * measure() keep a small timeline that getEntries*() search; resource and
+ * navigation entries are never recorded, so those lists are empty.
+ * google.com's results script calls performance.mark/measure/clearMarks
+ * around every render and getEntriesByType("resource") in its CSI ping;
+ * both threw "not a function" before. */
+(function () {
+	var perf = g.performance, rawNow = perf.now, base = rawNow.call(perf);
+	var origin = Date.now(), timeline = [];
+
+	function now() { return rawNow.call(perf) - base; }
+	function at(v) {
+		if (typeof v === "number") return v;
+		if (typeof v === "string") {
+			for (var i = timeline.length - 1; i >= 0; i--)
+				if (timeline[i].entryType === "mark" &&
+				    timeline[i].name === v)
+					return timeline[i].startTime;
+			throw new SyntaxError("The mark '" + v + "' does not exist.");
+		}
+		return undefined;
+	}
+	function entry(name, type, start, duration, detail) {
+		var e = { name: String(name), entryType: type, startTime: start,
+			  duration: duration, detail: detail === undefined ?
+			  null : detail };
+		e.toJSON = function () { return Object.assign({}, this); };
+		timeline.push(e);
+		if (timeline.length > 1000) timeline.shift();
+		return e;
+	}
+	function clear(type, name) {
+		timeline = timeline.filter(function (e) {
+			return e.entryType !== type ||
+			       (name !== undefined && e.name !== name);
+		});
+	}
+	perf.now = now;
+	perf.timeOrigin = origin;
+	perf.timing = {
+		navigationStart: origin, fetchStart: origin,
+		requestStart: origin, responseStart: origin,
+		responseEnd: origin, domLoading: origin,
+		domInteractive: origin, domContentLoadedEventStart: origin,
+		domContentLoadedEventEnd: origin, domComplete: origin,
+		loadEventStart: origin, loadEventEnd: origin,
+		toJSON: function () { return Object.assign({}, this); }
+	};
+	perf.navigation = { type: 0, redirectCount: 0 };
+	perf.mark = function (name, opts) {
+		opts = opts || {};
+		return entry(name, "mark", opts.startTime !== undefined ?
+			     opts.startTime : now(), 0, opts.detail);
+	};
+	perf.measure = function (name, start, end) {
+		var s = 0, e = now(), detail;
+
+		if (start && typeof start === "object") {
+			detail = start.detail;
+			if (start.start !== undefined) s = at(start.start);
+			if (start.end !== undefined) e = at(start.end);
+			if (start.duration !== undefined) {
+				if (start.start !== undefined) e = s + start.duration;
+				else s = e - start.duration;
+			}
+		} else {
+			if (start !== undefined) s = at(start);
+			if (end !== undefined) e = at(end);
+		}
+		return entry(name, "measure", s, e - s, detail);
+	};
+	perf.clearMarks = function (name) { clear("mark", name); };
+	perf.clearMeasures = function (name) { clear("measure", name); };
+	perf.clearResourceTimings = function () {};
+	perf.setResourceTimingBufferSize = function () {};
+	perf.getEntries = function () { return timeline.slice(); };
+	perf.getEntriesByType = function (type) {
+		return timeline.filter(function (e) { return e.entryType === type; });
+	};
+	perf.getEntriesByName = function (name, type) {
+		return timeline.filter(function (e) {
+			return e.name === name &&
+			       (type === undefined || e.entryType === type);
+		});
+	};
+	perf.toJSON = function () {
+		return { timeOrigin: origin, timing: perf.timing.toJSON() };
+	};
+})();
+class PerformanceObserver {
+	constructor(cb) { this._cb = cb; }
+	observe() {}
+	disconnect() {}
+	takeRecords() { return []; }
+}
+PerformanceObserver.supportedEntryTypes = [];
+def("PerformanceObserver", PerformanceObserver);
+
+/* ---- CSS namespace ----
+ * escape() is the CSSOM serialization of an identifier; supports() gives
+ * the cascade's own @supports answer (true unless it asks for selector()),
+ * so scripts and stylesheets agree. */
+def("CSS", {
+	escape: function (value) {
+		var s = String(value), out = "", i, c, first = s.charCodeAt(0);
+
+		if (s.length === 1 && first === 0x2D) return "\\-";
+		for (i = 0; i < s.length; i++) {
+			c = s.charCodeAt(i);
+			if (c === 0) out += "�";
+			else if ((c >= 0x01 && c <= 0x1F) || c === 0x7F ||
+				 (i === 0 && c >= 0x30 && c <= 0x39) ||
+				 (i === 1 && c >= 0x30 && c <= 0x39 &&
+				  first === 0x2D))
+				out += "\\" + c.toString(16) + " ";
+			else if (c >= 0x80 || c === 0x2D || c === 0x5F ||
+				 (c >= 0x30 && c <= 0x39) ||
+				 (c >= 0x41 && c <= 0x5A) ||
+				 (c >= 0x61 && c <= 0x7A))
+				out += s.charAt(i);
+			else
+				out += "\\" + s.charAt(i);
+		}
+		return out;
+	},
+	supports: function (prop, value) {
+		var q = arguments.length > 1 ? String(prop) + ":" + String(value) :
+			String(prop);
+
+		return !/selector\s*\(/i.test(q) && !/^\s*not\s/i.test(q);
+	}
+});
+
 g.history.state = null;
 g.screen = { width: g.innerWidth, height: g.innerHeight,
 	     availWidth: g.innerWidth, availHeight: g.innerHeight,

Неке датотеке нису приказане због велике количине промена