From c37999a1bc443ab66cd228ed43bb9d2f56f6bcd9 Mon Sep 17 00:00:00 2001 From: Tom Schuster Date: Wed, 15 Jun 2022 19:01:01 +0000 Subject: [PATCH 01/64] Bug 1738694 - Use openLinkIn instead of loadURI. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D147514 --- browser/base/content/browser.js | 39 +++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index 05d20e93a7b6..7104ada10814 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -2260,23 +2260,28 @@ var gBrowserInit = { window.arguments[5] != undefined ? window.arguments[5] : Ci.nsIScriptSecurityManager.DEFAULT_USER_CONTEXT_ID; - loadURI( - uriToLoad, - window.arguments[2] || null, - window.arguments[3] || null, - window.arguments[4] || false, - userContextId, - // pass the origin principal (if any) and force its use to create - // an initial about:blank viewer if present: - window.arguments[6], - window.arguments[7], - !!window.arguments[6], - window.arguments[8], - // TODO fix allowInheritPrincipal to default to false. - // Default to true unless explicitly set to false because of bug 1475201. - window.arguments[9] !== false, - window.arguments[10] - ); + + try { + openLinkIn(uriToLoad, "current", { + referrerInfo: window.arguments[2] || null, + postData: window.arguments[3] || null, + allowThirdPartyFixup: window.arguments[4] || false, + userContextId, + // pass the origin principal (if any) and force its use to create + // an initial about:blank viewer if present: + originPrincipal: window.arguments[6], + originStoragePrincipal: window.arguments[7], + triggeringPrincipal: window.arguments[8], + // TODO fix allowInheritPrincipal to default to false. + // Default to true unless explicitly set to false because of bug 1475201. + allowInheritPrincipal: window.arguments[9] !== false, + csp: window.arguments[10], + forceAboutBlankViewerInCurrent: !!window.arguments[6], + }); + } catch (e) { + Cu.reportError(e); + } + window.focus(); } else { // Note: loadOneOrMoreURIs *must not* be called if window.arguments.length >= 3. From f2caf19094aa246617ea2139a114fc663a83eb42 Mon Sep 17 00:00:00 2001 From: Tom Schuster Date: Wed, 15 Jun 2022 19:01:02 +0000 Subject: [PATCH 02/64] Bug 1738694 - Pass around hasValidUserGestureActivation and fromExternal when opening links from the UI or command-line. r=Gijs,edgar Differential Revision: https://phabricator.services.mozilla.com/D147515 --- browser/actors/ClickHandlerParent.jsm | 2 ++ browser/base/content/browser.js | 35 +++++++++++++++++-- browser/base/content/nsContextMenu.js | 1 + browser/base/content/utilityOverlay.js | 22 ++++++++---- browser/components/BrowserContentHandler.jsm | 7 +++- .../extensions/parent/ext-windows.js | 2 +- 6 files changed, 58 insertions(+), 11 deletions(-) diff --git a/browser/actors/ClickHandlerParent.jsm b/browser/actors/ClickHandlerParent.jsm index 5bf2ebaa5c65..9330ce5eeaac 100644 --- a/browser/actors/ClickHandlerParent.jsm +++ b/browser/actors/ClickHandlerParent.jsm @@ -115,6 +115,8 @@ class ClickHandlerParent extends JSWindowActorParent { csp: data.csp ? lazy.E10SUtils.deserializeCSP(data.csp) : null, frameID: data.frameID, openerBrowser: browser, + // The child ensures that untrusted events have a valid user activation. + hasValidUserGestureActivation: true, }; // The new tab/window must use the same userContextId. diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index 7104ada10814..ce10a28e6225 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -1508,11 +1508,13 @@ function _loadURI(browser, uri, params = {}) { userContextId, csp, remoteTypeOverride, + hasValidUserGestureActivation, } = params || {}; let loadFlags = params.loadFlags || params.flags || Ci.nsIWebNavigation.LOAD_FLAGS_NONE; - let hasValidUserGestureActivation = + hasValidUserGestureActivation ??= document.hasValidTransientUserGestureActivation; + if (!triggeringPrincipal) { throw new Error("Must load with a triggering Principal"); } @@ -2245,7 +2247,7 @@ var gBrowserInit = { }); } catch (e) {} } else if (window.arguments.length >= 3) { - // window.arguments[1]: unused (bug 871161) + // window.arguments[1]: extraOptions (nsIPropertyBag) // [2]: referrerInfo (nsIReferrerInfo) // [3]: postData (nsIInputStream) // [4]: allowThirdPartyFixup (bool) @@ -2261,6 +2263,26 @@ var gBrowserInit = { ? window.arguments[5] : Ci.nsIScriptSecurityManager.DEFAULT_USER_CONTEXT_ID; + let hasValidUserGestureActivation = undefined; + let fromExternal = undefined; + if (window.arguments[1]) { + if (!(window.arguments[1] instanceof Ci.nsIPropertyBag2)) { + throw new Error( + "window.arguments[1] must be null or Ci.nsIPropertyBag2!" + ); + } + + let extraOptions = window.arguments[1]; + if (extraOptions.hasKey("hasValidUserGestureActivation")) { + hasValidUserGestureActivation = extraOptions.getPropertyAsBool( + "hasValidUserGestureActivation" + ); + } + if (extraOptions.hasKey("fromExternal")) { + fromExternal = extraOptions.getPropertyAsBool("fromExternal"); + } + } + try { openLinkIn(uriToLoad, "current", { referrerInfo: window.arguments[2] || null, @@ -2277,6 +2299,8 @@ var gBrowserInit = { allowInheritPrincipal: window.arguments[9] !== false, csp: window.arguments[10], forceAboutBlankViewerInCurrent: !!window.arguments[6], + hasValidUserGestureActivation, + fromExternal, }); } catch (e) { Cu.reportError(e); @@ -6277,13 +6301,18 @@ nsBrowserAccess.prototype = { // Pass all params to openDialog to ensure that "url" isn't passed through // loadOneOrMoreURIs, which splits based on "|" try { + let extraOptions = Cc[ + "@mozilla.org/hash-property-bag;1" + ].createInstance(Ci.nsIWritablePropertyBag2); + extraOptions.setPropertyAsBool("fromExternal", isExternal); + openDialog( AppConstants.BROWSER_CHROME_URL, "_blank", features, // window.arguments url, - null, + extraOptions, null, null, null, diff --git a/browser/base/content/nsContextMenu.js b/browser/base/content/nsContextMenu.js index a197cefb1f26..ee4dd39d3f21 100644 --- a/browser/base/content/nsContextMenu.js +++ b/browser/base/content/nsContextMenu.js @@ -1309,6 +1309,7 @@ class nsContextMenu { triggeringPrincipal: this.principal, csp: this.csp, frameID: this.contentData.frameID, + hasValidUserGestureActivation: true, }; for (let p in extra) { params[p] = extra[p]; diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js index 40a1fa59d0e2..8afaccf7b5d3 100644 --- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -409,12 +409,17 @@ function openLinkIn(url, where, params) { ); wuri.data = url; - let charset = null; - if (aCharset) { - charset = Cc["@mozilla.org/supports-string;1"].createInstance( - Ci.nsISupportsString + let extraOptions = Cc["@mozilla.org/hash-property-bag;1"].createInstance( + Ci.nsIWritablePropertyBag2 + ); + if (params.hasValidUserGestureActivation !== undefined) { + extraOptions.setPropertyAsBool( + "hasValidUserGestureActivation", + params.hasValidUserGestureActivation ); - charset.data = "charset=" + aCharset; + } + if (params.fromExternal !== undefined) { + extraOptions.setPropertyAsBool("fromExternal", params.fromExternal); } var allowThirdPartyFixupSupports = Cc[ @@ -428,7 +433,7 @@ function openLinkIn(url, where, params) { userContextIdSupports.data = aUserContextId; sa.appendElement(wuri); - sa.appendElement(charset); + sa.appendElement(extraOptions); sa.appendElement(aReferrerInfo); sa.appendElement(aPostData); sa.appendElement(allowThirdPartyFixupSupports); @@ -579,6 +584,9 @@ function openLinkIn(url, where, params) { if (aForceAllowDataURI) { flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI; } + if (params.fromExternal) { + flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL; + } let { URI_INHERITS_SECURITY_CONTEXT } = Ci.nsIProtocolHandler; if ( @@ -600,6 +608,7 @@ function openLinkIn(url, where, params) { referrerInfo: aReferrerInfo, postData: aPostData, userContextId: aUserContextId, + hasValidUserGestureActivation: params.hasValidUserGestureActivation, }); if (aResolveOnContentBrowserReady) { aResolveOnContentBrowserReady(targetBrowser); @@ -636,6 +645,7 @@ function openLinkIn(url, where, params) { csp: aCsp, focusUrlBar, openerBrowser: params.openerBrowser, + fromExternal: params.fromExternal, }); targetBrowser = tabUsedForLoad.linkedBrowser; diff --git a/browser/components/BrowserContentHandler.jsm b/browser/components/BrowserContentHandler.jsm index 3eab259898b8..47647e8e9126 100644 --- a/browser/components/BrowserContentHandler.jsm +++ b/browser/components/BrowserContentHandler.jsm @@ -250,12 +250,17 @@ function openBrowserWindow( }); args = [uriArray]; } else { + let extraOptions = Cc["@mozilla.org/hash-property-bag;1"].createInstance( + Ci.nsIWritablePropertyBag2 + ); + extraOptions.setPropertyAsBool("fromExternal", true); + // Always pass at least 3 arguments to avoid the "|"-splitting behavior, // ie. avoid the loadOneOrMoreURIs function. // Also, we need to pass the triggering principal. args = [ urlOrUrlList, - null, // charset + extraOptions, null, // refererInfo postData, undefined, // allowThirdPartyFixup; this would be `false` but that diff --git a/browser/components/extensions/parent/ext-windows.js b/browser/components/extensions/parent/ext-windows.js index 34b7b0fa6dce..9968a54232ef 100644 --- a/browser/components/extensions/parent/ext-windows.js +++ b/browser/components/extensions/parent/ext-windows.js @@ -260,7 +260,7 @@ this.windows = class extends ExtensionAPIPersistent { } } - args.appendElement(null); // unused + args.appendElement(null); // extraOptions args.appendElement(null); // referrerInfo args.appendElement(null); // postData args.appendElement(null); // allowThirdPartyFixup From dbfa36ac473ee2d5902cba864a338aa7a6d33237 Mon Sep 17 00:00:00 2001 From: Niklas Goegge Date: Wed, 15 Jun 2022 19:01:02 +0000 Subject: [PATCH 03/64] Bug 1738694: Add sec-fetch tests for openening new windows. r=ckerschb Differential Revision: https://phabricator.services.mozilla.com/D130860 --- dom/security/test/sec-fetch/browser.ini | 3 + .../test/sec-fetch/browser_external_loads.js | 108 ++++++++++++++++-- .../test/sec-fetch/file_dummy_link.html | 9 ++ .../sec-fetch/file_dummy_link_location.html | 9 ++ 4 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 dom/security/test/sec-fetch/file_dummy_link.html create mode 100644 dom/security/test/sec-fetch/file_dummy_link_location.html diff --git a/dom/security/test/sec-fetch/browser.ini b/dom/security/test/sec-fetch/browser.ini index 6a5d8344cc57..a97235b74059 100644 --- a/dom/security/test/sec-fetch/browser.ini +++ b/dom/security/test/sec-fetch/browser.ini @@ -3,3 +3,6 @@ support-files = file_no_cache.sjs [browser_navigation.js] [browser_external_loads.js] +support-files = + file_dummy_link.html + file_dummy_link_location.html diff --git a/dom/security/test/sec-fetch/browser_external_loads.js b/dom/security/test/sec-fetch/browser_external_loads.js index f3b6fc6ad43a..ea2467d1fb5c 100644 --- a/dom/security/test/sec-fetch/browser_external_loads.js +++ b/dom/security/test/sec-fetch/browser_external_loads.js @@ -1,6 +1,11 @@ "use strict"; -let gExpectedHeader = {}; +const TEST_PATH = getRootDirectory(gTestPath).replace( + "chrome://mochitests/content", + "https://example.com" +); + +var gExpectedHeader = {}; function checkSecFetchUser(subject, topic, data) { let channel = subject.QueryInterface(Ci.nsIHttpChannel); @@ -27,7 +32,7 @@ function checkSecFetchUser(subject, topic, data) { ); } catch (e) { if (expectedValue) { - ok(false, "required headers are set"); + ok(false, `${header} should be set`); } else { ok(true, `${header} should not be set`); } @@ -37,7 +42,10 @@ function checkSecFetchUser(subject, topic, data) { add_task(async function external_load() { waitForExplicitFinish(); + Services.obs.addObserver(checkSecFetchUser, "http-on-stop-request"); + // Simulate an external load in the *current* window with + // Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL and the system principal. gExpectedHeader = { "sec-fetch-site": "none", "sec-fetch-mode": "navigate", @@ -45,13 +53,9 @@ add_task(async function external_load() { "sec-fetch-user": "?1", }; - Services.obs.addObserver(checkSecFetchUser, "http-on-stop-request"); - let loaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser); - // Simulate an external load with Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL and - // the system principal. window.browserDOMWindow.openURI( - makeURI("https://example.com"), + makeURI(`${TEST_PATH}file_dummy_link.html`), null, Ci.nsIBrowserDOMWindow.OPEN_CURRENTWINDOW, Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL, @@ -59,6 +63,96 @@ add_task(async function external_load() { ); await loaded; + // Open a link in a *new* window through the context menu. + gExpectedHeader = { + "sec-fetch-site": "same-origin", + "sec-fetch-mode": "navigate", + "sec-fetch-dest": "document", + "sec-fetch-user": "?1", + }; + + loaded = BrowserTestUtils.waitForNewWindow({ + url: `${TEST_PATH}file_dummy_link_location.html`, + }); + BrowserTestUtils.waitForEvent(document, "popupshown", false, event => { + document.getElementById("context-openlink").doCommand(); + event.target.hidePopup(); + return true; + }); + BrowserTestUtils.synthesizeMouseAtCenter( + "#dummylink", + { type: "contextmenu", button: 2 }, + gBrowser.selectedBrowser + ); + + let win = await loaded; + win.close(); + + // Simulate an external load in a *new* window with + // Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL and the system principal. + gExpectedHeader = { + "sec-fetch-site": "none", + "sec-fetch-mode": "navigate", + "sec-fetch-dest": "document", + "sec-fetch-user": "?1", + }; + + loaded = BrowserTestUtils.waitForNewWindow({ + url: "https://example.com/newwindow", + }); + window.browserDOMWindow.openURI( + makeURI("https://example.com/newwindow"), + null, + Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW, + Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL, + Services.scriptSecurityManager.getSystemPrincipal() + ); + win = await loaded; + win.close(); + + // Open a *new* window through window.open without user activation. + gExpectedHeader = { + "sec-fetch-site": "same-origin", + "sec-fetch-mode": "navigate", + "sec-fetch-dest": "document", + }; + + loaded = BrowserTestUtils.waitForNewWindow({ + url: "https://example.com/windowopen", + }); + await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => { + content.window.open( + "https://example.com/windowopen", + "_blank", + "height=500,width=500" + ); + }); + win = await loaded; + win.close(); + + // Open a *new* window through window.open with user activation. + gExpectedHeader = { + "sec-fetch-site": "same-origin", + "sec-fetch-mode": "navigate", + "sec-fetch-dest": "document", + "sec-fetch-user": "?1", + }; + + loaded = BrowserTestUtils.waitForNewWindow({ + url: "https://example.com/windowopen_withactivation", + }); + await SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => { + content.document.notifyUserGestureActivation(); + content.window.open( + "https://example.com/windowopen_withactivation", + "_blank", + "height=500,width=500" + ); + content.document.clearUserGestureActivation(); + }); + win = await loaded; + win.close(); + Services.obs.removeObserver(checkSecFetchUser, "http-on-stop-request"); finish(); }); diff --git a/dom/security/test/sec-fetch/file_dummy_link.html b/dom/security/test/sec-fetch/file_dummy_link.html new file mode 100644 index 000000000000..2150054226f4 --- /dev/null +++ b/dom/security/test/sec-fetch/file_dummy_link.html @@ -0,0 +1,9 @@ + + + + Bug 1738694 - Sec-Fetch-User header is missing when opening a link in a new window + + + Open + + diff --git a/dom/security/test/sec-fetch/file_dummy_link_location.html b/dom/security/test/sec-fetch/file_dummy_link_location.html new file mode 100644 index 000000000000..9f9400e1c32b --- /dev/null +++ b/dom/security/test/sec-fetch/file_dummy_link_location.html @@ -0,0 +1,9 @@ + + + + Bug 1738694 - Sec-Fetch-User header is missing when opening a link in a new window + + +

file_dummy_link_location.html

+ + From 1478087c1f94506c8f203906fbb01220601871f8 Mon Sep 17 00:00:00 2001 From: Andrew McCreight Date: Wed, 15 Jun 2022 19:09:02 +0000 Subject: [PATCH 04/64] Bug 1773044 - Remove the `dom.ipc.shims.enabledWarnings` pref. r=kmag DONTBUILD Differential Revision: https://phabricator.services.mozilla.com/D149287 --- browser/app/profile/firefox.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/browser/app/profile/firefox.js b/browser/app/profile/firefox.js index 7f5ad423db90..e10ca2cbfeea 100644 --- a/browser/app/profile/firefox.js +++ b/browser/app/profile/firefox.js @@ -1220,8 +1220,6 @@ pref("browser.bookmarks.editDialog.maxRecentFolders", 7); // just save on Accept, once the project is complete. pref("browser.bookmarks.editDialog.delayedApply.enabled", false); -pref("dom.ipc.shims.enabledWarnings", false); - #if defined(XP_WIN) && defined(MOZ_SANDBOX) // This controls the strength of the Windows content process sandbox for // testing purposes. This will require a restart. From a8d09d47af6310e629c4e7eded3e8e56e06b36c8 Mon Sep 17 00:00:00 2001 From: Jason Prickett Date: Wed, 15 Jun 2022 19:31:07 +0000 Subject: [PATCH 05/64] Bug 1774063 - Added a 'browser.aboutwelcome.templateMR' pref to support MR 2022 onboarding r=pdahiya Differential Revision: https://phabricator.services.mozilla.com/D149314 --- browser/app/profile/firefox.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/browser/app/profile/firefox.js b/browser/app/profile/firefox.js index e10ca2cbfeea..c49a2014253b 100644 --- a/browser/app/profile/firefox.js +++ b/browser/app/profile/firefox.js @@ -1604,6 +1604,8 @@ pref("browser.aboutwelcome.enabled", true); // Used to set multistage welcome UX pref("browser.aboutwelcome.screens", ""); pref("browser.aboutwelcome.skipFocus", true); +// Used to enable template for MR 2022 Onboarding +pref("browser.aboutwelcome.templateMR", false); // The pref that controls if the What's New panel is enabled. pref("browser.messaging-system.whatsNewPanel.enabled", true); From 44d5f1fe61cb4bc5abe730f72b1d3b6ad2c4e8d9 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:34:34 +0000 Subject: [PATCH 06/64] Bug 1608282 - Part 1: Support fetch, crypto, and indexedDB in the system global by default. r=mccr8 Differential Revision: https://phabricator.services.mozilla.com/D149194 --- js/xpconnect/src/Sandbox.cpp | 4 ++-- js/xpconnect/src/XPCJSRuntime.cpp | 3 +++ js/xpconnect/src/XPCRuntimeService.cpp | 32 +++++++++++++++++++++++++- js/xpconnect/src/xpcprivate.h | 6 +++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/js/xpconnect/src/Sandbox.cpp b/js/xpconnect/src/Sandbox.cpp index a1b79335fe06..8fb54ab09522 100644 --- a/js/xpconnect/src/Sandbox.cpp +++ b/js/xpconnect/src/Sandbox.cpp @@ -270,7 +270,7 @@ static bool SandboxImport(JSContext* cx, unsigned argc, Value* vp) { return true; } -static bool SandboxCreateCrypto(JSContext* cx, JS::HandleObject obj) { +bool xpc::SandboxCreateCrypto(JSContext* cx, JS::Handle obj) { MOZ_ASSERT(JS_IsGlobalObject(obj)); nsIGlobalObject* native = xpc::NativeGlobal(obj); @@ -359,7 +359,7 @@ static bool SandboxFetchPromise(JSContext* cx, unsigned argc, Value* vp) { return ConvertExceptionToPromise(cx, args.rval()); } -static bool SandboxCreateFetch(JSContext* cx, HandleObject obj) { +bool xpc::SandboxCreateFetch(JSContext* cx, JS::Handle obj) { MOZ_ASSERT(JS_IsGlobalObject(obj)); return JS_DefineFunction(cx, obj, "fetch", SandboxFetchPromise, 2, 0) && diff --git a/js/xpconnect/src/XPCJSRuntime.cpp b/js/xpconnect/src/XPCJSRuntime.cpp index 7db4e73e6c6a..8c3f37172a26 100644 --- a/js/xpconnect/src/XPCJSRuntime.cpp +++ b/js/xpconnect/src/XPCJSRuntime.cpp @@ -128,6 +128,9 @@ const char* const XPCJSRuntime::mStrings[] = { "interfaceId", // IDX_INTERFACE_ID "initializer", // IDX_INITIALIZER "print", // IDX_PRINT + "fetch", // IDX_FETCH + "crypto", // IDX_CRYPTO + "indexedDB", // IDX_INDEXEDDB }; /***************************************************************************/ diff --git a/js/xpconnect/src/XPCRuntimeService.cpp b/js/xpconnect/src/XPCRuntimeService.cpp index d7b6edd54ed1..857301fe72d7 100644 --- a/js/xpconnect/src/XPCRuntimeService.cpp +++ b/js/xpconnect/src/XPCRuntimeService.cpp @@ -11,6 +11,7 @@ #include "BackstagePass.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/WebIDLGlobalNameHash.h" +#include "mozilla/dom/IndexedDatabaseManager.h" using namespace mozilla::dom; @@ -66,7 +67,36 @@ BackstagePass::Resolve(nsIXPConnectWrappedNative* wrapper, JSContext* cx, JS::RootedId id(cx, idArg); *_retval = WebIDLGlobalNameHash::ResolveForSystemGlobal(cx, obj, id, resolvedp); - return *_retval ? NS_OK : NS_ERROR_FAILURE; + if (!*_retval) { + return NS_ERROR_FAILURE; + } + + if (*resolvedp) { + return NS_OK; + } + + XPCJSContext* xpccx = XPCJSContext::Get(); + if (idArg == xpccx->GetStringID(XPCJSContext::IDX_FETCH)) { + *_retval = xpc::SandboxCreateFetch(cx, obj); + if (!*_retval) { + return NS_ERROR_FAILURE; + } + *resolvedp = true; + } else if (idArg == xpccx->GetStringID(XPCJSContext::IDX_CRYPTO)) { + *_retval = xpc::SandboxCreateCrypto(cx, obj); + if (!*_retval) { + return NS_ERROR_FAILURE; + } + *resolvedp = true; + } else if (idArg == xpccx->GetStringID(XPCJSContext::IDX_INDEXEDDB)) { + *_retval = IndexedDatabaseManager::DefineIndexedDB(cx, obj); + if (!*_retval) { + return NS_ERROR_FAILURE; + } + *resolvedp = true; + } + + return NS_OK; } NS_IMETHODIMP diff --git a/js/xpconnect/src/xpcprivate.h b/js/xpconnect/src/xpcprivate.h index d2f785d599b0..c4727a746cf1 100644 --- a/js/xpconnect/src/xpcprivate.h +++ b/js/xpconnect/src/xpcprivate.h @@ -404,6 +404,9 @@ class XPCJSContext final : public mozilla::CycleCollectedJSContext, IDX_INTERFACE_ID, IDX_INITIALIZER, IDX_PRINT, + IDX_FETCH, + IDX_CRYPTO, + IDX_INDEXEDDB, IDX_TOTAL_COUNT // just a count of the above }; @@ -2850,6 +2853,9 @@ void InitializeValue(const nsXPTType& aType, void* aValue); void DestructValue(const nsXPTType& aType, void* aValue, uint32_t aArrayLen = 0); +bool SandboxCreateCrypto(JSContext* cx, JS::Handle obj); +bool SandboxCreateFetch(JSContext* cx, JS::Handle obj); + } // namespace xpc namespace mozilla { From ca6b8769e56709b4d5a3c3689d4f17443ef733b3 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:34:34 +0000 Subject: [PATCH 07/64] Bug 1608282 - Part 2: Update jsm environment definition to include fetch, crypto, indexedDB. r=mccr8 Differential Revision: https://phabricator.services.mozilla.com/D149195 --- .../eslint/eslint-plugin-mozilla/lib/environments/jsm.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js index 20478286d1fd..36c7b39fee05 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js @@ -22,5 +22,10 @@ module.exports = { // JS can run. It's definitely available in JSMs. So even if this is not // the perfect place to add it, it's not wrong, and we can move it later. WebAssembly: false, + // These are hard-coded and available in .jsm scopes. + // See BackstagePass::Resolve. + fetch: false, + crypto: false, + indexedDB: false, }, }; From 26d5bfebf13bcab00cfc6f1113cececd0c7492fb Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:34:35 +0000 Subject: [PATCH 08/64] Bug 1608282 - Part 3: Remove Cu.importGlobalProperties from JSM. r=extension-reviewers,kmag Depends on D149195 Differential Revision: https://phabricator.services.mozilla.com/D149196 --- browser/actors/AboutProtectionsParent.jsm | 2 -- browser/components/migration/ChromeMacOSLoginCrypto.jsm | 2 -- browser/components/migration/ChromeWindowsLoginCrypto.jsm | 2 -- browser/components/newtab/test/RemoteImagesTestUtils.jsm | 2 -- browser/components/pagedata/PageDataSchema.jsm | 2 -- browser/modules/PartnerLinkAttribution.jsm | 2 -- dom/base/IndexedDBHelper.jsm | 2 -- dom/indexedDB/test/unit/GlobalObjectsModule.jsm | 2 -- js/xpconnect/loader/XPCOMUtils.jsm | 3 --- services/settings/IDBHelpers.jsm | 6 ------ services/settings/SharedUtils.jsm | 5 ----- toolkit/actors/AboutHttpsOnlyErrorChild.jsm | 1 - .../tests/BackgroundTask_profile_is_slim.jsm | 2 -- toolkit/components/extensions/ExtensionStorageSyncKinto.jsm | 2 -- .../extensions/test/mochitest/webrequest_test.jsm | 2 -- toolkit/components/nimbus/test/NimbusTestUtils.jsm | 1 - toolkit/components/places/BookmarkJSONUtils.jsm | 2 -- toolkit/components/search/tests/SearchTestUtils.jsm | 2 -- toolkit/modules/IndexedDB.jsm | 2 -- toolkit/mozapps/extensions/AbuseReporter.jsm | 2 -- toolkit/mozapps/extensions/internal/AddonRepository.jsm | 2 -- toolkit/mozapps/extensions/internal/AddonTestUtils.jsm | 2 -- 22 files changed, 50 deletions(-) diff --git a/browser/actors/AboutProtectionsParent.jsm b/browser/actors/AboutProtectionsParent.jsm index 741f0592898b..948644efa5ea 100644 --- a/browser/actors/AboutProtectionsParent.jsm +++ b/browser/actors/AboutProtectionsParent.jsm @@ -4,8 +4,6 @@ "use strict"; -Cu.importGlobalProperties(["fetch"]); - var EXPORTED_SYMBOLS = ["AboutProtectionsParent"]; const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" diff --git a/browser/components/migration/ChromeMacOSLoginCrypto.jsm b/browser/components/migration/ChromeMacOSLoginCrypto.jsm index 7abb5cb1ae96..98b25f7a35bb 100644 --- a/browser/components/migration/ChromeMacOSLoginCrypto.jsm +++ b/browser/components/migration/ChromeMacOSLoginCrypto.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["ChromeMacOSLoginCrypto"]; -Cu.importGlobalProperties(["crypto"]); - const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); diff --git a/browser/components/migration/ChromeWindowsLoginCrypto.jsm b/browser/components/migration/ChromeWindowsLoginCrypto.jsm index bbe204132a9f..3cbb668f2ec6 100644 --- a/browser/components/migration/ChromeWindowsLoginCrypto.jsm +++ b/browser/components/migration/ChromeWindowsLoginCrypto.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["ChromeWindowsLoginCrypto"]; -Cu.importGlobalProperties(["atob", "crypto"]); - const { ChromeMigrationUtils } = ChromeUtils.import( "resource:///modules/ChromeMigrationUtils.jsm" ); diff --git a/browser/components/newtab/test/RemoteImagesTestUtils.jsm b/browser/components/newtab/test/RemoteImagesTestUtils.jsm index 2b9a0113ff50..e99646c620f0 100644 --- a/browser/components/newtab/test/RemoteImagesTestUtils.jsm +++ b/browser/components/newtab/test/RemoteImagesTestUtils.jsm @@ -14,8 +14,6 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const RS_SERVER_PREF = "services.settings.server"; -Cu.importGlobalProperties(["fetch"]); - const RemoteImagesTestUtils = { /** * Serve a mock Remote Settings server with content for Remote Images diff --git a/browser/components/pagedata/PageDataSchema.jsm b/browser/components/pagedata/PageDataSchema.jsm index 9fc37b5d33f9..29b757dbebec 100644 --- a/browser/components/pagedata/PageDataSchema.jsm +++ b/browser/components/pagedata/PageDataSchema.jsm @@ -6,8 +6,6 @@ var EXPORTED_SYMBOLS = ["PageDataSchema"]; -Cu.importGlobalProperties(["fetch"]); - const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); diff --git a/browser/modules/PartnerLinkAttribution.jsm b/browser/modules/PartnerLinkAttribution.jsm index cbb9e77a3c6a..1d8b2b8af5e7 100644 --- a/browser/modules/PartnerLinkAttribution.jsm +++ b/browser/modules/PartnerLinkAttribution.jsm @@ -4,8 +4,6 @@ "use strict"; -Cu.importGlobalProperties(["fetch"]); - var EXPORTED_SYMBOLS = [ "PartnerLinkAttribution", "CONTEXTUAL_SERVICES_PING_TYPES", diff --git a/dom/base/IndexedDBHelper.jsm b/dom/base/IndexedDBHelper.jsm index 170cfea6aa0f..3fd70668b115 100644 --- a/dom/base/IndexedDBHelper.jsm +++ b/dom/base/IndexedDBHelper.jsm @@ -16,8 +16,6 @@ if (DEBUG) { var EXPORTED_SYMBOLS = ["IndexedDBHelper"]; -Cu.importGlobalProperties(["indexedDB"]); - const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function getErrorName(err) { diff --git a/dom/indexedDB/test/unit/GlobalObjectsModule.jsm b/dom/indexedDB/test/unit/GlobalObjectsModule.jsm index c700bd8b180f..905e75c9ecef 100644 --- a/dom/indexedDB/test/unit/GlobalObjectsModule.jsm +++ b/dom/indexedDB/test/unit/GlobalObjectsModule.jsm @@ -3,8 +3,6 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ -Cu.importGlobalProperties(["indexedDB"]); - var EXPORTED_SYMBOLS = ["GlobalObjectsModule"]; function GlobalObjectsModule() {} diff --git a/js/xpconnect/loader/XPCOMUtils.jsm b/js/xpconnect/loader/XPCOMUtils.jsm index 789c3c5f961e..bcde97a9d9c7 100644 --- a/js/xpconnect/loader/XPCOMUtils.jsm +++ b/js/xpconnect/loader/XPCOMUtils.jsm @@ -21,10 +21,7 @@ let global = Cu.getGlobalForObject({}); // and `MessagePort`. This table maps those extra symbols to the main // import name. const EXTRA_GLOBAL_NAME_TO_IMPORT_NAME = { - Headers: "fetch", MessagePort: "MessageChannel", - Request: "fetch", - Response: "fetch", }; /** diff --git a/services/settings/IDBHelpers.jsm b/services/settings/IDBHelpers.jsm index 1199d87e943c..d58101caa4a2 100644 --- a/services/settings/IDBHelpers.jsm +++ b/services/settings/IDBHelpers.jsm @@ -7,12 +7,6 @@ var EXPORTED_SYMBOLS = ["IDBHelpers"]; const DB_NAME = "remote-settings"; const DB_VERSION = 3; -// `indexedDB` is accessible in the worker global, but not the JSM global, -// where we have to import it - and the worker global doesn't have Cu. -if (typeof indexedDB == "undefined") { - Cu.importGlobalProperties(["indexedDB"]); -} - /** * Wrap IndexedDB errors to catch them more easily. */ diff --git a/services/settings/SharedUtils.jsm b/services/settings/SharedUtils.jsm index 5d32fb38bd82..9804e80c91c4 100644 --- a/services/settings/SharedUtils.jsm +++ b/services/settings/SharedUtils.jsm @@ -8,11 +8,6 @@ var EXPORTED_SYMBOLS = ["SharedUtils"]; -// Import globals that are available by default in workers but not in JSMs. -if (typeof crypto == "undefined") { - Cu.importGlobalProperties(["fetch", "crypto"]); -} - var SharedUtils = { /** * Check that the specified content matches the expected size and SHA-256 hash. diff --git a/toolkit/actors/AboutHttpsOnlyErrorChild.jsm b/toolkit/actors/AboutHttpsOnlyErrorChild.jsm index 105bdb458453..4917e4d2fad8 100644 --- a/toolkit/actors/AboutHttpsOnlyErrorChild.jsm +++ b/toolkit/actors/AboutHttpsOnlyErrorChild.jsm @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -Cu.importGlobalProperties(["fetch"]); var EXPORTED_SYMBOLS = ["AboutHttpsOnlyErrorChild"]; diff --git a/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm b/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm index 550513a622a0..af7fac42606e 100644 --- a/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm +++ b/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["runBackgroundTask"]; -Cu.importGlobalProperties(["fetch"]); - const { EXIT_CODE } = ChromeUtils.import( "resource://gre/modules/BackgroundTasksManager.jsm" ).BackgroundTasksManager; diff --git a/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm b/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm index 4e49ce737c88..78d48c71726f 100644 --- a/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm +++ b/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm @@ -16,8 +16,6 @@ var EXPORTED_SYMBOLS = [ "extensionStorageSync", ]; -Cu.importGlobalProperties(["atob", "btoa"]); - const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); diff --git a/toolkit/components/extensions/test/mochitest/webrequest_test.jsm b/toolkit/components/extensions/test/mochitest/webrequest_test.jsm index 6fc2fe3d7f1d..50496524fcfa 100644 --- a/toolkit/components/extensions/test/mochitest/webrequest_test.jsm +++ b/toolkit/components/extensions/test/mochitest/webrequest_test.jsm @@ -2,8 +2,6 @@ var EXPORTED_SYMBOLS = ["webrequest_test"]; -Cu.importGlobalProperties(["fetch"]); - var webrequest_test = { testFetch(url) { return fetch(url); diff --git a/toolkit/components/nimbus/test/NimbusTestUtils.jsm b/toolkit/components/nimbus/test/NimbusTestUtils.jsm index 5d73d924c45b..b60e71847ddd 100644 --- a/toolkit/components/nimbus/test/NimbusTestUtils.jsm +++ b/toolkit/components/nimbus/test/NimbusTestUtils.jsm @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -Cu.importGlobalProperties(["fetch"]); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); diff --git a/toolkit/components/places/BookmarkJSONUtils.jsm b/toolkit/components/places/BookmarkJSONUtils.jsm index f1b191eab50a..dd18a4074c46 100644 --- a/toolkit/components/places/BookmarkJSONUtils.jsm +++ b/toolkit/components/places/BookmarkJSONUtils.jsm @@ -9,8 +9,6 @@ const { PlacesUtils } = ChromeUtils.import( "resource://gre/modules/PlacesUtils.jsm" ); -Cu.importGlobalProperties(["fetch"]); - const lazy = {}; ChromeUtils.defineModuleGetter( diff --git a/toolkit/components/search/tests/SearchTestUtils.jsm b/toolkit/components/search/tests/SearchTestUtils.jsm index 709b00a9dd5b..693a8d4a1c56 100644 --- a/toolkit/components/search/tests/SearchTestUtils.jsm +++ b/toolkit/components/search/tests/SearchTestUtils.jsm @@ -20,8 +20,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { sinon: "resource://testing-common/Sinon.jsm", }); -Cu.importGlobalProperties(["fetch"]); - var EXPORTED_SYMBOLS = ["SearchTestUtils"]; var gTestScope; diff --git a/toolkit/modules/IndexedDB.jsm b/toolkit/modules/IndexedDB.jsm index c0f11635445f..ecc47361bfb0 100644 --- a/toolkit/modules/IndexedDB.jsm +++ b/toolkit/modules/IndexedDB.jsm @@ -15,8 +15,6 @@ /* exported IndexedDB */ var EXPORTED_SYMBOLS = ["IndexedDB"]; -Cu.importGlobalProperties(["indexedDB"]); - /** * Wraps the given request object, and returns a Promise which resolves when * the requests succeeds or rejects when it fails. diff --git a/toolkit/mozapps/extensions/AbuseReporter.jsm b/toolkit/mozapps/extensions/AbuseReporter.jsm index 4bfacca2e29a..74aa746df6ba 100644 --- a/toolkit/mozapps/extensions/AbuseReporter.jsm +++ b/toolkit/mozapps/extensions/AbuseReporter.jsm @@ -12,8 +12,6 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); -Cu.importGlobalProperties(["fetch"]); - const PREF_ABUSE_REPORT_URL = "extensions.abuseReport.url"; const PREF_AMO_DETAILS_API_URL = "extensions.abuseReport.amoDetailsURL"; diff --git a/toolkit/mozapps/extensions/internal/AddonRepository.jsm b/toolkit/mozapps/extensions/internal/AddonRepository.jsm index fa2471140c92..481701e4300b 100644 --- a/toolkit/mozapps/extensions/internal/AddonRepository.jsm +++ b/toolkit/mozapps/extensions/internal/AddonRepository.jsm @@ -43,8 +43,6 @@ XPCOMUtils.defineLazyGetter(lazy, "PLATFORM", () => { var EXPORTED_SYMBOLS = ["AddonRepository"]; -Cu.importGlobalProperties(["fetch"]); - const PREF_GETADDONS_CACHE_ENABLED = "extensions.getAddons.cache.enabled"; const PREF_GETADDONS_CACHE_TYPES = "extensions.getAddons.cache.types"; const PREF_GETADDONS_CACHE_ID_ENABLED = diff --git a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm index 77eee4ab2ad1..898132bba095 100644 --- a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm +++ b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["AddonTestUtils", "MockAsyncShutdown"]; const CERTDB_CONTRACTID = "@mozilla.org/security/x509certdb;1"; -Cu.importGlobalProperties(["fetch"]); - const { AddonManager, AddonManagerPrivate } = ChromeUtils.import( "resource://gre/modules/AddonManager.jsm" ); From 8b8d6b141a41ff0c5d126faa6a2c2912cbe06b8e Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:34:35 +0000 Subject: [PATCH 09/64] Bug 1608282 - Part 4: Remove Cu.defineLazyGlobalGetters from JSM. r=webdriver-reviewers,extension-reviewers,jdescottes,kmag Depends on D149196 Differential Revision: https://phabricator.services.mozilla.com/D149197 --- browser/components/newtab/lib/ASRouter.jsm | 3 +- .../components/newtab/lib/CFRPageActions.jsm | 4 +- .../newtab/lib/DiscoveryStreamFeed.jsm | 6 +-- .../PersonalityProvider.jsm | 7 +-- browser/components/newtab/lib/Screenshots.jsm | 4 +- .../newtab/lib/TippyTopProvider.jsm | 9 +--- .../components/newtab/lib/TopSitesFeed.jsm | 4 +- .../components/newtab/lib/TopStoriesFeed.jsm | 10 ++-- .../urlbar/UrlbarProviderPreloadedSites.jsm | 2 - .../urlbar/UrlbarProviderQuickSuggest.jsm | 2 - dom/push/PushCrypto.jsm | 51 ++++++++----------- dom/system/NetworkGeolocationProvider.jsm | 4 +- .../android/actors/ContentDelegateChild.jsm | 4 +- remote/marionette/capture.js | 3 +- .../manager/ssl/RemoteSecuritySettings.jsm | 4 +- services/automation/ServicesAutomation.jsm | 4 +- services/crypto/modules/WeaveCrypto.js | 31 ++++------- services/crypto/modules/jwcrypto.jsm | 33 ++++-------- services/crypto/modules/utils.js | 17 +++---- .../fxaccounts/FxAccountsProfileClient.jsm | 9 +--- services/settings/Attachments.jsm | 3 +- services/settings/Utils.jsm | 6 +-- services/settings/remote-settings.js | 2 - services/sync/modules/bookmark_validator.js | 8 ++- services/sync/modules/resource.js | 8 ++- .../tps/resource/auth/fxaccounts.jsm | 10 +--- .../cleardata/SiteDataTestUtils.jsm | 14 +---- .../components/extensions/ExtensionCommon.jsm | 4 +- .../extensions/ExtensionContent.jsm | 4 +- .../components/extensions/ExtensionUtils.jsm | 4 +- .../components/featuregates/FeatureGate.jsm | 4 +- .../lib/RemoteSettingsExperimentLoader.jsm | 14 +++-- .../components/normandy/lib/NormandyApi.jsm | 7 +-- .../components/passwordmgr/LoginRecipes.jsm | 2 - .../passwordmgr/PasswordGenerator.jsm | 12 +---- toolkit/components/utils/Sampling.jsm | 8 +-- toolkit/modules/Region.jsm | 7 +-- toolkit/modules/UpdateUtils.jsm | 4 +- .../extensions/internal/XPIInstall.jsm | 5 +- 39 files changed, 97 insertions(+), 240 deletions(-) diff --git a/browser/components/newtab/lib/ASRouter.jsm b/browser/components/newtab/lib/ASRouter.jsm index d745083f8572..e5aa71694e1a 100644 --- a/browser/components/newtab/lib/ASRouter.jsm +++ b/browser/components/newtab/lib/ASRouter.jsm @@ -12,7 +12,6 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { SnippetsTestMessageProvider: "resource://activity-stream/lib/SnippetsTestMessageProvider.jsm", @@ -192,7 +191,7 @@ const MessageLoaderUtils = { let response; try { - response = await lazy.fetch(provider.url, { + response = await fetch(provider.url, { headers, credentials: "omit", }); diff --git a/browser/components/newtab/lib/CFRPageActions.jsm b/browser/components/newtab/lib/CFRPageActions.jsm index 0bd95b12d6b4..a6778d929992 100644 --- a/browser/components/newtab/lib/CFRPageActions.jsm +++ b/browser/components/newtab/lib/CFRPageActions.jsm @@ -10,8 +10,6 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyModuleGetters(lazy, { PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm", RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm", @@ -881,7 +879,7 @@ const CFRPageActions = { async _fetchLatestAddonVersion(id) { let url = null; try { - const response = await lazy.fetch(`${ADDONS_API_URL}/${id}/`, { + const response = await fetch(`${ADDONS_API_URL}/${id}/`, { credentials: "omit", }); if (response.status !== 204 && response.ok) { diff --git a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm index a32a2559485e..1abedd6767db 100644 --- a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm +++ b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm @@ -3,9 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const lazy = {}; ChromeUtils.defineModuleGetter( lazy, @@ -21,7 +18,6 @@ const { setTimeout, clearTimeout } = ChromeUtils.import( "resource://gre/modules/Timer.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { actionTypes: at, actionCreators: ac } = ChromeUtils.import( "resource://activity-stream/common/Actions.jsm" ); @@ -287,7 +283,7 @@ class DiscoveryStreamFeed { const controller = new AbortController(); const { signal } = controller; - const fetchPromise = lazy.fetch(endpoint, { + const fetchPromise = fetch(endpoint, { ...options, credentials: "omit", signal, diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm index c34c2a896471..841d4c8ca30c 100644 --- a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm +++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm @@ -18,11 +18,6 @@ ChromeUtils.defineModuleGetter( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { BasePromiseWorker } = ChromeUtils.import( "resource://gre/modules/PromiseWorker.jsm" @@ -67,7 +62,7 @@ class PersonalityProvider { } const server = Services.prefs.getCharPref("services.settings.server"); const serverInfo = await ( - await lazy.fetch(`${server}/`, { + await fetch(`${server}/`, { credentials: "omit", }) ).json(); diff --git a/browser/components/newtab/lib/Screenshots.jsm b/browser/components/newtab/lib/Screenshots.jsm index a012ed62dbaf..ccf5c4c65070 100644 --- a/browser/components/newtab/lib/Screenshots.jsm +++ b/browser/components/newtab/lib/Screenshots.jsm @@ -11,8 +11,6 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - ChromeUtils.defineModuleGetter( lazy, "BackgroundPageThumbs", @@ -63,7 +61,7 @@ const Screenshots = { // Blob URIs for the screenshots. const imgPath = lazy.PageThumbs.getThumbnailPath(url); - const filePathResponse = await lazy.fetch(`file://${imgPath}`); + const filePathResponse = await fetch(`file://${imgPath}`); const fileContents = await filePathResponse.blob(); // Check if the file is empty, which indicates there isn't actually a diff --git a/browser/components/newtab/lib/TippyTopProvider.jsm b/browser/components/newtab/lib/TippyTopProvider.jsm index 138d9a7ef3c4..ab2895f35a5c 100644 --- a/browser/components/newtab/lib/TippyTopProvider.jsm +++ b/browser/components/newtab/lib/TippyTopProvider.jsm @@ -2,15 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const TIPPYTOP_PATH = "chrome://activity-stream/content/data/content/tippytop/"; const TIPPYTOP_JSON_PATH = "chrome://activity-stream/content/data/content/tippytop/top_sites.json"; @@ -43,7 +36,7 @@ class TippyTopProvider { // Load the Tippy Top sites from the json manifest. try { for (const site of await ( - await lazy.fetch(TIPPYTOP_JSON_PATH, { + await fetch(TIPPYTOP_JSON_PATH, { credentials: "omit", }) ).json()) { diff --git a/browser/components/newtab/lib/TopSitesFeed.jsm b/browser/components/newtab/lib/TopSitesFeed.jsm index ffb8a43ccb00..cc5438dac8e1 100644 --- a/browser/components/newtab/lib/TopSitesFeed.jsm +++ b/browser/components/newtab/lib/TopSitesFeed.jsm @@ -74,8 +74,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/Region.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyGetter(lazy, "log", () => { const { Logger } = ChromeUtils.import( "resource://messaging-system/lib/Logger.jsm" @@ -186,7 +184,7 @@ class ContileIntegration { } try { let url = Services.prefs.getStringPref(CONTILE_ENDPOINT_PREF); - const response = await lazy.fetch(url, { credentials: "omit" }); + const response = await fetch(url, { credentials: "omit" }); if (!response.ok) { lazy.log.warn( `Contile endpoint returned unexpected status: ${response.status}` diff --git a/browser/components/newtab/lib/TopStoriesFeed.jsm b/browser/components/newtab/lib/TopStoriesFeed.jsm index 1bcf027c4a2b..811159bbdaa3 100644 --- a/browser/components/newtab/lib/TopStoriesFeed.jsm +++ b/browser/components/newtab/lib/TopStoriesFeed.jsm @@ -3,15 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { NewTabUtils } = ChromeUtils.import( "resource://gre/modules/NewTabUtils.jsm" ); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { actionTypes: at, actionCreators: ac } = ChromeUtils.import( "resource://activity-stream/common/Actions.jsm" @@ -29,6 +24,7 @@ const { PersistentCache } = ChromeUtils.import( "resource://activity-stream/lib/PersistentCache.jsm" ); +const lazy = {}; ChromeUtils.defineModuleGetter( lazy, "pktApi", @@ -196,7 +192,7 @@ class TopStoriesFeed { return null; } try { - const response = await lazy.fetch(this.stories_endpoint, { + const response = await fetch(this.stories_endpoint, { credentials: "omit", }); if (!response.ok) { @@ -296,7 +292,7 @@ class TopStoriesFeed { return null; } try { - const response = await lazy.fetch(this.topics_endpoint, { + const response = await fetch(this.topics_endpoint, { credentials: "omit", }); if (!response.ok) { diff --git a/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm b/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm index dfd4b81ca544..aa76060865db 100644 --- a/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm +++ b/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm @@ -17,8 +17,6 @@ const { XPCOMUtils } = ChromeUtils.import( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]); - XPCOMUtils.defineLazyModuleGetters(this, { ProfileAge: "resource://gre/modules/ProfileAge.jsm", UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm", diff --git a/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm b/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm index 1645f7448bdf..6b0ecf7463c4 100644 --- a/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm +++ b/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm @@ -28,8 +28,6 @@ XPCOMUtils.defineLazyModuleGetters(this, { UrlbarUtils: "resource:///modules/UrlbarUtils.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(this, ["crypto", "fetch"]); - const TIMESTAMP_TEMPLATE = "%YYYYMMDDHH%"; const TIMESTAMP_LENGTH = 10; const TIMESTAMP_REGEXP = /^\d{10}$/; diff --git a/dom/push/PushCrypto.jsm b/dom/push/PushCrypto.jsm index 39e945a4527b..a1ace86a8c5f 100644 --- a/dom/push/PushCrypto.jsm +++ b/dom/push/PushCrypto.jsm @@ -15,8 +15,6 @@ XPCOMUtils.defineLazyGetter(lazy, "gDOMBundle", () => Services.strings.createBundle("chrome://global/locale/dom/dom.properties") ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - // getCryptoParamsFromHeaders is exported for test purposes. const EXPORTED_SYMBOLS = ["PushCrypto", "getCryptoParamsFromHeaders"]; @@ -243,17 +241,13 @@ function concatArray(arrays) { } function hmac(key) { - this.keyPromise = lazy.crypto.subtle.importKey( - "raw", - key, - HMAC_SHA256, - false, - ["sign"] - ); + this.keyPromise = crypto.subtle.importKey("raw", key, HMAC_SHA256, false, [ + "sign", + ]); } hmac.prototype.hash = function(input) { - return this.keyPromise.then(k => lazy.crypto.subtle.sign("HMAC", k, input)); + return this.keyPromise.then(k => crypto.subtle.sign("HMAC", k, input)); }; function hkdf(salt, ikm) { @@ -331,7 +325,7 @@ class Decoder { try { let ikm = await this.computeSharedSecret(); let [gcmBits, nonce] = await this.deriveKeyAndNonce(ikm); - let key = await lazy.crypto.subtle.importKey( + let key = await crypto.subtle.importKey( "raw", gcmBits, "AES-GCM", @@ -368,14 +362,14 @@ class Decoder { */ async computeSharedSecret() { let [appServerKey, subscriptionPrivateKey] = await Promise.all([ - lazy.crypto.subtle.importKey("raw", this.senderKey, ECDH_KEY, false, [ + crypto.subtle.importKey("raw", this.senderKey, ECDH_KEY, false, [ "deriveBits", ]), - lazy.crypto.subtle.importKey("jwk", this.privateKey, ECDH_KEY, false, [ + crypto.subtle.importKey("jwk", this.privateKey, ECDH_KEY, false, [ "deriveBits", ]), ]); - return lazy.crypto.subtle.deriveBits( + return crypto.subtle.deriveBits( { name: "ECDH", public: appServerKey }, subscriptionPrivateKey, 256 @@ -408,7 +402,7 @@ class Decoder { name: "AES-GCM", iv: generateNonce(nonce, index), }; - let decoded = await lazy.crypto.subtle.decrypt(params, key, slice); + let decoded = await crypto.subtle.decrypt(params, key, slice); return this.unpadChunk(new Uint8Array(decoded), last); } @@ -609,22 +603,22 @@ var PushCrypto = { concatArray, generateAuthenticationSecret() { - return lazy.crypto.getRandomValues(new Uint8Array(16)); + return crypto.getRandomValues(new Uint8Array(16)); }, validateAppServerKey(key) { - return lazy.crypto.subtle + return crypto.subtle .importKey("raw", key, ECDSA_KEY, true, ["verify"]) .then(_ => key); }, generateKeys() { - return lazy.crypto.subtle + return crypto.subtle .generateKey(ECDH_KEY, true, ["deriveBits"]) .then(cryptoKey => Promise.all([ - lazy.crypto.subtle.exportKey("raw", cryptoKey.publicKey), - lazy.crypto.subtle.exportKey("jwk", cryptoKey.privateKey), + crypto.subtle.exportKey("raw", cryptoKey.publicKey), + crypto.subtle.exportKey("jwk", cryptoKey.privateKey), ]) ); }, @@ -731,10 +725,9 @@ var PushCrypto = { // purposes we allow it to be specified. const senderKeyPair = options.senderKeyPair || - (await lazy.crypto.subtle.generateKey(ECDH_KEY, true, ["deriveBits"])); + (await crypto.subtle.generateKey(ECDH_KEY, true, ["deriveBits"])); // allowing a salt to be specified is useful for tests. - const salt = - options.salt || lazy.crypto.getRandomValues(new Uint8Array(16)); + const salt = options.salt || crypto.getRandomValues(new Uint8Array(16)); const rs = options.rs === undefined ? 4096 : options.rs; const encoder = new aes128gcmEncoder( @@ -773,7 +766,7 @@ class aes128gcmEncoder { this.senderKeyPair.privateKey ); - const rawSenderPublicKey = await lazy.crypto.subtle.exportKey( + const rawSenderPublicKey = await crypto.subtle.exportKey( "raw", this.senderKeyPair.publicKey ); @@ -782,7 +775,7 @@ class aes128gcmEncoder { rawSenderPublicKey ); - const contentEncryptionKey = await lazy.crypto.subtle.importKey( + const contentEncryptionKey = await crypto.subtle.importKey( "raw", gcmBits, "AES-GCM", @@ -808,7 +801,7 @@ class aes128gcmEncoder { if (this.plaintext.byteLength === 0) { // Send an authentication tag for empty messages. chunks = [ - await lazy.crypto.subtle.encrypt( + await crypto.subtle.encrypt( { name: "AES-GCM", iv: generateNonce(nonce, 0), @@ -826,7 +819,7 @@ class aes128gcmEncoder { let isLast = index == inChunks.length - 1; let padding = new Uint8Array([isLast ? 2 : 1]); let input = concatArray([slice, padding]); - return lazy.crypto.subtle.encrypt( + return crypto.subtle.encrypt( { name: "AES-GCM", iv: generateNonce(nonce, index), @@ -860,7 +853,7 @@ class aes128gcmEncoder { // Note: this duplicates some of Decoder.computeSharedSecret, but the key // management is slightly different. async computeSharedSecret(receiverPublicKey, senderPrivateKey) { - const receiverPublicCryptoKey = await lazy.crypto.subtle.importKey( + const receiverPublicCryptoKey = await crypto.subtle.importKey( "raw", receiverPublicKey, ECDH_KEY, @@ -868,7 +861,7 @@ class aes128gcmEncoder { ["deriveBits"] ); - return lazy.crypto.subtle.deriveBits( + return crypto.subtle.deriveBits( { name: "ECDH", public: receiverPublicCryptoKey }, senderPrivateKey, 256 diff --git a/dom/system/NetworkGeolocationProvider.jsm b/dom/system/NetworkGeolocationProvider.jsm index 9791f821eaab..96724258c9ba 100644 --- a/dom/system/NetworkGeolocationProvider.jsm +++ b/dom/system/NetworkGeolocationProvider.jsm @@ -17,8 +17,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { setTimeout: "resource://gre/modules/Timer.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - // GeolocationPositionError has no interface object, so we can't use that here. const POSITION_UNAVAILABLE = 2; @@ -492,7 +490,7 @@ NetworkGeolocationProvider.prototype = { Services.prefs.getIntPref("geo.provider.network.timeout") ); - let req = await lazy.fetch(url, fetchOpts); + let req = await fetch(url, fetchOpts); lazy.clearTimeout(timeoutId); let result = req.json(); return result; diff --git a/mobile/android/actors/ContentDelegateChild.jsm b/mobile/android/actors/ContentDelegateChild.jsm index af7ab51b8a5c..6616efa35858 100644 --- a/mobile/android/actors/ContentDelegateChild.jsm +++ b/mobile/android/actors/ContentDelegateChild.jsm @@ -14,8 +14,6 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["URL"]); - XPCOMUtils.defineLazyModuleGetters(lazy, { ManifestObtainer: "resource://gre/modules/ManifestObtainer.jsm", }); @@ -83,7 +81,7 @@ class ContentDelegateChild extends GeckoViewActorChild { let elementSrc = (isImage || isMedia) && (node.currentSrc || node.src); if (elementSrc) { const isBlob = elementSrc.startsWith("blob:"); - if (isBlob && !lazy.URL.isValidURL(elementSrc)) { + if (isBlob && !URL.isValidURL(elementSrc)) { elementSrc = null; } } diff --git a/remote/marionette/capture.js b/remote/marionette/capture.js index 3fae5490bc52..ffa9cc457211 100644 --- a/remote/marionette/capture.js +++ b/remote/marionette/capture.js @@ -19,7 +19,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get(lazy.Log.TYPES.MARIONETTE) ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); const CONTEXT_2D = "2d"; const BG_COLOUR = "rgb(255,255,255)"; @@ -185,7 +184,7 @@ capture.toBase64 = function(canvas) { capture.toHash = function(canvas) { let u = capture.toBase64(canvas); let buffer = new TextEncoder("utf-8").encode(u); - return lazy.crypto.subtle.digest("SHA-256", buffer).then(hash => hex(hash)); + return crypto.subtle.digest("SHA-256", buffer).then(hash => hex(hash)); }; /** diff --git a/security/manager/ssl/RemoteSecuritySettings.jsm b/security/manager/ssl/RemoteSecuritySettings.jsm index f1481ca7c719..aaea7178bdad 100644 --- a/security/manager/ssl/RemoteSecuritySettings.jsm +++ b/security/manager/ssl/RemoteSecuritySettings.jsm @@ -31,8 +31,6 @@ const CRLITE_FILTERS_ENABLED_PREF = const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyGetter(lazy, "gTextDecoder", () => new TextDecoder()); XPCOMUtils.defineLazyGetter(lazy, "log", () => { @@ -593,7 +591,7 @@ class CRLiteFilters { try { // If we've already downloaded this, the backend should just grab it from its cache. let localURI = await this.client.attachments.downloadToDisk(filter); - let buffer = await (await lazy.fetch(localURI)).arrayBuffer(); + let buffer = await (await fetch(localURI)).arrayBuffer(); let bytes = new Uint8Array(buffer); lazy.log.debug( `Downloaded ${filter.details.name}: ${bytes.length} bytes` diff --git a/services/automation/ServicesAutomation.jsm b/services/automation/ServicesAutomation.jsm index 4a05536dcd5d..6a0fbdd98507 100644 --- a/services/automation/ServicesAutomation.jsm +++ b/services/automation/ServicesAutomation.jsm @@ -49,8 +49,6 @@ XPCOMUtils.defineLazyGetter(lazy, "fxAccounts", () => { ).getFxAccountsSingleton(); }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const AUTOCONFIG_PREF = "identity.fxaccounts.autoconfig.uri"; /* @@ -207,7 +205,7 @@ var Authentication = { const tries = 10; const normalWait = 4000; for (let i = 0; i < tries; ++i) { - let resp = await lazy.fetch(restmailURI); + let resp = await fetch(restmailURI); let messages = await resp.json(); // Sort so that the most recent emails are first. messages.sort((a, b) => new Date(b.receivedAt) - new Date(a.receivedAt)); diff --git a/services/crypto/modules/WeaveCrypto.js b/services/crypto/modules/WeaveCrypto.js index 03551ea93b29..38956b42e03b 100644 --- a/services/crypto/modules/WeaveCrypto.js +++ b/services/crypto/modules/WeaveCrypto.js @@ -9,10 +9,6 @@ const { XPCOMUtils } = ChromeUtils.import( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const CRYPT_ALGO = "AES-CBC"; const CRYPT_ALGO_LENGTH = 256; const CRYPT_ALGO_USAGES = ["encrypt", "decrypt"]; @@ -78,7 +74,7 @@ WeaveCrypto.prototype = { // /!\ Only use this for tests! /!\ _getCrypto() { - return lazy.crypto; + return crypto; }, async encrypt(clearTextUCS2, symmetricKey, iv) { @@ -135,17 +131,12 @@ WeaveCrypto.prototype = { let iv = this.byteCompressInts(ivStr); let symKey = await this.importSymKey(symKeyStr, operation); let cryptMethod = (operation === OPERATIONS.ENCRYPT - ? lazy.crypto.subtle.encrypt - : lazy.crypto.subtle.decrypt - ).bind(lazy.crypto.subtle); + ? crypto.subtle.encrypt + : crypto.subtle.decrypt + ).bind(crypto.subtle); let algo = { name: CRYPT_ALGO, iv }; - let keyBytes = await cryptMethod.call( - lazy.crypto.subtle, - algo, - symKey, - data - ); + let keyBytes = await cryptMethod.call(crypto.subtle, algo, symKey, data); return new Uint8Array(keyBytes); }, @@ -155,12 +146,8 @@ WeaveCrypto.prototype = { name: CRYPT_ALGO, length: CRYPT_ALGO_LENGTH, }; - let key = await lazy.crypto.subtle.generateKey( - algo, - true, - CRYPT_ALGO_USAGES - ); - let keyBytes = await lazy.crypto.subtle.exportKey("raw", key); + let key = await crypto.subtle.generateKey(algo, true, CRYPT_ALGO_USAGES); + let keyBytes = await crypto.subtle.exportKey("raw", key); return this.encodeBase64(new Uint8Array(keyBytes)); }, @@ -172,7 +159,7 @@ WeaveCrypto.prototype = { this.log("generateRandomBytes() called"); let randBytes = new Uint8Array(byteCount); - lazy.crypto.getRandomValues(randBytes); + crypto.getRandomValues(randBytes); return this.encodeBase64(randBytes); }, @@ -208,7 +195,7 @@ WeaveCrypto.prototype = { let symmetricKeyBuffer = this.makeUint8Array(encodedKeyString, true); let algo = { name: CRYPT_ALGO }; let usages = [operation === OPERATIONS.ENCRYPT ? "encrypt" : "decrypt"]; - let symKey = await lazy.crypto.subtle.importKey( + let symKey = await crypto.subtle.importKey( "raw", symmetricKeyBuffer, algo, diff --git a/services/crypto/modules/jwcrypto.jsm b/services/crypto/modules/jwcrypto.jsm index 05da9978bcc6..f95e9509d862 100644 --- a/services/crypto/modules/jwcrypto.jsm +++ b/services/crypto/modules/jwcrypto.jsm @@ -4,14 +4,6 @@ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const EXPORTED_SYMBOLS = ["jwcrypto"]; const ECDH_PARAMS = { @@ -47,13 +39,10 @@ class JWCrypto { async generateJWE(key, data) { // Generate an ephemeral key to use just for this encryption. // The public component gets embedded in the JWE header. - const epk = await lazy.crypto.subtle.generateKey(ECDH_PARAMS, true, [ + const epk = await crypto.subtle.generateKey(ECDH_PARAMS, true, [ "deriveKey", ]); - const ownPublicJWK = await lazy.crypto.subtle.exportKey( - "jwk", - epk.publicKey - ); + const ownPublicJWK = await crypto.subtle.exportKey("jwk", epk.publicKey); // Remove properties added by our WebCrypto implementation but that aren't typically // used with JWE in the wild. This saves space in the resulting JWE, and makes it easier // to re-import the resulting JWK. @@ -61,7 +50,7 @@ class JWCrypto { delete ownPublicJWK.ext; let header = { alg: "ECDH-ES", enc: "A256GCM", epk: ownPublicJWK }; // Import the peer's public key. - const peerPublicKey = await lazy.crypto.subtle.importKey( + const peerPublicKey = await crypto.subtle.importKey( "jwk", key, ECDH_PARAMS, @@ -81,14 +70,14 @@ class JWCrypto { // Note that the IV is generated randomly, which *in general* is not safe to do with AES-GCM because // it's too short to guarantee uniqueness. But we know that the AES-GCM key itself is unique and will // only be used for this single encryption, making a random IV safe to use for this particular use-case. - let iv = lazy.crypto.getRandomValues(new Uint8Array(AES_GCM_IV_SIZE)); + let iv = crypto.getRandomValues(new Uint8Array(AES_GCM_IV_SIZE)); // Yes, additionalData is the byte representation of the base64 representation of the stringified header. const additionalData = UTF8_ENCODER.encode( ChromeUtils.base64URLEncode(UTF8_ENCODER.encode(JSON.stringify(header)), { pad: false, }) ); - const encrypted = await lazy.crypto.subtle.encrypt( + const encrypted = await crypto.subtle.encrypt( { name: "AES-GCM", iv, @@ -143,7 +132,7 @@ class JWCrypto { if ("apu" in header || "apv" in header) { throw new Error("apu and apv header values are not supported."); } - const peerPublicKey = await lazy.crypto.subtle.importKey( + const peerPublicKey = await crypto.subtle.importKey( "jwk", header.epk, ECDH_PARAMS, @@ -163,7 +152,7 @@ class JWCrypto { ); const bundle = new Uint8Array([...ciphertext, ...authTag]); - const decrypted = await lazy.crypto.subtle.decrypt( + const decrypted = await crypto.subtle.decrypt( { name: "AES-GCM", iv, @@ -190,7 +179,7 @@ class JWCrypto { */ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { const params = { ...ECDH_PARAMS, ...{ public: publicKey } }; - const sharedKey = await lazy.crypto.subtle.deriveKey( + const sharedKey = await crypto.subtle.deriveKey( params, privateKey, AES_PARAMS, @@ -200,7 +189,7 @@ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { // This is the NIST Concat KDF specialized to a specific set of parameters, // which basically turn it into a single application of SHA256. // The details are from the JWA RFC. - let sharedKeyBytes = await lazy.crypto.subtle.exportKey("raw", sharedKey); + let sharedKeyBytes = await crypto.subtle.exportKey("raw", sharedKey); sharedKeyBytes = new Uint8Array(sharedKeyBytes); const info = [ "\x00\x00\x00\x07A256GCM", // 7-byte algorithm identifier @@ -215,13 +204,13 @@ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { const pkcsBuf = Uint8Array.from( Array.prototype.map.call(pkcs, c => c.charCodeAt(0)) ); - const derivedKeyBytes = await lazy.crypto.subtle.digest( + const derivedKeyBytes = await crypto.subtle.digest( { name: "SHA-256", }, pkcsBuf ); - return lazy.crypto.subtle.importKey( + return crypto.subtle.importKey( "raw", derivedKeyBytes, AES_PARAMS, diff --git a/services/crypto/modules/utils.js b/services/crypto/modules/utils.js index 48a82d337b89..47a2cd0dda03 100644 --- a/services/crypto/modules/utils.js +++ b/services/crypto/modules/utils.js @@ -14,7 +14,6 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); XPCOMUtils.defineLazyGetter(lazy, "textEncoder", function() { return new TextEncoder(); @@ -52,7 +51,7 @@ var CryptoUtils = { }, generateRandomBytes(length) { - return lazy.crypto.getRandomValues(new Uint8Array(length)); + return crypto.getRandomValues(new Uint8Array(length)); }, /** @@ -149,14 +148,14 @@ var CryptoUtils = { * @returns {Uint8Array} */ async hmac(alg, key, data) { - const hmacKey = await lazy.crypto.subtle.importKey( + const hmacKey = await crypto.subtle.importKey( "raw", key, { name: "HMAC", hash: alg }, false, ["sign"] ); - const result = await lazy.crypto.subtle.sign("HMAC", hmacKey, data); + const result = await crypto.subtle.sign("HMAC", hmacKey, data); return new Uint8Array(result); }, @@ -168,14 +167,14 @@ var CryptoUtils = { * @returns {Uint8Array} */ async hkdf(ikm, salt, info, len) { - const key = await lazy.crypto.subtle.importKey( + const key = await crypto.subtle.importKey( "raw", ikm, { name: "HKDF" }, false, ["deriveBits"] ); - const okm = await lazy.crypto.subtle.deriveBits( + const okm = await crypto.subtle.deriveBits( { name: "HKDF", hash: "SHA-256", @@ -199,14 +198,14 @@ var CryptoUtils = { async pbkdf2Generate(passphrase, salt, iterations, len) { passphrase = CommonUtils.byteStringToArrayBuffer(passphrase); salt = CommonUtils.byteStringToArrayBuffer(salt); - const key = await lazy.crypto.subtle.importKey( + const key = await crypto.subtle.importKey( "raw", passphrase, { name: "PBKDF2" }, false, ["deriveBits"] ); - const output = await lazy.crypto.subtle.deriveBits( + const output = await crypto.subtle.deriveBits( { name: "PBKDF2", hash: "SHA-256", @@ -473,7 +472,7 @@ var CryptoUtils = { const buffer = lazy.textEncoder.encode( `hawk.1.payload\n${contentType}\n${options.payload}\n` ); - const hash = await lazy.crypto.subtle.digest("SHA-256", buffer); + const hash = await crypto.subtle.digest("SHA-256", buffer); // HAWK specifies this .hash to use +/ (not _-) and include the // trailing "==" padding. artifacts.hash = ChromeUtils.base64URLEncode(hash, { pad: true }) diff --git a/services/fxaccounts/FxAccountsProfileClient.jsm b/services/fxaccounts/FxAccountsProfileClient.jsm index caa18497cb0d..c554699ef58b 100644 --- a/services/fxaccounts/FxAccountsProfileClient.jsm +++ b/services/fxaccounts/FxAccountsProfileClient.jsm @@ -32,13 +32,6 @@ const fxAccounts = getFxAccountsSingleton(); const { RESTRequest } = ChromeUtils.import( "resource://services-common/rest.js" ); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["URL"]); /** * Create a new FxAccountsProfileClient to be able to fetch Firefox Account profile information. @@ -59,7 +52,7 @@ var FxAccountsProfileClient = function(options) { this.fxai = options.fxai || fxAccounts._internal; try { - this.serverURL = new lazy.URL(options.serverURL); + this.serverURL = new URL(options.serverURL); } catch (e) { throw new Error("Invalid 'serverURL'"); } diff --git a/services/settings/Attachments.jsm b/services/settings/Attachments.jsm index 21fab90a8856..5ac6249f6774 100644 --- a/services/settings/Attachments.jsm +++ b/services/settings/Attachments.jsm @@ -13,7 +13,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { Utils: "resource://services-settings/Utils.jsm", }); ChromeUtils.defineModuleGetter(lazy, "OS", "resource://gre/modules/osfile.jsm"); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); class DownloadError extends Error { constructor(url, resp) { @@ -469,7 +468,7 @@ class Downloader { async _readAttachmentDump(attachmentId) { async function fetchResource(resourceUrl) { try { - return await lazy.fetch(resourceUrl); + return await fetch(resourceUrl); } catch (e) { throw new Downloader.DownloadError(resourceUrl); } diff --git a/services/settings/Utils.jsm b/services/settings/Utils.jsm index ce2d04ce92b1..21eacc72b586 100644 --- a/services/settings/Utils.jsm +++ b/services/settings/Utils.jsm @@ -34,8 +34,6 @@ XPCOMUtils.defineLazyServiceGetter( "nsINetworkLinkService" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - // Create a new instance of the ConsoleAPI so we can control the maxLogLevel with a pref. // See LOG_LEVELS in Console.jsm. Common examples: "all", "debug", "info", "warn", "error". XPCOMUtils.defineLazyGetter(lazy, "log", () => { @@ -303,7 +301,7 @@ var Utils = { */ async hasLocalDump(bucket, collection) { try { - await lazy.fetch( + await fetch( `resource://app/defaults/settings/${bucket}/${collection}.json`, { method: "HEAD", @@ -327,7 +325,7 @@ var Utils = { if (!this._dumpStatsInitPromise) { this._dumpStatsInitPromise = (async () => { try { - let res = await lazy.fetch( + let res = await fetch( "resource://app/defaults/settings/last_modified.json" ); this._dumpStats = await res.json(); diff --git a/services/settings/remote-settings.js b/services/settings/remote-settings.js index 350714a9ed2f..97aa802d7703 100644 --- a/services/settings/remote-settings.js +++ b/services/settings/remote-settings.js @@ -34,8 +34,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { RemoteSettingsWorker: "resource://services-settings/RemoteSettingsWorker.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const PREF_SETTINGS_BRANCH = "services.settings."; const PREF_SETTINGS_SERVER_BACKOFF = "server.backoff"; const PREF_SETTINGS_LAST_UPDATE = "last_update_seconds"; diff --git a/services/sync/modules/bookmark_validator.js b/services/sync/modules/bookmark_validator.js index 14ce10da993a..0405ee58caa7 100644 --- a/services/sync/modules/bookmark_validator.js +++ b/services/sync/modules/bookmark_validator.js @@ -32,8 +32,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/PlacesSyncUtils.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["URLSearchParams"]); - var EXPORTED_SYMBOLS = ["BookmarkValidator", "BookmarkProblemData"]; const QUERY_PROTOCOL = "place:"; @@ -48,12 +46,12 @@ function areURLsEqual(a, b) { // Tag queries are special because we rewrite them to point to the // local tag folder ID. It's expected that the folders won't match, // but all other params should. - let aParams = new lazy.URLSearchParams(a.slice(QUERY_PROTOCOL.length)); + let aParams = new URLSearchParams(a.slice(QUERY_PROTOCOL.length)); let aType = +aParams.get("type"); if (aType != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) { return false; } - let bParams = new lazy.URLSearchParams(b.slice(QUERY_PROTOCOL.length)); + let bParams = new URLSearchParams(b.slice(QUERY_PROTOCOL.length)); let bType = +bParams.get("type"); if (bType != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) { return false; @@ -683,7 +681,7 @@ class BookmarkValidator { ) { return; } - let params = new lazy.URLSearchParams( + let params = new URLSearchParams( entry.bmkUri.slice(QUERY_PROTOCOL.length) ); // Queries with `excludeQueries` won't form cycles because they'll diff --git a/services/sync/modules/resource.js b/services/sync/modules/resource.js index 33659c84a3c5..ae86ce596deb 100644 --- a/services/sync/modules/resource.js +++ b/services/sync/modules/resource.js @@ -18,8 +18,6 @@ const { Utils } = ChromeUtils.import("resource://services-sync/util.js"); const { setTimeout, clearTimeout } = ChromeUtils.import( "resource://gre/modules/Timer.jsm" ); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch", "Headers", "Request"]); /* global AbortController */ /* @@ -104,7 +102,7 @@ Resource.prototype = { * @returns {Headers} */ async _buildHeaders(method) { - const headers = new lazy.Headers(this._headers); + const headers = new Headers(this._headers); if (Resource.SEND_VERSION_INFO) { headers.append("user-agent", Utils.userAgent); @@ -168,7 +166,7 @@ Resource.prototype = { this._log.trace(`${method} Body: ${data}`); init.body = data; } - return new lazy.Request(this.uri.spec, init); + return new Request(this.uri.spec, init); }, /** @@ -179,7 +177,7 @@ Resource.prototype = { async _doRequest(method, data = null) { const controller = new AbortController(); const request = await this._createRequest(method, data, controller.signal); - const responsePromise = lazy.fetch(request); // Rejects on network failure. + const responsePromise = fetch(request); // Rejects on network failure. let didTimeout = false; const timeoutId = setTimeout(() => { didTimeout = true; diff --git a/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm b/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm index 3a9c54be8597..6c761bcc10ec 100644 --- a/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm +++ b/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm @@ -21,14 +21,8 @@ const { FxAccountsConfig } = ChromeUtils.import( "resource://gre/modules/FxAccountsConfig.jsm" ); const { Logger } = ChromeUtils.import("resource://tps/logger.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - /** * Helper object for Firefox Accounts authentication */ @@ -98,7 +92,7 @@ var Authentication = { const tries = 10; const normalWait = 2000; for (let i = 0; i < tries; ++i) { - let resp = await lazy.fetch(restmailURI); + let resp = await fetch(restmailURI); let messages = await resp.json(); // Sort so that the most recent emails are first. messages.sort((a, b) => new Date(b.receivedAt) - new Date(a.receivedAt)); @@ -145,7 +139,7 @@ var Authentication = { )}`; try { // Clean up after ourselves. - let deleteResult = await lazy.fetch(restmailURI, { method: "DELETE" }); + let deleteResult = await fetch(restmailURI, { method: "DELETE" }); if (!deleteResult.ok) { Logger.logInfo( `Warning: Got non-success status ${deleteResult.status} when deleting emails` diff --git a/toolkit/components/cleardata/SiteDataTestUtils.jsm b/toolkit/components/cleardata/SiteDataTestUtils.jsm index 81277ac933ce..9741cfc85662 100644 --- a/toolkit/components/cleardata/SiteDataTestUtils.jsm +++ b/toolkit/components/cleardata/SiteDataTestUtils.jsm @@ -23,8 +23,6 @@ XPCOMUtils.defineLazyServiceGetter( "nsIServiceWorkerManager" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["indexedDB"]); - /** * This module assists with tasks around testing functionality that shows * or clears site data. @@ -63,11 +61,7 @@ var SiteDataTestUtils = { let principal = Services.scriptSecurityManager.createContentPrincipalFromOrigin( origin ); - let request = lazy.indexedDB.openForPrincipal( - principal, - "TestDatabase", - 1 - ); + let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1); request.onupgradeneeded = function(e) { let db = e.target.result; db.createObjectStore("TestStore"); @@ -256,11 +250,7 @@ var SiteDataTestUtils = { ); return new Promise(resolve => { let data = true; - let request = lazy.indexedDB.openForPrincipal( - principal, - "TestDatabase", - 1 - ); + let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1); request.onupgradeneeded = function(e) { data = false; }; diff --git a/toolkit/components/extensions/ExtensionCommon.jsm b/toolkit/components/extensions/ExtensionCommon.jsm index 50496643afaa..00c6f7ed48fc 100644 --- a/toolkit/components/extensions/ExtensionCommon.jsm +++ b/toolkit/components/extensions/ExtensionCommon.jsm @@ -25,8 +25,6 @@ const { AppConstants } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyModuleGetters(lazy, { ConsoleAPI: "resource://gre/modules/Console.jsm", PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm", @@ -1394,7 +1392,7 @@ class SchemaAPIManager extends EventEmitter { } async loadModuleJSON(urls) { - let promises = urls.map(url => lazy.fetch(url).then(resp => resp.json())); + let promises = urls.map(url => fetch(url).then(resp => resp.json())); return this.initModuleJSON(await Promise.all(promises)); } diff --git a/toolkit/components/extensions/ExtensionContent.jsm b/toolkit/components/extensions/ExtensionContent.jsm index 10ef689307cf..124dd3fc86ac 100644 --- a/toolkit/components/extensions/ExtensionContent.jsm +++ b/toolkit/components/extensions/ExtensionContent.jsm @@ -48,8 +48,6 @@ const { ExtensionUtils } = ChromeUtils.import( "resource://gre/modules/ExtensionUtils.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const { DefaultMap, DefaultWeakMap, @@ -373,7 +371,7 @@ class Script { } // Store the hash of the cssCode. - const buffer = await lazy.crypto.subtle.digest( + const buffer = await crypto.subtle.digest( "SHA-1", new TextEncoder().encode(cssCode) ); diff --git a/toolkit/components/extensions/ExtensionUtils.jsm b/toolkit/components/extensions/ExtensionUtils.jsm index 47c38a7f4d8f..8eae43d87297 100644 --- a/toolkit/components/extensions/ExtensionUtils.jsm +++ b/toolkit/components/extensions/ExtensionUtils.jsm @@ -20,8 +20,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/Timer.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - // xpcshell doesn't handle idle callbacks well. XPCOMUtils.defineLazyGetter(lazy, "idleTimeout", () => Services.appinfo.name === "XPCShell" ? 500 : undefined @@ -324,7 +322,7 @@ function parseMatchPatterns(patterns, options) { async function makeDataURI(iconUrl) { let response; try { - response = await lazy.fetch(iconUrl); + response = await fetch(iconUrl); } catch (e) { // Failed to fetch, ignore engine's favicon. Cu.reportError(e); diff --git a/toolkit/components/featuregates/FeatureGate.jsm b/toolkit/components/featuregates/FeatureGate.jsm index 5d0204c8d15b..3c8a8b9b927c 100644 --- a/toolkit/components/featuregates/FeatureGate.jsm +++ b/toolkit/components/featuregates/FeatureGate.jsm @@ -17,8 +17,6 @@ ChromeUtils.defineModuleGetter( "resource://featuregates/FeatureGateImplementation.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - var EXPORTED_SYMBOLS = ["FeatureGate"]; XPCOMUtils.defineLazyGetter(lazy, "gFeatureDefinitionsPromise", async () => { @@ -27,7 +25,7 @@ XPCOMUtils.defineLazyGetter(lazy, "gFeatureDefinitionsPromise", async () => { }); async function fetchFeatureDefinitions(url) { - const res = await lazy.fetch(url); + const res = await fetch(url); let definitionsJson = await res.json(); return new Map(Object.entries(definitionsJson)); } diff --git a/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm b/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm index 37434c3afb02..bb47dfefbc35 100644 --- a/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm +++ b/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm @@ -16,7 +16,6 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { ASRouterTargeting: "resource://activity-stream/lib/ASRouterTargeting.jsm", TargetingContext: "resource://messaging-system/targeting/Targeting.jsm", @@ -67,10 +66,9 @@ XPCOMUtils.defineLazyPreferenceGetter( const SCHEMAS = { get NimbusExperiment() { - return lazy - .fetch("resource://nimbus/schemas/NimbusExperiment.schema.json", { - credentials: "omit", - }) + return fetch("resource://nimbus/schemas/NimbusExperiment.schema.json", { + credentials: "omit", + }) .then(rsp => rsp.json()) .then(json => json.definitions.NimbusExperiment); }, @@ -375,9 +373,9 @@ class _RemoteSettingsExperimentLoader { } else if (lazy.NimbusFeatures[featureId].manifest.schema?.uri) { const uri = lazy.NimbusFeatures[featureId].manifest.schema.uri; try { - const schema = await lazy - .fetch(uri, { credentials: "omit" }) - .then(rsp => rsp.json()); + const schema = await fetch(uri, { credentials: "omit" }).then(rsp => + rsp.json() + ); validator = validatorCache[ featureId ] = new lazy.JsonSchema.Validator(schema); diff --git a/toolkit/components/normandy/lib/NormandyApi.jsm b/toolkit/components/normandy/lib/NormandyApi.jsm index 226ed050e73b..0ea744683acf 100644 --- a/toolkit/components/normandy/lib/NormandyApi.jsm +++ b/toolkit/components/normandy/lib/NormandyApi.jsm @@ -5,9 +5,6 @@ "use strict"; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const lazy = {}; @@ -17,8 +14,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/CanonicalJSON.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - var EXPORTED_SYMBOLS = ["NormandyApi"]; const prefs = Services.prefs.getBranch("app.normandy."); @@ -59,7 +54,7 @@ var NormandyApi = { url.searchParams.set(key, data[key]); } } - return lazy.fetch(url.href, { + return fetch(url.href, { method: "get", headers: { Accept: "application/json" }, credentials: "omit", diff --git a/toolkit/components/passwordmgr/LoginRecipes.jsm b/toolkit/components/passwordmgr/LoginRecipes.jsm index 898925d4b197..bea7be6d65aa 100644 --- a/toolkit/components/passwordmgr/LoginRecipes.jsm +++ b/toolkit/components/passwordmgr/LoginRecipes.jsm @@ -28,8 +28,6 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - ChromeUtils.defineModuleGetter( lazy, "LoginHelper", diff --git a/toolkit/components/passwordmgr/PasswordGenerator.jsm b/toolkit/components/passwordmgr/PasswordGenerator.jsm index b08cc5107f0a..b6b4754f303e 100644 --- a/toolkit/components/passwordmgr/PasswordGenerator.jsm +++ b/toolkit/components/passwordmgr/PasswordGenerator.jsm @@ -12,14 +12,6 @@ const EXPORTED_SYMBOLS = ["PasswordGenerator"]; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const DEFAULT_PASSWORD_LENGTH = 15; const MAX_UINT8 = Math.pow(2, 8) - 1; const MAX_UINT32 = Math.pow(2, 32) - 1; @@ -169,7 +161,7 @@ const PasswordGenerator = { const randomValueArr = new Uint8Array(1); do { - lazy.crypto.getRandomValues(randomValueArr); + crypto.getRandomValues(randomValueArr); } while (randomValueArr[0] > MAX_ACCEPTABLE_VALUE); return randomValueArr[0] % range; }, @@ -183,7 +175,7 @@ const PasswordGenerator = { let arr = Array.from(str); // Generate all the random numbers that will be needed. const randomValues = new Uint32Array(arr.length - 1); - lazy.crypto.getRandomValues(randomValues); + crypto.getRandomValues(randomValues); // Fisher-Yates Shuffle // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle diff --git a/toolkit/components/utils/Sampling.jsm b/toolkit/components/utils/Sampling.jsm index 06a75689511b..c27d698dcd99 100644 --- a/toolkit/components/utils/Sampling.jsm +++ b/toolkit/components/utils/Sampling.jsm @@ -4,12 +4,6 @@ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - var EXPORTED_SYMBOLS = ["Sampling"]; const hashBits = 48; @@ -78,7 +72,7 @@ var Sampling = { * @promise A hash of `data`, truncated to the 12 most significant characters. */ async truncatedHash(data) { - const hasher = lazy.crypto.subtle; + const hasher = crypto.subtle; const input = new TextEncoder("utf-8").encode(JSON.stringify(data)); const hash = await hasher.digest("SHA-256", input); // truncate hash to 12 characters (2^48), because the full hash is larger diff --git a/toolkit/modules/Region.jsm b/toolkit/modules/Region.jsm index 9fbc02fa1dd1..3f0564a9c9b3 100644 --- a/toolkit/modules/Region.jsm +++ b/toolkit/modules/Region.jsm @@ -25,8 +25,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { setTimeout: "resource://gre/modules/Timer.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyPreferenceGetter( lazy, "wifiScanningEnabled", @@ -747,10 +745,7 @@ class RegionDetector { async _fetchTimeout(url, opts, timeout) { let controller = new AbortController(); opts.signal = controller.signal; - return Promise.race([ - lazy.fetch(url, opts), - this._timeout(timeout, controller), - ]); + return Promise.race([fetch(url, opts), this._timeout(timeout, controller)]); } /** diff --git a/toolkit/modules/UpdateUtils.jsm b/toolkit/modules/UpdateUtils.jsm index 74522d3f8b09..5257a5dcec0b 100644 --- a/toolkit/modules/UpdateUtils.jsm +++ b/toolkit/modules/UpdateUtils.jsm @@ -22,8 +22,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { "resource://gre/modules/components-utils/WindowsVersionInfo.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const PER_INSTALLATION_PREFS_PLATFORMS = ["win"]; // The file that stores Application Update configuration settings. The file is @@ -131,7 +129,7 @@ var UpdateUtils = { const url = "resource://" + res + "/" + FILE_UPDATE_LOCALE; let data; try { - data = await lazy.fetch(url); + data = await fetch(url); } catch (e) { continue; } diff --git a/toolkit/mozapps/extensions/internal/XPIInstall.jsm b/toolkit/mozapps/extensions/internal/XPIInstall.jsm index ae9a7a56f6d4..5140c1b4175a 100644 --- a/toolkit/mozapps/extensions/internal/XPIInstall.jsm +++ b/toolkit/mozapps/extensions/internal/XPIInstall.jsm @@ -35,7 +35,6 @@ const { AddonManager, AddonManagerPrivate } = ChromeUtils.import( ); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", @@ -337,7 +336,7 @@ XPIPackage = class XPIPackage extends Package { } async readBinary(...path) { - let response = await lazy.fetch(this.rootURI.resolve(path.join("/"))); + let response = await fetch(this.rootURI.resolve(path.join("/"))); return response.arrayBuffer(); } @@ -388,7 +387,7 @@ function builtinPackage(baseURL) { }, async hasResource(path) { try { - let response = await lazy.fetch(this.rootURI.resolve(path)); + let response = await fetch(this.rootURI.resolve(path)); return response.ok; } catch (e) { return false; From a3795d271375384513ef7c049134d61c5aa957ad Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:54:49 +0000 Subject: [PATCH 10/64] Bug 1773390 - Remove CommonJS "require" support from AndroidLog.jsm. r=agi Differential Revision: https://phabricator.services.mozilla.com/D149343 --- mobile/android/modules/geckoview/AndroidLog.jsm | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/mobile/android/modules/geckoview/AndroidLog.jsm b/mobile/android/modules/geckoview/AndroidLog.jsm index 7fc07b8ca3d5..fb397a21774e 100644 --- a/mobile/android/modules/geckoview/AndroidLog.jsm +++ b/mobile/android/modules/geckoview/AndroidLog.jsm @@ -13,10 +13,6 @@ * let Log = ChromeUtils.import("resource://gre/modules/AndroidLog.jsm") * .AndroidLog; * - * // Or require it in a chrome worker: - * importScripts("resource://gre/modules/workers/require.js"); - * let Log = require("resource://gre/modules/AndroidLog.jsm"); - * * // Use Log.i, Log.v, Log.d, Log.w, and Log.e to log verbose, debug, info, * // warning, and error messages, respectively. * Log.v("MyModule", "This is a verbose message."); @@ -40,14 +36,8 @@ * truncates tags longer than MAX_TAG_LENGTH characters (not including "Gecko"). */ -if (typeof Components != "undefined") { - // Specify exported symbols for JSM module loader. - // - // (bug 1773390) - // eslint-disable-next-line mozilla/reject-global-this - this.EXPORTED_SYMBOLS = ["AndroidLog"]; - var { ctypes } = ChromeUtils.import("resource://gre/modules/ctypes.jsm"); -} +const EXPORTED_SYMBOLS = ["AndroidLog"]; +const { ctypes } = ChromeUtils.import("resource://gre/modules/ctypes.jsm"); // From . const ANDROID_LOG_VERBOSE = 2; From 46b3c38fe4d35daa993c99e093808d7e995e35bd Mon Sep 17 00:00:00 2001 From: Jed Davis Date: Wed, 15 Jun 2022 20:55:23 +0000 Subject: [PATCH 11/64] Bug 1770905 - Add a validity check to the profiler's use of IPC Shmem. r=gerald If the child process failed to allocate Shmem (and this isn't a debug build, where that would cause an assertion failure) when sending profiling data back to the parent process, it will send an invalid Shmem and the parent process should not try to use it. Currently it does do that, and tries to construct an nsACString with length `(size_t)-1`, which fails a release assertion in the XPCOM string library and crashes the browser. With this patch, we'll simply fail to profile the affected process. Differential Revision: https://phabricator.services.mozilla.com/D148468 --- tools/profiler/gecko/nsProfiler.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tools/profiler/gecko/nsProfiler.cpp b/tools/profiler/gecko/nsProfiler.cpp index ada402bd9e30..0562226d4990 100644 --- a/tools/profiler/gecko/nsProfiler.cpp +++ b/tools/profiler/gecko/nsProfiler.cpp @@ -1121,9 +1121,15 @@ RefPtr nsProfiler::StartGathering( unsigned(childPid), unsigned(aResult.Size()), unsigned(self->mPendingProfiles.length()), pendingProfile ? "including" : "excluding", unsigned(childPid)); - const nsDependentCSubstring profileString(aResult.get(), - aResult.Size() - 1); - self->GatheredOOPProfile(childPid, profileString); + if (aResult.IsReadable()) { + const nsDependentCSubstring profileString( + aResult.get(), aResult.Size() - 1); + self->GatheredOOPProfile(childPid, profileString); + } else { + // This can happen if the child failed to allocate + // the Shmem (or maliciously sent an invalid Shmem). + self->GatheredOOPProfile(childPid, ""_ns); + } }, [self = RefPtr(this), childPid = profile.childPid](ipc::ResponseRejectReason&& aReason) { From c4d1df3cf79a264631b6809814f8607bc161378a Mon Sep 17 00:00:00 2001 From: Jed Davis Date: Wed, 15 Jun 2022 20:55:23 +0000 Subject: [PATCH 12/64] Bug 1770905 - Quietly reject `readlink` in the Linux GeckoMediaPlugin sandbox. r=gcp The profiler may try to readlink `/proc/self/exe` to determine the executable name; currently, its attempt to get information about loaded objects is broken for other reasons, so this isn't helpful. Thus, this patch has it fail with `EINVAL` (meaning "not a symbolic link) instead of being treated as unexpected. (In the future, if we need to, we could simulate that syscall by recording the target of `/proc/self/exe` before sandboxing, and recognizing that specific case in a trap function.) Differential Revision: https://phabricator.services.mozilla.com/D148469 --- .../sandbox/common/test/SandboxTestingChildTests.h | 6 ++++++ security/sandbox/linux/SandboxFilter.cpp | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/security/sandbox/common/test/SandboxTestingChildTests.h b/security/sandbox/common/test/SandboxTestingChildTests.h index ea32637bd14f..ef73026cf51a 100644 --- a/security/sandbox/common/test/SandboxTestingChildTests.h +++ b/security/sandbox/common/test/SandboxTestingChildTests.h @@ -680,6 +680,12 @@ void RunTestsGMPlugin(SandboxTestingChild* child) { return fd; }); } + + child->ErrnoValueTest("readlink_exe"_ns, EINVAL, [] { + char pathBuf[PATH_MAX]; + return readlink("/proc/self/exe", pathBuf, sizeof(pathBuf)); + }); + # elif XP_MACOSX // XP_LINUX RunMacTestLaunchProcess(child); /* The Mac GMP process requires access to the window server */ diff --git a/security/sandbox/linux/SandboxFilter.cpp b/security/sandbox/linux/SandboxFilter.cpp index 66b4b9eaaafb..279bc73e8f5f 100644 --- a/security/sandbox/linux/SandboxFilter.cpp +++ b/security/sandbox/linux/SandboxFilter.cpp @@ -1769,6 +1769,16 @@ class GMPSandboxPolicy : public SandboxPolicyCommon { .Else(Error(ENOSYS)); } + // The profiler will try to readlink /proc/self/exe for native + // stackwalking, but that's broken for several other reasons; + // see discussion in bug 1770905. (That can be emulated by + // pre-recording the result if/when we need it.) +#ifdef __NR_readlink + case __NR_readlink: +#endif + case __NR_readlinkat: + return Error(EINVAL); + default: return SandboxPolicyCommon::EvaluateSyscall(sysno); } From c807158580e722b7657e438bf2bae275e9e6c489 Mon Sep 17 00:00:00 2001 From: Jed Davis Date: Wed, 15 Jun 2022 20:55:24 +0000 Subject: [PATCH 13/64] Bug 1770905 - Allow GeckoMediaPlugin processes on Linux to be profiled if memfd_create is available. r=gcp,mstange,media-playback-reviewers,padenot There are two parts to this patch; both affect only Linux: 1. The GMP sandbox policy is adjusted to allow certain syscalls used in shared memory creation (ftruncate and fallocate). However, the file broker is not used; the process still has no access to files in /dev/shm. 2. The profiler is not initialized for GMP processes unless memfd_create is available (so the process can create shared memory to send profiling data back, without filesystem access), or the GMP sandbox is disabled (either at runtime or build time). As of this patch, profiling GMP processes on Linux should succeed on distros with kernel >=3.17 (Oct. 2014), but native stack frames won't have symbols (and may be incorrectly unwound, not that it matters much without symbols); see the bug for more info. Pseudo-stack frames and markers should work, however. Differential Revision: https://phabricator.services.mozilla.com/D148470 --- dom/media/gmp/GMPParent.cpp | 32 +++++++++++++------ ipc/chromium/src/base/shared_memory.h | 2 ++ ipc/chromium/src/base/shared_memory_posix.cc | 12 +++++++ .../common/test/SandboxTestingChildTests.h | 17 ++++++++++ security/sandbox/linux/SandboxFilter.cpp | 8 +++-- 5 files changed, 59 insertions(+), 12 deletions(-) diff --git a/dom/media/gmp/GMPParent.cpp b/dom/media/gmp/GMPParent.cpp index ef601ebb6ee4..8982c1603cd3 100644 --- a/dom/media/gmp/GMPParent.cpp +++ b/dom/media/gmp/GMPParent.cpp @@ -20,6 +20,7 @@ #include "mozilla/ipc/GeckoChildProcessHost.h" #if defined(XP_LINUX) && defined(MOZ_SANDBOX) # include "mozilla/SandboxInfo.h" +# include "base/shared_memory.h" #endif #include "mozilla/Services.h" #include "mozilla/SSE.h" @@ -261,19 +262,30 @@ class NotifyGMPProcessLoadedTask : public Runnable { NS_IMETHOD Run() override { MOZ_ASSERT(NS_IsMainThread()); - nsCOMPtr gmpEventTarget = - mGMPParent->GMPEventTarget(); - if (!gmpEventTarget) { - return NS_ERROR_FAILURE; + bool canProfile = true; + +#if defined(XP_LINUX) && defined(MOZ_SANDBOX) + if (SandboxInfo::Get().Test(SandboxInfo::kEnabledForMedia) && + base::SharedMemory::UsingPosixShm()) { + canProfile = false; } +#endif - ipc::Endpoint profilerParent( - ProfilerParent::CreateForProcess(mProcessId)); + if (canProfile) { + nsCOMPtr gmpEventTarget = + mGMPParent->GMPEventTarget(); + if (!gmpEventTarget) { + return NS_ERROR_FAILURE; + } - gmpEventTarget->Dispatch( - NewRunnableMethod&&>( - "GMPParent::SendInitProfiler", mGMPParent, - &GMPParent::SendInitProfiler, std::move(profilerParent))); + ipc::Endpoint profilerParent( + ProfilerParent::CreateForProcess(mProcessId)); + + gmpEventTarget->Dispatch( + NewRunnableMethod&&>( + "GMPParent::SendInitProfiler", mGMPParent, + &GMPParent::SendInitProfiler, std::move(profilerParent))); + } return NS_OK; } diff --git a/ipc/chromium/src/base/shared_memory.h b/ipc/chromium/src/base/shared_memory.h index 841dc62d3f81..ec3f9fc25972 100644 --- a/ipc/chromium/src/base/shared_memory.h +++ b/ipc/chromium/src/base/shared_memory.h @@ -155,6 +155,8 @@ class SharedMemory { // pid to the given string and return true. If not, return false. // (This is public so that the Linux sandboxing code can use it.) static bool AppendPosixShmPrefix(std::string* str, pid_t pid); + // Similar, but simply returns whether POSIX shm is in use. + static bool UsingPosixShm(); #endif private: diff --git a/ipc/chromium/src/base/shared_memory_posix.cc b/ipc/chromium/src/base/shared_memory_posix.cc index 805f9ebf96c0..d795db6f1cb0 100644 --- a/ipc/chromium/src/base/shared_memory_posix.cc +++ b/ipc/chromium/src/base/shared_memory_posix.cc @@ -81,6 +81,13 @@ bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) { // static SharedMemoryHandle SharedMemory::NULLHandle() { return nullptr; } +// static +bool SharedMemory::UsingPosixShm() { + // Undocumented feature of AppendPosixShmPrefix to reduce code + // duplication: if the string pointer is null, it's ignored. + return AppendPosixShmPrefix(nullptr, 0); +} + #ifdef ANDROID // Android has its own shared memory API, ashmem. It doesn't support @@ -88,6 +95,7 @@ SharedMemoryHandle SharedMemory::NULLHandle() { return nullptr; } // because its SELinux policy prevents the procfs operations we'd use // (see bug 1670277 for more details). +// static bool SharedMemory::AppendPosixShmPrefix(std::string* str, pid_t pid) { return false; } @@ -262,6 +270,10 @@ bool SharedMemory::AppendPosixShmPrefix(std::string* str, pid_t pid) { if (HaveMemfd()) { return false; } + // See also UsingPosixShm(). + if (!str) { + return true; + } *str += '/'; # ifdef MOZ_WIDGET_GTK // The Snap package environment doesn't provide a private /dev/shm diff --git a/security/sandbox/common/test/SandboxTestingChildTests.h b/security/sandbox/common/test/SandboxTestingChildTests.h index ef73026cf51a..9f94aa7d24d0 100644 --- a/security/sandbox/common/test/SandboxTestingChildTests.h +++ b/security/sandbox/common/test/SandboxTestingChildTests.h @@ -686,6 +686,23 @@ void RunTestsGMPlugin(SandboxTestingChild* child) { return readlink("/proc/self/exe", pathBuf, sizeof(pathBuf)); }); + child->ErrnoTest("memfd_sizing"_ns, true, [] { + int fd = syscall(__NR_memfd_create, "sandbox-test", 0); + if (fd < 0) { + if (errno == ENOSYS) { + // Don't fail the test if the kernel is old. + return 0; + } + return -1; + } + + int rv = ftruncate(fd, 4096); + int savedErrno = errno; + close(fd); + errno = savedErrno; + return rv; + }); + # elif XP_MACOSX // XP_LINUX RunMacTestLaunchProcess(child); /* The Mac GMP process requires access to the window server */ diff --git a/security/sandbox/linux/SandboxFilter.cpp b/security/sandbox/linux/SandboxFilter.cpp index 279bc73e8f5f..cbb2581db1da 100644 --- a/security/sandbox/linux/SandboxFilter.cpp +++ b/security/sandbox/linux/SandboxFilter.cpp @@ -1715,8 +1715,12 @@ class GMPSandboxPolicy : public SandboxPolicyCommon { const SandboxOpenedFiles* mFiles; public: - explicit GMPSandboxPolicy(const SandboxOpenedFiles* aFiles) - : mFiles(aFiles) {} + explicit GMPSandboxPolicy(const SandboxOpenedFiles* aFiles) : mFiles(aFiles) { + // Used by the profiler to send data back to the parent process; + // we are not enabling the file broker, so this will only work if + // memfd_create is available. + mMayCreateShmem = true; + } ~GMPSandboxPolicy() override = default; From 19b957d4dcda039a7e05c8a3377e6a0c9447c118 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:22 +0000 Subject: [PATCH 14/64] Bug 1773829 - Part 2: Stop using lazy getter unnecessarily in browser/components/newtab/. r=thecount Depends on D149010 Differential Revision: https://phabricator.services.mozilla.com/D149011 --- .../components/newtab/lib/ASRouterTargeting.jsm | 16 ++++++++++------ .../newtab/lib/ActivityStreamStorage.jsm | 3 ++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/browser/components/newtab/lib/ASRouterTargeting.jsm b/browser/components/newtab/lib/ASRouterTargeting.jsm index e9982b3dd613..fd909c2bcf3d 100644 --- a/browser/components/newtab/lib/ASRouterTargeting.jsm +++ b/browser/components/newtab/lib/ASRouterTargeting.jsm @@ -13,6 +13,12 @@ const { XPCOMUtils } = ChromeUtils.import( const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { NewTabUtils } = ChromeUtils.import( + "resource://gre/modules/NewTabUtils.jsm" +); +const { ShellService } = ChromeUtils.import( + "resource:///modules/ShellService.jsm" +); const lazy = {}; @@ -20,9 +26,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { ASRouterPreferences: "resource://activity-stream/lib/ASRouterPreferences.jsm", AddonManager: "resource://gre/modules/AddonManager.jsm", ClientEnvironment: "resource://normandy/lib/ClientEnvironment.jsm", - NewTabUtils: "resource://gre/modules/NewTabUtils.jsm", ProfileAge: "resource://gre/modules/ProfileAge.jsm", - ShellService: "resource:///modules/ShellService.jsm", TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.jsm", AttributionCode: "resource:///modules/AttributionCode.jsm", TargetingContext: "resource://messaging-system/targeting/Targeting.jsm", @@ -116,7 +120,7 @@ XPCOMUtils.defineLazyServiceGetters(lazy, { const FXA_USERNAME_PREF = "services.sync.username"; -const { activityStreamProvider: asProvider } = lazy.NewTabUtils; +const { activityStreamProvider: asProvider } = NewTabUtils; const FXA_ATTACHED_CLIENTS_UPDATE_INTERVAL = 4 * 60 * 60 * 1000; // Four hours const FRECENT_SITES_UPDATE_INTERVAL = 6 * 60 * 60 * 1000; // Six hours @@ -265,7 +269,7 @@ const QueryCache = { "doesAppNeedPin", null, FRECENT_SITES_UPDATE_INTERVAL, - lazy.ShellService + ShellService ), }, }; @@ -477,7 +481,7 @@ const TargetingGetters = { }, get isDefaultBrowser() { try { - return lazy.ShellService.isDefaultBrowser(); + return ShellService.isDefaultBrowser(); } catch (e) {} return null; }, @@ -498,7 +502,7 @@ const TargetingGetters = { return QueryCache.queries.RecentBookmarks.get(); }, get pinnedSites() { - return lazy.NewTabUtils.pinnedLinks.links.map(site => + return NewTabUtils.pinnedLinks.links.map(site => site ? { url: site.url, diff --git a/browser/components/newtab/lib/ActivityStreamStorage.jsm b/browser/components/newtab/lib/ActivityStreamStorage.jsm index 34b88bc6ca26..807ec8de86a2 100644 --- a/browser/components/newtab/lib/ActivityStreamStorage.jsm +++ b/browser/components/newtab/lib/ActivityStreamStorage.jsm @@ -1,8 +1,9 @@ -const lazy = {}; /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ +const lazy = {}; + ChromeUtils.defineModuleGetter( lazy, "IndexedDB", From 06dc9a6dfac2c8b33d16ba43b58b97727e24ca5e Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:23 +0000 Subject: [PATCH 15/64] Bug 1773829 - Part 3: Stop using lazy getter unnecessarily in browser/components/. r=MattN Depends on D149011 Differential Revision: https://phabricator.services.mozilla.com/D149012 --- .../aboutlogins/AboutLoginsParent.jsm | 7 +-- .../migration/360seMigrationUtils.jsm | 12 ++--- .../migration/ChromeProfileMigrator.jsm | 7 ++- .../components/migration/MSMigrationUtils.jsm | 54 +++++++++---------- .../components/pagedata/PageDataService.jsm | 6 ++- .../components/places/SnapshotSelector.jsm | 6 ++- .../components/sessionstore/SessionStore.jsm | 6 ++- 7 files changed, 52 insertions(+), 46 deletions(-) diff --git a/browser/components/aboutlogins/AboutLoginsParent.jsm b/browser/components/aboutlogins/AboutLoginsParent.jsm index c01ec27f21bb..7f37ce01f062 100644 --- a/browser/components/aboutlogins/AboutLoginsParent.jsm +++ b/browser/components/aboutlogins/AboutLoginsParent.jsm @@ -17,11 +17,13 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { E10SUtils } = ChromeUtils.import( + "resource://gre/modules/E10SUtils.jsm" +); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - E10SUtils: "resource://gre/modules/E10SUtils.jsm", LoginBreaches: "resource:///modules/LoginBreaches.jsm", LoginHelper: "resource://gre/modules/LoginHelper.jsm", LoginExport: "resource://gre/modules/LoginExport.jsm", @@ -69,8 +71,7 @@ const PRIMARY_PASSWORD_NOTIFICATION_ID = "primary-password-login-required"; // about:logins will always use the privileged content process, // even if it is disabled for other consumers such as about:newtab. -const EXPECTED_ABOUTLOGINS_REMOTE_TYPE = - lazy.E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE; +const EXPECTED_ABOUTLOGINS_REMOTE_TYPE = E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE; let _gPasswordRemaskTimeout = null; const convertSubjectToLogin = subject => { subject.QueryInterface(Ci.nsILoginMetaInfo).QueryInterface(Ci.nsILoginInfo); diff --git a/browser/components/migration/360seMigrationUtils.jsm b/browser/components/migration/360seMigrationUtils.jsm index d4a3883a6897..2b3c67679e22 100644 --- a/browser/components/migration/360seMigrationUtils.jsm +++ b/browser/components/migration/360seMigrationUtils.jsm @@ -9,9 +9,12 @@ var EXPORTED_SYMBOLS = ["Qihoo360seMigrationUtils"]; const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { MigrationUtils } = ChromeUtils.import( + "resource:///modules/MigrationUtils.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - MigrationUtils: "resource:///modules/MigrationUtils.jsm", PlacesUIUtils: "resource:///modules/PlacesUIUtils.jsm", PlacesUtils: "resource://gre/modules/PlacesUtils.jsm", Sqlite: "resource://gre/modules/Sqlite.jsm", @@ -32,7 +35,7 @@ function Bookmarks(aProfileFolder) { this._file = file; } Bookmarks.prototype = { - type: lazy.MigrationUtils.resourceTypes.BOOKMARKS, + type: MigrationUtils.resourceTypes.BOOKMARKS, get exists() { return this._file.exists() && this._file.isReadable(); @@ -105,10 +108,7 @@ Bookmarks.prototype = { if (toolbarBMs.length) { let parentGuid = lazy.PlacesUtils.bookmarks.toolbarGuid; - await lazy.MigrationUtils.insertManyBookmarksWrapper( - toolbarBMs, - parentGuid - ); + await MigrationUtils.insertManyBookmarksWrapper(toolbarBMs, parentGuid); lazy.PlacesUIUtils.maybeToggleBookmarkToolbarVisibilityAfterMigration(); } })().then( diff --git a/browser/components/migration/ChromeProfileMigrator.jsm b/browser/components/migration/ChromeProfileMigrator.jsm index 5e0d003e4ffe..59626aded194 100644 --- a/browser/components/migration/ChromeProfileMigrator.jsm +++ b/browser/components/migration/ChromeProfileMigrator.jsm @@ -19,10 +19,13 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { MigratorPrototype } = ChromeUtils.import( + "resource:///modules/MigrationUtils.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { ChromeMigrationUtils: "resource:///modules/ChromeMigrationUtils.jsm", - MigratorPrototype: "resource:///modules/MigrationUtils.jsm", MigrationUtils: "resource:///modules/MigrationUtils.jsm", NetUtil: "resource://gre/modules/NetUtil.jsm", OS: "resource://gre/modules/osfile.jsm", @@ -76,7 +79,7 @@ function ChromeProfileMigrator() { this._chromeUserDataPathSuffix = "Chrome"; } -ChromeProfileMigrator.prototype = Object.create(lazy.MigratorPrototype); +ChromeProfileMigrator.prototype = Object.create(MigratorPrototype); ChromeProfileMigrator.prototype._keychainServiceName = "Chrome Safe Storage"; ChromeProfileMigrator.prototype._keychainAccountName = "Chrome"; diff --git a/browser/components/migration/MSMigrationUtils.jsm b/browser/components/migration/MSMigrationUtils.jsm index aa6e28ef9f04..0427a37b714e 100644 --- a/browser/components/migration/MSMigrationUtils.jsm +++ b/browser/components/migration/MSMigrationUtils.jsm @@ -31,11 +31,7 @@ ChromeUtils.defineModuleGetter( "WindowsRegistry", "resource://gre/modules/WindowsRegistry.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "ctypes", - "resource://gre/modules/ctypes.jsm" -); +const { ctypes } = ChromeUtils.import("resource://gre/modules/ctypes.jsm"); const EDGE_COOKIE_PATH_OPTIONS = ["", "#!001\\", "#!002\\"]; const EDGE_COOKIES_SUFFIX = "MicrosoftEdge\\Cookies"; @@ -57,15 +53,15 @@ const WEB_CREDENTIALS_VAULT_ID = [ ]; const wintypes = { - BOOL: lazy.ctypes.int, - DWORD: lazy.ctypes.uint32_t, - DWORDLONG: lazy.ctypes.uint64_t, - CHAR: lazy.ctypes.char, - PCHAR: lazy.ctypes.char.ptr, - LPCWSTR: lazy.ctypes.char16_t.ptr, - PDWORD: lazy.ctypes.uint32_t.ptr, - VOIDP: lazy.ctypes.voidptr_t, - WORD: lazy.ctypes.uint16_t, + BOOL: ctypes.int, + DWORD: ctypes.uint32_t, + DWORDLONG: ctypes.uint64_t, + CHAR: ctypes.char, + PCHAR: ctypes.char.ptr, + LPCWSTR: ctypes.char16_t.ptr, + PDWORD: ctypes.uint32_t.ptr, + VOIDP: ctypes.voidptr_t, + WORD: ctypes.uint16_t, }; // TODO: Bug 1202978 - Refactor MSMigrationUtils ctypes helpers @@ -74,7 +70,7 @@ function CtypesKernelHelpers() { this._functions = {}; this._libs = {}; - this._structs.SYSTEMTIME = new lazy.ctypes.StructType("SYSTEMTIME", [ + this._structs.SYSTEMTIME = new ctypes.StructType("SYSTEMTIME", [ { wYear: wintypes.WORD }, { wMonth: wintypes.WORD }, { wDayOfWeek: wintypes.WORD }, @@ -85,17 +81,17 @@ function CtypesKernelHelpers() { { wMilliseconds: wintypes.WORD }, ]); - this._structs.FILETIME = new lazy.ctypes.StructType("FILETIME", [ + this._structs.FILETIME = new ctypes.StructType("FILETIME", [ { dwLowDateTime: wintypes.DWORD }, { dwHighDateTime: wintypes.DWORD }, ]); try { - this._libs.kernel32 = lazy.ctypes.open("Kernel32"); + this._libs.kernel32 = ctypes.open("Kernel32"); this._functions.FileTimeToSystemTime = this._libs.kernel32.declare( "FileTimeToSystemTime", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.BOOL, this._structs.FILETIME.ptr, this._structs.SYSTEMTIME.ptr @@ -142,7 +138,7 @@ CtypesKernelHelpers.prototype = { systemTime.address() ); if (result == 0) { - throw new Error(lazy.ctypes.winLastError); + throw new Error(ctypes.winLastError); } // System time is in UTC, so we use Date.UTC to get milliseconds from epoch, @@ -165,11 +161,11 @@ function CtypesVaultHelpers() { this._structs = {}; this._functions = {}; - this._structs.GUID = new lazy.ctypes.StructType("GUID", [ + this._structs.GUID = new ctypes.StructType("GUID", [ { id: wintypes.DWORD.array(4) }, ]); - this._structs.VAULT_ITEM_ELEMENT = new lazy.ctypes.StructType( + this._structs.VAULT_ITEM_ELEMENT = new ctypes.StructType( "VAULT_ITEM_ELEMENT", [ // not documented @@ -187,7 +183,7 @@ function CtypesVaultHelpers() { ] ); - this._structs.VAULT_ELEMENT = new lazy.ctypes.StructType("VAULT_ELEMENT", [ + this._structs.VAULT_ELEMENT = new ctypes.StructType("VAULT_ELEMENT", [ // vault item schemaId { schemaId: this._structs.GUID }, // a pointer to the name of the browser VAULT_ITEM_ELEMENT @@ -212,11 +208,11 @@ function CtypesVaultHelpers() { ]); try { - this._vaultcliLib = lazy.ctypes.open("vaultcli.dll"); + this._vaultcliLib = ctypes.open("vaultcli.dll"); this._functions.VaultOpenVault = this._vaultcliLib.declare( "VaultOpenVault", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, // GUID this._structs.GUID.ptr, @@ -227,7 +223,7 @@ function CtypesVaultHelpers() { ); this._functions.VaultEnumerateItems = this._vaultcliLib.declare( "VaultEnumerateItems", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, // Vault Handle wintypes.VOIDP, @@ -236,18 +232,18 @@ function CtypesVaultHelpers() { // Items Count wintypes.PDWORD, // Items - lazy.ctypes.voidptr_t + ctypes.voidptr_t ); this._functions.VaultCloseVault = this._vaultcliLib.declare( "VaultCloseVault", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, // Vault Handle wintypes.VOIDP ); this._functions.VaultGetItem = this._vaultcliLib.declare( "VaultGetItem", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, // Vault Handle wintypes.VOIDP, @@ -268,7 +264,7 @@ function CtypesVaultHelpers() { ); this._functions.VaultFree = this._vaultcliLib.declare( "VaultFree", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, // Memory this._structs.VAULT_ELEMENT.ptr diff --git a/browser/components/pagedata/PageDataService.jsm b/browser/components/pagedata/PageDataService.jsm index 487c955288e5..e70e04505fb5 100644 --- a/browser/components/pagedata/PageDataService.jsm +++ b/browser/components/pagedata/PageDataService.jsm @@ -10,13 +10,15 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { EventEmitter } = ChromeUtils.import( + "resource://gre/modules/EventEmitter.jsm" +); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm", E10SUtils: "resource://gre/modules/E10SUtils.jsm", - EventEmitter: "resource://gre/modules/EventEmitter.jsm", HiddenFrame: "resource://gre/modules/HiddenFrame.jsm", PromiseUtils: "resource://gre/modules/PromiseUtils.jsm", }); @@ -270,7 +272,7 @@ class PageDataCache { * the format defined by the schemas at `browser/components/pagedata/schemas`. */ -const PageDataService = new (class PageDataService extends lazy.EventEmitter { +const PageDataService = new (class PageDataService extends EventEmitter { /** * Caches page data discovered from browsers. * diff --git a/browser/components/places/SnapshotSelector.jsm b/browser/components/places/SnapshotSelector.jsm index bab5eca3b8d1..2afc1d5f61e5 100644 --- a/browser/components/places/SnapshotSelector.jsm +++ b/browser/components/places/SnapshotSelector.jsm @@ -7,11 +7,13 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { EventEmitter } = ChromeUtils.import( + "resource://gre/modules/EventEmitter.jsm" +); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - EventEmitter: "resource://gre/modules/EventEmitter.jsm", DeferredTask: "resource://gre/modules/DeferredTask.jsm", FilterAdult: "resource://activity-stream/lib/FilterAdult.jsm", PlacesUIUtils: "resource:///modules/PlacesUIUtils.jsm", @@ -75,7 +77,7 @@ XPCOMUtils.defineLazyGetter(lazy, "logConsole", function() { * This component is intentionally decoupled from where the context comes from * so it can be unit tested. */ -class SnapshotSelector extends lazy.EventEmitter { +class SnapshotSelector extends EventEmitter { /** * All of the active selectors. */ diff --git a/browser/components/sessionstore/SessionStore.jsm b/browser/components/sessionstore/SessionStore.jsm index d712cb4ef180..94edaf6eebef 100644 --- a/browser/components/sessionstore/SessionStore.jsm +++ b/browser/components/sessionstore/SessionStore.jsm @@ -230,6 +230,9 @@ const { XPCOMUtils } = ChromeUtils.import( const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { GlobalState } = ChromeUtils.import( + "resource:///modules/sessionstore/GlobalState.jsm" +); const lazy = {}; @@ -248,7 +251,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm", DevToolsShim: "chrome://devtools-startup/content/DevToolsShim.jsm", E10SUtils: "resource://gre/modules/E10SUtils.jsm", - GlobalState: "resource:///modules/sessionstore/GlobalState.jsm", HomePage: "resource:///modules/HomePage.jsm", PrivacyFilter: "resource://gre/modules/sessionstore/PrivacyFilter.jsm", PromiseUtils: "resource://gre/modules/PromiseUtils.jsm", @@ -606,7 +608,7 @@ var SessionStoreInternal = { "nsISupportsWeakReference", ]), - _globalState: new lazy.GlobalState(), + _globalState: new GlobalState(), // A counter to be used to generate a unique ID for each closed tab or window. _nextClosedId: 0, From f791fe2d2d7b5aec90baa4a95c945006b81f0fe0 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:23 +0000 Subject: [PATCH 16/64] Bug 1773829 - Part 5: Stop using lazy getter unnecessarily in mobile/. r=agi,calu Depends on D149013 Differential Revision: https://phabricator.services.mozilla.com/D149014 --- .../modules/geckoview/GeckoViewUtils.jsm | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/mobile/android/modules/geckoview/GeckoViewUtils.jsm b/mobile/android/modules/geckoview/GeckoViewUtils.jsm index 3f85114ad1ab..1ac64cfee0b5 100644 --- a/mobile/android/modules/geckoview/GeckoViewUtils.jsm +++ b/mobile/android/modules/geckoview/GeckoViewUtils.jsm @@ -7,13 +7,13 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { AndroidLog: "resource://gre/modules/AndroidLog.jsm", EventDispatcher: "resource://gre/modules/Messaging.jsm", - Log: "resource://gre/modules/Log.jsm", }); var EXPORTED_SYMBOLS = ["GeckoViewUtils"]; @@ -22,7 +22,7 @@ var EXPORTED_SYMBOLS = ["GeckoViewUtils"]; * A formatter that does not prepend time/name/level information to messages, * because those fields are logged separately when using the Android logger. */ -class AndroidFormatter extends lazy.Log.BasicFormatter { +class AndroidFormatter extends Log.BasicFormatter { format(message) { return this.formatText(message); } @@ -32,20 +32,20 @@ class AndroidFormatter extends lazy.Log.BasicFormatter { * AndroidAppender * Logs to Android logcat using AndroidLog.jsm */ -class AndroidAppender extends lazy.Log.Appender { +class AndroidAppender extends Log.Appender { constructor(aFormatter) { super(aFormatter || new AndroidFormatter()); this._name = "AndroidAppender"; // Map log level to AndroidLog.foo method. this._mapping = { - [lazy.Log.Level.Fatal]: "e", - [lazy.Log.Level.Error]: "e", - [lazy.Log.Level.Warn]: "w", - [lazy.Log.Level.Info]: "i", - [lazy.Log.Level.Config]: "d", - [lazy.Log.Level.Debug]: "d", - [lazy.Log.Level.Trace]: "v", + [Log.Level.Fatal]: "e", + [Log.Level.Error]: "e", + [Log.Level.Warn]: "w", + [Log.Level.Info]: "i", + [Log.Level.Config]: "d", + [Log.Level.Debug]: "d", + [Log.Level.Trace]: "v", }; } @@ -358,7 +358,7 @@ var GeckoViewUtils = { this._log(log.logger, level, strings, exprs); XPCOMUtils.defineLazyGetter(log, "logger", _ => { - const logger = lazy.Log.repository.getLogger(tag); + const logger = Log.repository.getLogger(tag); logger.parent = this.rootLogger; return logger; }); @@ -372,7 +372,7 @@ var GeckoViewUtils = { get rootLogger() { if (!this._rootLogger) { - this._rootLogger = lazy.Log.repository.getLogger("GeckoView"); + this._rootLogger = Log.repository.getLogger("GeckoView"); this._rootLogger.addAppender(new AndroidAppender()); this._rootLogger.manageLevelFromPref("geckoview.logging"); } @@ -389,7 +389,7 @@ var GeckoViewUtils = { ); } - if (aLogger.level > lazy.Log.Level.Numbers[aLevel]) { + if (aLogger.level > Log.Level.Numbers[aLevel]) { // Log disabled. return; } From 25d05032b16b8c4cb9abfab8dcab4e79b5197ce5 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:24 +0000 Subject: [PATCH 17/64] Bug 1773829 - Part 6: Stop using lazy getter unnecessarily in remote/. r=webdriver-reviewers,whimboo Differential Revision: https://phabricator.services.mozilla.com/D149015 --- remote/cdp/CDPConnection.jsm | 7 +++++-- remote/cdp/domains/content/DOM.jsm | 13 +++--------- remote/cdp/domains/content/Emulation.jsm | 8 ++++--- remote/cdp/domains/content/Input.jsm | 13 +++--------- remote/cdp/domains/content/Log.jsm | 14 ++++--------- remote/cdp/domains/content/Network.jsm | 13 +++--------- remote/cdp/domains/content/Performance.jsm | 13 +++--------- remote/cdp/domains/content/Runtime.jsm | 15 +++++++------ remote/cdp/domains/content/Security.jsm | 13 +++--------- remote/cdp/domains/parent/Browser.jsm | 13 ++++-------- remote/cdp/domains/parent/Emulation.jsm | 8 ++++--- remote/cdp/domains/parent/Fetch.jsm | 12 +++-------- remote/cdp/domains/parent/IO.jsm | 14 ++++++++----- remote/cdp/domains/parent/Input.jsm | 13 ++++-------- remote/cdp/domains/parent/Network.jsm | 13 ++++-------- remote/cdp/domains/parent/Page.jsm | 7 +++++-- remote/cdp/domains/parent/Security.jsm | 8 ++++--- remote/cdp/domains/parent/Target.jsm | 7 +++++-- remote/cdp/observers/ChannelEventSink.jsm | 14 ++++--------- remote/cdp/targets/MainProcessTarget.jsm | 7 +++++-- remote/cdp/targets/TabTarget.jsm | 7 +++++-- remote/marionette/driver.js | 21 +++++++++++-------- .../shared/messagehandler/MessageHandler.jsm | 8 ++++--- .../messagehandler/MessageHandlerRegistry.jsm | 8 ++++--- .../messagehandler/RootMessageHandler.jsm | 8 ++++--- .../RootMessageHandlerRegistry.jsm | 20 +++++++----------- .../WindowGlobalMessageHandler.jsm | 8 ++++--- .../WebDriverBiDiConnection.jsm | 7 +++++-- .../modules/root/browsingContext.jsm | 7 +++++-- remote/webdriver-bidi/modules/root/log.jsm | 7 +++++-- .../webdriver-bidi/modules/root/session.jsm | 7 +++++-- .../modules/windowglobal-in-root/log.jsm | 12 +++-------- .../modules/windowglobal/browsingContext.jsm | 7 +++++-- .../modules/windowglobal/log.jsm | 7 +++++-- 34 files changed, 168 insertions(+), 191 deletions(-) diff --git a/remote/cdp/CDPConnection.jsm b/remote/cdp/CDPConnection.jsm index 6fba2c77fbfb..c8b0a183b6e4 100644 --- a/remote/cdp/CDPConnection.jsm +++ b/remote/cdp/CDPConnection.jsm @@ -11,20 +11,23 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { WebSocketConnection } = ChromeUtils.import( + "chrome://remote/content/shared/WebSocketConnection.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { Log: "chrome://remote/content/shared/Log.jsm", truncate: "chrome://remote/content/shared/Format.jsm", UnknownMethodError: "chrome://remote/content/cdp/Error.jsm", - WebSocketConnection: "chrome://remote/content/shared/WebSocketConnection.jsm", }); XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get(lazy.Log.TYPES.CDP) ); -class CDPConnection extends lazy.WebSocketConnection { +class CDPConnection extends WebSocketConnection { /** * @param {WebSocket} webSocket * The WebSocket server connection to wrap. diff --git a/remote/cdp/domains/content/DOM.jsm b/remote/cdp/domains/content/DOM.jsm index 52e9112c429c..a3fd4013032b 100644 --- a/remote/cdp/domains/content/DOM.jsm +++ b/remote/cdp/domains/content/DOM.jsm @@ -6,18 +6,11 @@ var EXPORTED_SYMBOLS = ["DOM"]; -var { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", -}); - -class DOM extends lazy.ContentProcessDomain { +class DOM extends ContentProcessDomain { constructor(session) { super(session); this.enabled = false; diff --git a/remote/cdp/domains/content/Emulation.jsm b/remote/cdp/domains/content/Emulation.jsm index dab19cc400f7..02ff927a129f 100644 --- a/remote/cdp/domains/content/Emulation.jsm +++ b/remote/cdp/domains/content/Emulation.jsm @@ -10,15 +10,17 @@ var { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { AnimationFramePromise: "chrome://remote/content/shared/Sync.jsm", - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", }); -class Emulation extends lazy.ContentProcessDomain { +class Emulation extends ContentProcessDomain { // commands /** diff --git a/remote/cdp/domains/content/Input.jsm b/remote/cdp/domains/content/Input.jsm index 6a5d837c0223..39c545145011 100644 --- a/remote/cdp/domains/content/Input.jsm +++ b/remote/cdp/domains/content/Input.jsm @@ -6,18 +6,11 @@ var EXPORTED_SYMBOLS = ["Input"]; -var { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", -}); - -class Input extends lazy.ContentProcessDomain { +class Input extends ContentProcessDomain { constructor(session) { super(session); diff --git a/remote/cdp/domains/content/Log.jsm b/remote/cdp/domains/content/Log.jsm index 5f5137034a52..9a700cd8f843 100644 --- a/remote/cdp/domains/content/Log.jsm +++ b/remote/cdp/domains/content/Log.jsm @@ -7,17 +7,11 @@ var EXPORTED_SYMBOLS = ["Log"]; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" + +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", -}); - const CONSOLE_MESSAGE_LEVEL_MAP = { [Ci.nsIConsoleMessage.debug]: "verbose", [Ci.nsIConsoleMessage.info]: "info", @@ -25,7 +19,7 @@ const CONSOLE_MESSAGE_LEVEL_MAP = { [Ci.nsIConsoleMessage.error]: "error", }; -class Log extends lazy.ContentProcessDomain { +class Log extends ContentProcessDomain { constructor(session) { super(session); this.enabled = false; diff --git a/remote/cdp/domains/content/Network.jsm b/remote/cdp/domains/content/Network.jsm index a737a5907898..f2c07cbbe56d 100644 --- a/remote/cdp/domains/content/Network.jsm +++ b/remote/cdp/domains/content/Network.jsm @@ -6,18 +6,11 @@ var EXPORTED_SYMBOLS = ["Network"]; -var { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", -}); - -class Network extends lazy.ContentProcessDomain { +class Network extends ContentProcessDomain { // commands /** diff --git a/remote/cdp/domains/content/Performance.jsm b/remote/cdp/domains/content/Performance.jsm index 0a4d854ea0bb..865fa5a3daf5 100644 --- a/remote/cdp/domains/content/Performance.jsm +++ b/remote/cdp/domains/content/Performance.jsm @@ -6,18 +6,11 @@ var EXPORTED_SYMBOLS = ["Performance"]; -var { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", -}); - -class Performance extends lazy.ContentProcessDomain { +class Performance extends ContentProcessDomain { constructor(session) { super(session); this.enabled = false; diff --git a/remote/cdp/domains/content/Runtime.jsm b/remote/cdp/domains/content/Runtime.jsm index a3c0355ec55b..add37225695e 100644 --- a/remote/cdp/domains/content/Runtime.jsm +++ b/remote/cdp/domains/content/Runtime.jsm @@ -11,13 +11,16 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" +); +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - addDebuggerToGlobal: "resource://gre/modules/jsdebugger.jsm", - - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", executeSoon: "chrome://remote/content/shared/Sync.jsm", ExecutionContext: "chrome://remote/content/cdp/domains/content/runtime/ExecutionContext.jsm", @@ -30,7 +33,7 @@ XPCOMUtils.defineLazyGetter(lazy, "ConsoleAPIStorage", () => { }); // Import the `Debugger` constructor in the current scope -lazy.addDebuggerToGlobal(globalThis); +addDebuggerToGlobal(globalThis); const CONSOLE_API_LEVEL_MAP = { warn: "warning", @@ -62,7 +65,7 @@ class SetMap extends Map { } } -class Runtime extends lazy.ContentProcessDomain { +class Runtime extends ContentProcessDomain { constructor(session) { super(session); this.enabled = false; diff --git a/remote/cdp/domains/content/Security.jsm b/remote/cdp/domains/content/Security.jsm index 7460e6b9a3fc..957220caf8a4 100644 --- a/remote/cdp/domains/content/Security.jsm +++ b/remote/cdp/domains/content/Security.jsm @@ -6,18 +6,11 @@ var EXPORTED_SYMBOLS = ["Security"]; -var { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { ContentProcessDomain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ContentProcessDomain: - "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm", -}); - -class Security extends lazy.ContentProcessDomain { +class Security extends ContentProcessDomain { constructor(session) { super(session); this.enabled = false; diff --git a/remote/cdp/domains/parent/Browser.jsm b/remote/cdp/domains/parent/Browser.jsm index f3f7a4c6ad86..7f00dbef33b4 100644 --- a/remote/cdp/domains/parent/Browser.jsm +++ b/remote/cdp/domains/parent/Browser.jsm @@ -7,17 +7,12 @@ var EXPORTED_SYMBOLS = ["Browser"]; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" + +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", -}); - -class Browser extends lazy.Domain { +class Browser extends Domain { getVersion() { const { isHeadless } = Cc["@mozilla.org/gfx/info;1"].getService( Ci.nsIGfxInfo diff --git a/remote/cdp/domains/parent/Emulation.jsm b/remote/cdp/domains/parent/Emulation.jsm index d41c67ac3523..998e2f7ad323 100644 --- a/remote/cdp/domains/parent/Emulation.jsm +++ b/remote/cdp/domains/parent/Emulation.jsm @@ -10,17 +10,19 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { NetUtil: "resource://gre/modules/NetUtil.jsm", - - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", }); const MAX_WINDOW_SIZE = 10000000; -class Emulation extends lazy.Domain { +class Emulation extends Domain { destructor() { this.setUserAgentOverride({ userAgent: "", platform: "" }); diff --git a/remote/cdp/domains/parent/Fetch.jsm b/remote/cdp/domains/parent/Fetch.jsm index 57f903ace9d7..e4f26e2b1fb4 100644 --- a/remote/cdp/domains/parent/Fetch.jsm +++ b/remote/cdp/domains/parent/Fetch.jsm @@ -6,20 +6,14 @@ var EXPORTED_SYMBOLS = ["Fetch"]; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", -}); - // Note: For now this domain has only been added so that clients using CDP // (like Selenium) don't break when trying to disable Fetch events. -class Fetch extends lazy.Domain { +class Fetch extends Domain { constructor(session) { super(session); diff --git a/remote/cdp/domains/parent/IO.jsm b/remote/cdp/domains/parent/IO.jsm index e251f6e03b3b..33d58bb0c9a1 100644 --- a/remote/cdp/domains/parent/IO.jsm +++ b/remote/cdp/domains/parent/IO.jsm @@ -10,21 +10,25 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" +); +const { StreamRegistry } = ChromeUtils.import( + "chrome://remote/content/cdp/StreamRegistry.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { OS: "resource://gre/modules/osfile.jsm", - - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", - StreamRegistry: "chrome://remote/content/cdp/StreamRegistry.jsm", }); const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024; // Global singleton for managing open streams -const streamRegistry = new lazy.StreamRegistry(); +const streamRegistry = new StreamRegistry(); -class IO extends lazy.Domain { +class IO extends Domain { // commands /** diff --git a/remote/cdp/domains/parent/Input.jsm b/remote/cdp/domains/parent/Input.jsm index cd235e790049..ddbdfa2c9280 100644 --- a/remote/cdp/domains/parent/Input.jsm +++ b/remote/cdp/domains/parent/Input.jsm @@ -7,17 +7,12 @@ var EXPORTED_SYMBOLS = ["Input"]; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" + +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", -}); - -class Input extends lazy.Domain { +class Input extends Domain { // commands /** diff --git a/remote/cdp/domains/parent/Network.jsm b/remote/cdp/domains/parent/Network.jsm index 0b7f527d49a9..bf8724f5ac02 100644 --- a/remote/cdp/domains/parent/Network.jsm +++ b/remote/cdp/domains/parent/Network.jsm @@ -7,16 +7,11 @@ var EXPORTED_SYMBOLS = ["Network"]; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" + +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", -}); - const MAX_COOKIE_EXPIRY = Number.MAX_SAFE_INTEGER; const LOAD_CAUSE_STRINGS = { @@ -43,7 +38,7 @@ const LOAD_CAUSE_STRINGS = { [Ci.nsIContentPolicy.TYPE_WEB_MANIFEST]: "WebManifest", }; -class Network extends lazy.Domain { +class Network extends Domain { constructor(session) { super(session); this.enabled = false; diff --git a/remote/cdp/domains/parent/Page.jsm b/remote/cdp/domains/parent/Page.jsm index 45b2972a59fc..f54afbea9984 100644 --- a/remote/cdp/domains/parent/Page.jsm +++ b/remote/cdp/domains/parent/Page.jsm @@ -11,6 +11,10 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { @@ -21,7 +25,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { DialogHandler: "chrome://remote/content/cdp/domains/parent/page/DialogHandler.jsm", - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", PollPromise: "chrome://remote/content/shared/Sync.jsm", streamRegistry: "chrome://remote/content/cdp/domains/parent/IO.jsm", TabManager: "chrome://remote/content/shared/TabManager.jsm", @@ -42,7 +45,7 @@ const PDF_TRANSFER_MODES = { const TIMEOUT_SET_HISTORY_INDEX = 1000; -class Page extends lazy.Domain { +class Page extends Domain { constructor(session) { super(session); diff --git a/remote/cdp/domains/parent/Security.jsm b/remote/cdp/domains/parent/Security.jsm index 70a07308f2da..691f3e1e3d3d 100644 --- a/remote/cdp/domains/parent/Security.jsm +++ b/remote/cdp/domains/parent/Security.jsm @@ -10,12 +10,14 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { Preferences: "resource://gre/modules/Preferences.jsm", - - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", }); XPCOMUtils.defineLazyServiceGetters(lazy, { @@ -29,7 +31,7 @@ XPCOMUtils.defineLazyServiceGetters(lazy, { const CERT_PINNING_ENFORCEMENT_PREF = "security.cert_pinning.enforcement_level"; const HSTS_PRELOAD_LIST_PREF = "network.stricttransportsecurity.preloadlist"; -class Security extends lazy.Domain { +class Security extends Domain { destructor() { this.setIgnoreCertificateErrors({ ignore: false }); } diff --git a/remote/cdp/domains/parent/Target.jsm b/remote/cdp/domains/parent/Target.jsm index 7ed2d90c4163..2c2162d0cde7 100644 --- a/remote/cdp/domains/parent/Target.jsm +++ b/remote/cdp/domains/parent/Target.jsm @@ -11,13 +11,16 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Domain } = ChromeUtils.import( + "chrome://remote/content/cdp/domains/Domain.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { ContextualIdentityService: "resource://gre/modules/ContextualIdentityService.jsm", - Domain: "chrome://remote/content/cdp/domains/Domain.jsm", MainProcessTarget: "chrome://remote/content/cdp/targets/MainProcessTarget.jsm", TabManager: "chrome://remote/content/shared/TabManager.jsm", @@ -27,7 +30,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { let browserContextIds = 1; -class Target extends lazy.Domain { +class Target extends Domain { constructor(session) { super(session); diff --git a/remote/cdp/observers/ChannelEventSink.jsm b/remote/cdp/observers/ChannelEventSink.jsm index 61f61c78e16c..6206aac12938 100644 --- a/remote/cdp/observers/ChannelEventSink.jsm +++ b/remote/cdp/observers/ChannelEventSink.jsm @@ -6,16 +6,10 @@ var EXPORTED_SYMBOLS = ["ChannelEventSinkFactory"]; -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { ComponentUtils } = ChromeUtils.import( + "resource://gre/modules/ComponentUtils.jsm" ); - -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - ComponentUtils: "resource://gre/modules/ComponentUtils.jsm", -}); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const Cm = Components.manager; @@ -68,7 +62,7 @@ ChannelEventSink.prototype = { }, }; -const ChannelEventSinkFactory = lazy.ComponentUtils.generateSingletonFactory( +const ChannelEventSinkFactory = ComponentUtils.generateSingletonFactory( ChannelEventSink ); diff --git a/remote/cdp/targets/MainProcessTarget.jsm b/remote/cdp/targets/MainProcessTarget.jsm index 2a057cfb1e0e..f2fd56e4a047 100644 --- a/remote/cdp/targets/MainProcessTarget.jsm +++ b/remote/cdp/targets/MainProcessTarget.jsm @@ -10,13 +10,16 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Target } = ChromeUtils.import( + "chrome://remote/content/cdp/targets/Target.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { MainProcessSession: "chrome://remote/content/cdp/sessions/MainProcessSession.jsm", RemoteAgent: "chrome://remote/content/components/RemoteAgent.jsm", - Target: "chrome://remote/content/cdp/targets/Target.jsm", }); /** @@ -25,7 +28,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { * Matches BrowserDevToolsAgentHost from chromium, and only support a couple of Domains: * https://cs.chromium.org/chromium/src/content/browser/devtools/browser_devtools_agent_host.cc?dr=CSs&g=0&l=80-91 */ -class MainProcessTarget extends lazy.Target { +class MainProcessTarget extends Target { /* * @param TargetList targetList */ diff --git a/remote/cdp/targets/TabTarget.jsm b/remote/cdp/targets/TabTarget.jsm index 20bd76a9d61f..414819d006eb 100644 --- a/remote/cdp/targets/TabTarget.jsm +++ b/remote/cdp/targets/TabTarget.jsm @@ -11,13 +11,16 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Target } = ChromeUtils.import( + "chrome://remote/content/cdp/targets/Target.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { RemoteAgent: "chrome://remote/content/components/RemoteAgent.jsm", TabManager: "chrome://remote/content/shared/TabManager.jsm", TabSession: "chrome://remote/content/cdp/sessions/TabSession.jsm", - Target: "chrome://remote/content/cdp/targets/Target.jsm", }); XPCOMUtils.defineLazyServiceGetter( @@ -30,7 +33,7 @@ XPCOMUtils.defineLazyServiceGetter( /** * Target for a local tab or a remoted frame. */ -class TabTarget extends lazy.Target { +class TabTarget extends Target { /** * @param TargetList targetList * @param BrowserElement browser diff --git a/remote/marionette/driver.js b/remote/marionette/driver.js index 2ba232515085..345a2cdbdddd 100644 --- a/remote/marionette/driver.js +++ b/remote/marionette/driver.js @@ -11,6 +11,10 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { element } = ChromeUtils.import( + "chrome://remote/content/marionette/element.js" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { @@ -27,7 +31,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { DebounceCallback: "chrome://remote/content/marionette/sync.js", disableEventsActor: "chrome://remote/content/marionette/actors/MarionetteEventsParent.jsm", - element: "chrome://remote/content/marionette/element.js", enableEventsActor: "chrome://remote/content/marionette/actors/MarionetteEventsParent.jsm", error: "chrome://remote/content/shared/webdriver/Errors.jsm", @@ -73,14 +76,14 @@ XPCOMUtils.defineLazyGetter(lazy, "logger", () => const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; const SUPPORTED_STRATEGIES = new Set([ - lazy.element.Strategy.ClassName, - lazy.element.Strategy.Selector, - lazy.element.Strategy.ID, - lazy.element.Strategy.Name, - lazy.element.Strategy.LinkText, - lazy.element.Strategy.PartialLinkText, - lazy.element.Strategy.TagName, - lazy.element.Strategy.XPath, + element.Strategy.ClassName, + element.Strategy.Selector, + element.Strategy.ID, + element.Strategy.Name, + element.Strategy.LinkText, + element.Strategy.PartialLinkText, + element.Strategy.TagName, + element.Strategy.XPath, ]); // Timeout used to abort fullscreen, maximize, and minimize diff --git a/remote/shared/messagehandler/MessageHandler.jsm b/remote/shared/messagehandler/MessageHandler.jsm index 9f04b799f523..c13339eee354 100644 --- a/remote/shared/messagehandler/MessageHandler.jsm +++ b/remote/shared/messagehandler/MessageHandler.jsm @@ -10,11 +10,13 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { EventEmitter } = ChromeUtils.import( + "resource://gre/modules/EventEmitter.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - EventEmitter: "resource://gre/modules/EventEmitter.jsm", - error: "chrome://remote/content/shared/messagehandler/Errors.jsm", EventsDispatcher: "chrome://remote/content/shared/messagehandler/EventsDispatcher.jsm", @@ -79,7 +81,7 @@ const ContextDescriptorType = { * instances are properly registered and can be retrieved based on a given * session id as well as some other context information. */ -class MessageHandler extends lazy.EventEmitter { +class MessageHandler extends EventEmitter { /** * Create a new MessageHandler instance. * diff --git a/remote/shared/messagehandler/MessageHandlerRegistry.jsm b/remote/shared/messagehandler/MessageHandlerRegistry.jsm index e36eac0dafb7..a601e0637420 100644 --- a/remote/shared/messagehandler/MessageHandlerRegistry.jsm +++ b/remote/shared/messagehandler/MessageHandlerRegistry.jsm @@ -10,11 +10,13 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { EventEmitter } = ChromeUtils.import( + "resource://gre/modules/EventEmitter.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - EventEmitter: "resource://gre/modules/EventEmitter.jsm", - Log: "chrome://remote/content/shared/Log.jsm", readSessionData: "chrome://remote/content/shared/messagehandler/sessiondata/SessionDataReader.jsm", @@ -68,7 +70,7 @@ function getMessageHandlerClass(type) { * The registry is useful to retrieve the appropriate MessageHandler instance * after crossing a technical boundary (eg process, thread...). */ -class MessageHandlerRegistry extends lazy.EventEmitter { +class MessageHandlerRegistry extends EventEmitter { /* * @param {String} type * MessageHandler type, one of MessageHandler.type. diff --git a/remote/shared/messagehandler/RootMessageHandler.jsm b/remote/shared/messagehandler/RootMessageHandler.jsm index dde6b2a3e64e..db6cee003897 100644 --- a/remote/shared/messagehandler/RootMessageHandler.jsm +++ b/remote/shared/messagehandler/RootMessageHandler.jsm @@ -10,13 +10,15 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { MessageHandler } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/MessageHandler.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { FrameTransport: "chrome://remote/content/shared/messagehandler/transports/FrameTransport.jsm", - MessageHandler: - "chrome://remote/content/shared/messagehandler/MessageHandler.jsm", SessionData: "chrome://remote/content/shared/messagehandler/sessiondata/SessionData.jsm", WindowGlobalMessageHandler: @@ -28,7 +30,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { * in the parent process. It can forward commands to MessageHandlers in other * layers (at the moment WindowGlobalMessageHandlers in content processes). */ -class RootMessageHandler extends lazy.MessageHandler { +class RootMessageHandler extends MessageHandler { /** * Returns the RootMessageHandler module path. * diff --git a/remote/shared/messagehandler/RootMessageHandlerRegistry.jsm b/remote/shared/messagehandler/RootMessageHandlerRegistry.jsm index ed58f53c22b5..91f75dcae403 100644 --- a/remote/shared/messagehandler/RootMessageHandlerRegistry.jsm +++ b/remote/shared/messagehandler/RootMessageHandlerRegistry.jsm @@ -6,18 +6,12 @@ var EXPORTED_SYMBOLS = ["RootMessageHandlerRegistry"]; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { MessageHandlerRegistry } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/MessageHandlerRegistry.jsm" +); +const { RootMessageHandler } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/RootMessageHandler.jsm" ); - -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - MessageHandlerRegistry: - "chrome://remote/content/shared/messagehandler/MessageHandlerRegistry.jsm", - RootMessageHandler: - "chrome://remote/content/shared/messagehandler/RootMessageHandler.jsm", -}); /** * In the parent process, only one Root MessageHandlerRegistry should ever be @@ -25,6 +19,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { * registry and from there either create or retrieve Root MessageHandler * instances for a specific session. */ -var RootMessageHandlerRegistry = new lazy.MessageHandlerRegistry( - lazy.RootMessageHandler.type +var RootMessageHandlerRegistry = new MessageHandlerRegistry( + RootMessageHandler.type ); diff --git a/remote/shared/messagehandler/WindowGlobalMessageHandler.jsm b/remote/shared/messagehandler/WindowGlobalMessageHandler.jsm index 8bb1fd1e4eb4..4f9041374766 100644 --- a/remote/shared/messagehandler/WindowGlobalMessageHandler.jsm +++ b/remote/shared/messagehandler/WindowGlobalMessageHandler.jsm @@ -10,13 +10,15 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { MessageHandler } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/MessageHandler.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { ContextDescriptorType: "chrome://remote/content/shared/messagehandler/MessageHandler.jsm", - MessageHandler: - "chrome://remote/content/shared/messagehandler/MessageHandler.jsm", }); /** @@ -26,7 +28,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { * commands further to other MessageHandlers and represents a leaf node in a * MessageHandler network. */ -class WindowGlobalMessageHandler extends lazy.MessageHandler { +class WindowGlobalMessageHandler extends MessageHandler { constructor() { super(...arguments); diff --git a/remote/webdriver-bidi/WebDriverBiDiConnection.jsm b/remote/webdriver-bidi/WebDriverBiDiConnection.jsm index 19988e5ad803..4e583f4ec6cf 100644 --- a/remote/webdriver-bidi/WebDriverBiDiConnection.jsm +++ b/remote/webdriver-bidi/WebDriverBiDiConnection.jsm @@ -10,6 +10,10 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { WebSocketConnection } = ChromeUtils.import( + "chrome://remote/content/shared/WebSocketConnection.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { @@ -18,14 +22,13 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { Log: "chrome://remote/content/shared/Log.jsm", RemoteAgent: "chrome://remote/content/components/RemoteAgent.jsm", truncate: "chrome://remote/content/shared/Format.jsm", - WebSocketConnection: "chrome://remote/content/shared/WebSocketConnection.jsm", }); XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get(lazy.Log.TYPES.WEBDRIVER_BIDI) ); -class WebDriverBiDiConnection extends lazy.WebSocketConnection { +class WebDriverBiDiConnection extends WebSocketConnection { /** * @param {WebSocket} webSocket * The WebSocket server connection to wrap. diff --git a/remote/webdriver-bidi/modules/root/browsingContext.jsm b/remote/webdriver-bidi/modules/root/browsingContext.jsm index 66836710b95b..9ea3377401da 100644 --- a/remote/webdriver-bidi/modules/root/browsingContext.jsm +++ b/remote/webdriver-bidi/modules/root/browsingContext.jsm @@ -11,6 +11,10 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Module } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/Module.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { @@ -22,7 +26,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { "chrome://remote/content/shared/messagehandler/MessageHandler.jsm", error: "chrome://remote/content/shared/webdriver/Errors.jsm", Log: "chrome://remote/content/shared/Log.jsm", - Module: "chrome://remote/content/shared/messagehandler/Module.jsm", ProgressListener: "chrome://remote/content/shared/Navigate.jsm", TabManager: "chrome://remote/content/shared/TabManager.jsm", waitForInitialNavigationCompleted: @@ -66,7 +69,7 @@ const WaitCondition = { Complete: "complete", }; -class BrowsingContextModule extends lazy.Module { +class BrowsingContextModule extends Module { #contextListener; /** diff --git a/remote/webdriver-bidi/modules/root/log.jsm b/remote/webdriver-bidi/modules/root/log.jsm index cb16220c37cf..88f486d437df 100644 --- a/remote/webdriver-bidi/modules/root/log.jsm +++ b/remote/webdriver-bidi/modules/root/log.jsm @@ -10,15 +10,18 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Module } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/Module.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { ContextDescriptorType: "chrome://remote/content/shared/messagehandler/MessageHandler.jsm", - Module: "chrome://remote/content/shared/messagehandler/Module.jsm", }); -class LogModule extends lazy.Module { +class LogModule extends Module { destroy() {} /** diff --git a/remote/webdriver-bidi/modules/root/session.jsm b/remote/webdriver-bidi/modules/root/session.jsm index 8a9458516a46..e09134d341c6 100644 --- a/remote/webdriver-bidi/modules/root/session.jsm +++ b/remote/webdriver-bidi/modules/root/session.jsm @@ -10,17 +10,20 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Module } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/Module.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { assert: "chrome://remote/content/shared/webdriver/Assert.jsm", error: "chrome://remote/content/shared/webdriver/Errors.jsm", - Module: "chrome://remote/content/shared/messagehandler/Module.jsm", RootMessageHandler: "chrome://remote/content/shared/messagehandler/RootMessageHandler.jsm", }); -class SessionModule extends lazy.Module { +class SessionModule extends Module { destroy() {} /** diff --git a/remote/webdriver-bidi/modules/windowglobal-in-root/log.jsm b/remote/webdriver-bidi/modules/windowglobal-in-root/log.jsm index 3b03995cc20a..4a7030c910e3 100644 --- a/remote/webdriver-bidi/modules/windowglobal-in-root/log.jsm +++ b/remote/webdriver-bidi/modules/windowglobal-in-root/log.jsm @@ -6,17 +6,11 @@ const EXPORTED_SYMBOLS = ["log"]; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" +const { Module } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/Module.jsm" ); -const lazy = {}; - -XPCOMUtils.defineLazyModuleGetters(lazy, { - Module: "chrome://remote/content/shared/messagehandler/Module.jsm", -}); - -class LogModule extends lazy.Module { +class LogModule extends Module { destroy() {} } diff --git a/remote/webdriver-bidi/modules/windowglobal/browsingContext.jsm b/remote/webdriver-bidi/modules/windowglobal/browsingContext.jsm index 266656dc9083..163edad1e2e7 100644 --- a/remote/webdriver-bidi/modules/windowglobal/browsingContext.jsm +++ b/remote/webdriver-bidi/modules/windowglobal/browsingContext.jsm @@ -10,14 +10,17 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Module } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/Module.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { LoadListener: "chrome://remote/content/shared/listeners/LoadListener.jsm", - Module: "chrome://remote/content/shared/messagehandler/Module.jsm", }); -class BrowsingContextModule extends lazy.Module { +class BrowsingContextModule extends Module { #loadListener; constructor(messageHandler) { diff --git a/remote/webdriver-bidi/modules/windowglobal/log.jsm b/remote/webdriver-bidi/modules/windowglobal/log.jsm index 6ec5be278328..74c4d09d90b4 100644 --- a/remote/webdriver-bidi/modules/windowglobal/log.jsm +++ b/remote/webdriver-bidi/modules/windowglobal/log.jsm @@ -10,6 +10,10 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { Module } = ChromeUtils.import( + "chrome://remote/content/shared/messagehandler/Module.jsm" +); + const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { @@ -18,11 +22,10 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { ConsoleListener: "chrome://remote/content/shared/listeners/ConsoleListener.jsm", isChromeFrame: "chrome://remote/content/shared/Stack.jsm", - Module: "chrome://remote/content/shared/messagehandler/Module.jsm", serialize: "chrome://remote/content/webdriver-bidi/RemoteValue.jsm", }); -class LogModule extends lazy.Module { +class LogModule extends Module { #consoleAPIListener; #consoleMessageListener; From 7962c5d46aa3af89a6844839c9516f3a0f1b84ca Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:24 +0000 Subject: [PATCH 18/64] Bug 1773829 - Part 7: Stop using lazy getter unnecessarily in services/. r=markh Depends on D149015 Differential Revision: https://phabricator.services.mozilla.com/D149016 --- services/common/logmanager.js | 29 ++++++++++--------- services/settings/RemoteSettingsClient.jsm | 6 ++-- .../sync/modules/engines/extension-storage.js | 22 ++++++++------ services/sync/modules/telemetry.js | 4 +-- .../sync/tps/extensions/tps/resource/tps.jsm | 6 ++-- 5 files changed, 38 insertions(+), 29 deletions(-) diff --git a/services/common/logmanager.js b/services/common/logmanager.js index 82ccfba6b8d3..f9e02a8e7306 100644 --- a/services/common/logmanager.js +++ b/services/common/logmanager.js @@ -3,15 +3,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict;"; +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); + const lazy = {}; -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.defineModuleGetter( lazy, "FileUtils", "resource://gre/modules/FileUtils.jsm" ); -ChromeUtils.defineModuleGetter(lazy, "Log", "resource://gre/modules/Log.jsm"); ChromeUtils.defineModuleGetter(lazy, "OS", "resource://gre/modules/osfile.jsm"); ChromeUtils.defineModuleGetter( lazy, @@ -61,7 +62,7 @@ const PR_UINT32_MAX = 0xffffffff; * during logging. Instead, one can periodically consume the input stream and * e.g. write it to disk asynchronously. */ -class StorageStreamAppender extends lazy.Log.Appender { +class StorageStreamAppender extends Log.Appender { constructor(formatter) { super(formatter); this._name = "StorageStreamAppender"; @@ -148,7 +149,7 @@ class FlushableStorageAppender extends StorageStreamAppender { } append(message) { - if (message.level >= lazy.Log.Level.Error) { + if (message.level >= Log.Level.Error) { this.sawError = true; } StorageStreamAppender.prototype.append.call(this, message); @@ -251,9 +252,9 @@ LogManager.prototype = { this.logFilePrefix = logFilePrefix; if (!formatter) { // Create a formatter and various appenders to attach to the logs. - formatter = new lazy.Log.BasicFormatter(); - consoleAppender = new lazy.Log.ConsoleAppender(formatter); - dumpAppender = new lazy.Log.DumpAppender(formatter); + formatter = new Log.BasicFormatter(); + consoleAppender = new Log.ConsoleAppender(formatter); + dumpAppender = new Log.DumpAppender(formatter); } allBranches.add(this._prefs._branchStr); @@ -266,7 +267,7 @@ LogManager.prototype = { findSmallest = false ) => { let observer = newVal => { - let level = lazy.Log.Level[newVal] || defaultLevel; + let level = Log.Level[newVal] || defaultLevel; if (findSmallest) { // As some of our appenders have global impact (ie, there is only one // place 'dump' goes to), we need to find the smallest value from all @@ -275,7 +276,7 @@ LogManager.prototype = { // dump=Error, we need to keep dump=Debug so consumerA is respected. for (let branch of allBranches) { let lookPrefBranch = new Preferences(branch); - let lookVal = lazy.Log.Level[lookPrefBranch.get(prefName)]; + let lookVal = Log.Level[lookPrefBranch.get(prefName)]; if (lookVal && lookVal < level) { level = lookVal; } @@ -293,13 +294,13 @@ LogManager.prototype = { this._observeConsolePref = setupAppender( consoleAppender, "log.appender.console", - lazy.Log.Level.Fatal, + Log.Level.Fatal, true ); this._observeDumpPref = setupAppender( dumpAppender, "log.appender.dump", - lazy.Log.Level.Error, + Log.Level.Error, true ); @@ -310,18 +311,18 @@ LogManager.prototype = { this._observeStreamPref = setupAppender( fapp, "log.appender.file.level", - lazy.Log.Level.Debug + Log.Level.Debug ); // now attach the appenders to all our logs. for (let logName of logNames) { - let log = lazy.Log.repository.getLogger(logName); + let log = Log.repository.getLogger(logName); for (let appender of [fapp, dumpAppender, consoleAppender]) { log.addAppender(appender); } } // and use the first specified log as a "root" for our log. - this._log = lazy.Log.repository.getLogger(logNames[0] + ".LogManager"); + this._log = Log.repository.getLogger(logNames[0] + ".LogManager"); }, /** diff --git a/services/settings/RemoteSettingsClient.jsm b/services/settings/RemoteSettingsClient.jsm index e1af32190cde..2b07a06b26ef 100644 --- a/services/settings/RemoteSettingsClient.jsm +++ b/services/settings/RemoteSettingsClient.jsm @@ -13,6 +13,9 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { Downloader } = ChromeUtils.import( + "resource://services-settings/Attachments.jsm" +); const lazy = {}; @@ -20,7 +23,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { ClientEnvironmentBase: "resource://gre/modules/components-utils/ClientEnvironment.jsm", Database: "resource://services-settings/Database.jsm", - Downloader: "resource://services-settings/Attachments.jsm", IDBHelpers: "resource://services-settings/IDBHelpers.jsm", KintoHttpClient: "resource://services-common/kinto-http-client.js", ObjectUtils: "resource://gre/modules/ObjectUtils.jsm", @@ -193,7 +195,7 @@ class UnknownCollectionError extends Error { } } -class AttachmentDownloader extends lazy.Downloader { +class AttachmentDownloader extends Downloader { constructor(client) { super(client.bucketName, client.collectionName); this._client = client; diff --git a/services/sync/modules/engines/extension-storage.js b/services/sync/modules/engines/extension-storage.js index 3d72f4818606..569c692d06f5 100644 --- a/services/sync/modules/engines/extension-storage.js +++ b/services/sync/modules/engines/extension-storage.js @@ -12,17 +12,21 @@ var EXPORTED_SYMBOLS = [ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const { BridgedEngine } = ChromeUtils.import( + "resource://services-sync/bridged_engine.js" +); +const { SyncEngine } = ChromeUtils.import( + "resource://services-sync/engines.js" +); +const { Tracker } = ChromeUtils.import("resource://services-sync/engines.js"); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - BridgedEngine: "resource://services-sync/bridged_engine.js", LogAdapter: "resource://services-sync/bridged_engine.js", extensionStorageSync: "resource://gre/modules/ExtensionStorageSync.jsm", Observers: "resource://services-common/observers.js", Svc: "resource://services-sync/util.js", - SyncEngine: "resource://services-sync/engines.js", - Tracker: "resource://services-sync/engines.js", SCORE_INCREMENT_MEDIUM: "resource://services-sync/constants.js", MULTI_DEVICE_THRESHOLD: "resource://services-sync/constants.js", }); @@ -75,7 +79,7 @@ function setEngineEnabled(enabled) { // A "bridged engine" to our webext-storage component. function ExtensionStorageEngineBridge(service) { let bridge = lazy.StorageSyncService.getInterface(Ci.mozIBridgedSyncEngine); - lazy.BridgedEngine.call(this, bridge, "Extension-Storage", service); + BridgedEngine.call(this, bridge, "Extension-Storage", service); let app_services_logger = Cc["@mozilla.org/appservices/logger;1"].getService( Ci.mozIAppServicesLogger @@ -85,7 +89,7 @@ function ExtensionStorageEngineBridge(service) { } ExtensionStorageEngineBridge.prototype = { - __proto__: lazy.BridgedEngine.prototype, + __proto__: BridgedEngine.prototype, syncPriority: 10, // Used to override the engine name in telemetry, so that we can distinguish . @@ -201,7 +205,7 @@ ExtensionStorageEngineBridge.prototype = { * framework, so this is something of a stub. */ function ExtensionStorageEngineKinto(service) { - lazy.SyncEngine.call(this, "Extension-Storage", service); + SyncEngine.call(this, "Extension-Storage", service); XPCOMUtils.defineLazyPreferenceGetter( this, "_skipPercentageChance", @@ -210,7 +214,7 @@ function ExtensionStorageEngineKinto(service) { ); } ExtensionStorageEngineKinto.prototype = { - __proto__: lazy.SyncEngine.prototype, + __proto__: SyncEngine.prototype, _trackerObj: ExtensionStorageTracker, // we don't need these since we implement our own sync logic _storeObj: undefined, @@ -266,11 +270,11 @@ ExtensionStorageEngineKinto.prototype = { }; function ExtensionStorageTracker(name, engine) { - lazy.Tracker.call(this, name, engine); + Tracker.call(this, name, engine); this._ignoreAll = false; } ExtensionStorageTracker.prototype = { - __proto__: lazy.Tracker.prototype, + __proto__: Tracker.prototype, get ignoreAll() { return this._ignoreAll; diff --git a/services/sync/modules/telemetry.js b/services/sync/modules/telemetry.js index 16a042d5c2fe..15c3916873a2 100644 --- a/services/sync/modules/telemetry.js +++ b/services/sync/modules/telemetry.js @@ -24,6 +24,7 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); const lazy = {}; @@ -31,7 +32,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { Async: "resource://services-common/async.js", AuthenticationError: "resource://services-sync/sync_auth.js", FxAccounts: "resource://gre/modules/FxAccounts.jsm", - Log: "resource://gre/modules/Log.jsm", ObjectUtils: "resource://gre/modules/ObjectUtils.jsm", Observers: "resource://services-common/observers.js", OS: "resource://gre/modules/osfile.jsm", @@ -57,7 +57,7 @@ XPCOMUtils.defineLazyGetter( "WeaveService", () => Cc["@mozilla.org/weave/service;1"].getService().wrappedJSObject ); -const log = lazy.Log.repository.getLogger("Sync.Telemetry"); +const log = Log.repository.getLogger("Sync.Telemetry"); const TOPICS = [ // For tracking change to account/device identifiers. diff --git a/services/sync/tps/extensions/tps/resource/tps.jsm b/services/sync/tps/extensions/tps/resource/tps.jsm index 9d1e9312a8b1..94280d475d03 100644 --- a/services/sync/tps/extensions/tps/resource/tps.jsm +++ b/services/sync/tps/extensions/tps/resource/tps.jsm @@ -30,6 +30,9 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { PromiseUtils } = ChromeUtils.import( + "resource://gre/modules/PromiseUtils.jsm" +); const lazy = {}; @@ -46,7 +49,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { Logger: "resource://tps/logger.jsm", OS: "resource://gre/modules/osfile.jsm", PlacesUtils: "resource://gre/modules/PlacesUtils.jsm", - PromiseUtils: "resource://gre/modules/PromiseUtils.jsm", SessionStore: "resource:///modules/sessionstore/SessionStore.jsm", Svc: "resource://services-sync/util.js", SyncTelemetry: "resource://services-sync/telemetry.js", @@ -166,7 +168,7 @@ var TPS = { shouldValidateBookmarks: false, shouldValidatePasswords: false, shouldValidateForms: false, - _placesInitDeferred: lazy.PromiseUtils.defer(), + _placesInitDeferred: PromiseUtils.defer(), _init: function TPS__init() { this.delayAutoSync(); From 1781f10a02d62bd4d203b214e217dce6f7ce3d8c Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:24 +0000 Subject: [PATCH 19/64] Bug 1773829 - Part 8: Stop using lazy getter unnecessarily in toolkit/components/formautofill/. r=sgalich Depends on D149016 Differential Revision: https://phabricator.services.mozilla.com/D149017 --- .../formautofill/CreditCardRuleset.jsm | 32 +++++------ .../formautofill/FormAutofillHandler.jsm | 55 ++++++++----------- .../formautofill/FormAutofillParent.jsm | 18 +++--- .../FormAutofillTelemetryUtils.jsm | 9 +-- .../android/FormAutofillStorage.jsm | 4 +- .../phonenumberutils/PhoneNumber.jsm | 11 ++-- 6 files changed, 54 insertions(+), 75 deletions(-) diff --git a/toolkit/components/formautofill/CreditCardRuleset.jsm b/toolkit/components/formautofill/CreditCardRuleset.jsm index 6ae3efcba92c..78ba1f72ce65 100644 --- a/toolkit/components/formautofill/CreditCardRuleset.jsm +++ b/toolkit/components/formautofill/CreditCardRuleset.jsm @@ -26,20 +26,18 @@ const EXPORTED_SYMBOLS = ["creditCardRulesets"]; const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); -const lazy = {}; -ChromeUtils.defineModuleGetter( - lazy, - "fathom", +const { fathom } = ChromeUtils.import( "resource://gre/modules/third_party/fathom/fathom.jsm" ); -const { - element: clickedElement, - out, - rule, - ruleset, - score, - type, -} = lazy.fathom; +const { element: clickedElement, out, rule, ruleset, score, type } = fathom; +const { CreditCard } = ChromeUtils.import( + "resource://gre/modules/CreditCard.jsm" +); +const { NETWORK_NAMES } = ChromeUtils.import( + "resource://gre/modules/CreditCard.jsm" +); + +const lazy = {}; ChromeUtils.defineModuleGetter( lazy, @@ -52,8 +50,6 @@ ChromeUtils.defineModuleGetter( "resource://autofill/FormAutofillUtils.jsm" ); XPCOMUtils.defineLazyModuleGetters(lazy, { - CreditCard: "resource://gre/modules/CreditCard.jsm", - NETWORK_NAMES: "resource://gre/modules/CreditCard.jsm", LabelUtils: "resource://autofill/FormAutofillUtils.jsm", }); @@ -341,8 +337,8 @@ const yearRegExp = /year/i; const MMYYRegExp = /mm\s*(\/|\\)\s*yy/i; const VisaCheckoutRegExp = /visa(-|\s)checkout/i; const CREDIT_CARD_NETWORK_REGEXP = new RegExp( - lazy.CreditCard.getSupportedNetworks() - .concat(Object.keys(lazy.NETWORK_NAMES)) + CreditCard.getSupportedNetworks() + .concat(Object.keys(NETWORK_NAMES)) .join("|"), "gui" ); @@ -537,8 +533,8 @@ function isSelectWithCreditCardOptions(fnode) { if (element.tagName === "SELECT") { for (let option of element.querySelectorAll("option")) { if ( - lazy.CreditCard.getNetworkFromName(option.value) || - lazy.CreditCard.getNetworkFromName(option.text) + CreditCard.getNetworkFromName(option.value) || + CreditCard.getNetworkFromName(option.text) ) { return true; } diff --git a/toolkit/components/formautofill/FormAutofillHandler.jsm b/toolkit/components/formautofill/FormAutofillHandler.jsm index bffbad07c751..67cc0d52305b 100644 --- a/toolkit/components/formautofill/FormAutofillHandler.jsm +++ b/toolkit/components/formautofill/FormAutofillHandler.jsm @@ -21,14 +21,12 @@ const { XPCOMUtils } = ChromeUtils.import( const { FormAutofill } = ChromeUtils.import( "resource://autofill/FormAutofill.jsm" ); +const { FormAutofillUtils } = ChromeUtils.import( + "resource://autofill/FormAutofillUtils.jsm" +); const lazy = {}; -ChromeUtils.defineModuleGetter( - lazy, - "FormAutofillUtils", - "resource://autofill/FormAutofillUtils.jsm" -); ChromeUtils.defineModuleGetter( lazy, "CreditCardTelemetry", @@ -50,12 +48,12 @@ const formFillController = Cc[ ].getService(Ci.nsIFormFillController); XPCOMUtils.defineLazyGetter(lazy, "reauthPasswordPromptMessage", () => { - const brandShortName = lazy.FormAutofillUtils.brandBundle.GetStringFromName( + const brandShortName = FormAutofillUtils.brandBundle.GetStringFromName( "brandShortName" ); // The string name for Mac is changed because the value needed updating. const platform = AppConstants.platform.replace("macosx", "macos"); - return lazy.FormAutofillUtils.stringBundle.formatStringFromName( + return FormAutofillUtils.stringBundle.formatStringFromName( `useCreditCardPasswordPrompt.${platform}`, [brandShortName] ); @@ -67,7 +65,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { FormAutofill.defineLazyLogGetter(lazy, EXPORTED_SYMBOLS[0]); -const { FIELD_STATES } = lazy.FormAutofillUtils; +const { FIELD_STATES } = FormAutofillUtils; class FormAutofillSection { constructor(fieldDetails, winUtils) { @@ -234,7 +232,7 @@ class FormAutofillSection { continue; } - let option = lazy.FormAutofillUtils.findSelectOption( + let option = FormAutofillUtils.findSelectOption( element, profile, fieldName @@ -359,7 +357,7 @@ class FormAutofillSection { let element = fieldDetail.elementWeakRef.get(); // Skip the field if it is null or readonly or disabled - if (!lazy.FormAutofillUtils.isFieldAutofillable(element)) { + if (!FormAutofillUtils.isFieldAutofillable(element)) { continue; } @@ -438,7 +436,7 @@ class FormAutofillSection { ""; // Skip the field if it is null or readonly or disabled - if (!lazy.FormAutofillUtils.isFieldAutofillable(element)) { + if (!FormAutofillUtils.isFieldAutofillable(element)) { continue; } @@ -644,10 +642,7 @@ class FormAutofillSection { let value = detail.fieldValue ?? (element && element.value.trim()); value = this.computeFillingValue(value, detail, element); - if ( - !value || - value.length > lazy.FormAutofillUtils.MAX_FIELD_VALUE_LENGTH - ) { + if (!value || value.length > FormAutofillUtils.MAX_FIELD_VALUE_LENGTH) { // Keep the property and preserve more information for updating data.record[detail.fieldName] = ""; return; @@ -677,7 +672,7 @@ class FormAutofillSection { } const target = event.target; const targetFieldDetail = this.getFieldDetailByElement(target); - const isCreditCardField = lazy.FormAutofillUtils.isCreditCardField( + const isCreditCardField = FormAutofillUtils.isCreditCardField( targetFieldDetail.fieldName ); @@ -764,8 +759,7 @@ class FormAutofillAddressSection extends FormAutofillSection { isValidSection() { return ( - this.fieldDetails.length >= - lazy.FormAutofillUtils.AUTOFILL_FIELDS_THRESHOLD + this.fieldDetails.length >= FormAutofillUtils.AUTOFILL_FIELDS_THRESHOLD ); } @@ -793,13 +787,13 @@ class FormAutofillAddressSection extends FormAutofillSection { if (!record[key]) { continue; } - if (lazy.FormAutofillUtils.getCategoryFromFieldName(key) == "name") { + if (FormAutofillUtils.getCategoryFromFieldName(key) == "name") { hasName = 1; continue; } length++; } - return length + hasName >= lazy.FormAutofillUtils.AUTOFILL_FIELDS_THRESHOLD; + return length + hasName >= FormAutofillUtils.AUTOFILL_FIELDS_THRESHOLD; } _getOneLineStreetAddress(address) { @@ -809,7 +803,7 @@ class FormAutofillAddressSection extends FormAutofillSection { if (!this._cacheValue.oneLineStreetAddress[address]) { this._cacheValue.oneLineStreetAddress[ address - ] = lazy.FormAutofillUtils.toOneLineAddress(address); + ] = FormAutofillUtils.toOneLineAddress(address); } return this._cacheValue.oneLineStreetAddress[address]; } @@ -834,7 +828,7 @@ class FormAutofillAddressSection extends FormAutofillSection { waitForConcat.unshift(profile[f]); if (this.getFieldDetailByName(f)) { if (waitForConcat.length > 1) { - profile[f] = lazy.FormAutofillUtils.toOneLineAddress(waitForConcat); + profile[f] = FormAutofillUtils.toOneLineAddress(waitForConcat); } waitForConcat = []; } @@ -928,8 +922,7 @@ class FormAutofillAddressSection extends FormAutofillSection { } else { let text = element.selectedOptions[0].text.trim(); value = - lazy.FormAutofillUtils.getAbbreviatedSubregionName([value, text]) || - text; + FormAutofillUtils.getAbbreviatedSubregionName([value, text]) || text; } } return value; @@ -946,7 +939,7 @@ class FormAutofillAddressSection extends FormAutofillSection { // Try identifying country field aggressively if it doesn't come from // @autocomplete. if (detail._reason != "autocomplete") { - let countryCode = lazy.FormAutofillUtils.identifyCountryCode( + let countryCode = FormAutofillUtils.identifyCountryCode( address.record.country ); if (countryCode) { @@ -956,12 +949,11 @@ class FormAutofillAddressSection extends FormAutofillSection { } // Normalize Tel - lazy.FormAutofillUtils.compressTel(address.record); + FormAutofillUtils.compressTel(address.record); if (address.record.tel) { let allTelComponentsAreUntouched = Object.keys(address.record) .filter( - field => - lazy.FormAutofillUtils.getCategoryFromFieldName(field) == "tel" + field => FormAutofillUtils.getCategoryFromFieldName(field) == "tel" ) .every(field => address.untouchedFields.includes(field)); if (allTelComponentsAreUntouched) { @@ -1074,8 +1066,7 @@ class FormAutofillCreditCardSection extends FormAutofillSection { isRecordCreatable(record) { return ( - record["cc-number"] && - lazy.FormAutofillUtils.isCCNumber(record["cc-number"]) + record["cc-number"] && FormAutofillUtils.isCCNumber(record["cc-number"]) ); } @@ -1529,9 +1520,9 @@ class FormAutofillHandler { let allValidDetails = []; for (let { fieldDetails, type } of sections) { let section; - if (type == lazy.FormAutofillUtils.SECTION_TYPES.ADDRESS) { + if (type == FormAutofillUtils.SECTION_TYPES.ADDRESS) { section = new FormAutofillAddressSection(fieldDetails, this.winUtils); - } else if (type == lazy.FormAutofillUtils.SECTION_TYPES.CREDIT_CARD) { + } else if (type == FormAutofillUtils.SECTION_TYPES.CREDIT_CARD) { section = new FormAutofillCreditCardSection( fieldDetails, this.winUtils, diff --git a/toolkit/components/formautofill/FormAutofillParent.jsm b/toolkit/components/formautofill/FormAutofillParent.jsm index 8c2525c6c7cd..680bd620a7ca 100644 --- a/toolkit/components/formautofill/FormAutofillParent.jsm +++ b/toolkit/components/formautofill/FormAutofillParent.jsm @@ -38,6 +38,9 @@ const { XPCOMUtils } = ChromeUtils.import( const { FormAutofill } = ChromeUtils.import( "resource://autofill/FormAutofill.jsm" ); +const { FormAutofillUtils } = ChromeUtils.import( + "resource://autofill/FormAutofillUtils.jsm" +); const lazy = {}; @@ -46,7 +49,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { CreditCard: "resource://gre/modules/CreditCard.jsm", FormAutofillPreferences: "resource://autofill/FormAutofillPreferences.jsm", FormAutofillPrompter: "resource://autofill/FormAutofillPrompter.jsm", - FormAutofillUtils: "resource://autofill/FormAutofillUtils.jsm", OSKeyStore: "resource://gre/modules/OSKeyStore.jsm", }); @@ -60,7 +62,7 @@ const { const { ADDRESSES_COLLECTION_NAME, CREDITCARDS_COLLECTION_NAME, -} = lazy.FormAutofillUtils; +} = FormAutofillUtils; let gMessageObservers = new Set(); @@ -325,7 +327,7 @@ class FormAutofillParent extends JSWindowActorParent { } case "FormAutofill:GetDecryptedString": { let { cipherText, reauth } = data; - if (!lazy.FormAutofillUtils._reauthEnabledByUser) { + if (!FormAutofillUtils._reauthEnabledByUser) { lazy.log.debug("Reauth is disabled"); reauth = false; } @@ -361,7 +363,7 @@ class FormAutofillParent extends JSWindowActorParent { break; } case "FormAutofill:SaveCreditCard": { - if (!(await lazy.FormAutofillUtils.ensureLoggedIn()).authenticated) { + if (!(await FormAutofillUtils.ensureLoggedIn()).authenticated) { lazy.log.warn("User canceled encryption login"); return undefined; } @@ -498,9 +500,7 @@ class FormAutofillParent extends JSWindowActorParent { ); showDoorhanger = async () => { - const description = lazy.FormAutofillUtils.getAddressLabel( - address.record - ); + const description = FormAutofillUtils.getAddressLabel(address.record); const state = await lazy.FormAutofillPrompter.promptToSaveAddress( browser, "updateAddress", @@ -574,9 +574,7 @@ class FormAutofillParent extends JSWindowActorParent { false ); showDoorhanger = async () => { - const description = lazy.FormAutofillUtils.getAddressLabel( - address.record - ); + const description = FormAutofillUtils.getAddressLabel(address.record); const state = await lazy.FormAutofillPrompter.promptToSaveAddress( browser, "firstTimeUse", diff --git a/toolkit/components/formautofill/FormAutofillTelemetryUtils.jsm b/toolkit/components/formautofill/FormAutofillTelemetryUtils.jsm index 3c689da377dd..4b568b20b97d 100644 --- a/toolkit/components/formautofill/FormAutofillTelemetryUtils.jsm +++ b/toolkit/components/formautofill/FormAutofillTelemetryUtils.jsm @@ -7,16 +7,11 @@ var EXPORTED_SYMBOLS = ["CreditCardTelemetry"]; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); - -const lazy = {}; - -ChromeUtils.defineModuleGetter( - lazy, - "FormAutofillUtils", +const { FormAutofillUtils } = ChromeUtils.import( "resource://autofill/FormAutofillUtils.jsm" ); -const { FIELD_STATES } = lazy.FormAutofillUtils; +const { FIELD_STATES } = FormAutofillUtils; const CreditCardTelemetry = { // Mapping of field name used in formautofill code to the field name diff --git a/toolkit/components/formautofill/android/FormAutofillStorage.jsm b/toolkit/components/formautofill/android/FormAutofillStorage.jsm index 4e8a462c47c8..aaa2000cbcc4 100644 --- a/toolkit/components/formautofill/android/FormAutofillStorage.jsm +++ b/toolkit/components/formautofill/android/FormAutofillStorage.jsm @@ -21,6 +21,7 @@ const { CreditCardsBase, AddressesBase, } = ChromeUtils.import("resource://autofill/FormAutofillStorageBase.jsm"); +const { JSONFile } = ChromeUtils.import("resource://gre/modules/JSONFile.jsm"); const lazy = {}; @@ -28,10 +29,9 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { GeckoViewAutocomplete: "resource://gre/modules/GeckoViewAutocomplete.jsm", CreditCard: "resource://gre/modules/GeckoViewAutocomplete.jsm", Address: "resource://gre/modules/GeckoViewAutocomplete.jsm", - JSONFile: "resource://gre/modules/JSONFile.jsm", }); -class GeckoViewStorage extends lazy.JSONFile { +class GeckoViewStorage extends JSONFile { constructor() { super({ path: null }); } diff --git a/toolkit/components/formautofill/phonenumberutils/PhoneNumber.jsm b/toolkit/components/formautofill/phonenumberutils/PhoneNumber.jsm index 320dde629ece..47146bddbd72 100644 --- a/toolkit/components/formautofill/phonenumberutils/PhoneNumber.jsm +++ b/toolkit/components/formautofill/phonenumberutils/PhoneNumber.jsm @@ -9,13 +9,12 @@ var EXPORTED_SYMBOLS = ["PhoneNumber"]; -const lazy = {}; - -ChromeUtils.defineModuleGetter( - lazy, - "PHONE_NUMBER_META_DATA", +const { PHONE_NUMBER_META_DATA } = ChromeUtils.import( "resource://autofill/phonenumberutils/PhoneNumberMetaData.jsm" ); + +const lazy = {}; + ChromeUtils.defineModuleGetter( lazy, "PhoneNumberNormalizer", @@ -477,4 +476,4 @@ var PhoneNumber = (function(dataBase) { IsPlain: IsPlainPhoneNumber, Parse: ParseNumber, }; -})(lazy.PHONE_NUMBER_META_DATA); +})(PHONE_NUMBER_META_DATA); From 1aa66537957459ef911d446521f5f8024d553d41 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:25 +0000 Subject: [PATCH 20/64] Bug 1773829 - Part 9: Stop using lazy getter unnecessarily in toolkit/components/normandy/. r=barret Depends on D149017 Differential Revision: https://phabricator.services.mozilla.com/D149018 --- .../normandy/NormandyMigrations.jsm | 32 +++++-------- .../normandy/actions/BaseAction.jsm | 46 ++++++++----------- .../components/normandy/lib/AddonStudies.jsm | 10 ++-- .../normandy/lib/ClientEnvironment.jsm | 10 ++-- .../normandy/lib/PreferenceExperiments.jsm | 21 ++++----- .../components/normandy/lib/RecipeRunner.jsm | 6 ++- toolkit/components/normandy/lib/Uptake.jsm | 42 ++++++++--------- 7 files changed, 71 insertions(+), 96 deletions(-) diff --git a/toolkit/components/normandy/NormandyMigrations.jsm b/toolkit/components/normandy/NormandyMigrations.jsm index 661982b783e3..603f187540ec 100644 --- a/toolkit/components/normandy/NormandyMigrations.jsm +++ b/toolkit/components/normandy/NormandyMigrations.jsm @@ -6,21 +6,13 @@ const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; - -ChromeUtils.defineModuleGetter( - lazy, - "AddonStudies", +const { AddonStudies } = ChromeUtils.import( "resource://normandy/lib/AddonStudies.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "PreferenceExperiments", +const { PreferenceExperiments } = ChromeUtils.import( "resource://normandy/lib/PreferenceExperiments.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "RecipeRunner", +const { RecipeRunner } = ChromeUtils.import( "resource://normandy/lib/RecipeRunner.jsm" ); @@ -62,17 +54,17 @@ const NormandyMigrations = { migrations: [ migrateShieldPrefs, migrateStudiesEnabledWithoutHealthReporting, - lazy.AddonStudies.migrations + AddonStudies.migrations .migration01AddonStudyFieldsToSlugAndUserFacingFields, - lazy.PreferenceExperiments.migrations.migration01MoveExperiments, - lazy.PreferenceExperiments.migrations.migration02MultiPreference, - lazy.PreferenceExperiments.migrations.migration03AddActionName, - lazy.PreferenceExperiments.migrations.migration04RenameNameToSlug, - lazy.RecipeRunner.migrations.migration01RemoveOldRecipesCollection, - lazy.AddonStudies.migrations.migration02RemoveOldAddonStudyAction, + PreferenceExperiments.migrations.migration01MoveExperiments, + PreferenceExperiments.migrations.migration02MultiPreference, + PreferenceExperiments.migrations.migration03AddActionName, + PreferenceExperiments.migrations.migration04RenameNameToSlug, + RecipeRunner.migrations.migration01RemoveOldRecipesCollection, + AddonStudies.migrations.migration02RemoveOldAddonStudyAction, migrateRemoveLastBuildIdPref, - lazy.PreferenceExperiments.migrations.migration05RemoveOldAction, - lazy.PreferenceExperiments.migrations.migration06TrackOverriddenPrefs, + PreferenceExperiments.migrations.migration05RemoveOldAction, + PreferenceExperiments.migrations.migration06TrackOverriddenPrefs, ], }; diff --git a/toolkit/components/normandy/actions/BaseAction.jsm b/toolkit/components/normandy/actions/BaseAction.jsm index bb9609eb746b..b8c17a3e2e2d 100644 --- a/toolkit/components/normandy/actions/BaseAction.jsm +++ b/toolkit/components/normandy/actions/BaseAction.jsm @@ -1,18 +1,16 @@ -const lazy = {}; /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +const { Uptake } = ChromeUtils.import("resource://normandy/lib/Uptake.jsm"); + +const lazy = {}; + ChromeUtils.defineModuleGetter( lazy, "LogManager", "resource://normandy/lib/LogManager.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "Uptake", - "resource://normandy/lib/Uptake.jsm" -); ChromeUtils.defineModuleGetter( lazy, "JsonSchemaValidator", @@ -87,10 +85,7 @@ class BaseAction { fail(err) { switch (this.state) { case BaseAction.STATE_PREPARING: { - lazy.Uptake.reportAction( - this.name, - lazy.Uptake.ACTION_PRE_EXECUTION_ERROR - ); + Uptake.reportAction(this.name, Uptake.ACTION_PRE_EXECUTION_ERROR); break; } default: { @@ -155,7 +150,7 @@ class BaseAction { } if (this.state !== BaseAction.STATE_READY) { - lazy.Uptake.reportRecipe(recipe, lazy.Uptake.RECIPE_ACTION_DISABLED); + Uptake.reportRecipe(recipe, Uptake.RECIPE_ACTION_DISABLED); this.log.warn( `Skipping recipe ${recipe.name} because ${this.name} was disabled during preExecution.` ); @@ -176,7 +171,7 @@ class BaseAction { recipe.arguments = this.validateArguments(recipe.arguments); } catch (error) { Cu.reportError(error); - uptakeResult = lazy.Uptake.RECIPE_EXECUTION_ERROR; + uptakeResult = Uptake.RECIPE_EXECUTION_ERROR; suitability = BaseAction.suitability.ARGUMENTS_INVALID; } } @@ -185,9 +180,9 @@ class BaseAction { await this._processRecipe(recipe, suitability); } catch (err) { Cu.reportError(err); - uptakeResult = lazy.Uptake.RECIPE_EXECUTION_ERROR; + uptakeResult = Uptake.RECIPE_EXECUTION_ERROR; } - lazy.Uptake.reportRecipe(recipe, uptakeResult); + Uptake.reportRecipe(recipe, uptakeResult); } /** @@ -242,9 +237,9 @@ class BaseAction { case BaseAction.STATE_READY: { try { await this._finalize(options); - status = lazy.Uptake.ACTION_SUCCESS; + status = Uptake.ACTION_SUCCESS; } catch (err) { - status = lazy.Uptake.ACTION_POST_EXECUTION_ERROR; + status = Uptake.ACTION_POST_EXECUTION_ERROR; // Sometimes Error.message can be updated in place. This gives better messages when debugging errors. try { err.message = `Could not run postExecution hook for ${this.name}: ${err.message}`; @@ -262,7 +257,7 @@ class BaseAction { this.log.debug( `Skipping post-execution hook for ${this.name} because it is disabled.` ); - status = lazy.Uptake.ACTION_SUCCESS; + status = Uptake.ACTION_SUCCESS; break; } case BaseAction.STATE_FAILED: { @@ -279,7 +274,7 @@ class BaseAction { this.state = BaseAction.STATE_FINALIZED; if (status) { - lazy.Uptake.reportAction(this.name, status); + Uptake.reportAction(this.name, status); } } @@ -342,14 +337,11 @@ BaseAction.suitability = { BaseAction.suitabilitySet = new Set(Object.values(BaseAction.suitability)); BaseAction.suitabilityToUptakeStatus = { - [BaseAction.suitability.SIGNATURE_ERROR]: - lazy.Uptake.RECIPE_INVALID_SIGNATURE, + [BaseAction.suitability.SIGNATURE_ERROR]: Uptake.RECIPE_INVALID_SIGNATURE, [BaseAction.suitability.CAPABILITIES_MISMATCH]: - lazy.Uptake.RECIPE_INCOMPATIBLE_CAPABILITIES, - [BaseAction.suitability.FILTER_MATCH]: lazy.Uptake.RECIPE_SUCCESS, - [BaseAction.suitability.FILTER_MISMATCH]: - lazy.Uptake.RECIPE_DIDNT_MATCH_FILTER, - [BaseAction.suitability.FILTER_ERROR]: lazy.Uptake.RECIPE_FILTER_BROKEN, - [BaseAction.suitability.ARGUMENTS_INVALID]: - lazy.Uptake.RECIPE_ARGUMENTS_INVALID, + Uptake.RECIPE_INCOMPATIBLE_CAPABILITIES, + [BaseAction.suitability.FILTER_MATCH]: Uptake.RECIPE_SUCCESS, + [BaseAction.suitability.FILTER_MISMATCH]: Uptake.RECIPE_DIDNT_MATCH_FILTER, + [BaseAction.suitability.FILTER_ERROR]: Uptake.RECIPE_FILTER_BROKEN, + [BaseAction.suitability.ARGUMENTS_INVALID]: Uptake.RECIPE_ARGUMENTS_INVALID, }; diff --git a/toolkit/components/normandy/lib/AddonStudies.jsm b/toolkit/components/normandy/lib/AddonStudies.jsm index 15bf2848a80d..37413eaa7e05 100644 --- a/toolkit/components/normandy/lib/AddonStudies.jsm +++ b/toolkit/components/normandy/lib/AddonStudies.jsm @@ -45,6 +45,9 @@ */ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { LogManager } = ChromeUtils.import( + "resource://normandy/lib/LogManager.jsm" +); const lazy = {}; @@ -68,11 +71,6 @@ ChromeUtils.defineModuleGetter( "CleanupManager", "resource://normandy/lib/CleanupManager.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "LogManager", - "resource://normandy/lib/LogManager.jsm" -); ChromeUtils.defineModuleGetter( lazy, "TelemetryEnvironment", @@ -91,7 +89,7 @@ const STORE_NAME = "addon-studies"; const VERSION_STORE_NAME = "addon-studies-version"; const DB_VERSION = 2; const STUDY_ENDED_TOPIC = "shield-study-ended"; -const log = lazy.LogManager.getLogger("addon-studies"); +const log = LogManager.getLogger("addon-studies"); /** * Create a new connection to the database. diff --git a/toolkit/components/normandy/lib/ClientEnvironment.jsm b/toolkit/components/normandy/lib/ClientEnvironment.jsm index 5141fe6ac47e..39bb8477bb46 100644 --- a/toolkit/components/normandy/lib/ClientEnvironment.jsm +++ b/toolkit/components/normandy/lib/ClientEnvironment.jsm @@ -5,6 +5,9 @@ "use strict"; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { ClientEnvironmentBase } = ChromeUtils.import( + "resource://gre/modules/components-utils/ClientEnvironment.jsm" +); const lazy = {}; @@ -13,11 +16,6 @@ ChromeUtils.defineModuleGetter( "NormandyApi", "resource://normandy/lib/NormandyApi.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "ClientEnvironmentBase", - "resource://gre/modules/components-utils/ClientEnvironment.jsm" -); ChromeUtils.defineModuleGetter( lazy, "PreferenceExperiments", @@ -45,7 +43,7 @@ var EXPORTED_SYMBOLS = ["ClientEnvironment"]; // service. let _classifyRequest = null; -class ClientEnvironment extends lazy.ClientEnvironmentBase { +class ClientEnvironment extends ClientEnvironmentBase { /** * Fetches information about the client that is calculated on the server, * like geolocation and the current time. diff --git a/toolkit/components/normandy/lib/PreferenceExperiments.jsm b/toolkit/components/normandy/lib/PreferenceExperiments.jsm index f0883cd6c3a1..f8063753c2b2 100644 --- a/toolkit/components/normandy/lib/PreferenceExperiments.jsm +++ b/toolkit/components/normandy/lib/PreferenceExperiments.jsm @@ -82,22 +82,19 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; -ChromeUtils.defineModuleGetter( - lazy, - "CleanupManager", +const { CleanupManager } = ChromeUtils.import( "resource://normandy/lib/CleanupManager.jsm" ); +const { LogManager } = ChromeUtils.import( + "resource://normandy/lib/LogManager.jsm" +); + +const lazy = {}; ChromeUtils.defineModuleGetter( lazy, "JSONFile", "resource://gre/modules/JSONFile.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "LogManager", - "resource://normandy/lib/LogManager.jsm" -); ChromeUtils.defineModuleGetter( lazy, "TelemetryEnvironment", @@ -174,11 +171,11 @@ function ensureStorage() { return gStorePromise; } -const log = lazy.LogManager.getLogger("preference-experiments"); +const log = LogManager.getLogger("preference-experiments"); // List of active preference observers. Cleaned up on shutdown. let experimentObservers = new Map(); -lazy.CleanupManager.addCleanupHandler(() => +CleanupManager.addCleanupHandler(() => PreferenceExperiments.stopAllObservers() ); @@ -220,7 +217,7 @@ var PreferenceExperiments = { * default preference branch. */ async init() { - lazy.CleanupManager.addCleanupHandler(() => this.saveStartupPrefs()); + CleanupManager.addCleanupHandler(() => this.saveStartupPrefs()); for (const experiment of await this.getAllActive()) { // Check that the current value of the preference is still what we set it to diff --git a/toolkit/components/normandy/lib/RecipeRunner.jsm b/toolkit/components/normandy/lib/RecipeRunner.jsm index f00a5d1e7165..e02cb893ee50 100644 --- a/toolkit/components/normandy/lib/RecipeRunner.jsm +++ b/toolkit/components/normandy/lib/RecipeRunner.jsm @@ -11,6 +11,9 @@ const { XPCOMUtils } = ChromeUtils.import( const { LogManager } = ChromeUtils.import( "resource://normandy/lib/LogManager.jsm" ); +const { PromiseUtils } = ChromeUtils.import( + "resource://gre/modules/PromiseUtils.jsm" +); const lazy = {}; @@ -37,7 +40,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { RemoteSettingsClient: "resource://services-settings/RemoteSettingsClient.jsm", clearTimeout: "resource://gre/modules/Timer.jsm", setTimeout: "resource://gre/modules/Timer.jsm", - PromiseUtils: "resource://gre/modules/PromiseUtils.jsm", }); var EXPORTED_SYMBOLS = ["RecipeRunner"]; @@ -88,7 +90,7 @@ function cacheProxy(target) { } var RecipeRunner = { - initializedPromise: lazy.PromiseUtils.defer(), + initializedPromise: PromiseUtils.defer(), async init() { this.running = false; diff --git a/toolkit/components/normandy/lib/Uptake.jsm b/toolkit/components/normandy/lib/Uptake.jsm index 0bb0b142dfae..5ba5669b7730 100644 --- a/toolkit/components/normandy/lib/Uptake.jsm +++ b/toolkit/components/normandy/lib/Uptake.jsm @@ -4,11 +4,7 @@ "use strict"; -const lazy = {}; - -ChromeUtils.defineModuleGetter( - lazy, - "UptakeTelemetry", +const { UptakeTelemetry } = ChromeUtils.import( "resource://services-common/uptake-telemetry.js" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); @@ -19,27 +15,27 @@ const COMPONENT = "normandy"; var Uptake = { // Action uptake - ACTION_NETWORK_ERROR: lazy.UptakeTelemetry.STATUS.NETWORK_ERROR, - ACTION_PRE_EXECUTION_ERROR: lazy.UptakeTelemetry.STATUS.CUSTOM_1_ERROR, - ACTION_POST_EXECUTION_ERROR: lazy.UptakeTelemetry.STATUS.CUSTOM_2_ERROR, - ACTION_SERVER_ERROR: lazy.UptakeTelemetry.STATUS.SERVER_ERROR, - ACTION_SUCCESS: lazy.UptakeTelemetry.STATUS.SUCCESS, + ACTION_NETWORK_ERROR: UptakeTelemetry.STATUS.NETWORK_ERROR, + ACTION_PRE_EXECUTION_ERROR: UptakeTelemetry.STATUS.CUSTOM_1_ERROR, + ACTION_POST_EXECUTION_ERROR: UptakeTelemetry.STATUS.CUSTOM_2_ERROR, + ACTION_SERVER_ERROR: UptakeTelemetry.STATUS.SERVER_ERROR, + ACTION_SUCCESS: UptakeTelemetry.STATUS.SUCCESS, // Per-recipe uptake - RECIPE_ACTION_DISABLED: lazy.UptakeTelemetry.STATUS.CUSTOM_1_ERROR, - RECIPE_DIDNT_MATCH_FILTER: lazy.UptakeTelemetry.STATUS.BACKOFF, - RECIPE_INCOMPATIBLE_CAPABILITIES: lazy.UptakeTelemetry.STATUS.BACKOFF, - RECIPE_EXECUTION_ERROR: lazy.UptakeTelemetry.STATUS.APPLY_ERROR, - RECIPE_FILTER_BROKEN: lazy.UptakeTelemetry.STATUS.CONTENT_ERROR, - RECIPE_ARGUMENTS_INVALID: lazy.UptakeTelemetry.STATUS.CONTENT_ERROR, - RECIPE_INVALID_ACTION: lazy.UptakeTelemetry.STATUS.DOWNLOAD_ERROR, - RECIPE_SUCCESS: lazy.UptakeTelemetry.STATUS.SUCCESS, - RECIPE_INVALID_SIGNATURE: lazy.UptakeTelemetry.STATUS.SIGNATURE_ERROR, + RECIPE_ACTION_DISABLED: UptakeTelemetry.STATUS.CUSTOM_1_ERROR, + RECIPE_DIDNT_MATCH_FILTER: UptakeTelemetry.STATUS.BACKOFF, + RECIPE_INCOMPATIBLE_CAPABILITIES: UptakeTelemetry.STATUS.BACKOFF, + RECIPE_EXECUTION_ERROR: UptakeTelemetry.STATUS.APPLY_ERROR, + RECIPE_FILTER_BROKEN: UptakeTelemetry.STATUS.CONTENT_ERROR, + RECIPE_ARGUMENTS_INVALID: UptakeTelemetry.STATUS.CONTENT_ERROR, + RECIPE_INVALID_ACTION: UptakeTelemetry.STATUS.DOWNLOAD_ERROR, + RECIPE_SUCCESS: UptakeTelemetry.STATUS.SUCCESS, + RECIPE_INVALID_SIGNATURE: UptakeTelemetry.STATUS.SIGNATURE_ERROR, // Uptake for the runner as a whole - RUNNER_NETWORK_ERROR: lazy.UptakeTelemetry.STATUS.NETWORK_ERROR, - RUNNER_SERVER_ERROR: lazy.UptakeTelemetry.STATUS.SERVER_ERROR, - RUNNER_SUCCESS: lazy.UptakeTelemetry.STATUS.SUCCESS, + RUNNER_NETWORK_ERROR: UptakeTelemetry.STATUS.NETWORK_ERROR, + RUNNER_SERVER_ERROR: UptakeTelemetry.STATUS.SERVER_ERROR, + RUNNER_SUCCESS: UptakeTelemetry.STATUS.SUCCESS, async _report(status, source) { // Telemetry doesn't help us much with error detection, so do some here. @@ -53,7 +49,7 @@ var Uptake = { `Uptake source is required (got "${JSON.stringify(status)}` ); } - await lazy.UptakeTelemetry.report(COMPONENT, status, { + await UptakeTelemetry.report(COMPONENT, status, { source: `${COMPONENT}/${source}`, }); }, From 6dc0ff40f70c083d5ad0059ab52e0bb645dc745f Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:25 +0000 Subject: [PATCH 21/64] Bug 1773829 - Part 10: Stop using lazy getter unnecessarily in toolkit/components/passwordmgr/. r=MattN Depends on D149018 Differential Revision: https://phabricator.services.mozilla.com/D149019 --- toolkit/components/passwordmgr/LoginStore.jsm | 18 ++++--- .../passwordmgr/NewPasswordModel.jsm | 8 +--- .../components/passwordmgr/OSCrypto_win.jsm | 47 +++++++------------ 3 files changed, 28 insertions(+), 45 deletions(-) diff --git a/toolkit/components/passwordmgr/LoginStore.jsm b/toolkit/components/passwordmgr/LoginStore.jsm index e571305d301a..d69cec3cd131 100644 --- a/toolkit/components/passwordmgr/LoginStore.jsm +++ b/toolkit/components/passwordmgr/LoginStore.jsm @@ -43,17 +43,15 @@ const EXPORTED_SYMBOLS = ["LoginStore"]; // Globals const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; -ChromeUtils.defineModuleGetter(lazy, "OS", "resource://gre/modules/osfile.jsm"); -ChromeUtils.defineModuleGetter( - lazy, - "JSONFile", - "resource://gre/modules/JSONFile.jsm" -); +const { JSONFile } = ChromeUtils.import("resource://gre/modules/JSONFile.jsm"); const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); +const lazy = {}; + +ChromeUtils.defineModuleGetter(lazy, "OS", "resource://gre/modules/osfile.jsm"); + XPCOMUtils.defineLazyModuleGetters(lazy, { FXA_PWDMGR_HOST: "resource://gre/modules/FxAccountsCommon.js", FXA_PWDMGR_REALM: "resource://gre/modules/FxAccountsCommon.js", @@ -87,18 +85,18 @@ const MAX_DATE_MS = 8640000000000000; * String containing the file path where data should be saved. */ function LoginStore(aPath, aBackupPath = "") { - lazy.JSONFile.call(this, { + JSONFile.call(this, { path: aPath, dataPostProcessor: this._dataPostProcessor.bind(this), backupTo: aBackupPath, }); } -LoginStore.prototype = Object.create(lazy.JSONFile.prototype); +LoginStore.prototype = Object.create(JSONFile.prototype); LoginStore.prototype.constructor = LoginStore; LoginStore.prototype._save = async function() { - await lazy.JSONFile.prototype._save.call(this); + await JSONFile.prototype._save.call(this); // Notify tests that writes to the login store is complete. Services.obs.notifyObservers(null, "password-storage-updated"); diff --git a/toolkit/components/passwordmgr/NewPasswordModel.jsm b/toolkit/components/passwordmgr/NewPasswordModel.jsm index f6e5ded7273b..129defd5dadb 100644 --- a/toolkit/components/passwordmgr/NewPasswordModel.jsm +++ b/toolkit/components/passwordmgr/NewPasswordModel.jsm @@ -9,11 +9,7 @@ const EXPORTED_SYMBOLS = ["NewPasswordModel"]; -const lazy = {}; - -ChromeUtils.defineModuleGetter( - lazy, - "fathom", +const { fathom } = ChromeUtils.import( "resource://gre/modules/third_party/fathom/fathom.jsm" ); @@ -27,7 +23,7 @@ const { type, utils: { identity, isVisible, min, setDefault }, clusters: { euclidean }, -} = lazy.fathom; +} = fathom; /** * ----- Start of model ----- diff --git a/toolkit/components/passwordmgr/OSCrypto_win.jsm b/toolkit/components/passwordmgr/OSCrypto_win.jsm index 41d443b49049..d5878fdbe0bd 100644 --- a/toolkit/components/passwordmgr/OSCrypto_win.jsm +++ b/toolkit/components/passwordmgr/OSCrypto_win.jsm @@ -6,39 +6,33 @@ const EXPORTED_SYMBOLS = ["OSCrypto"]; -const lazy = {}; - -ChromeUtils.defineModuleGetter( - lazy, - "ctypes", - "resource://gre/modules/ctypes.jsm" -); +const { ctypes } = ChromeUtils.import("resource://gre/modules/ctypes.jsm"); const FLAGS_NOT_SET = 0; const wintypes = { - BOOL: lazy.ctypes.bool, - BYTE: lazy.ctypes.uint8_t, - DWORD: lazy.ctypes.uint32_t, - PBYTE: lazy.ctypes.unsigned_char.ptr, - PCHAR: lazy.ctypes.char.ptr, - PDWORD: lazy.ctypes.uint32_t.ptr, - PVOID: lazy.ctypes.voidptr_t, - WORD: lazy.ctypes.uint16_t, + BOOL: ctypes.bool, + BYTE: ctypes.uint8_t, + DWORD: ctypes.uint32_t, + PBYTE: ctypes.unsigned_char.ptr, + PCHAR: ctypes.char.ptr, + PDWORD: ctypes.uint32_t.ptr, + PVOID: ctypes.voidptr_t, + WORD: ctypes.uint16_t, }; function OSCrypto() { this._structs = {}; this._functions = new Map(); this._libs = new Map(); - this._structs.DATA_BLOB = new lazy.ctypes.StructType("DATA_BLOB", [ + this._structs.DATA_BLOB = new ctypes.StructType("DATA_BLOB", [ { cbData: wintypes.DWORD }, { pbData: wintypes.PVOID }, ]); try { - this._libs.set("crypt32", lazy.ctypes.open("Crypt32")); - this._libs.set("kernel32", lazy.ctypes.open("Kernel32")); + this._libs.set("crypt32", ctypes.open("Crypt32")); + this._libs.set("kernel32", ctypes.open("Kernel32")); this._functions.set( "CryptProtectData", @@ -46,7 +40,7 @@ function OSCrypto() { .get("crypt32") .declare( "CryptProtectData", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, this._structs.DATA_BLOB.ptr, wintypes.PVOID, @@ -63,7 +57,7 @@ function OSCrypto() { .get("crypt32") .declare( "CryptUnprotectData", - lazy.ctypes.winapi_abi, + ctypes.winapi_abi, wintypes.DWORD, this._structs.DATA_BLOB.ptr, wintypes.PVOID, @@ -78,12 +72,7 @@ function OSCrypto() { "LocalFree", this._libs .get("kernel32") - .declare( - "LocalFree", - lazy.ctypes.winapi_abi, - wintypes.DWORD, - wintypes.PVOID - ) + .declare("LocalFree", ctypes.winapi_abi, wintypes.DWORD, wintypes.PVOID) ); } catch (ex) { Cu.reportError(ex); @@ -181,7 +170,7 @@ OSCrypto.prototype = { _convertWinArrayToJSArray(dataBlob) { // Convert DATA_BLOB to JS accessible array - return lazy.ctypes.cast( + return ctypes.cast( dataBlob.pbData, wintypes.BYTE.array(dataBlob.cbData).ptr ).contents; @@ -216,7 +205,7 @@ OSCrypto.prototype = { outData.address() ); if (status === 0) { - throw new Error("decryptData failed: " + lazy.ctypes.winLastError); + throw new Error("decryptData failed: " + ctypes.winLastError); } let decrypted = this._convertWinArrayToJSArray(outData); @@ -268,7 +257,7 @@ OSCrypto.prototype = { outData.address() ); if (status === 0) { - throw new Error("encryptData failed: " + lazy.ctypes.winLastError); + throw new Error("encryptData failed: " + ctypes.winLastError); } let encrypted = this._convertWinArrayToJSArray(outData); From 016668ba23c7acd60e73a70752c1fb6afd2452a1 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:26 +0000 Subject: [PATCH 22/64] Bug 1773829 - Part 11: Stop using lazy getter unnecessarily in toolkit/components/telemetry/. r=chutten Depends on D149019 Differential Revision: https://phabricator.services.mozilla.com/D149020 --- .../app/TelemetryControllerParent.jsm | 14 +++++++------ .../telemetry/app/TelemetryEnvironment.jsm | 16 +++++++------- .../telemetry/pings/CoveragePing.jsm | 8 +++---- .../components/telemetry/pings/EventPing.jsm | 14 ++++++------- .../components/telemetry/pings/HealthPing.jsm | 21 +++++++++---------- .../telemetry/pings/ModulesPing.jsm | 15 ++++++------- .../telemetry/pings/UntrustedModulesPing.jsm | 9 +++----- 7 files changed, 44 insertions(+), 53 deletions(-) diff --git a/toolkit/components/telemetry/app/TelemetryControllerParent.jsm b/toolkit/components/telemetry/app/TelemetryControllerParent.jsm index 57b93074d35c..3b10139d8c02 100644 --- a/toolkit/components/telemetry/app/TelemetryControllerParent.jsm +++ b/toolkit/components/telemetry/app/TelemetryControllerParent.jsm @@ -8,6 +8,9 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { AsyncShutdown } = ChromeUtils.import( + "resource://gre/modules/AsyncShutdown.jsm" +); const { PromiseUtils } = ChromeUtils.import( "resource://gre/modules/PromiseUtils.jsm" ); @@ -59,7 +62,6 @@ ChromeUtils.defineModuleGetter( XPCOMUtils.defineLazyModuleGetters(lazy, { ClientID: "resource://gre/modules/ClientID.jsm", CoveragePing: "resource://gre/modules/CoveragePing.jsm", - AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm", TelemetryStorage: "resource://gre/modules/TelemetryStorage.jsm", TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.jsm", TelemetryArchive: "resource://gre/modules/TelemetryArchive.jsm", @@ -301,13 +303,13 @@ var Impl = { // This is a public barrier Telemetry clients can use to add blockers to the shutdown // of TelemetryController. // After this barrier, clients can not submit Telemetry pings anymore. - _shutdownBarrier: new lazy.AsyncShutdown.Barrier( + _shutdownBarrier: new AsyncShutdown.Barrier( "TelemetryController: Waiting for clients." ), // This state is included in the async shutdown annotation for crash pings and reports. _shutdownState: "Shutdown not started.", // This is a private barrier blocked by pending async ping activity (sending & saving). - _connectionsBarrier: new lazy.AsyncShutdown.Barrier( + _connectionsBarrier: new AsyncShutdown.Barrier( "TelemetryController: Waiting for pending ping activity" ), // This is true when running in the test infrastructure. @@ -910,7 +912,7 @@ var Impl = { this._testMode ? 0 : undefined ); - lazy.AsyncShutdown.sendTelemetry.addBlocker( + AsyncShutdown.sendTelemetry.addBlocker( "TelemetryController: shutting down", () => this.shutdown(), () => this._getState() @@ -1230,10 +1232,10 @@ var Impl = { let sessionReset = lazy.TelemetrySession.testReset(); - this._connectionsBarrier = new lazy.AsyncShutdown.Barrier( + this._connectionsBarrier = new AsyncShutdown.Barrier( "TelemetryController: Waiting for pending ping activity" ); - this._shutdownBarrier = new lazy.AsyncShutdown.Barrier( + this._shutdownBarrier = new AsyncShutdown.Barrier( "TelemetryController: Waiting for clients." ); diff --git a/toolkit/components/telemetry/app/TelemetryEnvironment.jsm b/toolkit/components/telemetry/app/TelemetryEnvironment.jsm index 192f305a92c6..61fb897b61c3 100644 --- a/toolkit/components/telemetry/app/TelemetryEnvironment.jsm +++ b/toolkit/components/telemetry/app/TelemetryEnvironment.jsm @@ -17,6 +17,9 @@ const { ObjectUtils } = ChromeUtils.import( const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { UpdateUtils } = ChromeUtils.import( + "resource://gre/modules/UpdateUtils.jsm" +); const Utils = TelemetryUtils; @@ -41,11 +44,6 @@ ChromeUtils.defineModuleGetter( "WindowsRegistry", "resource://gre/modules/WindowsRegistry.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "UpdateUtils", - "resource://gre/modules/UpdateUtils.jsm" -); const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); @@ -396,9 +394,9 @@ const SESSIONSTORE_WINDOWS_RESTORED_TOPIC = "sessionstore-windows-restored"; const PREF_CHANGED_TOPIC = "nsPref:changed"; const GMP_PROVIDER_REGISTERED_TOPIC = "gmp-provider-registered"; const AUTO_UPDATE_PREF_CHANGE_TOPIC = - lazy.UpdateUtils.PER_INSTALLATION_PREFS["app.update.auto"].observerTopic; + UpdateUtils.PER_INSTALLATION_PREFS["app.update.auto"].observerTopic; const BACKGROUND_UPDATE_PREF_CHANGE_TOPIC = - lazy.UpdateUtils.PER_INSTALLATION_PREFS["app.update.background.enabled"] + UpdateUtils.PER_INSTALLATION_PREFS["app.update.background.enabled"] .observerTopic; const SERVICES_INFO_CHANGE_TOPIC = "sync-ui-state:update"; const FIREFOX_SUGGEST_UPDATE_TOPIC = "firefox-suggest-update"; @@ -1727,8 +1725,8 @@ EnvironmentCache.prototype = { */ async _loadAsyncUpdateSettings() { if (AppConstants.MOZ_UPDATER) { - this._updateAutoDownloadCache = await lazy.UpdateUtils.getAppUpdateAutoEnabled(); - this._updateBackgroundCache = await lazy.UpdateUtils.readUpdateConfigSetting( + this._updateAutoDownloadCache = await UpdateUtils.getAppUpdateAutoEnabled(); + this._updateBackgroundCache = await UpdateUtils.readUpdateConfigSetting( "app.update.background.enabled" ); } else { diff --git a/toolkit/components/telemetry/pings/CoveragePing.jsm b/toolkit/components/telemetry/pings/CoveragePing.jsm index ab13a4d3c226..7a20b35de0d8 100644 --- a/toolkit/components/telemetry/pings/CoveragePing.jsm +++ b/toolkit/components/telemetry/pings/CoveragePing.jsm @@ -4,6 +4,7 @@ "use strict"; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); const lazy = {}; @@ -12,7 +13,6 @@ ChromeUtils.defineModuleGetter( "CommonUtils", "resource://services-common/utils.js" ); -ChromeUtils.defineModuleGetter(lazy, "Log", "resource://gre/modules/Log.jsm"); ChromeUtils.defineModuleGetter( lazy, "PromiseUtils", @@ -43,9 +43,9 @@ const REPORTING_ENDPOINT_BASE_PREF = `toolkit.coverage.endpoint.base`; const REPORTING_ENDPOINT = "submit/coverage/coverage"; const PING_SUBMISSION_TIMEOUT = 30 * 1000; // 30 seconds -const log = lazy.Log.repository.getLogger("Telemetry::CoveragePing"); -log.level = Services.prefs.getIntPref(LOG_LEVEL_PREF, lazy.Log.Level.Error); -log.addAppender(new lazy.Log.ConsoleAppender(new lazy.Log.BasicFormatter())); +const log = Log.repository.getLogger("Telemetry::CoveragePing"); +log.level = Services.prefs.getIntPref(LOG_LEVEL_PREF, Log.Level.Error); +log.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter())); var CoveragePing = Object.freeze({ async startup() { diff --git a/toolkit/components/telemetry/pings/EventPing.jsm b/toolkit/components/telemetry/pings/EventPing.jsm index edd07b451d99..8421a1284c1a 100644 --- a/toolkit/components/telemetry/pings/EventPing.jsm +++ b/toolkit/components/telemetry/pings/EventPing.jsm @@ -11,6 +11,10 @@ var EXPORTED_SYMBOLS = ["TelemetryEventPing", "Policy"]; +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { TelemetryUtils } = ChromeUtils.import( + "resource://gre/modules/TelemetryUtils.jsm" +); const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); @@ -33,14 +37,8 @@ ChromeUtils.defineModuleGetter( "clearTimeout", "resource://gre/modules/Timer.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "TelemetryUtils", - "resource://gre/modules/TelemetryUtils.jsm" -); -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const Utils = lazy.TelemetryUtils; +const Utils = TelemetryUtils; const MS_IN_A_MINUTE = 60 * 1000; @@ -90,7 +88,7 @@ var TelemetryEventPing = { // Calculate process creation once. this._processStartTimestamp = Math.round( - (Date.now() - lazy.TelemetryUtils.monotonicNow()) / MS_IN_A_MINUTE + (Date.now() - TelemetryUtils.monotonicNow()) / MS_IN_A_MINUTE ) * MS_IN_A_MINUTE; Services.obs.addObserver(this, EVENT_LIMIT_REACHED_TOPIC); diff --git a/toolkit/components/telemetry/pings/HealthPing.jsm b/toolkit/components/telemetry/pings/HealthPing.jsm index ee55752eb4ce..de5d6694f582 100644 --- a/toolkit/components/telemetry/pings/HealthPing.jsm +++ b/toolkit/components/telemetry/pings/HealthPing.jsm @@ -10,6 +10,14 @@ var EXPORTED_SYMBOLS = ["TelemetryHealthPing", "Policy"]; +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { TelemetryUtils } = ChromeUtils.import( + "resource://gre/modules/TelemetryUtils.jsm" +); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); + const lazy = {}; ChromeUtils.defineModuleGetter( @@ -27,18 +35,9 @@ ChromeUtils.defineModuleGetter( "clearTimeout", "resource://gre/modules/Timer.jsm" ); -ChromeUtils.defineModuleGetter( - lazy, - "TelemetryUtils", - "resource://gre/modules/TelemetryUtils.jsm" -); -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.defineModuleGetter(lazy, "Log", "resource://gre/modules/Log.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); -const Utils = lazy.TelemetryUtils; +const Utils = TelemetryUtils; const MS_IN_A_MINUTE = 60 * 1000; // Send health ping every hour @@ -285,6 +284,6 @@ var TelemetryHealthPing = { XPCOMUtils.defineLazyPreferenceGetter( TelemetryHealthPing, "enabled", - lazy.TelemetryUtils.Preferences.HealthPingEnabled, + TelemetryUtils.Preferences.HealthPingEnabled, true ); diff --git a/toolkit/components/telemetry/pings/ModulesPing.jsm b/toolkit/components/telemetry/pings/ModulesPing.jsm index 657b8540085e..7479b7e1a16f 100644 --- a/toolkit/components/telemetry/pings/ModulesPing.jsm +++ b/toolkit/components/telemetry/pings/ModulesPing.jsm @@ -4,6 +4,11 @@ "use strict"; +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); @@ -15,16 +20,11 @@ ChromeUtils.defineModuleGetter( "Preferences", "resource://gre/modules/Preferences.jsm" ); -ChromeUtils.defineModuleGetter(lazy, "Log", "resource://gre/modules/Log.jsm"); ChromeUtils.defineModuleGetter( lazy, "TelemetryController", "resource://gre/modules/TelemetryController.jsm" ); -const { AppConstants } = ChromeUtils.import( - "resource://gre/modules/AppConstants.jsm" -); -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); XPCOMUtils.defineLazyServiceGetter( lazy, @@ -48,10 +48,7 @@ const MAX_NAME_LENGTH = 64; const TRUNCATION_DELIMITER = "\u2026"; var TelemetryModules = Object.freeze({ - _log: lazy.Log.repository.getLoggerWithMessagePrefix( - LOGGER_NAME, - LOGGER_PREFIX - ), + _log: Log.repository.getLoggerWithMessagePrefix(LOGGER_NAME, LOGGER_PREFIX), start() { // The list of loaded modules is obtainable only when the profiler is enabled. diff --git a/toolkit/components/telemetry/pings/UntrustedModulesPing.jsm b/toolkit/components/telemetry/pings/UntrustedModulesPing.jsm index 2461025e1655..cc0d9ff4ea85 100644 --- a/toolkit/components/telemetry/pings/UntrustedModulesPing.jsm +++ b/toolkit/components/telemetry/pings/UntrustedModulesPing.jsm @@ -13,15 +13,15 @@ var EXPORTED_SYMBOLS = ["TelemetryUntrustedModulesPing"]; +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { - Log: "resource://gre/modules/Log.jsm", TelemetryController: "resource://gre/modules/TelemetryController.jsm", TelemetryUtils: "resource://gre/modules/TelemetryUtils.jsm", }); @@ -41,10 +41,7 @@ const TIMER_NAME = "telemetry_untrustedmodules_ping"; const PING_SUBMISSION_NAME = "third-party-modules"; var TelemetryUntrustedModulesPing = Object.freeze({ - _log: lazy.Log.repository.getLoggerWithMessagePrefix( - LOGGER_NAME, - LOGGER_PREFIX - ), + _log: Log.repository.getLoggerWithMessagePrefix(LOGGER_NAME, LOGGER_PREFIX), start() { lazy.UpdateTimerManager.registerTimer( From 9a3aad0024ee0daae7da9f0d3f83a8ae2580a0a2 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 20:56:26 +0000 Subject: [PATCH 23/64] Bug 1773829 - Part 13: Stop using lazy getter unnecessarily in toolkit/mozapps/update/. r=application-update-reviewers,nalexander Depends on D149021 Differential Revision: https://phabricator.services.mozilla.com/D149022 --- toolkit/mozapps/update/BackgroundUpdate.jsm | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/toolkit/mozapps/update/BackgroundUpdate.jsm b/toolkit/mozapps/update/BackgroundUpdate.jsm index 7d150f595097..2a0e56b787b7 100644 --- a/toolkit/mozapps/update/BackgroundUpdate.jsm +++ b/toolkit/mozapps/update/BackgroundUpdate.jsm @@ -7,20 +7,22 @@ var EXPORTED_SYMBOLS = ["BackgroundUpdate"]; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +const { BackgroundTasksManager } = ChromeUtils.import( + "resource://gre/modules/BackgroundTasksManager.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const lazy = {}; XPCOMUtils.defineLazyModuleGetters(lazy, { AddonManager: "resource://gre/modules/AddonManager.jsm", BackgroundTasksUtils: "resource://gre/modules/BackgroundTasksUtils.jsm", - BackgroundTasksManager: "resource://gre/modules/BackgroundTasksManager.jsm", FileUtils: "resource://gre/modules/FileUtils.jsm", TaskScheduler: "resource://gre/modules/TaskScheduler.jsm", UpdateUtils: "resource://gre/modules/UpdateUtils.jsm", @@ -641,7 +643,7 @@ BackgroundUpdate.REASON = { * more general errors reading from the default profile. */ BackgroundUpdate.EXIT_CODE = { - ...lazy.BackgroundTasksManager.EXIT_CODE, + ...BackgroundTasksManager.EXIT_CODE, // We clone the other exit codes simply so we can use one object for all the codes. DEFAULT_PROFILE_DOES_NOT_EXIST: 11, DEFAULT_PROFILE_CANNOT_BE_LOCKED: 12, From b8208675ddd51b371747eb6850f723eb367f4d33 Mon Sep 17 00:00:00 2001 From: Sam Foster Date: Wed, 15 Jun 2022 21:24:36 +0000 Subject: [PATCH 24/64] Bug 1771313 - Add an opaque background behind the print preview paginator buttons. r=mstriemer Differential Revision: https://phabricator.services.mozilla.com/D148865 --- toolkit/components/printing/content/printPagination.css | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/toolkit/components/printing/content/printPagination.css b/toolkit/components/printing/content/printPagination.css index 8eb84773f3fa..dee0c252cac5 100644 --- a/toolkit/components/printing/content/printPagination.css +++ b/toolkit/components/printing/content/printPagination.css @@ -33,6 +33,15 @@ border-radius: 6px; border-style: none; } +.container::before { + content: ""; + display: block; + position: absolute; + inset: 0; + z-index: -1; + background-color: ButtonFace; + border-radius: 6px; +} .toolbarButton, .toolbarCenter { From a15225ce69e949bfcf8691f561ffb671e10b384b Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:18 +0000 Subject: [PATCH 25/64] Bug 1773399 - Update semver to 1.0.10. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149322 --- Cargo.lock | 4 ++-- supply-chain/audits.toml | 5 +++++ third_party/rust/semver/.cargo-checksum.json | 2 +- third_party/rust/semver/Cargo.toml | 2 +- third_party/rust/semver/src/lib.rs | 12 +++++++++++- third_party/rust/semver/src/parse.rs | 10 +++++----- 6 files changed, 25 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1b407d7c14e3..b9314286f338 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4705,9 +4705,9 @@ checksum = "1ef965a420fe14fdac7dd018862966a4c14094f900e1650bbc71ddd7d580c8af" [[package]] name = "semver" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" +checksum = "a41d061efea015927ac527063765e73601444cdc344ba855bc7bd44578b25e1c" dependencies = [ "serde", ] diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index 50b35fe18e94..f5ec7aaa49c4 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -37,6 +37,11 @@ criteria = "safe-to-deploy" version = "0.5.4" notes = "I own this crate (I am contain-rs) and 0.5.4 passes miri. This code is very old and used by lots of people, so I'm pretty confident in it, even though it's in maintenance-mode and missing some nice-to-have APIs." +[[audits.semver]] +who = "Mike Hommey " +criteria = "safe-to-deploy" +delta = "1.0.9 -> 1.0.10" + [[audits.thin-vec]] who = "Aria Beingessner " criteria = "safe-to-deploy" diff --git a/third_party/rust/semver/.cargo-checksum.json b/third_party/rust/semver/.cargo-checksum.json index 9bc3bfba11fb..5628782876f1 100644 --- a/third_party/rust/semver/.cargo-checksum.json +++ b/third_party/rust/semver/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"2a2126f8fe5d20540ae6cfbf6649ed3af365ffb9a0a788a7552a6e7649a7a75f","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"57659341319915482c0b83779fb7f3f0f3accb7a8b881965799116afb5e9f7e9","benches/parse.rs":"6531f66f80ce2fc83878f9bf84f94c42e96f1e709466f2b88be8d95a3cec1511","build.rs":"47b42941210d44567c8561107420d7825aa1d01332c2d2f8892d9e20646a1c77","src/backport.rs":"f8866548840434c8974f135528693f25aacc4ad03639c4e3aea3be351e13fdf8","src/display.rs":"9ba42f7a6579aa9c7dd72f2380036f5c9664592f3eacd09ea25cef291a3e64e5","src/error.rs":"3bb489f4a29f38d93370e64ae8d6e4e9b451a055cd7d392b6aeacab7eb3e1953","src/eval.rs":"b7e7ec976051b9f87ddf5cfdbaad64654d98d86ae0763f7d88b14eeaeac6013c","src/identifier.rs":"601231351ac58602b7d193cb0951b5146bd868b62aba938d5cbe52cf2b93414b","src/impls.rs":"79b5a2ac6ca3d4cb46adfb1494756079f53bef780dd81c3a8d3adf86f91395c8","src/lib.rs":"8e116a19e521909f3fa50206c078f1e23bf033dc8057ba6101f80d5bc5900fed","src/parse.rs":"93593f62cdae489feb4f2e8ae1fa93d90dca63db50669b6265346ffaaf687be5","src/serde.rs":"970d343a6bac21ddd965168d3cc2af9998796bf29bf545e8b37c6bcdd97d9710","tests/node/mod.rs":"2710d9b8daace2038b66db0f8f4cc522dee938e7cbc42d7739c31995343c32f4","tests/test_autotrait.rs":"070500c32ceee14a8a0110c04a01f98278b24614a0aec8c382dcea3da0343f58","tests/test_identifier.rs":"6c3da46c73df210527b60f1069131b15e2c65eb7b5d11793940d00cf66812f4d","tests/test_version.rs":"09e37c3df162205acf3683d1c760a6001e34e1c709fd4a1a265d82450e340003","tests/test_version_req.rs":"b6eea0258cc3b6d567a9f6c42693a97316345083495236c47e85374fd45f7cf0","tests/util/mod.rs":"db61c2cd86af864d8be4f2a3d5f25c86d7712201cc6ab47b715facf5f7f275b7"},"package":"8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd"} \ No newline at end of file +{"files":{"Cargo.toml":"e59adea60e549bd648140e60b8fe7c543d3b65b1b52a2a80c5036d40c7db6300","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"57659341319915482c0b83779fb7f3f0f3accb7a8b881965799116afb5e9f7e9","benches/parse.rs":"6531f66f80ce2fc83878f9bf84f94c42e96f1e709466f2b88be8d95a3cec1511","build.rs":"47b42941210d44567c8561107420d7825aa1d01332c2d2f8892d9e20646a1c77","src/backport.rs":"f8866548840434c8974f135528693f25aacc4ad03639c4e3aea3be351e13fdf8","src/display.rs":"9ba42f7a6579aa9c7dd72f2380036f5c9664592f3eacd09ea25cef291a3e64e5","src/error.rs":"3bb489f4a29f38d93370e64ae8d6e4e9b451a055cd7d392b6aeacab7eb3e1953","src/eval.rs":"b7e7ec976051b9f87ddf5cfdbaad64654d98d86ae0763f7d88b14eeaeac6013c","src/identifier.rs":"601231351ac58602b7d193cb0951b5146bd868b62aba938d5cbe52cf2b93414b","src/impls.rs":"79b5a2ac6ca3d4cb46adfb1494756079f53bef780dd81c3a8d3adf86f91395c8","src/lib.rs":"515ebc351b700a0dab7d0f0259559b719c6d4ce86c1bd57d8a8662083aa8d801","src/parse.rs":"ffbb84081f0f66ec47b752a1e32f1bea5f206ca84f464b99d0497451305a92f8","src/serde.rs":"970d343a6bac21ddd965168d3cc2af9998796bf29bf545e8b37c6bcdd97d9710","tests/node/mod.rs":"2710d9b8daace2038b66db0f8f4cc522dee938e7cbc42d7739c31995343c32f4","tests/test_autotrait.rs":"070500c32ceee14a8a0110c04a01f98278b24614a0aec8c382dcea3da0343f58","tests/test_identifier.rs":"6c3da46c73df210527b60f1069131b15e2c65eb7b5d11793940d00cf66812f4d","tests/test_version.rs":"09e37c3df162205acf3683d1c760a6001e34e1c709fd4a1a265d82450e340003","tests/test_version_req.rs":"b6eea0258cc3b6d567a9f6c42693a97316345083495236c47e85374fd45f7cf0","tests/util/mod.rs":"db61c2cd86af864d8be4f2a3d5f25c86d7712201cc6ab47b715facf5f7f275b7"},"package":"a41d061efea015927ac527063765e73601444cdc344ba855bc7bd44578b25e1c"} \ No newline at end of file diff --git a/third_party/rust/semver/Cargo.toml b/third_party/rust/semver/Cargo.toml index 602b30b1eef5..a5fcd24209bb 100644 --- a/third_party/rust/semver/Cargo.toml +++ b/third_party/rust/semver/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.31" name = "semver" -version = "1.0.9" +version = "1.0.10" authors = ["David Tolnay "] description = "Parser and evaluator for Cargo's flavor of Semantic Versioning" documentation = "https://docs.rs/semver" diff --git a/third_party/rust/semver/src/lib.rs b/third_party/rust/semver/src/lib.rs index 9a43980658dc..5d6ece24195a 100644 --- a/third_party/rust/semver/src/lib.rs +++ b/third_party/rust/semver/src/lib.rs @@ -60,7 +60,7 @@ //! //! [Specifying Dependencies]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html -#![doc(html_root_url = "https://docs.rs/semver/1.0.9")] +#![doc(html_root_url = "https://docs.rs/semver/1.0.10")] #![cfg_attr(doc_cfg, feature(doc_cfg))] #![cfg_attr(all(not(feature = "std"), not(no_alloc_crate)), no_std)] #![cfg_attr(not(no_unsafe_op_in_unsafe_fn_lint), deny(unsafe_op_in_unsafe_fn))] @@ -497,6 +497,11 @@ impl Comparator { } impl Prerelease { + // Work around https://github.com/rust-lang/rust/issues/97933 + #[cfg(doc)] + pub const EMPTY: Self = ""; + + #[cfg(not(doc))] pub const EMPTY: Self = Prerelease { identifier: Identifier::empty(), }; @@ -515,6 +520,11 @@ impl Prerelease { } impl BuildMetadata { + // Work around https://github.com/rust-lang/rust/issues/97933 + #[cfg(doc)] + pub const EMPTY: Self = ""; + + #[cfg(not(doc))] pub const EMPTY: Self = BuildMetadata { identifier: Identifier::empty(), }; diff --git a/third_party/rust/semver/src/parse.rs b/third_party/rust/semver/src/parse.rs index bf70739fbad4..6a8f6ffba4fd 100644 --- a/third_party/rust/semver/src/parse.rs +++ b/third_party/rust/semver/src/parse.rs @@ -262,23 +262,23 @@ fn identifier(input: &str, pos: Position) -> Result<(&str, &str), Error> { fn op(input: &str) -> (Op, &str) { let bytes = input.as_bytes(); - if bytes.get(0) == Some(&b'=') { + if bytes.first() == Some(&b'=') { (Op::Exact, &input[1..]) - } else if bytes.get(0) == Some(&b'>') { + } else if bytes.first() == Some(&b'>') { if bytes.get(1) == Some(&b'=') { (Op::GreaterEq, &input[2..]) } else { (Op::Greater, &input[1..]) } - } else if bytes.get(0) == Some(&b'<') { + } else if bytes.first() == Some(&b'<') { if bytes.get(1) == Some(&b'=') { (Op::LessEq, &input[2..]) } else { (Op::Less, &input[1..]) } - } else if bytes.get(0) == Some(&b'~') { + } else if bytes.first() == Some(&b'~') { (Op::Tilde, &input[1..]) - } else if bytes.get(0) == Some(&b'^') { + } else if bytes.first() == Some(&b'^') { (Op::Caret, &input[1..]) } else { (Op::DEFAULT, input) From 1e9a55f2d525e119569ea878c036b71979aa4aa0 Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:19 +0000 Subject: [PATCH 26/64] Bug 1773399 - Stick geckodriver to clap 3.1. r=webdriver-reviewers,jgraham 3.2 adds deprecation warnings. Differential Revision: https://phabricator.services.mozilla.com/D149323 --- testing/geckodriver/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/geckodriver/Cargo.toml b/testing/geckodriver/Cargo.toml index 2ac373727e17..396e2d3a03ac 100644 --- a/testing/geckodriver/Cargo.toml +++ b/testing/geckodriver/Cargo.toml @@ -12,7 +12,7 @@ edition = "2018" [dependencies] base64 = "0.13" chrono = "0.4.6" -clap = { version = "3.1", default-features = false, features = ["cargo", "std", "suggestions", "wrap_help"] } +clap = { version = "~3.1", default-features = false, features = ["cargo", "std", "suggestions", "wrap_help"] } hyper = "0.14" lazy_static = "1.0" log = { version = "0.4", features = ["std"] } From b7f11da783b9e04604d54fabd999fcbea03fd7a8 Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:19 +0000 Subject: [PATCH 27/64] Bug 1773399 - Update arbitrary to 1.1.1. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149324 --- Cargo.lock | 8 +- supply-chain/audits.toml | 10 ++ .../rust/arbitrary/.cargo-checksum.json | 2 +- third_party/rust/arbitrary/CHANGELOG.md | 11 ++ third_party/rust/arbitrary/Cargo.lock | 6 +- third_party/rust/arbitrary/Cargo.toml | 2 +- .../rust/arbitrary/examples/derive_enum.rs | 4 + third_party/rust/arbitrary/src/lib.rs | 144 +++++++++++++----- .../rust/arbitrary/src/unstructured.rs | 55 ++++++- third_party/rust/arbitrary/tests/derive.rs | 50 +++++- third_party/rust/arbitrary/tests/path.rs | 4 + .../derive_arbitrary/.cargo-checksum.json | 2 +- third_party/rust/derive_arbitrary/Cargo.toml | 2 +- third_party/rust/derive_arbitrary/src/lib.rs | 71 ++++++++- 14 files changed, 309 insertions(+), 62 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b9314286f338..f1f48524f0af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,9 +99,9 @@ dependencies = [ [[package]] name = "arbitrary" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c38b6b6b79f671c25e1a3e785b7b82d7562ffc9cd3efdc98627e5668a2472490" +checksum = "4f7487a7cc86cea29c97c91007ad21294f9959949577b305ae118b8c11738ccf" dependencies = [ "derive_arbitrary", ] @@ -1363,9 +1363,9 @@ dependencies = [ [[package]] name = "derive_arbitrary" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98e23c06c035dac87bd802d98f368df73a7f2cb05a66ffbd1f377e821fac4af9" +checksum = "91d001046c3cc126eb2ee9bdc946d9f482fe9e74d4a5ef191a6834fdbf84d45c" dependencies = [ "proc-macro2", "quote", diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index f5ec7aaa49c4..042a91b5d86b 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -1,6 +1,11 @@ # cargo-vet audits file +[[audits.arbitrary]] +who = "Mike Hommey " +criteria = "safe-to-run" +delta = "1.1.0 -> 1.1.1" + [[audits.atomic_refcell]] who = "Bobby Holley " criteria = "safe-to-deploy" @@ -19,6 +24,11 @@ criteria = "safe-to-deploy" version = "0.6.3" notes = "Another crate I own via contain-rs that is ancient and in maintenance mode but otherwise perfectly fine." +[[audits.derive_arbitrary]] +who = "Mike Hommey " +criteria = "safe-to-run" +delta = "1.1.0 -> 1.1.1" + [[audits.glean]] who = "Jan-Erik Rediger " criteria = "safe-to-deploy" diff --git a/third_party/rust/arbitrary/.cargo-checksum.json b/third_party/rust/arbitrary/.cargo-checksum.json index 29fac25a735c..5f8858ccc9a7 100644 --- a/third_party/rust/arbitrary/.cargo-checksum.json +++ b/third_party/rust/arbitrary/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"502a4a3f03e0aa6202524862d1bd9ace9386f9888104d9b8071290d30e8ffaee","Cargo.lock":"baf9208d39ffd4c1328f991b2f898b36d893ab30140c1c97ea4bea0f2a7604a6","Cargo.toml":"e8d6b6242ff8378b1f73f1daa2e42ecece6b33df6ae01a7e6e1a0272f835be84","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"15656cc11a8331f28c0986b8ab97220d3e76f98e60ed388b5ffad37dfac4710c","README.md":"950e645eba942c01ae12aaf835b23f2b70bcc75c561e663fe483e000d067a57e","examples/derive_enum.rs":"4d399f1805c48780443182aa141be4e3bf773649b118eab245280799e67742f6","publish.sh":"752e221bdd960666b127df15effddd3d789ff3f1762498961fc79ae99f9a27f1","src/error.rs":"88293a722e314bcc05e4836167b49e76520c9b3d7f64d1ae711f7bd29280f480","src/lib.rs":"18ec8d74692260407ec6683a6f5ae0b9e65c9c258c4dc1510e3956b62b54169b","src/size_hint.rs":"9762b183f8277ee4955fe5b22552961744b6237286758161a551f904ef43e3eb","src/unstructured.rs":"91635cd36da7743758b01d125f21aa90bbf90994c7e26c379c17a8b3ea519a6a","tests/derive.rs":"9a97927c7bf192e6e229d6142cb9cccd8ec7010797a6da41c4a5cfb7c62fc853","tests/path.rs":"a9706f00ce95d5a11652ae926830756d9111837b55073a0bc6a1eadd25033387"},"package":"c38b6b6b79f671c25e1a3e785b7b82d7562ffc9cd3efdc98627e5668a2472490"} \ No newline at end of file +{"files":{"CHANGELOG.md":"f946d19cd959061b8f69c57a28e8751eba76bc3431c02a03a90a9651c5795ca9","Cargo.lock":"84aba8843f8b9b0ac30c2d635e243d28ecda3c43fc5a40e3abef9288439c226e","Cargo.toml":"8b0def133804d5bab323723c84ab83828f5b31fb7489f3955f2f01ddbc2974ae","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"15656cc11a8331f28c0986b8ab97220d3e76f98e60ed388b5ffad37dfac4710c","README.md":"950e645eba942c01ae12aaf835b23f2b70bcc75c561e663fe483e000d067a57e","examples/derive_enum.rs":"ef93268fbed2b70c177bebf5757ef1ee0ca5ba0cb0d335d0989a81725463f8c9","publish.sh":"752e221bdd960666b127df15effddd3d789ff3f1762498961fc79ae99f9a27f1","src/error.rs":"88293a722e314bcc05e4836167b49e76520c9b3d7f64d1ae711f7bd29280f480","src/lib.rs":"53bf8d1a84add93398b496618ddd98bf783df447e2d3bec547ed349db96fcc1a","src/size_hint.rs":"9762b183f8277ee4955fe5b22552961744b6237286758161a551f904ef43e3eb","src/unstructured.rs":"9f1f3c8e31fb66ce066182979904e495c308b9bb1addbd126dac05e4c7273bc9","tests/derive.rs":"825ec9e354b6e08529c49f7db924db53cff730b3f51029d729a97497d8de53a9","tests/path.rs":"3aa0e6a3d342a7efac5aa529ba806903877909289c1d3dd350b5e1ee4aa3e16a"},"package":"4f7487a7cc86cea29c97c91007ad21294f9959949577b305ae118b8c11738ccf"} \ No newline at end of file diff --git a/third_party/rust/arbitrary/CHANGELOG.md b/third_party/rust/arbitrary/CHANGELOG.md index 2a7c179e1e59..9000ce12c612 100644 --- a/third_party/rust/arbitrary/CHANGELOG.md +++ b/third_party/rust/arbitrary/CHANGELOG.md @@ -28,6 +28,17 @@ Released YYYY-MM-DD. -------------------------------------------------------------------------------- +## 1.1.1 + +Released 2022-06-14. + +### Fixed + +* Fixed a stack overflow when using `derive(Arbitrary)` with recursive types and + empty inputs. [#109](https://github.com/rust-fuzz/arbitrary/pull/109) + +-------------------------------------------------------------------------------- + ## 1.1.0 Released 2022-02-09. diff --git a/third_party/rust/arbitrary/Cargo.lock b/third_party/rust/arbitrary/Cargo.lock index 665ccdf69162..30f5bd0cffb0 100644 --- a/third_party/rust/arbitrary/Cargo.lock +++ b/third_party/rust/arbitrary/Cargo.lock @@ -4,16 +4,16 @@ version = 3 [[package]] name = "arbitrary" -version = "1.1.0" +version = "1.1.1" dependencies = [ "derive_arbitrary", ] [[package]] name = "derive_arbitrary" -version = "1.0.2" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b24629208e87a2d8b396ff43b15c4afb0a69cea3fbbaa9ed9b92b7c02f0aed73" +checksum = "91d001046c3cc126eb2ee9bdc946d9f482fe9e74d4a5ef191a6834fdbf84d45c" dependencies = [ "proc-macro2", "quote", diff --git a/third_party/rust/arbitrary/Cargo.toml b/third_party/rust/arbitrary/Cargo.toml index a42a90bd8be0..2bfb5dfb778a 100644 --- a/third_party/rust/arbitrary/Cargo.toml +++ b/third_party/rust/arbitrary/Cargo.toml @@ -12,7 +12,7 @@ [package] edition = "2018" name = "arbitrary" -version = "1.1.0" +version = "1.1.1" authors = [ "The Rust-Fuzz Project Developers", "Nick Fitzgerald ", diff --git a/third_party/rust/arbitrary/examples/derive_enum.rs b/third_party/rust/arbitrary/examples/derive_enum.rs index fbcc106b7d9d..c4fc9c958836 100644 --- a/third_party/rust/arbitrary/examples/derive_enum.rs +++ b/third_party/rust/arbitrary/examples/derive_enum.rs @@ -2,6 +2,10 @@ //! //! Note that this requires enabling the "derive" cargo feature. +// Various enums/fields that we are deriving `Arbitrary` for aren't actually +// used except to show off the derive. +#![allow(dead_code)] + use arbitrary::{Arbitrary, Unstructured}; #[derive(Arbitrary, Debug)] diff --git a/third_party/rust/arbitrary/src/lib.rs b/third_party/rust/arbitrary/src/lib.rs index 7b791ab032a9..2de041dfe9c1 100644 --- a/third_party/rust/arbitrary/src/lib.rs +++ b/third_party/rust/arbitrary/src/lib.rs @@ -202,6 +202,16 @@ pub trait Arbitrary<'a>: Sized { /// default with a better implementation. The /// [`size_hint`][crate::size_hint] module will help with this task. /// + /// ## Invariant + /// + /// It must be possible to construct every possible output using only inputs + /// of lengths bounded by these parameters. This applies to both + /// [`Arbitrary::arbitrary`] and [`Arbitrary::arbitrary_take_rest`]. + /// + /// This is trivially true for `(0, None)`. To restrict this further, it must be proven + /// that all inputs that are now excluded produced redundant outputs which are still + /// possible to produce using the reduced input space. + /// /// ## The `depth` Parameter /// /// If you 100% know that the type you are implementing `Arbitrary` for is @@ -672,8 +682,8 @@ impl<'a> Arbitrary<'a> for &'a [u8] { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - ::size_hint(depth) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -687,8 +697,8 @@ impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for Vec { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -702,8 +712,8 @@ impl<'a, K: Arbitrary<'a> + Ord, V: Arbitrary<'a>> Arbitrary<'a> for BTreeMap (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -717,8 +727,8 @@ impl<'a, A: Arbitrary<'a> + Ord> Arbitrary<'a> for BTreeSet { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -732,8 +742,8 @@ impl<'a, A: Arbitrary<'a> + Ord> Arbitrary<'a> for BinaryHeap { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -749,8 +759,8 @@ impl<'a, K: Arbitrary<'a> + Eq + ::std::hash::Hash, V: Arbitrary<'a>, S: BuildHa } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -766,8 +776,8 @@ impl<'a, A: Arbitrary<'a> + Eq + ::std::hash::Hash, S: BuildHasher + Default> Ar } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -781,8 +791,8 @@ impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for LinkedList { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -796,8 +806,8 @@ impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for VecDeque { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -846,8 +856,8 @@ impl<'a> Arbitrary<'a> for &'a str { } #[inline] - fn size_hint(depth: usize) -> (usize, Option) { - crate::size_hint::and(::size_hint(depth), (0, None)) + fn size_hint(_depth: usize) -> (usize, Option) { + (0, None) } } @@ -1104,6 +1114,56 @@ impl<'a> Arbitrary<'a> for Ipv6Addr { mod test { use super::*; + /// Generates an arbitrary `T`, and checks that the result is consistent with the + /// `size_hint()` reported by `T`. + fn checked_arbitrary<'a, T: Arbitrary<'a>>(u: &mut Unstructured<'a>) -> Result { + let (min, max) = T::size_hint(0); + + let len_before = u.len(); + let result = T::arbitrary(u); + + let consumed = len_before - u.len(); + + if let Some(max) = max { + assert!( + consumed <= max, + "incorrect maximum size: indicated {}, actually consumed {}", + max, + consumed + ); + } + + if result.is_ok() { + assert!( + consumed >= min, + "incorrect minimum size: indicated {}, actually consumed {}", + min, + consumed + ); + } + + result + } + + /// Like `checked_arbitrary()`, but calls `arbitrary_take_rest()` instead of `arbitrary()`. + fn checked_arbitrary_take_rest<'a, T: Arbitrary<'a>>(u: Unstructured<'a>) -> Result { + let (min, _) = T::size_hint(0); + + let len_before = u.len(); + let result = T::arbitrary_take_rest(u); + + if result.is_ok() { + assert!( + len_before >= min, + "incorrect minimum size: indicated {}, worked with {}", + min, + len_before + ); + } + + result + } + #[test] fn finite_buffer_fill_buffer() { let x = [1, 2, 3, 4]; @@ -1122,7 +1182,7 @@ mod test { let x = [1, 2, 3, 4]; let mut buf = Unstructured::new(&x); let expected = 1 | (2 << 8) | (3 << 16) | (4 << 24); - let actual = i32::arbitrary(&mut buf).unwrap(); + let actual = checked_arbitrary::(&mut buf).unwrap(); assert_eq!(expected, actual); } @@ -1131,7 +1191,7 @@ mod test { let x = [1, 2, 3, 4, 4]; let mut buf = Unstructured::new(&x); let expected = &[1, 2, 3, 4]; - let actual = <&[u8] as Arbitrary>::arbitrary(&mut buf).unwrap(); + let actual = checked_arbitrary::<&[u8]>(&mut buf).unwrap(); assert_eq!(expected, actual); } @@ -1140,26 +1200,30 @@ mod test { let x = [1, 2, 3, 4]; let buf = Unstructured::new(&x); let expected = &[1, 2, 3, 4]; - let actual = <&[u8] as Arbitrary>::arbitrary_take_rest(buf).unwrap(); + let actual = checked_arbitrary_take_rest::<&[u8]>(buf).unwrap(); assert_eq!(expected, actual); } #[test] fn arbitrary_collection() { let x = [ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, + 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 12, ]; assert_eq!( - Vec::::arbitrary(&mut Unstructured::new(&x)).unwrap(), + checked_arbitrary::<&[u8]>(&mut Unstructured::new(&x)).unwrap(), + &[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3] + ); + assert_eq!( + checked_arbitrary::>(&mut Unstructured::new(&x)).unwrap(), &[2, 4, 6, 8, 1] ); assert_eq!( - Vec::::arbitrary(&mut Unstructured::new(&x)).unwrap(), + checked_arbitrary::>(&mut Unstructured::new(&x)).unwrap(), &[84148994] ); assert_eq!( - String::arbitrary(&mut Unstructured::new(&x)).unwrap(), - "\x01\x02\x03\x04\x05\x06\x07\x08" + checked_arbitrary::(&mut Unstructured::new(&x)).unwrap(), + "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x01\x02\x03" ); } @@ -1167,17 +1231,30 @@ mod test { fn arbitrary_take_rest() { let x = [1, 2, 3, 4]; assert_eq!( - Vec::::arbitrary_take_rest(Unstructured::new(&x)).unwrap(), + checked_arbitrary_take_rest::<&[u8]>(Unstructured::new(&x)).unwrap(), &[1, 2, 3, 4] ); assert_eq!( - Vec::::arbitrary_take_rest(Unstructured::new(&x)).unwrap(), + checked_arbitrary_take_rest::>(Unstructured::new(&x)).unwrap(), + &[1, 2, 3, 4] + ); + assert_eq!( + checked_arbitrary_take_rest::>(Unstructured::new(&x)).unwrap(), &[0x4030201] ); assert_eq!( - String::arbitrary_take_rest(Unstructured::new(&x)).unwrap(), + checked_arbitrary_take_rest::(Unstructured::new(&x)).unwrap(), "\x01\x02\x03\x04" ); + + assert_eq!( + checked_arbitrary_take_rest::<&[u8]>(Unstructured::new(&[])).unwrap(), + &[] + ); + assert_eq!( + checked_arbitrary_take_rest::>(Unstructured::new(&[])).unwrap(), + &[] + ); } #[test] @@ -1186,9 +1263,6 @@ mod test { (7, Some(7)), <(bool, u16, i32) as Arbitrary<'_>>::size_hint(0) ); - assert_eq!( - (1 + mem::size_of::(), None), - <(u8, Vec) as Arbitrary>::size_hint(0) - ); + assert_eq!((1, None), <(u8, Vec) as Arbitrary>::size_hint(0)); } } diff --git a/third_party/rust/arbitrary/src/unstructured.rs b/third_party/rust/arbitrary/src/unstructured.rs index ff3e1f37d206..07ba932e2743 100644 --- a/third_party/rust/arbitrary/src/unstructured.rs +++ b/third_party/rust/arbitrary/src/unstructured.rs @@ -236,19 +236,20 @@ impl<'a> Unstructured<'a> { // We only consume as many bytes as necessary to cover the entire // range of the byte string. - let len = if self.data.len() <= std::u8::MAX as usize + 1 { + // Note: We cast to u64 so we don't overflow when checking std::u32::MAX + 4 on 32-bit archs + let len = if self.data.len() as u64 <= std::u8::MAX as u64 + 1 { let bytes = 1; let max_size = self.data.len() - bytes; let (rest, for_size) = self.data.split_at(max_size); self.data = rest; Self::int_in_range_impl(0..=max_size as u8, for_size.iter().copied())?.0 as usize - } else if self.data.len() <= std::u16::MAX as usize + 1 { + } else if self.data.len() as u64 <= std::u16::MAX as u64 + 2 { let bytes = 2; let max_size = self.data.len() - bytes; let (rest, for_size) = self.data.split_at(max_size); self.data = rest; Self::int_in_range_impl(0..=max_size as u16, for_size.iter().copied())?.0 as usize - } else if self.data.len() <= std::u32::MAX as usize + 1 { + } else if self.data.len() as u64 <= std::u32::MAX as u64 + 4 { let bytes = 4; let max_size = self.data.len() - bytes; let (rest, for_size) = self.data.split_at(max_size); @@ -376,11 +377,53 @@ impl<'a> Unstructured<'a> { /// assert!(result.is_err()); /// ``` pub fn choose<'b, T>(&mut self, choices: &'b [T]) -> Result<&'b T> { - if choices.is_empty() { + let idx = self.choose_index(choices.len())?; + Ok(&choices[idx]) + } + + /// Choose a value in `0..len`. + /// + /// Returns an error if the `len` is zero. + /// + /// # Examples + /// + /// Using Fisher–Yates shuffle shuffle to gerate an arbitrary permutation. + /// + /// [Fisher–Yates shuffle]: https://en.wikipedia.org/wiki/Fisher–Yates_shuffle + /// + /// ``` + /// use arbitrary::Unstructured; + /// + /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); + /// let mut permutation = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; + /// let mut to_permute = &mut permutation[..]; + /// while to_permute.len() > 1 { + /// let idx = u.choose_index(to_permute.len()).unwrap(); + /// to_permute.swap(0, idx); + /// to_permute = &mut to_permute[1..]; + /// } + /// + /// println!("permutation: {:?}", permutation); + /// ``` + /// + /// An error is returned if the length is zero: + /// + /// ``` + /// use arbitrary::Unstructured; + /// + /// let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); + /// let array: [i32; 0] = []; + /// + /// let result = u.choose_index(array.len()); + /// + /// assert!(result.is_err()); + /// ``` + pub fn choose_index(&mut self, len: usize) -> Result { + if len == 0 { return Err(Error::EmptyChoose); } - let idx = self.int_in_range(0..=choices.len() - 1)?; - Ok(&choices[idx]) + let idx = self.int_in_range(0..=len - 1)?; + Ok(idx) } /// Generate a boolean according to the given ratio. diff --git a/third_party/rust/arbitrary/tests/derive.rs b/third_party/rust/arbitrary/tests/derive.rs index adf1188556a0..3882236ea58b 100755 --- a/third_party/rust/arbitrary/tests/derive.rs +++ b/third_party/rust/arbitrary/tests/derive.rs @@ -1,5 +1,9 @@ #![cfg(feature = "derive")] +// Various structs/fields that we are deriving `Arbitrary` for aren't actually +// used except to exercise the derive. +#![allow(dead_code)] + use arbitrary::*; fn arbitrary_from<'a, T: Arbitrary<'a>>(input: &'a [u8]) -> T { @@ -164,7 +168,7 @@ fn one_lifetime() { assert_eq!("abc", lifetime.alpha); let (lower, upper) = ::size_hint(0); - assert_eq!(lower, std::mem::size_of::()); + assert_eq!(lower, 0); assert_eq!(upper, None); } @@ -183,6 +187,48 @@ fn two_lifetimes() { assert_eq!("def", lifetime.beta); let (lower, upper) = ::size_hint(0); - assert_eq!(lower, std::mem::size_of::() * 2); + assert_eq!(lower, 0); assert_eq!(upper, None); } + +#[test] +fn recursive_and_empty_input() { + // None of the following derives should result in a stack overflow. See + // https://github.com/rust-fuzz/arbitrary/issues/107 for details. + + #[derive(Debug, Arbitrary)] + enum Nat { + Succ(Box), + Zero, + } + + let _ = Nat::arbitrary(&mut Unstructured::new(&[])); + + #[derive(Debug, Arbitrary)] + enum Nat2 { + Zero, + Succ(Box), + } + + let _ = Nat2::arbitrary(&mut Unstructured::new(&[])); + + #[derive(Debug, Arbitrary)] + struct Nat3 { + f: Option>, + } + + let _ = Nat3::arbitrary(&mut Unstructured::new(&[])); + + #[derive(Debug, Arbitrary)] + struct Nat4(Option>); + + let _ = Nat4::arbitrary(&mut Unstructured::new(&[])); + + #[derive(Debug, Arbitrary)] + enum Nat5 { + Zero, + Succ { f: Box }, + } + + let _ = Nat5::arbitrary(&mut Unstructured::new(&[])); +} diff --git a/third_party/rust/arbitrary/tests/path.rs b/third_party/rust/arbitrary/tests/path.rs index 15dbbe338003..f9e2f29c79f4 100644 --- a/third_party/rust/arbitrary/tests/path.rs +++ b/third_party/rust/arbitrary/tests/path.rs @@ -1,5 +1,9 @@ #![cfg(feature = "derive")] +// Various structs/fields that we are deriving `Arbitrary` for aren't actually +// used except to show off the derive. +#![allow(dead_code)] + // Regression test for ensuring the derives work without Arbitrary being imported #[derive(arbitrary::Arbitrary, Clone, Debug)] diff --git a/third_party/rust/derive_arbitrary/.cargo-checksum.json b/third_party/rust/derive_arbitrary/.cargo-checksum.json index 36fb0eda3507..efcb51627ab1 100644 --- a/third_party/rust/derive_arbitrary/.cargo-checksum.json +++ b/third_party/rust/derive_arbitrary/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"ae161593802fd1da2916958e9c4c7a7f95e250f0f258195b98a43f5fc8eee6aa","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"15656cc11a8331f28c0986b8ab97220d3e76f98e60ed388b5ffad37dfac4710c","README.md":"7059db284b2016ba7355c63a2b14eb732c7b8952286ff1bc4fdde605018a39c4","src/lib.rs":"cdff09ae28184bc4bab1ff751ab9ea228c650463d4a08b359588efbae9d932f1"},"package":"98e23c06c035dac87bd802d98f368df73a7f2cb05a66ffbd1f377e821fac4af9"} \ No newline at end of file +{"files":{"Cargo.toml":"005fe9953afead6b3e52b17a3d3f7ee9fd41f8de45189bf755f5fa595f569a9d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"15656cc11a8331f28c0986b8ab97220d3e76f98e60ed388b5ffad37dfac4710c","README.md":"7059db284b2016ba7355c63a2b14eb732c7b8952286ff1bc4fdde605018a39c4","src/lib.rs":"299d5add03a9f7882e0ed9041a03837ebfd88fcdffc8c7710ad24694bffb6743"},"package":"91d001046c3cc126eb2ee9bdc946d9f482fe9e74d4a5ef191a6834fdbf84d45c"} \ No newline at end of file diff --git a/third_party/rust/derive_arbitrary/Cargo.toml b/third_party/rust/derive_arbitrary/Cargo.toml index d749034d5d9b..6a1d63c15175 100644 --- a/third_party/rust/derive_arbitrary/Cargo.toml +++ b/third_party/rust/derive_arbitrary/Cargo.toml @@ -12,7 +12,7 @@ [package] edition = "2018" name = "derive_arbitrary" -version = "1.1.0" +version = "1.1.1" authors = [ "The Rust-Fuzz Project Developers", "Nick Fitzgerald ", diff --git a/third_party/rust/derive_arbitrary/src/lib.rs b/third_party/rust/derive_arbitrary/src/lib.rs index 983bd68bee8c..cd8f1b24e3d6 100644 --- a/third_party/rust/derive_arbitrary/src/lib.rs +++ b/third_party/rust/derive_arbitrary/src/lib.rs @@ -12,7 +12,13 @@ pub fn derive_arbitrary(tokens: proc_macro::TokenStream) -> proc_macro::TokenStr let (lifetime_without_bounds, lifetime_with_bounds) = build_arbitrary_lifetime(input.generics.clone()); - let arbitrary_method = gen_arbitrary_method(&input, lifetime_without_bounds.clone()); + let recursive_count = syn::Ident::new( + &format!("RECURSIVE_COUNT_{}", input.ident), + Span::call_site(), + ); + + let arbitrary_method = + gen_arbitrary_method(&input, lifetime_without_bounds.clone(), &recursive_count); let size_hint_method = gen_size_hint_method(&input); let name = input.ident; // Add a bound `T: Arbitrary` to every type parameter T. @@ -29,6 +35,10 @@ pub fn derive_arbitrary(tokens: proc_macro::TokenStream) -> proc_macro::TokenStr let (_, ty_generics, where_clause) = generics.split_for_impl(); (quote! { + thread_local! { + static #recursive_count: std::cell::Cell = std::cell::Cell::new(0); + } + impl #impl_generics arbitrary::Arbitrary<#lifetime_without_bounds> for #name #ty_generics #where_clause { #arbitrary_method #size_hint_method @@ -67,21 +77,51 @@ fn add_trait_bounds(mut generics: Generics, lifetime: LifetimeDef) -> Generics { generics } -fn gen_arbitrary_method(input: &DeriveInput, lifetime: LifetimeDef) -> TokenStream { +fn with_recursive_count_guard( + recursive_count: &syn::Ident, + expr: impl quote::ToTokens, +) -> impl quote::ToTokens { + quote! { + #recursive_count.with(|count| { + if count.get() > 0 && u.is_empty() { + return Err(arbitrary::Error::NotEnoughData); + } + + count.set(count.get() + 1); + let result = { #expr }; + count.set(count.get() - 1); + + result + }) + } +} + +fn gen_arbitrary_method( + input: &DeriveInput, + lifetime: LifetimeDef, + recursive_count: &syn::Ident, +) -> TokenStream { let ident = &input.ident; + let arbitrary_structlike = |fields| { let arbitrary = construct(fields, |_, _| quote!(arbitrary::Arbitrary::arbitrary(u)?)); + let body = with_recursive_count_guard(recursive_count, quote! { Ok(#ident #arbitrary) }); + let arbitrary_take_rest = construct_take_rest(fields); + let take_rest_body = + with_recursive_count_guard(recursive_count, quote! { Ok(#ident #arbitrary_take_rest) }); + quote! { fn arbitrary(u: &mut arbitrary::Unstructured<#lifetime>) -> arbitrary::Result { - Ok(#ident #arbitrary) + #body } fn arbitrary_take_rest(mut u: arbitrary::Unstructured<#lifetime>) -> arbitrary::Result { - Ok(#ident #arbitrary_take_rest) + #take_rest_body } } }; + match &input.data { Data::Struct(data) => arbitrary_structlike(&data.fields), Data::Union(data) => arbitrary_structlike(&Fields::Named(data.fields.clone())), @@ -101,8 +141,10 @@ fn gen_arbitrary_method(input: &DeriveInput, lifetime: LifetimeDef) -> TokenStre quote! { #idx => #ident::#variant_name #ctor } }); let count = data.variants.len() as u64; - quote! { - fn arbitrary(u: &mut arbitrary::Unstructured<#lifetime>) -> arbitrary::Result { + + let arbitrary = with_recursive_count_guard( + recursive_count, + quote! { // Use a multiply + shift to generate a ranged random number // with slight bias. For details, see: // https://lemire.me/blog/2016/06/30/fast-random-shuffling @@ -110,9 +152,12 @@ fn gen_arbitrary_method(input: &DeriveInput, lifetime: LifetimeDef) -> TokenStre #(#variants,)* _ => unreachable!() }) - } + }, + ); - fn arbitrary_take_rest(mut u: arbitrary::Unstructured<#lifetime>) -> arbitrary::Result { + let arbitrary_take_rest = with_recursive_count_guard( + recursive_count, + quote! { // Use a multiply + shift to generate a ranged random number // with slight bias. For details, see: // https://lemire.me/blog/2016/06/30/fast-random-shuffling @@ -120,6 +165,16 @@ fn gen_arbitrary_method(input: &DeriveInput, lifetime: LifetimeDef) -> TokenStre #(#variants_take_rest,)* _ => unreachable!() }) + }, + ); + + quote! { + fn arbitrary(u: &mut arbitrary::Unstructured<#lifetime>) -> arbitrary::Result { + #arbitrary + } + + fn arbitrary_take_rest(mut u: arbitrary::Unstructured<#lifetime>) -> arbitrary::Result { + #arbitrary_take_rest } } } From 04f5c98efec61a827e3b45d678f4f59e9d792755 Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:19 +0000 Subject: [PATCH 28/64] Bug 1773399 - Update clap_lex to 0.2.2. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149325 --- Cargo.lock | 4 ++-- supply-chain/audits.toml | 5 +++++ third_party/rust/clap_lex/.cargo-checksum.json | 2 +- third_party/rust/clap_lex/Cargo.toml | 11 ++++++++--- third_party/rust/clap_lex/README.md | 8 ++++---- third_party/rust/clap_lex/src/lib.rs | 5 +++++ 6 files changed, 25 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f1f48524f0af..49a5096a480e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -805,9 +805,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213" +checksum = "5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613" dependencies = [ "os_str_bytes", ] diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index 042a91b5d86b..3d0eddb09a6c 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -24,6 +24,11 @@ criteria = "safe-to-deploy" version = "0.6.3" notes = "Another crate I own via contain-rs that is ancient and in maintenance mode but otherwise perfectly fine." +[[audits.clap_lex]] +who = "Mike Hommey " +criteria = "safe-to-deploy" +delta = "0.2.0 -> 0.2.2" + [[audits.derive_arbitrary]] who = "Mike Hommey " criteria = "safe-to-run" diff --git a/third_party/rust/clap_lex/.cargo-checksum.json b/third_party/rust/clap_lex/.cargo-checksum.json index f1eeaae84215..d1fc5c2feb40 100644 --- a/third_party/rust/clap_lex/.cargo-checksum.json +++ b/third_party/rust/clap_lex/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"1551ef7db77ad698c6afe7102648d7de8747d873e8c8da4ba0dd8264ac09cbf8","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"5de0646bd99b085f12e86777bc18e6a38731b577e6550d92de7dc1023bf265ca","src/lib.rs":"d812637d82a2c89bc2e85deefc342727e746a8d4354d574bd8586485c5eca958"},"package":"a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213"} \ No newline at end of file +{"files":{"Cargo.toml":"8141410d44a74e1783beeec03f35ac2b89ead0f2d0e0fb6ddc71dcc064749a89","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"b68af9a7bf1ad292ee5cfccb123dc639c5c1ad9b57645e533209965c394bf05d","src/lib.rs":"d78b54dc0fe6bd1a3a0ae764d31616a83b1a3b596ec75ad8f182c119c8c30b74"},"package":"5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613"} \ No newline at end of file diff --git a/third_party/rust/clap_lex/Cargo.toml b/third_party/rust/clap_lex/Cargo.toml index bbb41ad981ad..b089dcde8838 100644 --- a/third_party/rust/clap_lex/Cargo.toml +++ b/third_party/rust/clap_lex/Cargo.toml @@ -10,14 +10,18 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2018" +edition = "2021" +rust-version = "1.56.0" name = "clap_lex" -version = "0.2.0" +version = "0.2.2" include = [ + "build.rs", "src/**/*", "Cargo.toml", - "LICENSE-*", + "LICENSE*", "README.md", + "benches/**/*", + "examples/**/*", ] description = "Minimal, flexible command line parser" documentation = "https://docs.rs/clap_lex" @@ -32,6 +36,7 @@ keywords = [ categories = ["command-line-interface"] license = "MIT OR Apache-2.0" repository = "https://github.com/clap-rs/clap/tree/master/clap_lex" +resolver = "2" [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" diff --git a/third_party/rust/clap_lex/README.md b/third_party/rust/clap_lex/README.md index 374dc48a41b0..0c21bc819048 100644 --- a/third_party/rust/clap_lex/README.md +++ b/third_party/rust/clap_lex/README.md @@ -5,15 +5,15 @@ [![Crates.io](https://img.shields.io/crates/v/clap_lex?style=flat-square)](https://crates.io/crates/clap_lex) [![Crates.io](https://img.shields.io/crates/d/clap_lex?style=flat-square)](https://crates.io/crates/clap_lex) -[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.0/LICENSE-APACHE) -[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.0/LICENSE-MIT) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/LICENSE-APACHE) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/LICENSE-MIT) Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). 1. [About](#about) 2. [API Reference](https://docs.rs/clap_lex) 3. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) -4. [CONTRIBUTING](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.0/clap_lex/CONTRIBUTING.md) -5. [Sponsors](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.0/README.md#sponsors) +4. [CONTRIBUTING](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/clap_lex/CONTRIBUTING.md) +5. [Sponsors](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/README.md#sponsors) ## About diff --git a/third_party/rust/clap_lex/src/lib.rs b/third_party/rust/clap_lex/src/lib.rs index f1c8da35be41..f205c3de0150 100644 --- a/third_party/rust/clap_lex/src/lib.rs +++ b/third_party/rust/clap_lex/src/lib.rs @@ -235,6 +235,11 @@ impl RawArgs { insert_items.iter().map(OsString::from), ); } + + /// Any remaining args? + pub fn is_end(&self, cursor: &ArgCursor) -> bool { + self.peek_os(cursor).is_none() + } } impl From for RawArgs From 644033c9d88b87cdaa67d994f5d705ef2a880ca1 Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:20 +0000 Subject: [PATCH 29/64] Bug 1773399 - Update getrandom to 0.2.7. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149326 --- Cargo.lock | 19 +- Cargo.toml | 3 + supply-chain/audits.toml | 5 + supply-chain/config.toml | 2 +- .../rust/getrandom/.cargo-checksum.json | 2 +- third_party/rust/getrandom/CHANGELOG.md | 18 +- third_party/rust/getrandom/Cargo.toml | 38 +- third_party/rust/getrandom/src/bsd_arandom.rs | 1 + third_party/rust/getrandom/src/dragonfly.rs | 1 + third_party/rust/getrandom/src/error.rs | 4 - third_party/rust/getrandom/src/lib.rs | 2 +- .../rust/getrandom/src/linux_android.rs | 1 + third_party/rust/getrandom/src/macos.rs | 1 + third_party/rust/getrandom/src/openbsd.rs | 1 + .../rust/getrandom/src/solaris_illumos.rs | 1 + third_party/rust/getrandom/src/util_libc.rs | 57 +- third_party/rust/getrandom/src/wasi.rs | 12 +- third_party/rust/getrandom/src/windows.rs | 1 + third_party/rust/wasi/.cargo-checksum.json | 2 +- third_party/rust/wasi/Cargo.toml | 11 +- third_party/rust/wasi/README.md | 18 + third_party/rust/wasi/src/error.rs | 51 - third_party/rust/wasi/src/lib.rs | 1 - third_party/rust/wasi/src/lib_generated.rs | 2296 ++++++++++------- 24 files changed, 1556 insertions(+), 992 deletions(-) delete mode 100644 third_party/rust/wasi/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index 49a5096a480e..2ef0658e5f20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2112,13 +2112,13 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" +checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" dependencies = [ "cfg-if 1.0.0", "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", ] [[package]] @@ -5251,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" dependencies = [ "libc", - "wasi", + "wasi 0.10.0+wasi-snapshot-preview999", "winapi", ] @@ -5843,9 +5843,16 @@ dependencies = [ [[package]] name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" +version = "0.10.0+wasi-snapshot-preview999" +dependencies = [ + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" diff --git a/Cargo.toml b/Cargo.toml index 3af9a576f8c6..7aca1c1071d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -135,6 +135,9 @@ parking_lot = { path = "build/rust/parking_lot" } # Override tinyvec with smallvec tinyvec = { path = "build/rust/tinyvec" } +# Patch wasi 0.10 to 0.11 +wasi = { path = "build/rust/wasi" } + # Patch autocfg to hide rustc output. Workaround for https://github.com/cuviper/autocfg/issues/30 autocfg = { path = "third_party/rust/autocfg" } diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index 3d0eddb09a6c..dd3620529a51 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -34,6 +34,11 @@ who = "Mike Hommey " criteria = "safe-to-run" delta = "1.1.0 -> 1.1.1" +[[audits.getrandom]] +who = "Mike Hommey " +criteria = "safe-to-deploy" +delta = "0.2.6 -> 0.2.7" + [[audits.glean]] who = "Jan-Erik Rediger " criteria = "safe-to-deploy" diff --git a/supply-chain/config.toml b/supply-chain/config.toml index 4a52079fd815..11dc0e4f4577 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -1612,7 +1612,7 @@ version = "0.3.2" criteria = "safe-to-run" [[unaudited.wasi]] -version = "0.10.0+wasi-snapshot-preview1" +version = "0.11.0+wasi-snapshot-preview1" criteria = "safe-to-deploy" [[unaudited.wasm-encoder]] diff --git a/third_party/rust/getrandom/.cargo-checksum.json b/third_party/rust/getrandom/.cargo-checksum.json index 7bdcc1bc4ff2..adfe6c9e5198 100644 --- a/third_party/rust/getrandom/.cargo-checksum.json +++ b/third_party/rust/getrandom/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"e972a70c9a4729acbd6bd81ca0c3e03944cab242743b308d124d64b3552f8e63","Cargo.toml":"66283df4cc6406f65b46dded3469d23f9d1c6372a0385af8cdcde9da1b6cf5d9","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d2ee195acd80c7d1364a369ad0d2dad46f5f9f973f9d3960367413fd87acfcd6","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"28f3f7ac4f093dfb6cd2c8e7e0714f16d0f03f8c658e56caa8fe9bd03b1ff39b","src/error.rs":"110ffe8a2c6b0fa46a4e317e837efe617b343f250fedac61bcabc3c5250e7432","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"674af2d277b66ecf2e49e1059638abd58db089df095b8b65d9e347782e4bb1e0","src/linux_android.rs":"39cb80999c8534145240a350976d261b8924436bf9a4563960c7bd8c2c83c773","src/macos.rs":"b692f2fcc2319a5195f47751d5bd7dd87c7c24a61d14fa4e3dbc992ae66212b7","src/openbsd.rs":"066b2dd395c190444a658bb0b52a052eabbd68ea5a534fb729c7e5373abc0a6a","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"9c7004446fabe5a7a21c73d5a65d7e2115b5bd1d1dbb735c984cab3dba239785","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"9fd636b23121a86630f0c7891a310444f5b1bb29b0013290e130b79ed1e1f79e","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"02b3a75613dc80444847675ecfea59f390c2597ce1d3334612a8dba71f6082de","src/windows.rs":"e3c8f033d5d2a6b8abc5c92b005232f5aca8ce941bd94964a0f58f2436af9990","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"} \ No newline at end of file +{"files":{"CHANGELOG.md":"1289f7318d266dca92eceb373c5ff6ee81fa867a6f180ad57759d37df9fcad91","Cargo.toml":"2b0b1b62739f57c58e5069f90b70003f56f3242517d14ac1f875b9f36d227e6e","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d90c419d4def20f83e7535cd3f5ec07035045011a50c3652951d196a120c5d3e","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"47f933eac189f6ea48ecf021efd0747ebce1b43d1bece6bbf72a951bab705987","src/error.rs":"f87ce17f9299f9b59b47306dab25ed01d720a0ba53363f52b46b50e2f5e49e36","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"6f61a660fe35864a2fc8ed2fe29b1c2ddf5d29854a2871daade66f0059f65b8e","src/linux_android.rs":"ec24575aa4ae71b6991290dadfdea931b05397c3faababf24bd794f1a9624835","src/macos.rs":"6c09827ad5292cd022e063efa79523bfdb50ed08b9867ebaa007cd321b8d218e","src/openbsd.rs":"450a23ead462d4a840fee4aa0bfdab1e3d88c8f48e4bb608d457429ddeca69c0","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"d52fee9dd7d661f960c01894edd563c1ff8a512c111f7803092d9aa2ff98718e","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"2a63ac0e6dab16b85c4728b79a16e0640301e8b876f151b0a1db0b4394fa219f","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"dfdd0a870581948bd03abe64d49ca4295d9cfa26e09b97a526fd5e17148ad9ca","src/windows.rs":"d0b4f2afd1959660aa9abcd9477764bd7dc0b7d7048aee748804b37963c77c6f","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"} \ No newline at end of file diff --git a/third_party/rust/getrandom/CHANGELOG.md b/third_party/rust/getrandom/CHANGELOG.md index 4ab267ae06cd..b25704947a03 100644 --- a/third_party/rust/getrandom/CHANGELOG.md +++ b/third_party/rust/getrandom/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.7] - 2022-06-14 +### Changed +- Update `wasi` dependency to `0.11` [#253] + +### Fixed +- Use `AtomicPtr` instead of `AtomicUsize` for Strict Provenance compatibility. [#263] + +### Documentation +- Add comments explaining use of fallback mechanisms [#257] [#260] + +[#263]: https://github.com/rust-random/getrandom/pull/263 +[#260]: https://github.com/rust-random/getrandom/pull/260 +[#253]: https://github.com/rust-random/getrandom/pull/253 +[#257]: https://github.com/rust-random/getrandom/pull/257 + ## [0.2.6] - 2022-03-28 ### Added - Nintendo 3DS (`armv6k-nintendo-3ds`) support [#248] @@ -291,7 +306,8 @@ Publish initial implementation. ## [0.0.0] - 2019-01-19 Publish an empty template library. -[0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 +[0.2.7]: https://github.com/rust-random/getrandom/compare/v0.2.6...v0.2.7 +[0.2.6]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 [0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.4...v0.2.5 [0.2.4]: https://github.com/rust-random/getrandom/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/rust-random/getrandom/compare/v0.2.2...v0.2.3 diff --git a/third_party/rust/getrandom/Cargo.toml b/third_party/rust/getrandom/Cargo.toml index 0a664244e753..9b9c0880abb8 100644 --- a/third_party/rust/getrandom/Cargo.toml +++ b/third_party/rust/getrandom/Cargo.toml @@ -12,17 +12,29 @@ [package] edition = "2018" name = "getrandom" -version = "0.2.6" +version = "0.2.7" authors = ["The Rand Project Developers"] exclude = [".*"] description = "A small cross-platform library for retrieving random data from system source" documentation = "https://docs.rs/getrandom" -categories = ["os", "no-std"] +readme = "README.md" +categories = [ + "os", + "no-std", +] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-random/getrandom" + [package.metadata.docs.rs] -features = ["std", "custom"] -rustdoc-args = ["--cfg", "docsrs"] +features = [ + "std", + "custom", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] + [dependencies.cfg-if] version = "1" @@ -37,11 +49,20 @@ package = "rustc-std-workspace-core" [features] custom = [] -js = ["wasm-bindgen", "js-sys"] +js = [ + "wasm-bindgen", + "js-sys", +] rdrand = [] -rustc-dep-of-std = ["compiler_builtins", "core", "libc/rustc-dep-of-std", "wasi/rustc-dep-of-std"] +rustc-dep-of-std = [ + "compiler_builtins", + "core", + "libc/rustc-dep-of-std", + "wasi/rustc-dep-of-std", +] std = [] test-in-browser = [] + [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dependencies.js-sys] version = "0.3" optional = true @@ -50,10 +71,13 @@ optional = true version = "0.2.62" optional = true default-features = false + [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dev-dependencies.wasm-bindgen-test] version = "0.3.18" + [target."cfg(target_os = \"wasi\")".dependencies.wasi] -version = "0.10" +version = "0.11" + [target."cfg(unix)".dependencies.libc] version = "0.2.120" default-features = false diff --git a/third_party/rust/getrandom/src/bsd_arandom.rs b/third_party/rust/getrandom/src/bsd_arandom.rs index f26f2609c36b..d44121254111 100644 --- a/third_party/rust/getrandom/src/bsd_arandom.rs +++ b/third_party/rust/getrandom/src/bsd_arandom.rs @@ -31,6 +31,7 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { } pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0 #[cfg(target_os = "freebsd")] { use crate::util_libc::Weak; diff --git a/third_party/rust/getrandom/src/dragonfly.rs b/third_party/rust/getrandom/src/dragonfly.rs index f27e906908e9..8daaa40489cf 100644 --- a/third_party/rust/getrandom/src/dragonfly.rs +++ b/third_party/rust/getrandom/src/dragonfly.rs @@ -17,6 +17,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; + // getrandom(2) was introduced in DragonflyBSD 5.7 if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); diff --git a/third_party/rust/getrandom/src/error.rs b/third_party/rust/getrandom/src/error.rs index 6615753768aa..b5ab2bb18370 100644 --- a/third_party/rust/getrandom/src/error.rs +++ b/third_party/rust/getrandom/src/error.rs @@ -109,10 +109,6 @@ cfg_if! { let idx = buf.iter().position(|&b| b == 0).unwrap_or(n); core::str::from_utf8(&buf[..idx]).ok() } - } else if #[cfg(target_os = "wasi")] { - fn os_err(errno: i32, _buf: &mut [u8]) -> Option { - wasi::Error::from_raw_error(errno as _) - } } else { fn os_err(_errno: i32, _buf: &mut [u8]) -> Option<&str> { None diff --git a/third_party/rust/getrandom/src/lib.rs b/third_party/rust/getrandom/src/lib.rs index 888b9a51057a..c62056e55613 100644 --- a/third_party/rust/getrandom/src/lib.rs +++ b/third_party/rust/getrandom/src/lib.rs @@ -149,7 +149,7 @@ #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/getrandom/0.2.6" + html_root_url = "https://docs.rs/getrandom/0.2.7" )] #![no_std] #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)] diff --git a/third_party/rust/getrandom/src/linux_android.rs b/third_party/rust/getrandom/src/linux_android.rs index 5508fdd06ab3..4270b67c65df 100644 --- a/third_party/rust/getrandom/src/linux_android.rs +++ b/third_party/rust/getrandom/src/linux_android.rs @@ -14,6 +14,7 @@ use crate::{ }; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in Linux 3.17 static HAS_GETRANDOM: LazyBool = LazyBool::new(); if HAS_GETRANDOM.unsync_init(is_getrandom_available) { sys_fill_exact(dest, |buf| unsafe { diff --git a/third_party/rust/getrandom/src/macos.rs b/third_party/rust/getrandom/src/macos.rs index 585a35abd074..671a053bffc6 100644 --- a/third_party/rust/getrandom/src/macos.rs +++ b/third_party/rust/getrandom/src/macos.rs @@ -17,6 +17,7 @@ use core::mem; type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getentropy(2) was added in 10.12, Rust supports 10.7+ static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") }; if let Some(fptr) = GETENTROPY.ptr() { let func: GetEntropyFn = unsafe { mem::transmute(fptr) }; diff --git a/third_party/rust/getrandom/src/openbsd.rs b/third_party/rust/getrandom/src/openbsd.rs index c8d28b3d8882..41371736f119 100644 --- a/third_party/rust/getrandom/src/openbsd.rs +++ b/third_party/rust/getrandom/src/openbsd.rs @@ -10,6 +10,7 @@ use crate::{util_libc::last_os_error, Error}; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally. for chunk in dest.chunks_mut(256) { let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) }; if ret == -1 { diff --git a/third_party/rust/getrandom/src/solaris_illumos.rs b/third_party/rust/getrandom/src/solaris_illumos.rs index 2d1b767bb0c2..cf3067d6d80c 100644 --- a/third_party/rust/getrandom/src/solaris_illumos.rs +++ b/third_party/rust/getrandom/src/solaris_illumos.rs @@ -30,6 +30,7 @@ type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in Solaris 11.3 for Illumos in 2015. static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { mem::transmute(fptr) }; diff --git a/third_party/rust/getrandom/src/util_libc.rs b/third_party/rust/getrandom/src/util_libc.rs index 6df1cd7da80a..d057071a7468 100644 --- a/third_party/rust/getrandom/src/util_libc.rs +++ b/third_party/rust/getrandom/src/util_libc.rs @@ -6,8 +6,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] -use crate::{util::LazyUsize, Error}; -use core::{num::NonZeroU32, ptr::NonNull}; +use crate::Error; +use core::{ + num::NonZeroU32, + ptr::NonNull, + sync::atomic::{fence, AtomicPtr, Ordering}, +}; +use libc::c_void; cfg_if! { if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] { @@ -76,29 +81,57 @@ pub fn sys_fill_exact( // A "weak" binding to a C function that may or may not be present at runtime. // Used for supporting newer OS features while still building on older systems. -// F must be a function pointer of type `unsafe extern "C" fn`. Based off of the -// weak! macro in libstd. +// Based off of the DlsymWeak struct in libstd: +// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84 +// except that the caller must manually cast self.ptr() to a function pointer. pub struct Weak { name: &'static str, - addr: LazyUsize, + addr: AtomicPtr, } impl Weak { + // A non-null pointer value which indicates we are uninitialized. This + // constant should ideally not be a valid address of a function pointer. + // However, if by chance libc::dlsym does return UNINIT, there will not + // be undefined behavior. libc::dlsym will just be called each time ptr() + // is called. This would be inefficient, but correct. + // TODO: Replace with core::ptr::invalid_mut(1) when that is stable. + const UNINIT: *mut c_void = 1 as *mut c_void; + // Construct a binding to a C function with a given name. This function is // unsafe because `name` _must_ be null terminated. pub const unsafe fn new(name: &'static str) -> Self { Self { name, - addr: LazyUsize::new(), + addr: AtomicPtr::new(Self::UNINIT), } } - // Return a function pointer if present at runtime. Otherwise, return null. - pub fn ptr(&self) -> Option> { - let addr = self.addr.unsync_init(|| unsafe { - libc::dlsym(libc::RTLD_DEFAULT, self.name.as_ptr() as *const _) as usize - }); - NonNull::new(addr as *mut _) + // Return the address of a function if present at runtime. Otherwise, + // return None. Multiple callers can call ptr() concurrently. It will + // always return _some_ value returned by libc::dlsym. However, the + // dlsym function may be called multiple times. + pub fn ptr(&self) -> Option> { + // Despite having only a single atomic variable (self.addr), we still + // cannot always use Ordering::Relaxed, as we need to make sure a + // successful call to dlsym() is "ordered before" any data read through + // the returned pointer (which occurs when the function is called). + // Our implementation mirrors that of the one in libstd, meaning that + // the use of non-Relaxed operations is probably unnecessary. + match self.addr.load(Ordering::Relaxed) { + Self::UNINIT => { + let symbol = self.name.as_ptr() as *const _; + let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) }; + // Synchronizes with the Acquire fence below + self.addr.store(addr, Ordering::Release); + NonNull::new(addr) + } + addr => { + let func = NonNull::new(addr)?; + fence(Ordering::Acquire); + Some(func) + } + } } } diff --git a/third_party/rust/getrandom/src/wasi.rs b/third_party/rust/getrandom/src/wasi.rs index 2d413e020cd8..c5121824a7ef 100644 --- a/third_party/rust/getrandom/src/wasi.rs +++ b/third_party/rust/getrandom/src/wasi.rs @@ -9,15 +9,11 @@ //! Implementation for WASI use crate::Error; use core::num::NonZeroU32; -use wasi::random_get; +use wasi::wasi_snapshot_preview1::random_get; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - unsafe { - random_get(dest.as_mut_ptr(), dest.len()).map_err(|e: wasi::Error| { - // convert wasi's Error into getrandom's NonZeroU32 error - // SAFETY: `wasi::Error` is `NonZeroU16` internally, so `e.raw_error()` - // will never return 0 - NonZeroU32::new_unchecked(e.raw_error() as u32).into() - }) + match unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) } { + 0 => Ok(()), + err => Err(unsafe { NonZeroU32::new_unchecked(err as u32) }.into()), } } diff --git a/third_party/rust/getrandom/src/windows.rs b/third_party/rust/getrandom/src/windows.rs index 643badd07caa..41dc37a5c525 100644 --- a/third_party/rust/getrandom/src/windows.rs +++ b/third_party/rust/getrandom/src/windows.rs @@ -24,6 +24,7 @@ extern "system" { pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { // Prevent overflow of u32 for chunk in dest.chunks_mut(u32::max_value() as usize) { + // BCryptGenRandom was introduced in Windows Vista let ret = unsafe { BCryptGenRandom( ptr::null_mut(), diff --git a/third_party/rust/wasi/.cargo-checksum.json b/third_party/rust/wasi/.cargo-checksum.json index 534dc6e20555..a13fe2be5836 100644 --- a/third_party/rust/wasi/.cargo-checksum.json +++ b/third_party/rust/wasi/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CODE_OF_CONDUCT.md":"a13aaaf393818bd91207c618724d3fb74944ca5161201822a84af951bcf655ef","CONTRIBUTING.md":"2c908a3e263dc35dfed131c02ff907cd72fafb2c2096e4ba9b1e0cbb7a1b76df","Cargo.toml":"0507b220e56fe90becc31c95576b3c42f05b6453659af34e43eaab219274a14b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-Apache-2.0_WITH_LLVM-exception":"268872b9816f90fd8e85db5a28d33f8150ebb8dd016653fb39ef1f94f2686bc5","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","ORG_CODE_OF_CONDUCT.md":"a62b69bf86e605ee1bcbb2f0a12ba79e4cebb6983a7b6491949750aecc4f2178","README.md":"9412b3834687f28f0fae01a6e45b1309733ac92dcf04ef3ef36a823e76a6fed2","SECURITY.md":"4d75afb09dd28eb5982e3a1f768ee398d90204669ceef3240a16b31dcf04148a","src/error.rs":"96818880fab83125079842e35aacb49333ac66699e223f896699e4fdb88b99e8","src/lib.rs":"ce2e7ee6a6e4d5900f3835568b168afc70870d601b2bb94f1a6b9ddd2f046c3a","src/lib_generated.rs":"352b56bdb0f87dc18592a2241b312710c8326a415c2b3e3e7af26a8e36c2d303"},"package":"1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"} \ No newline at end of file +{"files":{"CODE_OF_CONDUCT.md":"a13aaaf393818bd91207c618724d3fb74944ca5161201822a84af951bcf655ef","CONTRIBUTING.md":"2c908a3e263dc35dfed131c02ff907cd72fafb2c2096e4ba9b1e0cbb7a1b76df","Cargo.toml":"7a38e6f90e220716b5b3f82c0a187dfef180db8d1d262250325a655d1b9888e6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-Apache-2.0_WITH_LLVM-exception":"268872b9816f90fd8e85db5a28d33f8150ebb8dd016653fb39ef1f94f2686bc5","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","ORG_CODE_OF_CONDUCT.md":"a62b69bf86e605ee1bcbb2f0a12ba79e4cebb6983a7b6491949750aecc4f2178","README.md":"c021f687a5a61d9c308581401e7aa4454585a30c418abdd02e3a1ef71daa035f","SECURITY.md":"4d75afb09dd28eb5982e3a1f768ee398d90204669ceef3240a16b31dcf04148a","src/lib.rs":"040651dd678b7788d7cc7a8fdc5f50f664d46bd18976bf638bcb4c827a1793d7","src/lib_generated.rs":"130977e4eaac5e9623caba3d5911616051c8b2cee926333213271a25b733a5df"},"package":"9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"} \ No newline at end of file diff --git a/third_party/rust/wasi/Cargo.toml b/third_party/rust/wasi/Cargo.toml index 00fe5b3cd421..c41e35e9ee88 100644 --- a/third_party/rust/wasi/Cargo.toml +++ b/third_party/rust/wasi/Cargo.toml @@ -3,17 +3,16 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" +version = "0.11.0+wasi-snapshot-preview1" authors = ["The Cranelift Project Developers"] description = "Experimental WASI API bindings for Rust" documentation = "https://docs.rs/wasi" diff --git a/third_party/rust/wasi/README.md b/third_party/rust/wasi/README.md index e92f50e3f5ca..801f56a4e023 100644 --- a/third_party/rust/wasi/README.md +++ b/third_party/rust/wasi/README.md @@ -64,6 +64,24 @@ $ cargo wasi run Hello, World! ``` +# Development + +The bulk of the `wasi` crate is generated by the `witx-bindgen` tool, which lives at +`crates/witx-bindgen` and is part of the cargo workspace. + +The `src/lib_generated.rs` file can be re-generated with the following +command: + +``` +cargo run -p witx-bindgen -- crates/witx-bindgen/WASI/phases/snapshot/witx/wasi_snapshot_preview1.witx > src/lib_generated.rs +``` + +Note that this uses the WASI standard repository as a submodule. If you do not +have this submodule present in your source tree, run: +``` +git submodule update --init +``` + # License This project is licensed under the Apache 2.0 license with the LLVM exception. diff --git a/third_party/rust/wasi/src/error.rs b/third_party/rust/wasi/src/error.rs deleted file mode 100644 index 2f2aaf4b90dd..000000000000 --- a/third_party/rust/wasi/src/error.rs +++ /dev/null @@ -1,51 +0,0 @@ -use super::Errno; -use core::fmt; -use core::num::NonZeroU16; - -/// A raw error returned by wasi APIs, internally containing a 16-bit error -/// code. -#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] -pub struct Error { - code: NonZeroU16, -} - -impl Error { - /// Constructs a new error from a raw error code, returning `None` if the - /// error code is zero (which means success). - pub fn from_raw_error(error: Errno) -> Option { - Some(Error { - code: NonZeroU16::new(error)?, - }) - } - - /// Returns the raw error code that this error represents. - pub fn raw_error(&self) -> u16 { - self.code.get() - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} (error {})", - super::strerror(self.code.get()), - self.code - )?; - Ok(()) - } -} - -impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Error") - .field("code", &self.code) - .field("message", &super::strerror(self.code.get())) - .finish() - } -} - -#[cfg(feature = "std")] -extern crate std; -#[cfg(feature = "std")] -impl std::error::Error for Error {} diff --git a/third_party/rust/wasi/src/lib.rs b/third_party/rust/wasi/src/lib.rs index 51f488907f82..0df207b60e5f 100644 --- a/third_party/rust/wasi/src/lib.rs +++ b/third_party/rust/wasi/src/lib.rs @@ -31,7 +31,6 @@ #![no_std] -mod error; mod lib_generated; pub use lib_generated::*; diff --git a/third_party/rust/wasi/src/lib_generated.rs b/third_party/rust/wasi/src/lib_generated.rs index 422794153d86..641528178f6c 100644 --- a/third_party/rust/wasi/src/lib_generated.rs +++ b/third_party/rust/wasi/src/lib_generated.rs @@ -1,335 +1,490 @@ // This file is automatically generated, DO NOT EDIT // -// To regenerate this file run the `crates/generate-raw` command +// To regenerate this file run the `crates/witx-bindgen` command +use core::fmt; use core::mem::MaybeUninit; - -pub use crate::error::Error; -pub type Result = core::result::Result; pub type Size = usize; pub type Filesize = u64; pub type Timestamp = u64; -pub type Clockid = u32; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Clockid(u32); /// The clock measuring real time. Time value zero corresponds with /// 1970-01-01T00:00:00Z. -pub const CLOCKID_REALTIME: Clockid = 0; +pub const CLOCKID_REALTIME: Clockid = Clockid(0); /// The store-wide monotonic clock, which is defined as a clock measuring /// real time, whose value cannot be adjusted and which cannot have negative /// clock jumps. The epoch of this clock is undefined. The absolute time /// value of this clock therefore has no meaning. -pub const CLOCKID_MONOTONIC: Clockid = 1; +pub const CLOCKID_MONOTONIC: Clockid = Clockid(1); /// The CPU-time clock associated with the current process. -pub const CLOCKID_PROCESS_CPUTIME_ID: Clockid = 2; +pub const CLOCKID_PROCESS_CPUTIME_ID: Clockid = Clockid(2); /// The CPU-time clock associated with the current thread. -pub const CLOCKID_THREAD_CPUTIME_ID: Clockid = 3; -pub type Errno = u16; -/// No error occurred. System call completed successfully. -pub const ERRNO_SUCCESS: Errno = 0; -/// Argument list too long. -pub const ERRNO_2BIG: Errno = 1; -/// Permission denied. -pub const ERRNO_ACCES: Errno = 2; -/// Address in use. -pub const ERRNO_ADDRINUSE: Errno = 3; -/// Address not available. -pub const ERRNO_ADDRNOTAVAIL: Errno = 4; -/// Address family not supported. -pub const ERRNO_AFNOSUPPORT: Errno = 5; -/// Resource unavailable, or operation would block. -pub const ERRNO_AGAIN: Errno = 6; -/// Connection already in progress. -pub const ERRNO_ALREADY: Errno = 7; -/// Bad file descriptor. -pub const ERRNO_BADF: Errno = 8; -/// Bad message. -pub const ERRNO_BADMSG: Errno = 9; -/// Device or resource busy. -pub const ERRNO_BUSY: Errno = 10; -/// Operation canceled. -pub const ERRNO_CANCELED: Errno = 11; -/// No child processes. -pub const ERRNO_CHILD: Errno = 12; -/// Connection aborted. -pub const ERRNO_CONNABORTED: Errno = 13; -/// Connection refused. -pub const ERRNO_CONNREFUSED: Errno = 14; -/// Connection reset. -pub const ERRNO_CONNRESET: Errno = 15; -/// Resource deadlock would occur. -pub const ERRNO_DEADLK: Errno = 16; -/// Destination address required. -pub const ERRNO_DESTADDRREQ: Errno = 17; -/// Mathematics argument out of domain of function. -pub const ERRNO_DOM: Errno = 18; -/// Reserved. -pub const ERRNO_DQUOT: Errno = 19; -/// File exists. -pub const ERRNO_EXIST: Errno = 20; -/// Bad address. -pub const ERRNO_FAULT: Errno = 21; -/// File too large. -pub const ERRNO_FBIG: Errno = 22; -/// Host is unreachable. -pub const ERRNO_HOSTUNREACH: Errno = 23; -/// Identifier removed. -pub const ERRNO_IDRM: Errno = 24; -/// Illegal byte sequence. -pub const ERRNO_ILSEQ: Errno = 25; -/// Operation in progress. -pub const ERRNO_INPROGRESS: Errno = 26; -/// Interrupted function. -pub const ERRNO_INTR: Errno = 27; -/// Invalid argument. -pub const ERRNO_INVAL: Errno = 28; -/// I/O error. -pub const ERRNO_IO: Errno = 29; -/// Socket is connected. -pub const ERRNO_ISCONN: Errno = 30; -/// Is a directory. -pub const ERRNO_ISDIR: Errno = 31; -/// Too many levels of symbolic links. -pub const ERRNO_LOOP: Errno = 32; -/// File descriptor value too large. -pub const ERRNO_MFILE: Errno = 33; -/// Too many links. -pub const ERRNO_MLINK: Errno = 34; -/// Message too large. -pub const ERRNO_MSGSIZE: Errno = 35; -/// Reserved. -pub const ERRNO_MULTIHOP: Errno = 36; -/// Filename too long. -pub const ERRNO_NAMETOOLONG: Errno = 37; -/// Network is down. -pub const ERRNO_NETDOWN: Errno = 38; -/// Connection aborted by network. -pub const ERRNO_NETRESET: Errno = 39; -/// Network unreachable. -pub const ERRNO_NETUNREACH: Errno = 40; -/// Too many files open in system. -pub const ERRNO_NFILE: Errno = 41; -/// No buffer space available. -pub const ERRNO_NOBUFS: Errno = 42; -/// No such device. -pub const ERRNO_NODEV: Errno = 43; -/// No such file or directory. -pub const ERRNO_NOENT: Errno = 44; -/// Executable file format error. -pub const ERRNO_NOEXEC: Errno = 45; -/// No locks available. -pub const ERRNO_NOLCK: Errno = 46; -/// Reserved. -pub const ERRNO_NOLINK: Errno = 47; -/// Not enough space. -pub const ERRNO_NOMEM: Errno = 48; -/// No message of the desired type. -pub const ERRNO_NOMSG: Errno = 49; -/// Protocol not available. -pub const ERRNO_NOPROTOOPT: Errno = 50; -/// No space left on device. -pub const ERRNO_NOSPC: Errno = 51; -/// Function not supported. -pub const ERRNO_NOSYS: Errno = 52; -/// The socket is not connected. -pub const ERRNO_NOTCONN: Errno = 53; -/// Not a directory or a symbolic link to a directory. -pub const ERRNO_NOTDIR: Errno = 54; -/// Directory not empty. -pub const ERRNO_NOTEMPTY: Errno = 55; -/// State not recoverable. -pub const ERRNO_NOTRECOVERABLE: Errno = 56; -/// Not a socket. -pub const ERRNO_NOTSOCK: Errno = 57; -/// Not supported, or operation not supported on socket. -pub const ERRNO_NOTSUP: Errno = 58; -/// Inappropriate I/O control operation. -pub const ERRNO_NOTTY: Errno = 59; -/// No such device or address. -pub const ERRNO_NXIO: Errno = 60; -/// Value too large to be stored in data type. -pub const ERRNO_OVERFLOW: Errno = 61; -/// Previous owner died. -pub const ERRNO_OWNERDEAD: Errno = 62; -/// Operation not permitted. -pub const ERRNO_PERM: Errno = 63; -/// Broken pipe. -pub const ERRNO_PIPE: Errno = 64; -/// Protocol error. -pub const ERRNO_PROTO: Errno = 65; -/// Protocol not supported. -pub const ERRNO_PROTONOSUPPORT: Errno = 66; -/// Protocol wrong type for socket. -pub const ERRNO_PROTOTYPE: Errno = 67; -/// Result too large. -pub const ERRNO_RANGE: Errno = 68; -/// Read-only file system. -pub const ERRNO_ROFS: Errno = 69; -/// Invalid seek. -pub const ERRNO_SPIPE: Errno = 70; -/// No such process. -pub const ERRNO_SRCH: Errno = 71; -/// Reserved. -pub const ERRNO_STALE: Errno = 72; -/// Connection timed out. -pub const ERRNO_TIMEDOUT: Errno = 73; -/// Text file busy. -pub const ERRNO_TXTBSY: Errno = 74; -/// Cross-device link. -pub const ERRNO_XDEV: Errno = 75; -/// Extension: Capabilities insufficient. -pub const ERRNO_NOTCAPABLE: Errno = 76; -pub(crate) fn strerror(code: u16) -> &'static str { - match code { - ERRNO_SUCCESS => "No error occurred. System call completed successfully.", - ERRNO_2BIG => "Argument list too long.", - ERRNO_ACCES => "Permission denied.", - ERRNO_ADDRINUSE => "Address in use.", - ERRNO_ADDRNOTAVAIL => "Address not available.", - ERRNO_AFNOSUPPORT => "Address family not supported.", - ERRNO_AGAIN => "Resource unavailable, or operation would block.", - ERRNO_ALREADY => "Connection already in progress.", - ERRNO_BADF => "Bad file descriptor.", - ERRNO_BADMSG => "Bad message.", - ERRNO_BUSY => "Device or resource busy.", - ERRNO_CANCELED => "Operation canceled.", - ERRNO_CHILD => "No child processes.", - ERRNO_CONNABORTED => "Connection aborted.", - ERRNO_CONNREFUSED => "Connection refused.", - ERRNO_CONNRESET => "Connection reset.", - ERRNO_DEADLK => "Resource deadlock would occur.", - ERRNO_DESTADDRREQ => "Destination address required.", - ERRNO_DOM => "Mathematics argument out of domain of function.", - ERRNO_DQUOT => "Reserved.", - ERRNO_EXIST => "File exists.", - ERRNO_FAULT => "Bad address.", - ERRNO_FBIG => "File too large.", - ERRNO_HOSTUNREACH => "Host is unreachable.", - ERRNO_IDRM => "Identifier removed.", - ERRNO_ILSEQ => "Illegal byte sequence.", - ERRNO_INPROGRESS => "Operation in progress.", - ERRNO_INTR => "Interrupted function.", - ERRNO_INVAL => "Invalid argument.", - ERRNO_IO => "I/O error.", - ERRNO_ISCONN => "Socket is connected.", - ERRNO_ISDIR => "Is a directory.", - ERRNO_LOOP => "Too many levels of symbolic links.", - ERRNO_MFILE => "File descriptor value too large.", - ERRNO_MLINK => "Too many links.", - ERRNO_MSGSIZE => "Message too large.", - ERRNO_MULTIHOP => "Reserved.", - ERRNO_NAMETOOLONG => "Filename too long.", - ERRNO_NETDOWN => "Network is down.", - ERRNO_NETRESET => "Connection aborted by network.", - ERRNO_NETUNREACH => "Network unreachable.", - ERRNO_NFILE => "Too many files open in system.", - ERRNO_NOBUFS => "No buffer space available.", - ERRNO_NODEV => "No such device.", - ERRNO_NOENT => "No such file or directory.", - ERRNO_NOEXEC => "Executable file format error.", - ERRNO_NOLCK => "No locks available.", - ERRNO_NOLINK => "Reserved.", - ERRNO_NOMEM => "Not enough space.", - ERRNO_NOMSG => "No message of the desired type.", - ERRNO_NOPROTOOPT => "Protocol not available.", - ERRNO_NOSPC => "No space left on device.", - ERRNO_NOSYS => "Function not supported.", - ERRNO_NOTCONN => "The socket is not connected.", - ERRNO_NOTDIR => "Not a directory or a symbolic link to a directory.", - ERRNO_NOTEMPTY => "Directory not empty.", - ERRNO_NOTRECOVERABLE => "State not recoverable.", - ERRNO_NOTSOCK => "Not a socket.", - ERRNO_NOTSUP => "Not supported, or operation not supported on socket.", - ERRNO_NOTTY => "Inappropriate I/O control operation.", - ERRNO_NXIO => "No such device or address.", - ERRNO_OVERFLOW => "Value too large to be stored in data type.", - ERRNO_OWNERDEAD => "Previous owner died.", - ERRNO_PERM => "Operation not permitted.", - ERRNO_PIPE => "Broken pipe.", - ERRNO_PROTO => "Protocol error.", - ERRNO_PROTONOSUPPORT => "Protocol not supported.", - ERRNO_PROTOTYPE => "Protocol wrong type for socket.", - ERRNO_RANGE => "Result too large.", - ERRNO_ROFS => "Read-only file system.", - ERRNO_SPIPE => "Invalid seek.", - ERRNO_SRCH => "No such process.", - ERRNO_STALE => "Reserved.", - ERRNO_TIMEDOUT => "Connection timed out.", - ERRNO_TXTBSY => "Text file busy.", - ERRNO_XDEV => "Cross-device link.", - ERRNO_NOTCAPABLE => "Extension: Capabilities insufficient.", - _ => "Unknown error.", +pub const CLOCKID_THREAD_CPUTIME_ID: Clockid = Clockid(3); +impl Clockid { + pub const fn raw(&self) -> u32 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "REALTIME", + 1 => "MONOTONIC", + 2 => "PROCESS_CPUTIME_ID", + 3 => "THREAD_CPUTIME_ID", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => { + "The clock measuring real time. Time value zero corresponds with +1970-01-01T00:00:00Z." + } + 1 => { + "The store-wide monotonic clock, which is defined as a clock measuring +real time, whose value cannot be adjusted and which cannot have negative +clock jumps. The epoch of this clock is undefined. The absolute time +value of this clock therefore has no meaning." + } + 2 => "The CPU-time clock associated with the current process.", + 3 => "The CPU-time clock associated with the current thread.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } } } +impl fmt::Debug for Clockid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Clockid") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Errno(u16); +/// No error occurred. System call completed successfully. +pub const ERRNO_SUCCESS: Errno = Errno(0); +/// Argument list too long. +pub const ERRNO_2BIG: Errno = Errno(1); +/// Permission denied. +pub const ERRNO_ACCES: Errno = Errno(2); +/// Address in use. +pub const ERRNO_ADDRINUSE: Errno = Errno(3); +/// Address not available. +pub const ERRNO_ADDRNOTAVAIL: Errno = Errno(4); +/// Address family not supported. +pub const ERRNO_AFNOSUPPORT: Errno = Errno(5); +/// Resource unavailable, or operation would block. +pub const ERRNO_AGAIN: Errno = Errno(6); +/// Connection already in progress. +pub const ERRNO_ALREADY: Errno = Errno(7); +/// Bad file descriptor. +pub const ERRNO_BADF: Errno = Errno(8); +/// Bad message. +pub const ERRNO_BADMSG: Errno = Errno(9); +/// Device or resource busy. +pub const ERRNO_BUSY: Errno = Errno(10); +/// Operation canceled. +pub const ERRNO_CANCELED: Errno = Errno(11); +/// No child processes. +pub const ERRNO_CHILD: Errno = Errno(12); +/// Connection aborted. +pub const ERRNO_CONNABORTED: Errno = Errno(13); +/// Connection refused. +pub const ERRNO_CONNREFUSED: Errno = Errno(14); +/// Connection reset. +pub const ERRNO_CONNRESET: Errno = Errno(15); +/// Resource deadlock would occur. +pub const ERRNO_DEADLK: Errno = Errno(16); +/// Destination address required. +pub const ERRNO_DESTADDRREQ: Errno = Errno(17); +/// Mathematics argument out of domain of function. +pub const ERRNO_DOM: Errno = Errno(18); +/// Reserved. +pub const ERRNO_DQUOT: Errno = Errno(19); +/// File exists. +pub const ERRNO_EXIST: Errno = Errno(20); +/// Bad address. +pub const ERRNO_FAULT: Errno = Errno(21); +/// File too large. +pub const ERRNO_FBIG: Errno = Errno(22); +/// Host is unreachable. +pub const ERRNO_HOSTUNREACH: Errno = Errno(23); +/// Identifier removed. +pub const ERRNO_IDRM: Errno = Errno(24); +/// Illegal byte sequence. +pub const ERRNO_ILSEQ: Errno = Errno(25); +/// Operation in progress. +pub const ERRNO_INPROGRESS: Errno = Errno(26); +/// Interrupted function. +pub const ERRNO_INTR: Errno = Errno(27); +/// Invalid argument. +pub const ERRNO_INVAL: Errno = Errno(28); +/// I/O error. +pub const ERRNO_IO: Errno = Errno(29); +/// Socket is connected. +pub const ERRNO_ISCONN: Errno = Errno(30); +/// Is a directory. +pub const ERRNO_ISDIR: Errno = Errno(31); +/// Too many levels of symbolic links. +pub const ERRNO_LOOP: Errno = Errno(32); +/// File descriptor value too large. +pub const ERRNO_MFILE: Errno = Errno(33); +/// Too many links. +pub const ERRNO_MLINK: Errno = Errno(34); +/// Message too large. +pub const ERRNO_MSGSIZE: Errno = Errno(35); +/// Reserved. +pub const ERRNO_MULTIHOP: Errno = Errno(36); +/// Filename too long. +pub const ERRNO_NAMETOOLONG: Errno = Errno(37); +/// Network is down. +pub const ERRNO_NETDOWN: Errno = Errno(38); +/// Connection aborted by network. +pub const ERRNO_NETRESET: Errno = Errno(39); +/// Network unreachable. +pub const ERRNO_NETUNREACH: Errno = Errno(40); +/// Too many files open in system. +pub const ERRNO_NFILE: Errno = Errno(41); +/// No buffer space available. +pub const ERRNO_NOBUFS: Errno = Errno(42); +/// No such device. +pub const ERRNO_NODEV: Errno = Errno(43); +/// No such file or directory. +pub const ERRNO_NOENT: Errno = Errno(44); +/// Executable file format error. +pub const ERRNO_NOEXEC: Errno = Errno(45); +/// No locks available. +pub const ERRNO_NOLCK: Errno = Errno(46); +/// Reserved. +pub const ERRNO_NOLINK: Errno = Errno(47); +/// Not enough space. +pub const ERRNO_NOMEM: Errno = Errno(48); +/// No message of the desired type. +pub const ERRNO_NOMSG: Errno = Errno(49); +/// Protocol not available. +pub const ERRNO_NOPROTOOPT: Errno = Errno(50); +/// No space left on device. +pub const ERRNO_NOSPC: Errno = Errno(51); +/// Function not supported. +pub const ERRNO_NOSYS: Errno = Errno(52); +/// The socket is not connected. +pub const ERRNO_NOTCONN: Errno = Errno(53); +/// Not a directory or a symbolic link to a directory. +pub const ERRNO_NOTDIR: Errno = Errno(54); +/// Directory not empty. +pub const ERRNO_NOTEMPTY: Errno = Errno(55); +/// State not recoverable. +pub const ERRNO_NOTRECOVERABLE: Errno = Errno(56); +/// Not a socket. +pub const ERRNO_NOTSOCK: Errno = Errno(57); +/// Not supported, or operation not supported on socket. +pub const ERRNO_NOTSUP: Errno = Errno(58); +/// Inappropriate I/O control operation. +pub const ERRNO_NOTTY: Errno = Errno(59); +/// No such device or address. +pub const ERRNO_NXIO: Errno = Errno(60); +/// Value too large to be stored in data type. +pub const ERRNO_OVERFLOW: Errno = Errno(61); +/// Previous owner died. +pub const ERRNO_OWNERDEAD: Errno = Errno(62); +/// Operation not permitted. +pub const ERRNO_PERM: Errno = Errno(63); +/// Broken pipe. +pub const ERRNO_PIPE: Errno = Errno(64); +/// Protocol error. +pub const ERRNO_PROTO: Errno = Errno(65); +/// Protocol not supported. +pub const ERRNO_PROTONOSUPPORT: Errno = Errno(66); +/// Protocol wrong type for socket. +pub const ERRNO_PROTOTYPE: Errno = Errno(67); +/// Result too large. +pub const ERRNO_RANGE: Errno = Errno(68); +/// Read-only file system. +pub const ERRNO_ROFS: Errno = Errno(69); +/// Invalid seek. +pub const ERRNO_SPIPE: Errno = Errno(70); +/// No such process. +pub const ERRNO_SRCH: Errno = Errno(71); +/// Reserved. +pub const ERRNO_STALE: Errno = Errno(72); +/// Connection timed out. +pub const ERRNO_TIMEDOUT: Errno = Errno(73); +/// Text file busy. +pub const ERRNO_TXTBSY: Errno = Errno(74); +/// Cross-device link. +pub const ERRNO_XDEV: Errno = Errno(75); +/// Extension: Capabilities insufficient. +pub const ERRNO_NOTCAPABLE: Errno = Errno(76); +impl Errno { + pub const fn raw(&self) -> u16 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "SUCCESS", + 1 => "2BIG", + 2 => "ACCES", + 3 => "ADDRINUSE", + 4 => "ADDRNOTAVAIL", + 5 => "AFNOSUPPORT", + 6 => "AGAIN", + 7 => "ALREADY", + 8 => "BADF", + 9 => "BADMSG", + 10 => "BUSY", + 11 => "CANCELED", + 12 => "CHILD", + 13 => "CONNABORTED", + 14 => "CONNREFUSED", + 15 => "CONNRESET", + 16 => "DEADLK", + 17 => "DESTADDRREQ", + 18 => "DOM", + 19 => "DQUOT", + 20 => "EXIST", + 21 => "FAULT", + 22 => "FBIG", + 23 => "HOSTUNREACH", + 24 => "IDRM", + 25 => "ILSEQ", + 26 => "INPROGRESS", + 27 => "INTR", + 28 => "INVAL", + 29 => "IO", + 30 => "ISCONN", + 31 => "ISDIR", + 32 => "LOOP", + 33 => "MFILE", + 34 => "MLINK", + 35 => "MSGSIZE", + 36 => "MULTIHOP", + 37 => "NAMETOOLONG", + 38 => "NETDOWN", + 39 => "NETRESET", + 40 => "NETUNREACH", + 41 => "NFILE", + 42 => "NOBUFS", + 43 => "NODEV", + 44 => "NOENT", + 45 => "NOEXEC", + 46 => "NOLCK", + 47 => "NOLINK", + 48 => "NOMEM", + 49 => "NOMSG", + 50 => "NOPROTOOPT", + 51 => "NOSPC", + 52 => "NOSYS", + 53 => "NOTCONN", + 54 => "NOTDIR", + 55 => "NOTEMPTY", + 56 => "NOTRECOVERABLE", + 57 => "NOTSOCK", + 58 => "NOTSUP", + 59 => "NOTTY", + 60 => "NXIO", + 61 => "OVERFLOW", + 62 => "OWNERDEAD", + 63 => "PERM", + 64 => "PIPE", + 65 => "PROTO", + 66 => "PROTONOSUPPORT", + 67 => "PROTOTYPE", + 68 => "RANGE", + 69 => "ROFS", + 70 => "SPIPE", + 71 => "SRCH", + 72 => "STALE", + 73 => "TIMEDOUT", + 74 => "TXTBSY", + 75 => "XDEV", + 76 => "NOTCAPABLE", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => "No error occurred. System call completed successfully.", + 1 => "Argument list too long.", + 2 => "Permission denied.", + 3 => "Address in use.", + 4 => "Address not available.", + 5 => "Address family not supported.", + 6 => "Resource unavailable, or operation would block.", + 7 => "Connection already in progress.", + 8 => "Bad file descriptor.", + 9 => "Bad message.", + 10 => "Device or resource busy.", + 11 => "Operation canceled.", + 12 => "No child processes.", + 13 => "Connection aborted.", + 14 => "Connection refused.", + 15 => "Connection reset.", + 16 => "Resource deadlock would occur.", + 17 => "Destination address required.", + 18 => "Mathematics argument out of domain of function.", + 19 => "Reserved.", + 20 => "File exists.", + 21 => "Bad address.", + 22 => "File too large.", + 23 => "Host is unreachable.", + 24 => "Identifier removed.", + 25 => "Illegal byte sequence.", + 26 => "Operation in progress.", + 27 => "Interrupted function.", + 28 => "Invalid argument.", + 29 => "I/O error.", + 30 => "Socket is connected.", + 31 => "Is a directory.", + 32 => "Too many levels of symbolic links.", + 33 => "File descriptor value too large.", + 34 => "Too many links.", + 35 => "Message too large.", + 36 => "Reserved.", + 37 => "Filename too long.", + 38 => "Network is down.", + 39 => "Connection aborted by network.", + 40 => "Network unreachable.", + 41 => "Too many files open in system.", + 42 => "No buffer space available.", + 43 => "No such device.", + 44 => "No such file or directory.", + 45 => "Executable file format error.", + 46 => "No locks available.", + 47 => "Reserved.", + 48 => "Not enough space.", + 49 => "No message of the desired type.", + 50 => "Protocol not available.", + 51 => "No space left on device.", + 52 => "Function not supported.", + 53 => "The socket is not connected.", + 54 => "Not a directory or a symbolic link to a directory.", + 55 => "Directory not empty.", + 56 => "State not recoverable.", + 57 => "Not a socket.", + 58 => "Not supported, or operation not supported on socket.", + 59 => "Inappropriate I/O control operation.", + 60 => "No such device or address.", + 61 => "Value too large to be stored in data type.", + 62 => "Previous owner died.", + 63 => "Operation not permitted.", + 64 => "Broken pipe.", + 65 => "Protocol error.", + 66 => "Protocol not supported.", + 67 => "Protocol wrong type for socket.", + 68 => "Result too large.", + 69 => "Read-only file system.", + 70 => "Invalid seek.", + 71 => "No such process.", + 72 => "Reserved.", + 73 => "Connection timed out.", + 74 => "Text file busy.", + 75 => "Cross-device link.", + 76 => "Extension: Capabilities insufficient.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Errno { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Errno") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} +impl fmt::Display for Errno { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} (error {})", self.name(), self.0) + } +} + +#[cfg(feature = "std")] +extern crate std; +#[cfg(feature = "std")] +impl std::error::Error for Errno {} + pub type Rights = u64; /// The right to invoke `fd_datasync`. /// If `path_open` is set, includes the right to invoke /// `path_open` with `fdflags::dsync`. -pub const RIGHTS_FD_DATASYNC: Rights = 0x1; +pub const RIGHTS_FD_DATASYNC: Rights = 1 << 0; /// The right to invoke `fd_read` and `sock_recv`. /// If `rights::fd_seek` is set, includes the right to invoke `fd_pread`. -pub const RIGHTS_FD_READ: Rights = 0x2; +pub const RIGHTS_FD_READ: Rights = 1 << 1; /// The right to invoke `fd_seek`. This flag implies `rights::fd_tell`. -pub const RIGHTS_FD_SEEK: Rights = 0x4; +pub const RIGHTS_FD_SEEK: Rights = 1 << 2; /// The right to invoke `fd_fdstat_set_flags`. -pub const RIGHTS_FD_FDSTAT_SET_FLAGS: Rights = 0x8; +pub const RIGHTS_FD_FDSTAT_SET_FLAGS: Rights = 1 << 3; /// The right to invoke `fd_sync`. /// If `path_open` is set, includes the right to invoke /// `path_open` with `fdflags::rsync` and `fdflags::dsync`. -pub const RIGHTS_FD_SYNC: Rights = 0x10; +pub const RIGHTS_FD_SYNC: Rights = 1 << 4; /// The right to invoke `fd_seek` in such a way that the file offset /// remains unaltered (i.e., `whence::cur` with offset zero), or to /// invoke `fd_tell`. -pub const RIGHTS_FD_TELL: Rights = 0x20; +pub const RIGHTS_FD_TELL: Rights = 1 << 5; /// The right to invoke `fd_write` and `sock_send`. /// If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`. -pub const RIGHTS_FD_WRITE: Rights = 0x40; +pub const RIGHTS_FD_WRITE: Rights = 1 << 6; /// The right to invoke `fd_advise`. -pub const RIGHTS_FD_ADVISE: Rights = 0x80; +pub const RIGHTS_FD_ADVISE: Rights = 1 << 7; /// The right to invoke `fd_allocate`. -pub const RIGHTS_FD_ALLOCATE: Rights = 0x100; +pub const RIGHTS_FD_ALLOCATE: Rights = 1 << 8; /// The right to invoke `path_create_directory`. -pub const RIGHTS_PATH_CREATE_DIRECTORY: Rights = 0x200; +pub const RIGHTS_PATH_CREATE_DIRECTORY: Rights = 1 << 9; /// If `path_open` is set, the right to invoke `path_open` with `oflags::creat`. -pub const RIGHTS_PATH_CREATE_FILE: Rights = 0x400; +pub const RIGHTS_PATH_CREATE_FILE: Rights = 1 << 10; /// The right to invoke `path_link` with the file descriptor as the /// source directory. -pub const RIGHTS_PATH_LINK_SOURCE: Rights = 0x800; +pub const RIGHTS_PATH_LINK_SOURCE: Rights = 1 << 11; /// The right to invoke `path_link` with the file descriptor as the /// target directory. -pub const RIGHTS_PATH_LINK_TARGET: Rights = 0x1000; +pub const RIGHTS_PATH_LINK_TARGET: Rights = 1 << 12; /// The right to invoke `path_open`. -pub const RIGHTS_PATH_OPEN: Rights = 0x2000; +pub const RIGHTS_PATH_OPEN: Rights = 1 << 13; /// The right to invoke `fd_readdir`. -pub const RIGHTS_FD_READDIR: Rights = 0x4000; +pub const RIGHTS_FD_READDIR: Rights = 1 << 14; /// The right to invoke `path_readlink`. -pub const RIGHTS_PATH_READLINK: Rights = 0x8000; +pub const RIGHTS_PATH_READLINK: Rights = 1 << 15; /// The right to invoke `path_rename` with the file descriptor as the source directory. -pub const RIGHTS_PATH_RENAME_SOURCE: Rights = 0x10000; +pub const RIGHTS_PATH_RENAME_SOURCE: Rights = 1 << 16; /// The right to invoke `path_rename` with the file descriptor as the target directory. -pub const RIGHTS_PATH_RENAME_TARGET: Rights = 0x20000; +pub const RIGHTS_PATH_RENAME_TARGET: Rights = 1 << 17; /// The right to invoke `path_filestat_get`. -pub const RIGHTS_PATH_FILESTAT_GET: Rights = 0x40000; +pub const RIGHTS_PATH_FILESTAT_GET: Rights = 1 << 18; /// The right to change a file's size (there is no `path_filestat_set_size`). /// If `path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`. -pub const RIGHTS_PATH_FILESTAT_SET_SIZE: Rights = 0x80000; +pub const RIGHTS_PATH_FILESTAT_SET_SIZE: Rights = 1 << 19; /// The right to invoke `path_filestat_set_times`. -pub const RIGHTS_PATH_FILESTAT_SET_TIMES: Rights = 0x100000; +pub const RIGHTS_PATH_FILESTAT_SET_TIMES: Rights = 1 << 20; /// The right to invoke `fd_filestat_get`. -pub const RIGHTS_FD_FILESTAT_GET: Rights = 0x200000; +pub const RIGHTS_FD_FILESTAT_GET: Rights = 1 << 21; /// The right to invoke `fd_filestat_set_size`. -pub const RIGHTS_FD_FILESTAT_SET_SIZE: Rights = 0x400000; +pub const RIGHTS_FD_FILESTAT_SET_SIZE: Rights = 1 << 22; /// The right to invoke `fd_filestat_set_times`. -pub const RIGHTS_FD_FILESTAT_SET_TIMES: Rights = 0x800000; +pub const RIGHTS_FD_FILESTAT_SET_TIMES: Rights = 1 << 23; /// The right to invoke `path_symlink`. -pub const RIGHTS_PATH_SYMLINK: Rights = 0x1000000; +pub const RIGHTS_PATH_SYMLINK: Rights = 1 << 24; /// The right to invoke `path_remove_directory`. -pub const RIGHTS_PATH_REMOVE_DIRECTORY: Rights = 0x2000000; +pub const RIGHTS_PATH_REMOVE_DIRECTORY: Rights = 1 << 25; /// The right to invoke `path_unlink_file`. -pub const RIGHTS_PATH_UNLINK_FILE: Rights = 0x4000000; +pub const RIGHTS_PATH_UNLINK_FILE: Rights = 1 << 26; /// If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`. /// If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`. -pub const RIGHTS_POLL_FD_READWRITE: Rights = 0x8000000; +pub const RIGHTS_POLL_FD_READWRITE: Rights = 1 << 27; /// The right to invoke `sock_shutdown`. -pub const RIGHTS_SOCK_SHUTDOWN: Rights = 0x10000000; +pub const RIGHTS_SOCK_SHUTDOWN: Rights = 1 << 28; +/// The right to invoke `sock_accept`. +pub const RIGHTS_SOCK_ACCEPT: Rights = 1 << 29; + pub type Fd = u32; #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -350,33 +505,101 @@ pub struct Ciovec { pub type IovecArray<'a> = &'a [Iovec]; pub type CiovecArray<'a> = &'a [Ciovec]; pub type Filedelta = i64; -pub type Whence = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Whence(u8); /// Seek relative to start-of-file. -pub const WHENCE_SET: Whence = 0; +pub const WHENCE_SET: Whence = Whence(0); /// Seek relative to current position. -pub const WHENCE_CUR: Whence = 1; +pub const WHENCE_CUR: Whence = Whence(1); /// Seek relative to end-of-file. -pub const WHENCE_END: Whence = 2; +pub const WHENCE_END: Whence = Whence(2); +impl Whence { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "SET", + 1 => "CUR", + 2 => "END", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => "Seek relative to start-of-file.", + 1 => "Seek relative to current position.", + 2 => "Seek relative to end-of-file.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Whence { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Whence") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Dircookie = u64; pub type Dirnamlen = u32; pub type Inode = u64; -pub type Filetype = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Filetype(u8); /// The type of the file descriptor or file is unknown or is different from any of the other types specified. -pub const FILETYPE_UNKNOWN: Filetype = 0; +pub const FILETYPE_UNKNOWN: Filetype = Filetype(0); /// The file descriptor or file refers to a block device inode. -pub const FILETYPE_BLOCK_DEVICE: Filetype = 1; +pub const FILETYPE_BLOCK_DEVICE: Filetype = Filetype(1); /// The file descriptor or file refers to a character device inode. -pub const FILETYPE_CHARACTER_DEVICE: Filetype = 2; +pub const FILETYPE_CHARACTER_DEVICE: Filetype = Filetype(2); /// The file descriptor or file refers to a directory inode. -pub const FILETYPE_DIRECTORY: Filetype = 3; +pub const FILETYPE_DIRECTORY: Filetype = Filetype(3); /// The file descriptor or file refers to a regular file inode. -pub const FILETYPE_REGULAR_FILE: Filetype = 4; +pub const FILETYPE_REGULAR_FILE: Filetype = Filetype(4); /// The file descriptor or file refers to a datagram socket. -pub const FILETYPE_SOCKET_DGRAM: Filetype = 5; +pub const FILETYPE_SOCKET_DGRAM: Filetype = Filetype(5); /// The file descriptor or file refers to a byte-stream socket. -pub const FILETYPE_SOCKET_STREAM: Filetype = 6; +pub const FILETYPE_SOCKET_STREAM: Filetype = Filetype(6); /// The file refers to a symbolic link inode. -pub const FILETYPE_SYMBOLIC_LINK: Filetype = 7; +pub const FILETYPE_SYMBOLIC_LINK: Filetype = Filetype(7); +impl Filetype { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "UNKNOWN", + 1 => "BLOCK_DEVICE", + 2 => "CHARACTER_DEVICE", + 3 => "DIRECTORY", + 4 => "REGULAR_FILE", + 5 => "SOCKET_DGRAM", + 6 => "SOCKET_STREAM", + 7 => "SYMBOLIC_LINK", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 {0 => "The type of the file descriptor or file is unknown or is different from any of the other types specified.",1 => "The file descriptor or file refers to a block device inode.",2 => "The file descriptor or file refers to a character device inode.",3 => "The file descriptor or file refers to a directory inode.",4 => "The file descriptor or file refers to a regular file inode.",5 => "The file descriptor or file refers to a datagram socket.",6 => "The file descriptor or file refers to a byte-stream socket.",7 => "The file refers to a symbolic link inode.",_ => unsafe { core::hint::unreachable_unchecked() },} + } +} +impl fmt::Debug for Filetype { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Filetype") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Dirent { @@ -389,32 +612,65 @@ pub struct Dirent { /// The type of the file referred to by this directory entry. pub d_type: Filetype, } -pub type Advice = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Advice(u8); /// The application has no advice to give on its behavior with respect to the specified data. -pub const ADVICE_NORMAL: Advice = 0; +pub const ADVICE_NORMAL: Advice = Advice(0); /// The application expects to access the specified data sequentially from lower offsets to higher offsets. -pub const ADVICE_SEQUENTIAL: Advice = 1; +pub const ADVICE_SEQUENTIAL: Advice = Advice(1); /// The application expects to access the specified data in a random order. -pub const ADVICE_RANDOM: Advice = 2; +pub const ADVICE_RANDOM: Advice = Advice(2); /// The application expects to access the specified data in the near future. -pub const ADVICE_WILLNEED: Advice = 3; +pub const ADVICE_WILLNEED: Advice = Advice(3); /// The application expects that it will not access the specified data in the near future. -pub const ADVICE_DONTNEED: Advice = 4; +pub const ADVICE_DONTNEED: Advice = Advice(4); /// The application expects to access the specified data once and then not reuse it thereafter. -pub const ADVICE_NOREUSE: Advice = 5; +pub const ADVICE_NOREUSE: Advice = Advice(5); +impl Advice { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "NORMAL", + 1 => "SEQUENTIAL", + 2 => "RANDOM", + 3 => "WILLNEED", + 4 => "DONTNEED", + 5 => "NOREUSE", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 {0 => "The application has no advice to give on its behavior with respect to the specified data.",1 => "The application expects to access the specified data sequentially from lower offsets to higher offsets.",2 => "The application expects to access the specified data in a random order.",3 => "The application expects to access the specified data in the near future.",4 => "The application expects that it will not access the specified data in the near future.",5 => "The application expects to access the specified data once and then not reuse it thereafter.",_ => unsafe { core::hint::unreachable_unchecked() },} + } +} +impl fmt::Debug for Advice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Advice") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Fdflags = u16; /// Append mode: Data written to the file is always appended to the file's end. -pub const FDFLAGS_APPEND: Fdflags = 0x1; +pub const FDFLAGS_APPEND: Fdflags = 1 << 0; /// Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. -pub const FDFLAGS_DSYNC: Fdflags = 0x2; +pub const FDFLAGS_DSYNC: Fdflags = 1 << 1; /// Non-blocking mode. -pub const FDFLAGS_NONBLOCK: Fdflags = 0x4; +pub const FDFLAGS_NONBLOCK: Fdflags = 1 << 2; /// Synchronized read I/O operations. -pub const FDFLAGS_RSYNC: Fdflags = 0x8; +pub const FDFLAGS_RSYNC: Fdflags = 1 << 3; /// Write according to synchronized I/O file integrity completion. In /// addition to synchronizing the data stored in the file, the implementation /// may also synchronously update the file's metadata. -pub const FDFLAGS_SYNC: Fdflags = 0x10; +pub const FDFLAGS_SYNC: Fdflags = 1 << 4; + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Fdstat { @@ -431,25 +687,28 @@ pub struct Fdstat { pub type Device = u64; pub type Fstflags = u16; /// Adjust the last data access timestamp to the value stored in `filestat::atim`. -pub const FSTFLAGS_ATIM: Fstflags = 0x1; +pub const FSTFLAGS_ATIM: Fstflags = 1 << 0; /// Adjust the last data access timestamp to the time of clock `clockid::realtime`. -pub const FSTFLAGS_ATIM_NOW: Fstflags = 0x2; +pub const FSTFLAGS_ATIM_NOW: Fstflags = 1 << 1; /// Adjust the last data modification timestamp to the value stored in `filestat::mtim`. -pub const FSTFLAGS_MTIM: Fstflags = 0x4; +pub const FSTFLAGS_MTIM: Fstflags = 1 << 2; /// Adjust the last data modification timestamp to the time of clock `clockid::realtime`. -pub const FSTFLAGS_MTIM_NOW: Fstflags = 0x8; +pub const FSTFLAGS_MTIM_NOW: Fstflags = 1 << 3; + pub type Lookupflags = u32; /// As long as the resolved path corresponds to a symbolic link, it is expanded. -pub const LOOKUPFLAGS_SYMLINK_FOLLOW: Lookupflags = 0x1; +pub const LOOKUPFLAGS_SYMLINK_FOLLOW: Lookupflags = 1 << 0; + pub type Oflags = u16; /// Create file if it does not exist. -pub const OFLAGS_CREAT: Oflags = 0x1; +pub const OFLAGS_CREAT: Oflags = 1 << 0; /// Fail if not a directory. -pub const OFLAGS_DIRECTORY: Oflags = 0x2; +pub const OFLAGS_DIRECTORY: Oflags = 1 << 1; /// Fail if file already exists. -pub const OFLAGS_EXCL: Oflags = 0x4; +pub const OFLAGS_EXCL: Oflags = 1 << 2; /// Truncate file to size 0. -pub const OFLAGS_TRUNC: Oflags = 0x8; +pub const OFLAGS_TRUNC: Oflags = 1 << 3; + pub type Linkcount = u64; #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -472,19 +731,63 @@ pub struct Filestat { pub ctim: Timestamp, } pub type Userdata = u64; -pub type Eventtype = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Eventtype(u8); /// The time value of clock `subscription_clock::id` has /// reached timestamp `subscription_clock::timeout`. -pub const EVENTTYPE_CLOCK: Eventtype = 0; +pub const EVENTTYPE_CLOCK: Eventtype = Eventtype(0); /// File descriptor `subscription_fd_readwrite::file_descriptor` has data /// available for reading. This event always triggers for regular files. -pub const EVENTTYPE_FD_READ: Eventtype = 1; +pub const EVENTTYPE_FD_READ: Eventtype = Eventtype(1); /// File descriptor `subscription_fd_readwrite::file_descriptor` has capacity /// available for writing. This event always triggers for regular files. -pub const EVENTTYPE_FD_WRITE: Eventtype = 2; +pub const EVENTTYPE_FD_WRITE: Eventtype = Eventtype(2); +impl Eventtype { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "CLOCK", + 1 => "FD_READ", + 2 => "FD_WRITE", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => { + "The time value of clock `subscription_clock::id` has +reached timestamp `subscription_clock::timeout`." + } + 1 => { + "File descriptor `subscription_fd_readwrite::file_descriptor` has data +available for reading. This event always triggers for regular files." + } + 2 => { + "File descriptor `subscription_fd_readwrite::file_descriptor` has capacity +available for writing. This event always triggers for regular files." + } + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Eventtype { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Eventtype") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Eventrwflags = u16; /// The peer of this socket has closed or disconnected. -pub const EVENTRWFLAGS_FD_READWRITE_HANGUP: Eventrwflags = 0x1; +pub const EVENTRWFLAGS_FD_READWRITE_HANGUP: Eventrwflags = 1 << 0; + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct EventFdReadwrite { @@ -501,7 +804,7 @@ pub struct Event { /// If non-zero, an error that occurred while processing the subscription request. pub error: Errno, /// The type of event that occured - pub r#type: Eventtype, + pub type_: Eventtype, /// The contents of the event, if it is an `eventtype::fd_read` or /// `eventtype::fd_write`. `eventtype::clock` events ignore this field. pub fd_readwrite: EventFdReadwrite, @@ -512,7 +815,8 @@ pub type Subclockflags = u16; /// `subscription_clock::id`. If clear, treat the timestamp /// provided in `subscription_clock::timeout` relative to the /// current time value of clock `subscription_clock::id`. -pub const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: Subclockflags = 0x1; +pub const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: Subclockflags = 1 << 0; + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SubscriptionClock { @@ -542,7 +846,7 @@ pub union SubscriptionUU { #[repr(C)] #[derive(Copy, Clone)] pub struct SubscriptionU { - pub tag: Eventtype, + pub tag: u8, pub u: SubscriptionUU, } @@ -556,117 +860,333 @@ pub struct Subscription { pub u: SubscriptionU, } pub type Exitcode = u32; -pub type Signal = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Signal(u8); /// No signal. Note that POSIX has special semantics for `kill(pid, 0)`, /// so this value is reserved. -pub const SIGNAL_NONE: Signal = 0; +pub const SIGNAL_NONE: Signal = Signal(0); /// Hangup. /// Action: Terminates the process. -pub const SIGNAL_HUP: Signal = 1; +pub const SIGNAL_HUP: Signal = Signal(1); /// Terminate interrupt signal. /// Action: Terminates the process. -pub const SIGNAL_INT: Signal = 2; +pub const SIGNAL_INT: Signal = Signal(2); /// Terminal quit signal. /// Action: Terminates the process. -pub const SIGNAL_QUIT: Signal = 3; +pub const SIGNAL_QUIT: Signal = Signal(3); /// Illegal instruction. /// Action: Terminates the process. -pub const SIGNAL_ILL: Signal = 4; +pub const SIGNAL_ILL: Signal = Signal(4); /// Trace/breakpoint trap. /// Action: Terminates the process. -pub const SIGNAL_TRAP: Signal = 5; +pub const SIGNAL_TRAP: Signal = Signal(5); /// Process abort signal. /// Action: Terminates the process. -pub const SIGNAL_ABRT: Signal = 6; +pub const SIGNAL_ABRT: Signal = Signal(6); /// Access to an undefined portion of a memory object. /// Action: Terminates the process. -pub const SIGNAL_BUS: Signal = 7; +pub const SIGNAL_BUS: Signal = Signal(7); /// Erroneous arithmetic operation. /// Action: Terminates the process. -pub const SIGNAL_FPE: Signal = 8; +pub const SIGNAL_FPE: Signal = Signal(8); /// Kill. /// Action: Terminates the process. -pub const SIGNAL_KILL: Signal = 9; +pub const SIGNAL_KILL: Signal = Signal(9); /// User-defined signal 1. /// Action: Terminates the process. -pub const SIGNAL_USR1: Signal = 10; +pub const SIGNAL_USR1: Signal = Signal(10); /// Invalid memory reference. /// Action: Terminates the process. -pub const SIGNAL_SEGV: Signal = 11; +pub const SIGNAL_SEGV: Signal = Signal(11); /// User-defined signal 2. /// Action: Terminates the process. -pub const SIGNAL_USR2: Signal = 12; +pub const SIGNAL_USR2: Signal = Signal(12); /// Write on a pipe with no one to read it. /// Action: Ignored. -pub const SIGNAL_PIPE: Signal = 13; +pub const SIGNAL_PIPE: Signal = Signal(13); /// Alarm clock. /// Action: Terminates the process. -pub const SIGNAL_ALRM: Signal = 14; +pub const SIGNAL_ALRM: Signal = Signal(14); /// Termination signal. /// Action: Terminates the process. -pub const SIGNAL_TERM: Signal = 15; +pub const SIGNAL_TERM: Signal = Signal(15); /// Child process terminated, stopped, or continued. /// Action: Ignored. -pub const SIGNAL_CHLD: Signal = 16; +pub const SIGNAL_CHLD: Signal = Signal(16); /// Continue executing, if stopped. /// Action: Continues executing, if stopped. -pub const SIGNAL_CONT: Signal = 17; +pub const SIGNAL_CONT: Signal = Signal(17); /// Stop executing. /// Action: Stops executing. -pub const SIGNAL_STOP: Signal = 18; +pub const SIGNAL_STOP: Signal = Signal(18); /// Terminal stop signal. /// Action: Stops executing. -pub const SIGNAL_TSTP: Signal = 19; +pub const SIGNAL_TSTP: Signal = Signal(19); /// Background process attempting read. /// Action: Stops executing. -pub const SIGNAL_TTIN: Signal = 20; +pub const SIGNAL_TTIN: Signal = Signal(20); /// Background process attempting write. /// Action: Stops executing. -pub const SIGNAL_TTOU: Signal = 21; +pub const SIGNAL_TTOU: Signal = Signal(21); /// High bandwidth data is available at a socket. /// Action: Ignored. -pub const SIGNAL_URG: Signal = 22; +pub const SIGNAL_URG: Signal = Signal(22); /// CPU time limit exceeded. /// Action: Terminates the process. -pub const SIGNAL_XCPU: Signal = 23; +pub const SIGNAL_XCPU: Signal = Signal(23); /// File size limit exceeded. /// Action: Terminates the process. -pub const SIGNAL_XFSZ: Signal = 24; +pub const SIGNAL_XFSZ: Signal = Signal(24); /// Virtual timer expired. /// Action: Terminates the process. -pub const SIGNAL_VTALRM: Signal = 25; +pub const SIGNAL_VTALRM: Signal = Signal(25); /// Profiling timer expired. /// Action: Terminates the process. -pub const SIGNAL_PROF: Signal = 26; +pub const SIGNAL_PROF: Signal = Signal(26); /// Window changed. /// Action: Ignored. -pub const SIGNAL_WINCH: Signal = 27; +pub const SIGNAL_WINCH: Signal = Signal(27); /// I/O possible. /// Action: Terminates the process. -pub const SIGNAL_POLL: Signal = 28; +pub const SIGNAL_POLL: Signal = Signal(28); /// Power failure. /// Action: Terminates the process. -pub const SIGNAL_PWR: Signal = 29; +pub const SIGNAL_PWR: Signal = Signal(29); /// Bad system call. /// Action: Terminates the process. -pub const SIGNAL_SYS: Signal = 30; +pub const SIGNAL_SYS: Signal = Signal(30); +impl Signal { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "NONE", + 1 => "HUP", + 2 => "INT", + 3 => "QUIT", + 4 => "ILL", + 5 => "TRAP", + 6 => "ABRT", + 7 => "BUS", + 8 => "FPE", + 9 => "KILL", + 10 => "USR1", + 11 => "SEGV", + 12 => "USR2", + 13 => "PIPE", + 14 => "ALRM", + 15 => "TERM", + 16 => "CHLD", + 17 => "CONT", + 18 => "STOP", + 19 => "TSTP", + 20 => "TTIN", + 21 => "TTOU", + 22 => "URG", + 23 => "XCPU", + 24 => "XFSZ", + 25 => "VTALRM", + 26 => "PROF", + 27 => "WINCH", + 28 => "POLL", + 29 => "PWR", + 30 => "SYS", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => { + "No signal. Note that POSIX has special semantics for `kill(pid, 0)`, +so this value is reserved." + } + 1 => { + "Hangup. +Action: Terminates the process." + } + 2 => { + "Terminate interrupt signal. +Action: Terminates the process." + } + 3 => { + "Terminal quit signal. +Action: Terminates the process." + } + 4 => { + "Illegal instruction. +Action: Terminates the process." + } + 5 => { + "Trace/breakpoint trap. +Action: Terminates the process." + } + 6 => { + "Process abort signal. +Action: Terminates the process." + } + 7 => { + "Access to an undefined portion of a memory object. +Action: Terminates the process." + } + 8 => { + "Erroneous arithmetic operation. +Action: Terminates the process." + } + 9 => { + "Kill. +Action: Terminates the process." + } + 10 => { + "User-defined signal 1. +Action: Terminates the process." + } + 11 => { + "Invalid memory reference. +Action: Terminates the process." + } + 12 => { + "User-defined signal 2. +Action: Terminates the process." + } + 13 => { + "Write on a pipe with no one to read it. +Action: Ignored." + } + 14 => { + "Alarm clock. +Action: Terminates the process." + } + 15 => { + "Termination signal. +Action: Terminates the process." + } + 16 => { + "Child process terminated, stopped, or continued. +Action: Ignored." + } + 17 => { + "Continue executing, if stopped. +Action: Continues executing, if stopped." + } + 18 => { + "Stop executing. +Action: Stops executing." + } + 19 => { + "Terminal stop signal. +Action: Stops executing." + } + 20 => { + "Background process attempting read. +Action: Stops executing." + } + 21 => { + "Background process attempting write. +Action: Stops executing." + } + 22 => { + "High bandwidth data is available at a socket. +Action: Ignored." + } + 23 => { + "CPU time limit exceeded. +Action: Terminates the process." + } + 24 => { + "File size limit exceeded. +Action: Terminates the process." + } + 25 => { + "Virtual timer expired. +Action: Terminates the process." + } + 26 => { + "Profiling timer expired. +Action: Terminates the process." + } + 27 => { + "Window changed. +Action: Ignored." + } + 28 => { + "I/O possible. +Action: Terminates the process." + } + 29 => { + "Power failure. +Action: Terminates the process." + } + 30 => { + "Bad system call. +Action: Terminates the process." + } + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Signal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Signal") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Riflags = u16; /// Returns the message without removing it from the socket's receive queue. -pub const RIFLAGS_RECV_PEEK: Riflags = 0x1; +pub const RIFLAGS_RECV_PEEK: Riflags = 1 << 0; /// On byte-stream sockets, block until the full amount of data can be returned. -pub const RIFLAGS_RECV_WAITALL: Riflags = 0x2; +pub const RIFLAGS_RECV_WAITALL: Riflags = 1 << 1; + pub type Roflags = u16; /// Returned by `sock_recv`: Message data has been truncated. -pub const ROFLAGS_RECV_DATA_TRUNCATED: Roflags = 0x1; +pub const ROFLAGS_RECV_DATA_TRUNCATED: Roflags = 1 << 0; + pub type Siflags = u16; pub type Sdflags = u8; /// Disables further receive operations. -pub const SDFLAGS_RD: Sdflags = 0x1; +pub const SDFLAGS_RD: Sdflags = 1 << 0; /// Disables further send operations. -pub const SDFLAGS_WR: Sdflags = 0x2; -pub type Preopentype = u8; +pub const SDFLAGS_WR: Sdflags = 1 << 1; + +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Preopentype(u8); /// A pre-opened directory. -pub const PREOPENTYPE_DIR: Preopentype = 0; +pub const PREOPENTYPE_DIR: Preopentype = Preopentype(0); +impl Preopentype { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "DIR", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => "A pre-opened directory.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Preopentype { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Preopentype") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct PrestatDir { @@ -681,18 +1201,18 @@ pub union PrestatU { #[repr(C)] #[derive(Copy, Clone)] pub struct Prestat { - pub tag: Preopentype, + pub tag: u8, pub u: PrestatU, } /// Read command-line argument data. -/// The size of the array should match that returned by `args_sizes_get` -pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<()> { - let rc = wasi_snapshot_preview1::args_get(argv, argv_buf); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +/// The size of the array should match that returned by `args_sizes_get`. +/// Each argument is expected to be `\0` terminated. +pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::args_get(argv as i32, argv_buf as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -700,27 +1220,30 @@ pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<()> { /// /// ## Return /// -/// * `argc` - The number of arguments. -/// * `argv_buf_size` - The size of the argument string data. -pub unsafe fn args_sizes_get() -> Result<(Size, Size)> { - let mut argc = MaybeUninit::uninit(); - let mut argv_buf_size = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::args_sizes_get(argc.as_mut_ptr(), argv_buf_size.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok((argc.assume_init(), argv_buf_size.assume_init())) +/// Returns the number of arguments and the size of the argument string +/// data, or an error. +pub unsafe fn args_sizes_get() -> Result<(Size, Size), Errno> { + let mut rp0 = MaybeUninit::::uninit(); + let mut rp1 = MaybeUninit::::uninit(); + let ret = + wasi_snapshot_preview1::args_sizes_get(rp0.as_mut_ptr() as i32, rp1.as_mut_ptr() as i32); + match ret { + 0 => Ok(( + core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), + core::ptr::read(rp1.as_mut_ptr() as i32 as *const Size), + )), + _ => Err(Errno(ret as u16)), } } /// Read environment variable data. /// The sizes of the buffers should match that returned by `environ_sizes_get`. -pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result<()> { - let rc = wasi_snapshot_preview1::environ_get(environ, environ_buf); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +/// Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s. +pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::environ_get(environ as i32, environ_buf as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -728,19 +1251,19 @@ pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result /// /// ## Return /// -/// * `environc` - The number of environment variable arguments. -/// * `environ_buf_size` - The size of the environment variable data. -pub unsafe fn environ_sizes_get() -> Result<(Size, Size)> { - let mut environc = MaybeUninit::uninit(); - let mut environ_buf_size = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::environ_sizes_get( - environc.as_mut_ptr(), - environ_buf_size.as_mut_ptr(), - ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok((environc.assume_init(), environ_buf_size.assume_init())) +/// Returns the number of environment variable arguments and the size of the +/// environment variable data. +pub unsafe fn environ_sizes_get() -> Result<(Size, Size), Errno> { + let mut rp0 = MaybeUninit::::uninit(); + let mut rp1 = MaybeUninit::::uninit(); + let ret = + wasi_snapshot_preview1::environ_sizes_get(rp0.as_mut_ptr() as i32, rp1.as_mut_ptr() as i32); + match ret { + 0 => Ok(( + core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), + core::ptr::read(rp1.as_mut_ptr() as i32 as *const Size), + )), + _ => Err(Errno(ret as u16)), } } @@ -755,14 +1278,13 @@ pub unsafe fn environ_sizes_get() -> Result<(Size, Size)> { /// /// ## Return /// -/// * `resolution` - The resolution of the clock. -pub unsafe fn clock_res_get(id: Clockid) -> Result { - let mut resolution = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::clock_res_get(id, resolution.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(resolution.assume_init()) +/// The resolution of the clock, or an error if one happened. +pub unsafe fn clock_res_get(id: Clockid) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::clock_res_get(id.0 as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Timestamp)), + _ => Err(Errno(ret as u16)), } } @@ -776,14 +1298,17 @@ pub unsafe fn clock_res_get(id: Clockid) -> Result { /// /// ## Return /// -/// * `time` - The time value of the clock. -pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result { - let mut time = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::clock_time_get(id, precision, time.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(time.assume_init()) +/// The time value of the clock. +pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::clock_time_get( + id.0 as i32, + precision as i64, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Timestamp)), + _ => Err(Errno(ret as u16)), } } @@ -795,12 +1320,17 @@ pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result Result<()> { - let rc = wasi_snapshot_preview1::fd_advise(fd, offset, len, advice); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_advise( + fd: Fd, + offset: Filesize, + len: Filesize, + advice: Advice, +) -> Result<(), Errno> { + let ret = + wasi_snapshot_preview1::fd_advise(fd as i32, offset as i64, len as i64, advice.0 as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -811,34 +1341,31 @@ pub unsafe fn fd_advise(fd: Fd, offset: Filesize, len: Filesize, advice: Advice) /// /// * `offset` - The offset at which to start the allocation. /// * `len` - The length of the area that is allocated. -pub unsafe fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_allocate(fd, offset, len); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_allocate(fd as i32, offset as i64, len as i64); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } /// Close a file descriptor. /// Note: This is similar to `close` in POSIX. -pub unsafe fn fd_close(fd: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_close(fd); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_close(fd: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_close(fd as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } /// Synchronize the data of a file to disk. /// Note: This is similar to `fdatasync` in POSIX. -pub unsafe fn fd_datasync(fd: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_datasync(fd); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_datasync(fd: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_datasync(fd as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -847,14 +1374,13 @@ pub unsafe fn fd_datasync(fd: Fd) -> Result<()> { /// /// ## Return /// -/// * `stat` - The buffer where the file descriptor's attributes are stored. -pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { - let mut stat = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_fdstat_get(fd, stat.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(stat.assume_init()) +/// The buffer where the file descriptor's attributes are stored. +pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_fdstat_get(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fdstat)), + _ => Err(Errno(ret as u16)), } } @@ -864,12 +1390,11 @@ pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `flags` - The desired values of the file descriptor flags. -pub unsafe fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_fdstat_set_flags(fd, flags); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_fdstat_set_flags(fd as i32, flags as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -883,12 +1408,15 @@ pub unsafe fn fd_fdstat_set_rights( fd: Fd, fs_rights_base: Rights, fs_rights_inheriting: Rights, -) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_fdstat_set_rights(fd, fs_rights_base, fs_rights_inheriting); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_fdstat_set_rights( + fd as i32, + fs_rights_base as i64, + fs_rights_inheriting as i64, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -896,14 +1424,13 @@ pub unsafe fn fd_fdstat_set_rights( /// /// ## Return /// -/// * `buf` - The buffer where the file's attributes are stored. -pub unsafe fn fd_filestat_get(fd: Fd) -> Result { - let mut buf = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_filestat_get(fd, buf.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(buf.assume_init()) +/// The buffer where the file's attributes are stored. +pub unsafe fn fd_filestat_get(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_filestat_get(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filestat)), + _ => Err(Errno(ret as u16)), } } @@ -913,12 +1440,11 @@ pub unsafe fn fd_filestat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `size` - The desired file size. -pub unsafe fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_filestat_set_size(fd, size); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_filestat_set_size(fd as i32, size as i64); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -935,12 +1461,16 @@ pub unsafe fn fd_filestat_set_times( atim: Timestamp, mtim: Timestamp, fst_flags: Fstflags, -) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_filestat_set_times(fd, atim, mtim, fst_flags); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_filestat_set_times( + fd as i32, + atim as i64, + mtim as i64, + fst_flags as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -954,15 +1484,19 @@ pub unsafe fn fd_filestat_set_times( /// /// ## Return /// -/// * `nread` - The number of bytes read. -pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray, offset: Filesize) -> Result { - let mut nread = MaybeUninit::uninit(); - let rc = - wasi_snapshot_preview1::fd_pread(fd, iovs.as_ptr(), iovs.len(), offset, nread.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nread.assume_init()) +/// The number of bytes read. +pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray<'_>, offset: Filesize) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_pread( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + offset as i64, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -970,14 +1504,13 @@ pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray, offset: Filesize) -> Result Result { - let mut buf = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_prestat_get(fd, buf.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(buf.assume_init()) +/// The buffer where the description is stored. +pub unsafe fn fd_prestat_get(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_prestat_get(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Prestat)), + _ => Err(Errno(ret as u16)), } } @@ -986,12 +1519,11 @@ pub unsafe fn fd_prestat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `path` - A buffer into which to write the preopened directory name. -pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_prestat_dir_name(fd, path, path_len); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_prestat_dir_name(fd as i32, path as i32, path_len as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1005,20 +1537,19 @@ pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Resu /// /// ## Return /// -/// * `nwritten` - The number of bytes written. -pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray, offset: Filesize) -> Result { - let mut nwritten = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_pwrite( - fd, - iovs.as_ptr(), - iovs.len(), - offset, - nwritten.as_mut_ptr(), +/// The number of bytes written. +pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray<'_>, offset: Filesize) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_pwrite( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + offset as i64, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nwritten.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1031,21 +1562,25 @@ pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray, offset: Filesize) -> Result Result { - let mut nread = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_read(fd, iovs.as_ptr(), iovs.len(), nread.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nread.assume_init()) +/// The number of bytes read. +pub unsafe fn fd_read(fd: Fd, iovs: IovecArray<'_>) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_read( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } /// Read directory entries from a directory. /// When successful, the contents of the output buffer consist of a sequence of -/// directory entries. Each directory entry consists of a dirent_t object, -/// followed by dirent_t::d_namlen bytes holding the name of the directory +/// directory entries. Each directory entry consists of a `dirent` object, +/// followed by `dirent::d_namlen` bytes holding the name of the directory /// entry. /// This function fills the output buffer as much as possible, potentially /// truncating the last directory entry. This allows the caller to grow its @@ -1059,14 +1594,24 @@ pub unsafe fn fd_read(fd: Fd, iovs: IovecArray) -> Result { /// /// ## Return /// -/// * `bufused` - The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. -pub unsafe fn fd_readdir(fd: Fd, buf: *mut u8, buf_len: Size, cookie: Dircookie) -> Result { - let mut bufused = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_readdir(fd, buf, buf_len, cookie, bufused.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(bufused.assume_init()) +/// The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. +pub unsafe fn fd_readdir( + fd: Fd, + buf: *mut u8, + buf_len: Size, + cookie: Dircookie, +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_readdir( + fd as i32, + buf as i32, + buf_len as i32, + cookie as i64, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1082,12 +1627,11 @@ pub unsafe fn fd_readdir(fd: Fd, buf: *mut u8, buf_len: Size, cookie: Dircookie) /// ## Parameters /// /// * `to` - The file descriptor to overwrite. -pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_renumber(fd, to); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_renumber(fd as i32, to as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1101,25 +1645,28 @@ pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<()> { /// /// ## Return /// -/// * `newoffset` - The new offset of the file descriptor, relative to the start of the file. -pub unsafe fn fd_seek(fd: Fd, offset: Filedelta, whence: Whence) -> Result { - let mut newoffset = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_seek(fd, offset, whence, newoffset.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(newoffset.assume_init()) +/// The new offset of the file descriptor, relative to the start of the file. +pub unsafe fn fd_seek(fd: Fd, offset: Filedelta, whence: Whence) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_seek( + fd as i32, + offset, + whence.0 as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filesize)), + _ => Err(Errno(ret as u16)), } } /// Synchronize the data and metadata of a file to disk. /// Note: This is similar to `fsync` in POSIX. -pub unsafe fn fd_sync(fd: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_sync(fd); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_sync(fd: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_sync(fd as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1128,14 +1675,13 @@ pub unsafe fn fd_sync(fd: Fd) -> Result<()> { /// /// ## Return /// -/// * `offset` - The current offset of the file descriptor, relative to the start of the file. -pub unsafe fn fd_tell(fd: Fd) -> Result { - let mut offset = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_tell(fd, offset.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(offset.assume_init()) +/// The current offset of the file descriptor, relative to the start of the file. +pub unsafe fn fd_tell(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_tell(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filesize)), + _ => Err(Errno(ret as u16)), } } @@ -1145,17 +1691,17 @@ pub unsafe fn fd_tell(fd: Fd) -> Result { /// ## Parameters /// /// * `iovs` - List of scatter/gather vectors from which to retrieve data. -/// -/// ## Return -/// -/// * `nwritten` - The number of bytes written. -pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray) -> Result { - let mut nwritten = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_write(fd, iovs.as_ptr(), iovs.len(), nwritten.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nwritten.assume_init()) +pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray<'_>) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_write( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1165,12 +1711,15 @@ pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray) -> Result { /// ## Parameters /// /// * `path` - The path at which to create the directory. -pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_create_directory(fd, path.as_ptr(), path.len()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_create_directory( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1184,20 +1733,19 @@ pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<()> { /// /// ## Return /// -/// * `buf` - The buffer where the file's attributes are stored. -pub unsafe fn path_filestat_get(fd: Fd, flags: Lookupflags, path: &str) -> Result { - let mut buf = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::path_filestat_get( - fd, - flags, - path.as_ptr(), - path.len(), - buf.as_mut_ptr(), +/// The buffer where the file's attributes are stored. +pub unsafe fn path_filestat_get(fd: Fd, flags: Lookupflags, path: &str) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::path_filestat_get( + fd as i32, + flags as i32, + path.as_ptr() as i32, + path.len() as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(buf.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filestat)), + _ => Err(Errno(ret as u16)), } } @@ -1218,20 +1766,19 @@ pub unsafe fn path_filestat_set_times( atim: Timestamp, mtim: Timestamp, fst_flags: Fstflags, -) -> Result<()> { - let rc = wasi_snapshot_preview1::path_filestat_set_times( - fd, - flags, - path.as_ptr(), - path.len(), - atim, - mtim, - fst_flags, +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_filestat_set_times( + fd as i32, + flags as i32, + path.as_ptr() as i32, + path.len() as i32, + atim as i64, + mtim as i64, + fst_flags as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1250,20 +1797,19 @@ pub unsafe fn path_link( old_path: &str, new_fd: Fd, new_path: &str, -) -> Result<()> { - let rc = wasi_snapshot_preview1::path_link( - old_fd, - old_flags, - old_path.as_ptr(), - old_path.len(), - new_fd, - new_path.as_ptr(), - new_path.len(), +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_link( + old_fd as i32, + old_flags as i32, + old_path.as_ptr() as i32, + old_path.len() as i32, + new_fd as i32, + new_path.as_ptr() as i32, + new_path.len() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1291,32 +1837,31 @@ pub unsafe fn path_link( /// /// ## Return /// -/// * `opened_fd` - The file descriptor of the file that has been opened. +/// The file descriptor of the file that has been opened. pub unsafe fn path_open( fd: Fd, dirflags: Lookupflags, path: &str, oflags: Oflags, fs_rights_base: Rights, - fs_rights_inherting: Rights, + fs_rights_inheriting: Rights, fdflags: Fdflags, -) -> Result { - let mut opened_fd = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::path_open( - fd, - dirflags, - path.as_ptr(), - path.len(), - oflags, - fs_rights_base, - fs_rights_inherting, - fdflags, - opened_fd.as_mut_ptr(), +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::path_open( + fd as i32, + dirflags as i32, + path.as_ptr() as i32, + path.len() as i32, + oflags as i32, + fs_rights_base as i64, + fs_rights_inheriting as i64, + fdflags as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(opened_fd.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fd)), + _ => Err(Errno(ret as u16)), } } @@ -1330,21 +1875,25 @@ pub unsafe fn path_open( /// /// ## Return /// -/// * `bufused` - The number of bytes placed in the buffer. -pub unsafe fn path_readlink(fd: Fd, path: &str, buf: *mut u8, buf_len: Size) -> Result { - let mut bufused = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::path_readlink( - fd, - path.as_ptr(), - path.len(), - buf, - buf_len, - bufused.as_mut_ptr(), +/// The number of bytes placed in the buffer. +pub unsafe fn path_readlink( + fd: Fd, + path: &str, + buf: *mut u8, + buf_len: Size, +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::path_readlink( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + buf as i32, + buf_len as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(bufused.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1355,12 +1904,15 @@ pub unsafe fn path_readlink(fd: Fd, path: &str, buf: *mut u8, buf_len: Size) -> /// ## Parameters /// /// * `path` - The path to a directory to remove. -pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_remove_directory(fd, path.as_ptr(), path.len()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_remove_directory( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1372,19 +1924,18 @@ pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<()> { /// * `old_path` - The source path of the file or directory to rename. /// * `new_fd` - The working directory at which the resolution of the new path starts. /// * `new_path` - The destination path to which to rename the file or directory. -pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_rename( - fd, - old_path.as_ptr(), - old_path.len(), - new_fd, - new_path.as_ptr(), - new_path.len(), +pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_rename( + fd as i32, + old_path.as_ptr() as i32, + old_path.len() as i32, + new_fd as i32, + new_path.as_ptr() as i32, + new_path.len() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1395,18 +1946,17 @@ pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> /// /// * `old_path` - The contents of the symbolic link. /// * `new_path` - The destination path at which to create the symbolic link. -pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_symlink( - old_path.as_ptr(), - old_path.len(), - fd, - new_path.as_ptr(), - new_path.len(), +pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_symlink( + old_path.as_ptr() as i32, + old_path.len() as i32, + fd as i32, + new_path.as_ptr() as i32, + new_path.len() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1417,12 +1967,15 @@ pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<()> /// ## Parameters /// /// * `path` - The path to a file to unlink. -pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_unlink_file(fd, path.as_ptr(), path.len()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_unlink_file( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1430,24 +1983,28 @@ pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<()> { /// /// ## Parameters /// -/// * `r#in` - The events to which to subscribe. +/// * `in_` - The events to which to subscribe. /// * `out` - The events that have occurred. /// * `nsubscriptions` - Both the number of subscriptions and events. /// /// ## Return /// -/// * `nevents` - The number of events stored. +/// The number of events stored. pub unsafe fn poll_oneoff( - r#in: *const Subscription, + in_: *const Subscription, out: *mut Event, nsubscriptions: Size, -) -> Result { - let mut nevents = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::poll_oneoff(r#in, out, nsubscriptions, nevents.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nevents.assume_init()) +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::poll_oneoff( + in_ as i32, + out as i32, + nsubscriptions as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1459,7 +2016,7 @@ pub unsafe fn poll_oneoff( /// /// * `rval` - The exit code returned by the process. pub unsafe fn proc_exit(rval: Exitcode) { - wasi_snapshot_preview1::proc_exit(rval); + wasi_snapshot_preview1::proc_exit(rval as i32); } /// Send a signal to the process of the calling thread. @@ -1468,23 +2025,21 @@ pub unsafe fn proc_exit(rval: Exitcode) { /// ## Parameters /// /// * `sig` - The signal condition to trigger. -pub unsafe fn proc_raise(sig: Signal) -> Result<()> { - let rc = wasi_snapshot_preview1::proc_raise(sig); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn proc_raise(sig: Signal) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::proc_raise(sig.0 as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } /// Temporarily yield execution of the calling thread. /// Note: This is similar to `sched_yield` in POSIX. -pub unsafe fn sched_yield() -> Result<()> { - let rc = wasi_snapshot_preview1::sched_yield(); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn sched_yield() -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::sched_yield(); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1498,12 +2053,31 @@ pub unsafe fn sched_yield() -> Result<()> { /// ## Parameters /// /// * `buf` - The buffer to fill with random data. -pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<()> { - let rc = wasi_snapshot_preview1::random_get(buf, buf_len); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::random_get(buf as i32, buf_len as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), + } +} + +/// Accept a new incoming connection. +/// Note: This is similar to `accept` in POSIX. +/// +/// ## Parameters +/// +/// * `fd` - The listening socket. +/// * `flags` - The desired values of the file descriptor flags. +/// +/// ## Return +/// +/// New socket connection +pub unsafe fn sock_accept(fd: Fd, flags: Fdflags) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::sock_accept(fd as i32, flags as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fd)), + _ => Err(Errno(ret as u16)), } } @@ -1518,23 +2092,28 @@ pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<()> { /// /// ## Return /// -/// * `ro_datalen` - Number of bytes stored in ri_data. -/// * `ro_flags` - Message flags. -pub unsafe fn sock_recv(fd: Fd, ri_data: IovecArray, ri_flags: Riflags) -> Result<(Size, Roflags)> { - let mut ro_datalen = MaybeUninit::uninit(); - let mut ro_flags = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::sock_recv( - fd, - ri_data.as_ptr(), - ri_data.len(), - ri_flags, - ro_datalen.as_mut_ptr(), - ro_flags.as_mut_ptr(), +/// Number of bytes stored in ri_data and message flags. +pub unsafe fn sock_recv( + fd: Fd, + ri_data: IovecArray<'_>, + ri_flags: Riflags, +) -> Result<(Size, Roflags), Errno> { + let mut rp0 = MaybeUninit::::uninit(); + let mut rp1 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::sock_recv( + fd as i32, + ri_data.as_ptr() as i32, + ri_data.len() as i32, + ri_flags as i32, + rp0.as_mut_ptr() as i32, + rp1.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok((ro_datalen.assume_init(), ro_flags.assume_init())) + match ret { + 0 => Ok(( + core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), + core::ptr::read(rp1.as_mut_ptr() as i32 as *const Roflags), + )), + _ => Err(Errno(ret as u16)), } } @@ -1549,20 +2128,23 @@ pub unsafe fn sock_recv(fd: Fd, ri_data: IovecArray, ri_flags: Riflags) -> Resul /// /// ## Return /// -/// * `so_datalen` - Number of bytes transmitted. -pub unsafe fn sock_send(fd: Fd, si_data: CiovecArray, si_flags: Siflags) -> Result { - let mut so_datalen = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::sock_send( - fd, - si_data.as_ptr(), - si_data.len(), - si_flags, - so_datalen.as_mut_ptr(), +/// Number of bytes transmitted. +pub unsafe fn sock_send( + fd: Fd, + si_data: CiovecArray<'_>, + si_flags: Siflags, +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::sock_send( + fd as i32, + si_data.as_ptr() as i32, + si_data.len() as i32, + si_flags as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(so_datalen.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1572,116 +2154,89 @@ pub unsafe fn sock_send(fd: Fd, si_data: CiovecArray, si_flags: Siflags) -> Resu /// ## Parameters /// /// * `how` - Which channels on the socket to shut down. -pub unsafe fn sock_shutdown(fd: Fd, how: Sdflags) -> Result<()> { - let rc = wasi_snapshot_preview1::sock_shutdown(fd, how); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn sock_shutdown(fd: Fd, how: Sdflags) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::sock_shutdown(fd as i32, how as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } pub mod wasi_snapshot_preview1 { - use super::*; #[link(wasm_import_module = "wasi_snapshot_preview1")] extern "C" { /// Read command-line argument data. - /// The size of the array should match that returned by `args_sizes_get` - pub fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Errno; + /// The size of the array should match that returned by `args_sizes_get`. + /// Each argument is expected to be `\0` terminated. + pub fn args_get(arg0: i32, arg1: i32) -> i32; /// Return command-line argument data sizes. - pub fn args_sizes_get(argc: *mut Size, argv_buf_size: *mut Size) -> Errno; + pub fn args_sizes_get(arg0: i32, arg1: i32) -> i32; /// Read environment variable data. /// The sizes of the buffers should match that returned by `environ_sizes_get`. - pub fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Errno; + /// Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s. + pub fn environ_get(arg0: i32, arg1: i32) -> i32; /// Return environment variable data sizes. - pub fn environ_sizes_get(environc: *mut Size, environ_buf_size: *mut Size) -> Errno; + pub fn environ_sizes_get(arg0: i32, arg1: i32) -> i32; /// Return the resolution of a clock. /// Implementations are required to provide a non-zero value for supported clocks. For unsupported clocks, /// return `errno::inval`. /// Note: This is similar to `clock_getres` in POSIX. - pub fn clock_res_get(id: Clockid, resolution: *mut Timestamp) -> Errno; + pub fn clock_res_get(arg0: i32, arg1: i32) -> i32; /// Return the time value of a clock. /// Note: This is similar to `clock_gettime` in POSIX. - pub fn clock_time_get(id: Clockid, precision: Timestamp, time: *mut Timestamp) -> Errno; + pub fn clock_time_get(arg0: i32, arg1: i64, arg2: i32) -> i32; /// Provide file advisory information on a file descriptor. /// Note: This is similar to `posix_fadvise` in POSIX. - pub fn fd_advise(fd: Fd, offset: Filesize, len: Filesize, advice: Advice) -> Errno; + pub fn fd_advise(arg0: i32, arg1: i64, arg2: i64, arg3: i32) -> i32; /// Force the allocation of space in a file. /// Note: This is similar to `posix_fallocate` in POSIX. - pub fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Errno; + pub fn fd_allocate(arg0: i32, arg1: i64, arg2: i64) -> i32; /// Close a file descriptor. /// Note: This is similar to `close` in POSIX. - pub fn fd_close(fd: Fd) -> Errno; + pub fn fd_close(arg0: i32) -> i32; /// Synchronize the data of a file to disk. /// Note: This is similar to `fdatasync` in POSIX. - pub fn fd_datasync(fd: Fd) -> Errno; + pub fn fd_datasync(arg0: i32) -> i32; /// Get the attributes of a file descriptor. /// Note: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields. - pub fn fd_fdstat_get(fd: Fd, stat: *mut Fdstat) -> Errno; + pub fn fd_fdstat_get(arg0: i32, arg1: i32) -> i32; /// Adjust the flags associated with a file descriptor. /// Note: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX. - pub fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Errno; + pub fn fd_fdstat_set_flags(arg0: i32, arg1: i32) -> i32; /// Adjust the rights associated with a file descriptor. /// This can only be used to remove rights, and returns `errno::notcapable` if called in a way that would attempt to add rights - pub fn fd_fdstat_set_rights( - fd: Fd, - fs_rights_base: Rights, - fs_rights_inheriting: Rights, - ) -> Errno; + pub fn fd_fdstat_set_rights(arg0: i32, arg1: i64, arg2: i64) -> i32; /// Return the attributes of an open file. - pub fn fd_filestat_get(fd: Fd, buf: *mut Filestat) -> Errno; + pub fn fd_filestat_get(arg0: i32, arg1: i32) -> i32; /// Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros. /// Note: This is similar to `ftruncate` in POSIX. - pub fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Errno; + pub fn fd_filestat_set_size(arg0: i32, arg1: i64) -> i32; /// Adjust the timestamps of an open file or directory. /// Note: This is similar to `futimens` in POSIX. - pub fn fd_filestat_set_times( - fd: Fd, - atim: Timestamp, - mtim: Timestamp, - fst_flags: Fstflags, - ) -> Errno; + pub fn fd_filestat_set_times(arg0: i32, arg1: i64, arg2: i64, arg3: i32) -> i32; /// Read from a file descriptor, without using and updating the file descriptor's offset. /// Note: This is similar to `preadv` in POSIX. - pub fn fd_pread( - fd: Fd, - iovs_ptr: *const Iovec, - iovs_len: usize, - offset: Filesize, - nread: *mut Size, - ) -> Errno; + pub fn fd_pread(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; /// Return a description of the given preopened file descriptor. - pub fn fd_prestat_get(fd: Fd, buf: *mut Prestat) -> Errno; + pub fn fd_prestat_get(arg0: i32, arg1: i32) -> i32; /// Return a description of the given preopened file descriptor. - pub fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Errno; + pub fn fd_prestat_dir_name(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Write to a file descriptor, without using and updating the file descriptor's offset. /// Note: This is similar to `pwritev` in POSIX. - pub fn fd_pwrite( - fd: Fd, - iovs_ptr: *const Ciovec, - iovs_len: usize, - offset: Filesize, - nwritten: *mut Size, - ) -> Errno; + pub fn fd_pwrite(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; /// Read from a file descriptor. /// Note: This is similar to `readv` in POSIX. - pub fn fd_read(fd: Fd, iovs_ptr: *const Iovec, iovs_len: usize, nread: *mut Size) -> Errno; + pub fn fd_read(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; /// Read directory entries from a directory. /// When successful, the contents of the output buffer consist of a sequence of - /// directory entries. Each directory entry consists of a dirent_t object, - /// followed by dirent_t::d_namlen bytes holding the name of the directory + /// directory entries. Each directory entry consists of a `dirent` object, + /// followed by `dirent::d_namlen` bytes holding the name of the directory /// entry. /// This function fills the output buffer as much as possible, potentially /// truncating the last directory entry. This allows the caller to grow its /// read buffer size in case it's too small to fit a single large directory /// entry, or skip the oversized directory entry. - pub fn fd_readdir( - fd: Fd, - buf: *mut u8, - buf_len: Size, - cookie: Dircookie, - bufused: *mut Size, - ) -> Errno; + pub fn fd_readdir(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; /// Atomically replace a file descriptor by renumbering another file descriptor. /// Due to the strong focus on thread safety, this environment does not provide /// a mechanism to duplicate or renumber a file descriptor to an arbitrary @@ -1690,63 +2245,47 @@ pub mod wasi_snapshot_preview1 { /// thread at the same time. /// This function provides a way to atomically renumber file descriptors, which /// would disappear if `dup2()` were to be removed entirely. - pub fn fd_renumber(fd: Fd, to: Fd) -> Errno; + pub fn fd_renumber(arg0: i32, arg1: i32) -> i32; /// Move the offset of a file descriptor. /// Note: This is similar to `lseek` in POSIX. - pub fn fd_seek( - fd: Fd, - offset: Filedelta, - whence: Whence, - newoffset: *mut Filesize, - ) -> Errno; + pub fn fd_seek(arg0: i32, arg1: i64, arg2: i32, arg3: i32) -> i32; /// Synchronize the data and metadata of a file to disk. /// Note: This is similar to `fsync` in POSIX. - pub fn fd_sync(fd: Fd) -> Errno; + pub fn fd_sync(arg0: i32) -> i32; /// Return the current offset of a file descriptor. /// Note: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX. - pub fn fd_tell(fd: Fd, offset: *mut Filesize) -> Errno; + pub fn fd_tell(arg0: i32, arg1: i32) -> i32; /// Write to a file descriptor. /// Note: This is similar to `writev` in POSIX. - pub fn fd_write( - fd: Fd, - iovs_ptr: *const Ciovec, - iovs_len: usize, - nwritten: *mut Size, - ) -> Errno; + pub fn fd_write(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; /// Create a directory. /// Note: This is similar to `mkdirat` in POSIX. - pub fn path_create_directory(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; + pub fn path_create_directory(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Return the attributes of a file or directory. /// Note: This is similar to `stat` in POSIX. - pub fn path_filestat_get( - fd: Fd, - flags: Lookupflags, - path_ptr: *const u8, - path_len: usize, - buf: *mut Filestat, - ) -> Errno; + pub fn path_filestat_get(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; /// Adjust the timestamps of a file or directory. /// Note: This is similar to `utimensat` in POSIX. pub fn path_filestat_set_times( - fd: Fd, - flags: Lookupflags, - path_ptr: *const u8, - path_len: usize, - atim: Timestamp, - mtim: Timestamp, - fst_flags: Fstflags, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i64, + arg5: i64, + arg6: i32, + ) -> i32; /// Create a hard link. /// Note: This is similar to `linkat` in POSIX. pub fn path_link( - old_fd: Fd, - old_flags: Lookupflags, - old_path_ptr: *const u8, - old_path_len: usize, - new_fd: Fd, - new_path_ptr: *const u8, - new_path_len: usize, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i32, + arg5: i32, + arg6: i32, + ) -> i32; /// Open a file or directory. /// The returned file descriptor is not guaranteed to be the lowest-numbered /// file descriptor not currently open; it is randomized to prevent @@ -1755,100 +2294,73 @@ pub mod wasi_snapshot_preview1 { /// guaranteed to be less than 2**31. /// Note: This is similar to `openat` in POSIX. pub fn path_open( - fd: Fd, - dirflags: Lookupflags, - path_ptr: *const u8, - path_len: usize, - oflags: Oflags, - fs_rights_base: Rights, - fs_rights_inherting: Rights, - fdflags: Fdflags, - opened_fd: *mut Fd, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i32, + arg5: i64, + arg6: i64, + arg7: i32, + arg8: i32, + ) -> i32; /// Read the contents of a symbolic link. /// Note: This is similar to `readlinkat` in POSIX. pub fn path_readlink( - fd: Fd, - path_ptr: *const u8, - path_len: usize, - buf: *mut u8, - buf_len: Size, - bufused: *mut Size, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i32, + arg5: i32, + ) -> i32; /// Remove a directory. /// Return `errno::notempty` if the directory is not empty. /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - pub fn path_remove_directory(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; + pub fn path_remove_directory(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Rename a file or directory. /// Note: This is similar to `renameat` in POSIX. - pub fn path_rename( - fd: Fd, - old_path_ptr: *const u8, - old_path_len: usize, - new_fd: Fd, - new_path_ptr: *const u8, - new_path_len: usize, - ) -> Errno; + pub fn path_rename(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32) + -> i32; /// Create a symbolic link. /// Note: This is similar to `symlinkat` in POSIX. - pub fn path_symlink( - old_path_ptr: *const u8, - old_path_len: usize, - fd: Fd, - new_path_ptr: *const u8, - new_path_len: usize, - ) -> Errno; + pub fn path_symlink(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; /// Unlink a file. /// Return `errno::isdir` if the path refers to a directory. /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - pub fn path_unlink_file(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; + pub fn path_unlink_file(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Concurrently poll for the occurrence of a set of events. - pub fn poll_oneoff( - r#in: *const Subscription, - out: *mut Event, - nsubscriptions: Size, - nevents: *mut Size, - ) -> Errno; + pub fn poll_oneoff(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; /// Terminate the process normally. An exit code of 0 indicates successful /// termination of the program. The meanings of other values is dependent on /// the environment. - pub fn proc_exit(rval: Exitcode) -> !; + pub fn proc_exit(arg0: i32) -> !; /// Send a signal to the process of the calling thread. /// Note: This is similar to `raise` in POSIX. - pub fn proc_raise(sig: Signal) -> Errno; + pub fn proc_raise(arg0: i32) -> i32; /// Temporarily yield execution of the calling thread. /// Note: This is similar to `sched_yield` in POSIX. - pub fn sched_yield() -> Errno; + pub fn sched_yield() -> i32; /// Write high-quality random data into a buffer. /// This function blocks when the implementation is unable to immediately /// provide sufficient high-quality random data. /// This function may execute slowly, so when large mounts of random data are /// required, it's advisable to use this function to seed a pseudo-random /// number generator, rather than to provide the random data directly. - pub fn random_get(buf: *mut u8, buf_len: Size) -> Errno; + pub fn random_get(arg0: i32, arg1: i32) -> i32; + /// Accept a new incoming connection. + /// Note: This is similar to `accept` in POSIX. + pub fn sock_accept(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Receive a message from a socket. /// Note: This is similar to `recv` in POSIX, though it also supports reading /// the data into multiple buffers in the manner of `readv`. - pub fn sock_recv( - fd: Fd, - ri_data_ptr: *const Iovec, - ri_data_len: usize, - ri_flags: Riflags, - ro_datalen: *mut Size, - ro_flags: *mut Roflags, - ) -> Errno; + pub fn sock_recv(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32) -> i32; /// Send a message on a socket. /// Note: This is similar to `send` in POSIX, though it also supports writing /// the data from multiple buffers in the manner of `writev`. - pub fn sock_send( - fd: Fd, - si_data_ptr: *const Ciovec, - si_data_len: usize, - si_flags: Siflags, - so_datalen: *mut Size, - ) -> Errno; + pub fn sock_send(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; /// Shut down socket send and receive channels. /// Note: This is similar to `shutdown` in POSIX. - pub fn sock_shutdown(fd: Fd, how: Sdflags) -> Errno; + pub fn sock_shutdown(arg0: i32, arg1: i32) -> i32; } } From 600d66cac570fc9ca4309213ea2978c599948a09 Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:20 +0000 Subject: [PATCH 30/64] Bug 1773399 - Update rust_decimal to 1.25.0. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149327 --- Cargo.lock | 4 +- supply-chain/audits.toml | 5 + .../rust/rust_decimal/.cargo-checksum.json | 2 +- third_party/rust/rust_decimal/CHANGELOG.md | 10 ++ third_party/rust/rust_decimal/Cargo.toml | 21 ++- third_party/rust/rust_decimal/Makefile.toml | 11 +- third_party/rust/rust_decimal/README.md | 12 +- third_party/rust/rust_decimal/src/decimal.rs | 11 ++ third_party/rust/rust_decimal/src/lib.rs | 3 +- third_party/rust/rust_decimal/src/rand.rs | 163 +++++++++++++++++- .../rust/rust_decimal/tests/decimal_tests.rs | 43 ++++- 11 files changed, 259 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2ef0658e5f20..62374fe9320e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4584,9 +4584,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.24.0" +version = "1.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2ee7337df68898256ad0d4af4aad178210d9e44d2ff900ce44064a97cd86530" +checksum = "34a3bb58e85333f1ab191bf979104b586ebd77475bc6681882825f4532dfe87c" dependencies = [ "arrayvec", "num-traits", diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index dd3620529a51..cf6b9753ac88 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -57,6 +57,11 @@ criteria = "safe-to-deploy" version = "0.5.4" notes = "I own this crate (I am contain-rs) and 0.5.4 passes miri. This code is very old and used by lots of people, so I'm pretty confident in it, even though it's in maintenance-mode and missing some nice-to-have APIs." +[[audits.rust_decimal]] +who = "Mike Hommey " +criteria = "safe-to-deploy" +delta = "1.24.0 -> 1.25.0" + [[audits.semver]] who = "Mike Hommey " criteria = "safe-to-deploy" diff --git a/third_party/rust/rust_decimal/.cargo-checksum.json b/third_party/rust/rust_decimal/.cargo-checksum.json index 43833472cb60..5f1fd608fee4 100644 --- a/third_party/rust/rust_decimal/.cargo-checksum.json +++ b/third_party/rust/rust_decimal/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"BUILD.md":"302c5260cb6eb87efc1d968b42f082ea3569cca084c0cbcc1821a8670235c19a","CHANGELOG.md":"9eb97b0c6d9a54cb9a8e317a015c906fccd0400b19802651212b30e1f362497a","CODE_OF_CONDUCT.md":"64765f10290cfce7191b4208cb21698b708a118568f5016602cccc304846a09a","CONTRIBUTING.md":"471d6281fb5038e17e32d3b4450aacf542a396709605aa170e07d3971d70b9c1","Cargo.toml":"60ce8e5e75560df63b4897f5b4d856e1c727de56c4fa4a7ccd90fed8e7b5e059","LICENSE":"f8218253704e32441cafea1b9b3bcb2c6a3c51c5553cd8513d179290202bccb2","Makefile.toml":"3b56a3e8b8d9a8737793dedf02b4c19df0452e20452b9d095c8e0399cb406439","README.md":"14dc4562575c0cde12aeedfdfe1c5adbd90cdbc14168acb6da829a4742becdc6","benches/comparison.rs":"e8b14531b129acb8ffca2dd44565d9160f510ec38abd32fc49fd4e2386067e25","benches/lib_benches.rs":"1525a2b3424e04da73153a0a57f8ee6e3c7ba93f3d847940ee596be57d469248","build.rs":"0ec25a3f820ea04eae1e3caeb0cc422d2f9b53b387553db728dcf2d088a67ab9","rustfmt.toml":"f33bda44a494d17c95b7bc1b3dd88c203030b75be766f3a7f9b63ef45d960bb0","src/arithmetic_impls.rs":"87a87bc46214ba7f239dfafcffb6ca05453f2ff07ed36e94792548d508da7a9d","src/constants.rs":"5a31626a234e4bb1f06752d7db6ebb39a543c5e0df1e929dd0032689ef7aaa1f","src/decimal.rs":"c16606f8b5358611e882d09a26082136845ef18ffd2a3c57cb9c51b393c299d8","src/error.rs":"2a3f31951bcffc3bb3cfb48bb68e0e8f51713b0cd38a441bd4fdfb02228fe9c7","src/fuzz.rs":"86c07d8d541b9ee92a51275993b686902712f94c30785ba93f38997f3569e700","src/lib.rs":"70dbf6c86f99df5d8b6e9d4102ee53e9ad222cbfe8b677ee85afe205165bebee","src/maths.rs":"f82016c5ae8406103835a3fedebeb1360cfe3cc40ac4ab28e13da89636c6782c","src/mysql.rs":"1995123011bda5ac6a7d2df5885a568dfdfecd9897ab8d89205817877a242cb3","src/ops.rs":"4d426a35f73b0b69cbceee6e01c6eff59b8cc09aab7c885570aea52d8f258f66","src/ops/add.rs":"a85b6214be92a5563e8bb4a936275d8de094507d77384c9184d63583a78b3f55","src/ops/array.rs":"17a1af576390c8f33ed6c13e1b62722eeaa24c0c0086fb951def6d5dacfdc1cd","src/ops/cmp.rs":"95437401daf93d60425c388fc243e52ad5570cfe6c5d818b5aa144759a5f2ef1","src/ops/common.rs":"6d48ecfa4796a38cb9d4c48f50ffed5d1ee79ba8e168a175615b6fe97194b7c2","src/ops/div.rs":"6b1e90b383293eb51f20f22846002a61f17211f7791860d4e9d6f82ad940fb87","src/ops/legacy.rs":"08bc45454b1815a592cc2fd02df8c50bec36c831ab7af098018e29dfc81f0ec4","src/ops/mul.rs":"b0bb69461b4934cb53c49e105d21da8aa661e1215e8797b8fdc64564df431d92","src/ops/rem.rs":"125d64e9425effd01d4ff400f811f43ef76bf846b6823195059648fdf004b592","src/postgres.rs":"73c41588262ea8d243a4758596ade35ef902fec7dfaba60c44a40c2456900171","src/rand.rs":"386d5a53feec63f53247f102287a4bf8ffe9dbc464246e5f18bd6b14f15f056d","src/rocket.rs":"4d05f292281e4d463abeba603b07ea460065cb1b8ec1c6dafdb4e41f7b89e828","src/serde.rs":"d04dcd3a2143c7145bdaa917dfac61591f79348134b883d05764993bda5e0bac","src/str.rs":"e6750a1ab197a024bea32e2b31dea86bfb1ad640903d36143396e40864339a27","tests/decimal_tests.rs":"9f9a782cdfb215a0b0d3c191b793c2f14d86b3bde90792a0f512de112c86f43c","tests/macros.rs":"f4e1ade99bf8a7aaf2a2d4ee557df5b0b32266a349daf59b2e8b1ae7bc72599c","tests/version-numbers.rs":"73301b7bfe500eada5ede66f0dce89bd3e354af50a8e7a123b02931cd5eb8e16"},"package":"e2ee7337df68898256ad0d4af4aad178210d9e44d2ff900ce44064a97cd86530"} \ No newline at end of file +{"files":{"BUILD.md":"302c5260cb6eb87efc1d968b42f082ea3569cca084c0cbcc1821a8670235c19a","CHANGELOG.md":"1807b647f6d805e7957846be727462418a1c7fcc77995cc02a6f46c9489e2c3e","CODE_OF_CONDUCT.md":"64765f10290cfce7191b4208cb21698b708a118568f5016602cccc304846a09a","CONTRIBUTING.md":"471d6281fb5038e17e32d3b4450aacf542a396709605aa170e07d3971d70b9c1","Cargo.toml":"51d3e23eff65de0d993604235bb2ba346ce48ad11a03ee81c4e46009f0724db3","LICENSE":"f8218253704e32441cafea1b9b3bcb2c6a3c51c5553cd8513d179290202bccb2","Makefile.toml":"759446fa7bc82f7e20333b310204873bf2d7c3a938ed8fd61e4733ffb6e15e32","README.md":"5df24462f65eb1898680080441a178f3918e97841d75f925df38511916dbe0b8","benches/comparison.rs":"e8b14531b129acb8ffca2dd44565d9160f510ec38abd32fc49fd4e2386067e25","benches/lib_benches.rs":"1525a2b3424e04da73153a0a57f8ee6e3c7ba93f3d847940ee596be57d469248","build.rs":"0ec25a3f820ea04eae1e3caeb0cc422d2f9b53b387553db728dcf2d088a67ab9","rustfmt.toml":"f33bda44a494d17c95b7bc1b3dd88c203030b75be766f3a7f9b63ef45d960bb0","src/arithmetic_impls.rs":"87a87bc46214ba7f239dfafcffb6ca05453f2ff07ed36e94792548d508da7a9d","src/constants.rs":"5a31626a234e4bb1f06752d7db6ebb39a543c5e0df1e929dd0032689ef7aaa1f","src/decimal.rs":"9681335e1889d08fae55326b20cd5b863ece5619a238b9c5871ed45f5d88b9e7","src/error.rs":"2a3f31951bcffc3bb3cfb48bb68e0e8f51713b0cd38a441bd4fdfb02228fe9c7","src/fuzz.rs":"86c07d8d541b9ee92a51275993b686902712f94c30785ba93f38997f3569e700","src/lib.rs":"320b247f5b39b309d8a97a76ae58ac0cfd005f88ed3aa7962d8e31c7d3a4733c","src/maths.rs":"f82016c5ae8406103835a3fedebeb1360cfe3cc40ac4ab28e13da89636c6782c","src/mysql.rs":"1995123011bda5ac6a7d2df5885a568dfdfecd9897ab8d89205817877a242cb3","src/ops.rs":"4d426a35f73b0b69cbceee6e01c6eff59b8cc09aab7c885570aea52d8f258f66","src/ops/add.rs":"a85b6214be92a5563e8bb4a936275d8de094507d77384c9184d63583a78b3f55","src/ops/array.rs":"17a1af576390c8f33ed6c13e1b62722eeaa24c0c0086fb951def6d5dacfdc1cd","src/ops/cmp.rs":"95437401daf93d60425c388fc243e52ad5570cfe6c5d818b5aa144759a5f2ef1","src/ops/common.rs":"6d48ecfa4796a38cb9d4c48f50ffed5d1ee79ba8e168a175615b6fe97194b7c2","src/ops/div.rs":"6b1e90b383293eb51f20f22846002a61f17211f7791860d4e9d6f82ad940fb87","src/ops/legacy.rs":"08bc45454b1815a592cc2fd02df8c50bec36c831ab7af098018e29dfc81f0ec4","src/ops/mul.rs":"b0bb69461b4934cb53c49e105d21da8aa661e1215e8797b8fdc64564df431d92","src/ops/rem.rs":"125d64e9425effd01d4ff400f811f43ef76bf846b6823195059648fdf004b592","src/postgres.rs":"73c41588262ea8d243a4758596ade35ef902fec7dfaba60c44a40c2456900171","src/rand.rs":"382f057f4a8752a6028afbecd3cb27422d530c6aa0142ddc04b698b501f8f9db","src/rocket.rs":"4d05f292281e4d463abeba603b07ea460065cb1b8ec1c6dafdb4e41f7b89e828","src/serde.rs":"d04dcd3a2143c7145bdaa917dfac61591f79348134b883d05764993bda5e0bac","src/str.rs":"e6750a1ab197a024bea32e2b31dea86bfb1ad640903d36143396e40864339a27","tests/decimal_tests.rs":"a7ec2edab94d6974677c213b8b6e286772c70e7d81ce76925622dab700c93dea","tests/macros.rs":"f4e1ade99bf8a7aaf2a2d4ee557df5b0b32266a349daf59b2e8b1ae7bc72599c","tests/version-numbers.rs":"73301b7bfe500eada5ede66f0dce89bd3e354af50a8e7a123b02931cd5eb8e16"},"package":"34a3bb58e85333f1ab191bf979104b586ebd77475bc6681882825f4532dfe87c"} \ No newline at end of file diff --git a/third_party/rust/rust_decimal/CHANGELOG.md b/third_party/rust/rust_decimal/CHANGELOG.md index 3d045e42e407..485c99fb9784 100644 --- a/third_party/rust/rust_decimal/CHANGELOG.md +++ b/third_party/rust/rust_decimal/CHANGELOG.md @@ -1,5 +1,15 @@ # Version History +## 1.25.0 + +### Added + +* Expands `rand` support to implement `SampleUniform` to allow for `rng.gen_range` calls ([#519](https://github.com/paupino/rust-decimal/pull/519)) +* Adds [`rkyv` framework](https://github.com/rkyv/rkyv) support for zero-cost (de)serialization ([#520](https://github.com/paupino/rust-decimal/pull/520)) + +A big thank you to [@lukesneeringer](https://github.com/lukesneeringer) and [@dovahcrow](https://github.com/dovahcrow) for your help building +features for this release. + ## 1.24.0 * Introduces new feature `rand` which allows for random number generation within `rust_decimal` ([#517](https://github.com/paupino/rust-decimal/pull/517)). diff --git a/third_party/rust/rust_decimal/Cargo.toml b/third_party/rust/rust_decimal/Cargo.toml index b9c736fb7ad4..8febaae70e3c 100644 --- a/third_party/rust/rust_decimal/Cargo.toml +++ b/third_party/rust/rust_decimal/Cargo.toml @@ -12,7 +12,7 @@ [package] edition = "2021" name = "rust_decimal" -version = "1.24.0" +version = "1.25.0" authors = ["Paul Mason "] build = "build.rs" exclude = ["tests/generated/*"] @@ -57,6 +57,11 @@ version = "0.9.3" optional = true default-features = false +[dependencies.bytecheck] +version = "0.6" +optional = true +default-features = false + [dependencies.byteorder] version = "1.3" optional = true @@ -87,6 +92,15 @@ version = "0.8" optional = true default-features = false +[dependencies.rkyv] +version = "0.7" +features = [ + "size_32", + "std", +] +optional = true +default-features = false + [dependencies.rocket] version = "0.5.0-rc.1" optional = true @@ -186,6 +200,11 @@ default = [ legacy-ops = [] maths = [] maths-nopanic = ["maths"] +rkyv-safe = [ + "bytecheck", + "rkyv", + "rkyv/validation", +] rocket-traits = ["rocket"] rust-fuzz = ["arbitrary"] serde-arbitrary-precision = ["serde-with-arbitrary-precision"] diff --git a/third_party/rust/rust_decimal/Makefile.toml b/third_party/rust/rust_decimal/Makefile.toml index 95e2aa33d0fd..18b9debf71fb 100644 --- a/third_party/rust/rust_decimal/Makefile.toml +++ b/third_party/rust/rust_decimal/Makefile.toml @@ -176,7 +176,8 @@ args = ["test", "--workspace", "--no-default-features", "--features=maths-nopani [tasks.test-misc] dependencies = [ "test-rust-fuzz", - "test-borsh" + "test-borsh", + "test-rkyv" ] [tasks.test-rust-fuzz] @@ -249,9 +250,13 @@ args = ["test", "--workspace", "--tests", "--features=serde-with-str", "serde", [tasks.test-borsh] command = "cargo" -args = ["test", "--workspace", "--features=borsh"] +args = ["test", "--workspace", "--features=borsh", "--", "--skip", "generated"] + +[tasks.test-rkyv] +command = "cargo" +args = ["test", "--workspace", "--features=rkyv", "--features=rkyv-safe", "--", "--skip", "generated"] [tasks.test-rand] command = "cargo" -args = ["test", "--workspace", "--features=rand"] +args = ["test", "--workspace", "--features=rand", "--", "--skip", "generated"] diff --git a/third_party/rust/rust_decimal/README.md b/third_party/rust/rust_decimal/README.md index 85c2df43fe7f..2662a2ffda2f 100644 --- a/third_party/rust/rust_decimal/README.md +++ b/third_party/rust/rust_decimal/README.md @@ -17,8 +17,8 @@ To get started, add `rust_decimal` and optionally `rust_decimal_macros` to your ```toml [dependencies] -rust_decimal = "1.24" -rust_decimal_macros = "1.24" +rust_decimal = "1.25" +rust_decimal_macros = "1.25" ``` ## Usage @@ -79,6 +79,7 @@ assert_eq!(total.to_string(), "27.26"); * [c-repr](#c-repr) * [legacy-ops](#legacy-ops) * [maths](#maths) +* [rkyv](#rkyv) * [rocket-traits](#rocket-traits) * [rust-fuzz](#rust-fuzz) * [std](#std) @@ -144,6 +145,13 @@ non-panicking behavior, please use the feature: `maths-nopanic`. Implements `rand::distributions::Distribution` to allow the creation of random instances. +Note: When using `rand::Rng` trait to generate a decimal between a range of two other decimals, the scale of the randomly-generated +decimal will be the same as the scale of the input decimals (or, if the inputs have different scales, the higher of the two). + +### `rkyv` +Enables [rkyv](https://github.com/rkyv/rkyv) serialization for `Decimal`. +Supports rkyv's safe API when the `rkyv-safe` feature is enabled as well. + ### `rocket-traits` Enable support for Rocket forms by implementing the `FromFormField` trait. diff --git a/third_party/rust/rust_decimal/src/decimal.rs b/third_party/rust/rust_decimal/src/decimal.rs index e2100b8164af..0ec113f83311 100644 --- a/third_party/rust/rust_decimal/src/decimal.rs +++ b/third_party/rust/rust_decimal/src/decimal.rs @@ -5,6 +5,8 @@ use crate::constants::{ use crate::ops; use crate::Error; +#[cfg(feature = "rkyv-safe")] +use bytecheck::CheckBytes; use core::{ cmp::{Ordering::Equal, *}, fmt, @@ -19,6 +21,8 @@ use diesel::sql_types::Numeric; #[cfg(not(feature = "std"))] use num_traits::float::FloatCore; use num_traits::{FromPrimitive, Num, One, Signed, ToPrimitive, Zero}; +#[cfg(feature = "rkyv")] +use rkyv::{Archive, Deserialize, Serialize}; /// The smallest value that can be represented by this decimal type. const MIN: Decimal = Decimal { @@ -101,6 +105,13 @@ pub struct UnpackedDecimal { feature = "borsh", derive(borsh::BorshDeserialize, borsh::BorshSerialize, borsh::BorshSchema) )] +#[cfg_attr( + feature = "rkyv", + derive(Archive, Deserialize, Serialize), + archive(compare(PartialEq)), + archive_attr(derive(Debug)) +)] +#[cfg_attr(feature = "rkyv-safe", archive_attr(derive(CheckBytes)))] pub struct Decimal { // Bits 0-15: unused // Bits 16-23: Contains "e", a value between 0-28 that indicates the scale diff --git a/third_party/rust/rust_decimal/src/lib.rs b/third_party/rust/rust_decimal/src/lib.rs index 87694d1a75ec..99ea26bad756 100644 --- a/third_party/rust/rust_decimal/src/lib.rs +++ b/third_party/rust/rust_decimal/src/lib.rs @@ -7,7 +7,6 @@ mod constants; mod decimal; mod error; mod ops; -mod rand; mod str; // We purposely place this here for documentation ordering @@ -25,6 +24,8 @@ mod mysql; feature = "db-diesel-postgres", ))] mod postgres; +#[cfg(feature = "rand")] +mod rand; #[cfg(feature = "rocket-traits")] mod rocket; #[cfg(all( diff --git a/third_party/rust/rust_decimal/src/rand.rs b/third_party/rust/rust_decimal/src/rand.rs index 64401b39ef2c..afd8a64361d6 100644 --- a/third_party/rust/rust_decimal/src/rand.rs +++ b/third_party/rust/rust_decimal/src/rand.rs @@ -1,8 +1,9 @@ -#![cfg(feature = "rand")] - use crate::Decimal; use rand::{ - distributions::{Distribution, Standard}, + distributions::{ + uniform::{SampleBorrow, SampleUniform, UniformInt, UniformSampler}, + Distribution, Standard, + }, Rng, }; @@ -21,9 +22,155 @@ impl Distribution for Standard { } } -#[test] -fn has_random_decimal_instances() { - let mut rng = rand::rngs::OsRng; - let random: [Decimal; 32] = rng.gen(); - assert!(random.windows(2).any(|slice| { slice[0] != slice[1] })); +impl SampleUniform for Decimal { + type Sampler = DecimalSampler; +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DecimalSampler { + mantissa_sampler: UniformInt, + scale: u32, +} + +impl UniformSampler for DecimalSampler { + type X = Decimal; + + /// Creates a new sampler that will yield random decimal objects between `low` and `high`. + /// + /// The sampler will always provide decimals at the same scale as the inputs; if the inputs + /// have different scales, the higher scale is used. + /// + /// # Example + /// + /// ``` + /// # use rand::Rng; + /// # use rust_decimal_macros::dec; + /// let mut rng = rand::rngs::OsRng; + /// let random = rng.gen_range(dec!(1.00)..dec!(2.00)); + /// assert!(random >= dec!(1.00)); + /// assert!(random < dec!(2.00)); + /// assert_eq!(random.scale(), 2); + /// ``` + #[inline] + fn new(low: B1, high: B2) -> Self + where + B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized, + { + let (low, high) = sync_scales(*low.borrow(), *high.borrow()); + let high = Decimal::from_i128_with_scale(high.mantissa() - 1, high.scale()); + UniformSampler::new_inclusive(low, high) + } + + /// Creates a new sampler that will yield random decimal objects between `low` and `high`. + /// + /// The sampler will always provide decimals at the same scale as the inputs; if the inputs + /// have different scales, the higher scale is used. + /// + /// # Example + /// + /// ``` + /// # use rand::Rng; + /// # use rust_decimal_macros::dec; + /// let mut rng = rand::rngs::OsRng; + /// let random = rng.gen_range(dec!(1.00)..=dec!(2.00)); + /// assert!(random >= dec!(1.00)); + /// assert!(random <= dec!(2.00)); + /// assert_eq!(random.scale(), 2); + /// ``` + #[inline] + fn new_inclusive(low: B1, high: B2) -> Self + where + B1: SampleBorrow + Sized, + B2: SampleBorrow + Sized, + { + let (low, high) = sync_scales(*low.borrow(), *high.borrow()); + + // Return our sampler, which contains an underlying i128 sampler so we + // outsource the actual randomness implementation. + Self { + mantissa_sampler: UniformInt::new_inclusive(low.mantissa(), high.mantissa()), + scale: low.scale(), + } + } + + #[inline] + fn sample(&self, rng: &mut R) -> Self::X { + let mantissa = self.mantissa_sampler.sample(rng); + Decimal::from_i128_with_scale(mantissa, self.scale) + } +} + +/// Return equivalent Decimal objects with the same scale as one another. +#[inline] +fn sync_scales(mut a: Decimal, mut b: Decimal) -> (Decimal, Decimal) { + if a.scale() == b.scale() { + return (a, b); + } + + // Set scales to match one another, because we are relying on mantissas' + // being comparable in order outsource the actual sampling implementation. + a.rescale(a.scale().max(b.scale())); + b.rescale(a.scale().max(b.scale())); + + // Edge case: If the values have _wildly_ different scales, the values may not have rescaled far enough to match one another. + // + // In this case, we accept some precision loss because the randomization approach we are using assumes that the scales will necessarily match. + if a.scale() != b.scale() { + a.rescale(a.scale().min(b.scale())); + b.rescale(a.scale().min(b.scale())); + } + + (a, b) +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + macro_rules! dec { + ($e:expr) => { + Decimal::from_str_exact(stringify!($e)).unwrap() + }; + } + + #[test] + fn has_random_decimal_instances() { + let mut rng = rand::rngs::OsRng; + let random: [Decimal; 32] = rng.gen(); + assert!(random.windows(2).any(|slice| { slice[0] != slice[1] })); + } + + #[test] + fn generates_within_range() { + let mut rng = rand::rngs::OsRng; + for _ in 0..128 { + let random = rng.gen_range(dec!(1.00)..dec!(1.05)); + assert!(random < dec!(1.05)); + assert!(random >= dec!(1.00)); + } + } + + #[test] + fn generates_within_inclusive_range() { + let mut rng = rand::rngs::OsRng; + let mut values: HashSet = HashSet::new(); + for _ in 0..256 { + let random = rng.gen_range(dec!(1.00)..=dec!(1.01)); + // The scale is 2, so 1.00 and 1.01 are the only two valid choices. + assert!(random == dec!(1.00) || random == dec!(1.01)); + values.insert(random); + } + // Somewhat flaky, will fail 1 out of every 2^255 times this is run. + // Probably acceptable in the real world. + assert_eq!(values.len(), 2); + } + + #[test] + fn test_edge_case_scales_match() { + let (low, high) = sync_scales(dec!(1.000_000_000_000_000_000_01), dec!(100_000_000_000_000_000_001)); + assert_eq!(low.scale(), high.scale()); + } } diff --git a/third_party/rust/rust_decimal/tests/decimal_tests.rs b/third_party/rust/rust_decimal/tests/decimal_tests.rs index 2e6c7cf4bc69..240e8dbbecf8 100644 --- a/third_party/rust/rust_decimal/tests/decimal_tests.rs +++ b/third_party/rust/rust_decimal/tests/decimal_tests.rs @@ -152,6 +152,33 @@ fn it_can_serialize_deserialize_borsh() { } } +#[test] +#[cfg(feature = "rkyv")] +fn it_can_serialize_deserialize_rkyv() { + use rkyv::Deserialize; + let tests = [ + "12.3456789", + "5233.9008808150288439427720175", + "-5233.9008808150288439427720175", + ]; + for test in &tests { + let a = Decimal::from_str(test).unwrap(); + let bytes = rkyv::to_bytes::<_, 256>(&a).unwrap(); + + #[cfg(feature = "rkyv-safe")] + { + let archived = rkyv::check_archived_root::(&bytes[..]).unwrap(); + assert_eq!(archived, &a); + } + + let archived = unsafe { rkyv::archived_root::(&bytes[..]) }; + assert_eq!(archived, &a); + + let deserialized: Decimal = archived.deserialize(&mut rkyv::Infallible).unwrap(); + assert_eq!(deserialized, a); + } +} + #[test] fn it_can_deserialize_unbounded_values() { // Mantissa for these: 19393111376951473493673267553 @@ -2556,14 +2583,14 @@ fn it_can_return_the_min_value() { #[test] fn it_can_go_from_and_into() { let d = Decimal::from_str("5").unwrap(); - let di8 = 5u8.into(); - let di32 = 5i32.into(); - let disize = 5isize.into(); - let di64 = 5i64.into(); - let du8 = 5u8.into(); - let du32 = 5u32.into(); - let dusize = 5usize.into(); - let du64 = 5u64.into(); + let di8: Decimal = 5u8.into(); + let di32: Decimal = 5i32.into(); + let disize: Decimal = 5isize.into(); + let di64: Decimal = 5i64.into(); + let du8: Decimal = 5u8.into(); + let du32: Decimal = 5u32.into(); + let dusize: Decimal = 5usize.into(); + let du64: Decimal = 5u64.into(); assert_eq!(d, di8); assert_eq!(di8, di32); From 6266da2cef500973c89c57b1ea300372f2b4459c Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 21:26:21 +0000 Subject: [PATCH 31/64] Bug 1773399 - Update unicode-ident to 1.0.1. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149328 --- Cargo.lock | 4 ++-- supply-chain/audits.toml | 5 +++++ third_party/rust/unicode-ident/.cargo-checksum.json | 2 +- third_party/rust/unicode-ident/Cargo.toml | 2 +- third_party/rust/unicode-ident/README.md | 2 +- third_party/rust/unicode-ident/src/lib.rs | 2 +- third_party/rust/unicode-ident/src/tables.rs | 6 ++++++ third_party/rust/unicode-ident/tests/static_size.rs | 13 +++++++++++++ 8 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 62374fe9320e..1a1b14d1546e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5637,9 +5637,9 @@ checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-ident" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee" +checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" [[package]] name = "unicode-normalization" diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index cf6b9753ac88..3c4b7f1e8d4c 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -73,3 +73,8 @@ criteria = "safe-to-deploy" version = "0.2.5" notes = "I own this crate, and most of its versions were codeveloped and reviewed by Nika Layzell. This version was not explicitly reviewed by her, but it was specifically a release that made the code pass miri and was reviewed by me. Firefox uses it in the gecko-ffi configuration which is less thoroughly tested and more dangerous but we're reasonably confident in it. The real danger is from C++ code failing to use it correctly in FFI but that's just how FFI is." +[[audits.unicode-ident]] +who = "Mike Hommey " +criteria = "safe-to-deploy" +delta = "1.0.0 -> 1.0.1" + diff --git a/third_party/rust/unicode-ident/.cargo-checksum.json b/third_party/rust/unicode-ident/.cargo-checksum.json index 5934c5047170..8066cd8bceef 100644 --- a/third_party/rust/unicode-ident/.cargo-checksum.json +++ b/third_party/rust/unicode-ident/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"c28569507ef5f4aa676b9464919586a08d9963456ee1b971ba3b447079ae4fdc","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"978354c627f8884d0adff27e6174db3a3b7fc398879e6938dc3dec4694ed8b05","benches/xid.rs":"a61f61ecc7d5124c759cdeb55ab74470ab69f2f3ca37613da65f16e0e5e33487","src/lib.rs":"88ccdd144277224a59b21855ca7744b8dc3aebe2d02db1f579ae315503441b64","src/tables.rs":"c644ad2c02b62e4ba04f6cc310347faa2c04863786562f50fdd1cf5a75abcf0e","tests/compare.rs":"89c4dc4f745064a9f734667b1d960596a10b8cb019a8ed1c5b9512678a866ad5","tests/fst/mod.rs":"69a3aaf59acd8bca962ecc6234be56be8c0934ab79b253162f10eb881523901f","tests/fst/xid_continue.fst":"6e079a81175e445461dc330f61294c9f24bdb1681b7a591999fbb4547766ea99","tests/fst/xid_start.fst":"382fc736b472d09052a53c89cc2060bd839792350c6d22638b91e9123bf14540","tests/roaring/mod.rs":"784f65a48477fab7549620c7843c7ad6da533f69a18abca1172f6acb95045e53","tests/static_size.rs":"e4c7f8ea5c582048bb8c5896df7dd64cd6c97341a9b94c80ee6afac7c6882e79","tests/trie/mod.rs":"d4acbb716bcbaf80660039797f45e138ed8bbd66749fa3b19b1a971574679cc9","tests/trie/trie.rs":"6780e33f74f86131aa32f321bc3c77c4d9b526b708e82db64b198dce4c86429b"},"package":"d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"} \ No newline at end of file +{"files":{"Cargo.toml":"43a169366c8f04f5c100d7b1a29fbe9f4d50ff5a019d72761be6c949f259333a","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"31a16b16a84da0ccaaeb16b1a4c70d89592d12de5c139053f724dbac91bdd40c","benches/xid.rs":"a61f61ecc7d5124c759cdeb55ab74470ab69f2f3ca37613da65f16e0e5e33487","src/lib.rs":"d0030259a628125669ad6c02d3eb791526e6d6ae35d8a858a87f90245162666c","src/tables.rs":"887457a7ce0d2fff750b40134de684e86d3999e5d191544f31ee45936b7bcb72","tests/compare.rs":"89c4dc4f745064a9f734667b1d960596a10b8cb019a8ed1c5b9512678a866ad5","tests/fst/mod.rs":"69a3aaf59acd8bca962ecc6234be56be8c0934ab79b253162f10eb881523901f","tests/fst/xid_continue.fst":"6e079a81175e445461dc330f61294c9f24bdb1681b7a591999fbb4547766ea99","tests/fst/xid_start.fst":"382fc736b472d09052a53c89cc2060bd839792350c6d22638b91e9123bf14540","tests/roaring/mod.rs":"784f65a48477fab7549620c7843c7ad6da533f69a18abca1172f6acb95045e53","tests/static_size.rs":"3974f6948c06d60b63738ddf5688478144718da87ccfdc4af6918d76a0bd9f06","tests/trie/mod.rs":"d4acbb716bcbaf80660039797f45e138ed8bbd66749fa3b19b1a971574679cc9","tests/trie/trie.rs":"6780e33f74f86131aa32f321bc3c77c4d9b526b708e82db64b198dce4c86429b"},"package":"5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c"} \ No newline at end of file diff --git a/third_party/rust/unicode-ident/Cargo.toml b/third_party/rust/unicode-ident/Cargo.toml index a5e5b3984712..bb1171eaa80e 100644 --- a/third_party/rust/unicode-ident/Cargo.toml +++ b/third_party/rust/unicode-ident/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.31" name = "unicode-ident" -version = "1.0.0" +version = "1.0.1" authors = ["David Tolnay "] description = "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31" documentation = "https://docs.rs/unicode-ident" diff --git a/third_party/rust/unicode-ident/README.md b/third_party/rust/unicode-ident/README.md index d189dac105bf..4acefdb055a2 100644 --- a/third_party/rust/unicode-ident/README.md +++ b/third_party/rust/unicode-ident/README.md @@ -3,7 +3,7 @@ Unicode ident [github](https://github.com/dtolnay/unicode-ident) [crates.io](https://crates.io/crates/unicode-ident) -[docs.rs](https://docs.rs/unicode-ident) +[docs.rs](https://docs.rs/unicode-ident) [build status](https://github.com/dtolnay/unicode-ident/actions?query=branch%3Amaster) Implementation of [Unicode Standard Annex #31][tr31] for determining which diff --git a/third_party/rust/unicode-ident/src/lib.rs b/third_party/rust/unicode-ident/src/lib.rs index 67aaf5ad16de..42126dd2b5fa 100644 --- a/third_party/rust/unicode-ident/src/lib.rs +++ b/third_party/rust/unicode-ident/src/lib.rs @@ -2,7 +2,7 @@ //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust -//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! diff --git a/third_party/rust/unicode-ident/src/tables.rs b/third_party/rust/unicode-ident/src/tables.rs index 53aa5b5ad909..a697636b6de3 100644 --- a/third_party/rust/unicode-ident/src/tables.rs +++ b/third_party/rust/unicode-ident/src/tables.rs @@ -1,3 +1,9 @@ +// @generated by ../generate. To regenerate, run the following in the repo root: +// +// $ curl -LO https://www.unicode.org/Public/zipped/14.0.0/UCD.zip +// $ unzip UCD.zip -d UCD +// $ cargo run --manifest-path generate/Cargo.toml + const T: bool = true; const F: bool = false; diff --git a/third_party/rust/unicode-ident/tests/static_size.rs b/third_party/rust/unicode-ident/tests/static_size.rs index b8622d701132..f0e04d4db66e 100644 --- a/third_party/rust/unicode-ident/tests/static_size.rs +++ b/third_party/rust/unicode-ident/tests/static_size.rs @@ -16,6 +16,19 @@ fn test_size() { assert_eq!(9752, size); } +#[test] +fn test_xid_size() { + #[deny(dead_code)] + #[allow(clippy::redundant_static_lifetimes)] + #[path = "../generate/src/ucd.rs"] + mod ucd; + + let size = size_of_val(ucd::XID_START) + size_of_val(ucd::XID_CONTINUE); + assert_eq!(11344, size); + + let _ = ucd::BY_NAME; +} + #[cfg(target_pointer_width = "64")] #[test] fn test_trieset_size() { From 4f215efcf97e1a88870b7783c13d7ee638d583ac Mon Sep 17 00:00:00 2001 From: Butkovits Atila Date: Thu, 16 Jun 2022 00:43:00 +0300 Subject: [PATCH 32/64] Backed out changeset 8f87ffd7365c (bug 1773399) for causing build bustages. CLOSED TREE --- Cargo.lock | 19 +- Cargo.toml | 3 - supply-chain/audits.toml | 5 - supply-chain/config.toml | 2 +- .../rust/getrandom/.cargo-checksum.json | 2 +- third_party/rust/getrandom/CHANGELOG.md | 18 +- third_party/rust/getrandom/Cargo.toml | 38 +- third_party/rust/getrandom/src/bsd_arandom.rs | 1 - third_party/rust/getrandom/src/dragonfly.rs | 1 - third_party/rust/getrandom/src/error.rs | 4 + third_party/rust/getrandom/src/lib.rs | 2 +- .../rust/getrandom/src/linux_android.rs | 1 - third_party/rust/getrandom/src/macos.rs | 1 - third_party/rust/getrandom/src/openbsd.rs | 1 - .../rust/getrandom/src/solaris_illumos.rs | 1 - third_party/rust/getrandom/src/util_libc.rs | 57 +- third_party/rust/getrandom/src/wasi.rs | 12 +- third_party/rust/getrandom/src/windows.rs | 1 - third_party/rust/wasi/.cargo-checksum.json | 2 +- third_party/rust/wasi/Cargo.toml | 11 +- third_party/rust/wasi/README.md | 18 - third_party/rust/wasi/src/error.rs | 51 + third_party/rust/wasi/src/lib.rs | 1 + third_party/rust/wasi/src/lib_generated.rs | 2142 +++++++---------- 24 files changed, 915 insertions(+), 1479 deletions(-) create mode 100644 third_party/rust/wasi/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index 1a1b14d1546e..edb09f488077 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2112,13 +2112,13 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.7" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" +checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" dependencies = [ "cfg-if 1.0.0", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", ] [[package]] @@ -5251,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" dependencies = [ "libc", - "wasi 0.10.0+wasi-snapshot-preview999", + "wasi", "winapi", ] @@ -5843,16 +5843,9 @@ dependencies = [ [[package]] name = "wasi" -version = "0.10.0+wasi-snapshot-preview999" -dependencies = [ - "wasi 0.11.0+wasi-snapshot-preview1", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.10.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" [[package]] name = "wasm-bindgen" diff --git a/Cargo.toml b/Cargo.toml index 7aca1c1071d6..3af9a576f8c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -135,9 +135,6 @@ parking_lot = { path = "build/rust/parking_lot" } # Override tinyvec with smallvec tinyvec = { path = "build/rust/tinyvec" } -# Patch wasi 0.10 to 0.11 -wasi = { path = "build/rust/wasi" } - # Patch autocfg to hide rustc output. Workaround for https://github.com/cuviper/autocfg/issues/30 autocfg = { path = "third_party/rust/autocfg" } diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index 3c4b7f1e8d4c..82b7dd2a56ac 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -34,11 +34,6 @@ who = "Mike Hommey " criteria = "safe-to-run" delta = "1.1.0 -> 1.1.1" -[[audits.getrandom]] -who = "Mike Hommey " -criteria = "safe-to-deploy" -delta = "0.2.6 -> 0.2.7" - [[audits.glean]] who = "Jan-Erik Rediger " criteria = "safe-to-deploy" diff --git a/supply-chain/config.toml b/supply-chain/config.toml index 11dc0e4f4577..4a52079fd815 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -1612,7 +1612,7 @@ version = "0.3.2" criteria = "safe-to-run" [[unaudited.wasi]] -version = "0.11.0+wasi-snapshot-preview1" +version = "0.10.0+wasi-snapshot-preview1" criteria = "safe-to-deploy" [[unaudited.wasm-encoder]] diff --git a/third_party/rust/getrandom/.cargo-checksum.json b/third_party/rust/getrandom/.cargo-checksum.json index adfe6c9e5198..7bdcc1bc4ff2 100644 --- a/third_party/rust/getrandom/.cargo-checksum.json +++ b/third_party/rust/getrandom/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"1289f7318d266dca92eceb373c5ff6ee81fa867a6f180ad57759d37df9fcad91","Cargo.toml":"2b0b1b62739f57c58e5069f90b70003f56f3242517d14ac1f875b9f36d227e6e","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d90c419d4def20f83e7535cd3f5ec07035045011a50c3652951d196a120c5d3e","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"47f933eac189f6ea48ecf021efd0747ebce1b43d1bece6bbf72a951bab705987","src/error.rs":"f87ce17f9299f9b59b47306dab25ed01d720a0ba53363f52b46b50e2f5e49e36","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"6f61a660fe35864a2fc8ed2fe29b1c2ddf5d29854a2871daade66f0059f65b8e","src/linux_android.rs":"ec24575aa4ae71b6991290dadfdea931b05397c3faababf24bd794f1a9624835","src/macos.rs":"6c09827ad5292cd022e063efa79523bfdb50ed08b9867ebaa007cd321b8d218e","src/openbsd.rs":"450a23ead462d4a840fee4aa0bfdab1e3d88c8f48e4bb608d457429ddeca69c0","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"d52fee9dd7d661f960c01894edd563c1ff8a512c111f7803092d9aa2ff98718e","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"2a63ac0e6dab16b85c4728b79a16e0640301e8b876f151b0a1db0b4394fa219f","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"dfdd0a870581948bd03abe64d49ca4295d9cfa26e09b97a526fd5e17148ad9ca","src/windows.rs":"d0b4f2afd1959660aa9abcd9477764bd7dc0b7d7048aee748804b37963c77c6f","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"} \ No newline at end of file +{"files":{"CHANGELOG.md":"e972a70c9a4729acbd6bd81ca0c3e03944cab242743b308d124d64b3552f8e63","Cargo.toml":"66283df4cc6406f65b46dded3469d23f9d1c6372a0385af8cdcde9da1b6cf5d9","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d2ee195acd80c7d1364a369ad0d2dad46f5f9f973f9d3960367413fd87acfcd6","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"28f3f7ac4f093dfb6cd2c8e7e0714f16d0f03f8c658e56caa8fe9bd03b1ff39b","src/error.rs":"110ffe8a2c6b0fa46a4e317e837efe617b343f250fedac61bcabc3c5250e7432","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"674af2d277b66ecf2e49e1059638abd58db089df095b8b65d9e347782e4bb1e0","src/linux_android.rs":"39cb80999c8534145240a350976d261b8924436bf9a4563960c7bd8c2c83c773","src/macos.rs":"b692f2fcc2319a5195f47751d5bd7dd87c7c24a61d14fa4e3dbc992ae66212b7","src/openbsd.rs":"066b2dd395c190444a658bb0b52a052eabbd68ea5a534fb729c7e5373abc0a6a","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"9c7004446fabe5a7a21c73d5a65d7e2115b5bd1d1dbb735c984cab3dba239785","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"9fd636b23121a86630f0c7891a310444f5b1bb29b0013290e130b79ed1e1f79e","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"02b3a75613dc80444847675ecfea59f390c2597ce1d3334612a8dba71f6082de","src/windows.rs":"e3c8f033d5d2a6b8abc5c92b005232f5aca8ce941bd94964a0f58f2436af9990","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"} \ No newline at end of file diff --git a/third_party/rust/getrandom/CHANGELOG.md b/third_party/rust/getrandom/CHANGELOG.md index b25704947a03..4ab267ae06cd 100644 --- a/third_party/rust/getrandom/CHANGELOG.md +++ b/third_party/rust/getrandom/CHANGELOG.md @@ -4,21 +4,6 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [0.2.7] - 2022-06-14 -### Changed -- Update `wasi` dependency to `0.11` [#253] - -### Fixed -- Use `AtomicPtr` instead of `AtomicUsize` for Strict Provenance compatibility. [#263] - -### Documentation -- Add comments explaining use of fallback mechanisms [#257] [#260] - -[#263]: https://github.com/rust-random/getrandom/pull/263 -[#260]: https://github.com/rust-random/getrandom/pull/260 -[#253]: https://github.com/rust-random/getrandom/pull/253 -[#257]: https://github.com/rust-random/getrandom/pull/257 - ## [0.2.6] - 2022-03-28 ### Added - Nintendo 3DS (`armv6k-nintendo-3ds`) support [#248] @@ -306,8 +291,7 @@ Publish initial implementation. ## [0.0.0] - 2019-01-19 Publish an empty template library. -[0.2.7]: https://github.com/rust-random/getrandom/compare/v0.2.6...v0.2.7 -[0.2.6]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 +[0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 [0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.4...v0.2.5 [0.2.4]: https://github.com/rust-random/getrandom/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/rust-random/getrandom/compare/v0.2.2...v0.2.3 diff --git a/third_party/rust/getrandom/Cargo.toml b/third_party/rust/getrandom/Cargo.toml index 9b9c0880abb8..0a664244e753 100644 --- a/third_party/rust/getrandom/Cargo.toml +++ b/third_party/rust/getrandom/Cargo.toml @@ -12,29 +12,17 @@ [package] edition = "2018" name = "getrandom" -version = "0.2.7" +version = "0.2.6" authors = ["The Rand Project Developers"] exclude = [".*"] description = "A small cross-platform library for retrieving random data from system source" documentation = "https://docs.rs/getrandom" -readme = "README.md" -categories = [ - "os", - "no-std", -] +categories = ["os", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-random/getrandom" - [package.metadata.docs.rs] -features = [ - "std", - "custom", -] -rustdoc-args = [ - "--cfg", - "docsrs", -] - +features = ["std", "custom"] +rustdoc-args = ["--cfg", "docsrs"] [dependencies.cfg-if] version = "1" @@ -49,20 +37,11 @@ package = "rustc-std-workspace-core" [features] custom = [] -js = [ - "wasm-bindgen", - "js-sys", -] +js = ["wasm-bindgen", "js-sys"] rdrand = [] -rustc-dep-of-std = [ - "compiler_builtins", - "core", - "libc/rustc-dep-of-std", - "wasi/rustc-dep-of-std", -] +rustc-dep-of-std = ["compiler_builtins", "core", "libc/rustc-dep-of-std", "wasi/rustc-dep-of-std"] std = [] test-in-browser = [] - [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dependencies.js-sys] version = "0.3" optional = true @@ -71,13 +50,10 @@ optional = true version = "0.2.62" optional = true default-features = false - [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dev-dependencies.wasm-bindgen-test] version = "0.3.18" - [target."cfg(target_os = \"wasi\")".dependencies.wasi] -version = "0.11" - +version = "0.10" [target."cfg(unix)".dependencies.libc] version = "0.2.120" default-features = false diff --git a/third_party/rust/getrandom/src/bsd_arandom.rs b/third_party/rust/getrandom/src/bsd_arandom.rs index d44121254111..f26f2609c36b 100644 --- a/third_party/rust/getrandom/src/bsd_arandom.rs +++ b/third_party/rust/getrandom/src/bsd_arandom.rs @@ -31,7 +31,6 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { } pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0 #[cfg(target_os = "freebsd")] { use crate::util_libc::Weak; diff --git a/third_party/rust/getrandom/src/dragonfly.rs b/third_party/rust/getrandom/src/dragonfly.rs index 8daaa40489cf..f27e906908e9 100644 --- a/third_party/rust/getrandom/src/dragonfly.rs +++ b/third_party/rust/getrandom/src/dragonfly.rs @@ -17,7 +17,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; - // getrandom(2) was introduced in DragonflyBSD 5.7 if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); diff --git a/third_party/rust/getrandom/src/error.rs b/third_party/rust/getrandom/src/error.rs index b5ab2bb18370..6615753768aa 100644 --- a/third_party/rust/getrandom/src/error.rs +++ b/third_party/rust/getrandom/src/error.rs @@ -109,6 +109,10 @@ cfg_if! { let idx = buf.iter().position(|&b| b == 0).unwrap_or(n); core::str::from_utf8(&buf[..idx]).ok() } + } else if #[cfg(target_os = "wasi")] { + fn os_err(errno: i32, _buf: &mut [u8]) -> Option { + wasi::Error::from_raw_error(errno as _) + } } else { fn os_err(_errno: i32, _buf: &mut [u8]) -> Option<&str> { None diff --git a/third_party/rust/getrandom/src/lib.rs b/third_party/rust/getrandom/src/lib.rs index c62056e55613..888b9a51057a 100644 --- a/third_party/rust/getrandom/src/lib.rs +++ b/third_party/rust/getrandom/src/lib.rs @@ -149,7 +149,7 @@ #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/getrandom/0.2.7" + html_root_url = "https://docs.rs/getrandom/0.2.6" )] #![no_std] #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)] diff --git a/third_party/rust/getrandom/src/linux_android.rs b/third_party/rust/getrandom/src/linux_android.rs index 4270b67c65df..5508fdd06ab3 100644 --- a/third_party/rust/getrandom/src/linux_android.rs +++ b/third_party/rust/getrandom/src/linux_android.rs @@ -14,7 +14,6 @@ use crate::{ }; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - // getrandom(2) was introduced in Linux 3.17 static HAS_GETRANDOM: LazyBool = LazyBool::new(); if HAS_GETRANDOM.unsync_init(is_getrandom_available) { sys_fill_exact(dest, |buf| unsafe { diff --git a/third_party/rust/getrandom/src/macos.rs b/third_party/rust/getrandom/src/macos.rs index 671a053bffc6..585a35abd074 100644 --- a/third_party/rust/getrandom/src/macos.rs +++ b/third_party/rust/getrandom/src/macos.rs @@ -17,7 +17,6 @@ use core::mem; type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - // getentropy(2) was added in 10.12, Rust supports 10.7+ static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") }; if let Some(fptr) = GETENTROPY.ptr() { let func: GetEntropyFn = unsafe { mem::transmute(fptr) }; diff --git a/third_party/rust/getrandom/src/openbsd.rs b/third_party/rust/getrandom/src/openbsd.rs index 41371736f119..c8d28b3d8882 100644 --- a/third_party/rust/getrandom/src/openbsd.rs +++ b/third_party/rust/getrandom/src/openbsd.rs @@ -10,7 +10,6 @@ use crate::{util_libc::last_os_error, Error}; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - // getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally. for chunk in dest.chunks_mut(256) { let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) }; if ret == -1 { diff --git a/third_party/rust/getrandom/src/solaris_illumos.rs b/third_party/rust/getrandom/src/solaris_illumos.rs index cf3067d6d80c..2d1b767bb0c2 100644 --- a/third_party/rust/getrandom/src/solaris_illumos.rs +++ b/third_party/rust/getrandom/src/solaris_illumos.rs @@ -30,7 +30,6 @@ type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - // getrandom(2) was introduced in Solaris 11.3 for Illumos in 2015. static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { mem::transmute(fptr) }; diff --git a/third_party/rust/getrandom/src/util_libc.rs b/third_party/rust/getrandom/src/util_libc.rs index d057071a7468..6df1cd7da80a 100644 --- a/third_party/rust/getrandom/src/util_libc.rs +++ b/third_party/rust/getrandom/src/util_libc.rs @@ -6,13 +6,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] -use crate::Error; -use core::{ - num::NonZeroU32, - ptr::NonNull, - sync::atomic::{fence, AtomicPtr, Ordering}, -}; -use libc::c_void; +use crate::{util::LazyUsize, Error}; +use core::{num::NonZeroU32, ptr::NonNull}; cfg_if! { if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] { @@ -81,57 +76,29 @@ pub fn sys_fill_exact( // A "weak" binding to a C function that may or may not be present at runtime. // Used for supporting newer OS features while still building on older systems. -// Based off of the DlsymWeak struct in libstd: -// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84 -// except that the caller must manually cast self.ptr() to a function pointer. +// F must be a function pointer of type `unsafe extern "C" fn`. Based off of the +// weak! macro in libstd. pub struct Weak { name: &'static str, - addr: AtomicPtr, + addr: LazyUsize, } impl Weak { - // A non-null pointer value which indicates we are uninitialized. This - // constant should ideally not be a valid address of a function pointer. - // However, if by chance libc::dlsym does return UNINIT, there will not - // be undefined behavior. libc::dlsym will just be called each time ptr() - // is called. This would be inefficient, but correct. - // TODO: Replace with core::ptr::invalid_mut(1) when that is stable. - const UNINIT: *mut c_void = 1 as *mut c_void; - // Construct a binding to a C function with a given name. This function is // unsafe because `name` _must_ be null terminated. pub const unsafe fn new(name: &'static str) -> Self { Self { name, - addr: AtomicPtr::new(Self::UNINIT), + addr: LazyUsize::new(), } } - // Return the address of a function if present at runtime. Otherwise, - // return None. Multiple callers can call ptr() concurrently. It will - // always return _some_ value returned by libc::dlsym. However, the - // dlsym function may be called multiple times. - pub fn ptr(&self) -> Option> { - // Despite having only a single atomic variable (self.addr), we still - // cannot always use Ordering::Relaxed, as we need to make sure a - // successful call to dlsym() is "ordered before" any data read through - // the returned pointer (which occurs when the function is called). - // Our implementation mirrors that of the one in libstd, meaning that - // the use of non-Relaxed operations is probably unnecessary. - match self.addr.load(Ordering::Relaxed) { - Self::UNINIT => { - let symbol = self.name.as_ptr() as *const _; - let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) }; - // Synchronizes with the Acquire fence below - self.addr.store(addr, Ordering::Release); - NonNull::new(addr) - } - addr => { - let func = NonNull::new(addr)?; - fence(Ordering::Acquire); - Some(func) - } - } + // Return a function pointer if present at runtime. Otherwise, return null. + pub fn ptr(&self) -> Option> { + let addr = self.addr.unsync_init(|| unsafe { + libc::dlsym(libc::RTLD_DEFAULT, self.name.as_ptr() as *const _) as usize + }); + NonNull::new(addr as *mut _) } } diff --git a/third_party/rust/getrandom/src/wasi.rs b/third_party/rust/getrandom/src/wasi.rs index c5121824a7ef..2d413e020cd8 100644 --- a/third_party/rust/getrandom/src/wasi.rs +++ b/third_party/rust/getrandom/src/wasi.rs @@ -9,11 +9,15 @@ //! Implementation for WASI use crate::Error; use core::num::NonZeroU32; -use wasi::wasi_snapshot_preview1::random_get; +use wasi::random_get; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - match unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) } { - 0 => Ok(()), - err => Err(unsafe { NonZeroU32::new_unchecked(err as u32) }.into()), + unsafe { + random_get(dest.as_mut_ptr(), dest.len()).map_err(|e: wasi::Error| { + // convert wasi's Error into getrandom's NonZeroU32 error + // SAFETY: `wasi::Error` is `NonZeroU16` internally, so `e.raw_error()` + // will never return 0 + NonZeroU32::new_unchecked(e.raw_error() as u32).into() + }) } } diff --git a/third_party/rust/getrandom/src/windows.rs b/third_party/rust/getrandom/src/windows.rs index 41dc37a5c525..643badd07caa 100644 --- a/third_party/rust/getrandom/src/windows.rs +++ b/third_party/rust/getrandom/src/windows.rs @@ -24,7 +24,6 @@ extern "system" { pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { // Prevent overflow of u32 for chunk in dest.chunks_mut(u32::max_value() as usize) { - // BCryptGenRandom was introduced in Windows Vista let ret = unsafe { BCryptGenRandom( ptr::null_mut(), diff --git a/third_party/rust/wasi/.cargo-checksum.json b/third_party/rust/wasi/.cargo-checksum.json index a13fe2be5836..534dc6e20555 100644 --- a/third_party/rust/wasi/.cargo-checksum.json +++ b/third_party/rust/wasi/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CODE_OF_CONDUCT.md":"a13aaaf393818bd91207c618724d3fb74944ca5161201822a84af951bcf655ef","CONTRIBUTING.md":"2c908a3e263dc35dfed131c02ff907cd72fafb2c2096e4ba9b1e0cbb7a1b76df","Cargo.toml":"7a38e6f90e220716b5b3f82c0a187dfef180db8d1d262250325a655d1b9888e6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-Apache-2.0_WITH_LLVM-exception":"268872b9816f90fd8e85db5a28d33f8150ebb8dd016653fb39ef1f94f2686bc5","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","ORG_CODE_OF_CONDUCT.md":"a62b69bf86e605ee1bcbb2f0a12ba79e4cebb6983a7b6491949750aecc4f2178","README.md":"c021f687a5a61d9c308581401e7aa4454585a30c418abdd02e3a1ef71daa035f","SECURITY.md":"4d75afb09dd28eb5982e3a1f768ee398d90204669ceef3240a16b31dcf04148a","src/lib.rs":"040651dd678b7788d7cc7a8fdc5f50f664d46bd18976bf638bcb4c827a1793d7","src/lib_generated.rs":"130977e4eaac5e9623caba3d5911616051c8b2cee926333213271a25b733a5df"},"package":"9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"} \ No newline at end of file +{"files":{"CODE_OF_CONDUCT.md":"a13aaaf393818bd91207c618724d3fb74944ca5161201822a84af951bcf655ef","CONTRIBUTING.md":"2c908a3e263dc35dfed131c02ff907cd72fafb2c2096e4ba9b1e0cbb7a1b76df","Cargo.toml":"0507b220e56fe90becc31c95576b3c42f05b6453659af34e43eaab219274a14b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-Apache-2.0_WITH_LLVM-exception":"268872b9816f90fd8e85db5a28d33f8150ebb8dd016653fb39ef1f94f2686bc5","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","ORG_CODE_OF_CONDUCT.md":"a62b69bf86e605ee1bcbb2f0a12ba79e4cebb6983a7b6491949750aecc4f2178","README.md":"9412b3834687f28f0fae01a6e45b1309733ac92dcf04ef3ef36a823e76a6fed2","SECURITY.md":"4d75afb09dd28eb5982e3a1f768ee398d90204669ceef3240a16b31dcf04148a","src/error.rs":"96818880fab83125079842e35aacb49333ac66699e223f896699e4fdb88b99e8","src/lib.rs":"ce2e7ee6a6e4d5900f3835568b168afc70870d601b2bb94f1a6b9ddd2f046c3a","src/lib_generated.rs":"352b56bdb0f87dc18592a2241b312710c8326a415c2b3e3e7af26a8e36c2d303"},"package":"1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"} \ No newline at end of file diff --git a/third_party/rust/wasi/Cargo.toml b/third_party/rust/wasi/Cargo.toml index c41e35e9ee88..00fe5b3cd421 100644 --- a/third_party/rust/wasi/Cargo.toml +++ b/third_party/rust/wasi/Cargo.toml @@ -3,16 +3,17 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. +# to registry (e.g., crates.io) dependencies # -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) [package] edition = "2018" name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.10.0+wasi-snapshot-preview1" authors = ["The Cranelift Project Developers"] description = "Experimental WASI API bindings for Rust" documentation = "https://docs.rs/wasi" diff --git a/third_party/rust/wasi/README.md b/third_party/rust/wasi/README.md index 801f56a4e023..e92f50e3f5ca 100644 --- a/third_party/rust/wasi/README.md +++ b/third_party/rust/wasi/README.md @@ -64,24 +64,6 @@ $ cargo wasi run Hello, World! ``` -# Development - -The bulk of the `wasi` crate is generated by the `witx-bindgen` tool, which lives at -`crates/witx-bindgen` and is part of the cargo workspace. - -The `src/lib_generated.rs` file can be re-generated with the following -command: - -``` -cargo run -p witx-bindgen -- crates/witx-bindgen/WASI/phases/snapshot/witx/wasi_snapshot_preview1.witx > src/lib_generated.rs -``` - -Note that this uses the WASI standard repository as a submodule. If you do not -have this submodule present in your source tree, run: -``` -git submodule update --init -``` - # License This project is licensed under the Apache 2.0 license with the LLVM exception. diff --git a/third_party/rust/wasi/src/error.rs b/third_party/rust/wasi/src/error.rs new file mode 100644 index 000000000000..2f2aaf4b90dd --- /dev/null +++ b/third_party/rust/wasi/src/error.rs @@ -0,0 +1,51 @@ +use super::Errno; +use core::fmt; +use core::num::NonZeroU16; + +/// A raw error returned by wasi APIs, internally containing a 16-bit error +/// code. +#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] +pub struct Error { + code: NonZeroU16, +} + +impl Error { + /// Constructs a new error from a raw error code, returning `None` if the + /// error code is zero (which means success). + pub fn from_raw_error(error: Errno) -> Option { + Some(Error { + code: NonZeroU16::new(error)?, + }) + } + + /// Returns the raw error code that this error represents. + pub fn raw_error(&self) -> u16 { + self.code.get() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} (error {})", + super::strerror(self.code.get()), + self.code + )?; + Ok(()) + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Error") + .field("code", &self.code) + .field("message", &super::strerror(self.code.get())) + .finish() + } +} + +#[cfg(feature = "std")] +extern crate std; +#[cfg(feature = "std")] +impl std::error::Error for Error {} diff --git a/third_party/rust/wasi/src/lib.rs b/third_party/rust/wasi/src/lib.rs index 0df207b60e5f..51f488907f82 100644 --- a/third_party/rust/wasi/src/lib.rs +++ b/third_party/rust/wasi/src/lib.rs @@ -31,6 +31,7 @@ #![no_std] +mod error; mod lib_generated; pub use lib_generated::*; diff --git a/third_party/rust/wasi/src/lib_generated.rs b/third_party/rust/wasi/src/lib_generated.rs index 641528178f6c..422794153d86 100644 --- a/third_party/rust/wasi/src/lib_generated.rs +++ b/third_party/rust/wasi/src/lib_generated.rs @@ -1,490 +1,335 @@ // This file is automatically generated, DO NOT EDIT // -// To regenerate this file run the `crates/witx-bindgen` command +// To regenerate this file run the `crates/generate-raw` command -use core::fmt; use core::mem::MaybeUninit; + +pub use crate::error::Error; +pub type Result = core::result::Result; pub type Size = usize; pub type Filesize = u64; pub type Timestamp = u64; -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Clockid(u32); +pub type Clockid = u32; /// The clock measuring real time. Time value zero corresponds with /// 1970-01-01T00:00:00Z. -pub const CLOCKID_REALTIME: Clockid = Clockid(0); +pub const CLOCKID_REALTIME: Clockid = 0; /// The store-wide monotonic clock, which is defined as a clock measuring /// real time, whose value cannot be adjusted and which cannot have negative /// clock jumps. The epoch of this clock is undefined. The absolute time /// value of this clock therefore has no meaning. -pub const CLOCKID_MONOTONIC: Clockid = Clockid(1); +pub const CLOCKID_MONOTONIC: Clockid = 1; /// The CPU-time clock associated with the current process. -pub const CLOCKID_PROCESS_CPUTIME_ID: Clockid = Clockid(2); +pub const CLOCKID_PROCESS_CPUTIME_ID: Clockid = 2; /// The CPU-time clock associated with the current thread. -pub const CLOCKID_THREAD_CPUTIME_ID: Clockid = Clockid(3); -impl Clockid { - pub const fn raw(&self) -> u32 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "REALTIME", - 1 => "MONOTONIC", - 2 => "PROCESS_CPUTIME_ID", - 3 => "THREAD_CPUTIME_ID", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 { - 0 => { - "The clock measuring real time. Time value zero corresponds with -1970-01-01T00:00:00Z." - } - 1 => { - "The store-wide monotonic clock, which is defined as a clock measuring -real time, whose value cannot be adjusted and which cannot have negative -clock jumps. The epoch of this clock is undefined. The absolute time -value of this clock therefore has no meaning." - } - 2 => "The CPU-time clock associated with the current process.", - 3 => "The CPU-time clock associated with the current thread.", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } -} -impl fmt::Debug for Clockid { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Clockid") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Errno(u16); +pub const CLOCKID_THREAD_CPUTIME_ID: Clockid = 3; +pub type Errno = u16; /// No error occurred. System call completed successfully. -pub const ERRNO_SUCCESS: Errno = Errno(0); +pub const ERRNO_SUCCESS: Errno = 0; /// Argument list too long. -pub const ERRNO_2BIG: Errno = Errno(1); +pub const ERRNO_2BIG: Errno = 1; /// Permission denied. -pub const ERRNO_ACCES: Errno = Errno(2); +pub const ERRNO_ACCES: Errno = 2; /// Address in use. -pub const ERRNO_ADDRINUSE: Errno = Errno(3); +pub const ERRNO_ADDRINUSE: Errno = 3; /// Address not available. -pub const ERRNO_ADDRNOTAVAIL: Errno = Errno(4); +pub const ERRNO_ADDRNOTAVAIL: Errno = 4; /// Address family not supported. -pub const ERRNO_AFNOSUPPORT: Errno = Errno(5); +pub const ERRNO_AFNOSUPPORT: Errno = 5; /// Resource unavailable, or operation would block. -pub const ERRNO_AGAIN: Errno = Errno(6); +pub const ERRNO_AGAIN: Errno = 6; /// Connection already in progress. -pub const ERRNO_ALREADY: Errno = Errno(7); +pub const ERRNO_ALREADY: Errno = 7; /// Bad file descriptor. -pub const ERRNO_BADF: Errno = Errno(8); +pub const ERRNO_BADF: Errno = 8; /// Bad message. -pub const ERRNO_BADMSG: Errno = Errno(9); +pub const ERRNO_BADMSG: Errno = 9; /// Device or resource busy. -pub const ERRNO_BUSY: Errno = Errno(10); +pub const ERRNO_BUSY: Errno = 10; /// Operation canceled. -pub const ERRNO_CANCELED: Errno = Errno(11); +pub const ERRNO_CANCELED: Errno = 11; /// No child processes. -pub const ERRNO_CHILD: Errno = Errno(12); +pub const ERRNO_CHILD: Errno = 12; /// Connection aborted. -pub const ERRNO_CONNABORTED: Errno = Errno(13); +pub const ERRNO_CONNABORTED: Errno = 13; /// Connection refused. -pub const ERRNO_CONNREFUSED: Errno = Errno(14); +pub const ERRNO_CONNREFUSED: Errno = 14; /// Connection reset. -pub const ERRNO_CONNRESET: Errno = Errno(15); +pub const ERRNO_CONNRESET: Errno = 15; /// Resource deadlock would occur. -pub const ERRNO_DEADLK: Errno = Errno(16); +pub const ERRNO_DEADLK: Errno = 16; /// Destination address required. -pub const ERRNO_DESTADDRREQ: Errno = Errno(17); +pub const ERRNO_DESTADDRREQ: Errno = 17; /// Mathematics argument out of domain of function. -pub const ERRNO_DOM: Errno = Errno(18); +pub const ERRNO_DOM: Errno = 18; /// Reserved. -pub const ERRNO_DQUOT: Errno = Errno(19); +pub const ERRNO_DQUOT: Errno = 19; /// File exists. -pub const ERRNO_EXIST: Errno = Errno(20); +pub const ERRNO_EXIST: Errno = 20; /// Bad address. -pub const ERRNO_FAULT: Errno = Errno(21); +pub const ERRNO_FAULT: Errno = 21; /// File too large. -pub const ERRNO_FBIG: Errno = Errno(22); +pub const ERRNO_FBIG: Errno = 22; /// Host is unreachable. -pub const ERRNO_HOSTUNREACH: Errno = Errno(23); +pub const ERRNO_HOSTUNREACH: Errno = 23; /// Identifier removed. -pub const ERRNO_IDRM: Errno = Errno(24); +pub const ERRNO_IDRM: Errno = 24; /// Illegal byte sequence. -pub const ERRNO_ILSEQ: Errno = Errno(25); +pub const ERRNO_ILSEQ: Errno = 25; /// Operation in progress. -pub const ERRNO_INPROGRESS: Errno = Errno(26); +pub const ERRNO_INPROGRESS: Errno = 26; /// Interrupted function. -pub const ERRNO_INTR: Errno = Errno(27); +pub const ERRNO_INTR: Errno = 27; /// Invalid argument. -pub const ERRNO_INVAL: Errno = Errno(28); +pub const ERRNO_INVAL: Errno = 28; /// I/O error. -pub const ERRNO_IO: Errno = Errno(29); +pub const ERRNO_IO: Errno = 29; /// Socket is connected. -pub const ERRNO_ISCONN: Errno = Errno(30); +pub const ERRNO_ISCONN: Errno = 30; /// Is a directory. -pub const ERRNO_ISDIR: Errno = Errno(31); +pub const ERRNO_ISDIR: Errno = 31; /// Too many levels of symbolic links. -pub const ERRNO_LOOP: Errno = Errno(32); +pub const ERRNO_LOOP: Errno = 32; /// File descriptor value too large. -pub const ERRNO_MFILE: Errno = Errno(33); +pub const ERRNO_MFILE: Errno = 33; /// Too many links. -pub const ERRNO_MLINK: Errno = Errno(34); +pub const ERRNO_MLINK: Errno = 34; /// Message too large. -pub const ERRNO_MSGSIZE: Errno = Errno(35); +pub const ERRNO_MSGSIZE: Errno = 35; /// Reserved. -pub const ERRNO_MULTIHOP: Errno = Errno(36); +pub const ERRNO_MULTIHOP: Errno = 36; /// Filename too long. -pub const ERRNO_NAMETOOLONG: Errno = Errno(37); +pub const ERRNO_NAMETOOLONG: Errno = 37; /// Network is down. -pub const ERRNO_NETDOWN: Errno = Errno(38); +pub const ERRNO_NETDOWN: Errno = 38; /// Connection aborted by network. -pub const ERRNO_NETRESET: Errno = Errno(39); +pub const ERRNO_NETRESET: Errno = 39; /// Network unreachable. -pub const ERRNO_NETUNREACH: Errno = Errno(40); +pub const ERRNO_NETUNREACH: Errno = 40; /// Too many files open in system. -pub const ERRNO_NFILE: Errno = Errno(41); +pub const ERRNO_NFILE: Errno = 41; /// No buffer space available. -pub const ERRNO_NOBUFS: Errno = Errno(42); +pub const ERRNO_NOBUFS: Errno = 42; /// No such device. -pub const ERRNO_NODEV: Errno = Errno(43); +pub const ERRNO_NODEV: Errno = 43; /// No such file or directory. -pub const ERRNO_NOENT: Errno = Errno(44); +pub const ERRNO_NOENT: Errno = 44; /// Executable file format error. -pub const ERRNO_NOEXEC: Errno = Errno(45); +pub const ERRNO_NOEXEC: Errno = 45; /// No locks available. -pub const ERRNO_NOLCK: Errno = Errno(46); +pub const ERRNO_NOLCK: Errno = 46; /// Reserved. -pub const ERRNO_NOLINK: Errno = Errno(47); +pub const ERRNO_NOLINK: Errno = 47; /// Not enough space. -pub const ERRNO_NOMEM: Errno = Errno(48); +pub const ERRNO_NOMEM: Errno = 48; /// No message of the desired type. -pub const ERRNO_NOMSG: Errno = Errno(49); +pub const ERRNO_NOMSG: Errno = 49; /// Protocol not available. -pub const ERRNO_NOPROTOOPT: Errno = Errno(50); +pub const ERRNO_NOPROTOOPT: Errno = 50; /// No space left on device. -pub const ERRNO_NOSPC: Errno = Errno(51); +pub const ERRNO_NOSPC: Errno = 51; /// Function not supported. -pub const ERRNO_NOSYS: Errno = Errno(52); +pub const ERRNO_NOSYS: Errno = 52; /// The socket is not connected. -pub const ERRNO_NOTCONN: Errno = Errno(53); +pub const ERRNO_NOTCONN: Errno = 53; /// Not a directory or a symbolic link to a directory. -pub const ERRNO_NOTDIR: Errno = Errno(54); +pub const ERRNO_NOTDIR: Errno = 54; /// Directory not empty. -pub const ERRNO_NOTEMPTY: Errno = Errno(55); +pub const ERRNO_NOTEMPTY: Errno = 55; /// State not recoverable. -pub const ERRNO_NOTRECOVERABLE: Errno = Errno(56); +pub const ERRNO_NOTRECOVERABLE: Errno = 56; /// Not a socket. -pub const ERRNO_NOTSOCK: Errno = Errno(57); +pub const ERRNO_NOTSOCK: Errno = 57; /// Not supported, or operation not supported on socket. -pub const ERRNO_NOTSUP: Errno = Errno(58); +pub const ERRNO_NOTSUP: Errno = 58; /// Inappropriate I/O control operation. -pub const ERRNO_NOTTY: Errno = Errno(59); +pub const ERRNO_NOTTY: Errno = 59; /// No such device or address. -pub const ERRNO_NXIO: Errno = Errno(60); +pub const ERRNO_NXIO: Errno = 60; /// Value too large to be stored in data type. -pub const ERRNO_OVERFLOW: Errno = Errno(61); +pub const ERRNO_OVERFLOW: Errno = 61; /// Previous owner died. -pub const ERRNO_OWNERDEAD: Errno = Errno(62); +pub const ERRNO_OWNERDEAD: Errno = 62; /// Operation not permitted. -pub const ERRNO_PERM: Errno = Errno(63); +pub const ERRNO_PERM: Errno = 63; /// Broken pipe. -pub const ERRNO_PIPE: Errno = Errno(64); +pub const ERRNO_PIPE: Errno = 64; /// Protocol error. -pub const ERRNO_PROTO: Errno = Errno(65); +pub const ERRNO_PROTO: Errno = 65; /// Protocol not supported. -pub const ERRNO_PROTONOSUPPORT: Errno = Errno(66); +pub const ERRNO_PROTONOSUPPORT: Errno = 66; /// Protocol wrong type for socket. -pub const ERRNO_PROTOTYPE: Errno = Errno(67); +pub const ERRNO_PROTOTYPE: Errno = 67; /// Result too large. -pub const ERRNO_RANGE: Errno = Errno(68); +pub const ERRNO_RANGE: Errno = 68; /// Read-only file system. -pub const ERRNO_ROFS: Errno = Errno(69); +pub const ERRNO_ROFS: Errno = 69; /// Invalid seek. -pub const ERRNO_SPIPE: Errno = Errno(70); +pub const ERRNO_SPIPE: Errno = 70; /// No such process. -pub const ERRNO_SRCH: Errno = Errno(71); +pub const ERRNO_SRCH: Errno = 71; /// Reserved. -pub const ERRNO_STALE: Errno = Errno(72); +pub const ERRNO_STALE: Errno = 72; /// Connection timed out. -pub const ERRNO_TIMEDOUT: Errno = Errno(73); +pub const ERRNO_TIMEDOUT: Errno = 73; /// Text file busy. -pub const ERRNO_TXTBSY: Errno = Errno(74); +pub const ERRNO_TXTBSY: Errno = 74; /// Cross-device link. -pub const ERRNO_XDEV: Errno = Errno(75); +pub const ERRNO_XDEV: Errno = 75; /// Extension: Capabilities insufficient. -pub const ERRNO_NOTCAPABLE: Errno = Errno(76); -impl Errno { - pub const fn raw(&self) -> u16 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "SUCCESS", - 1 => "2BIG", - 2 => "ACCES", - 3 => "ADDRINUSE", - 4 => "ADDRNOTAVAIL", - 5 => "AFNOSUPPORT", - 6 => "AGAIN", - 7 => "ALREADY", - 8 => "BADF", - 9 => "BADMSG", - 10 => "BUSY", - 11 => "CANCELED", - 12 => "CHILD", - 13 => "CONNABORTED", - 14 => "CONNREFUSED", - 15 => "CONNRESET", - 16 => "DEADLK", - 17 => "DESTADDRREQ", - 18 => "DOM", - 19 => "DQUOT", - 20 => "EXIST", - 21 => "FAULT", - 22 => "FBIG", - 23 => "HOSTUNREACH", - 24 => "IDRM", - 25 => "ILSEQ", - 26 => "INPROGRESS", - 27 => "INTR", - 28 => "INVAL", - 29 => "IO", - 30 => "ISCONN", - 31 => "ISDIR", - 32 => "LOOP", - 33 => "MFILE", - 34 => "MLINK", - 35 => "MSGSIZE", - 36 => "MULTIHOP", - 37 => "NAMETOOLONG", - 38 => "NETDOWN", - 39 => "NETRESET", - 40 => "NETUNREACH", - 41 => "NFILE", - 42 => "NOBUFS", - 43 => "NODEV", - 44 => "NOENT", - 45 => "NOEXEC", - 46 => "NOLCK", - 47 => "NOLINK", - 48 => "NOMEM", - 49 => "NOMSG", - 50 => "NOPROTOOPT", - 51 => "NOSPC", - 52 => "NOSYS", - 53 => "NOTCONN", - 54 => "NOTDIR", - 55 => "NOTEMPTY", - 56 => "NOTRECOVERABLE", - 57 => "NOTSOCK", - 58 => "NOTSUP", - 59 => "NOTTY", - 60 => "NXIO", - 61 => "OVERFLOW", - 62 => "OWNERDEAD", - 63 => "PERM", - 64 => "PIPE", - 65 => "PROTO", - 66 => "PROTONOSUPPORT", - 67 => "PROTOTYPE", - 68 => "RANGE", - 69 => "ROFS", - 70 => "SPIPE", - 71 => "SRCH", - 72 => "STALE", - 73 => "TIMEDOUT", - 74 => "TXTBSY", - 75 => "XDEV", - 76 => "NOTCAPABLE", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 { - 0 => "No error occurred. System call completed successfully.", - 1 => "Argument list too long.", - 2 => "Permission denied.", - 3 => "Address in use.", - 4 => "Address not available.", - 5 => "Address family not supported.", - 6 => "Resource unavailable, or operation would block.", - 7 => "Connection already in progress.", - 8 => "Bad file descriptor.", - 9 => "Bad message.", - 10 => "Device or resource busy.", - 11 => "Operation canceled.", - 12 => "No child processes.", - 13 => "Connection aborted.", - 14 => "Connection refused.", - 15 => "Connection reset.", - 16 => "Resource deadlock would occur.", - 17 => "Destination address required.", - 18 => "Mathematics argument out of domain of function.", - 19 => "Reserved.", - 20 => "File exists.", - 21 => "Bad address.", - 22 => "File too large.", - 23 => "Host is unreachable.", - 24 => "Identifier removed.", - 25 => "Illegal byte sequence.", - 26 => "Operation in progress.", - 27 => "Interrupted function.", - 28 => "Invalid argument.", - 29 => "I/O error.", - 30 => "Socket is connected.", - 31 => "Is a directory.", - 32 => "Too many levels of symbolic links.", - 33 => "File descriptor value too large.", - 34 => "Too many links.", - 35 => "Message too large.", - 36 => "Reserved.", - 37 => "Filename too long.", - 38 => "Network is down.", - 39 => "Connection aborted by network.", - 40 => "Network unreachable.", - 41 => "Too many files open in system.", - 42 => "No buffer space available.", - 43 => "No such device.", - 44 => "No such file or directory.", - 45 => "Executable file format error.", - 46 => "No locks available.", - 47 => "Reserved.", - 48 => "Not enough space.", - 49 => "No message of the desired type.", - 50 => "Protocol not available.", - 51 => "No space left on device.", - 52 => "Function not supported.", - 53 => "The socket is not connected.", - 54 => "Not a directory or a symbolic link to a directory.", - 55 => "Directory not empty.", - 56 => "State not recoverable.", - 57 => "Not a socket.", - 58 => "Not supported, or operation not supported on socket.", - 59 => "Inappropriate I/O control operation.", - 60 => "No such device or address.", - 61 => "Value too large to be stored in data type.", - 62 => "Previous owner died.", - 63 => "Operation not permitted.", - 64 => "Broken pipe.", - 65 => "Protocol error.", - 66 => "Protocol not supported.", - 67 => "Protocol wrong type for socket.", - 68 => "Result too large.", - 69 => "Read-only file system.", - 70 => "Invalid seek.", - 71 => "No such process.", - 72 => "Reserved.", - 73 => "Connection timed out.", - 74 => "Text file busy.", - 75 => "Cross-device link.", - 76 => "Extension: Capabilities insufficient.", - _ => unsafe { core::hint::unreachable_unchecked() }, - } +pub const ERRNO_NOTCAPABLE: Errno = 76; +pub(crate) fn strerror(code: u16) -> &'static str { + match code { + ERRNO_SUCCESS => "No error occurred. System call completed successfully.", + ERRNO_2BIG => "Argument list too long.", + ERRNO_ACCES => "Permission denied.", + ERRNO_ADDRINUSE => "Address in use.", + ERRNO_ADDRNOTAVAIL => "Address not available.", + ERRNO_AFNOSUPPORT => "Address family not supported.", + ERRNO_AGAIN => "Resource unavailable, or operation would block.", + ERRNO_ALREADY => "Connection already in progress.", + ERRNO_BADF => "Bad file descriptor.", + ERRNO_BADMSG => "Bad message.", + ERRNO_BUSY => "Device or resource busy.", + ERRNO_CANCELED => "Operation canceled.", + ERRNO_CHILD => "No child processes.", + ERRNO_CONNABORTED => "Connection aborted.", + ERRNO_CONNREFUSED => "Connection refused.", + ERRNO_CONNRESET => "Connection reset.", + ERRNO_DEADLK => "Resource deadlock would occur.", + ERRNO_DESTADDRREQ => "Destination address required.", + ERRNO_DOM => "Mathematics argument out of domain of function.", + ERRNO_DQUOT => "Reserved.", + ERRNO_EXIST => "File exists.", + ERRNO_FAULT => "Bad address.", + ERRNO_FBIG => "File too large.", + ERRNO_HOSTUNREACH => "Host is unreachable.", + ERRNO_IDRM => "Identifier removed.", + ERRNO_ILSEQ => "Illegal byte sequence.", + ERRNO_INPROGRESS => "Operation in progress.", + ERRNO_INTR => "Interrupted function.", + ERRNO_INVAL => "Invalid argument.", + ERRNO_IO => "I/O error.", + ERRNO_ISCONN => "Socket is connected.", + ERRNO_ISDIR => "Is a directory.", + ERRNO_LOOP => "Too many levels of symbolic links.", + ERRNO_MFILE => "File descriptor value too large.", + ERRNO_MLINK => "Too many links.", + ERRNO_MSGSIZE => "Message too large.", + ERRNO_MULTIHOP => "Reserved.", + ERRNO_NAMETOOLONG => "Filename too long.", + ERRNO_NETDOWN => "Network is down.", + ERRNO_NETRESET => "Connection aborted by network.", + ERRNO_NETUNREACH => "Network unreachable.", + ERRNO_NFILE => "Too many files open in system.", + ERRNO_NOBUFS => "No buffer space available.", + ERRNO_NODEV => "No such device.", + ERRNO_NOENT => "No such file or directory.", + ERRNO_NOEXEC => "Executable file format error.", + ERRNO_NOLCK => "No locks available.", + ERRNO_NOLINK => "Reserved.", + ERRNO_NOMEM => "Not enough space.", + ERRNO_NOMSG => "No message of the desired type.", + ERRNO_NOPROTOOPT => "Protocol not available.", + ERRNO_NOSPC => "No space left on device.", + ERRNO_NOSYS => "Function not supported.", + ERRNO_NOTCONN => "The socket is not connected.", + ERRNO_NOTDIR => "Not a directory or a symbolic link to a directory.", + ERRNO_NOTEMPTY => "Directory not empty.", + ERRNO_NOTRECOVERABLE => "State not recoverable.", + ERRNO_NOTSOCK => "Not a socket.", + ERRNO_NOTSUP => "Not supported, or operation not supported on socket.", + ERRNO_NOTTY => "Inappropriate I/O control operation.", + ERRNO_NXIO => "No such device or address.", + ERRNO_OVERFLOW => "Value too large to be stored in data type.", + ERRNO_OWNERDEAD => "Previous owner died.", + ERRNO_PERM => "Operation not permitted.", + ERRNO_PIPE => "Broken pipe.", + ERRNO_PROTO => "Protocol error.", + ERRNO_PROTONOSUPPORT => "Protocol not supported.", + ERRNO_PROTOTYPE => "Protocol wrong type for socket.", + ERRNO_RANGE => "Result too large.", + ERRNO_ROFS => "Read-only file system.", + ERRNO_SPIPE => "Invalid seek.", + ERRNO_SRCH => "No such process.", + ERRNO_STALE => "Reserved.", + ERRNO_TIMEDOUT => "Connection timed out.", + ERRNO_TXTBSY => "Text file busy.", + ERRNO_XDEV => "Cross-device link.", + ERRNO_NOTCAPABLE => "Extension: Capabilities insufficient.", + _ => "Unknown error.", } } -impl fmt::Debug for Errno { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Errno") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} -impl fmt::Display for Errno { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} (error {})", self.name(), self.0) - } -} - -#[cfg(feature = "std")] -extern crate std; -#[cfg(feature = "std")] -impl std::error::Error for Errno {} - pub type Rights = u64; /// The right to invoke `fd_datasync`. /// If `path_open` is set, includes the right to invoke /// `path_open` with `fdflags::dsync`. -pub const RIGHTS_FD_DATASYNC: Rights = 1 << 0; +pub const RIGHTS_FD_DATASYNC: Rights = 0x1; /// The right to invoke `fd_read` and `sock_recv`. /// If `rights::fd_seek` is set, includes the right to invoke `fd_pread`. -pub const RIGHTS_FD_READ: Rights = 1 << 1; +pub const RIGHTS_FD_READ: Rights = 0x2; /// The right to invoke `fd_seek`. This flag implies `rights::fd_tell`. -pub const RIGHTS_FD_SEEK: Rights = 1 << 2; +pub const RIGHTS_FD_SEEK: Rights = 0x4; /// The right to invoke `fd_fdstat_set_flags`. -pub const RIGHTS_FD_FDSTAT_SET_FLAGS: Rights = 1 << 3; +pub const RIGHTS_FD_FDSTAT_SET_FLAGS: Rights = 0x8; /// The right to invoke `fd_sync`. /// If `path_open` is set, includes the right to invoke /// `path_open` with `fdflags::rsync` and `fdflags::dsync`. -pub const RIGHTS_FD_SYNC: Rights = 1 << 4; +pub const RIGHTS_FD_SYNC: Rights = 0x10; /// The right to invoke `fd_seek` in such a way that the file offset /// remains unaltered (i.e., `whence::cur` with offset zero), or to /// invoke `fd_tell`. -pub const RIGHTS_FD_TELL: Rights = 1 << 5; +pub const RIGHTS_FD_TELL: Rights = 0x20; /// The right to invoke `fd_write` and `sock_send`. /// If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`. -pub const RIGHTS_FD_WRITE: Rights = 1 << 6; +pub const RIGHTS_FD_WRITE: Rights = 0x40; /// The right to invoke `fd_advise`. -pub const RIGHTS_FD_ADVISE: Rights = 1 << 7; +pub const RIGHTS_FD_ADVISE: Rights = 0x80; /// The right to invoke `fd_allocate`. -pub const RIGHTS_FD_ALLOCATE: Rights = 1 << 8; +pub const RIGHTS_FD_ALLOCATE: Rights = 0x100; /// The right to invoke `path_create_directory`. -pub const RIGHTS_PATH_CREATE_DIRECTORY: Rights = 1 << 9; +pub const RIGHTS_PATH_CREATE_DIRECTORY: Rights = 0x200; /// If `path_open` is set, the right to invoke `path_open` with `oflags::creat`. -pub const RIGHTS_PATH_CREATE_FILE: Rights = 1 << 10; +pub const RIGHTS_PATH_CREATE_FILE: Rights = 0x400; /// The right to invoke `path_link` with the file descriptor as the /// source directory. -pub const RIGHTS_PATH_LINK_SOURCE: Rights = 1 << 11; +pub const RIGHTS_PATH_LINK_SOURCE: Rights = 0x800; /// The right to invoke `path_link` with the file descriptor as the /// target directory. -pub const RIGHTS_PATH_LINK_TARGET: Rights = 1 << 12; +pub const RIGHTS_PATH_LINK_TARGET: Rights = 0x1000; /// The right to invoke `path_open`. -pub const RIGHTS_PATH_OPEN: Rights = 1 << 13; +pub const RIGHTS_PATH_OPEN: Rights = 0x2000; /// The right to invoke `fd_readdir`. -pub const RIGHTS_FD_READDIR: Rights = 1 << 14; +pub const RIGHTS_FD_READDIR: Rights = 0x4000; /// The right to invoke `path_readlink`. -pub const RIGHTS_PATH_READLINK: Rights = 1 << 15; +pub const RIGHTS_PATH_READLINK: Rights = 0x8000; /// The right to invoke `path_rename` with the file descriptor as the source directory. -pub const RIGHTS_PATH_RENAME_SOURCE: Rights = 1 << 16; +pub const RIGHTS_PATH_RENAME_SOURCE: Rights = 0x10000; /// The right to invoke `path_rename` with the file descriptor as the target directory. -pub const RIGHTS_PATH_RENAME_TARGET: Rights = 1 << 17; +pub const RIGHTS_PATH_RENAME_TARGET: Rights = 0x20000; /// The right to invoke `path_filestat_get`. -pub const RIGHTS_PATH_FILESTAT_GET: Rights = 1 << 18; +pub const RIGHTS_PATH_FILESTAT_GET: Rights = 0x40000; /// The right to change a file's size (there is no `path_filestat_set_size`). /// If `path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`. -pub const RIGHTS_PATH_FILESTAT_SET_SIZE: Rights = 1 << 19; +pub const RIGHTS_PATH_FILESTAT_SET_SIZE: Rights = 0x80000; /// The right to invoke `path_filestat_set_times`. -pub const RIGHTS_PATH_FILESTAT_SET_TIMES: Rights = 1 << 20; +pub const RIGHTS_PATH_FILESTAT_SET_TIMES: Rights = 0x100000; /// The right to invoke `fd_filestat_get`. -pub const RIGHTS_FD_FILESTAT_GET: Rights = 1 << 21; +pub const RIGHTS_FD_FILESTAT_GET: Rights = 0x200000; /// The right to invoke `fd_filestat_set_size`. -pub const RIGHTS_FD_FILESTAT_SET_SIZE: Rights = 1 << 22; +pub const RIGHTS_FD_FILESTAT_SET_SIZE: Rights = 0x400000; /// The right to invoke `fd_filestat_set_times`. -pub const RIGHTS_FD_FILESTAT_SET_TIMES: Rights = 1 << 23; +pub const RIGHTS_FD_FILESTAT_SET_TIMES: Rights = 0x800000; /// The right to invoke `path_symlink`. -pub const RIGHTS_PATH_SYMLINK: Rights = 1 << 24; +pub const RIGHTS_PATH_SYMLINK: Rights = 0x1000000; /// The right to invoke `path_remove_directory`. -pub const RIGHTS_PATH_REMOVE_DIRECTORY: Rights = 1 << 25; +pub const RIGHTS_PATH_REMOVE_DIRECTORY: Rights = 0x2000000; /// The right to invoke `path_unlink_file`. -pub const RIGHTS_PATH_UNLINK_FILE: Rights = 1 << 26; +pub const RIGHTS_PATH_UNLINK_FILE: Rights = 0x4000000; /// If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`. /// If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`. -pub const RIGHTS_POLL_FD_READWRITE: Rights = 1 << 27; +pub const RIGHTS_POLL_FD_READWRITE: Rights = 0x8000000; /// The right to invoke `sock_shutdown`. -pub const RIGHTS_SOCK_SHUTDOWN: Rights = 1 << 28; -/// The right to invoke `sock_accept`. -pub const RIGHTS_SOCK_ACCEPT: Rights = 1 << 29; - +pub const RIGHTS_SOCK_SHUTDOWN: Rights = 0x10000000; pub type Fd = u32; #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -505,101 +350,33 @@ pub struct Ciovec { pub type IovecArray<'a> = &'a [Iovec]; pub type CiovecArray<'a> = &'a [Ciovec]; pub type Filedelta = i64; -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Whence(u8); +pub type Whence = u8; /// Seek relative to start-of-file. -pub const WHENCE_SET: Whence = Whence(0); +pub const WHENCE_SET: Whence = 0; /// Seek relative to current position. -pub const WHENCE_CUR: Whence = Whence(1); +pub const WHENCE_CUR: Whence = 1; /// Seek relative to end-of-file. -pub const WHENCE_END: Whence = Whence(2); -impl Whence { - pub const fn raw(&self) -> u8 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "SET", - 1 => "CUR", - 2 => "END", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 { - 0 => "Seek relative to start-of-file.", - 1 => "Seek relative to current position.", - 2 => "Seek relative to end-of-file.", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } -} -impl fmt::Debug for Whence { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Whence") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - +pub const WHENCE_END: Whence = 2; pub type Dircookie = u64; pub type Dirnamlen = u32; pub type Inode = u64; -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Filetype(u8); +pub type Filetype = u8; /// The type of the file descriptor or file is unknown or is different from any of the other types specified. -pub const FILETYPE_UNKNOWN: Filetype = Filetype(0); +pub const FILETYPE_UNKNOWN: Filetype = 0; /// The file descriptor or file refers to a block device inode. -pub const FILETYPE_BLOCK_DEVICE: Filetype = Filetype(1); +pub const FILETYPE_BLOCK_DEVICE: Filetype = 1; /// The file descriptor or file refers to a character device inode. -pub const FILETYPE_CHARACTER_DEVICE: Filetype = Filetype(2); +pub const FILETYPE_CHARACTER_DEVICE: Filetype = 2; /// The file descriptor or file refers to a directory inode. -pub const FILETYPE_DIRECTORY: Filetype = Filetype(3); +pub const FILETYPE_DIRECTORY: Filetype = 3; /// The file descriptor or file refers to a regular file inode. -pub const FILETYPE_REGULAR_FILE: Filetype = Filetype(4); +pub const FILETYPE_REGULAR_FILE: Filetype = 4; /// The file descriptor or file refers to a datagram socket. -pub const FILETYPE_SOCKET_DGRAM: Filetype = Filetype(5); +pub const FILETYPE_SOCKET_DGRAM: Filetype = 5; /// The file descriptor or file refers to a byte-stream socket. -pub const FILETYPE_SOCKET_STREAM: Filetype = Filetype(6); +pub const FILETYPE_SOCKET_STREAM: Filetype = 6; /// The file refers to a symbolic link inode. -pub const FILETYPE_SYMBOLIC_LINK: Filetype = Filetype(7); -impl Filetype { - pub const fn raw(&self) -> u8 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "UNKNOWN", - 1 => "BLOCK_DEVICE", - 2 => "CHARACTER_DEVICE", - 3 => "DIRECTORY", - 4 => "REGULAR_FILE", - 5 => "SOCKET_DGRAM", - 6 => "SOCKET_STREAM", - 7 => "SYMBOLIC_LINK", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 {0 => "The type of the file descriptor or file is unknown or is different from any of the other types specified.",1 => "The file descriptor or file refers to a block device inode.",2 => "The file descriptor or file refers to a character device inode.",3 => "The file descriptor or file refers to a directory inode.",4 => "The file descriptor or file refers to a regular file inode.",5 => "The file descriptor or file refers to a datagram socket.",6 => "The file descriptor or file refers to a byte-stream socket.",7 => "The file refers to a symbolic link inode.",_ => unsafe { core::hint::unreachable_unchecked() },} - } -} -impl fmt::Debug for Filetype { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Filetype") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - +pub const FILETYPE_SYMBOLIC_LINK: Filetype = 7; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Dirent { @@ -612,65 +389,32 @@ pub struct Dirent { /// The type of the file referred to by this directory entry. pub d_type: Filetype, } -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Advice(u8); +pub type Advice = u8; /// The application has no advice to give on its behavior with respect to the specified data. -pub const ADVICE_NORMAL: Advice = Advice(0); +pub const ADVICE_NORMAL: Advice = 0; /// The application expects to access the specified data sequentially from lower offsets to higher offsets. -pub const ADVICE_SEQUENTIAL: Advice = Advice(1); +pub const ADVICE_SEQUENTIAL: Advice = 1; /// The application expects to access the specified data in a random order. -pub const ADVICE_RANDOM: Advice = Advice(2); +pub const ADVICE_RANDOM: Advice = 2; /// The application expects to access the specified data in the near future. -pub const ADVICE_WILLNEED: Advice = Advice(3); +pub const ADVICE_WILLNEED: Advice = 3; /// The application expects that it will not access the specified data in the near future. -pub const ADVICE_DONTNEED: Advice = Advice(4); +pub const ADVICE_DONTNEED: Advice = 4; /// The application expects to access the specified data once and then not reuse it thereafter. -pub const ADVICE_NOREUSE: Advice = Advice(5); -impl Advice { - pub const fn raw(&self) -> u8 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "NORMAL", - 1 => "SEQUENTIAL", - 2 => "RANDOM", - 3 => "WILLNEED", - 4 => "DONTNEED", - 5 => "NOREUSE", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 {0 => "The application has no advice to give on its behavior with respect to the specified data.",1 => "The application expects to access the specified data sequentially from lower offsets to higher offsets.",2 => "The application expects to access the specified data in a random order.",3 => "The application expects to access the specified data in the near future.",4 => "The application expects that it will not access the specified data in the near future.",5 => "The application expects to access the specified data once and then not reuse it thereafter.",_ => unsafe { core::hint::unreachable_unchecked() },} - } -} -impl fmt::Debug for Advice { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Advice") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - +pub const ADVICE_NOREUSE: Advice = 5; pub type Fdflags = u16; /// Append mode: Data written to the file is always appended to the file's end. -pub const FDFLAGS_APPEND: Fdflags = 1 << 0; +pub const FDFLAGS_APPEND: Fdflags = 0x1; /// Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. -pub const FDFLAGS_DSYNC: Fdflags = 1 << 1; +pub const FDFLAGS_DSYNC: Fdflags = 0x2; /// Non-blocking mode. -pub const FDFLAGS_NONBLOCK: Fdflags = 1 << 2; +pub const FDFLAGS_NONBLOCK: Fdflags = 0x4; /// Synchronized read I/O operations. -pub const FDFLAGS_RSYNC: Fdflags = 1 << 3; +pub const FDFLAGS_RSYNC: Fdflags = 0x8; /// Write according to synchronized I/O file integrity completion. In /// addition to synchronizing the data stored in the file, the implementation /// may also synchronously update the file's metadata. -pub const FDFLAGS_SYNC: Fdflags = 1 << 4; - +pub const FDFLAGS_SYNC: Fdflags = 0x10; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Fdstat { @@ -687,28 +431,25 @@ pub struct Fdstat { pub type Device = u64; pub type Fstflags = u16; /// Adjust the last data access timestamp to the value stored in `filestat::atim`. -pub const FSTFLAGS_ATIM: Fstflags = 1 << 0; +pub const FSTFLAGS_ATIM: Fstflags = 0x1; /// Adjust the last data access timestamp to the time of clock `clockid::realtime`. -pub const FSTFLAGS_ATIM_NOW: Fstflags = 1 << 1; +pub const FSTFLAGS_ATIM_NOW: Fstflags = 0x2; /// Adjust the last data modification timestamp to the value stored in `filestat::mtim`. -pub const FSTFLAGS_MTIM: Fstflags = 1 << 2; +pub const FSTFLAGS_MTIM: Fstflags = 0x4; /// Adjust the last data modification timestamp to the time of clock `clockid::realtime`. -pub const FSTFLAGS_MTIM_NOW: Fstflags = 1 << 3; - +pub const FSTFLAGS_MTIM_NOW: Fstflags = 0x8; pub type Lookupflags = u32; /// As long as the resolved path corresponds to a symbolic link, it is expanded. -pub const LOOKUPFLAGS_SYMLINK_FOLLOW: Lookupflags = 1 << 0; - +pub const LOOKUPFLAGS_SYMLINK_FOLLOW: Lookupflags = 0x1; pub type Oflags = u16; /// Create file if it does not exist. -pub const OFLAGS_CREAT: Oflags = 1 << 0; +pub const OFLAGS_CREAT: Oflags = 0x1; /// Fail if not a directory. -pub const OFLAGS_DIRECTORY: Oflags = 1 << 1; +pub const OFLAGS_DIRECTORY: Oflags = 0x2; /// Fail if file already exists. -pub const OFLAGS_EXCL: Oflags = 1 << 2; +pub const OFLAGS_EXCL: Oflags = 0x4; /// Truncate file to size 0. -pub const OFLAGS_TRUNC: Oflags = 1 << 3; - +pub const OFLAGS_TRUNC: Oflags = 0x8; pub type Linkcount = u64; #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -731,63 +472,19 @@ pub struct Filestat { pub ctim: Timestamp, } pub type Userdata = u64; -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Eventtype(u8); +pub type Eventtype = u8; /// The time value of clock `subscription_clock::id` has /// reached timestamp `subscription_clock::timeout`. -pub const EVENTTYPE_CLOCK: Eventtype = Eventtype(0); +pub const EVENTTYPE_CLOCK: Eventtype = 0; /// File descriptor `subscription_fd_readwrite::file_descriptor` has data /// available for reading. This event always triggers for regular files. -pub const EVENTTYPE_FD_READ: Eventtype = Eventtype(1); +pub const EVENTTYPE_FD_READ: Eventtype = 1; /// File descriptor `subscription_fd_readwrite::file_descriptor` has capacity /// available for writing. This event always triggers for regular files. -pub const EVENTTYPE_FD_WRITE: Eventtype = Eventtype(2); -impl Eventtype { - pub const fn raw(&self) -> u8 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "CLOCK", - 1 => "FD_READ", - 2 => "FD_WRITE", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 { - 0 => { - "The time value of clock `subscription_clock::id` has -reached timestamp `subscription_clock::timeout`." - } - 1 => { - "File descriptor `subscription_fd_readwrite::file_descriptor` has data -available for reading. This event always triggers for regular files." - } - 2 => { - "File descriptor `subscription_fd_readwrite::file_descriptor` has capacity -available for writing. This event always triggers for regular files." - } - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } -} -impl fmt::Debug for Eventtype { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Eventtype") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - +pub const EVENTTYPE_FD_WRITE: Eventtype = 2; pub type Eventrwflags = u16; /// The peer of this socket has closed or disconnected. -pub const EVENTRWFLAGS_FD_READWRITE_HANGUP: Eventrwflags = 1 << 0; - +pub const EVENTRWFLAGS_FD_READWRITE_HANGUP: Eventrwflags = 0x1; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct EventFdReadwrite { @@ -804,7 +501,7 @@ pub struct Event { /// If non-zero, an error that occurred while processing the subscription request. pub error: Errno, /// The type of event that occured - pub type_: Eventtype, + pub r#type: Eventtype, /// The contents of the event, if it is an `eventtype::fd_read` or /// `eventtype::fd_write`. `eventtype::clock` events ignore this field. pub fd_readwrite: EventFdReadwrite, @@ -815,8 +512,7 @@ pub type Subclockflags = u16; /// `subscription_clock::id`. If clear, treat the timestamp /// provided in `subscription_clock::timeout` relative to the /// current time value of clock `subscription_clock::id`. -pub const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: Subclockflags = 1 << 0; - +pub const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: Subclockflags = 0x1; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SubscriptionClock { @@ -846,7 +542,7 @@ pub union SubscriptionUU { #[repr(C)] #[derive(Copy, Clone)] pub struct SubscriptionU { - pub tag: u8, + pub tag: Eventtype, pub u: SubscriptionUU, } @@ -860,333 +556,117 @@ pub struct Subscription { pub u: SubscriptionU, } pub type Exitcode = u32; -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Signal(u8); +pub type Signal = u8; /// No signal. Note that POSIX has special semantics for `kill(pid, 0)`, /// so this value is reserved. -pub const SIGNAL_NONE: Signal = Signal(0); +pub const SIGNAL_NONE: Signal = 0; /// Hangup. /// Action: Terminates the process. -pub const SIGNAL_HUP: Signal = Signal(1); +pub const SIGNAL_HUP: Signal = 1; /// Terminate interrupt signal. /// Action: Terminates the process. -pub const SIGNAL_INT: Signal = Signal(2); +pub const SIGNAL_INT: Signal = 2; /// Terminal quit signal. /// Action: Terminates the process. -pub const SIGNAL_QUIT: Signal = Signal(3); +pub const SIGNAL_QUIT: Signal = 3; /// Illegal instruction. /// Action: Terminates the process. -pub const SIGNAL_ILL: Signal = Signal(4); +pub const SIGNAL_ILL: Signal = 4; /// Trace/breakpoint trap. /// Action: Terminates the process. -pub const SIGNAL_TRAP: Signal = Signal(5); +pub const SIGNAL_TRAP: Signal = 5; /// Process abort signal. /// Action: Terminates the process. -pub const SIGNAL_ABRT: Signal = Signal(6); +pub const SIGNAL_ABRT: Signal = 6; /// Access to an undefined portion of a memory object. /// Action: Terminates the process. -pub const SIGNAL_BUS: Signal = Signal(7); +pub const SIGNAL_BUS: Signal = 7; /// Erroneous arithmetic operation. /// Action: Terminates the process. -pub const SIGNAL_FPE: Signal = Signal(8); +pub const SIGNAL_FPE: Signal = 8; /// Kill. /// Action: Terminates the process. -pub const SIGNAL_KILL: Signal = Signal(9); +pub const SIGNAL_KILL: Signal = 9; /// User-defined signal 1. /// Action: Terminates the process. -pub const SIGNAL_USR1: Signal = Signal(10); +pub const SIGNAL_USR1: Signal = 10; /// Invalid memory reference. /// Action: Terminates the process. -pub const SIGNAL_SEGV: Signal = Signal(11); +pub const SIGNAL_SEGV: Signal = 11; /// User-defined signal 2. /// Action: Terminates the process. -pub const SIGNAL_USR2: Signal = Signal(12); +pub const SIGNAL_USR2: Signal = 12; /// Write on a pipe with no one to read it. /// Action: Ignored. -pub const SIGNAL_PIPE: Signal = Signal(13); +pub const SIGNAL_PIPE: Signal = 13; /// Alarm clock. /// Action: Terminates the process. -pub const SIGNAL_ALRM: Signal = Signal(14); +pub const SIGNAL_ALRM: Signal = 14; /// Termination signal. /// Action: Terminates the process. -pub const SIGNAL_TERM: Signal = Signal(15); +pub const SIGNAL_TERM: Signal = 15; /// Child process terminated, stopped, or continued. /// Action: Ignored. -pub const SIGNAL_CHLD: Signal = Signal(16); +pub const SIGNAL_CHLD: Signal = 16; /// Continue executing, if stopped. /// Action: Continues executing, if stopped. -pub const SIGNAL_CONT: Signal = Signal(17); +pub const SIGNAL_CONT: Signal = 17; /// Stop executing. /// Action: Stops executing. -pub const SIGNAL_STOP: Signal = Signal(18); +pub const SIGNAL_STOP: Signal = 18; /// Terminal stop signal. /// Action: Stops executing. -pub const SIGNAL_TSTP: Signal = Signal(19); +pub const SIGNAL_TSTP: Signal = 19; /// Background process attempting read. /// Action: Stops executing. -pub const SIGNAL_TTIN: Signal = Signal(20); +pub const SIGNAL_TTIN: Signal = 20; /// Background process attempting write. /// Action: Stops executing. -pub const SIGNAL_TTOU: Signal = Signal(21); +pub const SIGNAL_TTOU: Signal = 21; /// High bandwidth data is available at a socket. /// Action: Ignored. -pub const SIGNAL_URG: Signal = Signal(22); +pub const SIGNAL_URG: Signal = 22; /// CPU time limit exceeded. /// Action: Terminates the process. -pub const SIGNAL_XCPU: Signal = Signal(23); +pub const SIGNAL_XCPU: Signal = 23; /// File size limit exceeded. /// Action: Terminates the process. -pub const SIGNAL_XFSZ: Signal = Signal(24); +pub const SIGNAL_XFSZ: Signal = 24; /// Virtual timer expired. /// Action: Terminates the process. -pub const SIGNAL_VTALRM: Signal = Signal(25); +pub const SIGNAL_VTALRM: Signal = 25; /// Profiling timer expired. /// Action: Terminates the process. -pub const SIGNAL_PROF: Signal = Signal(26); +pub const SIGNAL_PROF: Signal = 26; /// Window changed. /// Action: Ignored. -pub const SIGNAL_WINCH: Signal = Signal(27); +pub const SIGNAL_WINCH: Signal = 27; /// I/O possible. /// Action: Terminates the process. -pub const SIGNAL_POLL: Signal = Signal(28); +pub const SIGNAL_POLL: Signal = 28; /// Power failure. /// Action: Terminates the process. -pub const SIGNAL_PWR: Signal = Signal(29); +pub const SIGNAL_PWR: Signal = 29; /// Bad system call. /// Action: Terminates the process. -pub const SIGNAL_SYS: Signal = Signal(30); -impl Signal { - pub const fn raw(&self) -> u8 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "NONE", - 1 => "HUP", - 2 => "INT", - 3 => "QUIT", - 4 => "ILL", - 5 => "TRAP", - 6 => "ABRT", - 7 => "BUS", - 8 => "FPE", - 9 => "KILL", - 10 => "USR1", - 11 => "SEGV", - 12 => "USR2", - 13 => "PIPE", - 14 => "ALRM", - 15 => "TERM", - 16 => "CHLD", - 17 => "CONT", - 18 => "STOP", - 19 => "TSTP", - 20 => "TTIN", - 21 => "TTOU", - 22 => "URG", - 23 => "XCPU", - 24 => "XFSZ", - 25 => "VTALRM", - 26 => "PROF", - 27 => "WINCH", - 28 => "POLL", - 29 => "PWR", - 30 => "SYS", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 { - 0 => { - "No signal. Note that POSIX has special semantics for `kill(pid, 0)`, -so this value is reserved." - } - 1 => { - "Hangup. -Action: Terminates the process." - } - 2 => { - "Terminate interrupt signal. -Action: Terminates the process." - } - 3 => { - "Terminal quit signal. -Action: Terminates the process." - } - 4 => { - "Illegal instruction. -Action: Terminates the process." - } - 5 => { - "Trace/breakpoint trap. -Action: Terminates the process." - } - 6 => { - "Process abort signal. -Action: Terminates the process." - } - 7 => { - "Access to an undefined portion of a memory object. -Action: Terminates the process." - } - 8 => { - "Erroneous arithmetic operation. -Action: Terminates the process." - } - 9 => { - "Kill. -Action: Terminates the process." - } - 10 => { - "User-defined signal 1. -Action: Terminates the process." - } - 11 => { - "Invalid memory reference. -Action: Terminates the process." - } - 12 => { - "User-defined signal 2. -Action: Terminates the process." - } - 13 => { - "Write on a pipe with no one to read it. -Action: Ignored." - } - 14 => { - "Alarm clock. -Action: Terminates the process." - } - 15 => { - "Termination signal. -Action: Terminates the process." - } - 16 => { - "Child process terminated, stopped, or continued. -Action: Ignored." - } - 17 => { - "Continue executing, if stopped. -Action: Continues executing, if stopped." - } - 18 => { - "Stop executing. -Action: Stops executing." - } - 19 => { - "Terminal stop signal. -Action: Stops executing." - } - 20 => { - "Background process attempting read. -Action: Stops executing." - } - 21 => { - "Background process attempting write. -Action: Stops executing." - } - 22 => { - "High bandwidth data is available at a socket. -Action: Ignored." - } - 23 => { - "CPU time limit exceeded. -Action: Terminates the process." - } - 24 => { - "File size limit exceeded. -Action: Terminates the process." - } - 25 => { - "Virtual timer expired. -Action: Terminates the process." - } - 26 => { - "Profiling timer expired. -Action: Terminates the process." - } - 27 => { - "Window changed. -Action: Ignored." - } - 28 => { - "I/O possible. -Action: Terminates the process." - } - 29 => { - "Power failure. -Action: Terminates the process." - } - 30 => { - "Bad system call. -Action: Terminates the process." - } - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } -} -impl fmt::Debug for Signal { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Signal") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - +pub const SIGNAL_SYS: Signal = 30; pub type Riflags = u16; /// Returns the message without removing it from the socket's receive queue. -pub const RIFLAGS_RECV_PEEK: Riflags = 1 << 0; +pub const RIFLAGS_RECV_PEEK: Riflags = 0x1; /// On byte-stream sockets, block until the full amount of data can be returned. -pub const RIFLAGS_RECV_WAITALL: Riflags = 1 << 1; - +pub const RIFLAGS_RECV_WAITALL: Riflags = 0x2; pub type Roflags = u16; /// Returned by `sock_recv`: Message data has been truncated. -pub const ROFLAGS_RECV_DATA_TRUNCATED: Roflags = 1 << 0; - +pub const ROFLAGS_RECV_DATA_TRUNCATED: Roflags = 0x1; pub type Siflags = u16; pub type Sdflags = u8; /// Disables further receive operations. -pub const SDFLAGS_RD: Sdflags = 1 << 0; +pub const SDFLAGS_RD: Sdflags = 0x1; /// Disables further send operations. -pub const SDFLAGS_WR: Sdflags = 1 << 1; - -#[repr(transparent)] -#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct Preopentype(u8); +pub const SDFLAGS_WR: Sdflags = 0x2; +pub type Preopentype = u8; /// A pre-opened directory. -pub const PREOPENTYPE_DIR: Preopentype = Preopentype(0); -impl Preopentype { - pub const fn raw(&self) -> u8 { - self.0 - } - - pub fn name(&self) -> &'static str { - match self.0 { - 0 => "DIR", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } - pub fn message(&self) -> &'static str { - match self.0 { - 0 => "A pre-opened directory.", - _ => unsafe { core::hint::unreachable_unchecked() }, - } - } -} -impl fmt::Debug for Preopentype { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Preopentype") - .field("code", &self.0) - .field("name", &self.name()) - .field("message", &self.message()) - .finish() - } -} - +pub const PREOPENTYPE_DIR: Preopentype = 0; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct PrestatDir { @@ -1201,18 +681,18 @@ pub union PrestatU { #[repr(C)] #[derive(Copy, Clone)] pub struct Prestat { - pub tag: u8, + pub tag: Preopentype, pub u: PrestatU, } /// Read command-line argument data. -/// The size of the array should match that returned by `args_sizes_get`. -/// Each argument is expected to be `\0` terminated. -pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::args_get(argv as i32, argv_buf as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +/// The size of the array should match that returned by `args_sizes_get` +pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<()> { + let rc = wasi_snapshot_preview1::args_get(argv, argv_buf); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1220,30 +700,27 @@ pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<(), Errn /// /// ## Return /// -/// Returns the number of arguments and the size of the argument string -/// data, or an error. -pub unsafe fn args_sizes_get() -> Result<(Size, Size), Errno> { - let mut rp0 = MaybeUninit::::uninit(); - let mut rp1 = MaybeUninit::::uninit(); - let ret = - wasi_snapshot_preview1::args_sizes_get(rp0.as_mut_ptr() as i32, rp1.as_mut_ptr() as i32); - match ret { - 0 => Ok(( - core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), - core::ptr::read(rp1.as_mut_ptr() as i32 as *const Size), - )), - _ => Err(Errno(ret as u16)), +/// * `argc` - The number of arguments. +/// * `argv_buf_size` - The size of the argument string data. +pub unsafe fn args_sizes_get() -> Result<(Size, Size)> { + let mut argc = MaybeUninit::uninit(); + let mut argv_buf_size = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::args_sizes_get(argc.as_mut_ptr(), argv_buf_size.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok((argc.assume_init(), argv_buf_size.assume_init())) } } /// Read environment variable data. /// The sizes of the buffers should match that returned by `environ_sizes_get`. -/// Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s. -pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::environ_get(environ as i32, environ_buf as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result<()> { + let rc = wasi_snapshot_preview1::environ_get(environ, environ_buf); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1251,19 +728,19 @@ pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result /// /// ## Return /// -/// Returns the number of environment variable arguments and the size of the -/// environment variable data. -pub unsafe fn environ_sizes_get() -> Result<(Size, Size), Errno> { - let mut rp0 = MaybeUninit::::uninit(); - let mut rp1 = MaybeUninit::::uninit(); - let ret = - wasi_snapshot_preview1::environ_sizes_get(rp0.as_mut_ptr() as i32, rp1.as_mut_ptr() as i32); - match ret { - 0 => Ok(( - core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), - core::ptr::read(rp1.as_mut_ptr() as i32 as *const Size), - )), - _ => Err(Errno(ret as u16)), +/// * `environc` - The number of environment variable arguments. +/// * `environ_buf_size` - The size of the environment variable data. +pub unsafe fn environ_sizes_get() -> Result<(Size, Size)> { + let mut environc = MaybeUninit::uninit(); + let mut environ_buf_size = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::environ_sizes_get( + environc.as_mut_ptr(), + environ_buf_size.as_mut_ptr(), + ); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok((environc.assume_init(), environ_buf_size.assume_init())) } } @@ -1278,13 +755,14 @@ pub unsafe fn environ_sizes_get() -> Result<(Size, Size), Errno> { /// /// ## Return /// -/// The resolution of the clock, or an error if one happened. -pub unsafe fn clock_res_get(id: Clockid) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::clock_res_get(id.0 as i32, rp0.as_mut_ptr() as i32); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Timestamp)), - _ => Err(Errno(ret as u16)), +/// * `resolution` - The resolution of the clock. +pub unsafe fn clock_res_get(id: Clockid) -> Result { + let mut resolution = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::clock_res_get(id, resolution.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(resolution.assume_init()) } } @@ -1298,17 +776,14 @@ pub unsafe fn clock_res_get(id: Clockid) -> Result { /// /// ## Return /// -/// The time value of the clock. -pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::clock_time_get( - id.0 as i32, - precision as i64, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Timestamp)), - _ => Err(Errno(ret as u16)), +/// * `time` - The time value of the clock. +pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result { + let mut time = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::clock_time_get(id, precision, time.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(time.assume_init()) } } @@ -1320,17 +795,12 @@ pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result Result<(), Errno> { - let ret = - wasi_snapshot_preview1::fd_advise(fd as i32, offset as i64, len as i64, advice.0 as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_advise(fd: Fd, offset: Filesize, len: Filesize, advice: Advice) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_advise(fd, offset, len, advice); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1341,31 +811,34 @@ pub unsafe fn fd_advise( /// /// * `offset` - The offset at which to start the allocation. /// * `len` - The length of the area that is allocated. -pub unsafe fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_allocate(fd as i32, offset as i64, len as i64); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_allocate(fd, offset, len); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } /// Close a file descriptor. /// Note: This is similar to `close` in POSIX. -pub unsafe fn fd_close(fd: Fd) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_close(fd as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_close(fd: Fd) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_close(fd); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } /// Synchronize the data of a file to disk. /// Note: This is similar to `fdatasync` in POSIX. -pub unsafe fn fd_datasync(fd: Fd) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_datasync(fd as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_datasync(fd: Fd) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_datasync(fd); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1374,13 +847,14 @@ pub unsafe fn fd_datasync(fd: Fd) -> Result<(), Errno> { /// /// ## Return /// -/// The buffer where the file descriptor's attributes are stored. -pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_fdstat_get(fd as i32, rp0.as_mut_ptr() as i32); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fdstat)), - _ => Err(Errno(ret as u16)), +/// * `stat` - The buffer where the file descriptor's attributes are stored. +pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { + let mut stat = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_fdstat_get(fd, stat.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(stat.assume_init()) } } @@ -1390,11 +864,12 @@ pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `flags` - The desired values of the file descriptor flags. -pub unsafe fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_fdstat_set_flags(fd as i32, flags as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_fdstat_set_flags(fd, flags); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1408,15 +883,12 @@ pub unsafe fn fd_fdstat_set_rights( fd: Fd, fs_rights_base: Rights, fs_rights_inheriting: Rights, -) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_fdstat_set_rights( - fd as i32, - fs_rights_base as i64, - fs_rights_inheriting as i64, - ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_fdstat_set_rights(fd, fs_rights_base, fs_rights_inheriting); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1424,13 +896,14 @@ pub unsafe fn fd_fdstat_set_rights( /// /// ## Return /// -/// The buffer where the file's attributes are stored. -pub unsafe fn fd_filestat_get(fd: Fd) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_filestat_get(fd as i32, rp0.as_mut_ptr() as i32); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filestat)), - _ => Err(Errno(ret as u16)), +/// * `buf` - The buffer where the file's attributes are stored. +pub unsafe fn fd_filestat_get(fd: Fd) -> Result { + let mut buf = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_filestat_get(fd, buf.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(buf.assume_init()) } } @@ -1440,11 +913,12 @@ pub unsafe fn fd_filestat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `size` - The desired file size. -pub unsafe fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_filestat_set_size(fd as i32, size as i64); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_filestat_set_size(fd, size); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1461,16 +935,12 @@ pub unsafe fn fd_filestat_set_times( atim: Timestamp, mtim: Timestamp, fst_flags: Fstflags, -) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_filestat_set_times( - fd as i32, - atim as i64, - mtim as i64, - fst_flags as i32, - ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_filestat_set_times(fd, atim, mtim, fst_flags); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1484,19 +954,15 @@ pub unsafe fn fd_filestat_set_times( /// /// ## Return /// -/// The number of bytes read. -pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray<'_>, offset: Filesize) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_pread( - fd as i32, - iovs.as_ptr() as i32, - iovs.len() as i32, - offset as i64, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), +/// * `nread` - The number of bytes read. +pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray, offset: Filesize) -> Result { + let mut nread = MaybeUninit::uninit(); + let rc = + wasi_snapshot_preview1::fd_pread(fd, iovs.as_ptr(), iovs.len(), offset, nread.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(nread.assume_init()) } } @@ -1504,13 +970,14 @@ pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray<'_>, offset: Filesize) -> Result /// /// ## Return /// -/// The buffer where the description is stored. -pub unsafe fn fd_prestat_get(fd: Fd) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_prestat_get(fd as i32, rp0.as_mut_ptr() as i32); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Prestat)), - _ => Err(Errno(ret as u16)), +/// * `buf` - The buffer where the description is stored. +pub unsafe fn fd_prestat_get(fd: Fd) -> Result { + let mut buf = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_prestat_get(fd, buf.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(buf.assume_init()) } } @@ -1519,11 +986,12 @@ pub unsafe fn fd_prestat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `path` - A buffer into which to write the preopened directory name. -pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_prestat_dir_name(fd as i32, path as i32, path_len as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_prestat_dir_name(fd, path, path_len); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1537,19 +1005,20 @@ pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Resu /// /// ## Return /// -/// The number of bytes written. -pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray<'_>, offset: Filesize) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_pwrite( - fd as i32, - iovs.as_ptr() as i32, - iovs.len() as i32, - offset as i64, - rp0.as_mut_ptr() as i32, +/// * `nwritten` - The number of bytes written. +pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray, offset: Filesize) -> Result { + let mut nwritten = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_pwrite( + fd, + iovs.as_ptr(), + iovs.len(), + offset, + nwritten.as_mut_ptr(), ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(nwritten.assume_init()) } } @@ -1562,25 +1031,21 @@ pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray<'_>, offset: Filesize) -> Resu /// /// ## Return /// -/// The number of bytes read. -pub unsafe fn fd_read(fd: Fd, iovs: IovecArray<'_>) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_read( - fd as i32, - iovs.as_ptr() as i32, - iovs.len() as i32, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), +/// * `nread` - The number of bytes read. +pub unsafe fn fd_read(fd: Fd, iovs: IovecArray) -> Result { + let mut nread = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_read(fd, iovs.as_ptr(), iovs.len(), nread.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(nread.assume_init()) } } /// Read directory entries from a directory. /// When successful, the contents of the output buffer consist of a sequence of -/// directory entries. Each directory entry consists of a `dirent` object, -/// followed by `dirent::d_namlen` bytes holding the name of the directory +/// directory entries. Each directory entry consists of a dirent_t object, +/// followed by dirent_t::d_namlen bytes holding the name of the directory /// entry. /// This function fills the output buffer as much as possible, potentially /// truncating the last directory entry. This allows the caller to grow its @@ -1594,24 +1059,14 @@ pub unsafe fn fd_read(fd: Fd, iovs: IovecArray<'_>) -> Result { /// /// ## Return /// -/// The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. -pub unsafe fn fd_readdir( - fd: Fd, - buf: *mut u8, - buf_len: Size, - cookie: Dircookie, -) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_readdir( - fd as i32, - buf as i32, - buf_len as i32, - cookie as i64, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), +/// * `bufused` - The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. +pub unsafe fn fd_readdir(fd: Fd, buf: *mut u8, buf_len: Size, cookie: Dircookie) -> Result { + let mut bufused = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_readdir(fd, buf, buf_len, cookie, bufused.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(bufused.assume_init()) } } @@ -1627,11 +1082,12 @@ pub unsafe fn fd_readdir( /// ## Parameters /// /// * `to` - The file descriptor to overwrite. -pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_renumber(fd as i32, to as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_renumber(fd, to); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1645,28 +1101,25 @@ pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<(), Errno> { /// /// ## Return /// -/// The new offset of the file descriptor, relative to the start of the file. -pub unsafe fn fd_seek(fd: Fd, offset: Filedelta, whence: Whence) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_seek( - fd as i32, - offset, - whence.0 as i32, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filesize)), - _ => Err(Errno(ret as u16)), +/// * `newoffset` - The new offset of the file descriptor, relative to the start of the file. +pub unsafe fn fd_seek(fd: Fd, offset: Filedelta, whence: Whence) -> Result { + let mut newoffset = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_seek(fd, offset, whence, newoffset.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(newoffset.assume_init()) } } /// Synchronize the data and metadata of a file to disk. /// Note: This is similar to `fsync` in POSIX. -pub unsafe fn fd_sync(fd: Fd) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::fd_sync(fd as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn fd_sync(fd: Fd) -> Result<()> { + let rc = wasi_snapshot_preview1::fd_sync(fd); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1675,13 +1128,14 @@ pub unsafe fn fd_sync(fd: Fd) -> Result<(), Errno> { /// /// ## Return /// -/// The current offset of the file descriptor, relative to the start of the file. -pub unsafe fn fd_tell(fd: Fd) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_tell(fd as i32, rp0.as_mut_ptr() as i32); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filesize)), - _ => Err(Errno(ret as u16)), +/// * `offset` - The current offset of the file descriptor, relative to the start of the file. +pub unsafe fn fd_tell(fd: Fd) -> Result { + let mut offset = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_tell(fd, offset.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(offset.assume_init()) } } @@ -1691,17 +1145,17 @@ pub unsafe fn fd_tell(fd: Fd) -> Result { /// ## Parameters /// /// * `iovs` - List of scatter/gather vectors from which to retrieve data. -pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray<'_>) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::fd_write( - fd as i32, - iovs.as_ptr() as i32, - iovs.len() as i32, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), +/// +/// ## Return +/// +/// * `nwritten` - The number of bytes written. +pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray) -> Result { + let mut nwritten = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::fd_write(fd, iovs.as_ptr(), iovs.len(), nwritten.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(nwritten.assume_init()) } } @@ -1711,15 +1165,12 @@ pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray<'_>) -> Result { /// ## Parameters /// /// * `path` - The path at which to create the directory. -pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_create_directory( - fd as i32, - path.as_ptr() as i32, - path.len() as i32, - ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<()> { + let rc = wasi_snapshot_preview1::path_create_directory(fd, path.as_ptr(), path.len()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1733,19 +1184,20 @@ pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<(), Errno> { /// /// ## Return /// -/// The buffer where the file's attributes are stored. -pub unsafe fn path_filestat_get(fd: Fd, flags: Lookupflags, path: &str) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::path_filestat_get( - fd as i32, - flags as i32, - path.as_ptr() as i32, - path.len() as i32, - rp0.as_mut_ptr() as i32, +/// * `buf` - The buffer where the file's attributes are stored. +pub unsafe fn path_filestat_get(fd: Fd, flags: Lookupflags, path: &str) -> Result { + let mut buf = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::path_filestat_get( + fd, + flags, + path.as_ptr(), + path.len(), + buf.as_mut_ptr(), ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filestat)), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(buf.assume_init()) } } @@ -1766,19 +1218,20 @@ pub unsafe fn path_filestat_set_times( atim: Timestamp, mtim: Timestamp, fst_flags: Fstflags, -) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_filestat_set_times( - fd as i32, - flags as i32, - path.as_ptr() as i32, - path.len() as i32, - atim as i64, - mtim as i64, - fst_flags as i32, +) -> Result<()> { + let rc = wasi_snapshot_preview1::path_filestat_set_times( + fd, + flags, + path.as_ptr(), + path.len(), + atim, + mtim, + fst_flags, ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1797,19 +1250,20 @@ pub unsafe fn path_link( old_path: &str, new_fd: Fd, new_path: &str, -) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_link( - old_fd as i32, - old_flags as i32, - old_path.as_ptr() as i32, - old_path.len() as i32, - new_fd as i32, - new_path.as_ptr() as i32, - new_path.len() as i32, +) -> Result<()> { + let rc = wasi_snapshot_preview1::path_link( + old_fd, + old_flags, + old_path.as_ptr(), + old_path.len(), + new_fd, + new_path.as_ptr(), + new_path.len(), ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1837,31 +1291,32 @@ pub unsafe fn path_link( /// /// ## Return /// -/// The file descriptor of the file that has been opened. +/// * `opened_fd` - The file descriptor of the file that has been opened. pub unsafe fn path_open( fd: Fd, dirflags: Lookupflags, path: &str, oflags: Oflags, fs_rights_base: Rights, - fs_rights_inheriting: Rights, + fs_rights_inherting: Rights, fdflags: Fdflags, -) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::path_open( - fd as i32, - dirflags as i32, - path.as_ptr() as i32, - path.len() as i32, - oflags as i32, - fs_rights_base as i64, - fs_rights_inheriting as i64, - fdflags as i32, - rp0.as_mut_ptr() as i32, +) -> Result { + let mut opened_fd = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::path_open( + fd, + dirflags, + path.as_ptr(), + path.len(), + oflags, + fs_rights_base, + fs_rights_inherting, + fdflags, + opened_fd.as_mut_ptr(), ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fd)), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(opened_fd.assume_init()) } } @@ -1875,25 +1330,21 @@ pub unsafe fn path_open( /// /// ## Return /// -/// The number of bytes placed in the buffer. -pub unsafe fn path_readlink( - fd: Fd, - path: &str, - buf: *mut u8, - buf_len: Size, -) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::path_readlink( - fd as i32, - path.as_ptr() as i32, - path.len() as i32, - buf as i32, - buf_len as i32, - rp0.as_mut_ptr() as i32, +/// * `bufused` - The number of bytes placed in the buffer. +pub unsafe fn path_readlink(fd: Fd, path: &str, buf: *mut u8, buf_len: Size) -> Result { + let mut bufused = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::path_readlink( + fd, + path.as_ptr(), + path.len(), + buf, + buf_len, + bufused.as_mut_ptr(), ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(bufused.assume_init()) } } @@ -1904,15 +1355,12 @@ pub unsafe fn path_readlink( /// ## Parameters /// /// * `path` - The path to a directory to remove. -pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_remove_directory( - fd as i32, - path.as_ptr() as i32, - path.len() as i32, - ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<()> { + let rc = wasi_snapshot_preview1::path_remove_directory(fd, path.as_ptr(), path.len()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1924,18 +1372,19 @@ pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<(), Errno> { /// * `old_path` - The source path of the file or directory to rename. /// * `new_fd` - The working directory at which the resolution of the new path starts. /// * `new_path` - The destination path to which to rename the file or directory. -pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_rename( - fd as i32, - old_path.as_ptr() as i32, - old_path.len() as i32, - new_fd as i32, - new_path.as_ptr() as i32, - new_path.len() as i32, +pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> Result<()> { + let rc = wasi_snapshot_preview1::path_rename( + fd, + old_path.as_ptr(), + old_path.len(), + new_fd, + new_path.as_ptr(), + new_path.len(), ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1946,17 +1395,18 @@ pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> /// /// * `old_path` - The contents of the symbolic link. /// * `new_path` - The destination path at which to create the symbolic link. -pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_symlink( - old_path.as_ptr() as i32, - old_path.len() as i32, - fd as i32, - new_path.as_ptr() as i32, - new_path.len() as i32, +pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<()> { + let rc = wasi_snapshot_preview1::path_symlink( + old_path.as_ptr(), + old_path.len(), + fd, + new_path.as_ptr(), + new_path.len(), ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1967,15 +1417,12 @@ pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<(), /// ## Parameters /// /// * `path` - The path to a file to unlink. -pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::path_unlink_file( - fd as i32, - path.as_ptr() as i32, - path.len() as i32, - ); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<()> { + let rc = wasi_snapshot_preview1::path_unlink_file(fd, path.as_ptr(), path.len()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -1983,28 +1430,24 @@ pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<(), Errno> { /// /// ## Parameters /// -/// * `in_` - The events to which to subscribe. +/// * `r#in` - The events to which to subscribe. /// * `out` - The events that have occurred. /// * `nsubscriptions` - Both the number of subscriptions and events. /// /// ## Return /// -/// The number of events stored. +/// * `nevents` - The number of events stored. pub unsafe fn poll_oneoff( - in_: *const Subscription, + r#in: *const Subscription, out: *mut Event, nsubscriptions: Size, -) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::poll_oneoff( - in_ as i32, - out as i32, - nsubscriptions as i32, - rp0.as_mut_ptr() as i32, - ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), +) -> Result { + let mut nevents = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::poll_oneoff(r#in, out, nsubscriptions, nevents.as_mut_ptr()); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(nevents.assume_init()) } } @@ -2016,7 +1459,7 @@ pub unsafe fn poll_oneoff( /// /// * `rval` - The exit code returned by the process. pub unsafe fn proc_exit(rval: Exitcode) { - wasi_snapshot_preview1::proc_exit(rval as i32); + wasi_snapshot_preview1::proc_exit(rval); } /// Send a signal to the process of the calling thread. @@ -2025,21 +1468,23 @@ pub unsafe fn proc_exit(rval: Exitcode) { /// ## Parameters /// /// * `sig` - The signal condition to trigger. -pub unsafe fn proc_raise(sig: Signal) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::proc_raise(sig.0 as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn proc_raise(sig: Signal) -> Result<()> { + let rc = wasi_snapshot_preview1::proc_raise(sig); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } /// Temporarily yield execution of the calling thread. /// Note: This is similar to `sched_yield` in POSIX. -pub unsafe fn sched_yield() -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::sched_yield(); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn sched_yield() -> Result<()> { + let rc = wasi_snapshot_preview1::sched_yield(); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -2053,31 +1498,12 @@ pub unsafe fn sched_yield() -> Result<(), Errno> { /// ## Parameters /// /// * `buf` - The buffer to fill with random data. -pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::random_get(buf as i32, buf_len as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), - } -} - -/// Accept a new incoming connection. -/// Note: This is similar to `accept` in POSIX. -/// -/// ## Parameters -/// -/// * `fd` - The listening socket. -/// * `flags` - The desired values of the file descriptor flags. -/// -/// ## Return -/// -/// New socket connection -pub unsafe fn sock_accept(fd: Fd, flags: Fdflags) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::sock_accept(fd as i32, flags as i32, rp0.as_mut_ptr() as i32); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fd)), - _ => Err(Errno(ret as u16)), +pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<()> { + let rc = wasi_snapshot_preview1::random_get(buf, buf_len); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } @@ -2092,28 +1518,23 @@ pub unsafe fn sock_accept(fd: Fd, flags: Fdflags) -> Result { /// /// ## Return /// -/// Number of bytes stored in ri_data and message flags. -pub unsafe fn sock_recv( - fd: Fd, - ri_data: IovecArray<'_>, - ri_flags: Riflags, -) -> Result<(Size, Roflags), Errno> { - let mut rp0 = MaybeUninit::::uninit(); - let mut rp1 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::sock_recv( - fd as i32, - ri_data.as_ptr() as i32, - ri_data.len() as i32, - ri_flags as i32, - rp0.as_mut_ptr() as i32, - rp1.as_mut_ptr() as i32, +/// * `ro_datalen` - Number of bytes stored in ri_data. +/// * `ro_flags` - Message flags. +pub unsafe fn sock_recv(fd: Fd, ri_data: IovecArray, ri_flags: Riflags) -> Result<(Size, Roflags)> { + let mut ro_datalen = MaybeUninit::uninit(); + let mut ro_flags = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::sock_recv( + fd, + ri_data.as_ptr(), + ri_data.len(), + ri_flags, + ro_datalen.as_mut_ptr(), + ro_flags.as_mut_ptr(), ); - match ret { - 0 => Ok(( - core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), - core::ptr::read(rp1.as_mut_ptr() as i32 as *const Roflags), - )), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok((ro_datalen.assume_init(), ro_flags.assume_init())) } } @@ -2128,23 +1549,20 @@ pub unsafe fn sock_recv( /// /// ## Return /// -/// Number of bytes transmitted. -pub unsafe fn sock_send( - fd: Fd, - si_data: CiovecArray<'_>, - si_flags: Siflags, -) -> Result { - let mut rp0 = MaybeUninit::::uninit(); - let ret = wasi_snapshot_preview1::sock_send( - fd as i32, - si_data.as_ptr() as i32, - si_data.len() as i32, - si_flags as i32, - rp0.as_mut_ptr() as i32, +/// * `so_datalen` - Number of bytes transmitted. +pub unsafe fn sock_send(fd: Fd, si_data: CiovecArray, si_flags: Siflags) -> Result { + let mut so_datalen = MaybeUninit::uninit(); + let rc = wasi_snapshot_preview1::sock_send( + fd, + si_data.as_ptr(), + si_data.len(), + si_flags, + so_datalen.as_mut_ptr(), ); - match ret { - 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), - _ => Err(Errno(ret as u16)), + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(so_datalen.assume_init()) } } @@ -2154,89 +1572,116 @@ pub unsafe fn sock_send( /// ## Parameters /// /// * `how` - Which channels on the socket to shut down. -pub unsafe fn sock_shutdown(fd: Fd, how: Sdflags) -> Result<(), Errno> { - let ret = wasi_snapshot_preview1::sock_shutdown(fd as i32, how as i32); - match ret { - 0 => Ok(()), - _ => Err(Errno(ret as u16)), +pub unsafe fn sock_shutdown(fd: Fd, how: Sdflags) -> Result<()> { + let rc = wasi_snapshot_preview1::sock_shutdown(fd, how); + if let Some(err) = Error::from_raw_error(rc) { + Err(err) + } else { + Ok(()) } } pub mod wasi_snapshot_preview1 { + use super::*; #[link(wasm_import_module = "wasi_snapshot_preview1")] extern "C" { /// Read command-line argument data. - /// The size of the array should match that returned by `args_sizes_get`. - /// Each argument is expected to be `\0` terminated. - pub fn args_get(arg0: i32, arg1: i32) -> i32; + /// The size of the array should match that returned by `args_sizes_get` + pub fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Errno; /// Return command-line argument data sizes. - pub fn args_sizes_get(arg0: i32, arg1: i32) -> i32; + pub fn args_sizes_get(argc: *mut Size, argv_buf_size: *mut Size) -> Errno; /// Read environment variable data. /// The sizes of the buffers should match that returned by `environ_sizes_get`. - /// Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s. - pub fn environ_get(arg0: i32, arg1: i32) -> i32; + pub fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Errno; /// Return environment variable data sizes. - pub fn environ_sizes_get(arg0: i32, arg1: i32) -> i32; + pub fn environ_sizes_get(environc: *mut Size, environ_buf_size: *mut Size) -> Errno; /// Return the resolution of a clock. /// Implementations are required to provide a non-zero value for supported clocks. For unsupported clocks, /// return `errno::inval`. /// Note: This is similar to `clock_getres` in POSIX. - pub fn clock_res_get(arg0: i32, arg1: i32) -> i32; + pub fn clock_res_get(id: Clockid, resolution: *mut Timestamp) -> Errno; /// Return the time value of a clock. /// Note: This is similar to `clock_gettime` in POSIX. - pub fn clock_time_get(arg0: i32, arg1: i64, arg2: i32) -> i32; + pub fn clock_time_get(id: Clockid, precision: Timestamp, time: *mut Timestamp) -> Errno; /// Provide file advisory information on a file descriptor. /// Note: This is similar to `posix_fadvise` in POSIX. - pub fn fd_advise(arg0: i32, arg1: i64, arg2: i64, arg3: i32) -> i32; + pub fn fd_advise(fd: Fd, offset: Filesize, len: Filesize, advice: Advice) -> Errno; /// Force the allocation of space in a file. /// Note: This is similar to `posix_fallocate` in POSIX. - pub fn fd_allocate(arg0: i32, arg1: i64, arg2: i64) -> i32; + pub fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Errno; /// Close a file descriptor. /// Note: This is similar to `close` in POSIX. - pub fn fd_close(arg0: i32) -> i32; + pub fn fd_close(fd: Fd) -> Errno; /// Synchronize the data of a file to disk. /// Note: This is similar to `fdatasync` in POSIX. - pub fn fd_datasync(arg0: i32) -> i32; + pub fn fd_datasync(fd: Fd) -> Errno; /// Get the attributes of a file descriptor. /// Note: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields. - pub fn fd_fdstat_get(arg0: i32, arg1: i32) -> i32; + pub fn fd_fdstat_get(fd: Fd, stat: *mut Fdstat) -> Errno; /// Adjust the flags associated with a file descriptor. /// Note: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX. - pub fn fd_fdstat_set_flags(arg0: i32, arg1: i32) -> i32; + pub fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Errno; /// Adjust the rights associated with a file descriptor. /// This can only be used to remove rights, and returns `errno::notcapable` if called in a way that would attempt to add rights - pub fn fd_fdstat_set_rights(arg0: i32, arg1: i64, arg2: i64) -> i32; + pub fn fd_fdstat_set_rights( + fd: Fd, + fs_rights_base: Rights, + fs_rights_inheriting: Rights, + ) -> Errno; /// Return the attributes of an open file. - pub fn fd_filestat_get(arg0: i32, arg1: i32) -> i32; + pub fn fd_filestat_get(fd: Fd, buf: *mut Filestat) -> Errno; /// Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros. /// Note: This is similar to `ftruncate` in POSIX. - pub fn fd_filestat_set_size(arg0: i32, arg1: i64) -> i32; + pub fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Errno; /// Adjust the timestamps of an open file or directory. /// Note: This is similar to `futimens` in POSIX. - pub fn fd_filestat_set_times(arg0: i32, arg1: i64, arg2: i64, arg3: i32) -> i32; + pub fn fd_filestat_set_times( + fd: Fd, + atim: Timestamp, + mtim: Timestamp, + fst_flags: Fstflags, + ) -> Errno; /// Read from a file descriptor, without using and updating the file descriptor's offset. /// Note: This is similar to `preadv` in POSIX. - pub fn fd_pread(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; + pub fn fd_pread( + fd: Fd, + iovs_ptr: *const Iovec, + iovs_len: usize, + offset: Filesize, + nread: *mut Size, + ) -> Errno; /// Return a description of the given preopened file descriptor. - pub fn fd_prestat_get(arg0: i32, arg1: i32) -> i32; + pub fn fd_prestat_get(fd: Fd, buf: *mut Prestat) -> Errno; /// Return a description of the given preopened file descriptor. - pub fn fd_prestat_dir_name(arg0: i32, arg1: i32, arg2: i32) -> i32; + pub fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Errno; /// Write to a file descriptor, without using and updating the file descriptor's offset. /// Note: This is similar to `pwritev` in POSIX. - pub fn fd_pwrite(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; + pub fn fd_pwrite( + fd: Fd, + iovs_ptr: *const Ciovec, + iovs_len: usize, + offset: Filesize, + nwritten: *mut Size, + ) -> Errno; /// Read from a file descriptor. /// Note: This is similar to `readv` in POSIX. - pub fn fd_read(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; + pub fn fd_read(fd: Fd, iovs_ptr: *const Iovec, iovs_len: usize, nread: *mut Size) -> Errno; /// Read directory entries from a directory. /// When successful, the contents of the output buffer consist of a sequence of - /// directory entries. Each directory entry consists of a `dirent` object, - /// followed by `dirent::d_namlen` bytes holding the name of the directory + /// directory entries. Each directory entry consists of a dirent_t object, + /// followed by dirent_t::d_namlen bytes holding the name of the directory /// entry. /// This function fills the output buffer as much as possible, potentially /// truncating the last directory entry. This allows the caller to grow its /// read buffer size in case it's too small to fit a single large directory /// entry, or skip the oversized directory entry. - pub fn fd_readdir(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; + pub fn fd_readdir( + fd: Fd, + buf: *mut u8, + buf_len: Size, + cookie: Dircookie, + bufused: *mut Size, + ) -> Errno; /// Atomically replace a file descriptor by renumbering another file descriptor. /// Due to the strong focus on thread safety, this environment does not provide /// a mechanism to duplicate or renumber a file descriptor to an arbitrary @@ -2245,47 +1690,63 @@ pub mod wasi_snapshot_preview1 { /// thread at the same time. /// This function provides a way to atomically renumber file descriptors, which /// would disappear if `dup2()` were to be removed entirely. - pub fn fd_renumber(arg0: i32, arg1: i32) -> i32; + pub fn fd_renumber(fd: Fd, to: Fd) -> Errno; /// Move the offset of a file descriptor. /// Note: This is similar to `lseek` in POSIX. - pub fn fd_seek(arg0: i32, arg1: i64, arg2: i32, arg3: i32) -> i32; + pub fn fd_seek( + fd: Fd, + offset: Filedelta, + whence: Whence, + newoffset: *mut Filesize, + ) -> Errno; /// Synchronize the data and metadata of a file to disk. /// Note: This is similar to `fsync` in POSIX. - pub fn fd_sync(arg0: i32) -> i32; + pub fn fd_sync(fd: Fd) -> Errno; /// Return the current offset of a file descriptor. /// Note: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX. - pub fn fd_tell(arg0: i32, arg1: i32) -> i32; + pub fn fd_tell(fd: Fd, offset: *mut Filesize) -> Errno; /// Write to a file descriptor. /// Note: This is similar to `writev` in POSIX. - pub fn fd_write(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; + pub fn fd_write( + fd: Fd, + iovs_ptr: *const Ciovec, + iovs_len: usize, + nwritten: *mut Size, + ) -> Errno; /// Create a directory. /// Note: This is similar to `mkdirat` in POSIX. - pub fn path_create_directory(arg0: i32, arg1: i32, arg2: i32) -> i32; + pub fn path_create_directory(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; /// Return the attributes of a file or directory. /// Note: This is similar to `stat` in POSIX. - pub fn path_filestat_get(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; + pub fn path_filestat_get( + fd: Fd, + flags: Lookupflags, + path_ptr: *const u8, + path_len: usize, + buf: *mut Filestat, + ) -> Errno; /// Adjust the timestamps of a file or directory. /// Note: This is similar to `utimensat` in POSIX. pub fn path_filestat_set_times( - arg0: i32, - arg1: i32, - arg2: i32, - arg3: i32, - arg4: i64, - arg5: i64, - arg6: i32, - ) -> i32; + fd: Fd, + flags: Lookupflags, + path_ptr: *const u8, + path_len: usize, + atim: Timestamp, + mtim: Timestamp, + fst_flags: Fstflags, + ) -> Errno; /// Create a hard link. /// Note: This is similar to `linkat` in POSIX. pub fn path_link( - arg0: i32, - arg1: i32, - arg2: i32, - arg3: i32, - arg4: i32, - arg5: i32, - arg6: i32, - ) -> i32; + old_fd: Fd, + old_flags: Lookupflags, + old_path_ptr: *const u8, + old_path_len: usize, + new_fd: Fd, + new_path_ptr: *const u8, + new_path_len: usize, + ) -> Errno; /// Open a file or directory. /// The returned file descriptor is not guaranteed to be the lowest-numbered /// file descriptor not currently open; it is randomized to prevent @@ -2294,73 +1755,100 @@ pub mod wasi_snapshot_preview1 { /// guaranteed to be less than 2**31. /// Note: This is similar to `openat` in POSIX. pub fn path_open( - arg0: i32, - arg1: i32, - arg2: i32, - arg3: i32, - arg4: i32, - arg5: i64, - arg6: i64, - arg7: i32, - arg8: i32, - ) -> i32; + fd: Fd, + dirflags: Lookupflags, + path_ptr: *const u8, + path_len: usize, + oflags: Oflags, + fs_rights_base: Rights, + fs_rights_inherting: Rights, + fdflags: Fdflags, + opened_fd: *mut Fd, + ) -> Errno; /// Read the contents of a symbolic link. /// Note: This is similar to `readlinkat` in POSIX. pub fn path_readlink( - arg0: i32, - arg1: i32, - arg2: i32, - arg3: i32, - arg4: i32, - arg5: i32, - ) -> i32; + fd: Fd, + path_ptr: *const u8, + path_len: usize, + buf: *mut u8, + buf_len: Size, + bufused: *mut Size, + ) -> Errno; /// Remove a directory. /// Return `errno::notempty` if the directory is not empty. /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - pub fn path_remove_directory(arg0: i32, arg1: i32, arg2: i32) -> i32; + pub fn path_remove_directory(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; /// Rename a file or directory. /// Note: This is similar to `renameat` in POSIX. - pub fn path_rename(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32) - -> i32; + pub fn path_rename( + fd: Fd, + old_path_ptr: *const u8, + old_path_len: usize, + new_fd: Fd, + new_path_ptr: *const u8, + new_path_len: usize, + ) -> Errno; /// Create a symbolic link. /// Note: This is similar to `symlinkat` in POSIX. - pub fn path_symlink(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; + pub fn path_symlink( + old_path_ptr: *const u8, + old_path_len: usize, + fd: Fd, + new_path_ptr: *const u8, + new_path_len: usize, + ) -> Errno; /// Unlink a file. /// Return `errno::isdir` if the path refers to a directory. /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - pub fn path_unlink_file(arg0: i32, arg1: i32, arg2: i32) -> i32; + pub fn path_unlink_file(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; /// Concurrently poll for the occurrence of a set of events. - pub fn poll_oneoff(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; + pub fn poll_oneoff( + r#in: *const Subscription, + out: *mut Event, + nsubscriptions: Size, + nevents: *mut Size, + ) -> Errno; /// Terminate the process normally. An exit code of 0 indicates successful /// termination of the program. The meanings of other values is dependent on /// the environment. - pub fn proc_exit(arg0: i32) -> !; + pub fn proc_exit(rval: Exitcode) -> !; /// Send a signal to the process of the calling thread. /// Note: This is similar to `raise` in POSIX. - pub fn proc_raise(arg0: i32) -> i32; + pub fn proc_raise(sig: Signal) -> Errno; /// Temporarily yield execution of the calling thread. /// Note: This is similar to `sched_yield` in POSIX. - pub fn sched_yield() -> i32; + pub fn sched_yield() -> Errno; /// Write high-quality random data into a buffer. /// This function blocks when the implementation is unable to immediately /// provide sufficient high-quality random data. /// This function may execute slowly, so when large mounts of random data are /// required, it's advisable to use this function to seed a pseudo-random /// number generator, rather than to provide the random data directly. - pub fn random_get(arg0: i32, arg1: i32) -> i32; - /// Accept a new incoming connection. - /// Note: This is similar to `accept` in POSIX. - pub fn sock_accept(arg0: i32, arg1: i32, arg2: i32) -> i32; + pub fn random_get(buf: *mut u8, buf_len: Size) -> Errno; /// Receive a message from a socket. /// Note: This is similar to `recv` in POSIX, though it also supports reading /// the data into multiple buffers in the manner of `readv`. - pub fn sock_recv(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32) -> i32; + pub fn sock_recv( + fd: Fd, + ri_data_ptr: *const Iovec, + ri_data_len: usize, + ri_flags: Riflags, + ro_datalen: *mut Size, + ro_flags: *mut Roflags, + ) -> Errno; /// Send a message on a socket. /// Note: This is similar to `send` in POSIX, though it also supports writing /// the data from multiple buffers in the manner of `writev`. - pub fn sock_send(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; + pub fn sock_send( + fd: Fd, + si_data_ptr: *const Ciovec, + si_data_len: usize, + si_flags: Siflags, + so_datalen: *mut Size, + ) -> Errno; /// Shut down socket send and receive channels. /// Note: This is similar to `shutdown` in POSIX. - pub fn sock_shutdown(arg0: i32, arg1: i32) -> i32; + pub fn sock_shutdown(fd: Fd, how: Sdflags) -> Errno; } } From 918c0e9b5edcac8c94b36efb9c30aeedcb9a285d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A3o=20Gottwald?= Date: Wed, 15 Jun 2022 21:34:44 +0000 Subject: [PATCH 33/64] Bug 1774377 - Add Firefox View menu item to the Tools menu. r=Gijs,fluent-reviewers Differential Revision: https://phabricator.services.mozilla.com/D149367 --- browser/base/content/browser-menubar.inc | 5 +++ browser/base/content/browser.js | 34 ++++++++++++++++- browser/base/content/macWindow.inc.xhtml | 3 ++ browser/base/content/nonbrowser-mac.js | 5 +++ browser/base/content/tabbrowser.js | 2 +- browser/base/content/utilityOverlay.js | 2 +- .../customizableui/CustomizableWidgets.jsm | 38 +------------------ .../components/firefoxview/firefoxView.ftl | 4 ++ .../tests/browser/browser_firefoxview_tab.js | 20 +++++----- .../components/sessionstore/SessionStore.jsm | 4 +- browser/themes/shared/tabs.css | 4 +- 11 files changed, 67 insertions(+), 54 deletions(-) diff --git a/browser/base/content/browser-menubar.inc b/browser/base/content/browser-menubar.inc index 48bed2a96849..0245d27a7288 100644 --- a/browser/base/content/browser-menubar.inc +++ b/browser/base/content/browser-menubar.inc @@ -392,6 +392,11 @@ class="sync-ui-item" hidden="true" oncommand="gSync.openSignInAgainPage('menubar');" data-l10n-id="menu-tools-fxa-re-auth"/> + +#ifdef NIGHTLY_BUILD + +#endif
diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index ce10a28e6225..7a9a596966ff 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -565,7 +565,6 @@ var gMultiProcessBrowser = window.docShell.QueryInterface(Ci.nsILoadContext) .useRemoteTabs; var gFissionBrowser = window.docShell.QueryInterface(Ci.nsILoadContext) .useRemoteSubframes; -var gFirefoxViewTab; var gBrowserAllowScriptsToCloseInitialTabs = false; @@ -1997,6 +1996,8 @@ var gBrowserInit = { ctrlTab.readPref(); Services.prefs.addObserver(ctrlTab.prefName, ctrlTab); + FirefoxViewHandler.init(); + // The object handling the downloads indicator is initialized here in the // delayed startup function, but the actual indicator element is not loaded // unless there are downloads to be displayed. @@ -10028,3 +10029,34 @@ var ConfirmationHint = { } }, }; + +var FirefoxViewHandler = { + tab: null, + init() { + if (!Services.prefs.getBoolPref("browser.tabs.firefox-view")) { + document.getElementById("menu_openFirefoxView").hidden = true; + } + }, + openTab() { + if (!this.tab) { + this.tab = gBrowser.addTrustedTab("about:firefoxview", { index: 0 }); + this.tab.addEventListener("TabClose", this, { once: true }); + gBrowser.tabContainer.addEventListener("TabSelect", this); + gBrowser.hideTab(this.tab); + } + gBrowser.selectedTab = this.tab; + }, + handleEvent(e) { + switch (e.type) { + case "TabSelect": + document + .getElementById("firefox-view-button") + ?.toggleAttribute("open", e.target == this.tab); + break; + case "TabClose": + this.tab = null; + gBrowser.tabContainer.removeEventListener("TabSelect", this); + break; + } + }, +}; diff --git a/browser/base/content/macWindow.inc.xhtml b/browser/base/content/macWindow.inc.xhtml index f13f6b2a2872..5be2c3bb8832 100644 --- a/browser/base/content/macWindow.inc.xhtml +++ b/browser/base/content/macWindow.inc.xhtml @@ -16,6 +16,9 @@ +#ifdef NIGHTLY_BUILD + +#endif # All JS files which are needed by browser.xhtml and other top level windows to diff --git a/browser/base/content/nonbrowser-mac.js b/browser/base/content/nonbrowser-mac.js index a499db807738..6615c8d3bf57 100644 --- a/browser/base/content/nonbrowser-mac.js +++ b/browser/base/content/nonbrowser-mac.js @@ -46,6 +46,7 @@ function nonBrowserWindowStartup() { "Browser:BookmarkAllTabs", "View:PageInfo", "History:UndoCloseTab", + "menu_openFirefoxView", ]; var element; @@ -127,6 +128,10 @@ function nonBrowserWindowDelayedStartup() { // initialize the private browsing UI gPrivateBrowsingUI.init(); + + if (!Services.prefs.getBoolPref("browser.tabs.firefox-view")) { + document.getElementById("menu_openFirefoxView").hidden = true; + } } function nonBrowserWindowShutdown() { diff --git a/browser/base/content/tabbrowser.js b/browser/base/content/tabbrowser.js index 0a6edc3ebf43..e4dcce259ce3 100644 --- a/browser/base/content/tabbrowser.js +++ b/browser/base/content/tabbrowser.js @@ -1108,7 +1108,7 @@ this._selectedBrowser = newBrowser; this._selectedTab = newTab; - if (newTab != gFirefoxViewTab) { + if (newTab != FirefoxViewHandler.tab) { this.showTab(newTab); } diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js index 8afaccf7b5d3..4f1e0f17bd95 100644 --- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -525,7 +525,7 @@ function openLinkIn(url, where, params) { // page. If a load request bounces off for the currently selected tab, // we'll open a new tab instead. let tab = w.gBrowser.getTabForBrowser(targetBrowser); - if (tab == w.gFirefoxViewTab) { + if (tab == w.FirefoxViewHandler.tab) { where = "tab"; targetBrowser = null; } else if ( diff --git a/browser/components/customizableui/CustomizableWidgets.jsm b/browser/components/customizableui/CustomizableWidgets.jsm index 59d5d8aaa693..ea5fb88e5e5b 100644 --- a/browser/components/customizableui/CustomizableWidgets.jsm +++ b/browser/components/customizableui/CustomizableWidgets.jsm @@ -467,43 +467,7 @@ const CustomizableWidgets = [ return Services.prefs.getBoolPref("browser.tabs.firefox-view"); }, onCommand(e) { - let button = e.target; - if (button.hasAttribute("open")) { - return; - } - let window = button.ownerGlobal; - let tabbrowser = window.gBrowser; - let tab = window.gFirefoxViewTab; - if (!tab) { - tab = tabbrowser.addTrustedTab("about:firefoxview", { index: 0 }); - tabbrowser.hideTab(tab); - window.gFirefoxViewTab = tab; - - let onTabSelect = event => { - button.toggleAttribute("open", event.target == tab); - }; - - let onTabClose = () => { - window.gFirefoxViewTab = null; - tabbrowser.tabContainer.removeEventListener("TabSelect", onTabSelect); - }; - - tabbrowser.tabContainer.addEventListener("TabSelect", onTabSelect); - tab.addEventListener("TabClose", onTabClose, { once: true }); - - window.addEventListener( - "unload", - () => { - tabbrowser.tabContainer.removeEventListener( - "TabSelect", - onTabSelect - ); - tab.removeEventListener("TabClose", onTabClose); - }, - { once: true } - ); - } - tabbrowser.selectedTab = tab; + e.view.FirefoxViewHandler.openTab(); }, }, ]; diff --git a/browser/components/firefoxview/firefoxView.ftl b/browser/components/firefoxview/firefoxView.ftl index daf2e5647234..c4654379d5fb 100644 --- a/browser/components/firefoxview/firefoxView.ftl +++ b/browser/components/firefoxview/firefoxView.ftl @@ -8,6 +8,10 @@ toolbar-button-firefox-view = .label = { -firefoxview-brand-name } .tooltiptext = { -firefoxview-brand-name } +menu-tools-firefox-view = + .label = { -firefoxview-brand-name } + .accesskey = F + firefoxview-page-title = { -firefoxview-brand-name } # Used instead of the localized relative time when a timestamp is within a minute or so of now diff --git a/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js b/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js index 481600d6ee6e..4212475fdb46 100644 --- a/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js +++ b/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js @@ -18,15 +18,15 @@ add_setup(async function() { }); function assertFirefoxViewTab(w = window) { - ok(w.gFirefoxViewTab, "Firefox View tab exists"); - ok(w.gFirefoxViewTab?.hidden, "Firefox View tab is hidden"); + ok(w.FirefoxViewHandler.tab, "Firefox View tab exists"); + ok(w.FirefoxViewHandler.tab?.hidden, "Firefox View tab is hidden"); is( - w.gBrowser.tabs.indexOf(w.gFirefoxViewTab), + w.gBrowser.tabs.indexOf(w.FirefoxViewHandler.tab), 0, "Firefox View tab is the first tab" ); is( - w.gBrowser.visibleTabs.indexOf(w.gFirefoxViewTab), + w.gBrowser.visibleTabs.indexOf(w.FirefoxViewHandler.tab), -1, "Firefox View tab is not in the list of visible tabs" ); @@ -34,7 +34,7 @@ function assertFirefoxViewTab(w = window) { async function openFirefoxViewTab(w = window) { ok( - !w.gFirefoxViewTab, + !w.FirefoxViewHandler.tab, "Firefox View tab doesn't exist prior to clicking the button" ); info("Clicking the Firefox View button"); @@ -45,14 +45,14 @@ async function openFirefoxViewTab(w = window) { ); assertFirefoxViewTab(w); is(w.gBrowser.tabContainer.selectedIndex, 0, "Firefox View tab is selected"); - await BrowserTestUtils.browserLoaded(w.gFirefoxViewTab.linkedBrowser); - return w.gFirefoxViewTab; + await BrowserTestUtils.browserLoaded(w.FirefoxViewHandler.tab.linkedBrowser); + return w.FirefoxViewHandler.tab; } function closeFirefoxViewTab(w = window) { - w.gBrowser.removeTab(w.gFirefoxViewTab); + w.gBrowser.removeTab(w.FirefoxViewHandler.tab); ok( - !w.gFirefoxViewTab, + !w.FirefoxViewHandler.tab, "Reference to Firefox View tab got removed when closing the tab" ); } @@ -98,7 +98,7 @@ add_task(async function accel_w_behavior() { let win = await BrowserTestUtils.openNewBrowserWindow(); await openFirefoxViewTab(win); EventUtils.synthesizeKey("w", { accelKey: true }, win); - ok(!win.gFirefoxViewTab, "Accel+w closed the Firefox View tab"); + ok(!win.FirefoxViewHandler.tab, "Accel+w closed the Firefox View tab"); await openFirefoxViewTab(win); win.gBrowser.selectedTab = win.gBrowser.visibleTabs[0]; info( diff --git a/browser/components/sessionstore/SessionStore.jsm b/browser/components/sessionstore/SessionStore.jsm index 94edaf6eebef..9b2730f1d525 100644 --- a/browser/components/sessionstore/SessionStore.jsm +++ b/browser/components/sessionstore/SessionStore.jsm @@ -2547,7 +2547,7 @@ var SessionStoreInternal = { if (!isPrivateWindow && tabState.isPrivate) { return; } - if (aTab == aWindow.gFirefoxViewTab) { + if (aTab == aWindow.FirefoxViewHandler.tab) { return; } @@ -4130,7 +4130,7 @@ var SessionStoreInternal = { // update the internal state data for this window for (let tab of tabs) { - if (tab == aWindow.gFirefoxViewTab) { + if (tab == aWindow.FirefoxViewHandler.tab) { continue; } let tabData = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab)); diff --git a/browser/themes/shared/tabs.css b/browser/themes/shared/tabs.css index fea6a7b8e368..801565a83263 100644 --- a/browser/themes/shared/tabs.css +++ b/browser/themes/shared/tabs.css @@ -681,7 +681,7 @@ } } -/* Firefox View button */ +/* Firefox View button and menu item */ :root:not([privatebrowsingmode=temporary]) :is(#firefox-view-button, #wrapper-firefox-view-button) + #tabbrowser-tabs { border-inline-start: 1px solid color-mix(in srgb, currentColor 25%, transparent); @@ -689,7 +689,7 @@ margin-inline-start: 4px; } -:root[privatebrowsingmode=temporary] #firefox-view-button { +:root[privatebrowsingmode=temporary] :is(#firefox-view-button, #menu_openFirefoxView) { display: none; } From 2791053ad5d7a6999adc9adcc5e5faaf442584ff Mon Sep 17 00:00:00 2001 From: sakar Date: Wed, 15 Jun 2022 21:53:47 +0000 Subject: [PATCH 34/64] Bug 1772841 - Disabled datetime input field should not be focusable by click. r=emilio Differential Revision: https://phabricator.services.mozilla.com/D149416 --- dom/html/test/forms/mochitest.ini | 1 + .../test_input_datetime_disabled_focus.html | 42 +++++++++++++++++++ .../forms/test_input_datetime_tabindex.html | 2 - toolkit/content/widgets/datetimebox.js | 12 +++--- 4 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 dom/html/test/forms/test_input_datetime_disabled_focus.html diff --git a/dom/html/test/forms/mochitest.ini b/dom/html/test/forms/mochitest.ini index 50fc01bf945b..745a946e3df2 100644 --- a/dom/html/test/forms/mochitest.ini +++ b/dom/html/test/forms/mochitest.ini @@ -37,6 +37,7 @@ support-files = file_double_submit.html [test_input_date_bad_input.html] [test_input_date_key_events.html] [test_input_datetime_input_change_events.html] +[test_input_datetime_disabled_focus.html] [test_input_datetime_focus_blur.html] [test_input_datetime_focus_blur_events.html] [test_input_datetime_focus_state.html] diff --git a/dom/html/test/forms/test_input_datetime_disabled_focus.html b/dom/html/test/forms/test_input_datetime_disabled_focus.html new file mode 100644 index 000000000000..19cbdbef2732 --- /dev/null +++ b/dom/html/test/forms/test_input_datetime_disabled_focus.html @@ -0,0 +1,42 @@ + +Test for bug 1772841 + + + +Mozilla Bug 1772841 +
+ + + + + + + +
+ diff --git a/dom/html/test/forms/test_input_datetime_tabindex.html b/dom/html/test/forms/test_input_datetime_tabindex.html index 3e763fe8589f..60dff9177d35 100644 --- a/dom/html/test/forms/test_input_datetime_tabindex.html +++ b/dom/html/test/forms/test_input_datetime_tabindex.html @@ -79,7 +79,6 @@ function testTabindex(type) { checkInnerTextboxTabindex(input1, 0); checkInnerTextboxTabindex(input2, -1); checkInnerTextboxTabindex(input3, 0); - checkInnerTextboxTabindex(input4, -1); // Changing the tabindex attribute dynamically. input3.setAttribute("tabindex", "-1"); @@ -92,7 +91,6 @@ function testTabindex(type) { "disabled element should not be tabbable"); checkInnerTextboxTabindex(input3, -1); - checkInnerTextboxTabindex(input4, -1); } function test() { diff --git a/toolkit/content/widgets/datetimebox.js b/toolkit/content/widgets/datetimebox.js index d2fa5946b19e..945f4d6b2fbb 100644 --- a/toolkit/content/widgets/datetimebox.js +++ b/toolkit/content/widgets/datetimebox.js @@ -346,7 +346,7 @@ this.DateTimeBoxWidget = class { field.textContent = aPlaceHolder; field.placeholder = aPlaceHolder; field.setAttribute("aria-valuetext", ""); - field.tabIndex = this.editFieldTabIndex(); + this.setFieldTabIndexAttribute(field); field.setAttribute("readonly", this.mInputElement.readOnly); field.setAttribute("disabled", this.mInputElement.disabled); @@ -447,11 +447,12 @@ this.DateTimeBoxWidget = class { this.mIsPickerOpen = aIsOpen; } - editFieldTabIndex() { + setFieldTabIndexAttribute(field) { if (this.mInputElement.disabled) { - return -1; + field.removeAttribute("tabindex"); + } else { + field.tabIndex = this.mInputElement.tabIndex; } - return this.mInputElement.tabIndex; } updateEditAttributes() { @@ -472,8 +473,7 @@ this.DateTimeBoxWidget = class { child.disabled = this.mInputElement.disabled; child.readOnly = this.mInputElement.readOnly; - // tabIndex as a property works on all relevant elements. - child.tabIndex = this.editFieldTabIndex(); + this.setFieldTabIndexAttribute(child); } this.mResetButton.disabled = From 9a86df3ec442191bde5412ccf98db6a1bdae1720 Mon Sep 17 00:00:00 2001 From: David Parks Date: Wed, 15 Jun 2022 21:59:40 +0000 Subject: [PATCH 35/64] Bug 1773513: Ignore Alt-key sequences when hiding the cursor on Windows r=cmartin On Windows 11, Alt-Space was opening a system context menu while also hiding the mouse cursor. Differential Revision: https://phabricator.services.mozilla.com/D148841 --- widget/windows/nsWindow.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/widget/windows/nsWindow.cpp b/widget/windows/nsWindow.cpp index b8c231561f11..7866d372db0e 100644 --- a/widget/windows/nsWindow.cpp +++ b/widget/windows/nsWindow.cpp @@ -674,8 +674,9 @@ static bool IsMouseVanishKey(WPARAM aVirtKey) { case VK_NEXT: // PgDn return false; default: - // Return true unless Ctrl is pressed - return (GetKeyState(VK_CONTROL) & 0x8000) != 0x8000; + // Return true unless Ctrl or Alt is pressed + return (GetKeyState(VK_CONTROL) & 0x8000) != 0x8000 && + (GetKeyState(VK_MENU) & 0x8000) != 0x8000; } } From 34cf638dd6e0b7c65bda7ebb47a3a8e4e2ca0206 Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Wed, 15 Jun 2022 22:03:20 +0000 Subject: [PATCH 36/64] Bug 1773399 - Update getrandom to 0.2.7. r=emilio,supply-chain-reviewers,bholley Differential Revision: https://phabricator.services.mozilla.com/D149326 --- Cargo.lock | 19 +- Cargo.toml | 3 + build/rust/wasi/Cargo.toml | 17 + build/rust/wasi/lib.rs | 5 + supply-chain/audits.toml | 5 + supply-chain/config.toml | 2 +- .../rust/getrandom/.cargo-checksum.json | 2 +- third_party/rust/getrandom/CHANGELOG.md | 18 +- third_party/rust/getrandom/Cargo.toml | 38 +- third_party/rust/getrandom/src/bsd_arandom.rs | 1 + third_party/rust/getrandom/src/dragonfly.rs | 1 + third_party/rust/getrandom/src/error.rs | 4 - third_party/rust/getrandom/src/lib.rs | 2 +- .../rust/getrandom/src/linux_android.rs | 1 + third_party/rust/getrandom/src/macos.rs | 1 + third_party/rust/getrandom/src/openbsd.rs | 1 + .../rust/getrandom/src/solaris_illumos.rs | 1 + third_party/rust/getrandom/src/util_libc.rs | 57 +- third_party/rust/getrandom/src/wasi.rs | 12 +- third_party/rust/getrandom/src/windows.rs | 1 + third_party/rust/wasi/.cargo-checksum.json | 2 +- third_party/rust/wasi/Cargo.toml | 11 +- third_party/rust/wasi/README.md | 18 + third_party/rust/wasi/src/error.rs | 51 - third_party/rust/wasi/src/lib.rs | 1 - third_party/rust/wasi/src/lib_generated.rs | 2296 ++++++++++------- 26 files changed, 1578 insertions(+), 992 deletions(-) create mode 100644 build/rust/wasi/Cargo.toml create mode 100644 build/rust/wasi/lib.rs delete mode 100644 third_party/rust/wasi/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index edb09f488077..1a1b14d1546e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2112,13 +2112,13 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" +checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" dependencies = [ "cfg-if 1.0.0", "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", ] [[package]] @@ -5251,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" dependencies = [ "libc", - "wasi", + "wasi 0.10.0+wasi-snapshot-preview999", "winapi", ] @@ -5843,9 +5843,16 @@ dependencies = [ [[package]] name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" +version = "0.10.0+wasi-snapshot-preview999" +dependencies = [ + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" diff --git a/Cargo.toml b/Cargo.toml index 3af9a576f8c6..7aca1c1071d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -135,6 +135,9 @@ parking_lot = { path = "build/rust/parking_lot" } # Override tinyvec with smallvec tinyvec = { path = "build/rust/tinyvec" } +# Patch wasi 0.10 to 0.11 +wasi = { path = "build/rust/wasi" } + # Patch autocfg to hide rustc output. Workaround for https://github.com/cuviper/autocfg/issues/30 autocfg = { path = "third_party/rust/autocfg" } diff --git a/build/rust/wasi/Cargo.toml b/build/rust/wasi/Cargo.toml new file mode 100644 index 000000000000..e1f392a96104 --- /dev/null +++ b/build/rust/wasi/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview999" +edition = "2018" +license = "MPL-2.0" + +[lib] +path = "lib.rs" + +[dependencies.wasi] +version = "0.11" +default-features = false + +[features] +default = ["wasi/default"] +rustc-dep-of-std = ["wasi/rustc-dep-of-std"] +std = ["wasi/std"] diff --git a/build/rust/wasi/lib.rs b/build/rust/wasi/lib.rs new file mode 100644 index 000000000000..1bb120620291 --- /dev/null +++ b/build/rust/wasi/lib.rs @@ -0,0 +1,5 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +pub use wasi::*; diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml index 82b7dd2a56ac..3c4b7f1e8d4c 100644 --- a/supply-chain/audits.toml +++ b/supply-chain/audits.toml @@ -34,6 +34,11 @@ who = "Mike Hommey " criteria = "safe-to-run" delta = "1.1.0 -> 1.1.1" +[[audits.getrandom]] +who = "Mike Hommey " +criteria = "safe-to-deploy" +delta = "0.2.6 -> 0.2.7" + [[audits.glean]] who = "Jan-Erik Rediger " criteria = "safe-to-deploy" diff --git a/supply-chain/config.toml b/supply-chain/config.toml index 4a52079fd815..11dc0e4f4577 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -1612,7 +1612,7 @@ version = "0.3.2" criteria = "safe-to-run" [[unaudited.wasi]] -version = "0.10.0+wasi-snapshot-preview1" +version = "0.11.0+wasi-snapshot-preview1" criteria = "safe-to-deploy" [[unaudited.wasm-encoder]] diff --git a/third_party/rust/getrandom/.cargo-checksum.json b/third_party/rust/getrandom/.cargo-checksum.json index 7bdcc1bc4ff2..adfe6c9e5198 100644 --- a/third_party/rust/getrandom/.cargo-checksum.json +++ b/third_party/rust/getrandom/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"e972a70c9a4729acbd6bd81ca0c3e03944cab242743b308d124d64b3552f8e63","Cargo.toml":"66283df4cc6406f65b46dded3469d23f9d1c6372a0385af8cdcde9da1b6cf5d9","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d2ee195acd80c7d1364a369ad0d2dad46f5f9f973f9d3960367413fd87acfcd6","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"28f3f7ac4f093dfb6cd2c8e7e0714f16d0f03f8c658e56caa8fe9bd03b1ff39b","src/error.rs":"110ffe8a2c6b0fa46a4e317e837efe617b343f250fedac61bcabc3c5250e7432","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"674af2d277b66ecf2e49e1059638abd58db089df095b8b65d9e347782e4bb1e0","src/linux_android.rs":"39cb80999c8534145240a350976d261b8924436bf9a4563960c7bd8c2c83c773","src/macos.rs":"b692f2fcc2319a5195f47751d5bd7dd87c7c24a61d14fa4e3dbc992ae66212b7","src/openbsd.rs":"066b2dd395c190444a658bb0b52a052eabbd68ea5a534fb729c7e5373abc0a6a","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"9c7004446fabe5a7a21c73d5a65d7e2115b5bd1d1dbb735c984cab3dba239785","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"9fd636b23121a86630f0c7891a310444f5b1bb29b0013290e130b79ed1e1f79e","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"02b3a75613dc80444847675ecfea59f390c2597ce1d3334612a8dba71f6082de","src/windows.rs":"e3c8f033d5d2a6b8abc5c92b005232f5aca8ce941bd94964a0f58f2436af9990","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"} \ No newline at end of file +{"files":{"CHANGELOG.md":"1289f7318d266dca92eceb373c5ff6ee81fa867a6f180ad57759d37df9fcad91","Cargo.toml":"2b0b1b62739f57c58e5069f90b70003f56f3242517d14ac1f875b9f36d227e6e","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d90c419d4def20f83e7535cd3f5ec07035045011a50c3652951d196a120c5d3e","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"47f933eac189f6ea48ecf021efd0747ebce1b43d1bece6bbf72a951bab705987","src/error.rs":"f87ce17f9299f9b59b47306dab25ed01d720a0ba53363f52b46b50e2f5e49e36","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"6f61a660fe35864a2fc8ed2fe29b1c2ddf5d29854a2871daade66f0059f65b8e","src/linux_android.rs":"ec24575aa4ae71b6991290dadfdea931b05397c3faababf24bd794f1a9624835","src/macos.rs":"6c09827ad5292cd022e063efa79523bfdb50ed08b9867ebaa007cd321b8d218e","src/openbsd.rs":"450a23ead462d4a840fee4aa0bfdab1e3d88c8f48e4bb608d457429ddeca69c0","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"d52fee9dd7d661f960c01894edd563c1ff8a512c111f7803092d9aa2ff98718e","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"2a63ac0e6dab16b85c4728b79a16e0640301e8b876f151b0a1db0b4394fa219f","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"dfdd0a870581948bd03abe64d49ca4295d9cfa26e09b97a526fd5e17148ad9ca","src/windows.rs":"d0b4f2afd1959660aa9abcd9477764bd7dc0b7d7048aee748804b37963c77c6f","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"} \ No newline at end of file diff --git a/third_party/rust/getrandom/CHANGELOG.md b/third_party/rust/getrandom/CHANGELOG.md index 4ab267ae06cd..b25704947a03 100644 --- a/third_party/rust/getrandom/CHANGELOG.md +++ b/third_party/rust/getrandom/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.7] - 2022-06-14 +### Changed +- Update `wasi` dependency to `0.11` [#253] + +### Fixed +- Use `AtomicPtr` instead of `AtomicUsize` for Strict Provenance compatibility. [#263] + +### Documentation +- Add comments explaining use of fallback mechanisms [#257] [#260] + +[#263]: https://github.com/rust-random/getrandom/pull/263 +[#260]: https://github.com/rust-random/getrandom/pull/260 +[#253]: https://github.com/rust-random/getrandom/pull/253 +[#257]: https://github.com/rust-random/getrandom/pull/257 + ## [0.2.6] - 2022-03-28 ### Added - Nintendo 3DS (`armv6k-nintendo-3ds`) support [#248] @@ -291,7 +306,8 @@ Publish initial implementation. ## [0.0.0] - 2019-01-19 Publish an empty template library. -[0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 +[0.2.7]: https://github.com/rust-random/getrandom/compare/v0.2.6...v0.2.7 +[0.2.6]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 [0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.4...v0.2.5 [0.2.4]: https://github.com/rust-random/getrandom/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/rust-random/getrandom/compare/v0.2.2...v0.2.3 diff --git a/third_party/rust/getrandom/Cargo.toml b/third_party/rust/getrandom/Cargo.toml index 0a664244e753..9b9c0880abb8 100644 --- a/third_party/rust/getrandom/Cargo.toml +++ b/third_party/rust/getrandom/Cargo.toml @@ -12,17 +12,29 @@ [package] edition = "2018" name = "getrandom" -version = "0.2.6" +version = "0.2.7" authors = ["The Rand Project Developers"] exclude = [".*"] description = "A small cross-platform library for retrieving random data from system source" documentation = "https://docs.rs/getrandom" -categories = ["os", "no-std"] +readme = "README.md" +categories = [ + "os", + "no-std", +] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-random/getrandom" + [package.metadata.docs.rs] -features = ["std", "custom"] -rustdoc-args = ["--cfg", "docsrs"] +features = [ + "std", + "custom", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] + [dependencies.cfg-if] version = "1" @@ -37,11 +49,20 @@ package = "rustc-std-workspace-core" [features] custom = [] -js = ["wasm-bindgen", "js-sys"] +js = [ + "wasm-bindgen", + "js-sys", +] rdrand = [] -rustc-dep-of-std = ["compiler_builtins", "core", "libc/rustc-dep-of-std", "wasi/rustc-dep-of-std"] +rustc-dep-of-std = [ + "compiler_builtins", + "core", + "libc/rustc-dep-of-std", + "wasi/rustc-dep-of-std", +] std = [] test-in-browser = [] + [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dependencies.js-sys] version = "0.3" optional = true @@ -50,10 +71,13 @@ optional = true version = "0.2.62" optional = true default-features = false + [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dev-dependencies.wasm-bindgen-test] version = "0.3.18" + [target."cfg(target_os = \"wasi\")".dependencies.wasi] -version = "0.10" +version = "0.11" + [target."cfg(unix)".dependencies.libc] version = "0.2.120" default-features = false diff --git a/third_party/rust/getrandom/src/bsd_arandom.rs b/third_party/rust/getrandom/src/bsd_arandom.rs index f26f2609c36b..d44121254111 100644 --- a/third_party/rust/getrandom/src/bsd_arandom.rs +++ b/third_party/rust/getrandom/src/bsd_arandom.rs @@ -31,6 +31,7 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { } pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0 #[cfg(target_os = "freebsd")] { use crate::util_libc::Weak; diff --git a/third_party/rust/getrandom/src/dragonfly.rs b/third_party/rust/getrandom/src/dragonfly.rs index f27e906908e9..8daaa40489cf 100644 --- a/third_party/rust/getrandom/src/dragonfly.rs +++ b/third_party/rust/getrandom/src/dragonfly.rs @@ -17,6 +17,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; + // getrandom(2) was introduced in DragonflyBSD 5.7 if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); diff --git a/third_party/rust/getrandom/src/error.rs b/third_party/rust/getrandom/src/error.rs index 6615753768aa..b5ab2bb18370 100644 --- a/third_party/rust/getrandom/src/error.rs +++ b/third_party/rust/getrandom/src/error.rs @@ -109,10 +109,6 @@ cfg_if! { let idx = buf.iter().position(|&b| b == 0).unwrap_or(n); core::str::from_utf8(&buf[..idx]).ok() } - } else if #[cfg(target_os = "wasi")] { - fn os_err(errno: i32, _buf: &mut [u8]) -> Option { - wasi::Error::from_raw_error(errno as _) - } } else { fn os_err(_errno: i32, _buf: &mut [u8]) -> Option<&str> { None diff --git a/third_party/rust/getrandom/src/lib.rs b/third_party/rust/getrandom/src/lib.rs index 888b9a51057a..c62056e55613 100644 --- a/third_party/rust/getrandom/src/lib.rs +++ b/third_party/rust/getrandom/src/lib.rs @@ -149,7 +149,7 @@ #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/getrandom/0.2.6" + html_root_url = "https://docs.rs/getrandom/0.2.7" )] #![no_std] #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)] diff --git a/third_party/rust/getrandom/src/linux_android.rs b/third_party/rust/getrandom/src/linux_android.rs index 5508fdd06ab3..4270b67c65df 100644 --- a/third_party/rust/getrandom/src/linux_android.rs +++ b/third_party/rust/getrandom/src/linux_android.rs @@ -14,6 +14,7 @@ use crate::{ }; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in Linux 3.17 static HAS_GETRANDOM: LazyBool = LazyBool::new(); if HAS_GETRANDOM.unsync_init(is_getrandom_available) { sys_fill_exact(dest, |buf| unsafe { diff --git a/third_party/rust/getrandom/src/macos.rs b/third_party/rust/getrandom/src/macos.rs index 585a35abd074..671a053bffc6 100644 --- a/third_party/rust/getrandom/src/macos.rs +++ b/third_party/rust/getrandom/src/macos.rs @@ -17,6 +17,7 @@ use core::mem; type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getentropy(2) was added in 10.12, Rust supports 10.7+ static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") }; if let Some(fptr) = GETENTROPY.ptr() { let func: GetEntropyFn = unsafe { mem::transmute(fptr) }; diff --git a/third_party/rust/getrandom/src/openbsd.rs b/third_party/rust/getrandom/src/openbsd.rs index c8d28b3d8882..41371736f119 100644 --- a/third_party/rust/getrandom/src/openbsd.rs +++ b/third_party/rust/getrandom/src/openbsd.rs @@ -10,6 +10,7 @@ use crate::{util_libc::last_os_error, Error}; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally. for chunk in dest.chunks_mut(256) { let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) }; if ret == -1 { diff --git a/third_party/rust/getrandom/src/solaris_illumos.rs b/third_party/rust/getrandom/src/solaris_illumos.rs index 2d1b767bb0c2..cf3067d6d80c 100644 --- a/third_party/rust/getrandom/src/solaris_illumos.rs +++ b/third_party/rust/getrandom/src/solaris_illumos.rs @@ -30,6 +30,7 @@ type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in Solaris 11.3 for Illumos in 2015. static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { mem::transmute(fptr) }; diff --git a/third_party/rust/getrandom/src/util_libc.rs b/third_party/rust/getrandom/src/util_libc.rs index 6df1cd7da80a..d057071a7468 100644 --- a/third_party/rust/getrandom/src/util_libc.rs +++ b/third_party/rust/getrandom/src/util_libc.rs @@ -6,8 +6,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] -use crate::{util::LazyUsize, Error}; -use core::{num::NonZeroU32, ptr::NonNull}; +use crate::Error; +use core::{ + num::NonZeroU32, + ptr::NonNull, + sync::atomic::{fence, AtomicPtr, Ordering}, +}; +use libc::c_void; cfg_if! { if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] { @@ -76,29 +81,57 @@ pub fn sys_fill_exact( // A "weak" binding to a C function that may or may not be present at runtime. // Used for supporting newer OS features while still building on older systems. -// F must be a function pointer of type `unsafe extern "C" fn`. Based off of the -// weak! macro in libstd. +// Based off of the DlsymWeak struct in libstd: +// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84 +// except that the caller must manually cast self.ptr() to a function pointer. pub struct Weak { name: &'static str, - addr: LazyUsize, + addr: AtomicPtr, } impl Weak { + // A non-null pointer value which indicates we are uninitialized. This + // constant should ideally not be a valid address of a function pointer. + // However, if by chance libc::dlsym does return UNINIT, there will not + // be undefined behavior. libc::dlsym will just be called each time ptr() + // is called. This would be inefficient, but correct. + // TODO: Replace with core::ptr::invalid_mut(1) when that is stable. + const UNINIT: *mut c_void = 1 as *mut c_void; + // Construct a binding to a C function with a given name. This function is // unsafe because `name` _must_ be null terminated. pub const unsafe fn new(name: &'static str) -> Self { Self { name, - addr: LazyUsize::new(), + addr: AtomicPtr::new(Self::UNINIT), } } - // Return a function pointer if present at runtime. Otherwise, return null. - pub fn ptr(&self) -> Option> { - let addr = self.addr.unsync_init(|| unsafe { - libc::dlsym(libc::RTLD_DEFAULT, self.name.as_ptr() as *const _) as usize - }); - NonNull::new(addr as *mut _) + // Return the address of a function if present at runtime. Otherwise, + // return None. Multiple callers can call ptr() concurrently. It will + // always return _some_ value returned by libc::dlsym. However, the + // dlsym function may be called multiple times. + pub fn ptr(&self) -> Option> { + // Despite having only a single atomic variable (self.addr), we still + // cannot always use Ordering::Relaxed, as we need to make sure a + // successful call to dlsym() is "ordered before" any data read through + // the returned pointer (which occurs when the function is called). + // Our implementation mirrors that of the one in libstd, meaning that + // the use of non-Relaxed operations is probably unnecessary. + match self.addr.load(Ordering::Relaxed) { + Self::UNINIT => { + let symbol = self.name.as_ptr() as *const _; + let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) }; + // Synchronizes with the Acquire fence below + self.addr.store(addr, Ordering::Release); + NonNull::new(addr) + } + addr => { + let func = NonNull::new(addr)?; + fence(Ordering::Acquire); + Some(func) + } + } } } diff --git a/third_party/rust/getrandom/src/wasi.rs b/third_party/rust/getrandom/src/wasi.rs index 2d413e020cd8..c5121824a7ef 100644 --- a/third_party/rust/getrandom/src/wasi.rs +++ b/third_party/rust/getrandom/src/wasi.rs @@ -9,15 +9,11 @@ //! Implementation for WASI use crate::Error; use core::num::NonZeroU32; -use wasi::random_get; +use wasi::wasi_snapshot_preview1::random_get; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - unsafe { - random_get(dest.as_mut_ptr(), dest.len()).map_err(|e: wasi::Error| { - // convert wasi's Error into getrandom's NonZeroU32 error - // SAFETY: `wasi::Error` is `NonZeroU16` internally, so `e.raw_error()` - // will never return 0 - NonZeroU32::new_unchecked(e.raw_error() as u32).into() - }) + match unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) } { + 0 => Ok(()), + err => Err(unsafe { NonZeroU32::new_unchecked(err as u32) }.into()), } } diff --git a/third_party/rust/getrandom/src/windows.rs b/third_party/rust/getrandom/src/windows.rs index 643badd07caa..41dc37a5c525 100644 --- a/third_party/rust/getrandom/src/windows.rs +++ b/third_party/rust/getrandom/src/windows.rs @@ -24,6 +24,7 @@ extern "system" { pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { // Prevent overflow of u32 for chunk in dest.chunks_mut(u32::max_value() as usize) { + // BCryptGenRandom was introduced in Windows Vista let ret = unsafe { BCryptGenRandom( ptr::null_mut(), diff --git a/third_party/rust/wasi/.cargo-checksum.json b/third_party/rust/wasi/.cargo-checksum.json index 534dc6e20555..a13fe2be5836 100644 --- a/third_party/rust/wasi/.cargo-checksum.json +++ b/third_party/rust/wasi/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CODE_OF_CONDUCT.md":"a13aaaf393818bd91207c618724d3fb74944ca5161201822a84af951bcf655ef","CONTRIBUTING.md":"2c908a3e263dc35dfed131c02ff907cd72fafb2c2096e4ba9b1e0cbb7a1b76df","Cargo.toml":"0507b220e56fe90becc31c95576b3c42f05b6453659af34e43eaab219274a14b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-Apache-2.0_WITH_LLVM-exception":"268872b9816f90fd8e85db5a28d33f8150ebb8dd016653fb39ef1f94f2686bc5","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","ORG_CODE_OF_CONDUCT.md":"a62b69bf86e605ee1bcbb2f0a12ba79e4cebb6983a7b6491949750aecc4f2178","README.md":"9412b3834687f28f0fae01a6e45b1309733ac92dcf04ef3ef36a823e76a6fed2","SECURITY.md":"4d75afb09dd28eb5982e3a1f768ee398d90204669ceef3240a16b31dcf04148a","src/error.rs":"96818880fab83125079842e35aacb49333ac66699e223f896699e4fdb88b99e8","src/lib.rs":"ce2e7ee6a6e4d5900f3835568b168afc70870d601b2bb94f1a6b9ddd2f046c3a","src/lib_generated.rs":"352b56bdb0f87dc18592a2241b312710c8326a415c2b3e3e7af26a8e36c2d303"},"package":"1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"} \ No newline at end of file +{"files":{"CODE_OF_CONDUCT.md":"a13aaaf393818bd91207c618724d3fb74944ca5161201822a84af951bcf655ef","CONTRIBUTING.md":"2c908a3e263dc35dfed131c02ff907cd72fafb2c2096e4ba9b1e0cbb7a1b76df","Cargo.toml":"7a38e6f90e220716b5b3f82c0a187dfef180db8d1d262250325a655d1b9888e6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-Apache-2.0_WITH_LLVM-exception":"268872b9816f90fd8e85db5a28d33f8150ebb8dd016653fb39ef1f94f2686bc5","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","ORG_CODE_OF_CONDUCT.md":"a62b69bf86e605ee1bcbb2f0a12ba79e4cebb6983a7b6491949750aecc4f2178","README.md":"c021f687a5a61d9c308581401e7aa4454585a30c418abdd02e3a1ef71daa035f","SECURITY.md":"4d75afb09dd28eb5982e3a1f768ee398d90204669ceef3240a16b31dcf04148a","src/lib.rs":"040651dd678b7788d7cc7a8fdc5f50f664d46bd18976bf638bcb4c827a1793d7","src/lib_generated.rs":"130977e4eaac5e9623caba3d5911616051c8b2cee926333213271a25b733a5df"},"package":"9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"} \ No newline at end of file diff --git a/third_party/rust/wasi/Cargo.toml b/third_party/rust/wasi/Cargo.toml index 00fe5b3cd421..c41e35e9ee88 100644 --- a/third_party/rust/wasi/Cargo.toml +++ b/third_party/rust/wasi/Cargo.toml @@ -3,17 +3,16 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" +version = "0.11.0+wasi-snapshot-preview1" authors = ["The Cranelift Project Developers"] description = "Experimental WASI API bindings for Rust" documentation = "https://docs.rs/wasi" diff --git a/third_party/rust/wasi/README.md b/third_party/rust/wasi/README.md index e92f50e3f5ca..801f56a4e023 100644 --- a/third_party/rust/wasi/README.md +++ b/third_party/rust/wasi/README.md @@ -64,6 +64,24 @@ $ cargo wasi run Hello, World! ``` +# Development + +The bulk of the `wasi` crate is generated by the `witx-bindgen` tool, which lives at +`crates/witx-bindgen` and is part of the cargo workspace. + +The `src/lib_generated.rs` file can be re-generated with the following +command: + +``` +cargo run -p witx-bindgen -- crates/witx-bindgen/WASI/phases/snapshot/witx/wasi_snapshot_preview1.witx > src/lib_generated.rs +``` + +Note that this uses the WASI standard repository as a submodule. If you do not +have this submodule present in your source tree, run: +``` +git submodule update --init +``` + # License This project is licensed under the Apache 2.0 license with the LLVM exception. diff --git a/third_party/rust/wasi/src/error.rs b/third_party/rust/wasi/src/error.rs deleted file mode 100644 index 2f2aaf4b90dd..000000000000 --- a/third_party/rust/wasi/src/error.rs +++ /dev/null @@ -1,51 +0,0 @@ -use super::Errno; -use core::fmt; -use core::num::NonZeroU16; - -/// A raw error returned by wasi APIs, internally containing a 16-bit error -/// code. -#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] -pub struct Error { - code: NonZeroU16, -} - -impl Error { - /// Constructs a new error from a raw error code, returning `None` if the - /// error code is zero (which means success). - pub fn from_raw_error(error: Errno) -> Option { - Some(Error { - code: NonZeroU16::new(error)?, - }) - } - - /// Returns the raw error code that this error represents. - pub fn raw_error(&self) -> u16 { - self.code.get() - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} (error {})", - super::strerror(self.code.get()), - self.code - )?; - Ok(()) - } -} - -impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Error") - .field("code", &self.code) - .field("message", &super::strerror(self.code.get())) - .finish() - } -} - -#[cfg(feature = "std")] -extern crate std; -#[cfg(feature = "std")] -impl std::error::Error for Error {} diff --git a/third_party/rust/wasi/src/lib.rs b/third_party/rust/wasi/src/lib.rs index 51f488907f82..0df207b60e5f 100644 --- a/third_party/rust/wasi/src/lib.rs +++ b/third_party/rust/wasi/src/lib.rs @@ -31,7 +31,6 @@ #![no_std] -mod error; mod lib_generated; pub use lib_generated::*; diff --git a/third_party/rust/wasi/src/lib_generated.rs b/third_party/rust/wasi/src/lib_generated.rs index 422794153d86..641528178f6c 100644 --- a/third_party/rust/wasi/src/lib_generated.rs +++ b/third_party/rust/wasi/src/lib_generated.rs @@ -1,335 +1,490 @@ // This file is automatically generated, DO NOT EDIT // -// To regenerate this file run the `crates/generate-raw` command +// To regenerate this file run the `crates/witx-bindgen` command +use core::fmt; use core::mem::MaybeUninit; - -pub use crate::error::Error; -pub type Result = core::result::Result; pub type Size = usize; pub type Filesize = u64; pub type Timestamp = u64; -pub type Clockid = u32; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Clockid(u32); /// The clock measuring real time. Time value zero corresponds with /// 1970-01-01T00:00:00Z. -pub const CLOCKID_REALTIME: Clockid = 0; +pub const CLOCKID_REALTIME: Clockid = Clockid(0); /// The store-wide monotonic clock, which is defined as a clock measuring /// real time, whose value cannot be adjusted and which cannot have negative /// clock jumps. The epoch of this clock is undefined. The absolute time /// value of this clock therefore has no meaning. -pub const CLOCKID_MONOTONIC: Clockid = 1; +pub const CLOCKID_MONOTONIC: Clockid = Clockid(1); /// The CPU-time clock associated with the current process. -pub const CLOCKID_PROCESS_CPUTIME_ID: Clockid = 2; +pub const CLOCKID_PROCESS_CPUTIME_ID: Clockid = Clockid(2); /// The CPU-time clock associated with the current thread. -pub const CLOCKID_THREAD_CPUTIME_ID: Clockid = 3; -pub type Errno = u16; -/// No error occurred. System call completed successfully. -pub const ERRNO_SUCCESS: Errno = 0; -/// Argument list too long. -pub const ERRNO_2BIG: Errno = 1; -/// Permission denied. -pub const ERRNO_ACCES: Errno = 2; -/// Address in use. -pub const ERRNO_ADDRINUSE: Errno = 3; -/// Address not available. -pub const ERRNO_ADDRNOTAVAIL: Errno = 4; -/// Address family not supported. -pub const ERRNO_AFNOSUPPORT: Errno = 5; -/// Resource unavailable, or operation would block. -pub const ERRNO_AGAIN: Errno = 6; -/// Connection already in progress. -pub const ERRNO_ALREADY: Errno = 7; -/// Bad file descriptor. -pub const ERRNO_BADF: Errno = 8; -/// Bad message. -pub const ERRNO_BADMSG: Errno = 9; -/// Device or resource busy. -pub const ERRNO_BUSY: Errno = 10; -/// Operation canceled. -pub const ERRNO_CANCELED: Errno = 11; -/// No child processes. -pub const ERRNO_CHILD: Errno = 12; -/// Connection aborted. -pub const ERRNO_CONNABORTED: Errno = 13; -/// Connection refused. -pub const ERRNO_CONNREFUSED: Errno = 14; -/// Connection reset. -pub const ERRNO_CONNRESET: Errno = 15; -/// Resource deadlock would occur. -pub const ERRNO_DEADLK: Errno = 16; -/// Destination address required. -pub const ERRNO_DESTADDRREQ: Errno = 17; -/// Mathematics argument out of domain of function. -pub const ERRNO_DOM: Errno = 18; -/// Reserved. -pub const ERRNO_DQUOT: Errno = 19; -/// File exists. -pub const ERRNO_EXIST: Errno = 20; -/// Bad address. -pub const ERRNO_FAULT: Errno = 21; -/// File too large. -pub const ERRNO_FBIG: Errno = 22; -/// Host is unreachable. -pub const ERRNO_HOSTUNREACH: Errno = 23; -/// Identifier removed. -pub const ERRNO_IDRM: Errno = 24; -/// Illegal byte sequence. -pub const ERRNO_ILSEQ: Errno = 25; -/// Operation in progress. -pub const ERRNO_INPROGRESS: Errno = 26; -/// Interrupted function. -pub const ERRNO_INTR: Errno = 27; -/// Invalid argument. -pub const ERRNO_INVAL: Errno = 28; -/// I/O error. -pub const ERRNO_IO: Errno = 29; -/// Socket is connected. -pub const ERRNO_ISCONN: Errno = 30; -/// Is a directory. -pub const ERRNO_ISDIR: Errno = 31; -/// Too many levels of symbolic links. -pub const ERRNO_LOOP: Errno = 32; -/// File descriptor value too large. -pub const ERRNO_MFILE: Errno = 33; -/// Too many links. -pub const ERRNO_MLINK: Errno = 34; -/// Message too large. -pub const ERRNO_MSGSIZE: Errno = 35; -/// Reserved. -pub const ERRNO_MULTIHOP: Errno = 36; -/// Filename too long. -pub const ERRNO_NAMETOOLONG: Errno = 37; -/// Network is down. -pub const ERRNO_NETDOWN: Errno = 38; -/// Connection aborted by network. -pub const ERRNO_NETRESET: Errno = 39; -/// Network unreachable. -pub const ERRNO_NETUNREACH: Errno = 40; -/// Too many files open in system. -pub const ERRNO_NFILE: Errno = 41; -/// No buffer space available. -pub const ERRNO_NOBUFS: Errno = 42; -/// No such device. -pub const ERRNO_NODEV: Errno = 43; -/// No such file or directory. -pub const ERRNO_NOENT: Errno = 44; -/// Executable file format error. -pub const ERRNO_NOEXEC: Errno = 45; -/// No locks available. -pub const ERRNO_NOLCK: Errno = 46; -/// Reserved. -pub const ERRNO_NOLINK: Errno = 47; -/// Not enough space. -pub const ERRNO_NOMEM: Errno = 48; -/// No message of the desired type. -pub const ERRNO_NOMSG: Errno = 49; -/// Protocol not available. -pub const ERRNO_NOPROTOOPT: Errno = 50; -/// No space left on device. -pub const ERRNO_NOSPC: Errno = 51; -/// Function not supported. -pub const ERRNO_NOSYS: Errno = 52; -/// The socket is not connected. -pub const ERRNO_NOTCONN: Errno = 53; -/// Not a directory or a symbolic link to a directory. -pub const ERRNO_NOTDIR: Errno = 54; -/// Directory not empty. -pub const ERRNO_NOTEMPTY: Errno = 55; -/// State not recoverable. -pub const ERRNO_NOTRECOVERABLE: Errno = 56; -/// Not a socket. -pub const ERRNO_NOTSOCK: Errno = 57; -/// Not supported, or operation not supported on socket. -pub const ERRNO_NOTSUP: Errno = 58; -/// Inappropriate I/O control operation. -pub const ERRNO_NOTTY: Errno = 59; -/// No such device or address. -pub const ERRNO_NXIO: Errno = 60; -/// Value too large to be stored in data type. -pub const ERRNO_OVERFLOW: Errno = 61; -/// Previous owner died. -pub const ERRNO_OWNERDEAD: Errno = 62; -/// Operation not permitted. -pub const ERRNO_PERM: Errno = 63; -/// Broken pipe. -pub const ERRNO_PIPE: Errno = 64; -/// Protocol error. -pub const ERRNO_PROTO: Errno = 65; -/// Protocol not supported. -pub const ERRNO_PROTONOSUPPORT: Errno = 66; -/// Protocol wrong type for socket. -pub const ERRNO_PROTOTYPE: Errno = 67; -/// Result too large. -pub const ERRNO_RANGE: Errno = 68; -/// Read-only file system. -pub const ERRNO_ROFS: Errno = 69; -/// Invalid seek. -pub const ERRNO_SPIPE: Errno = 70; -/// No such process. -pub const ERRNO_SRCH: Errno = 71; -/// Reserved. -pub const ERRNO_STALE: Errno = 72; -/// Connection timed out. -pub const ERRNO_TIMEDOUT: Errno = 73; -/// Text file busy. -pub const ERRNO_TXTBSY: Errno = 74; -/// Cross-device link. -pub const ERRNO_XDEV: Errno = 75; -/// Extension: Capabilities insufficient. -pub const ERRNO_NOTCAPABLE: Errno = 76; -pub(crate) fn strerror(code: u16) -> &'static str { - match code { - ERRNO_SUCCESS => "No error occurred. System call completed successfully.", - ERRNO_2BIG => "Argument list too long.", - ERRNO_ACCES => "Permission denied.", - ERRNO_ADDRINUSE => "Address in use.", - ERRNO_ADDRNOTAVAIL => "Address not available.", - ERRNO_AFNOSUPPORT => "Address family not supported.", - ERRNO_AGAIN => "Resource unavailable, or operation would block.", - ERRNO_ALREADY => "Connection already in progress.", - ERRNO_BADF => "Bad file descriptor.", - ERRNO_BADMSG => "Bad message.", - ERRNO_BUSY => "Device or resource busy.", - ERRNO_CANCELED => "Operation canceled.", - ERRNO_CHILD => "No child processes.", - ERRNO_CONNABORTED => "Connection aborted.", - ERRNO_CONNREFUSED => "Connection refused.", - ERRNO_CONNRESET => "Connection reset.", - ERRNO_DEADLK => "Resource deadlock would occur.", - ERRNO_DESTADDRREQ => "Destination address required.", - ERRNO_DOM => "Mathematics argument out of domain of function.", - ERRNO_DQUOT => "Reserved.", - ERRNO_EXIST => "File exists.", - ERRNO_FAULT => "Bad address.", - ERRNO_FBIG => "File too large.", - ERRNO_HOSTUNREACH => "Host is unreachable.", - ERRNO_IDRM => "Identifier removed.", - ERRNO_ILSEQ => "Illegal byte sequence.", - ERRNO_INPROGRESS => "Operation in progress.", - ERRNO_INTR => "Interrupted function.", - ERRNO_INVAL => "Invalid argument.", - ERRNO_IO => "I/O error.", - ERRNO_ISCONN => "Socket is connected.", - ERRNO_ISDIR => "Is a directory.", - ERRNO_LOOP => "Too many levels of symbolic links.", - ERRNO_MFILE => "File descriptor value too large.", - ERRNO_MLINK => "Too many links.", - ERRNO_MSGSIZE => "Message too large.", - ERRNO_MULTIHOP => "Reserved.", - ERRNO_NAMETOOLONG => "Filename too long.", - ERRNO_NETDOWN => "Network is down.", - ERRNO_NETRESET => "Connection aborted by network.", - ERRNO_NETUNREACH => "Network unreachable.", - ERRNO_NFILE => "Too many files open in system.", - ERRNO_NOBUFS => "No buffer space available.", - ERRNO_NODEV => "No such device.", - ERRNO_NOENT => "No such file or directory.", - ERRNO_NOEXEC => "Executable file format error.", - ERRNO_NOLCK => "No locks available.", - ERRNO_NOLINK => "Reserved.", - ERRNO_NOMEM => "Not enough space.", - ERRNO_NOMSG => "No message of the desired type.", - ERRNO_NOPROTOOPT => "Protocol not available.", - ERRNO_NOSPC => "No space left on device.", - ERRNO_NOSYS => "Function not supported.", - ERRNO_NOTCONN => "The socket is not connected.", - ERRNO_NOTDIR => "Not a directory or a symbolic link to a directory.", - ERRNO_NOTEMPTY => "Directory not empty.", - ERRNO_NOTRECOVERABLE => "State not recoverable.", - ERRNO_NOTSOCK => "Not a socket.", - ERRNO_NOTSUP => "Not supported, or operation not supported on socket.", - ERRNO_NOTTY => "Inappropriate I/O control operation.", - ERRNO_NXIO => "No such device or address.", - ERRNO_OVERFLOW => "Value too large to be stored in data type.", - ERRNO_OWNERDEAD => "Previous owner died.", - ERRNO_PERM => "Operation not permitted.", - ERRNO_PIPE => "Broken pipe.", - ERRNO_PROTO => "Protocol error.", - ERRNO_PROTONOSUPPORT => "Protocol not supported.", - ERRNO_PROTOTYPE => "Protocol wrong type for socket.", - ERRNO_RANGE => "Result too large.", - ERRNO_ROFS => "Read-only file system.", - ERRNO_SPIPE => "Invalid seek.", - ERRNO_SRCH => "No such process.", - ERRNO_STALE => "Reserved.", - ERRNO_TIMEDOUT => "Connection timed out.", - ERRNO_TXTBSY => "Text file busy.", - ERRNO_XDEV => "Cross-device link.", - ERRNO_NOTCAPABLE => "Extension: Capabilities insufficient.", - _ => "Unknown error.", +pub const CLOCKID_THREAD_CPUTIME_ID: Clockid = Clockid(3); +impl Clockid { + pub const fn raw(&self) -> u32 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "REALTIME", + 1 => "MONOTONIC", + 2 => "PROCESS_CPUTIME_ID", + 3 => "THREAD_CPUTIME_ID", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => { + "The clock measuring real time. Time value zero corresponds with +1970-01-01T00:00:00Z." + } + 1 => { + "The store-wide monotonic clock, which is defined as a clock measuring +real time, whose value cannot be adjusted and which cannot have negative +clock jumps. The epoch of this clock is undefined. The absolute time +value of this clock therefore has no meaning." + } + 2 => "The CPU-time clock associated with the current process.", + 3 => "The CPU-time clock associated with the current thread.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } } } +impl fmt::Debug for Clockid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Clockid") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Errno(u16); +/// No error occurred. System call completed successfully. +pub const ERRNO_SUCCESS: Errno = Errno(0); +/// Argument list too long. +pub const ERRNO_2BIG: Errno = Errno(1); +/// Permission denied. +pub const ERRNO_ACCES: Errno = Errno(2); +/// Address in use. +pub const ERRNO_ADDRINUSE: Errno = Errno(3); +/// Address not available. +pub const ERRNO_ADDRNOTAVAIL: Errno = Errno(4); +/// Address family not supported. +pub const ERRNO_AFNOSUPPORT: Errno = Errno(5); +/// Resource unavailable, or operation would block. +pub const ERRNO_AGAIN: Errno = Errno(6); +/// Connection already in progress. +pub const ERRNO_ALREADY: Errno = Errno(7); +/// Bad file descriptor. +pub const ERRNO_BADF: Errno = Errno(8); +/// Bad message. +pub const ERRNO_BADMSG: Errno = Errno(9); +/// Device or resource busy. +pub const ERRNO_BUSY: Errno = Errno(10); +/// Operation canceled. +pub const ERRNO_CANCELED: Errno = Errno(11); +/// No child processes. +pub const ERRNO_CHILD: Errno = Errno(12); +/// Connection aborted. +pub const ERRNO_CONNABORTED: Errno = Errno(13); +/// Connection refused. +pub const ERRNO_CONNREFUSED: Errno = Errno(14); +/// Connection reset. +pub const ERRNO_CONNRESET: Errno = Errno(15); +/// Resource deadlock would occur. +pub const ERRNO_DEADLK: Errno = Errno(16); +/// Destination address required. +pub const ERRNO_DESTADDRREQ: Errno = Errno(17); +/// Mathematics argument out of domain of function. +pub const ERRNO_DOM: Errno = Errno(18); +/// Reserved. +pub const ERRNO_DQUOT: Errno = Errno(19); +/// File exists. +pub const ERRNO_EXIST: Errno = Errno(20); +/// Bad address. +pub const ERRNO_FAULT: Errno = Errno(21); +/// File too large. +pub const ERRNO_FBIG: Errno = Errno(22); +/// Host is unreachable. +pub const ERRNO_HOSTUNREACH: Errno = Errno(23); +/// Identifier removed. +pub const ERRNO_IDRM: Errno = Errno(24); +/// Illegal byte sequence. +pub const ERRNO_ILSEQ: Errno = Errno(25); +/// Operation in progress. +pub const ERRNO_INPROGRESS: Errno = Errno(26); +/// Interrupted function. +pub const ERRNO_INTR: Errno = Errno(27); +/// Invalid argument. +pub const ERRNO_INVAL: Errno = Errno(28); +/// I/O error. +pub const ERRNO_IO: Errno = Errno(29); +/// Socket is connected. +pub const ERRNO_ISCONN: Errno = Errno(30); +/// Is a directory. +pub const ERRNO_ISDIR: Errno = Errno(31); +/// Too many levels of symbolic links. +pub const ERRNO_LOOP: Errno = Errno(32); +/// File descriptor value too large. +pub const ERRNO_MFILE: Errno = Errno(33); +/// Too many links. +pub const ERRNO_MLINK: Errno = Errno(34); +/// Message too large. +pub const ERRNO_MSGSIZE: Errno = Errno(35); +/// Reserved. +pub const ERRNO_MULTIHOP: Errno = Errno(36); +/// Filename too long. +pub const ERRNO_NAMETOOLONG: Errno = Errno(37); +/// Network is down. +pub const ERRNO_NETDOWN: Errno = Errno(38); +/// Connection aborted by network. +pub const ERRNO_NETRESET: Errno = Errno(39); +/// Network unreachable. +pub const ERRNO_NETUNREACH: Errno = Errno(40); +/// Too many files open in system. +pub const ERRNO_NFILE: Errno = Errno(41); +/// No buffer space available. +pub const ERRNO_NOBUFS: Errno = Errno(42); +/// No such device. +pub const ERRNO_NODEV: Errno = Errno(43); +/// No such file or directory. +pub const ERRNO_NOENT: Errno = Errno(44); +/// Executable file format error. +pub const ERRNO_NOEXEC: Errno = Errno(45); +/// No locks available. +pub const ERRNO_NOLCK: Errno = Errno(46); +/// Reserved. +pub const ERRNO_NOLINK: Errno = Errno(47); +/// Not enough space. +pub const ERRNO_NOMEM: Errno = Errno(48); +/// No message of the desired type. +pub const ERRNO_NOMSG: Errno = Errno(49); +/// Protocol not available. +pub const ERRNO_NOPROTOOPT: Errno = Errno(50); +/// No space left on device. +pub const ERRNO_NOSPC: Errno = Errno(51); +/// Function not supported. +pub const ERRNO_NOSYS: Errno = Errno(52); +/// The socket is not connected. +pub const ERRNO_NOTCONN: Errno = Errno(53); +/// Not a directory or a symbolic link to a directory. +pub const ERRNO_NOTDIR: Errno = Errno(54); +/// Directory not empty. +pub const ERRNO_NOTEMPTY: Errno = Errno(55); +/// State not recoverable. +pub const ERRNO_NOTRECOVERABLE: Errno = Errno(56); +/// Not a socket. +pub const ERRNO_NOTSOCK: Errno = Errno(57); +/// Not supported, or operation not supported on socket. +pub const ERRNO_NOTSUP: Errno = Errno(58); +/// Inappropriate I/O control operation. +pub const ERRNO_NOTTY: Errno = Errno(59); +/// No such device or address. +pub const ERRNO_NXIO: Errno = Errno(60); +/// Value too large to be stored in data type. +pub const ERRNO_OVERFLOW: Errno = Errno(61); +/// Previous owner died. +pub const ERRNO_OWNERDEAD: Errno = Errno(62); +/// Operation not permitted. +pub const ERRNO_PERM: Errno = Errno(63); +/// Broken pipe. +pub const ERRNO_PIPE: Errno = Errno(64); +/// Protocol error. +pub const ERRNO_PROTO: Errno = Errno(65); +/// Protocol not supported. +pub const ERRNO_PROTONOSUPPORT: Errno = Errno(66); +/// Protocol wrong type for socket. +pub const ERRNO_PROTOTYPE: Errno = Errno(67); +/// Result too large. +pub const ERRNO_RANGE: Errno = Errno(68); +/// Read-only file system. +pub const ERRNO_ROFS: Errno = Errno(69); +/// Invalid seek. +pub const ERRNO_SPIPE: Errno = Errno(70); +/// No such process. +pub const ERRNO_SRCH: Errno = Errno(71); +/// Reserved. +pub const ERRNO_STALE: Errno = Errno(72); +/// Connection timed out. +pub const ERRNO_TIMEDOUT: Errno = Errno(73); +/// Text file busy. +pub const ERRNO_TXTBSY: Errno = Errno(74); +/// Cross-device link. +pub const ERRNO_XDEV: Errno = Errno(75); +/// Extension: Capabilities insufficient. +pub const ERRNO_NOTCAPABLE: Errno = Errno(76); +impl Errno { + pub const fn raw(&self) -> u16 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "SUCCESS", + 1 => "2BIG", + 2 => "ACCES", + 3 => "ADDRINUSE", + 4 => "ADDRNOTAVAIL", + 5 => "AFNOSUPPORT", + 6 => "AGAIN", + 7 => "ALREADY", + 8 => "BADF", + 9 => "BADMSG", + 10 => "BUSY", + 11 => "CANCELED", + 12 => "CHILD", + 13 => "CONNABORTED", + 14 => "CONNREFUSED", + 15 => "CONNRESET", + 16 => "DEADLK", + 17 => "DESTADDRREQ", + 18 => "DOM", + 19 => "DQUOT", + 20 => "EXIST", + 21 => "FAULT", + 22 => "FBIG", + 23 => "HOSTUNREACH", + 24 => "IDRM", + 25 => "ILSEQ", + 26 => "INPROGRESS", + 27 => "INTR", + 28 => "INVAL", + 29 => "IO", + 30 => "ISCONN", + 31 => "ISDIR", + 32 => "LOOP", + 33 => "MFILE", + 34 => "MLINK", + 35 => "MSGSIZE", + 36 => "MULTIHOP", + 37 => "NAMETOOLONG", + 38 => "NETDOWN", + 39 => "NETRESET", + 40 => "NETUNREACH", + 41 => "NFILE", + 42 => "NOBUFS", + 43 => "NODEV", + 44 => "NOENT", + 45 => "NOEXEC", + 46 => "NOLCK", + 47 => "NOLINK", + 48 => "NOMEM", + 49 => "NOMSG", + 50 => "NOPROTOOPT", + 51 => "NOSPC", + 52 => "NOSYS", + 53 => "NOTCONN", + 54 => "NOTDIR", + 55 => "NOTEMPTY", + 56 => "NOTRECOVERABLE", + 57 => "NOTSOCK", + 58 => "NOTSUP", + 59 => "NOTTY", + 60 => "NXIO", + 61 => "OVERFLOW", + 62 => "OWNERDEAD", + 63 => "PERM", + 64 => "PIPE", + 65 => "PROTO", + 66 => "PROTONOSUPPORT", + 67 => "PROTOTYPE", + 68 => "RANGE", + 69 => "ROFS", + 70 => "SPIPE", + 71 => "SRCH", + 72 => "STALE", + 73 => "TIMEDOUT", + 74 => "TXTBSY", + 75 => "XDEV", + 76 => "NOTCAPABLE", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => "No error occurred. System call completed successfully.", + 1 => "Argument list too long.", + 2 => "Permission denied.", + 3 => "Address in use.", + 4 => "Address not available.", + 5 => "Address family not supported.", + 6 => "Resource unavailable, or operation would block.", + 7 => "Connection already in progress.", + 8 => "Bad file descriptor.", + 9 => "Bad message.", + 10 => "Device or resource busy.", + 11 => "Operation canceled.", + 12 => "No child processes.", + 13 => "Connection aborted.", + 14 => "Connection refused.", + 15 => "Connection reset.", + 16 => "Resource deadlock would occur.", + 17 => "Destination address required.", + 18 => "Mathematics argument out of domain of function.", + 19 => "Reserved.", + 20 => "File exists.", + 21 => "Bad address.", + 22 => "File too large.", + 23 => "Host is unreachable.", + 24 => "Identifier removed.", + 25 => "Illegal byte sequence.", + 26 => "Operation in progress.", + 27 => "Interrupted function.", + 28 => "Invalid argument.", + 29 => "I/O error.", + 30 => "Socket is connected.", + 31 => "Is a directory.", + 32 => "Too many levels of symbolic links.", + 33 => "File descriptor value too large.", + 34 => "Too many links.", + 35 => "Message too large.", + 36 => "Reserved.", + 37 => "Filename too long.", + 38 => "Network is down.", + 39 => "Connection aborted by network.", + 40 => "Network unreachable.", + 41 => "Too many files open in system.", + 42 => "No buffer space available.", + 43 => "No such device.", + 44 => "No such file or directory.", + 45 => "Executable file format error.", + 46 => "No locks available.", + 47 => "Reserved.", + 48 => "Not enough space.", + 49 => "No message of the desired type.", + 50 => "Protocol not available.", + 51 => "No space left on device.", + 52 => "Function not supported.", + 53 => "The socket is not connected.", + 54 => "Not a directory or a symbolic link to a directory.", + 55 => "Directory not empty.", + 56 => "State not recoverable.", + 57 => "Not a socket.", + 58 => "Not supported, or operation not supported on socket.", + 59 => "Inappropriate I/O control operation.", + 60 => "No such device or address.", + 61 => "Value too large to be stored in data type.", + 62 => "Previous owner died.", + 63 => "Operation not permitted.", + 64 => "Broken pipe.", + 65 => "Protocol error.", + 66 => "Protocol not supported.", + 67 => "Protocol wrong type for socket.", + 68 => "Result too large.", + 69 => "Read-only file system.", + 70 => "Invalid seek.", + 71 => "No such process.", + 72 => "Reserved.", + 73 => "Connection timed out.", + 74 => "Text file busy.", + 75 => "Cross-device link.", + 76 => "Extension: Capabilities insufficient.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Errno { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Errno") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} +impl fmt::Display for Errno { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} (error {})", self.name(), self.0) + } +} + +#[cfg(feature = "std")] +extern crate std; +#[cfg(feature = "std")] +impl std::error::Error for Errno {} + pub type Rights = u64; /// The right to invoke `fd_datasync`. /// If `path_open` is set, includes the right to invoke /// `path_open` with `fdflags::dsync`. -pub const RIGHTS_FD_DATASYNC: Rights = 0x1; +pub const RIGHTS_FD_DATASYNC: Rights = 1 << 0; /// The right to invoke `fd_read` and `sock_recv`. /// If `rights::fd_seek` is set, includes the right to invoke `fd_pread`. -pub const RIGHTS_FD_READ: Rights = 0x2; +pub const RIGHTS_FD_READ: Rights = 1 << 1; /// The right to invoke `fd_seek`. This flag implies `rights::fd_tell`. -pub const RIGHTS_FD_SEEK: Rights = 0x4; +pub const RIGHTS_FD_SEEK: Rights = 1 << 2; /// The right to invoke `fd_fdstat_set_flags`. -pub const RIGHTS_FD_FDSTAT_SET_FLAGS: Rights = 0x8; +pub const RIGHTS_FD_FDSTAT_SET_FLAGS: Rights = 1 << 3; /// The right to invoke `fd_sync`. /// If `path_open` is set, includes the right to invoke /// `path_open` with `fdflags::rsync` and `fdflags::dsync`. -pub const RIGHTS_FD_SYNC: Rights = 0x10; +pub const RIGHTS_FD_SYNC: Rights = 1 << 4; /// The right to invoke `fd_seek` in such a way that the file offset /// remains unaltered (i.e., `whence::cur` with offset zero), or to /// invoke `fd_tell`. -pub const RIGHTS_FD_TELL: Rights = 0x20; +pub const RIGHTS_FD_TELL: Rights = 1 << 5; /// The right to invoke `fd_write` and `sock_send`. /// If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`. -pub const RIGHTS_FD_WRITE: Rights = 0x40; +pub const RIGHTS_FD_WRITE: Rights = 1 << 6; /// The right to invoke `fd_advise`. -pub const RIGHTS_FD_ADVISE: Rights = 0x80; +pub const RIGHTS_FD_ADVISE: Rights = 1 << 7; /// The right to invoke `fd_allocate`. -pub const RIGHTS_FD_ALLOCATE: Rights = 0x100; +pub const RIGHTS_FD_ALLOCATE: Rights = 1 << 8; /// The right to invoke `path_create_directory`. -pub const RIGHTS_PATH_CREATE_DIRECTORY: Rights = 0x200; +pub const RIGHTS_PATH_CREATE_DIRECTORY: Rights = 1 << 9; /// If `path_open` is set, the right to invoke `path_open` with `oflags::creat`. -pub const RIGHTS_PATH_CREATE_FILE: Rights = 0x400; +pub const RIGHTS_PATH_CREATE_FILE: Rights = 1 << 10; /// The right to invoke `path_link` with the file descriptor as the /// source directory. -pub const RIGHTS_PATH_LINK_SOURCE: Rights = 0x800; +pub const RIGHTS_PATH_LINK_SOURCE: Rights = 1 << 11; /// The right to invoke `path_link` with the file descriptor as the /// target directory. -pub const RIGHTS_PATH_LINK_TARGET: Rights = 0x1000; +pub const RIGHTS_PATH_LINK_TARGET: Rights = 1 << 12; /// The right to invoke `path_open`. -pub const RIGHTS_PATH_OPEN: Rights = 0x2000; +pub const RIGHTS_PATH_OPEN: Rights = 1 << 13; /// The right to invoke `fd_readdir`. -pub const RIGHTS_FD_READDIR: Rights = 0x4000; +pub const RIGHTS_FD_READDIR: Rights = 1 << 14; /// The right to invoke `path_readlink`. -pub const RIGHTS_PATH_READLINK: Rights = 0x8000; +pub const RIGHTS_PATH_READLINK: Rights = 1 << 15; /// The right to invoke `path_rename` with the file descriptor as the source directory. -pub const RIGHTS_PATH_RENAME_SOURCE: Rights = 0x10000; +pub const RIGHTS_PATH_RENAME_SOURCE: Rights = 1 << 16; /// The right to invoke `path_rename` with the file descriptor as the target directory. -pub const RIGHTS_PATH_RENAME_TARGET: Rights = 0x20000; +pub const RIGHTS_PATH_RENAME_TARGET: Rights = 1 << 17; /// The right to invoke `path_filestat_get`. -pub const RIGHTS_PATH_FILESTAT_GET: Rights = 0x40000; +pub const RIGHTS_PATH_FILESTAT_GET: Rights = 1 << 18; /// The right to change a file's size (there is no `path_filestat_set_size`). /// If `path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`. -pub const RIGHTS_PATH_FILESTAT_SET_SIZE: Rights = 0x80000; +pub const RIGHTS_PATH_FILESTAT_SET_SIZE: Rights = 1 << 19; /// The right to invoke `path_filestat_set_times`. -pub const RIGHTS_PATH_FILESTAT_SET_TIMES: Rights = 0x100000; +pub const RIGHTS_PATH_FILESTAT_SET_TIMES: Rights = 1 << 20; /// The right to invoke `fd_filestat_get`. -pub const RIGHTS_FD_FILESTAT_GET: Rights = 0x200000; +pub const RIGHTS_FD_FILESTAT_GET: Rights = 1 << 21; /// The right to invoke `fd_filestat_set_size`. -pub const RIGHTS_FD_FILESTAT_SET_SIZE: Rights = 0x400000; +pub const RIGHTS_FD_FILESTAT_SET_SIZE: Rights = 1 << 22; /// The right to invoke `fd_filestat_set_times`. -pub const RIGHTS_FD_FILESTAT_SET_TIMES: Rights = 0x800000; +pub const RIGHTS_FD_FILESTAT_SET_TIMES: Rights = 1 << 23; /// The right to invoke `path_symlink`. -pub const RIGHTS_PATH_SYMLINK: Rights = 0x1000000; +pub const RIGHTS_PATH_SYMLINK: Rights = 1 << 24; /// The right to invoke `path_remove_directory`. -pub const RIGHTS_PATH_REMOVE_DIRECTORY: Rights = 0x2000000; +pub const RIGHTS_PATH_REMOVE_DIRECTORY: Rights = 1 << 25; /// The right to invoke `path_unlink_file`. -pub const RIGHTS_PATH_UNLINK_FILE: Rights = 0x4000000; +pub const RIGHTS_PATH_UNLINK_FILE: Rights = 1 << 26; /// If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`. /// If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`. -pub const RIGHTS_POLL_FD_READWRITE: Rights = 0x8000000; +pub const RIGHTS_POLL_FD_READWRITE: Rights = 1 << 27; /// The right to invoke `sock_shutdown`. -pub const RIGHTS_SOCK_SHUTDOWN: Rights = 0x10000000; +pub const RIGHTS_SOCK_SHUTDOWN: Rights = 1 << 28; +/// The right to invoke `sock_accept`. +pub const RIGHTS_SOCK_ACCEPT: Rights = 1 << 29; + pub type Fd = u32; #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -350,33 +505,101 @@ pub struct Ciovec { pub type IovecArray<'a> = &'a [Iovec]; pub type CiovecArray<'a> = &'a [Ciovec]; pub type Filedelta = i64; -pub type Whence = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Whence(u8); /// Seek relative to start-of-file. -pub const WHENCE_SET: Whence = 0; +pub const WHENCE_SET: Whence = Whence(0); /// Seek relative to current position. -pub const WHENCE_CUR: Whence = 1; +pub const WHENCE_CUR: Whence = Whence(1); /// Seek relative to end-of-file. -pub const WHENCE_END: Whence = 2; +pub const WHENCE_END: Whence = Whence(2); +impl Whence { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "SET", + 1 => "CUR", + 2 => "END", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => "Seek relative to start-of-file.", + 1 => "Seek relative to current position.", + 2 => "Seek relative to end-of-file.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Whence { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Whence") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Dircookie = u64; pub type Dirnamlen = u32; pub type Inode = u64; -pub type Filetype = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Filetype(u8); /// The type of the file descriptor or file is unknown or is different from any of the other types specified. -pub const FILETYPE_UNKNOWN: Filetype = 0; +pub const FILETYPE_UNKNOWN: Filetype = Filetype(0); /// The file descriptor or file refers to a block device inode. -pub const FILETYPE_BLOCK_DEVICE: Filetype = 1; +pub const FILETYPE_BLOCK_DEVICE: Filetype = Filetype(1); /// The file descriptor or file refers to a character device inode. -pub const FILETYPE_CHARACTER_DEVICE: Filetype = 2; +pub const FILETYPE_CHARACTER_DEVICE: Filetype = Filetype(2); /// The file descriptor or file refers to a directory inode. -pub const FILETYPE_DIRECTORY: Filetype = 3; +pub const FILETYPE_DIRECTORY: Filetype = Filetype(3); /// The file descriptor or file refers to a regular file inode. -pub const FILETYPE_REGULAR_FILE: Filetype = 4; +pub const FILETYPE_REGULAR_FILE: Filetype = Filetype(4); /// The file descriptor or file refers to a datagram socket. -pub const FILETYPE_SOCKET_DGRAM: Filetype = 5; +pub const FILETYPE_SOCKET_DGRAM: Filetype = Filetype(5); /// The file descriptor or file refers to a byte-stream socket. -pub const FILETYPE_SOCKET_STREAM: Filetype = 6; +pub const FILETYPE_SOCKET_STREAM: Filetype = Filetype(6); /// The file refers to a symbolic link inode. -pub const FILETYPE_SYMBOLIC_LINK: Filetype = 7; +pub const FILETYPE_SYMBOLIC_LINK: Filetype = Filetype(7); +impl Filetype { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "UNKNOWN", + 1 => "BLOCK_DEVICE", + 2 => "CHARACTER_DEVICE", + 3 => "DIRECTORY", + 4 => "REGULAR_FILE", + 5 => "SOCKET_DGRAM", + 6 => "SOCKET_STREAM", + 7 => "SYMBOLIC_LINK", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 {0 => "The type of the file descriptor or file is unknown or is different from any of the other types specified.",1 => "The file descriptor or file refers to a block device inode.",2 => "The file descriptor or file refers to a character device inode.",3 => "The file descriptor or file refers to a directory inode.",4 => "The file descriptor or file refers to a regular file inode.",5 => "The file descriptor or file refers to a datagram socket.",6 => "The file descriptor or file refers to a byte-stream socket.",7 => "The file refers to a symbolic link inode.",_ => unsafe { core::hint::unreachable_unchecked() },} + } +} +impl fmt::Debug for Filetype { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Filetype") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Dirent { @@ -389,32 +612,65 @@ pub struct Dirent { /// The type of the file referred to by this directory entry. pub d_type: Filetype, } -pub type Advice = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Advice(u8); /// The application has no advice to give on its behavior with respect to the specified data. -pub const ADVICE_NORMAL: Advice = 0; +pub const ADVICE_NORMAL: Advice = Advice(0); /// The application expects to access the specified data sequentially from lower offsets to higher offsets. -pub const ADVICE_SEQUENTIAL: Advice = 1; +pub const ADVICE_SEQUENTIAL: Advice = Advice(1); /// The application expects to access the specified data in a random order. -pub const ADVICE_RANDOM: Advice = 2; +pub const ADVICE_RANDOM: Advice = Advice(2); /// The application expects to access the specified data in the near future. -pub const ADVICE_WILLNEED: Advice = 3; +pub const ADVICE_WILLNEED: Advice = Advice(3); /// The application expects that it will not access the specified data in the near future. -pub const ADVICE_DONTNEED: Advice = 4; +pub const ADVICE_DONTNEED: Advice = Advice(4); /// The application expects to access the specified data once and then not reuse it thereafter. -pub const ADVICE_NOREUSE: Advice = 5; +pub const ADVICE_NOREUSE: Advice = Advice(5); +impl Advice { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "NORMAL", + 1 => "SEQUENTIAL", + 2 => "RANDOM", + 3 => "WILLNEED", + 4 => "DONTNEED", + 5 => "NOREUSE", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 {0 => "The application has no advice to give on its behavior with respect to the specified data.",1 => "The application expects to access the specified data sequentially from lower offsets to higher offsets.",2 => "The application expects to access the specified data in a random order.",3 => "The application expects to access the specified data in the near future.",4 => "The application expects that it will not access the specified data in the near future.",5 => "The application expects to access the specified data once and then not reuse it thereafter.",_ => unsafe { core::hint::unreachable_unchecked() },} + } +} +impl fmt::Debug for Advice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Advice") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Fdflags = u16; /// Append mode: Data written to the file is always appended to the file's end. -pub const FDFLAGS_APPEND: Fdflags = 0x1; +pub const FDFLAGS_APPEND: Fdflags = 1 << 0; /// Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. -pub const FDFLAGS_DSYNC: Fdflags = 0x2; +pub const FDFLAGS_DSYNC: Fdflags = 1 << 1; /// Non-blocking mode. -pub const FDFLAGS_NONBLOCK: Fdflags = 0x4; +pub const FDFLAGS_NONBLOCK: Fdflags = 1 << 2; /// Synchronized read I/O operations. -pub const FDFLAGS_RSYNC: Fdflags = 0x8; +pub const FDFLAGS_RSYNC: Fdflags = 1 << 3; /// Write according to synchronized I/O file integrity completion. In /// addition to synchronizing the data stored in the file, the implementation /// may also synchronously update the file's metadata. -pub const FDFLAGS_SYNC: Fdflags = 0x10; +pub const FDFLAGS_SYNC: Fdflags = 1 << 4; + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Fdstat { @@ -431,25 +687,28 @@ pub struct Fdstat { pub type Device = u64; pub type Fstflags = u16; /// Adjust the last data access timestamp to the value stored in `filestat::atim`. -pub const FSTFLAGS_ATIM: Fstflags = 0x1; +pub const FSTFLAGS_ATIM: Fstflags = 1 << 0; /// Adjust the last data access timestamp to the time of clock `clockid::realtime`. -pub const FSTFLAGS_ATIM_NOW: Fstflags = 0x2; +pub const FSTFLAGS_ATIM_NOW: Fstflags = 1 << 1; /// Adjust the last data modification timestamp to the value stored in `filestat::mtim`. -pub const FSTFLAGS_MTIM: Fstflags = 0x4; +pub const FSTFLAGS_MTIM: Fstflags = 1 << 2; /// Adjust the last data modification timestamp to the time of clock `clockid::realtime`. -pub const FSTFLAGS_MTIM_NOW: Fstflags = 0x8; +pub const FSTFLAGS_MTIM_NOW: Fstflags = 1 << 3; + pub type Lookupflags = u32; /// As long as the resolved path corresponds to a symbolic link, it is expanded. -pub const LOOKUPFLAGS_SYMLINK_FOLLOW: Lookupflags = 0x1; +pub const LOOKUPFLAGS_SYMLINK_FOLLOW: Lookupflags = 1 << 0; + pub type Oflags = u16; /// Create file if it does not exist. -pub const OFLAGS_CREAT: Oflags = 0x1; +pub const OFLAGS_CREAT: Oflags = 1 << 0; /// Fail if not a directory. -pub const OFLAGS_DIRECTORY: Oflags = 0x2; +pub const OFLAGS_DIRECTORY: Oflags = 1 << 1; /// Fail if file already exists. -pub const OFLAGS_EXCL: Oflags = 0x4; +pub const OFLAGS_EXCL: Oflags = 1 << 2; /// Truncate file to size 0. -pub const OFLAGS_TRUNC: Oflags = 0x8; +pub const OFLAGS_TRUNC: Oflags = 1 << 3; + pub type Linkcount = u64; #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -472,19 +731,63 @@ pub struct Filestat { pub ctim: Timestamp, } pub type Userdata = u64; -pub type Eventtype = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Eventtype(u8); /// The time value of clock `subscription_clock::id` has /// reached timestamp `subscription_clock::timeout`. -pub const EVENTTYPE_CLOCK: Eventtype = 0; +pub const EVENTTYPE_CLOCK: Eventtype = Eventtype(0); /// File descriptor `subscription_fd_readwrite::file_descriptor` has data /// available for reading. This event always triggers for regular files. -pub const EVENTTYPE_FD_READ: Eventtype = 1; +pub const EVENTTYPE_FD_READ: Eventtype = Eventtype(1); /// File descriptor `subscription_fd_readwrite::file_descriptor` has capacity /// available for writing. This event always triggers for regular files. -pub const EVENTTYPE_FD_WRITE: Eventtype = 2; +pub const EVENTTYPE_FD_WRITE: Eventtype = Eventtype(2); +impl Eventtype { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "CLOCK", + 1 => "FD_READ", + 2 => "FD_WRITE", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => { + "The time value of clock `subscription_clock::id` has +reached timestamp `subscription_clock::timeout`." + } + 1 => { + "File descriptor `subscription_fd_readwrite::file_descriptor` has data +available for reading. This event always triggers for regular files." + } + 2 => { + "File descriptor `subscription_fd_readwrite::file_descriptor` has capacity +available for writing. This event always triggers for regular files." + } + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Eventtype { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Eventtype") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Eventrwflags = u16; /// The peer of this socket has closed or disconnected. -pub const EVENTRWFLAGS_FD_READWRITE_HANGUP: Eventrwflags = 0x1; +pub const EVENTRWFLAGS_FD_READWRITE_HANGUP: Eventrwflags = 1 << 0; + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct EventFdReadwrite { @@ -501,7 +804,7 @@ pub struct Event { /// If non-zero, an error that occurred while processing the subscription request. pub error: Errno, /// The type of event that occured - pub r#type: Eventtype, + pub type_: Eventtype, /// The contents of the event, if it is an `eventtype::fd_read` or /// `eventtype::fd_write`. `eventtype::clock` events ignore this field. pub fd_readwrite: EventFdReadwrite, @@ -512,7 +815,8 @@ pub type Subclockflags = u16; /// `subscription_clock::id`. If clear, treat the timestamp /// provided in `subscription_clock::timeout` relative to the /// current time value of clock `subscription_clock::id`. -pub const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: Subclockflags = 0x1; +pub const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME: Subclockflags = 1 << 0; + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SubscriptionClock { @@ -542,7 +846,7 @@ pub union SubscriptionUU { #[repr(C)] #[derive(Copy, Clone)] pub struct SubscriptionU { - pub tag: Eventtype, + pub tag: u8, pub u: SubscriptionUU, } @@ -556,117 +860,333 @@ pub struct Subscription { pub u: SubscriptionU, } pub type Exitcode = u32; -pub type Signal = u8; +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Signal(u8); /// No signal. Note that POSIX has special semantics for `kill(pid, 0)`, /// so this value is reserved. -pub const SIGNAL_NONE: Signal = 0; +pub const SIGNAL_NONE: Signal = Signal(0); /// Hangup. /// Action: Terminates the process. -pub const SIGNAL_HUP: Signal = 1; +pub const SIGNAL_HUP: Signal = Signal(1); /// Terminate interrupt signal. /// Action: Terminates the process. -pub const SIGNAL_INT: Signal = 2; +pub const SIGNAL_INT: Signal = Signal(2); /// Terminal quit signal. /// Action: Terminates the process. -pub const SIGNAL_QUIT: Signal = 3; +pub const SIGNAL_QUIT: Signal = Signal(3); /// Illegal instruction. /// Action: Terminates the process. -pub const SIGNAL_ILL: Signal = 4; +pub const SIGNAL_ILL: Signal = Signal(4); /// Trace/breakpoint trap. /// Action: Terminates the process. -pub const SIGNAL_TRAP: Signal = 5; +pub const SIGNAL_TRAP: Signal = Signal(5); /// Process abort signal. /// Action: Terminates the process. -pub const SIGNAL_ABRT: Signal = 6; +pub const SIGNAL_ABRT: Signal = Signal(6); /// Access to an undefined portion of a memory object. /// Action: Terminates the process. -pub const SIGNAL_BUS: Signal = 7; +pub const SIGNAL_BUS: Signal = Signal(7); /// Erroneous arithmetic operation. /// Action: Terminates the process. -pub const SIGNAL_FPE: Signal = 8; +pub const SIGNAL_FPE: Signal = Signal(8); /// Kill. /// Action: Terminates the process. -pub const SIGNAL_KILL: Signal = 9; +pub const SIGNAL_KILL: Signal = Signal(9); /// User-defined signal 1. /// Action: Terminates the process. -pub const SIGNAL_USR1: Signal = 10; +pub const SIGNAL_USR1: Signal = Signal(10); /// Invalid memory reference. /// Action: Terminates the process. -pub const SIGNAL_SEGV: Signal = 11; +pub const SIGNAL_SEGV: Signal = Signal(11); /// User-defined signal 2. /// Action: Terminates the process. -pub const SIGNAL_USR2: Signal = 12; +pub const SIGNAL_USR2: Signal = Signal(12); /// Write on a pipe with no one to read it. /// Action: Ignored. -pub const SIGNAL_PIPE: Signal = 13; +pub const SIGNAL_PIPE: Signal = Signal(13); /// Alarm clock. /// Action: Terminates the process. -pub const SIGNAL_ALRM: Signal = 14; +pub const SIGNAL_ALRM: Signal = Signal(14); /// Termination signal. /// Action: Terminates the process. -pub const SIGNAL_TERM: Signal = 15; +pub const SIGNAL_TERM: Signal = Signal(15); /// Child process terminated, stopped, or continued. /// Action: Ignored. -pub const SIGNAL_CHLD: Signal = 16; +pub const SIGNAL_CHLD: Signal = Signal(16); /// Continue executing, if stopped. /// Action: Continues executing, if stopped. -pub const SIGNAL_CONT: Signal = 17; +pub const SIGNAL_CONT: Signal = Signal(17); /// Stop executing. /// Action: Stops executing. -pub const SIGNAL_STOP: Signal = 18; +pub const SIGNAL_STOP: Signal = Signal(18); /// Terminal stop signal. /// Action: Stops executing. -pub const SIGNAL_TSTP: Signal = 19; +pub const SIGNAL_TSTP: Signal = Signal(19); /// Background process attempting read. /// Action: Stops executing. -pub const SIGNAL_TTIN: Signal = 20; +pub const SIGNAL_TTIN: Signal = Signal(20); /// Background process attempting write. /// Action: Stops executing. -pub const SIGNAL_TTOU: Signal = 21; +pub const SIGNAL_TTOU: Signal = Signal(21); /// High bandwidth data is available at a socket. /// Action: Ignored. -pub const SIGNAL_URG: Signal = 22; +pub const SIGNAL_URG: Signal = Signal(22); /// CPU time limit exceeded. /// Action: Terminates the process. -pub const SIGNAL_XCPU: Signal = 23; +pub const SIGNAL_XCPU: Signal = Signal(23); /// File size limit exceeded. /// Action: Terminates the process. -pub const SIGNAL_XFSZ: Signal = 24; +pub const SIGNAL_XFSZ: Signal = Signal(24); /// Virtual timer expired. /// Action: Terminates the process. -pub const SIGNAL_VTALRM: Signal = 25; +pub const SIGNAL_VTALRM: Signal = Signal(25); /// Profiling timer expired. /// Action: Terminates the process. -pub const SIGNAL_PROF: Signal = 26; +pub const SIGNAL_PROF: Signal = Signal(26); /// Window changed. /// Action: Ignored. -pub const SIGNAL_WINCH: Signal = 27; +pub const SIGNAL_WINCH: Signal = Signal(27); /// I/O possible. /// Action: Terminates the process. -pub const SIGNAL_POLL: Signal = 28; +pub const SIGNAL_POLL: Signal = Signal(28); /// Power failure. /// Action: Terminates the process. -pub const SIGNAL_PWR: Signal = 29; +pub const SIGNAL_PWR: Signal = Signal(29); /// Bad system call. /// Action: Terminates the process. -pub const SIGNAL_SYS: Signal = 30; +pub const SIGNAL_SYS: Signal = Signal(30); +impl Signal { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "NONE", + 1 => "HUP", + 2 => "INT", + 3 => "QUIT", + 4 => "ILL", + 5 => "TRAP", + 6 => "ABRT", + 7 => "BUS", + 8 => "FPE", + 9 => "KILL", + 10 => "USR1", + 11 => "SEGV", + 12 => "USR2", + 13 => "PIPE", + 14 => "ALRM", + 15 => "TERM", + 16 => "CHLD", + 17 => "CONT", + 18 => "STOP", + 19 => "TSTP", + 20 => "TTIN", + 21 => "TTOU", + 22 => "URG", + 23 => "XCPU", + 24 => "XFSZ", + 25 => "VTALRM", + 26 => "PROF", + 27 => "WINCH", + 28 => "POLL", + 29 => "PWR", + 30 => "SYS", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => { + "No signal. Note that POSIX has special semantics for `kill(pid, 0)`, +so this value is reserved." + } + 1 => { + "Hangup. +Action: Terminates the process." + } + 2 => { + "Terminate interrupt signal. +Action: Terminates the process." + } + 3 => { + "Terminal quit signal. +Action: Terminates the process." + } + 4 => { + "Illegal instruction. +Action: Terminates the process." + } + 5 => { + "Trace/breakpoint trap. +Action: Terminates the process." + } + 6 => { + "Process abort signal. +Action: Terminates the process." + } + 7 => { + "Access to an undefined portion of a memory object. +Action: Terminates the process." + } + 8 => { + "Erroneous arithmetic operation. +Action: Terminates the process." + } + 9 => { + "Kill. +Action: Terminates the process." + } + 10 => { + "User-defined signal 1. +Action: Terminates the process." + } + 11 => { + "Invalid memory reference. +Action: Terminates the process." + } + 12 => { + "User-defined signal 2. +Action: Terminates the process." + } + 13 => { + "Write on a pipe with no one to read it. +Action: Ignored." + } + 14 => { + "Alarm clock. +Action: Terminates the process." + } + 15 => { + "Termination signal. +Action: Terminates the process." + } + 16 => { + "Child process terminated, stopped, or continued. +Action: Ignored." + } + 17 => { + "Continue executing, if stopped. +Action: Continues executing, if stopped." + } + 18 => { + "Stop executing. +Action: Stops executing." + } + 19 => { + "Terminal stop signal. +Action: Stops executing." + } + 20 => { + "Background process attempting read. +Action: Stops executing." + } + 21 => { + "Background process attempting write. +Action: Stops executing." + } + 22 => { + "High bandwidth data is available at a socket. +Action: Ignored." + } + 23 => { + "CPU time limit exceeded. +Action: Terminates the process." + } + 24 => { + "File size limit exceeded. +Action: Terminates the process." + } + 25 => { + "Virtual timer expired. +Action: Terminates the process." + } + 26 => { + "Profiling timer expired. +Action: Terminates the process." + } + 27 => { + "Window changed. +Action: Ignored." + } + 28 => { + "I/O possible. +Action: Terminates the process." + } + 29 => { + "Power failure. +Action: Terminates the process." + } + 30 => { + "Bad system call. +Action: Terminates the process." + } + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Signal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Signal") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + pub type Riflags = u16; /// Returns the message without removing it from the socket's receive queue. -pub const RIFLAGS_RECV_PEEK: Riflags = 0x1; +pub const RIFLAGS_RECV_PEEK: Riflags = 1 << 0; /// On byte-stream sockets, block until the full amount of data can be returned. -pub const RIFLAGS_RECV_WAITALL: Riflags = 0x2; +pub const RIFLAGS_RECV_WAITALL: Riflags = 1 << 1; + pub type Roflags = u16; /// Returned by `sock_recv`: Message data has been truncated. -pub const ROFLAGS_RECV_DATA_TRUNCATED: Roflags = 0x1; +pub const ROFLAGS_RECV_DATA_TRUNCATED: Roflags = 1 << 0; + pub type Siflags = u16; pub type Sdflags = u8; /// Disables further receive operations. -pub const SDFLAGS_RD: Sdflags = 0x1; +pub const SDFLAGS_RD: Sdflags = 1 << 0; /// Disables further send operations. -pub const SDFLAGS_WR: Sdflags = 0x2; -pub type Preopentype = u8; +pub const SDFLAGS_WR: Sdflags = 1 << 1; + +#[repr(transparent)] +#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct Preopentype(u8); /// A pre-opened directory. -pub const PREOPENTYPE_DIR: Preopentype = 0; +pub const PREOPENTYPE_DIR: Preopentype = Preopentype(0); +impl Preopentype { + pub const fn raw(&self) -> u8 { + self.0 + } + + pub fn name(&self) -> &'static str { + match self.0 { + 0 => "DIR", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } + pub fn message(&self) -> &'static str { + match self.0 { + 0 => "A pre-opened directory.", + _ => unsafe { core::hint::unreachable_unchecked() }, + } + } +} +impl fmt::Debug for Preopentype { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Preopentype") + .field("code", &self.0) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } +} + #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct PrestatDir { @@ -681,18 +1201,18 @@ pub union PrestatU { #[repr(C)] #[derive(Copy, Clone)] pub struct Prestat { - pub tag: Preopentype, + pub tag: u8, pub u: PrestatU, } /// Read command-line argument data. -/// The size of the array should match that returned by `args_sizes_get` -pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<()> { - let rc = wasi_snapshot_preview1::args_get(argv, argv_buf); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +/// The size of the array should match that returned by `args_sizes_get`. +/// Each argument is expected to be `\0` terminated. +pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::args_get(argv as i32, argv_buf as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -700,27 +1220,30 @@ pub unsafe fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Result<()> { /// /// ## Return /// -/// * `argc` - The number of arguments. -/// * `argv_buf_size` - The size of the argument string data. -pub unsafe fn args_sizes_get() -> Result<(Size, Size)> { - let mut argc = MaybeUninit::uninit(); - let mut argv_buf_size = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::args_sizes_get(argc.as_mut_ptr(), argv_buf_size.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok((argc.assume_init(), argv_buf_size.assume_init())) +/// Returns the number of arguments and the size of the argument string +/// data, or an error. +pub unsafe fn args_sizes_get() -> Result<(Size, Size), Errno> { + let mut rp0 = MaybeUninit::::uninit(); + let mut rp1 = MaybeUninit::::uninit(); + let ret = + wasi_snapshot_preview1::args_sizes_get(rp0.as_mut_ptr() as i32, rp1.as_mut_ptr() as i32); + match ret { + 0 => Ok(( + core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), + core::ptr::read(rp1.as_mut_ptr() as i32 as *const Size), + )), + _ => Err(Errno(ret as u16)), } } /// Read environment variable data. /// The sizes of the buffers should match that returned by `environ_sizes_get`. -pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result<()> { - let rc = wasi_snapshot_preview1::environ_get(environ, environ_buf); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +/// Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s. +pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::environ_get(environ as i32, environ_buf as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -728,19 +1251,19 @@ pub unsafe fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Result /// /// ## Return /// -/// * `environc` - The number of environment variable arguments. -/// * `environ_buf_size` - The size of the environment variable data. -pub unsafe fn environ_sizes_get() -> Result<(Size, Size)> { - let mut environc = MaybeUninit::uninit(); - let mut environ_buf_size = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::environ_sizes_get( - environc.as_mut_ptr(), - environ_buf_size.as_mut_ptr(), - ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok((environc.assume_init(), environ_buf_size.assume_init())) +/// Returns the number of environment variable arguments and the size of the +/// environment variable data. +pub unsafe fn environ_sizes_get() -> Result<(Size, Size), Errno> { + let mut rp0 = MaybeUninit::::uninit(); + let mut rp1 = MaybeUninit::::uninit(); + let ret = + wasi_snapshot_preview1::environ_sizes_get(rp0.as_mut_ptr() as i32, rp1.as_mut_ptr() as i32); + match ret { + 0 => Ok(( + core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), + core::ptr::read(rp1.as_mut_ptr() as i32 as *const Size), + )), + _ => Err(Errno(ret as u16)), } } @@ -755,14 +1278,13 @@ pub unsafe fn environ_sizes_get() -> Result<(Size, Size)> { /// /// ## Return /// -/// * `resolution` - The resolution of the clock. -pub unsafe fn clock_res_get(id: Clockid) -> Result { - let mut resolution = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::clock_res_get(id, resolution.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(resolution.assume_init()) +/// The resolution of the clock, or an error if one happened. +pub unsafe fn clock_res_get(id: Clockid) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::clock_res_get(id.0 as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Timestamp)), + _ => Err(Errno(ret as u16)), } } @@ -776,14 +1298,17 @@ pub unsafe fn clock_res_get(id: Clockid) -> Result { /// /// ## Return /// -/// * `time` - The time value of the clock. -pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result { - let mut time = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::clock_time_get(id, precision, time.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(time.assume_init()) +/// The time value of the clock. +pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::clock_time_get( + id.0 as i32, + precision as i64, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Timestamp)), + _ => Err(Errno(ret as u16)), } } @@ -795,12 +1320,17 @@ pub unsafe fn clock_time_get(id: Clockid, precision: Timestamp) -> Result Result<()> { - let rc = wasi_snapshot_preview1::fd_advise(fd, offset, len, advice); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_advise( + fd: Fd, + offset: Filesize, + len: Filesize, + advice: Advice, +) -> Result<(), Errno> { + let ret = + wasi_snapshot_preview1::fd_advise(fd as i32, offset as i64, len as i64, advice.0 as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -811,34 +1341,31 @@ pub unsafe fn fd_advise(fd: Fd, offset: Filesize, len: Filesize, advice: Advice) /// /// * `offset` - The offset at which to start the allocation. /// * `len` - The length of the area that is allocated. -pub unsafe fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_allocate(fd, offset, len); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_allocate(fd as i32, offset as i64, len as i64); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } /// Close a file descriptor. /// Note: This is similar to `close` in POSIX. -pub unsafe fn fd_close(fd: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_close(fd); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_close(fd: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_close(fd as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } /// Synchronize the data of a file to disk. /// Note: This is similar to `fdatasync` in POSIX. -pub unsafe fn fd_datasync(fd: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_datasync(fd); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_datasync(fd: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_datasync(fd as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -847,14 +1374,13 @@ pub unsafe fn fd_datasync(fd: Fd) -> Result<()> { /// /// ## Return /// -/// * `stat` - The buffer where the file descriptor's attributes are stored. -pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { - let mut stat = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_fdstat_get(fd, stat.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(stat.assume_init()) +/// The buffer where the file descriptor's attributes are stored. +pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_fdstat_get(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fdstat)), + _ => Err(Errno(ret as u16)), } } @@ -864,12 +1390,11 @@ pub unsafe fn fd_fdstat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `flags` - The desired values of the file descriptor flags. -pub unsafe fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_fdstat_set_flags(fd, flags); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_fdstat_set_flags(fd as i32, flags as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -883,12 +1408,15 @@ pub unsafe fn fd_fdstat_set_rights( fd: Fd, fs_rights_base: Rights, fs_rights_inheriting: Rights, -) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_fdstat_set_rights(fd, fs_rights_base, fs_rights_inheriting); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_fdstat_set_rights( + fd as i32, + fs_rights_base as i64, + fs_rights_inheriting as i64, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -896,14 +1424,13 @@ pub unsafe fn fd_fdstat_set_rights( /// /// ## Return /// -/// * `buf` - The buffer where the file's attributes are stored. -pub unsafe fn fd_filestat_get(fd: Fd) -> Result { - let mut buf = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_filestat_get(fd, buf.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(buf.assume_init()) +/// The buffer where the file's attributes are stored. +pub unsafe fn fd_filestat_get(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_filestat_get(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filestat)), + _ => Err(Errno(ret as u16)), } } @@ -913,12 +1440,11 @@ pub unsafe fn fd_filestat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `size` - The desired file size. -pub unsafe fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_filestat_set_size(fd, size); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_filestat_set_size(fd as i32, size as i64); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -935,12 +1461,16 @@ pub unsafe fn fd_filestat_set_times( atim: Timestamp, mtim: Timestamp, fst_flags: Fstflags, -) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_filestat_set_times(fd, atim, mtim, fst_flags); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_filestat_set_times( + fd as i32, + atim as i64, + mtim as i64, + fst_flags as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -954,15 +1484,19 @@ pub unsafe fn fd_filestat_set_times( /// /// ## Return /// -/// * `nread` - The number of bytes read. -pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray, offset: Filesize) -> Result { - let mut nread = MaybeUninit::uninit(); - let rc = - wasi_snapshot_preview1::fd_pread(fd, iovs.as_ptr(), iovs.len(), offset, nread.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nread.assume_init()) +/// The number of bytes read. +pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray<'_>, offset: Filesize) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_pread( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + offset as i64, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -970,14 +1504,13 @@ pub unsafe fn fd_pread(fd: Fd, iovs: IovecArray, offset: Filesize) -> Result Result { - let mut buf = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_prestat_get(fd, buf.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(buf.assume_init()) +/// The buffer where the description is stored. +pub unsafe fn fd_prestat_get(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_prestat_get(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Prestat)), + _ => Err(Errno(ret as u16)), } } @@ -986,12 +1519,11 @@ pub unsafe fn fd_prestat_get(fd: Fd) -> Result { /// ## Parameters /// /// * `path` - A buffer into which to write the preopened directory name. -pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_prestat_dir_name(fd, path, path_len); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_prestat_dir_name(fd as i32, path as i32, path_len as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1005,20 +1537,19 @@ pub unsafe fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Resu /// /// ## Return /// -/// * `nwritten` - The number of bytes written. -pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray, offset: Filesize) -> Result { - let mut nwritten = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_pwrite( - fd, - iovs.as_ptr(), - iovs.len(), - offset, - nwritten.as_mut_ptr(), +/// The number of bytes written. +pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray<'_>, offset: Filesize) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_pwrite( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + offset as i64, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nwritten.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1031,21 +1562,25 @@ pub unsafe fn fd_pwrite(fd: Fd, iovs: CiovecArray, offset: Filesize) -> Result Result { - let mut nread = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_read(fd, iovs.as_ptr(), iovs.len(), nread.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nread.assume_init()) +/// The number of bytes read. +pub unsafe fn fd_read(fd: Fd, iovs: IovecArray<'_>) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_read( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } /// Read directory entries from a directory. /// When successful, the contents of the output buffer consist of a sequence of -/// directory entries. Each directory entry consists of a dirent_t object, -/// followed by dirent_t::d_namlen bytes holding the name of the directory +/// directory entries. Each directory entry consists of a `dirent` object, +/// followed by `dirent::d_namlen` bytes holding the name of the directory /// entry. /// This function fills the output buffer as much as possible, potentially /// truncating the last directory entry. This allows the caller to grow its @@ -1059,14 +1594,24 @@ pub unsafe fn fd_read(fd: Fd, iovs: IovecArray) -> Result { /// /// ## Return /// -/// * `bufused` - The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. -pub unsafe fn fd_readdir(fd: Fd, buf: *mut u8, buf_len: Size, cookie: Dircookie) -> Result { - let mut bufused = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_readdir(fd, buf, buf_len, cookie, bufused.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(bufused.assume_init()) +/// The number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. +pub unsafe fn fd_readdir( + fd: Fd, + buf: *mut u8, + buf_len: Size, + cookie: Dircookie, +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_readdir( + fd as i32, + buf as i32, + buf_len as i32, + cookie as i64, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1082,12 +1627,11 @@ pub unsafe fn fd_readdir(fd: Fd, buf: *mut u8, buf_len: Size, cookie: Dircookie) /// ## Parameters /// /// * `to` - The file descriptor to overwrite. -pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_renumber(fd, to); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_renumber(fd as i32, to as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1101,25 +1645,28 @@ pub unsafe fn fd_renumber(fd: Fd, to: Fd) -> Result<()> { /// /// ## Return /// -/// * `newoffset` - The new offset of the file descriptor, relative to the start of the file. -pub unsafe fn fd_seek(fd: Fd, offset: Filedelta, whence: Whence) -> Result { - let mut newoffset = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_seek(fd, offset, whence, newoffset.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(newoffset.assume_init()) +/// The new offset of the file descriptor, relative to the start of the file. +pub unsafe fn fd_seek(fd: Fd, offset: Filedelta, whence: Whence) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_seek( + fd as i32, + offset, + whence.0 as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filesize)), + _ => Err(Errno(ret as u16)), } } /// Synchronize the data and metadata of a file to disk. /// Note: This is similar to `fsync` in POSIX. -pub unsafe fn fd_sync(fd: Fd) -> Result<()> { - let rc = wasi_snapshot_preview1::fd_sync(fd); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn fd_sync(fd: Fd) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::fd_sync(fd as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1128,14 +1675,13 @@ pub unsafe fn fd_sync(fd: Fd) -> Result<()> { /// /// ## Return /// -/// * `offset` - The current offset of the file descriptor, relative to the start of the file. -pub unsafe fn fd_tell(fd: Fd) -> Result { - let mut offset = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_tell(fd, offset.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(offset.assume_init()) +/// The current offset of the file descriptor, relative to the start of the file. +pub unsafe fn fd_tell(fd: Fd) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_tell(fd as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filesize)), + _ => Err(Errno(ret as u16)), } } @@ -1145,17 +1691,17 @@ pub unsafe fn fd_tell(fd: Fd) -> Result { /// ## Parameters /// /// * `iovs` - List of scatter/gather vectors from which to retrieve data. -/// -/// ## Return -/// -/// * `nwritten` - The number of bytes written. -pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray) -> Result { - let mut nwritten = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::fd_write(fd, iovs.as_ptr(), iovs.len(), nwritten.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nwritten.assume_init()) +pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray<'_>) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::fd_write( + fd as i32, + iovs.as_ptr() as i32, + iovs.len() as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1165,12 +1711,15 @@ pub unsafe fn fd_write(fd: Fd, iovs: CiovecArray) -> Result { /// ## Parameters /// /// * `path` - The path at which to create the directory. -pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_create_directory(fd, path.as_ptr(), path.len()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_create_directory( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1184,20 +1733,19 @@ pub unsafe fn path_create_directory(fd: Fd, path: &str) -> Result<()> { /// /// ## Return /// -/// * `buf` - The buffer where the file's attributes are stored. -pub unsafe fn path_filestat_get(fd: Fd, flags: Lookupflags, path: &str) -> Result { - let mut buf = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::path_filestat_get( - fd, - flags, - path.as_ptr(), - path.len(), - buf.as_mut_ptr(), +/// The buffer where the file's attributes are stored. +pub unsafe fn path_filestat_get(fd: Fd, flags: Lookupflags, path: &str) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::path_filestat_get( + fd as i32, + flags as i32, + path.as_ptr() as i32, + path.len() as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(buf.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Filestat)), + _ => Err(Errno(ret as u16)), } } @@ -1218,20 +1766,19 @@ pub unsafe fn path_filestat_set_times( atim: Timestamp, mtim: Timestamp, fst_flags: Fstflags, -) -> Result<()> { - let rc = wasi_snapshot_preview1::path_filestat_set_times( - fd, - flags, - path.as_ptr(), - path.len(), - atim, - mtim, - fst_flags, +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_filestat_set_times( + fd as i32, + flags as i32, + path.as_ptr() as i32, + path.len() as i32, + atim as i64, + mtim as i64, + fst_flags as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1250,20 +1797,19 @@ pub unsafe fn path_link( old_path: &str, new_fd: Fd, new_path: &str, -) -> Result<()> { - let rc = wasi_snapshot_preview1::path_link( - old_fd, - old_flags, - old_path.as_ptr(), - old_path.len(), - new_fd, - new_path.as_ptr(), - new_path.len(), +) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_link( + old_fd as i32, + old_flags as i32, + old_path.as_ptr() as i32, + old_path.len() as i32, + new_fd as i32, + new_path.as_ptr() as i32, + new_path.len() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1291,32 +1837,31 @@ pub unsafe fn path_link( /// /// ## Return /// -/// * `opened_fd` - The file descriptor of the file that has been opened. +/// The file descriptor of the file that has been opened. pub unsafe fn path_open( fd: Fd, dirflags: Lookupflags, path: &str, oflags: Oflags, fs_rights_base: Rights, - fs_rights_inherting: Rights, + fs_rights_inheriting: Rights, fdflags: Fdflags, -) -> Result { - let mut opened_fd = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::path_open( - fd, - dirflags, - path.as_ptr(), - path.len(), - oflags, - fs_rights_base, - fs_rights_inherting, - fdflags, - opened_fd.as_mut_ptr(), +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::path_open( + fd as i32, + dirflags as i32, + path.as_ptr() as i32, + path.len() as i32, + oflags as i32, + fs_rights_base as i64, + fs_rights_inheriting as i64, + fdflags as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(opened_fd.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fd)), + _ => Err(Errno(ret as u16)), } } @@ -1330,21 +1875,25 @@ pub unsafe fn path_open( /// /// ## Return /// -/// * `bufused` - The number of bytes placed in the buffer. -pub unsafe fn path_readlink(fd: Fd, path: &str, buf: *mut u8, buf_len: Size) -> Result { - let mut bufused = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::path_readlink( - fd, - path.as_ptr(), - path.len(), - buf, - buf_len, - bufused.as_mut_ptr(), +/// The number of bytes placed in the buffer. +pub unsafe fn path_readlink( + fd: Fd, + path: &str, + buf: *mut u8, + buf_len: Size, +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::path_readlink( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + buf as i32, + buf_len as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(bufused.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1355,12 +1904,15 @@ pub unsafe fn path_readlink(fd: Fd, path: &str, buf: *mut u8, buf_len: Size) -> /// ## Parameters /// /// * `path` - The path to a directory to remove. -pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_remove_directory(fd, path.as_ptr(), path.len()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_remove_directory( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1372,19 +1924,18 @@ pub unsafe fn path_remove_directory(fd: Fd, path: &str) -> Result<()> { /// * `old_path` - The source path of the file or directory to rename. /// * `new_fd` - The working directory at which the resolution of the new path starts. /// * `new_path` - The destination path to which to rename the file or directory. -pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_rename( - fd, - old_path.as_ptr(), - old_path.len(), - new_fd, - new_path.as_ptr(), - new_path.len(), +pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_rename( + fd as i32, + old_path.as_ptr() as i32, + old_path.len() as i32, + new_fd as i32, + new_path.as_ptr() as i32, + new_path.len() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1395,18 +1946,17 @@ pub unsafe fn path_rename(fd: Fd, old_path: &str, new_fd: Fd, new_path: &str) -> /// /// * `old_path` - The contents of the symbolic link. /// * `new_path` - The destination path at which to create the symbolic link. -pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_symlink( - old_path.as_ptr(), - old_path.len(), - fd, - new_path.as_ptr(), - new_path.len(), +pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_symlink( + old_path.as_ptr() as i32, + old_path.len() as i32, + fd as i32, + new_path.as_ptr() as i32, + new_path.len() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1417,12 +1967,15 @@ pub unsafe fn path_symlink(old_path: &str, fd: Fd, new_path: &str) -> Result<()> /// ## Parameters /// /// * `path` - The path to a file to unlink. -pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<()> { - let rc = wasi_snapshot_preview1::path_unlink_file(fd, path.as_ptr(), path.len()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::path_unlink_file( + fd as i32, + path.as_ptr() as i32, + path.len() as i32, + ); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1430,24 +1983,28 @@ pub unsafe fn path_unlink_file(fd: Fd, path: &str) -> Result<()> { /// /// ## Parameters /// -/// * `r#in` - The events to which to subscribe. +/// * `in_` - The events to which to subscribe. /// * `out` - The events that have occurred. /// * `nsubscriptions` - Both the number of subscriptions and events. /// /// ## Return /// -/// * `nevents` - The number of events stored. +/// The number of events stored. pub unsafe fn poll_oneoff( - r#in: *const Subscription, + in_: *const Subscription, out: *mut Event, nsubscriptions: Size, -) -> Result { - let mut nevents = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::poll_oneoff(r#in, out, nsubscriptions, nevents.as_mut_ptr()); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(nevents.assume_init()) +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::poll_oneoff( + in_ as i32, + out as i32, + nsubscriptions as i32, + rp0.as_mut_ptr() as i32, + ); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1459,7 +2016,7 @@ pub unsafe fn poll_oneoff( /// /// * `rval` - The exit code returned by the process. pub unsafe fn proc_exit(rval: Exitcode) { - wasi_snapshot_preview1::proc_exit(rval); + wasi_snapshot_preview1::proc_exit(rval as i32); } /// Send a signal to the process of the calling thread. @@ -1468,23 +2025,21 @@ pub unsafe fn proc_exit(rval: Exitcode) { /// ## Parameters /// /// * `sig` - The signal condition to trigger. -pub unsafe fn proc_raise(sig: Signal) -> Result<()> { - let rc = wasi_snapshot_preview1::proc_raise(sig); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn proc_raise(sig: Signal) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::proc_raise(sig.0 as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } /// Temporarily yield execution of the calling thread. /// Note: This is similar to `sched_yield` in POSIX. -pub unsafe fn sched_yield() -> Result<()> { - let rc = wasi_snapshot_preview1::sched_yield(); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn sched_yield() -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::sched_yield(); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } @@ -1498,12 +2053,31 @@ pub unsafe fn sched_yield() -> Result<()> { /// ## Parameters /// /// * `buf` - The buffer to fill with random data. -pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<()> { - let rc = wasi_snapshot_preview1::random_get(buf, buf_len); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::random_get(buf as i32, buf_len as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), + } +} + +/// Accept a new incoming connection. +/// Note: This is similar to `accept` in POSIX. +/// +/// ## Parameters +/// +/// * `fd` - The listening socket. +/// * `flags` - The desired values of the file descriptor flags. +/// +/// ## Return +/// +/// New socket connection +pub unsafe fn sock_accept(fd: Fd, flags: Fdflags) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::sock_accept(fd as i32, flags as i32, rp0.as_mut_ptr() as i32); + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Fd)), + _ => Err(Errno(ret as u16)), } } @@ -1518,23 +2092,28 @@ pub unsafe fn random_get(buf: *mut u8, buf_len: Size) -> Result<()> { /// /// ## Return /// -/// * `ro_datalen` - Number of bytes stored in ri_data. -/// * `ro_flags` - Message flags. -pub unsafe fn sock_recv(fd: Fd, ri_data: IovecArray, ri_flags: Riflags) -> Result<(Size, Roflags)> { - let mut ro_datalen = MaybeUninit::uninit(); - let mut ro_flags = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::sock_recv( - fd, - ri_data.as_ptr(), - ri_data.len(), - ri_flags, - ro_datalen.as_mut_ptr(), - ro_flags.as_mut_ptr(), +/// Number of bytes stored in ri_data and message flags. +pub unsafe fn sock_recv( + fd: Fd, + ri_data: IovecArray<'_>, + ri_flags: Riflags, +) -> Result<(Size, Roflags), Errno> { + let mut rp0 = MaybeUninit::::uninit(); + let mut rp1 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::sock_recv( + fd as i32, + ri_data.as_ptr() as i32, + ri_data.len() as i32, + ri_flags as i32, + rp0.as_mut_ptr() as i32, + rp1.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok((ro_datalen.assume_init(), ro_flags.assume_init())) + match ret { + 0 => Ok(( + core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size), + core::ptr::read(rp1.as_mut_ptr() as i32 as *const Roflags), + )), + _ => Err(Errno(ret as u16)), } } @@ -1549,20 +2128,23 @@ pub unsafe fn sock_recv(fd: Fd, ri_data: IovecArray, ri_flags: Riflags) -> Resul /// /// ## Return /// -/// * `so_datalen` - Number of bytes transmitted. -pub unsafe fn sock_send(fd: Fd, si_data: CiovecArray, si_flags: Siflags) -> Result { - let mut so_datalen = MaybeUninit::uninit(); - let rc = wasi_snapshot_preview1::sock_send( - fd, - si_data.as_ptr(), - si_data.len(), - si_flags, - so_datalen.as_mut_ptr(), +/// Number of bytes transmitted. +pub unsafe fn sock_send( + fd: Fd, + si_data: CiovecArray<'_>, + si_flags: Siflags, +) -> Result { + let mut rp0 = MaybeUninit::::uninit(); + let ret = wasi_snapshot_preview1::sock_send( + fd as i32, + si_data.as_ptr() as i32, + si_data.len() as i32, + si_flags as i32, + rp0.as_mut_ptr() as i32, ); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(so_datalen.assume_init()) + match ret { + 0 => Ok(core::ptr::read(rp0.as_mut_ptr() as i32 as *const Size)), + _ => Err(Errno(ret as u16)), } } @@ -1572,116 +2154,89 @@ pub unsafe fn sock_send(fd: Fd, si_data: CiovecArray, si_flags: Siflags) -> Resu /// ## Parameters /// /// * `how` - Which channels on the socket to shut down. -pub unsafe fn sock_shutdown(fd: Fd, how: Sdflags) -> Result<()> { - let rc = wasi_snapshot_preview1::sock_shutdown(fd, how); - if let Some(err) = Error::from_raw_error(rc) { - Err(err) - } else { - Ok(()) +pub unsafe fn sock_shutdown(fd: Fd, how: Sdflags) -> Result<(), Errno> { + let ret = wasi_snapshot_preview1::sock_shutdown(fd as i32, how as i32); + match ret { + 0 => Ok(()), + _ => Err(Errno(ret as u16)), } } pub mod wasi_snapshot_preview1 { - use super::*; #[link(wasm_import_module = "wasi_snapshot_preview1")] extern "C" { /// Read command-line argument data. - /// The size of the array should match that returned by `args_sizes_get` - pub fn args_get(argv: *mut *mut u8, argv_buf: *mut u8) -> Errno; + /// The size of the array should match that returned by `args_sizes_get`. + /// Each argument is expected to be `\0` terminated. + pub fn args_get(arg0: i32, arg1: i32) -> i32; /// Return command-line argument data sizes. - pub fn args_sizes_get(argc: *mut Size, argv_buf_size: *mut Size) -> Errno; + pub fn args_sizes_get(arg0: i32, arg1: i32) -> i32; /// Read environment variable data. /// The sizes of the buffers should match that returned by `environ_sizes_get`. - pub fn environ_get(environ: *mut *mut u8, environ_buf: *mut u8) -> Errno; + /// Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s. + pub fn environ_get(arg0: i32, arg1: i32) -> i32; /// Return environment variable data sizes. - pub fn environ_sizes_get(environc: *mut Size, environ_buf_size: *mut Size) -> Errno; + pub fn environ_sizes_get(arg0: i32, arg1: i32) -> i32; /// Return the resolution of a clock. /// Implementations are required to provide a non-zero value for supported clocks. For unsupported clocks, /// return `errno::inval`. /// Note: This is similar to `clock_getres` in POSIX. - pub fn clock_res_get(id: Clockid, resolution: *mut Timestamp) -> Errno; + pub fn clock_res_get(arg0: i32, arg1: i32) -> i32; /// Return the time value of a clock. /// Note: This is similar to `clock_gettime` in POSIX. - pub fn clock_time_get(id: Clockid, precision: Timestamp, time: *mut Timestamp) -> Errno; + pub fn clock_time_get(arg0: i32, arg1: i64, arg2: i32) -> i32; /// Provide file advisory information on a file descriptor. /// Note: This is similar to `posix_fadvise` in POSIX. - pub fn fd_advise(fd: Fd, offset: Filesize, len: Filesize, advice: Advice) -> Errno; + pub fn fd_advise(arg0: i32, arg1: i64, arg2: i64, arg3: i32) -> i32; /// Force the allocation of space in a file. /// Note: This is similar to `posix_fallocate` in POSIX. - pub fn fd_allocate(fd: Fd, offset: Filesize, len: Filesize) -> Errno; + pub fn fd_allocate(arg0: i32, arg1: i64, arg2: i64) -> i32; /// Close a file descriptor. /// Note: This is similar to `close` in POSIX. - pub fn fd_close(fd: Fd) -> Errno; + pub fn fd_close(arg0: i32) -> i32; /// Synchronize the data of a file to disk. /// Note: This is similar to `fdatasync` in POSIX. - pub fn fd_datasync(fd: Fd) -> Errno; + pub fn fd_datasync(arg0: i32) -> i32; /// Get the attributes of a file descriptor. /// Note: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields. - pub fn fd_fdstat_get(fd: Fd, stat: *mut Fdstat) -> Errno; + pub fn fd_fdstat_get(arg0: i32, arg1: i32) -> i32; /// Adjust the flags associated with a file descriptor. /// Note: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX. - pub fn fd_fdstat_set_flags(fd: Fd, flags: Fdflags) -> Errno; + pub fn fd_fdstat_set_flags(arg0: i32, arg1: i32) -> i32; /// Adjust the rights associated with a file descriptor. /// This can only be used to remove rights, and returns `errno::notcapable` if called in a way that would attempt to add rights - pub fn fd_fdstat_set_rights( - fd: Fd, - fs_rights_base: Rights, - fs_rights_inheriting: Rights, - ) -> Errno; + pub fn fd_fdstat_set_rights(arg0: i32, arg1: i64, arg2: i64) -> i32; /// Return the attributes of an open file. - pub fn fd_filestat_get(fd: Fd, buf: *mut Filestat) -> Errno; + pub fn fd_filestat_get(arg0: i32, arg1: i32) -> i32; /// Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros. /// Note: This is similar to `ftruncate` in POSIX. - pub fn fd_filestat_set_size(fd: Fd, size: Filesize) -> Errno; + pub fn fd_filestat_set_size(arg0: i32, arg1: i64) -> i32; /// Adjust the timestamps of an open file or directory. /// Note: This is similar to `futimens` in POSIX. - pub fn fd_filestat_set_times( - fd: Fd, - atim: Timestamp, - mtim: Timestamp, - fst_flags: Fstflags, - ) -> Errno; + pub fn fd_filestat_set_times(arg0: i32, arg1: i64, arg2: i64, arg3: i32) -> i32; /// Read from a file descriptor, without using and updating the file descriptor's offset. /// Note: This is similar to `preadv` in POSIX. - pub fn fd_pread( - fd: Fd, - iovs_ptr: *const Iovec, - iovs_len: usize, - offset: Filesize, - nread: *mut Size, - ) -> Errno; + pub fn fd_pread(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; /// Return a description of the given preopened file descriptor. - pub fn fd_prestat_get(fd: Fd, buf: *mut Prestat) -> Errno; + pub fn fd_prestat_get(arg0: i32, arg1: i32) -> i32; /// Return a description of the given preopened file descriptor. - pub fn fd_prestat_dir_name(fd: Fd, path: *mut u8, path_len: Size) -> Errno; + pub fn fd_prestat_dir_name(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Write to a file descriptor, without using and updating the file descriptor's offset. /// Note: This is similar to `pwritev` in POSIX. - pub fn fd_pwrite( - fd: Fd, - iovs_ptr: *const Ciovec, - iovs_len: usize, - offset: Filesize, - nwritten: *mut Size, - ) -> Errno; + pub fn fd_pwrite(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; /// Read from a file descriptor. /// Note: This is similar to `readv` in POSIX. - pub fn fd_read(fd: Fd, iovs_ptr: *const Iovec, iovs_len: usize, nread: *mut Size) -> Errno; + pub fn fd_read(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; /// Read directory entries from a directory. /// When successful, the contents of the output buffer consist of a sequence of - /// directory entries. Each directory entry consists of a dirent_t object, - /// followed by dirent_t::d_namlen bytes holding the name of the directory + /// directory entries. Each directory entry consists of a `dirent` object, + /// followed by `dirent::d_namlen` bytes holding the name of the directory /// entry. /// This function fills the output buffer as much as possible, potentially /// truncating the last directory entry. This allows the caller to grow its /// read buffer size in case it's too small to fit a single large directory /// entry, or skip the oversized directory entry. - pub fn fd_readdir( - fd: Fd, - buf: *mut u8, - buf_len: Size, - cookie: Dircookie, - bufused: *mut Size, - ) -> Errno; + pub fn fd_readdir(arg0: i32, arg1: i32, arg2: i32, arg3: i64, arg4: i32) -> i32; /// Atomically replace a file descriptor by renumbering another file descriptor. /// Due to the strong focus on thread safety, this environment does not provide /// a mechanism to duplicate or renumber a file descriptor to an arbitrary @@ -1690,63 +2245,47 @@ pub mod wasi_snapshot_preview1 { /// thread at the same time. /// This function provides a way to atomically renumber file descriptors, which /// would disappear if `dup2()` were to be removed entirely. - pub fn fd_renumber(fd: Fd, to: Fd) -> Errno; + pub fn fd_renumber(arg0: i32, arg1: i32) -> i32; /// Move the offset of a file descriptor. /// Note: This is similar to `lseek` in POSIX. - pub fn fd_seek( - fd: Fd, - offset: Filedelta, - whence: Whence, - newoffset: *mut Filesize, - ) -> Errno; + pub fn fd_seek(arg0: i32, arg1: i64, arg2: i32, arg3: i32) -> i32; /// Synchronize the data and metadata of a file to disk. /// Note: This is similar to `fsync` in POSIX. - pub fn fd_sync(fd: Fd) -> Errno; + pub fn fd_sync(arg0: i32) -> i32; /// Return the current offset of a file descriptor. /// Note: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX. - pub fn fd_tell(fd: Fd, offset: *mut Filesize) -> Errno; + pub fn fd_tell(arg0: i32, arg1: i32) -> i32; /// Write to a file descriptor. /// Note: This is similar to `writev` in POSIX. - pub fn fd_write( - fd: Fd, - iovs_ptr: *const Ciovec, - iovs_len: usize, - nwritten: *mut Size, - ) -> Errno; + pub fn fd_write(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; /// Create a directory. /// Note: This is similar to `mkdirat` in POSIX. - pub fn path_create_directory(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; + pub fn path_create_directory(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Return the attributes of a file or directory. /// Note: This is similar to `stat` in POSIX. - pub fn path_filestat_get( - fd: Fd, - flags: Lookupflags, - path_ptr: *const u8, - path_len: usize, - buf: *mut Filestat, - ) -> Errno; + pub fn path_filestat_get(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; /// Adjust the timestamps of a file or directory. /// Note: This is similar to `utimensat` in POSIX. pub fn path_filestat_set_times( - fd: Fd, - flags: Lookupflags, - path_ptr: *const u8, - path_len: usize, - atim: Timestamp, - mtim: Timestamp, - fst_flags: Fstflags, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i64, + arg5: i64, + arg6: i32, + ) -> i32; /// Create a hard link. /// Note: This is similar to `linkat` in POSIX. pub fn path_link( - old_fd: Fd, - old_flags: Lookupflags, - old_path_ptr: *const u8, - old_path_len: usize, - new_fd: Fd, - new_path_ptr: *const u8, - new_path_len: usize, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i32, + arg5: i32, + arg6: i32, + ) -> i32; /// Open a file or directory. /// The returned file descriptor is not guaranteed to be the lowest-numbered /// file descriptor not currently open; it is randomized to prevent @@ -1755,100 +2294,73 @@ pub mod wasi_snapshot_preview1 { /// guaranteed to be less than 2**31. /// Note: This is similar to `openat` in POSIX. pub fn path_open( - fd: Fd, - dirflags: Lookupflags, - path_ptr: *const u8, - path_len: usize, - oflags: Oflags, - fs_rights_base: Rights, - fs_rights_inherting: Rights, - fdflags: Fdflags, - opened_fd: *mut Fd, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i32, + arg5: i64, + arg6: i64, + arg7: i32, + arg8: i32, + ) -> i32; /// Read the contents of a symbolic link. /// Note: This is similar to `readlinkat` in POSIX. pub fn path_readlink( - fd: Fd, - path_ptr: *const u8, - path_len: usize, - buf: *mut u8, - buf_len: Size, - bufused: *mut Size, - ) -> Errno; + arg0: i32, + arg1: i32, + arg2: i32, + arg3: i32, + arg4: i32, + arg5: i32, + ) -> i32; /// Remove a directory. /// Return `errno::notempty` if the directory is not empty. /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - pub fn path_remove_directory(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; + pub fn path_remove_directory(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Rename a file or directory. /// Note: This is similar to `renameat` in POSIX. - pub fn path_rename( - fd: Fd, - old_path_ptr: *const u8, - old_path_len: usize, - new_fd: Fd, - new_path_ptr: *const u8, - new_path_len: usize, - ) -> Errno; + pub fn path_rename(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32) + -> i32; /// Create a symbolic link. /// Note: This is similar to `symlinkat` in POSIX. - pub fn path_symlink( - old_path_ptr: *const u8, - old_path_len: usize, - fd: Fd, - new_path_ptr: *const u8, - new_path_len: usize, - ) -> Errno; + pub fn path_symlink(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; /// Unlink a file. /// Return `errno::isdir` if the path refers to a directory. /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - pub fn path_unlink_file(fd: Fd, path_ptr: *const u8, path_len: usize) -> Errno; + pub fn path_unlink_file(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Concurrently poll for the occurrence of a set of events. - pub fn poll_oneoff( - r#in: *const Subscription, - out: *mut Event, - nsubscriptions: Size, - nevents: *mut Size, - ) -> Errno; + pub fn poll_oneoff(arg0: i32, arg1: i32, arg2: i32, arg3: i32) -> i32; /// Terminate the process normally. An exit code of 0 indicates successful /// termination of the program. The meanings of other values is dependent on /// the environment. - pub fn proc_exit(rval: Exitcode) -> !; + pub fn proc_exit(arg0: i32) -> !; /// Send a signal to the process of the calling thread. /// Note: This is similar to `raise` in POSIX. - pub fn proc_raise(sig: Signal) -> Errno; + pub fn proc_raise(arg0: i32) -> i32; /// Temporarily yield execution of the calling thread. /// Note: This is similar to `sched_yield` in POSIX. - pub fn sched_yield() -> Errno; + pub fn sched_yield() -> i32; /// Write high-quality random data into a buffer. /// This function blocks when the implementation is unable to immediately /// provide sufficient high-quality random data. /// This function may execute slowly, so when large mounts of random data are /// required, it's advisable to use this function to seed a pseudo-random /// number generator, rather than to provide the random data directly. - pub fn random_get(buf: *mut u8, buf_len: Size) -> Errno; + pub fn random_get(arg0: i32, arg1: i32) -> i32; + /// Accept a new incoming connection. + /// Note: This is similar to `accept` in POSIX. + pub fn sock_accept(arg0: i32, arg1: i32, arg2: i32) -> i32; /// Receive a message from a socket. /// Note: This is similar to `recv` in POSIX, though it also supports reading /// the data into multiple buffers in the manner of `readv`. - pub fn sock_recv( - fd: Fd, - ri_data_ptr: *const Iovec, - ri_data_len: usize, - ri_flags: Riflags, - ro_datalen: *mut Size, - ro_flags: *mut Roflags, - ) -> Errno; + pub fn sock_recv(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32, arg5: i32) -> i32; /// Send a message on a socket. /// Note: This is similar to `send` in POSIX, though it also supports writing /// the data from multiple buffers in the manner of `writev`. - pub fn sock_send( - fd: Fd, - si_data_ptr: *const Ciovec, - si_data_len: usize, - si_flags: Siflags, - so_datalen: *mut Size, - ) -> Errno; + pub fn sock_send(arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: i32) -> i32; /// Shut down socket send and receive channels. /// Note: This is similar to `shutdown` in POSIX. - pub fn sock_shutdown(fd: Fd, how: Sdflags) -> Errno; + pub fn sock_shutdown(arg0: i32, arg1: i32) -> i32; } } From 381a82e50417adc2478d1a25e9fcec32e162969f Mon Sep 17 00:00:00 2001 From: Butkovits Atila Date: Thu, 16 Jun 2022 01:20:24 +0300 Subject: [PATCH 37/64] Backed out changeset df17ec7a8095 (bug 1774377) for causing assertion failures at ErrorResult.h. CLOSED TREE --- browser/base/content/browser-menubar.inc | 5 --- browser/base/content/browser.js | 34 +---------------- browser/base/content/macWindow.inc.xhtml | 3 -- browser/base/content/nonbrowser-mac.js | 5 --- browser/base/content/tabbrowser.js | 2 +- browser/base/content/utilityOverlay.js | 2 +- .../customizableui/CustomizableWidgets.jsm | 38 ++++++++++++++++++- .../components/firefoxview/firefoxView.ftl | 4 -- .../tests/browser/browser_firefoxview_tab.js | 20 +++++----- .../components/sessionstore/SessionStore.jsm | 4 +- browser/themes/shared/tabs.css | 4 +- 11 files changed, 54 insertions(+), 67 deletions(-) diff --git a/browser/base/content/browser-menubar.inc b/browser/base/content/browser-menubar.inc index 0245d27a7288..48bed2a96849 100644 --- a/browser/base/content/browser-menubar.inc +++ b/browser/base/content/browser-menubar.inc @@ -392,11 +392,6 @@ class="sync-ui-item" hidden="true" oncommand="gSync.openSignInAgainPage('menubar');" data-l10n-id="menu-tools-fxa-re-auth"/> - -#ifdef NIGHTLY_BUILD - -#endif diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index 7a9a596966ff..ce10a28e6225 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -565,6 +565,7 @@ var gMultiProcessBrowser = window.docShell.QueryInterface(Ci.nsILoadContext) .useRemoteTabs; var gFissionBrowser = window.docShell.QueryInterface(Ci.nsILoadContext) .useRemoteSubframes; +var gFirefoxViewTab; var gBrowserAllowScriptsToCloseInitialTabs = false; @@ -1996,8 +1997,6 @@ var gBrowserInit = { ctrlTab.readPref(); Services.prefs.addObserver(ctrlTab.prefName, ctrlTab); - FirefoxViewHandler.init(); - // The object handling the downloads indicator is initialized here in the // delayed startup function, but the actual indicator element is not loaded // unless there are downloads to be displayed. @@ -10029,34 +10028,3 @@ var ConfirmationHint = { } }, }; - -var FirefoxViewHandler = { - tab: null, - init() { - if (!Services.prefs.getBoolPref("browser.tabs.firefox-view")) { - document.getElementById("menu_openFirefoxView").hidden = true; - } - }, - openTab() { - if (!this.tab) { - this.tab = gBrowser.addTrustedTab("about:firefoxview", { index: 0 }); - this.tab.addEventListener("TabClose", this, { once: true }); - gBrowser.tabContainer.addEventListener("TabSelect", this); - gBrowser.hideTab(this.tab); - } - gBrowser.selectedTab = this.tab; - }, - handleEvent(e) { - switch (e.type) { - case "TabSelect": - document - .getElementById("firefox-view-button") - ?.toggleAttribute("open", e.target == this.tab); - break; - case "TabClose": - this.tab = null; - gBrowser.tabContainer.removeEventListener("TabSelect", this); - break; - } - }, -}; diff --git a/browser/base/content/macWindow.inc.xhtml b/browser/base/content/macWindow.inc.xhtml index 5be2c3bb8832..f13f6b2a2872 100644 --- a/browser/base/content/macWindow.inc.xhtml +++ b/browser/base/content/macWindow.inc.xhtml @@ -16,9 +16,6 @@ -#ifdef NIGHTLY_BUILD - -#endif # All JS files which are needed by browser.xhtml and other top level windows to diff --git a/browser/base/content/nonbrowser-mac.js b/browser/base/content/nonbrowser-mac.js index 6615c8d3bf57..a499db807738 100644 --- a/browser/base/content/nonbrowser-mac.js +++ b/browser/base/content/nonbrowser-mac.js @@ -46,7 +46,6 @@ function nonBrowserWindowStartup() { "Browser:BookmarkAllTabs", "View:PageInfo", "History:UndoCloseTab", - "menu_openFirefoxView", ]; var element; @@ -128,10 +127,6 @@ function nonBrowserWindowDelayedStartup() { // initialize the private browsing UI gPrivateBrowsingUI.init(); - - if (!Services.prefs.getBoolPref("browser.tabs.firefox-view")) { - document.getElementById("menu_openFirefoxView").hidden = true; - } } function nonBrowserWindowShutdown() { diff --git a/browser/base/content/tabbrowser.js b/browser/base/content/tabbrowser.js index e4dcce259ce3..0a6edc3ebf43 100644 --- a/browser/base/content/tabbrowser.js +++ b/browser/base/content/tabbrowser.js @@ -1108,7 +1108,7 @@ this._selectedBrowser = newBrowser; this._selectedTab = newTab; - if (newTab != FirefoxViewHandler.tab) { + if (newTab != gFirefoxViewTab) { this.showTab(newTab); } diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js index 4f1e0f17bd95..8afaccf7b5d3 100644 --- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -525,7 +525,7 @@ function openLinkIn(url, where, params) { // page. If a load request bounces off for the currently selected tab, // we'll open a new tab instead. let tab = w.gBrowser.getTabForBrowser(targetBrowser); - if (tab == w.FirefoxViewHandler.tab) { + if (tab == w.gFirefoxViewTab) { where = "tab"; targetBrowser = null; } else if ( diff --git a/browser/components/customizableui/CustomizableWidgets.jsm b/browser/components/customizableui/CustomizableWidgets.jsm index ea5fb88e5e5b..59d5d8aaa693 100644 --- a/browser/components/customizableui/CustomizableWidgets.jsm +++ b/browser/components/customizableui/CustomizableWidgets.jsm @@ -467,7 +467,43 @@ const CustomizableWidgets = [ return Services.prefs.getBoolPref("browser.tabs.firefox-view"); }, onCommand(e) { - e.view.FirefoxViewHandler.openTab(); + let button = e.target; + if (button.hasAttribute("open")) { + return; + } + let window = button.ownerGlobal; + let tabbrowser = window.gBrowser; + let tab = window.gFirefoxViewTab; + if (!tab) { + tab = tabbrowser.addTrustedTab("about:firefoxview", { index: 0 }); + tabbrowser.hideTab(tab); + window.gFirefoxViewTab = tab; + + let onTabSelect = event => { + button.toggleAttribute("open", event.target == tab); + }; + + let onTabClose = () => { + window.gFirefoxViewTab = null; + tabbrowser.tabContainer.removeEventListener("TabSelect", onTabSelect); + }; + + tabbrowser.tabContainer.addEventListener("TabSelect", onTabSelect); + tab.addEventListener("TabClose", onTabClose, { once: true }); + + window.addEventListener( + "unload", + () => { + tabbrowser.tabContainer.removeEventListener( + "TabSelect", + onTabSelect + ); + tab.removeEventListener("TabClose", onTabClose); + }, + { once: true } + ); + } + tabbrowser.selectedTab = tab; }, }, ]; diff --git a/browser/components/firefoxview/firefoxView.ftl b/browser/components/firefoxview/firefoxView.ftl index c4654379d5fb..daf2e5647234 100644 --- a/browser/components/firefoxview/firefoxView.ftl +++ b/browser/components/firefoxview/firefoxView.ftl @@ -8,10 +8,6 @@ toolbar-button-firefox-view = .label = { -firefoxview-brand-name } .tooltiptext = { -firefoxview-brand-name } -menu-tools-firefox-view = - .label = { -firefoxview-brand-name } - .accesskey = F - firefoxview-page-title = { -firefoxview-brand-name } # Used instead of the localized relative time when a timestamp is within a minute or so of now diff --git a/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js b/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js index 4212475fdb46..481600d6ee6e 100644 --- a/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js +++ b/browser/components/firefoxview/tests/browser/browser_firefoxview_tab.js @@ -18,15 +18,15 @@ add_setup(async function() { }); function assertFirefoxViewTab(w = window) { - ok(w.FirefoxViewHandler.tab, "Firefox View tab exists"); - ok(w.FirefoxViewHandler.tab?.hidden, "Firefox View tab is hidden"); + ok(w.gFirefoxViewTab, "Firefox View tab exists"); + ok(w.gFirefoxViewTab?.hidden, "Firefox View tab is hidden"); is( - w.gBrowser.tabs.indexOf(w.FirefoxViewHandler.tab), + w.gBrowser.tabs.indexOf(w.gFirefoxViewTab), 0, "Firefox View tab is the first tab" ); is( - w.gBrowser.visibleTabs.indexOf(w.FirefoxViewHandler.tab), + w.gBrowser.visibleTabs.indexOf(w.gFirefoxViewTab), -1, "Firefox View tab is not in the list of visible tabs" ); @@ -34,7 +34,7 @@ function assertFirefoxViewTab(w = window) { async function openFirefoxViewTab(w = window) { ok( - !w.FirefoxViewHandler.tab, + !w.gFirefoxViewTab, "Firefox View tab doesn't exist prior to clicking the button" ); info("Clicking the Firefox View button"); @@ -45,14 +45,14 @@ async function openFirefoxViewTab(w = window) { ); assertFirefoxViewTab(w); is(w.gBrowser.tabContainer.selectedIndex, 0, "Firefox View tab is selected"); - await BrowserTestUtils.browserLoaded(w.FirefoxViewHandler.tab.linkedBrowser); - return w.FirefoxViewHandler.tab; + await BrowserTestUtils.browserLoaded(w.gFirefoxViewTab.linkedBrowser); + return w.gFirefoxViewTab; } function closeFirefoxViewTab(w = window) { - w.gBrowser.removeTab(w.FirefoxViewHandler.tab); + w.gBrowser.removeTab(w.gFirefoxViewTab); ok( - !w.FirefoxViewHandler.tab, + !w.gFirefoxViewTab, "Reference to Firefox View tab got removed when closing the tab" ); } @@ -98,7 +98,7 @@ add_task(async function accel_w_behavior() { let win = await BrowserTestUtils.openNewBrowserWindow(); await openFirefoxViewTab(win); EventUtils.synthesizeKey("w", { accelKey: true }, win); - ok(!win.FirefoxViewHandler.tab, "Accel+w closed the Firefox View tab"); + ok(!win.gFirefoxViewTab, "Accel+w closed the Firefox View tab"); await openFirefoxViewTab(win); win.gBrowser.selectedTab = win.gBrowser.visibleTabs[0]; info( diff --git a/browser/components/sessionstore/SessionStore.jsm b/browser/components/sessionstore/SessionStore.jsm index 9b2730f1d525..94edaf6eebef 100644 --- a/browser/components/sessionstore/SessionStore.jsm +++ b/browser/components/sessionstore/SessionStore.jsm @@ -2547,7 +2547,7 @@ var SessionStoreInternal = { if (!isPrivateWindow && tabState.isPrivate) { return; } - if (aTab == aWindow.FirefoxViewHandler.tab) { + if (aTab == aWindow.gFirefoxViewTab) { return; } @@ -4130,7 +4130,7 @@ var SessionStoreInternal = { // update the internal state data for this window for (let tab of tabs) { - if (tab == aWindow.FirefoxViewHandler.tab) { + if (tab == aWindow.gFirefoxViewTab) { continue; } let tabData = lazy.TabState.collect(tab, TAB_CUSTOM_VALUES.get(tab)); diff --git a/browser/themes/shared/tabs.css b/browser/themes/shared/tabs.css index 801565a83263..fea6a7b8e368 100644 --- a/browser/themes/shared/tabs.css +++ b/browser/themes/shared/tabs.css @@ -681,7 +681,7 @@ } } -/* Firefox View button and menu item */ +/* Firefox View button */ :root:not([privatebrowsingmode=temporary]) :is(#firefox-view-button, #wrapper-firefox-view-button) + #tabbrowser-tabs { border-inline-start: 1px solid color-mix(in srgb, currentColor 25%, transparent); @@ -689,7 +689,7 @@ margin-inline-start: 4px; } -:root[privatebrowsingmode=temporary] :is(#firefox-view-button, #menu_openFirefoxView) { +:root[privatebrowsingmode=temporary] #firefox-view-button { display: none; } From 2337bc5418ce36498243294ca8b25f354d0e2532 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Wed, 15 Jun 2022 22:20:53 +0000 Subject: [PATCH 38/64] Bug 1772299 - Reject modification to globalThis inside system module. r=Standard8,webdriver-reviewers,jdescottes Differential Revision: https://phabricator.services.mozilla.com/D148116 --- .../lint/linters/eslint-plugin-mozilla.rst | 1 + .../reject-globalThis-modification.rst | 19 ++++ remote/cdp/domains/content/Runtime.jsm | 1 + testing/modules/CoverageUtils.jsm | 1 + .../certviewer/content/certDecoder.jsm | 2 + .../lib/configs/recommended.js | 1 + .../eslint/eslint-plugin-mozilla/lib/index.js | 1 + .../rules/reject-globalThis-modification.js | 70 +++++++++++++++ .../tests/reject-globalThis-modification.js | 90 +++++++++++++++++++ 9 files changed, 186 insertions(+) create mode 100644 docs/code-quality/lint/linters/eslint-plugin-mozilla/reject-globalThis-modification.rst create mode 100644 tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-globalThis-modification.js create mode 100644 tools/lint/eslint/eslint-plugin-mozilla/tests/reject-globalThis-modification.js diff --git a/docs/code-quality/lint/linters/eslint-plugin-mozilla.rst b/docs/code-quality/lint/linters/eslint-plugin-mozilla.rst index 79695ac0eecb..3dfa5154acfc 100644 --- a/docs/code-quality/lint/linters/eslint-plugin-mozilla.rst +++ b/docs/code-quality/lint/linters/eslint-plugin-mozilla.rst @@ -49,6 +49,7 @@ The plugin implements the following rules: eslint-plugin-mozilla/reject-addtask-only eslint-plugin-mozilla/reject-chromeutils-import-params eslint-plugin-mozilla/reject-global-this + eslint-plugin-mozilla/reject-globalThis-modification eslint-plugin-mozilla/reject-importGlobalProperties eslint-plugin-mozilla/reject-osfile eslint-plugin-mozilla/reject-relative-requires diff --git a/docs/code-quality/lint/linters/eslint-plugin-mozilla/reject-globalThis-modification.rst b/docs/code-quality/lint/linters/eslint-plugin-mozilla/reject-globalThis-modification.rst new file mode 100644 index 000000000000..402cf133cb4b --- /dev/null +++ b/docs/code-quality/lint/linters/eslint-plugin-mozilla/reject-globalThis-modification.rst @@ -0,0 +1,19 @@ +reject-globalThis-modification +============================== + +Reject any modification to ``globalThis`` inside the system modules. + +``globalThis`` is the shared global inside the system modules, and modification +on it is visible from all modules, and it shouldn't be done unless it's really +necessary. + +Examples of incorrect code for this rule: +----------------------------------------- + +.. code-block:: js + + globalThis.foo = 10; + Object.defineProperty(globalThis, "bar", { value: 20}); + XPCOMUtils.defineLazyModuleGetters(globalThis, { + Services: "resource://gre/modules/Services.jsm", + }); diff --git a/remote/cdp/domains/content/Runtime.jsm b/remote/cdp/domains/content/Runtime.jsm index add37225695e..fe1725938dd8 100644 --- a/remote/cdp/domains/content/Runtime.jsm +++ b/remote/cdp/domains/content/Runtime.jsm @@ -33,6 +33,7 @@ XPCOMUtils.defineLazyGetter(lazy, "ConsoleAPIStorage", () => { }); // Import the `Debugger` constructor in the current scope +// eslint-disable-next-line mozilla/reject-globalThis-modification addDebuggerToGlobal(globalThis); const CONSOLE_API_LEVEL_MAP = { diff --git a/testing/modules/CoverageUtils.jsm b/testing/modules/CoverageUtils.jsm index ae4eb9902fd2..a9bc68c3090d 100644 --- a/testing/modules/CoverageUtils.jsm +++ b/testing/modules/CoverageUtils.jsm @@ -10,6 +10,7 @@ var EXPORTED_SYMBOLS = ["CoverageCollector"]; const { addDebuggerToGlobal } = ChromeUtils.import( "resource://gre/modules/jsdebugger.jsm" ); +// eslint-disable-next-line mozilla/reject-globalThis-modification addDebuggerToGlobal(globalThis); /** diff --git a/toolkit/components/certviewer/content/certDecoder.jsm b/toolkit/components/certviewer/content/certDecoder.jsm index 87a694bc12d7..9c3b7f96de98 100644 --- a/toolkit/components/certviewer/content/certDecoder.jsm +++ b/toolkit/components/certviewer/content/certDecoder.jsm @@ -1297,6 +1297,8 @@ function certDecoderInitializer( return { parse, pemToDER }; } +// This must be removed when all consumer is converted to ES module. +// eslint-disable-next-line mozilla/reject-globalThis-modification globalThis.certDecoderInitializer = certDecoderInitializer; /* eslint-disable-next-line no-unused-vars */ var EXPORTED_SYMBOLS = ["certDecoderInitializer"]; diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js index 6d48cbdcc5a3..77be19894f7d 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js @@ -51,6 +51,7 @@ module.exports = { files: ["**/*.sys.mjs", "**/*.jsm", "**/*.jsm.js"], rules: { "mozilla/reject-global-this": "error", + "mozilla/reject-globalThis-modification": "error", "mozilla/reject-top-level-await": "error", // Bug 1703953: We don't have a good way to check a file runs in a // privilieged context. Apply this for these files as we know those are diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/index.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/index.js index b7f3a733b0bf..c37e8ab91a23 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/index.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/index.js @@ -55,6 +55,7 @@ module.exports = { "reject-addtask-only": require("../lib/rules/reject-addtask-only"), "reject-chromeutils-import-params": require("../lib/rules/reject-chromeutils-import-params"), "reject-global-this": require("../lib/rules/reject-global-this"), + "reject-globalThis-modification": require("../lib/rules/reject-globalThis-modification"), "reject-import-system-module-from-non-system": require("../lib/rules/reject-import-system-module-from-non-system"), "reject-importGlobalProperties": require("../lib/rules/reject-importGlobalProperties"), "reject-osfile": require("../lib/rules/reject-osfile"), diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-globalThis-modification.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-globalThis-modification.js new file mode 100644 index 000000000000..11c726101433 --- /dev/null +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-globalThis-modification.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Enforce the standard object name for + * ChromeUtils.defineESMGetters + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +"use strict"; + +function isIdentifier(node, id) { + return node.type === "Identifier" && node.name === id; +} + +function calleeToString(node) { + if (node.type === "Identifier") { + return node.name; + } + + if (node.type === "MemberExpression" && !node.computed) { + return calleeToString(node.object) + "." + node.property.name; + } + + return "???"; +} + +module.exports = { + meta: { + docs: { + url: + "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/reject-globalThis-modification.html", + }, + type: "problem", + }, + + create(context) { + return { + AssignmentExpression(node, parents) { + let target = node.left; + while (target.type === "MemberExpression") { + target = target.object; + } + if (isIdentifier(target, "globalThis")) { + context.report({ + node, + message: + "`globalThis` shouldn't be modified. `globalThis` is the shared global inside the system module, and properties defined on it is visible from all modules.", + }); + } + }, + CallExpression(node) { + const calleeStr = calleeToString(node.callee); + if (calleeStr.endsWith(".deserialize")) { + return; + } + + for (const arg of node.arguments) { + if (isIdentifier(arg, "globalThis")) { + context.report({ + node, + message: + "`globalThis` shouldn't be passed to function that can modify it. `globalThis` is the shared global inside the system module, and properties defined on it is visible from all modules.", + }); + } + } + }, + }; + }, +}; diff --git a/tools/lint/eslint/eslint-plugin-mozilla/tests/reject-globalThis-modification.js b/tools/lint/eslint/eslint-plugin-mozilla/tests/reject-globalThis-modification.js new file mode 100644 index 000000000000..493bcdf27dfe --- /dev/null +++ b/tools/lint/eslint/eslint-plugin-mozilla/tests/reject-globalThis-modification.js @@ -0,0 +1,90 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// ------------------------------------------------------------------------------ +// Requirements +// ------------------------------------------------------------------------------ + +var rule = require("../lib/rules/reject-globalThis-modification"); +var RuleTester = require("eslint").RuleTester; + +const ruleTester = new RuleTester(); + +// ------------------------------------------------------------------------------ +// Tests +// ------------------------------------------------------------------------------ + +function invalidCall(code) { + return { + code, + errors: [ + { + message: + "`globalThis` shouldn't be passed to function that can modify it. `globalThis` is the shared global inside the system module, and properties defined on it is visible from all modules.", + type: "CallExpression", + }, + ], + }; +} + +function invalidAssignment(code) { + return { + code, + errors: [ + { + message: + "`globalThis` shouldn't be modified. `globalThis` is the shared global inside the system module, and properties defined on it is visible from all modules.", + type: "AssignmentExpression", + }, + ], + }; +} + +ruleTester.run("reject-globalThis-modification", rule, { + valid: [ + `var x = globalThis.Array;`, + `Array in globalThis;`, + `result.deserialize(globalThis)`, + ], + invalid: [ + invalidAssignment(` + globalThis.foo = 10; +`), + invalidCall(` + Object.defineProperty(globalThis, "foo", { value: 10 }); +`), + invalidCall(` + Object.defineProperties(globalThis, { + foo: { value: 10 }, + }); +`), + invalidCall(` + Object.assign(globalThis, { foo: 10 }); +`), + invalidCall(` + ChromeUtils.defineModuleGetter( + globalThis, "Services", "resource://gre/modules/Services.jsm" + ); +`), + invalidCall(` + ChromeUtils.defineESMGetters(globalThis, { + Services: "resource://gre/modules/Services.sys.mjs", + }); +`), + invalidCall(` + XPCOMUtils.defineLazyModuleGetter( + globalThis, "Services", "resource://gre/modules/Services.jsm" + ); +`), + invalidCall(` + XPCOMUtils.defineLazyModuleGetters(globalThis, { + Services: "resource://gre/modules/Services.jsm", + }); +`), + invalidCall(` + someFunction(1, globalThis); +`), + ], +}); From b16c4d741ff7335340181b4d79d7d6e6b69bf288 Mon Sep 17 00:00:00 2001 From: Masayuki Nakano Date: Wed, 15 Jun 2022 22:31:38 +0000 Subject: [PATCH 39/64] Bug 1770877 - part 1: Make `HTMLEditor::CreateOrChangeBlockContainerElement` stop touching `Selection` directly r=m_kato Although the its only caller does not need the caret position, it should return a candidate caret position for aligning to the other methods. Differential Revision: https://phabricator.services.mozilla.com/D149065 --- editor/libeditor/HTMLEditSubActionHandler.cpp | 140 +++++++----------- editor/libeditor/HTMLEditor.h | 8 +- 2 files changed, 58 insertions(+), 90 deletions(-) diff --git a/editor/libeditor/HTMLEditSubActionHandler.cpp b/editor/libeditor/HTMLEditSubActionHandler.cpp index b64fc0e9acc6..9e82855e835b 100644 --- a/editor/libeditor/HTMLEditSubActionHandler.cpp +++ b/editor/libeditor/HTMLEditSubActionHandler.cpp @@ -3794,7 +3794,7 @@ nsresult HTMLEditor::RemoveListAtSelectionAsSubAction() { nsresult HTMLEditor::FormatBlockContainerWithTransaction(nsAtom& blockType) { MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable()); - RefPtr editingHost = ComputeEditingHost(); + const RefPtr editingHost = ComputeEditingHost(); if (MOZ_UNLIKELY(NS_WARN_IF(!editingHost))) { return NS_ERROR_FAILURE; } @@ -3977,11 +3977,16 @@ nsresult HTMLEditor::FormatBlockContainerWithTransaction(nsAtom& blockType) { "HTMLEditor::RemoveBlockContainerElements() failed"); return rv; } - rv = CreateOrChangeBlockContainerElement(arrayOfContents, blockType); - NS_WARNING_ASSERTION( - NS_SUCCEEDED(rv), - "HTMLEditor::CreateOrChangeBlockContainerElement() failed"); - return rv; + Result wrapContentsInBlockElementResult = + CreateOrChangeBlockContainerElement(arrayOfContents, blockType, + *editingHost); + if (MOZ_UNLIKELY(wrapContentsInBlockElementResult.isErr())) { + NS_WARNING("HTMLEditor::CreateOrChangeBlockContainerElement() failed"); + return wrapContentsInBlockElementResult.unwrapErr(); + } + // Selection will be restored by `restoreSelectionLater`. Therefore, we + // should ignore the suggested caret point. + return NS_OK; } nsresult HTMLEditor::MaybeInsertPaddingBRElementForEmptyLastLineAtSelection() { @@ -8470,20 +8475,17 @@ nsresult HTMLEditor::RemoveBlockContainerElements( return NS_OK; } -nsresult HTMLEditor::CreateOrChangeBlockContainerElement( - nsTArray>& aArrayOfContents, nsAtom& aBlockTag) { +Result +HTMLEditor::CreateOrChangeBlockContainerElement( + nsTArray>& aArrayOfContents, nsAtom& aBlockTag, + const Element& aEditingHost) { MOZ_ASSERT(IsTopLevelEditSubActionDataAvailable()); - RefPtr editingHost = ComputeEditingHost(); - if (MOZ_UNLIKELY(NS_WARN_IF(!editingHost))) { - return NS_ERROR_FAILURE; - } - // Intent of this routine is to be used for converting to/from headers, // paragraphs, pre, and address. Those blocks that pretty much just contain // inline things... - nsCOMPtr newBlock; - nsCOMPtr curBlock; + RefPtr newBlock, curBlock; + EditorDOMPoint pointToPutCaret; for (auto& content : aArrayOfContents) { EditorDOMPoint atContent(content); if (NS_WARN_IF(!atContent.IsInContentNode())) { @@ -8519,26 +8521,17 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( NS_WARNING( "EditorBase::ReplaceContainerAndCloneAttributesWithTransaction() " "failed"); - return newBlockElementOrError.unwrapErr(); + return Err(newBlockElementOrError.unwrapErr()); } // If the new block element was moved to different element or removed by // the web app via mutation event listener, we should stop handling this // action since we cannot handle each of a lot of edge cases. if (NS_WARN_IF(newBlockElementOrError.GetNewNode()->GetParentNode() != atContent.GetContainer())) { - return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE; + return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE); } - nsresult rv = newBlockElementOrError.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion, - SuggestCaret::OnlyIfTransactionsAllowedToDoIt, - SuggestCaret::AndIgnoreTrivialError}); - if (NS_FAILED(rv)) { - NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed"); - return rv; - } - NS_WARNING_ASSERTION( - rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR, - "CreateElementResult::SuggestCaretPointTo() failed, but ignored"); + newBlockElementOrError.MoveCaretPointTo( + pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion}); newBlock = newBlockElementOrError.UnwrapNewNode(); continue; } @@ -8554,12 +8547,16 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( AutoTArray, 24> childContents; HTMLEditor::GetChildNodesOf(*content, childContents); if (!childContents.IsEmpty()) { - nsresult rv = - CreateOrChangeBlockContainerElement(childContents, aBlockTag); - if (NS_FAILED(rv)) { + Result wrapChildrenInBlockElementResult = + CreateOrChangeBlockContainerElement(childContents, aBlockTag, + aEditingHost); + if (MOZ_UNLIKELY(wrapChildrenInBlockElementResult.isErr())) { NS_WARNING( "HTMLEditor::CreateOrChangeBlockContainerElement() failed"); - return rv; + return wrapChildrenInBlockElementResult; + } + if (wrapChildrenInBlockElementResult.inspect().IsSet()) { + pointToPutCaret = wrapChildrenInBlockElementResult.unwrap(); } continue; } @@ -8568,7 +8565,7 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( CreateElementResult createNewBlockElementResult = InsertElementWithSplittingAncestorsWithTransaction( aBlockTag, atContent, BRElementNextToSplitPoint::Keep, - *editingHost); + aEditingHost); if (createNewBlockElementResult.isErr()) { NS_WARNING( nsPrintfCString( @@ -8576,15 +8573,10 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( "InsertElementWithSplittingAncestorsWithTransaction(%s) failed", nsAtomCString(&aBlockTag).get()) .get()); - return createNewBlockElementResult.unwrapErr(); - } - nsresult rv = createNewBlockElementResult.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion, - SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); - if (NS_FAILED(rv)) { - NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed"); - return rv; + return Err(createNewBlockElementResult.unwrapErr()); } + createNewBlockElementResult.MoveCaretPointTo( + pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion}); MOZ_ASSERT(createNewBlockElementResult.GetNewNode()); // Remember our new block for postprocessing TopLevelEditSubActionDataRef().mNewBlockElement = @@ -8603,7 +8595,7 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(*content)); if (NS_FAILED(rv)) { NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed"); - return rv; + return Err(rv); } continue; } @@ -8613,7 +8605,7 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( CreateElementResult createNewBlockElementResult = InsertElementWithSplittingAncestorsWithTransaction( aBlockTag, atContent, BRElementNextToSplitPoint::Keep, - *editingHost); + aEditingHost); if (createNewBlockElementResult.isErr()) { NS_WARNING( nsPrintfCString( @@ -8621,15 +8613,10 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( "InsertElementWithSplittingAncestorsWithTransaction(%s) failed", nsAtomCString(&aBlockTag).get()) .get()); - return createNewBlockElementResult.unwrapErr(); - } - nsresult rv = createNewBlockElementResult.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion, - SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); - if (NS_FAILED(rv)) { - NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed"); - return rv; + return Err(createNewBlockElementResult.unwrapErr()); } + createNewBlockElementResult.MoveCaretPointTo( + pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion}); RefPtr newBlockElement = createNewBlockElementResult.UnwrapNewNode(); MOZ_ASSERT(newBlockElement); @@ -8638,23 +8625,14 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( TopLevelEditSubActionDataRef().mNewBlockElement = newBlockElement; // MOZ_KnownLive because 'aArrayOfContents' is guaranteed to keep it // alive. - const MoveNodeResult moveNodeResult = MoveNodeToEndWithTransaction( + MoveNodeResult moveNodeResult = MoveNodeToEndWithTransaction( MOZ_KnownLive(content), *newBlockElement); if (moveNodeResult.isErr()) { NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed"); - return moveNodeResult.unwrapErr(); + return Err(moveNodeResult.unwrapErr()); } - rv = moveNodeResult.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion, - SuggestCaret::OnlyIfTransactionsAllowedToDoIt, - SuggestCaret::AndIgnoreTrivialError}); - if (NS_FAILED(rv)) { - NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed"); - return rv; - } - NS_WARNING_ASSERTION( - rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR, - "MoveNodeResult::SuggestCaretPointTo() failed, but ignored"); + moveNodeResult.MoveCaretPointTo(pointToPutCaret, + {SuggestCaret::OnlyIfHasSuggestion}); curBlock = std::move(newBlockElement); continue; } @@ -8678,22 +8656,17 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( CreateElementResult createNewBlockElementResult = InsertElementWithSplittingAncestorsWithTransaction( aBlockTag, atContent, BRElementNextToSplitPoint::Keep, - *editingHost); + aEditingHost); if (createNewBlockElementResult.isErr()) { NS_WARNING(nsPrintfCString("HTMLEditor::" "InsertElementWithSplittingAncestorsWithTr" "ansaction(%s) failed", nsAtomCString(&aBlockTag).get()) .get()); - return createNewBlockElementResult.unwrapErr(); - } - nsresult rv = createNewBlockElementResult.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion, - SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); - if (NS_FAILED(rv)) { - NS_WARNING("CreateElementResult::SuggestCaretPointTo() failed"); - return rv; + return Err(createNewBlockElementResult.unwrapErr()); } + createNewBlockElementResult.MoveCaretPointTo( + pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion}); MOZ_ASSERT(createNewBlockElementResult.GetNewNode()); curBlock = createNewBlockElementResult.UnwrapNewNode(); @@ -8707,7 +8680,7 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement( if (NS_WARN_IF(!atContent.IsSet())) { // This is possible due to mutation events, let's not assert - return NS_ERROR_UNEXPECTED; + return Err(NS_ERROR_UNEXPECTED); } // XXX If content is a br, replace it with a return if going to
@@ -8719,26 +8692,17 @@ nsresult HTMLEditor::CreateOrChangeBlockContainerElement(
       // alive.  We could try to make that a rvalue ref and create a const array
       // on the stack here, but callers are passing in auto arrays, and we don't
       // want to introduce copies..
-      const MoveNodeResult moveNodeResult =
+      MoveNodeResult moveNodeResult =
           MoveNodeToEndWithTransaction(MOZ_KnownLive(content), *curBlock);
       if (moveNodeResult.isErr()) {
         NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
-        return moveNodeResult.unwrapErr();
+        return Err(moveNodeResult.unwrapErr());
       }
-      nsresult rv = moveNodeResult.SuggestCaretPointTo(
-          *this, {SuggestCaret::OnlyIfHasSuggestion,
-                  SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
-                  SuggestCaret::AndIgnoreTrivialError});
-      if (NS_FAILED(rv)) {
-        NS_WARNING("MoveNodeResult::SuggestCaretPointTo() failed");
-        return rv;
-      }
-      NS_WARNING_ASSERTION(
-          rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
-          "MoveNodeResult::SuggestCaretPointTo() failed, but ignored");
+      moveNodeResult.MoveCaretPointTo(pointToPutCaret,
+                                      {SuggestCaret::OnlyIfHasSuggestion});
     }
   }
-  return NS_OK;
+  return pointToPutCaret;
 }
 
 SplitNodeResult HTMLEditor::MaybeSplitAncestorsForInsertWithTransaction(
diff --git a/editor/libeditor/HTMLEditor.h b/editor/libeditor/HTMLEditor.h
index 3080db5c6e36..a26642c0bf3a 100644
--- a/editor/libeditor/HTMLEditor.h
+++ b/editor/libeditor/HTMLEditor.h
@@ -1613,9 +1613,13 @@ class HTMLEditor final : public EditorBase,
    *
    * @param aArrayOfContents    Must be descendants of a node.
    * @param aBlockTag           The element name of new block elements.
+   * @param aEditingHost        The editing host.
+   * @return                    May suggest a point to put caret if succeeded.
    */
-  [[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult CreateOrChangeBlockContainerElement(
-      nsTArray>& aArrayOfContents, nsAtom& aBlockTag);
+  [[nodiscard]] MOZ_CAN_RUN_SCRIPT Result
+  CreateOrChangeBlockContainerElement(
+      nsTArray>& aArrayOfContents, nsAtom& aBlockTag,
+      const Element& aEditingHost);
 
   /**
    * FormatBlockContainerWithTransaction() is implementation of "formatBlock"

From f6d593afa9b25bde23563543d39df255f73bb387 Mon Sep 17 00:00:00 2001
From: Butkovits Atila 
Date: Thu, 16 Jun 2022 01:40:32 +0300
Subject: [PATCH 40/64] Backed out changeset 65e66c0b9eee (bug 1772841) for
 causing failures at test_input_datetime_disabled_focus.html. CLOSED TREE

---
 dom/html/test/forms/mochitest.ini             |  1 -
 .../test_input_datetime_disabled_focus.html   | 42 -------------------
 .../forms/test_input_datetime_tabindex.html   |  2 +
 toolkit/content/widgets/datetimebox.js        | 12 +++---
 4 files changed, 8 insertions(+), 49 deletions(-)
 delete mode 100644 dom/html/test/forms/test_input_datetime_disabled_focus.html

diff --git a/dom/html/test/forms/mochitest.ini b/dom/html/test/forms/mochitest.ini
index 745a946e3df2..50fc01bf945b 100644
--- a/dom/html/test/forms/mochitest.ini
+++ b/dom/html/test/forms/mochitest.ini
@@ -37,7 +37,6 @@ support-files = file_double_submit.html
 [test_input_date_bad_input.html]
 [test_input_date_key_events.html]
 [test_input_datetime_input_change_events.html]
-[test_input_datetime_disabled_focus.html]
 [test_input_datetime_focus_blur.html]
 [test_input_datetime_focus_blur_events.html]
 [test_input_datetime_focus_state.html]
diff --git a/dom/html/test/forms/test_input_datetime_disabled_focus.html b/dom/html/test/forms/test_input_datetime_disabled_focus.html
deleted file mode 100644
index 19cbdbef2732..000000000000
--- a/dom/html/test/forms/test_input_datetime_disabled_focus.html
+++ /dev/null
@@ -1,42 +0,0 @@
-
-Test for bug 1772841
-
-
-
-Mozilla Bug 1772841
-
- - - - - - - -
- diff --git a/dom/html/test/forms/test_input_datetime_tabindex.html b/dom/html/test/forms/test_input_datetime_tabindex.html index 60dff9177d35..3e763fe8589f 100644 --- a/dom/html/test/forms/test_input_datetime_tabindex.html +++ b/dom/html/test/forms/test_input_datetime_tabindex.html @@ -79,6 +79,7 @@ function testTabindex(type) { checkInnerTextboxTabindex(input1, 0); checkInnerTextboxTabindex(input2, -1); checkInnerTextboxTabindex(input3, 0); + checkInnerTextboxTabindex(input4, -1); // Changing the tabindex attribute dynamically. input3.setAttribute("tabindex", "-1"); @@ -91,6 +92,7 @@ function testTabindex(type) { "disabled element should not be tabbable"); checkInnerTextboxTabindex(input3, -1); + checkInnerTextboxTabindex(input4, -1); } function test() { diff --git a/toolkit/content/widgets/datetimebox.js b/toolkit/content/widgets/datetimebox.js index 945f4d6b2fbb..d2fa5946b19e 100644 --- a/toolkit/content/widgets/datetimebox.js +++ b/toolkit/content/widgets/datetimebox.js @@ -346,7 +346,7 @@ this.DateTimeBoxWidget = class { field.textContent = aPlaceHolder; field.placeholder = aPlaceHolder; field.setAttribute("aria-valuetext", ""); - this.setFieldTabIndexAttribute(field); + field.tabIndex = this.editFieldTabIndex(); field.setAttribute("readonly", this.mInputElement.readOnly); field.setAttribute("disabled", this.mInputElement.disabled); @@ -447,12 +447,11 @@ this.DateTimeBoxWidget = class { this.mIsPickerOpen = aIsOpen; } - setFieldTabIndexAttribute(field) { + editFieldTabIndex() { if (this.mInputElement.disabled) { - field.removeAttribute("tabindex"); - } else { - field.tabIndex = this.mInputElement.tabIndex; + return -1; } + return this.mInputElement.tabIndex; } updateEditAttributes() { @@ -473,7 +472,8 @@ this.DateTimeBoxWidget = class { child.disabled = this.mInputElement.disabled; child.readOnly = this.mInputElement.readOnly; - this.setFieldTabIndexAttribute(child); + // tabIndex as a property works on all relevant elements. + child.tabIndex = this.editFieldTabIndex(); } this.mResetButton.disabled = From 08ea6a836734c27f47a81ade15c832500f673106 Mon Sep 17 00:00:00 2001 From: Razvan Cojocaru Date: Wed, 15 Jun 2022 22:37:48 +0000 Subject: [PATCH 41/64] Bug 1773384 - Change the type of Downscaler::mScale to MatrixScalesDouble. r=botond Differential Revision: https://phabricator.services.mozilla.com/D149380 --- image/Downscaler.cpp | 7 ++++--- image/Downscaler.h | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/image/Downscaler.cpp b/image/Downscaler.cpp index 17a7351fc046..5bf15f1469d1 100644 --- a/image/Downscaler.cpp +++ b/image/Downscaler.cpp @@ -82,8 +82,9 @@ nsresult Downscaler::BeginFrame(const nsIntSize& aOriginalSize, aHasAlpha); mOriginalSize = aOriginalSize; - mScale = gfxSize(double(mOriginalSize.width) / mTargetSize.width, - double(mOriginalSize.height) / mTargetSize.height); + mScale = gfx::MatrixScalesDouble( + double(mOriginalSize.width) / mTargetSize.width, + double(mOriginalSize.height) / mTargetSize.height); mOutputBuffer = aOutputBuffer; mHasAlpha = aHasAlpha; mFlipVertically = aFlipVertically; @@ -244,7 +245,7 @@ DownscalerInvalidRect Downscaler::TakeInvalidRect() { // Compute the original size invalid rect. invalidRect.mOriginalSizeRect = invalidRect.mTargetSizeRect; - invalidRect.mOriginalSizeRect.ScaleRoundOut(mScale.width, mScale.height); + invalidRect.mOriginalSizeRect.ScaleRoundOut(mScale.xScale, mScale.yScale); return invalidRect; } diff --git a/image/Downscaler.h b/image/Downscaler.h index effa535a295b..e5fcf0387e1e 100644 --- a/image/Downscaler.h +++ b/image/Downscaler.h @@ -17,6 +17,7 @@ #include "gfxPoint.h" #include "nsRect.h" #include "mozilla/gfx/ConvolutionFilter.h" +#include "mozilla/gfx/Matrix.h" namespace mozilla { namespace image { @@ -55,7 +56,7 @@ class Downscaler { const nsIntSize FrameSize() const { return nsIntSize(mFrameRect.Width(), mFrameRect.Height()); } - const gfxSize& Scale() const { return mScale; } + const gfx::MatrixScalesDouble& Scale() const { return mScale; } /** * Begins a new frame and reinitializes the Downscaler. @@ -118,7 +119,7 @@ class Downscaler { nsIntSize mOriginalSize; nsIntSize mTargetSize; nsIntRect mFrameRect; - gfxSize mScale; + gfx::MatrixScalesDouble mScale; uint8_t* mOutputBuffer; From 04cc9153664cded8e4093f6399740db040945f6a Mon Sep 17 00:00:00 2001 From: Karl Tomlinson Date: Wed, 15 Jun 2022 22:50:32 +0000 Subject: [PATCH 42/64] Bug 1727653 wait for resize event before testing restoration of persisted sizes r=niklas Differential Revision: https://phabricator.services.mozilla.com/D149329 --- .../tests/chrome/test_navigate_persist.html | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/toolkit/content/tests/chrome/test_navigate_persist.html b/toolkit/content/tests/chrome/test_navigate_persist.html index 794422bfb793..f7ee06e15590 100644 --- a/toolkit/content/tests/chrome/test_navigate_persist.html +++ b/toolkit/content/tests/chrome/test_navigate_persist.html @@ -25,15 +25,22 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1460639 }); } - function resize(win, size) { - let resizePromise = new Promise(resolve => { - if (win.outerWidth === size && win.outerHeight === size) { + function promiseMaybeResizeEvent(win, expectedSize) { + return new Promise(resolve => { + // If the size is already as expected, then there may be no resize + // event. + if (win.outerWidth === expectedSize + && win.outerHeight === expectedSize) { resolve(); } win.addEventListener("resize", () => { resolve(); }, {once: true}); }); + } + + function resize(win, size) { + const resizePromise = promiseMaybeResizeEvent(win, size); win.resizeTo(size, size); return resizePromise; } @@ -60,6 +67,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1460639 isnot(win.outerHeight, PERSIST_SIZE, "Initial window height is not the persisted size"); await navigateWindowTo(win, "window_navigate_persist.html"); + await promiseMaybeResizeEvent(win, PERSIST_SIZE); is(win.outerWidth, PERSIST_SIZE, "Window width is persisted"); is(win.outerHeight, PERSIST_SIZE, "Window height is persisted"); win.close(); From 59416bd5ae6a127e1a78bff964b68f5c7d680b08 Mon Sep 17 00:00:00 2001 From: Andrew Erickson Date: Wed, 15 Jun 2022 22:50:33 +0000 Subject: [PATCH 43/64] Bug 1771520: update mac hostutils r=gbrown Now that standard8's change has landed, base off of m-c. based off of: ``` MAC_BUILD_URL="https://ftp.mozilla.org/pub/firefox/nightly/2022/06/2022-06-14-21-37-29-mozilla-central" ``` Differential Revision: https://phabricator.services.mozilla.com/D149451 --- .../config/tooltool-manifests/macosx64/hostutils.manifest | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/testing/config/tooltool-manifests/macosx64/hostutils.manifest b/testing/config/tooltool-manifests/macosx64/hostutils.manifest index 798ff766bce7..d89f6a757d11 100644 --- a/testing/config/tooltool-manifests/macosx64/hostutils.manifest +++ b/testing/config/tooltool-manifests/macosx64/hostutils.manifest @@ -1,10 +1,10 @@ [ { + "filename": "host-utils-103.0a1.en-US.mac.tar.gz", + "size": 152932731, "algorithm": "sha512", - "visibility": "public", - "filename": "host-utils-101.0a1.en-US.mac.tar.gz", + "digest": "dca1f742fa4f0c482e2ab5823ff563fcf8487261650f305ec4b43a06dccdba7bf67e0fd6919cef997b6dd4525f3fca0e6f1579f9abb351ed55394bf7c82a04a1", "unpack": true, - "digest": "2e6c338921d271cec9d7b96c067f2d5b0e56a319a38584fd6f4490ca2308fc31b5694f6b88875652b5444df961fb42a87e52e176bbf82184f4327e71c4fbc4e7", - "size": 152686257 + "visibility": "public" } ] \ No newline at end of file From 1a8c790333de7e9153823e6bf41463d54842e98c Mon Sep 17 00:00:00 2001 From: Daniel Holbert Date: Wed, 15 Jun 2022 23:18:32 +0000 Subject: [PATCH 44/64] Bug 1524064: annotate crashtest 1547420-1.html as failing one extra assertion on Android. (no review, just a test-manifest update to reflect reality) Differential Revision: https://phabricator.services.mozilla.com/D149460 --- layout/painting/crashtests/crashtests.list | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/layout/painting/crashtests/crashtests.list b/layout/painting/crashtests/crashtests.list index 924fefd117f9..e72a97c9a8b3 100644 --- a/layout/painting/crashtests/crashtests.list +++ b/layout/painting/crashtests/crashtests.list @@ -18,7 +18,7 @@ load 1469472.html load 1477831-1.html load 1504033.html load 1514544-1.html -asserts(0-1) load 1547420-1.html +asserts(0-1) asserts-if(Android,0-2) load 1547420-1.html load 1549909.html asserts(6) load 1551389-1.html # bug 847368 asserts(0-2) load 1555819-1.html From ebb6012c31520b78bc63b028f183c21a013f972e Mon Sep 17 00:00:00 2001 From: Masayuki Nakano Date: Wed, 15 Jun 2022 23:38:54 +0000 Subject: [PATCH 45/64] Bug 1770877 - part 2: Make `HTMLEditor::SplitRangeOffFromBlock` stop touching `Selection` directly r=m_kato The constructor of `SplitRangeOffFromNodeResult` is used only by the method. Therefore, we can customize the constructor and make it store the caret suggestion. Differential Revision: https://phabricator.services.mozilla.com/D149066 --- editor/libeditor/HTMLEditHelpers.cpp | 47 ++++++++++++ editor/libeditor/HTMLEditHelpers.h | 58 ++++++++++++++- editor/libeditor/HTMLEditSubActionHandler.cpp | 72 +++++++++++-------- editor/libeditor/HTMLEditor.h | 13 ++-- 4 files changed, 151 insertions(+), 39 deletions(-) diff --git a/editor/libeditor/HTMLEditHelpers.cpp b/editor/libeditor/HTMLEditHelpers.cpp index f5e5b28e3d99..18b819cf7ad3 100644 --- a/editor/libeditor/HTMLEditHelpers.cpp +++ b/editor/libeditor/HTMLEditHelpers.cpp @@ -179,4 +179,51 @@ bool SplitNodeResult::MoveCaretPointTo(EditorDOMPoint& aPointToPutCaret, return true; } +/****************************************************************************** + * mozilla::SplitRangeOffFromNodeResult + *****************************************************************************/ + +nsresult SplitRangeOffFromNodeResult::SuggestCaretPointTo( + const HTMLEditor& aHTMLEditor, const SuggestCaretOptions& aOptions) const { + mHandledCaretPoint = true; + if (!mCaretPoint.IsSet()) { + if (aOptions.contains(SuggestCaret::OnlyIfHasSuggestion)) { + return NS_OK; + } + NS_WARNING("There was no suggestion to put caret"); + return NS_ERROR_FAILURE; + } + if (aOptions.contains(SuggestCaret::OnlyIfTransactionsAllowedToDoIt) && + !aHTMLEditor.AllowsTransactionsToChangeSelection()) { + return NS_OK; + } + nsresult rv = aHTMLEditor.CollapseSelectionTo(mCaretPoint); + if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) { + NS_WARNING( + "EditorBase::CollapseSelectionTo() caused destroying the editor"); + return NS_ERROR_EDITOR_DESTROYED; + } + return aOptions.contains(SuggestCaret::AndIgnoreTrivialError) && + MOZ_UNLIKELY(NS_FAILED(rv)) + ? NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR + : rv; +} + +bool SplitRangeOffFromNodeResult::MoveCaretPointTo( + EditorDOMPoint& aPointToPutCaret, const HTMLEditor& aHTMLEditor, + const SuggestCaretOptions& aOptions) { + MOZ_ASSERT(!aOptions.contains(SuggestCaret::AndIgnoreTrivialError)); + mHandledCaretPoint = true; + if (aOptions.contains(SuggestCaret::OnlyIfHasSuggestion) && + !mCaretPoint.IsSet()) { + return false; + } + if (aOptions.contains(SuggestCaret::OnlyIfTransactionsAllowedToDoIt) && + !aHTMLEditor.AllowsTransactionsToChangeSelection()) { + return false; + } + aPointToPutCaret = UnwrapCaretPoint(); + return true; +} + } // namespace mozilla diff --git a/editor/libeditor/HTMLEditHelpers.h b/editor/libeditor/HTMLEditHelpers.h index 82fdbe734e05..2f9d6230c9de 100644 --- a/editor/libeditor/HTMLEditHelpers.h +++ b/editor/libeditor/HTMLEditHelpers.h @@ -825,6 +825,41 @@ class MOZ_STACK_CLASS SplitRangeOffFromNodeResult final { return dom::Element::FromNodeOrNull(mRightContent); } + /** + * Suggest caret position to aHTMLEditor. + */ + [[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult SuggestCaretPointTo( + const HTMLEditor& aHTMLEditor, const SuggestCaretOptions& aOptions) const; + + /** + * IgnoreCaretPointSuggestion() should be called if the method does not want + * to use caret position recommended by this instance. + */ + void IgnoreCaretPointSuggestion() const { mHandledCaretPoint = true; } + + bool HasCaretPointSuggestion() const { return mCaretPoint.IsSet(); } + constexpr EditorDOMPoint&& UnwrapCaretPoint() { + mHandledCaretPoint = true; + return std::move(mCaretPoint); + } + bool MoveCaretPointTo(EditorDOMPoint& aPointToPutCaret, + const SuggestCaretOptions& aOptions) { + MOZ_ASSERT(!aOptions.contains(SuggestCaret::AndIgnoreTrivialError)); + MOZ_ASSERT( + !aOptions.contains(SuggestCaret::OnlyIfTransactionsAllowedToDoIt)); + if (aOptions.contains(SuggestCaret::OnlyIfHasSuggestion) && + !mCaretPoint.IsSet()) { + return false; + } + aPointToPutCaret = UnwrapCaretPoint(); + return true; + } + bool MoveCaretPointTo(EditorDOMPoint& aPointToPutCaret, + const HTMLEditor& aHTMLEditor, + const SuggestCaretOptions& aOptions); + + SplitRangeOffFromNodeResult() = delete; + SplitRangeOffFromNodeResult(nsIContent* aLeftContent, nsIContent* aMiddleContent, nsIContent* aRightContent) @@ -838,7 +873,7 @@ class MOZ_STACK_CLASS SplitRangeOffFromNodeResult final { : mRv(NS_OK) { // The given results are created for creating this instance so that the // caller may not need to handle with them. For making who taking the - // reposible clearer, we should move them into this constructor. + // responsible clearer, we should move them into this constructor. SplitNodeResult splitResultAtLeftOfMiddleNode( std::move(aSplitResultAtLeftOfMiddleNode)); SplitNodeResult splitResultARightOfMiddleNode( @@ -855,6 +890,15 @@ class MOZ_STACK_CLASS SplitRangeOffFromNodeResult final { if (!mMiddleContent && splitResultAtLeftOfMiddleNode.isOk()) { mMiddleContent = splitResultAtLeftOfMiddleNode.GetNextContent(); } + // Prefer the right split result if available. + if (splitResultARightOfMiddleNode.HasCaretPointSuggestion()) { + splitResultAtLeftOfMiddleNode.IgnoreCaretPointSuggestion(); + mCaretPoint = splitResultARightOfMiddleNode.UnwrapCaretPoint(); + } + // Otherwise, if the left split result has a suggestion, take it. + else if (splitResultAtLeftOfMiddleNode.HasCaretPointSuggestion()) { + mCaretPoint = splitResultAtLeftOfMiddleNode.UnwrapCaretPoint(); + } } explicit SplitRangeOffFromNodeResult(nsresult aRv) : mRv(aRv) { @@ -869,14 +913,24 @@ class MOZ_STACK_CLASS SplitRangeOffFromNodeResult final { SplitRangeOffFromNodeResult& operator=(SplitRangeOffFromNodeResult&& aOther) = default; +#ifdef DEBUG + ~SplitRangeOffFromNodeResult() { + MOZ_ASSERT_IF(isOk(), !mCaretPoint.IsSet() || mHandledCaretPoint); + } +#endif + private: nsCOMPtr mLeftContent; nsCOMPtr mMiddleContent; nsCOMPtr mRightContent; + // The point which is a good point to put caret from point of view the + // splitter. + EditorDOMPoint mCaretPoint; + nsresult mRv; - SplitRangeOffFromNodeResult() = delete; + bool mutable mHandledCaretPoint = false; }; /***************************************************************************** diff --git a/editor/libeditor/HTMLEditSubActionHandler.cpp b/editor/libeditor/HTMLEditSubActionHandler.cpp index 9e82855e835b..48f12c7944ee 100644 --- a/editor/libeditor/HTMLEditSubActionHandler.cpp +++ b/editor/libeditor/HTMLEditSubActionHandler.cpp @@ -5305,13 +5305,25 @@ HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer( SplitRangeOffFromNodeResult splitResult = SplitRangeOffFromBlock(aBlockElement, aStartOfRange, aEndOfRange); if (splitResult.EditorDestroyed()) { - NS_WARNING( - "HTMLEditor::SplitRangeOffFromBlock() caused destorying the editor"); + NS_WARNING("HTMLEditor::SplitRangeOffFromBlock() failed"); return splitResult; } - NS_WARNING_ASSERTION( - splitResult.isOk(), - "HTMLEditor::SplitRangeOffFromBlock() failed, but might be ignored"); + if (splitResult.isOk()) { + nsresult rv = splitResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt, + SuggestCaret::AndIgnoreTrivialError}); + if (NS_FAILED(rv)) { + NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return SplitRangeOffFromNodeResult(rv); + } + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), + "SplitRangeOffFromNodeResult::SuggestCaretPointTo() " + "failed, but ignored"); + } else { + NS_WARNING( + "HTMLEditor::SplitRangeOffFromBlock() failed, but might be ignored"); + } const Result unwrapBlockElementResult = RemoveBlockContainerWithTransaction(aBlockElement); if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) { @@ -5343,7 +5355,8 @@ SplitRangeOffFromNodeResult HTMLEditor::SplitRangeOffFromBlock( SplitNodeResult splitAtStartResult = SplitNodeDeepWithTransaction( aBlockElement, EditorDOMPoint(&aStartOfMiddleElement), SplitAtEdges::eDoNotCreateEmptyContainer); - if (MOZ_UNLIKELY(NS_WARN_IF(splitAtStartResult.EditorDestroyed()))) { + if (splitAtStartResult.EditorDestroyed()) { + NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed (at left)"); return SplitRangeOffFromNodeResult(NS_ERROR_EDITOR_DESTROYED); } NS_WARNING_ASSERTION( @@ -5355,7 +5368,8 @@ SplitRangeOffFromNodeResult HTMLEditor::SplitRangeOffFromBlock( auto atAfterEnd = EditorDOMPoint::After(aEndOfMiddleElement); SplitNodeResult splitAtEndResult = SplitNodeDeepWithTransaction( aBlockElement, atAfterEnd, SplitAtEdges::eDoNotCreateEmptyContainer); - if (MOZ_UNLIKELY(NS_WARN_IF(splitAtEndResult.EditorDestroyed()))) { + if (splitAtEndResult.EditorDestroyed()) { + NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed (at right)"); return SplitRangeOffFromNodeResult(NS_ERROR_EDITOR_DESTROYED); } NS_WARNING_ASSERTION( @@ -5363,26 +5377,6 @@ SplitRangeOffFromNodeResult HTMLEditor::SplitRangeOffFromBlock( "HTMLEditor::SplitNodeDeepWithTransaction(SplitAtEdges::" "eDoNotCreateEmptyContainer) after end of middle element failed"); - if (AllowsTransactionsToChangeSelection() && - (splitAtStartResult.HasCaretPointSuggestion() || - splitAtEndResult.HasCaretPointSuggestion())) { - const SplitNodeResult& splitNodeResultHavingLatestCaretSuggestion = - [&]() -> SplitNodeResult& { - if (splitAtEndResult.HasCaretPointSuggestion()) { - splitAtStartResult.IgnoreCaretPointSuggestion(); - return splitAtEndResult; - } - return splitAtStartResult; - }(); - nsresult rv = - splitNodeResultHavingLatestCaretSuggestion.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion}); - if (NS_FAILED(rv)) { - NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed"); - return SplitRangeOffFromNodeResult(rv); - } - } - return SplitRangeOffFromNodeResult(std::move(splitAtStartResult), std::move(splitAtEndResult)); } @@ -5394,18 +5388,34 @@ SplitRangeOffFromNodeResult HTMLEditor::OutdentPartOfBlock( SplitRangeOffFromNodeResult splitResult = SplitRangeOffFromBlock(aBlockElement, aStartOfOutdent, aEndOfOutdent); - if (NS_WARN_IF(splitResult.EditorDestroyed())) { + if (splitResult.EditorDestroyed()) { + NS_WARNING("HTMLEditor::SplitRangeOffFromBlock() failed"); return SplitRangeOffFromNodeResult(NS_ERROR_EDITOR_DESTROYED); } if (!splitResult.GetMiddleContentAsElement()) { NS_WARNING( "HTMLEditor::SplitRangeOffFromBlock() didn't return middle content"); + splitResult.IgnoreCaretPointSuggestion(); return SplitRangeOffFromNodeResult(NS_ERROR_FAILURE); } - NS_WARNING_ASSERTION( - splitResult.isOk(), - "HTMLEditor::SplitRangeOffFromBlock() failed, but might be ignored"); + + if (splitResult.isOk()) { + nsresult rv = splitResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt, + SuggestCaret::AndIgnoreTrivialError}); + if (NS_FAILED(rv)) { + NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return SplitRangeOffFromNodeResult(rv); + } + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), + "SplitRangeOffFromNodeResult::SuggestCaretPointTo() " + "failed, but ignored"); + } else { + NS_WARNING( + "HTMLEditor::SplitRangeOffFromBlock() failed, but might be ignored"); + } if (aBlockIndentedWith == BlockIndentedWith::HTML) { Result unwrapBlockElementResult = diff --git a/editor/libeditor/HTMLEditor.h b/editor/libeditor/HTMLEditor.h index a26642c0bf3a..eec213bc2280 100644 --- a/editor/libeditor/HTMLEditor.h +++ b/editor/libeditor/HTMLEditor.h @@ -1541,7 +1541,7 @@ class HTMLEditor final : public EditorBase, /** * SplitRangeOffFromBlock() splits aBlockElement at two points, before * aStartOfMiddleElement and after aEndOfMiddleElement. If they are very - * start or very end of aBlcok, this won't create empty block. + * start or very end of aBlockElement, this won't create empty block. * * @param aBlockElement A block element which will be split. * @param aStartOfMiddleElement Start node of middle block element. @@ -4661,11 +4661,12 @@ class HTMLEditor final : public EditorBase, // CollectListChildren, // CollectNonEditableNodes, // CollectTableChildren - friend class SlurpBlobEventListener; // BlobReader - friend class SplitNodeResult; // CollapseSelectionTo - friend class SplitNodeTransaction; // DoJoinNodes, DoSplitNode - friend class TransactionManager; // DidDoTransaction, DidRedoTransaction, - // DidUndoTransaction + friend class SlurpBlobEventListener; // BlobReader + friend class SplitNodeResult; // CollapseSelectionTo + friend class SplitNodeTransaction; // DoJoinNodes, DoSplitNode + friend class SplitRangeOffFromNodeResult; // CollapseSelectionTo + friend class TransactionManager; // DidDoTransaction, DidRedoTransaction, + // DidUndoTransaction friend class WhiteSpaceVisibilityKeeper; // CanMoveChildren, // CanMoveOrDeleteSomethingInHardLine, From c2622fb9cef7e2b76359787d1fe90ccca89c5ece Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Wed, 15 Jun 2022 23:42:37 +0000 Subject: [PATCH 46/64] Bug 1774408 - Don't use widget scale in AppWindow. r=tnikkel This does fix the Pre-XUL skeleton UI scaling for me, but the others are harmless and I can't repro the bug as described. I _guess_ this can happen if you have window borders on Windows, since we were mishandling those? But I don't know how to get those on Win10+. The other scalings are symmetrical so they ended up working out in the end. In any case this is the right thing to do and I'm ~sure it will fix the bug in the reporter's configuration. Differential Revision: https://phabricator.services.mozilla.com/D149449 --- xpfe/appshell/AppWindow.cpp | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/xpfe/appshell/AppWindow.cpp b/xpfe/appshell/AppWindow.cpp index 4bd9ed49e56b..4636faf705ac 100644 --- a/xpfe/appshell/AppWindow.cpp +++ b/xpfe/appshell/AppWindow.cpp @@ -463,23 +463,25 @@ static LayoutDeviceIntSize GetOuterToInnerSizeDifference(nsIWidget* aWindow) { return windowSize - baseSize; } -static CSSIntSize GetOuterToInnerSizeDifferenceInCSSPixels(nsIWidget* aWindow) { - if (!aWindow) { - return {}; - } +static CSSIntSize GetOuterToInnerSizeDifferenceInCSSPixels( + nsIWidget* aWindow, CSSToLayoutDeviceScale aScale) { LayoutDeviceIntSize devPixelSize = GetOuterToInnerSizeDifference(aWindow); - return RoundedToInt(devPixelSize / aWindow->GetDefaultScale()); + return RoundedToInt(devPixelSize / aScale); } NS_IMETHODIMP AppWindow::GetOuterToInnerHeightDifferenceInCSSPixels(uint32_t* aResult) { - *aResult = GetOuterToInnerSizeDifferenceInCSSPixels(mWindow).height; + *aResult = GetOuterToInnerSizeDifferenceInCSSPixels( + mWindow, UnscaledDevicePixelsPerCSSPixel()) + .height; return NS_OK; } NS_IMETHODIMP AppWindow::GetOuterToInnerWidthDifferenceInCSSPixels(uint32_t* aResult) { - *aResult = GetOuterToInnerSizeDifferenceInCSSPixels(mWindow).width; + *aResult = GetOuterToInnerSizeDifferenceInCSSPixels( + mWindow, UnscaledDevicePixelsPerCSSPixel()) + .width; return NS_OK; } @@ -1253,12 +1255,12 @@ bool AppWindow::LoadPositionFromXUL(int32_t aSpecWidth, int32_t aSpecHeight) { // Convert to global display pixels for consistent window management across // screens with diverse resolutions - double devToDesktopScale = 1.0 / mWindow->GetDesktopToDeviceScale().scale; + double devToDesktopScale = 1.0 / DevicePixelsPerDesktopPixel().scale; currX = NSToIntRound(currX * devToDesktopScale); currY = NSToIntRound(currY * devToDesktopScale); // For size, use specified value if > 0, else current value - double devToCSSScale = 1.0 / mWindow->GetDefaultScale().scale; + double devToCSSScale = 1.0 / UnscaledDevicePixelsPerCSSPixel().scale; int32_t cssWidth = aSpecWidth > 0 ? aSpecWidth : NSToIntRound(currWidth * devToCSSScale); int32_t cssHeight = @@ -1802,7 +1804,7 @@ nsresult AppWindow::MaybeSaveEarlyWindowPersistentValues( settings.height = aRect.Height(); settings.maximized = mWindow->SizeMode() == nsSizeMode_Maximized; - settings.cssToDevPixelScaling = mWindow->GetDefaultScale().scale; + settings.cssToDevPixelScaling = UnscaledDevicePixelsPerCSSPixel().scale; nsCOMPtr windowElement = GetWindowDOMElement(); Document* doc = windowElement->GetComposedDoc(); @@ -1998,8 +2000,8 @@ NS_IMETHODIMP AppWindow::SavePersistentAttributes() { bool gotRestoredBounds = NS_SUCCEEDED(mWindow->GetRestoredBounds(rect)); // we use CSS pixels for size, but desktop pixels for position - CSSToLayoutDeviceScale sizeScale = mWindow->GetDefaultScale(); - DesktopToLayoutDeviceScale posScale = mWindow->GetDesktopToDeviceScale(); + CSSToLayoutDeviceScale sizeScale = UnscaledDevicePixelsPerCSSPixel(); + DesktopToLayoutDeviceScale posScale = DevicePixelsPerDesktopPixel(); // make our position relative to our parent, if any nsCOMPtr parent(do_QueryReferent(mParentWindow)); @@ -2622,7 +2624,8 @@ void AppWindow::SizeShell() { windowElement->GetAttribute(WINDOWTYPE_ATTRIBUTE, windowType); } - CSSIntSize windowDiff = GetOuterToInnerSizeDifferenceInCSSPixels(mWindow); + CSSIntSize windowDiff = GetOuterToInnerSizeDifferenceInCSSPixels( + mWindow, UnscaledDevicePixelsPerCSSPixel()); // If we're using fingerprint resistance, we're going to resize the window // once we have primary content. From 8218713aac11b4189008d741de5658259a019909 Mon Sep 17 00:00:00 2001 From: Butkovits Atila Date: Thu, 16 Jun 2022 03:10:02 +0300 Subject: [PATCH 47/64] Backed out 4 changesets (bug 1608282) for causing hazard failures. CLOSED TREE Backed out changeset 32aebc8be201 (bug 1608282) Backed out changeset 37c970364269 (bug 1608282) Backed out changeset ced8d82cc2d2 (bug 1608282) Backed out changeset e26e480c7dd6 (bug 1608282) --- browser/actors/AboutProtectionsParent.jsm | 2 + .../migration/ChromeMacOSLoginCrypto.jsm | 2 + .../migration/ChromeWindowsLoginCrypto.jsm | 2 + browser/components/newtab/lib/ASRouter.jsm | 3 +- .../components/newtab/lib/CFRPageActions.jsm | 4 +- .../newtab/lib/DiscoveryStreamFeed.jsm | 6 ++- .../PersonalityProvider.jsm | 7 ++- browser/components/newtab/lib/Screenshots.jsm | 4 +- .../newtab/lib/TippyTopProvider.jsm | 9 +++- .../components/newtab/lib/TopSitesFeed.jsm | 4 +- .../components/newtab/lib/TopStoriesFeed.jsm | 10 ++-- .../newtab/test/RemoteImagesTestUtils.jsm | 2 + .../components/pagedata/PageDataSchema.jsm | 2 + .../urlbar/UrlbarProviderPreloadedSites.jsm | 2 + .../urlbar/UrlbarProviderQuickSuggest.jsm | 2 + browser/modules/PartnerLinkAttribution.jsm | 2 + dom/base/IndexedDBHelper.jsm | 2 + .../test/unit/GlobalObjectsModule.jsm | 2 + dom/push/PushCrypto.jsm | 51 +++++++++++-------- dom/system/NetworkGeolocationProvider.jsm | 4 +- js/xpconnect/loader/XPCOMUtils.jsm | 3 ++ js/xpconnect/src/Sandbox.cpp | 4 +- js/xpconnect/src/XPCJSRuntime.cpp | 3 -- js/xpconnect/src/XPCRuntimeService.cpp | 32 +----------- js/xpconnect/src/xpcprivate.h | 6 --- .../android/actors/ContentDelegateChild.jsm | 4 +- remote/marionette/capture.js | 3 +- .../manager/ssl/RemoteSecuritySettings.jsm | 4 +- services/automation/ServicesAutomation.jsm | 4 +- services/crypto/modules/WeaveCrypto.js | 31 +++++++---- services/crypto/modules/jwcrypto.jsm | 33 ++++++++---- services/crypto/modules/utils.js | 17 ++++--- .../fxaccounts/FxAccountsProfileClient.jsm | 9 +++- services/settings/Attachments.jsm | 3 +- services/settings/IDBHelpers.jsm | 6 +++ services/settings/SharedUtils.jsm | 5 ++ services/settings/Utils.jsm | 6 ++- services/settings/remote-settings.js | 2 + services/sync/modules/bookmark_validator.js | 8 +-- services/sync/modules/resource.js | 8 +-- .../tps/resource/auth/fxaccounts.jsm | 10 +++- toolkit/actors/AboutHttpsOnlyErrorChild.jsm | 1 + .../tests/BackgroundTask_profile_is_slim.jsm | 2 + .../cleardata/SiteDataTestUtils.jsm | 14 ++++- .../components/extensions/ExtensionCommon.jsm | 4 +- .../extensions/ExtensionContent.jsm | 4 +- .../extensions/ExtensionStorageSyncKinto.jsm | 2 + .../components/extensions/ExtensionUtils.jsm | 4 +- .../test/mochitest/webrequest_test.jsm | 2 + .../components/featuregates/FeatureGate.jsm | 4 +- .../lib/RemoteSettingsExperimentLoader.jsm | 14 ++--- .../nimbus/test/NimbusTestUtils.jsm | 1 + .../components/normandy/lib/NormandyApi.jsm | 7 ++- .../components/passwordmgr/LoginRecipes.jsm | 2 + .../passwordmgr/PasswordGenerator.jsm | 12 ++++- .../components/places/BookmarkJSONUtils.jsm | 2 + .../search/tests/SearchTestUtils.jsm | 2 + toolkit/components/utils/Sampling.jsm | 8 ++- toolkit/modules/IndexedDB.jsm | 2 + toolkit/modules/Region.jsm | 7 ++- toolkit/modules/UpdateUtils.jsm | 4 +- toolkit/mozapps/extensions/AbuseReporter.jsm | 2 + .../extensions/internal/AddonRepository.jsm | 2 + .../extensions/internal/AddonTestUtils.jsm | 2 + .../extensions/internal/XPIInstall.jsm | 5 +- .../lib/environments/jsm.js | 5 -- 66 files changed, 293 insertions(+), 144 deletions(-) diff --git a/browser/actors/AboutProtectionsParent.jsm b/browser/actors/AboutProtectionsParent.jsm index 948644efa5ea..741f0592898b 100644 --- a/browser/actors/AboutProtectionsParent.jsm +++ b/browser/actors/AboutProtectionsParent.jsm @@ -4,6 +4,8 @@ "use strict"; +Cu.importGlobalProperties(["fetch"]); + var EXPORTED_SYMBOLS = ["AboutProtectionsParent"]; const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" diff --git a/browser/components/migration/ChromeMacOSLoginCrypto.jsm b/browser/components/migration/ChromeMacOSLoginCrypto.jsm index 98b25f7a35bb..7abb5cb1ae96 100644 --- a/browser/components/migration/ChromeMacOSLoginCrypto.jsm +++ b/browser/components/migration/ChromeMacOSLoginCrypto.jsm @@ -11,6 +11,8 @@ var EXPORTED_SYMBOLS = ["ChromeMacOSLoginCrypto"]; +Cu.importGlobalProperties(["crypto"]); + const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); diff --git a/browser/components/migration/ChromeWindowsLoginCrypto.jsm b/browser/components/migration/ChromeWindowsLoginCrypto.jsm index 3cbb668f2ec6..bbe204132a9f 100644 --- a/browser/components/migration/ChromeWindowsLoginCrypto.jsm +++ b/browser/components/migration/ChromeWindowsLoginCrypto.jsm @@ -11,6 +11,8 @@ var EXPORTED_SYMBOLS = ["ChromeWindowsLoginCrypto"]; +Cu.importGlobalProperties(["atob", "crypto"]); + const { ChromeMigrationUtils } = ChromeUtils.import( "resource:///modules/ChromeMigrationUtils.jsm" ); diff --git a/browser/components/newtab/lib/ASRouter.jsm b/browser/components/newtab/lib/ASRouter.jsm index e5aa71694e1a..d745083f8572 100644 --- a/browser/components/newtab/lib/ASRouter.jsm +++ b/browser/components/newtab/lib/ASRouter.jsm @@ -12,6 +12,7 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { SnippetsTestMessageProvider: "resource://activity-stream/lib/SnippetsTestMessageProvider.jsm", @@ -191,7 +192,7 @@ const MessageLoaderUtils = { let response; try { - response = await fetch(provider.url, { + response = await lazy.fetch(provider.url, { headers, credentials: "omit", }); diff --git a/browser/components/newtab/lib/CFRPageActions.jsm b/browser/components/newtab/lib/CFRPageActions.jsm index a6778d929992..0bd95b12d6b4 100644 --- a/browser/components/newtab/lib/CFRPageActions.jsm +++ b/browser/components/newtab/lib/CFRPageActions.jsm @@ -10,6 +10,8 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + XPCOMUtils.defineLazyModuleGetters(lazy, { PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm", RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm", @@ -879,7 +881,7 @@ const CFRPageActions = { async _fetchLatestAddonVersion(id) { let url = null; try { - const response = await fetch(`${ADDONS_API_URL}/${id}/`, { + const response = await lazy.fetch(`${ADDONS_API_URL}/${id}/`, { credentials: "omit", }); if (response.status !== 204 && response.ok) { diff --git a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm index 1abedd6767db..a32a2559485e 100644 --- a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm +++ b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm @@ -3,6 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const lazy = {}; ChromeUtils.defineModuleGetter( lazy, @@ -18,6 +21,7 @@ const { setTimeout, clearTimeout } = ChromeUtils.import( "resource://gre/modules/Timer.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { actionTypes: at, actionCreators: ac } = ChromeUtils.import( "resource://activity-stream/common/Actions.jsm" ); @@ -283,7 +287,7 @@ class DiscoveryStreamFeed { const controller = new AbortController(); const { signal } = controller; - const fetchPromise = fetch(endpoint, { + const fetchPromise = lazy.fetch(endpoint, { ...options, credentials: "omit", signal, diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm index 841d4c8ca30c..c34c2a896471 100644 --- a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm +++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm @@ -18,6 +18,11 @@ ChromeUtils.defineModuleGetter( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); + +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { BasePromiseWorker } = ChromeUtils.import( "resource://gre/modules/PromiseWorker.jsm" @@ -62,7 +67,7 @@ class PersonalityProvider { } const server = Services.prefs.getCharPref("services.settings.server"); const serverInfo = await ( - await fetch(`${server}/`, { + await lazy.fetch(`${server}/`, { credentials: "omit", }) ).json(); diff --git a/browser/components/newtab/lib/Screenshots.jsm b/browser/components/newtab/lib/Screenshots.jsm index ccf5c4c65070..a012ed62dbaf 100644 --- a/browser/components/newtab/lib/Screenshots.jsm +++ b/browser/components/newtab/lib/Screenshots.jsm @@ -11,6 +11,8 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + ChromeUtils.defineModuleGetter( lazy, "BackgroundPageThumbs", @@ -61,7 +63,7 @@ const Screenshots = { // Blob URIs for the screenshots. const imgPath = lazy.PageThumbs.getThumbnailPath(url); - const filePathResponse = await fetch(`file://${imgPath}`); + const filePathResponse = await lazy.fetch(`file://${imgPath}`); const fileContents = await filePathResponse.blob(); // Check if the file is empty, which indicates there isn't actually a diff --git a/browser/components/newtab/lib/TippyTopProvider.jsm b/browser/components/newtab/lib/TippyTopProvider.jsm index ab2895f35a5c..138d9a7ef3c4 100644 --- a/browser/components/newtab/lib/TippyTopProvider.jsm +++ b/browser/components/newtab/lib/TippyTopProvider.jsm @@ -2,8 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const lazy = {}; + +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + const TIPPYTOP_PATH = "chrome://activity-stream/content/data/content/tippytop/"; const TIPPYTOP_JSON_PATH = "chrome://activity-stream/content/data/content/tippytop/top_sites.json"; @@ -36,7 +43,7 @@ class TippyTopProvider { // Load the Tippy Top sites from the json manifest. try { for (const site of await ( - await fetch(TIPPYTOP_JSON_PATH, { + await lazy.fetch(TIPPYTOP_JSON_PATH, { credentials: "omit", }) ).json()) { diff --git a/browser/components/newtab/lib/TopSitesFeed.jsm b/browser/components/newtab/lib/TopSitesFeed.jsm index cc5438dac8e1..ffb8a43ccb00 100644 --- a/browser/components/newtab/lib/TopSitesFeed.jsm +++ b/browser/components/newtab/lib/TopSitesFeed.jsm @@ -74,6 +74,8 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/Region.jsm" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + XPCOMUtils.defineLazyGetter(lazy, "log", () => { const { Logger } = ChromeUtils.import( "resource://messaging-system/lib/Logger.jsm" @@ -184,7 +186,7 @@ class ContileIntegration { } try { let url = Services.prefs.getStringPref(CONTILE_ENDPOINT_PREF); - const response = await fetch(url, { credentials: "omit" }); + const response = await lazy.fetch(url, { credentials: "omit" }); if (!response.ok) { lazy.log.warn( `Contile endpoint returned unexpected status: ${response.status}` diff --git a/browser/components/newtab/lib/TopStoriesFeed.jsm b/browser/components/newtab/lib/TopStoriesFeed.jsm index 811159bbdaa3..1bcf027c4a2b 100644 --- a/browser/components/newtab/lib/TopStoriesFeed.jsm +++ b/browser/components/newtab/lib/TopStoriesFeed.jsm @@ -3,10 +3,15 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { NewTabUtils } = ChromeUtils.import( "resource://gre/modules/NewTabUtils.jsm" ); +const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { actionTypes: at, actionCreators: ac } = ChromeUtils.import( "resource://activity-stream/common/Actions.jsm" @@ -24,7 +29,6 @@ const { PersistentCache } = ChromeUtils.import( "resource://activity-stream/lib/PersistentCache.jsm" ); -const lazy = {}; ChromeUtils.defineModuleGetter( lazy, "pktApi", @@ -192,7 +196,7 @@ class TopStoriesFeed { return null; } try { - const response = await fetch(this.stories_endpoint, { + const response = await lazy.fetch(this.stories_endpoint, { credentials: "omit", }); if (!response.ok) { @@ -292,7 +296,7 @@ class TopStoriesFeed { return null; } try { - const response = await fetch(this.topics_endpoint, { + const response = await lazy.fetch(this.topics_endpoint, { credentials: "omit", }); if (!response.ok) { diff --git a/browser/components/newtab/test/RemoteImagesTestUtils.jsm b/browser/components/newtab/test/RemoteImagesTestUtils.jsm index e99646c620f0..2b9a0113ff50 100644 --- a/browser/components/newtab/test/RemoteImagesTestUtils.jsm +++ b/browser/components/newtab/test/RemoteImagesTestUtils.jsm @@ -14,6 +14,8 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const RS_SERVER_PREF = "services.settings.server"; +Cu.importGlobalProperties(["fetch"]); + const RemoteImagesTestUtils = { /** * Serve a mock Remote Settings server with content for Remote Images diff --git a/browser/components/pagedata/PageDataSchema.jsm b/browser/components/pagedata/PageDataSchema.jsm index 29b757dbebec..9fc37b5d33f9 100644 --- a/browser/components/pagedata/PageDataSchema.jsm +++ b/browser/components/pagedata/PageDataSchema.jsm @@ -6,6 +6,8 @@ var EXPORTED_SYMBOLS = ["PageDataSchema"]; +Cu.importGlobalProperties(["fetch"]); + const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); diff --git a/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm b/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm index aa76060865db..dfd4b81ca544 100644 --- a/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm +++ b/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm @@ -17,6 +17,8 @@ const { XPCOMUtils } = ChromeUtils.import( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]); + XPCOMUtils.defineLazyModuleGetters(this, { ProfileAge: "resource://gre/modules/ProfileAge.jsm", UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm", diff --git a/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm b/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm index 6b0ecf7463c4..1645f7448bdf 100644 --- a/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm +++ b/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm @@ -28,6 +28,8 @@ XPCOMUtils.defineLazyModuleGetters(this, { UrlbarUtils: "resource:///modules/UrlbarUtils.jsm", }); +XPCOMUtils.defineLazyGlobalGetters(this, ["crypto", "fetch"]); + const TIMESTAMP_TEMPLATE = "%YYYYMMDDHH%"; const TIMESTAMP_LENGTH = 10; const TIMESTAMP_REGEXP = /^\d{10}$/; diff --git a/browser/modules/PartnerLinkAttribution.jsm b/browser/modules/PartnerLinkAttribution.jsm index 1d8b2b8af5e7..cbb9e77a3c6a 100644 --- a/browser/modules/PartnerLinkAttribution.jsm +++ b/browser/modules/PartnerLinkAttribution.jsm @@ -4,6 +4,8 @@ "use strict"; +Cu.importGlobalProperties(["fetch"]); + var EXPORTED_SYMBOLS = [ "PartnerLinkAttribution", "CONTEXTUAL_SERVICES_PING_TYPES", diff --git a/dom/base/IndexedDBHelper.jsm b/dom/base/IndexedDBHelper.jsm index 3fd70668b115..170cfea6aa0f 100644 --- a/dom/base/IndexedDBHelper.jsm +++ b/dom/base/IndexedDBHelper.jsm @@ -16,6 +16,8 @@ if (DEBUG) { var EXPORTED_SYMBOLS = ["IndexedDBHelper"]; +Cu.importGlobalProperties(["indexedDB"]); + const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function getErrorName(err) { diff --git a/dom/indexedDB/test/unit/GlobalObjectsModule.jsm b/dom/indexedDB/test/unit/GlobalObjectsModule.jsm index 905e75c9ecef..c700bd8b180f 100644 --- a/dom/indexedDB/test/unit/GlobalObjectsModule.jsm +++ b/dom/indexedDB/test/unit/GlobalObjectsModule.jsm @@ -3,6 +3,8 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ +Cu.importGlobalProperties(["indexedDB"]); + var EXPORTED_SYMBOLS = ["GlobalObjectsModule"]; function GlobalObjectsModule() {} diff --git a/dom/push/PushCrypto.jsm b/dom/push/PushCrypto.jsm index a1ace86a8c5f..39e945a4527b 100644 --- a/dom/push/PushCrypto.jsm +++ b/dom/push/PushCrypto.jsm @@ -15,6 +15,8 @@ XPCOMUtils.defineLazyGetter(lazy, "gDOMBundle", () => Services.strings.createBundle("chrome://global/locale/dom/dom.properties") ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); + // getCryptoParamsFromHeaders is exported for test purposes. const EXPORTED_SYMBOLS = ["PushCrypto", "getCryptoParamsFromHeaders"]; @@ -241,13 +243,17 @@ function concatArray(arrays) { } function hmac(key) { - this.keyPromise = crypto.subtle.importKey("raw", key, HMAC_SHA256, false, [ - "sign", - ]); + this.keyPromise = lazy.crypto.subtle.importKey( + "raw", + key, + HMAC_SHA256, + false, + ["sign"] + ); } hmac.prototype.hash = function(input) { - return this.keyPromise.then(k => crypto.subtle.sign("HMAC", k, input)); + return this.keyPromise.then(k => lazy.crypto.subtle.sign("HMAC", k, input)); }; function hkdf(salt, ikm) { @@ -325,7 +331,7 @@ class Decoder { try { let ikm = await this.computeSharedSecret(); let [gcmBits, nonce] = await this.deriveKeyAndNonce(ikm); - let key = await crypto.subtle.importKey( + let key = await lazy.crypto.subtle.importKey( "raw", gcmBits, "AES-GCM", @@ -362,14 +368,14 @@ class Decoder { */ async computeSharedSecret() { let [appServerKey, subscriptionPrivateKey] = await Promise.all([ - crypto.subtle.importKey("raw", this.senderKey, ECDH_KEY, false, [ + lazy.crypto.subtle.importKey("raw", this.senderKey, ECDH_KEY, false, [ "deriveBits", ]), - crypto.subtle.importKey("jwk", this.privateKey, ECDH_KEY, false, [ + lazy.crypto.subtle.importKey("jwk", this.privateKey, ECDH_KEY, false, [ "deriveBits", ]), ]); - return crypto.subtle.deriveBits( + return lazy.crypto.subtle.deriveBits( { name: "ECDH", public: appServerKey }, subscriptionPrivateKey, 256 @@ -402,7 +408,7 @@ class Decoder { name: "AES-GCM", iv: generateNonce(nonce, index), }; - let decoded = await crypto.subtle.decrypt(params, key, slice); + let decoded = await lazy.crypto.subtle.decrypt(params, key, slice); return this.unpadChunk(new Uint8Array(decoded), last); } @@ -603,22 +609,22 @@ var PushCrypto = { concatArray, generateAuthenticationSecret() { - return crypto.getRandomValues(new Uint8Array(16)); + return lazy.crypto.getRandomValues(new Uint8Array(16)); }, validateAppServerKey(key) { - return crypto.subtle + return lazy.crypto.subtle .importKey("raw", key, ECDSA_KEY, true, ["verify"]) .then(_ => key); }, generateKeys() { - return crypto.subtle + return lazy.crypto.subtle .generateKey(ECDH_KEY, true, ["deriveBits"]) .then(cryptoKey => Promise.all([ - crypto.subtle.exportKey("raw", cryptoKey.publicKey), - crypto.subtle.exportKey("jwk", cryptoKey.privateKey), + lazy.crypto.subtle.exportKey("raw", cryptoKey.publicKey), + lazy.crypto.subtle.exportKey("jwk", cryptoKey.privateKey), ]) ); }, @@ -725,9 +731,10 @@ var PushCrypto = { // purposes we allow it to be specified. const senderKeyPair = options.senderKeyPair || - (await crypto.subtle.generateKey(ECDH_KEY, true, ["deriveBits"])); + (await lazy.crypto.subtle.generateKey(ECDH_KEY, true, ["deriveBits"])); // allowing a salt to be specified is useful for tests. - const salt = options.salt || crypto.getRandomValues(new Uint8Array(16)); + const salt = + options.salt || lazy.crypto.getRandomValues(new Uint8Array(16)); const rs = options.rs === undefined ? 4096 : options.rs; const encoder = new aes128gcmEncoder( @@ -766,7 +773,7 @@ class aes128gcmEncoder { this.senderKeyPair.privateKey ); - const rawSenderPublicKey = await crypto.subtle.exportKey( + const rawSenderPublicKey = await lazy.crypto.subtle.exportKey( "raw", this.senderKeyPair.publicKey ); @@ -775,7 +782,7 @@ class aes128gcmEncoder { rawSenderPublicKey ); - const contentEncryptionKey = await crypto.subtle.importKey( + const contentEncryptionKey = await lazy.crypto.subtle.importKey( "raw", gcmBits, "AES-GCM", @@ -801,7 +808,7 @@ class aes128gcmEncoder { if (this.plaintext.byteLength === 0) { // Send an authentication tag for empty messages. chunks = [ - await crypto.subtle.encrypt( + await lazy.crypto.subtle.encrypt( { name: "AES-GCM", iv: generateNonce(nonce, 0), @@ -819,7 +826,7 @@ class aes128gcmEncoder { let isLast = index == inChunks.length - 1; let padding = new Uint8Array([isLast ? 2 : 1]); let input = concatArray([slice, padding]); - return crypto.subtle.encrypt( + return lazy.crypto.subtle.encrypt( { name: "AES-GCM", iv: generateNonce(nonce, index), @@ -853,7 +860,7 @@ class aes128gcmEncoder { // Note: this duplicates some of Decoder.computeSharedSecret, but the key // management is slightly different. async computeSharedSecret(receiverPublicKey, senderPrivateKey) { - const receiverPublicCryptoKey = await crypto.subtle.importKey( + const receiverPublicCryptoKey = await lazy.crypto.subtle.importKey( "raw", receiverPublicKey, ECDH_KEY, @@ -861,7 +868,7 @@ class aes128gcmEncoder { ["deriveBits"] ); - return crypto.subtle.deriveBits( + return lazy.crypto.subtle.deriveBits( { name: "ECDH", public: receiverPublicCryptoKey }, senderPrivateKey, 256 diff --git a/dom/system/NetworkGeolocationProvider.jsm b/dom/system/NetworkGeolocationProvider.jsm index 96724258c9ba..9791f821eaab 100644 --- a/dom/system/NetworkGeolocationProvider.jsm +++ b/dom/system/NetworkGeolocationProvider.jsm @@ -17,6 +17,8 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { setTimeout: "resource://gre/modules/Timer.jsm", }); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + // GeolocationPositionError has no interface object, so we can't use that here. const POSITION_UNAVAILABLE = 2; @@ -490,7 +492,7 @@ NetworkGeolocationProvider.prototype = { Services.prefs.getIntPref("geo.provider.network.timeout") ); - let req = await fetch(url, fetchOpts); + let req = await lazy.fetch(url, fetchOpts); lazy.clearTimeout(timeoutId); let result = req.json(); return result; diff --git a/js/xpconnect/loader/XPCOMUtils.jsm b/js/xpconnect/loader/XPCOMUtils.jsm index bcde97a9d9c7..789c3c5f961e 100644 --- a/js/xpconnect/loader/XPCOMUtils.jsm +++ b/js/xpconnect/loader/XPCOMUtils.jsm @@ -21,7 +21,10 @@ let global = Cu.getGlobalForObject({}); // and `MessagePort`. This table maps those extra symbols to the main // import name. const EXTRA_GLOBAL_NAME_TO_IMPORT_NAME = { + Headers: "fetch", MessagePort: "MessageChannel", + Request: "fetch", + Response: "fetch", }; /** diff --git a/js/xpconnect/src/Sandbox.cpp b/js/xpconnect/src/Sandbox.cpp index 8fb54ab09522..a1b79335fe06 100644 --- a/js/xpconnect/src/Sandbox.cpp +++ b/js/xpconnect/src/Sandbox.cpp @@ -270,7 +270,7 @@ static bool SandboxImport(JSContext* cx, unsigned argc, Value* vp) { return true; } -bool xpc::SandboxCreateCrypto(JSContext* cx, JS::Handle obj) { +static bool SandboxCreateCrypto(JSContext* cx, JS::HandleObject obj) { MOZ_ASSERT(JS_IsGlobalObject(obj)); nsIGlobalObject* native = xpc::NativeGlobal(obj); @@ -359,7 +359,7 @@ static bool SandboxFetchPromise(JSContext* cx, unsigned argc, Value* vp) { return ConvertExceptionToPromise(cx, args.rval()); } -bool xpc::SandboxCreateFetch(JSContext* cx, JS::Handle obj) { +static bool SandboxCreateFetch(JSContext* cx, HandleObject obj) { MOZ_ASSERT(JS_IsGlobalObject(obj)); return JS_DefineFunction(cx, obj, "fetch", SandboxFetchPromise, 2, 0) && diff --git a/js/xpconnect/src/XPCJSRuntime.cpp b/js/xpconnect/src/XPCJSRuntime.cpp index 8c3f37172a26..7db4e73e6c6a 100644 --- a/js/xpconnect/src/XPCJSRuntime.cpp +++ b/js/xpconnect/src/XPCJSRuntime.cpp @@ -128,9 +128,6 @@ const char* const XPCJSRuntime::mStrings[] = { "interfaceId", // IDX_INTERFACE_ID "initializer", // IDX_INITIALIZER "print", // IDX_PRINT - "fetch", // IDX_FETCH - "crypto", // IDX_CRYPTO - "indexedDB", // IDX_INDEXEDDB }; /***************************************************************************/ diff --git a/js/xpconnect/src/XPCRuntimeService.cpp b/js/xpconnect/src/XPCRuntimeService.cpp index 857301fe72d7..d7b6edd54ed1 100644 --- a/js/xpconnect/src/XPCRuntimeService.cpp +++ b/js/xpconnect/src/XPCRuntimeService.cpp @@ -11,7 +11,6 @@ #include "BackstagePass.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/WebIDLGlobalNameHash.h" -#include "mozilla/dom/IndexedDatabaseManager.h" using namespace mozilla::dom; @@ -67,36 +66,7 @@ BackstagePass::Resolve(nsIXPConnectWrappedNative* wrapper, JSContext* cx, JS::RootedId id(cx, idArg); *_retval = WebIDLGlobalNameHash::ResolveForSystemGlobal(cx, obj, id, resolvedp); - if (!*_retval) { - return NS_ERROR_FAILURE; - } - - if (*resolvedp) { - return NS_OK; - } - - XPCJSContext* xpccx = XPCJSContext::Get(); - if (idArg == xpccx->GetStringID(XPCJSContext::IDX_FETCH)) { - *_retval = xpc::SandboxCreateFetch(cx, obj); - if (!*_retval) { - return NS_ERROR_FAILURE; - } - *resolvedp = true; - } else if (idArg == xpccx->GetStringID(XPCJSContext::IDX_CRYPTO)) { - *_retval = xpc::SandboxCreateCrypto(cx, obj); - if (!*_retval) { - return NS_ERROR_FAILURE; - } - *resolvedp = true; - } else if (idArg == xpccx->GetStringID(XPCJSContext::IDX_INDEXEDDB)) { - *_retval = IndexedDatabaseManager::DefineIndexedDB(cx, obj); - if (!*_retval) { - return NS_ERROR_FAILURE; - } - *resolvedp = true; - } - - return NS_OK; + return *_retval ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP diff --git a/js/xpconnect/src/xpcprivate.h b/js/xpconnect/src/xpcprivate.h index c4727a746cf1..d2f785d599b0 100644 --- a/js/xpconnect/src/xpcprivate.h +++ b/js/xpconnect/src/xpcprivate.h @@ -404,9 +404,6 @@ class XPCJSContext final : public mozilla::CycleCollectedJSContext, IDX_INTERFACE_ID, IDX_INITIALIZER, IDX_PRINT, - IDX_FETCH, - IDX_CRYPTO, - IDX_INDEXEDDB, IDX_TOTAL_COUNT // just a count of the above }; @@ -2853,9 +2850,6 @@ void InitializeValue(const nsXPTType& aType, void* aValue); void DestructValue(const nsXPTType& aType, void* aValue, uint32_t aArrayLen = 0); -bool SandboxCreateCrypto(JSContext* cx, JS::Handle obj); -bool SandboxCreateFetch(JSContext* cx, JS::Handle obj); - } // namespace xpc namespace mozilla { diff --git a/mobile/android/actors/ContentDelegateChild.jsm b/mobile/android/actors/ContentDelegateChild.jsm index 6616efa35858..af7ab51b8a5c 100644 --- a/mobile/android/actors/ContentDelegateChild.jsm +++ b/mobile/android/actors/ContentDelegateChild.jsm @@ -14,6 +14,8 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["URL"]); + XPCOMUtils.defineLazyModuleGetters(lazy, { ManifestObtainer: "resource://gre/modules/ManifestObtainer.jsm", }); @@ -81,7 +83,7 @@ class ContentDelegateChild extends GeckoViewActorChild { let elementSrc = (isImage || isMedia) && (node.currentSrc || node.src); if (elementSrc) { const isBlob = elementSrc.startsWith("blob:"); - if (isBlob && !URL.isValidURL(elementSrc)) { + if (isBlob && !lazy.URL.isValidURL(elementSrc)) { elementSrc = null; } } diff --git a/remote/marionette/capture.js b/remote/marionette/capture.js index ffa9cc457211..3fae5490bc52 100644 --- a/remote/marionette/capture.js +++ b/remote/marionette/capture.js @@ -19,6 +19,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get(lazy.Log.TYPES.MARIONETTE) ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); const CONTEXT_2D = "2d"; const BG_COLOUR = "rgb(255,255,255)"; @@ -184,7 +185,7 @@ capture.toBase64 = function(canvas) { capture.toHash = function(canvas) { let u = capture.toBase64(canvas); let buffer = new TextEncoder("utf-8").encode(u); - return crypto.subtle.digest("SHA-256", buffer).then(hash => hex(hash)); + return lazy.crypto.subtle.digest("SHA-256", buffer).then(hash => hex(hash)); }; /** diff --git a/security/manager/ssl/RemoteSecuritySettings.jsm b/security/manager/ssl/RemoteSecuritySettings.jsm index aaea7178bdad..f1481ca7c719 100644 --- a/security/manager/ssl/RemoteSecuritySettings.jsm +++ b/security/manager/ssl/RemoteSecuritySettings.jsm @@ -31,6 +31,8 @@ const CRLITE_FILTERS_ENABLED_PREF = const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + XPCOMUtils.defineLazyGetter(lazy, "gTextDecoder", () => new TextDecoder()); XPCOMUtils.defineLazyGetter(lazy, "log", () => { @@ -591,7 +593,7 @@ class CRLiteFilters { try { // If we've already downloaded this, the backend should just grab it from its cache. let localURI = await this.client.attachments.downloadToDisk(filter); - let buffer = await (await fetch(localURI)).arrayBuffer(); + let buffer = await (await lazy.fetch(localURI)).arrayBuffer(); let bytes = new Uint8Array(buffer); lazy.log.debug( `Downloaded ${filter.details.name}: ${bytes.length} bytes` diff --git a/services/automation/ServicesAutomation.jsm b/services/automation/ServicesAutomation.jsm index 6a0fbdd98507..4a05536dcd5d 100644 --- a/services/automation/ServicesAutomation.jsm +++ b/services/automation/ServicesAutomation.jsm @@ -49,6 +49,8 @@ XPCOMUtils.defineLazyGetter(lazy, "fxAccounts", () => { ).getFxAccountsSingleton(); }); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + const AUTOCONFIG_PREF = "identity.fxaccounts.autoconfig.uri"; /* @@ -205,7 +207,7 @@ var Authentication = { const tries = 10; const normalWait = 4000; for (let i = 0; i < tries; ++i) { - let resp = await fetch(restmailURI); + let resp = await lazy.fetch(restmailURI); let messages = await resp.json(); // Sort so that the most recent emails are first. messages.sort((a, b) => new Date(b.receivedAt) - new Date(a.receivedAt)); diff --git a/services/crypto/modules/WeaveCrypto.js b/services/crypto/modules/WeaveCrypto.js index 38956b42e03b..03551ea93b29 100644 --- a/services/crypto/modules/WeaveCrypto.js +++ b/services/crypto/modules/WeaveCrypto.js @@ -9,6 +9,10 @@ const { XPCOMUtils } = ChromeUtils.import( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const lazy = {}; + +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); + const CRYPT_ALGO = "AES-CBC"; const CRYPT_ALGO_LENGTH = 256; const CRYPT_ALGO_USAGES = ["encrypt", "decrypt"]; @@ -74,7 +78,7 @@ WeaveCrypto.prototype = { // /!\ Only use this for tests! /!\ _getCrypto() { - return crypto; + return lazy.crypto; }, async encrypt(clearTextUCS2, symmetricKey, iv) { @@ -131,12 +135,17 @@ WeaveCrypto.prototype = { let iv = this.byteCompressInts(ivStr); let symKey = await this.importSymKey(symKeyStr, operation); let cryptMethod = (operation === OPERATIONS.ENCRYPT - ? crypto.subtle.encrypt - : crypto.subtle.decrypt - ).bind(crypto.subtle); + ? lazy.crypto.subtle.encrypt + : lazy.crypto.subtle.decrypt + ).bind(lazy.crypto.subtle); let algo = { name: CRYPT_ALGO, iv }; - let keyBytes = await cryptMethod.call(crypto.subtle, algo, symKey, data); + let keyBytes = await cryptMethod.call( + lazy.crypto.subtle, + algo, + symKey, + data + ); return new Uint8Array(keyBytes); }, @@ -146,8 +155,12 @@ WeaveCrypto.prototype = { name: CRYPT_ALGO, length: CRYPT_ALGO_LENGTH, }; - let key = await crypto.subtle.generateKey(algo, true, CRYPT_ALGO_USAGES); - let keyBytes = await crypto.subtle.exportKey("raw", key); + let key = await lazy.crypto.subtle.generateKey( + algo, + true, + CRYPT_ALGO_USAGES + ); + let keyBytes = await lazy.crypto.subtle.exportKey("raw", key); return this.encodeBase64(new Uint8Array(keyBytes)); }, @@ -159,7 +172,7 @@ WeaveCrypto.prototype = { this.log("generateRandomBytes() called"); let randBytes = new Uint8Array(byteCount); - crypto.getRandomValues(randBytes); + lazy.crypto.getRandomValues(randBytes); return this.encodeBase64(randBytes); }, @@ -195,7 +208,7 @@ WeaveCrypto.prototype = { let symmetricKeyBuffer = this.makeUint8Array(encodedKeyString, true); let algo = { name: CRYPT_ALGO }; let usages = [operation === OPERATIONS.ENCRYPT ? "encrypt" : "decrypt"]; - let symKey = await crypto.subtle.importKey( + let symKey = await lazy.crypto.subtle.importKey( "raw", symmetricKeyBuffer, algo, diff --git a/services/crypto/modules/jwcrypto.jsm b/services/crypto/modules/jwcrypto.jsm index f95e9509d862..05da9978bcc6 100644 --- a/services/crypto/modules/jwcrypto.jsm +++ b/services/crypto/modules/jwcrypto.jsm @@ -4,6 +4,14 @@ "use strict"; +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); + +const lazy = {}; + +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); + const EXPORTED_SYMBOLS = ["jwcrypto"]; const ECDH_PARAMS = { @@ -39,10 +47,13 @@ class JWCrypto { async generateJWE(key, data) { // Generate an ephemeral key to use just for this encryption. // The public component gets embedded in the JWE header. - const epk = await crypto.subtle.generateKey(ECDH_PARAMS, true, [ + const epk = await lazy.crypto.subtle.generateKey(ECDH_PARAMS, true, [ "deriveKey", ]); - const ownPublicJWK = await crypto.subtle.exportKey("jwk", epk.publicKey); + const ownPublicJWK = await lazy.crypto.subtle.exportKey( + "jwk", + epk.publicKey + ); // Remove properties added by our WebCrypto implementation but that aren't typically // used with JWE in the wild. This saves space in the resulting JWE, and makes it easier // to re-import the resulting JWK. @@ -50,7 +61,7 @@ class JWCrypto { delete ownPublicJWK.ext; let header = { alg: "ECDH-ES", enc: "A256GCM", epk: ownPublicJWK }; // Import the peer's public key. - const peerPublicKey = await crypto.subtle.importKey( + const peerPublicKey = await lazy.crypto.subtle.importKey( "jwk", key, ECDH_PARAMS, @@ -70,14 +81,14 @@ class JWCrypto { // Note that the IV is generated randomly, which *in general* is not safe to do with AES-GCM because // it's too short to guarantee uniqueness. But we know that the AES-GCM key itself is unique and will // only be used for this single encryption, making a random IV safe to use for this particular use-case. - let iv = crypto.getRandomValues(new Uint8Array(AES_GCM_IV_SIZE)); + let iv = lazy.crypto.getRandomValues(new Uint8Array(AES_GCM_IV_SIZE)); // Yes, additionalData is the byte representation of the base64 representation of the stringified header. const additionalData = UTF8_ENCODER.encode( ChromeUtils.base64URLEncode(UTF8_ENCODER.encode(JSON.stringify(header)), { pad: false, }) ); - const encrypted = await crypto.subtle.encrypt( + const encrypted = await lazy.crypto.subtle.encrypt( { name: "AES-GCM", iv, @@ -132,7 +143,7 @@ class JWCrypto { if ("apu" in header || "apv" in header) { throw new Error("apu and apv header values are not supported."); } - const peerPublicKey = await crypto.subtle.importKey( + const peerPublicKey = await lazy.crypto.subtle.importKey( "jwk", header.epk, ECDH_PARAMS, @@ -152,7 +163,7 @@ class JWCrypto { ); const bundle = new Uint8Array([...ciphertext, ...authTag]); - const decrypted = await crypto.subtle.decrypt( + const decrypted = await lazy.crypto.subtle.decrypt( { name: "AES-GCM", iv, @@ -179,7 +190,7 @@ class JWCrypto { */ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { const params = { ...ECDH_PARAMS, ...{ public: publicKey } }; - const sharedKey = await crypto.subtle.deriveKey( + const sharedKey = await lazy.crypto.subtle.deriveKey( params, privateKey, AES_PARAMS, @@ -189,7 +200,7 @@ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { // This is the NIST Concat KDF specialized to a specific set of parameters, // which basically turn it into a single application of SHA256. // The details are from the JWA RFC. - let sharedKeyBytes = await crypto.subtle.exportKey("raw", sharedKey); + let sharedKeyBytes = await lazy.crypto.subtle.exportKey("raw", sharedKey); sharedKeyBytes = new Uint8Array(sharedKeyBytes); const info = [ "\x00\x00\x00\x07A256GCM", // 7-byte algorithm identifier @@ -204,13 +215,13 @@ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { const pkcsBuf = Uint8Array.from( Array.prototype.map.call(pkcs, c => c.charCodeAt(0)) ); - const derivedKeyBytes = await crypto.subtle.digest( + const derivedKeyBytes = await lazy.crypto.subtle.digest( { name: "SHA-256", }, pkcsBuf ); - return crypto.subtle.importKey( + return lazy.crypto.subtle.importKey( "raw", derivedKeyBytes, AES_PARAMS, diff --git a/services/crypto/modules/utils.js b/services/crypto/modules/utils.js index 47a2cd0dda03..48a82d337b89 100644 --- a/services/crypto/modules/utils.js +++ b/services/crypto/modules/utils.js @@ -14,6 +14,7 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); XPCOMUtils.defineLazyGetter(lazy, "textEncoder", function() { return new TextEncoder(); @@ -51,7 +52,7 @@ var CryptoUtils = { }, generateRandomBytes(length) { - return crypto.getRandomValues(new Uint8Array(length)); + return lazy.crypto.getRandomValues(new Uint8Array(length)); }, /** @@ -148,14 +149,14 @@ var CryptoUtils = { * @returns {Uint8Array} */ async hmac(alg, key, data) { - const hmacKey = await crypto.subtle.importKey( + const hmacKey = await lazy.crypto.subtle.importKey( "raw", key, { name: "HMAC", hash: alg }, false, ["sign"] ); - const result = await crypto.subtle.sign("HMAC", hmacKey, data); + const result = await lazy.crypto.subtle.sign("HMAC", hmacKey, data); return new Uint8Array(result); }, @@ -167,14 +168,14 @@ var CryptoUtils = { * @returns {Uint8Array} */ async hkdf(ikm, salt, info, len) { - const key = await crypto.subtle.importKey( + const key = await lazy.crypto.subtle.importKey( "raw", ikm, { name: "HKDF" }, false, ["deriveBits"] ); - const okm = await crypto.subtle.deriveBits( + const okm = await lazy.crypto.subtle.deriveBits( { name: "HKDF", hash: "SHA-256", @@ -198,14 +199,14 @@ var CryptoUtils = { async pbkdf2Generate(passphrase, salt, iterations, len) { passphrase = CommonUtils.byteStringToArrayBuffer(passphrase); salt = CommonUtils.byteStringToArrayBuffer(salt); - const key = await crypto.subtle.importKey( + const key = await lazy.crypto.subtle.importKey( "raw", passphrase, { name: "PBKDF2" }, false, ["deriveBits"] ); - const output = await crypto.subtle.deriveBits( + const output = await lazy.crypto.subtle.deriveBits( { name: "PBKDF2", hash: "SHA-256", @@ -472,7 +473,7 @@ var CryptoUtils = { const buffer = lazy.textEncoder.encode( `hawk.1.payload\n${contentType}\n${options.payload}\n` ); - const hash = await crypto.subtle.digest("SHA-256", buffer); + const hash = await lazy.crypto.subtle.digest("SHA-256", buffer); // HAWK specifies this .hash to use +/ (not _-) and include the // trailing "==" padding. artifacts.hash = ChromeUtils.base64URLEncode(hash, { pad: true }) diff --git a/services/fxaccounts/FxAccountsProfileClient.jsm b/services/fxaccounts/FxAccountsProfileClient.jsm index c554699ef58b..caa18497cb0d 100644 --- a/services/fxaccounts/FxAccountsProfileClient.jsm +++ b/services/fxaccounts/FxAccountsProfileClient.jsm @@ -32,6 +32,13 @@ const fxAccounts = getFxAccountsSingleton(); const { RESTRequest } = ChromeUtils.import( "resource://services-common/rest.js" ); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); + +const lazy = {}; + +XPCOMUtils.defineLazyGlobalGetters(lazy, ["URL"]); /** * Create a new FxAccountsProfileClient to be able to fetch Firefox Account profile information. @@ -52,7 +59,7 @@ var FxAccountsProfileClient = function(options) { this.fxai = options.fxai || fxAccounts._internal; try { - this.serverURL = new URL(options.serverURL); + this.serverURL = new lazy.URL(options.serverURL); } catch (e) { throw new Error("Invalid 'serverURL'"); } diff --git a/services/settings/Attachments.jsm b/services/settings/Attachments.jsm index 5ac6249f6774..21fab90a8856 100644 --- a/services/settings/Attachments.jsm +++ b/services/settings/Attachments.jsm @@ -13,6 +13,7 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { Utils: "resource://services-settings/Utils.jsm", }); ChromeUtils.defineModuleGetter(lazy, "OS", "resource://gre/modules/osfile.jsm"); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); class DownloadError extends Error { constructor(url, resp) { @@ -468,7 +469,7 @@ class Downloader { async _readAttachmentDump(attachmentId) { async function fetchResource(resourceUrl) { try { - return await fetch(resourceUrl); + return await lazy.fetch(resourceUrl); } catch (e) { throw new Downloader.DownloadError(resourceUrl); } diff --git a/services/settings/IDBHelpers.jsm b/services/settings/IDBHelpers.jsm index d58101caa4a2..1199d87e943c 100644 --- a/services/settings/IDBHelpers.jsm +++ b/services/settings/IDBHelpers.jsm @@ -7,6 +7,12 @@ var EXPORTED_SYMBOLS = ["IDBHelpers"]; const DB_NAME = "remote-settings"; const DB_VERSION = 3; +// `indexedDB` is accessible in the worker global, but not the JSM global, +// where we have to import it - and the worker global doesn't have Cu. +if (typeof indexedDB == "undefined") { + Cu.importGlobalProperties(["indexedDB"]); +} + /** * Wrap IndexedDB errors to catch them more easily. */ diff --git a/services/settings/SharedUtils.jsm b/services/settings/SharedUtils.jsm index 9804e80c91c4..5d32fb38bd82 100644 --- a/services/settings/SharedUtils.jsm +++ b/services/settings/SharedUtils.jsm @@ -8,6 +8,11 @@ var EXPORTED_SYMBOLS = ["SharedUtils"]; +// Import globals that are available by default in workers but not in JSMs. +if (typeof crypto == "undefined") { + Cu.importGlobalProperties(["fetch", "crypto"]); +} + var SharedUtils = { /** * Check that the specified content matches the expected size and SHA-256 hash. diff --git a/services/settings/Utils.jsm b/services/settings/Utils.jsm index 21eacc72b586..ce2d04ce92b1 100644 --- a/services/settings/Utils.jsm +++ b/services/settings/Utils.jsm @@ -34,6 +34,8 @@ XPCOMUtils.defineLazyServiceGetter( "nsINetworkLinkService" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + // Create a new instance of the ConsoleAPI so we can control the maxLogLevel with a pref. // See LOG_LEVELS in Console.jsm. Common examples: "all", "debug", "info", "warn", "error". XPCOMUtils.defineLazyGetter(lazy, "log", () => { @@ -301,7 +303,7 @@ var Utils = { */ async hasLocalDump(bucket, collection) { try { - await fetch( + await lazy.fetch( `resource://app/defaults/settings/${bucket}/${collection}.json`, { method: "HEAD", @@ -325,7 +327,7 @@ var Utils = { if (!this._dumpStatsInitPromise) { this._dumpStatsInitPromise = (async () => { try { - let res = await fetch( + let res = await lazy.fetch( "resource://app/defaults/settings/last_modified.json" ); this._dumpStats = await res.json(); diff --git a/services/settings/remote-settings.js b/services/settings/remote-settings.js index 97aa802d7703..350714a9ed2f 100644 --- a/services/settings/remote-settings.js +++ b/services/settings/remote-settings.js @@ -34,6 +34,8 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { RemoteSettingsWorker: "resource://services-settings/RemoteSettingsWorker.jsm", }); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + const PREF_SETTINGS_BRANCH = "services.settings."; const PREF_SETTINGS_SERVER_BACKOFF = "server.backoff"; const PREF_SETTINGS_LAST_UPDATE = "last_update_seconds"; diff --git a/services/sync/modules/bookmark_validator.js b/services/sync/modules/bookmark_validator.js index 0405ee58caa7..14ce10da993a 100644 --- a/services/sync/modules/bookmark_validator.js +++ b/services/sync/modules/bookmark_validator.js @@ -32,6 +32,8 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/PlacesSyncUtils.jsm" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["URLSearchParams"]); + var EXPORTED_SYMBOLS = ["BookmarkValidator", "BookmarkProblemData"]; const QUERY_PROTOCOL = "place:"; @@ -46,12 +48,12 @@ function areURLsEqual(a, b) { // Tag queries are special because we rewrite them to point to the // local tag folder ID. It's expected that the folders won't match, // but all other params should. - let aParams = new URLSearchParams(a.slice(QUERY_PROTOCOL.length)); + let aParams = new lazy.URLSearchParams(a.slice(QUERY_PROTOCOL.length)); let aType = +aParams.get("type"); if (aType != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) { return false; } - let bParams = new URLSearchParams(b.slice(QUERY_PROTOCOL.length)); + let bParams = new lazy.URLSearchParams(b.slice(QUERY_PROTOCOL.length)); let bType = +bParams.get("type"); if (bType != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) { return false; @@ -681,7 +683,7 @@ class BookmarkValidator { ) { return; } - let params = new URLSearchParams( + let params = new lazy.URLSearchParams( entry.bmkUri.slice(QUERY_PROTOCOL.length) ); // Queries with `excludeQueries` won't form cycles because they'll diff --git a/services/sync/modules/resource.js b/services/sync/modules/resource.js index ae86ce596deb..33659c84a3c5 100644 --- a/services/sync/modules/resource.js +++ b/services/sync/modules/resource.js @@ -18,6 +18,8 @@ const { Utils } = ChromeUtils.import("resource://services-sync/util.js"); const { setTimeout, clearTimeout } = ChromeUtils.import( "resource://gre/modules/Timer.jsm" ); +const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch", "Headers", "Request"]); /* global AbortController */ /* @@ -102,7 +104,7 @@ Resource.prototype = { * @returns {Headers} */ async _buildHeaders(method) { - const headers = new Headers(this._headers); + const headers = new lazy.Headers(this._headers); if (Resource.SEND_VERSION_INFO) { headers.append("user-agent", Utils.userAgent); @@ -166,7 +168,7 @@ Resource.prototype = { this._log.trace(`${method} Body: ${data}`); init.body = data; } - return new Request(this.uri.spec, init); + return new lazy.Request(this.uri.spec, init); }, /** @@ -177,7 +179,7 @@ Resource.prototype = { async _doRequest(method, data = null) { const controller = new AbortController(); const request = await this._createRequest(method, data, controller.signal); - const responsePromise = fetch(request); // Rejects on network failure. + const responsePromise = lazy.fetch(request); // Rejects on network failure. let didTimeout = false; const timeoutId = setTimeout(() => { didTimeout = true; diff --git a/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm b/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm index 6c761bcc10ec..3a9c54be8597 100644 --- a/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm +++ b/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm @@ -21,8 +21,14 @@ const { FxAccountsConfig } = ChromeUtils.import( "resource://gre/modules/FxAccountsConfig.jsm" ); const { Logger } = ChromeUtils.import("resource://tps/logger.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + /** * Helper object for Firefox Accounts authentication */ @@ -92,7 +98,7 @@ var Authentication = { const tries = 10; const normalWait = 2000; for (let i = 0; i < tries; ++i) { - let resp = await fetch(restmailURI); + let resp = await lazy.fetch(restmailURI); let messages = await resp.json(); // Sort so that the most recent emails are first. messages.sort((a, b) => new Date(b.receivedAt) - new Date(a.receivedAt)); @@ -139,7 +145,7 @@ var Authentication = { )}`; try { // Clean up after ourselves. - let deleteResult = await fetch(restmailURI, { method: "DELETE" }); + let deleteResult = await lazy.fetch(restmailURI, { method: "DELETE" }); if (!deleteResult.ok) { Logger.logInfo( `Warning: Got non-success status ${deleteResult.status} when deleting emails` diff --git a/toolkit/actors/AboutHttpsOnlyErrorChild.jsm b/toolkit/actors/AboutHttpsOnlyErrorChild.jsm index 4917e4d2fad8..105bdb458453 100644 --- a/toolkit/actors/AboutHttpsOnlyErrorChild.jsm +++ b/toolkit/actors/AboutHttpsOnlyErrorChild.jsm @@ -3,6 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +Cu.importGlobalProperties(["fetch"]); var EXPORTED_SYMBOLS = ["AboutHttpsOnlyErrorChild"]; diff --git a/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm b/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm index af7fac42606e..550513a622a0 100644 --- a/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm +++ b/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm @@ -11,6 +11,8 @@ var EXPORTED_SYMBOLS = ["runBackgroundTask"]; +Cu.importGlobalProperties(["fetch"]); + const { EXIT_CODE } = ChromeUtils.import( "resource://gre/modules/BackgroundTasksManager.jsm" ).BackgroundTasksManager; diff --git a/toolkit/components/cleardata/SiteDataTestUtils.jsm b/toolkit/components/cleardata/SiteDataTestUtils.jsm index 9741cfc85662..81277ac933ce 100644 --- a/toolkit/components/cleardata/SiteDataTestUtils.jsm +++ b/toolkit/components/cleardata/SiteDataTestUtils.jsm @@ -23,6 +23,8 @@ XPCOMUtils.defineLazyServiceGetter( "nsIServiceWorkerManager" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["indexedDB"]); + /** * This module assists with tasks around testing functionality that shows * or clears site data. @@ -61,7 +63,11 @@ var SiteDataTestUtils = { let principal = Services.scriptSecurityManager.createContentPrincipalFromOrigin( origin ); - let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1); + let request = lazy.indexedDB.openForPrincipal( + principal, + "TestDatabase", + 1 + ); request.onupgradeneeded = function(e) { let db = e.target.result; db.createObjectStore("TestStore"); @@ -250,7 +256,11 @@ var SiteDataTestUtils = { ); return new Promise(resolve => { let data = true; - let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1); + let request = lazy.indexedDB.openForPrincipal( + principal, + "TestDatabase", + 1 + ); request.onupgradeneeded = function(e) { data = false; }; diff --git a/toolkit/components/extensions/ExtensionCommon.jsm b/toolkit/components/extensions/ExtensionCommon.jsm index 00c6f7ed48fc..50496643afaa 100644 --- a/toolkit/components/extensions/ExtensionCommon.jsm +++ b/toolkit/components/extensions/ExtensionCommon.jsm @@ -25,6 +25,8 @@ const { AppConstants } = ChromeUtils.import( const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + XPCOMUtils.defineLazyModuleGetters(lazy, { ConsoleAPI: "resource://gre/modules/Console.jsm", PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm", @@ -1392,7 +1394,7 @@ class SchemaAPIManager extends EventEmitter { } async loadModuleJSON(urls) { - let promises = urls.map(url => fetch(url).then(resp => resp.json())); + let promises = urls.map(url => lazy.fetch(url).then(resp => resp.json())); return this.initModuleJSON(await Promise.all(promises)); } diff --git a/toolkit/components/extensions/ExtensionContent.jsm b/toolkit/components/extensions/ExtensionContent.jsm index 124dd3fc86ac..10ef689307cf 100644 --- a/toolkit/components/extensions/ExtensionContent.jsm +++ b/toolkit/components/extensions/ExtensionContent.jsm @@ -48,6 +48,8 @@ const { ExtensionUtils } = ChromeUtils.import( "resource://gre/modules/ExtensionUtils.jsm" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); + const { DefaultMap, DefaultWeakMap, @@ -371,7 +373,7 @@ class Script { } // Store the hash of the cssCode. - const buffer = await crypto.subtle.digest( + const buffer = await lazy.crypto.subtle.digest( "SHA-1", new TextEncoder().encode(cssCode) ); diff --git a/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm b/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm index 78d48c71726f..4e49ce737c88 100644 --- a/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm +++ b/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm @@ -16,6 +16,8 @@ var EXPORTED_SYMBOLS = [ "extensionStorageSync", ]; +Cu.importGlobalProperties(["atob", "btoa"]); + const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); diff --git a/toolkit/components/extensions/ExtensionUtils.jsm b/toolkit/components/extensions/ExtensionUtils.jsm index 8eae43d87297..47c38a7f4d8f 100644 --- a/toolkit/components/extensions/ExtensionUtils.jsm +++ b/toolkit/components/extensions/ExtensionUtils.jsm @@ -20,6 +20,8 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/Timer.jsm" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + // xpcshell doesn't handle idle callbacks well. XPCOMUtils.defineLazyGetter(lazy, "idleTimeout", () => Services.appinfo.name === "XPCShell" ? 500 : undefined @@ -322,7 +324,7 @@ function parseMatchPatterns(patterns, options) { async function makeDataURI(iconUrl) { let response; try { - response = await fetch(iconUrl); + response = await lazy.fetch(iconUrl); } catch (e) { // Failed to fetch, ignore engine's favicon. Cu.reportError(e); diff --git a/toolkit/components/extensions/test/mochitest/webrequest_test.jsm b/toolkit/components/extensions/test/mochitest/webrequest_test.jsm index 50496524fcfa..6fc2fe3d7f1d 100644 --- a/toolkit/components/extensions/test/mochitest/webrequest_test.jsm +++ b/toolkit/components/extensions/test/mochitest/webrequest_test.jsm @@ -2,6 +2,8 @@ var EXPORTED_SYMBOLS = ["webrequest_test"]; +Cu.importGlobalProperties(["fetch"]); + var webrequest_test = { testFetch(url) { return fetch(url); diff --git a/toolkit/components/featuregates/FeatureGate.jsm b/toolkit/components/featuregates/FeatureGate.jsm index 3c8a8b9b927c..5d0204c8d15b 100644 --- a/toolkit/components/featuregates/FeatureGate.jsm +++ b/toolkit/components/featuregates/FeatureGate.jsm @@ -17,6 +17,8 @@ ChromeUtils.defineModuleGetter( "resource://featuregates/FeatureGateImplementation.jsm" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + var EXPORTED_SYMBOLS = ["FeatureGate"]; XPCOMUtils.defineLazyGetter(lazy, "gFeatureDefinitionsPromise", async () => { @@ -25,7 +27,7 @@ XPCOMUtils.defineLazyGetter(lazy, "gFeatureDefinitionsPromise", async () => { }); async function fetchFeatureDefinitions(url) { - const res = await fetch(url); + const res = await lazy.fetch(url); let definitionsJson = await res.json(); return new Map(Object.entries(definitionsJson)); } diff --git a/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm b/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm index bb47dfefbc35..37434c3afb02 100644 --- a/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm +++ b/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm @@ -16,6 +16,7 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { ASRouterTargeting: "resource://activity-stream/lib/ASRouterTargeting.jsm", TargetingContext: "resource://messaging-system/targeting/Targeting.jsm", @@ -66,9 +67,10 @@ XPCOMUtils.defineLazyPreferenceGetter( const SCHEMAS = { get NimbusExperiment() { - return fetch("resource://nimbus/schemas/NimbusExperiment.schema.json", { - credentials: "omit", - }) + return lazy + .fetch("resource://nimbus/schemas/NimbusExperiment.schema.json", { + credentials: "omit", + }) .then(rsp => rsp.json()) .then(json => json.definitions.NimbusExperiment); }, @@ -373,9 +375,9 @@ class _RemoteSettingsExperimentLoader { } else if (lazy.NimbusFeatures[featureId].manifest.schema?.uri) { const uri = lazy.NimbusFeatures[featureId].manifest.schema.uri; try { - const schema = await fetch(uri, { credentials: "omit" }).then(rsp => - rsp.json() - ); + const schema = await lazy + .fetch(uri, { credentials: "omit" }) + .then(rsp => rsp.json()); validator = validatorCache[ featureId ] = new lazy.JsonSchema.Validator(schema); diff --git a/toolkit/components/nimbus/test/NimbusTestUtils.jsm b/toolkit/components/nimbus/test/NimbusTestUtils.jsm index b60e71847ddd..5d73d924c45b 100644 --- a/toolkit/components/nimbus/test/NimbusTestUtils.jsm +++ b/toolkit/components/nimbus/test/NimbusTestUtils.jsm @@ -3,6 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +Cu.importGlobalProperties(["fetch"]); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); diff --git a/toolkit/components/normandy/lib/NormandyApi.jsm b/toolkit/components/normandy/lib/NormandyApi.jsm index 0ea744683acf..226ed050e73b 100644 --- a/toolkit/components/normandy/lib/NormandyApi.jsm +++ b/toolkit/components/normandy/lib/NormandyApi.jsm @@ -5,6 +5,9 @@ "use strict"; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const lazy = {}; @@ -14,6 +17,8 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/CanonicalJSON.jsm" ); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + var EXPORTED_SYMBOLS = ["NormandyApi"]; const prefs = Services.prefs.getBranch("app.normandy."); @@ -54,7 +59,7 @@ var NormandyApi = { url.searchParams.set(key, data[key]); } } - return fetch(url.href, { + return lazy.fetch(url.href, { method: "get", headers: { Accept: "application/json" }, credentials: "omit", diff --git a/toolkit/components/passwordmgr/LoginRecipes.jsm b/toolkit/components/passwordmgr/LoginRecipes.jsm index bea7be6d65aa..898925d4b197 100644 --- a/toolkit/components/passwordmgr/LoginRecipes.jsm +++ b/toolkit/components/passwordmgr/LoginRecipes.jsm @@ -28,6 +28,8 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + ChromeUtils.defineModuleGetter( lazy, "LoginHelper", diff --git a/toolkit/components/passwordmgr/PasswordGenerator.jsm b/toolkit/components/passwordmgr/PasswordGenerator.jsm index b6b4754f303e..b08cc5107f0a 100644 --- a/toolkit/components/passwordmgr/PasswordGenerator.jsm +++ b/toolkit/components/passwordmgr/PasswordGenerator.jsm @@ -12,6 +12,14 @@ const EXPORTED_SYMBOLS = ["PasswordGenerator"]; +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); + +const lazy = {}; + +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); + const DEFAULT_PASSWORD_LENGTH = 15; const MAX_UINT8 = Math.pow(2, 8) - 1; const MAX_UINT32 = Math.pow(2, 32) - 1; @@ -161,7 +169,7 @@ const PasswordGenerator = { const randomValueArr = new Uint8Array(1); do { - crypto.getRandomValues(randomValueArr); + lazy.crypto.getRandomValues(randomValueArr); } while (randomValueArr[0] > MAX_ACCEPTABLE_VALUE); return randomValueArr[0] % range; }, @@ -175,7 +183,7 @@ const PasswordGenerator = { let arr = Array.from(str); // Generate all the random numbers that will be needed. const randomValues = new Uint32Array(arr.length - 1); - crypto.getRandomValues(randomValues); + lazy.crypto.getRandomValues(randomValues); // Fisher-Yates Shuffle // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle diff --git a/toolkit/components/places/BookmarkJSONUtils.jsm b/toolkit/components/places/BookmarkJSONUtils.jsm index dd18a4074c46..f1b191eab50a 100644 --- a/toolkit/components/places/BookmarkJSONUtils.jsm +++ b/toolkit/components/places/BookmarkJSONUtils.jsm @@ -9,6 +9,8 @@ const { PlacesUtils } = ChromeUtils.import( "resource://gre/modules/PlacesUtils.jsm" ); +Cu.importGlobalProperties(["fetch"]); + const lazy = {}; ChromeUtils.defineModuleGetter( diff --git a/toolkit/components/search/tests/SearchTestUtils.jsm b/toolkit/components/search/tests/SearchTestUtils.jsm index 693a8d4a1c56..709b00a9dd5b 100644 --- a/toolkit/components/search/tests/SearchTestUtils.jsm +++ b/toolkit/components/search/tests/SearchTestUtils.jsm @@ -20,6 +20,8 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { sinon: "resource://testing-common/Sinon.jsm", }); +Cu.importGlobalProperties(["fetch"]); + var EXPORTED_SYMBOLS = ["SearchTestUtils"]; var gTestScope; diff --git a/toolkit/components/utils/Sampling.jsm b/toolkit/components/utils/Sampling.jsm index c27d698dcd99..06a75689511b 100644 --- a/toolkit/components/utils/Sampling.jsm +++ b/toolkit/components/utils/Sampling.jsm @@ -4,6 +4,12 @@ "use strict"; +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); + var EXPORTED_SYMBOLS = ["Sampling"]; const hashBits = 48; @@ -72,7 +78,7 @@ var Sampling = { * @promise A hash of `data`, truncated to the 12 most significant characters. */ async truncatedHash(data) { - const hasher = crypto.subtle; + const hasher = lazy.crypto.subtle; const input = new TextEncoder("utf-8").encode(JSON.stringify(data)); const hash = await hasher.digest("SHA-256", input); // truncate hash to 12 characters (2^48), because the full hash is larger diff --git a/toolkit/modules/IndexedDB.jsm b/toolkit/modules/IndexedDB.jsm index ecc47361bfb0..c0f11635445f 100644 --- a/toolkit/modules/IndexedDB.jsm +++ b/toolkit/modules/IndexedDB.jsm @@ -15,6 +15,8 @@ /* exported IndexedDB */ var EXPORTED_SYMBOLS = ["IndexedDB"]; +Cu.importGlobalProperties(["indexedDB"]); + /** * Wraps the given request object, and returns a Promise which resolves when * the requests succeeds or rejects when it fails. diff --git a/toolkit/modules/Region.jsm b/toolkit/modules/Region.jsm index 3f0564a9c9b3..9fbc02fa1dd1 100644 --- a/toolkit/modules/Region.jsm +++ b/toolkit/modules/Region.jsm @@ -25,6 +25,8 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { setTimeout: "resource://gre/modules/Timer.jsm", }); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + XPCOMUtils.defineLazyPreferenceGetter( lazy, "wifiScanningEnabled", @@ -745,7 +747,10 @@ class RegionDetector { async _fetchTimeout(url, opts, timeout) { let controller = new AbortController(); opts.signal = controller.signal; - return Promise.race([fetch(url, opts), this._timeout(timeout, controller)]); + return Promise.race([ + lazy.fetch(url, opts), + this._timeout(timeout, controller), + ]); } /** diff --git a/toolkit/modules/UpdateUtils.jsm b/toolkit/modules/UpdateUtils.jsm index 5257a5dcec0b..74522d3f8b09 100644 --- a/toolkit/modules/UpdateUtils.jsm +++ b/toolkit/modules/UpdateUtils.jsm @@ -22,6 +22,8 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { "resource://gre/modules/components-utils/WindowsVersionInfo.jsm", }); +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); + const PER_INSTALLATION_PREFS_PLATFORMS = ["win"]; // The file that stores Application Update configuration settings. The file is @@ -129,7 +131,7 @@ var UpdateUtils = { const url = "resource://" + res + "/" + FILE_UPDATE_LOCALE; let data; try { - data = await fetch(url); + data = await lazy.fetch(url); } catch (e) { continue; } diff --git a/toolkit/mozapps/extensions/AbuseReporter.jsm b/toolkit/mozapps/extensions/AbuseReporter.jsm index 74aa746df6ba..4bfacca2e29a 100644 --- a/toolkit/mozapps/extensions/AbuseReporter.jsm +++ b/toolkit/mozapps/extensions/AbuseReporter.jsm @@ -12,6 +12,8 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); +Cu.importGlobalProperties(["fetch"]); + const PREF_ABUSE_REPORT_URL = "extensions.abuseReport.url"; const PREF_AMO_DETAILS_API_URL = "extensions.abuseReport.amoDetailsURL"; diff --git a/toolkit/mozapps/extensions/internal/AddonRepository.jsm b/toolkit/mozapps/extensions/internal/AddonRepository.jsm index 481701e4300b..fa2471140c92 100644 --- a/toolkit/mozapps/extensions/internal/AddonRepository.jsm +++ b/toolkit/mozapps/extensions/internal/AddonRepository.jsm @@ -43,6 +43,8 @@ XPCOMUtils.defineLazyGetter(lazy, "PLATFORM", () => { var EXPORTED_SYMBOLS = ["AddonRepository"]; +Cu.importGlobalProperties(["fetch"]); + const PREF_GETADDONS_CACHE_ENABLED = "extensions.getAddons.cache.enabled"; const PREF_GETADDONS_CACHE_TYPES = "extensions.getAddons.cache.types"; const PREF_GETADDONS_CACHE_ID_ENABLED = diff --git a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm index 898132bba095..77eee4ab2ad1 100644 --- a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm +++ b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm @@ -11,6 +11,8 @@ var EXPORTED_SYMBOLS = ["AddonTestUtils", "MockAsyncShutdown"]; const CERTDB_CONTRACTID = "@mozilla.org/security/x509certdb;1"; +Cu.importGlobalProperties(["fetch"]); + const { AddonManager, AddonManagerPrivate } = ChromeUtils.import( "resource://gre/modules/AddonManager.jsm" ); diff --git a/toolkit/mozapps/extensions/internal/XPIInstall.jsm b/toolkit/mozapps/extensions/internal/XPIInstall.jsm index 5140c1b4175a..ae9a7a56f6d4 100644 --- a/toolkit/mozapps/extensions/internal/XPIInstall.jsm +++ b/toolkit/mozapps/extensions/internal/XPIInstall.jsm @@ -35,6 +35,7 @@ const { AddonManager, AddonManagerPrivate } = ChromeUtils.import( ); const lazy = {}; +XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", @@ -336,7 +337,7 @@ XPIPackage = class XPIPackage extends Package { } async readBinary(...path) { - let response = await fetch(this.rootURI.resolve(path.join("/"))); + let response = await lazy.fetch(this.rootURI.resolve(path.join("/"))); return response.arrayBuffer(); } @@ -387,7 +388,7 @@ function builtinPackage(baseURL) { }, async hasResource(path) { try { - let response = await fetch(this.rootURI.resolve(path)); + let response = await lazy.fetch(this.rootURI.resolve(path)); return response.ok; } catch (e) { return false; diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js index 36c7b39fee05..20478286d1fd 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js @@ -22,10 +22,5 @@ module.exports = { // JS can run. It's definitely available in JSMs. So even if this is not // the perfect place to add it, it's not wrong, and we can move it later. WebAssembly: false, - // These are hard-coded and available in .jsm scopes. - // See BackstagePass::Resolve. - fetch: false, - crypto: false, - indexedDB: false, }, }; From 9df90c7c454e08f1593f51f1cd11e9ed03739887 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Thu, 16 Jun 2022 00:19:53 +0000 Subject: [PATCH 48/64] Bug 1608282 - Part 1: Support fetch, crypto, and indexedDB in the system global by default. r=mccr8 Differential Revision: https://phabricator.services.mozilla.com/D149194 --- js/xpconnect/src/Sandbox.cpp | 4 ++-- js/xpconnect/src/XPCJSRuntime.cpp | 3 +++ js/xpconnect/src/XPCRuntimeService.cpp | 32 +++++++++++++++++++++++++- js/xpconnect/src/xpcprivate.h | 6 +++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/js/xpconnect/src/Sandbox.cpp b/js/xpconnect/src/Sandbox.cpp index a1b79335fe06..8fb54ab09522 100644 --- a/js/xpconnect/src/Sandbox.cpp +++ b/js/xpconnect/src/Sandbox.cpp @@ -270,7 +270,7 @@ static bool SandboxImport(JSContext* cx, unsigned argc, Value* vp) { return true; } -static bool SandboxCreateCrypto(JSContext* cx, JS::HandleObject obj) { +bool xpc::SandboxCreateCrypto(JSContext* cx, JS::Handle obj) { MOZ_ASSERT(JS_IsGlobalObject(obj)); nsIGlobalObject* native = xpc::NativeGlobal(obj); @@ -359,7 +359,7 @@ static bool SandboxFetchPromise(JSContext* cx, unsigned argc, Value* vp) { return ConvertExceptionToPromise(cx, args.rval()); } -static bool SandboxCreateFetch(JSContext* cx, HandleObject obj) { +bool xpc::SandboxCreateFetch(JSContext* cx, JS::Handle obj) { MOZ_ASSERT(JS_IsGlobalObject(obj)); return JS_DefineFunction(cx, obj, "fetch", SandboxFetchPromise, 2, 0) && diff --git a/js/xpconnect/src/XPCJSRuntime.cpp b/js/xpconnect/src/XPCJSRuntime.cpp index 7db4e73e6c6a..8c3f37172a26 100644 --- a/js/xpconnect/src/XPCJSRuntime.cpp +++ b/js/xpconnect/src/XPCJSRuntime.cpp @@ -128,6 +128,9 @@ const char* const XPCJSRuntime::mStrings[] = { "interfaceId", // IDX_INTERFACE_ID "initializer", // IDX_INITIALIZER "print", // IDX_PRINT + "fetch", // IDX_FETCH + "crypto", // IDX_CRYPTO + "indexedDB", // IDX_INDEXEDDB }; /***************************************************************************/ diff --git a/js/xpconnect/src/XPCRuntimeService.cpp b/js/xpconnect/src/XPCRuntimeService.cpp index d7b6edd54ed1..c22fd3393930 100644 --- a/js/xpconnect/src/XPCRuntimeService.cpp +++ b/js/xpconnect/src/XPCRuntimeService.cpp @@ -11,6 +11,7 @@ #include "BackstagePass.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/WebIDLGlobalNameHash.h" +#include "mozilla/dom/IndexedDatabaseManager.h" using namespace mozilla::dom; @@ -66,7 +67,36 @@ BackstagePass::Resolve(nsIXPConnectWrappedNative* wrapper, JSContext* cx, JS::RootedId id(cx, idArg); *_retval = WebIDLGlobalNameHash::ResolveForSystemGlobal(cx, obj, id, resolvedp); - return *_retval ? NS_OK : NS_ERROR_FAILURE; + if (!*_retval) { + return NS_ERROR_FAILURE; + } + + if (*resolvedp) { + return NS_OK; + } + + XPCJSContext* xpccx = XPCJSContext::Get(); + if (id == xpccx->GetStringID(XPCJSContext::IDX_FETCH)) { + *_retval = xpc::SandboxCreateFetch(cx, obj); + if (!*_retval) { + return NS_ERROR_FAILURE; + } + *resolvedp = true; + } else if (id == xpccx->GetStringID(XPCJSContext::IDX_CRYPTO)) { + *_retval = xpc::SandboxCreateCrypto(cx, obj); + if (!*_retval) { + return NS_ERROR_FAILURE; + } + *resolvedp = true; + } else if (id == xpccx->GetStringID(XPCJSContext::IDX_INDEXEDDB)) { + *_retval = IndexedDatabaseManager::DefineIndexedDB(cx, obj); + if (!*_retval) { + return NS_ERROR_FAILURE; + } + *resolvedp = true; + } + + return NS_OK; } NS_IMETHODIMP diff --git a/js/xpconnect/src/xpcprivate.h b/js/xpconnect/src/xpcprivate.h index d2f785d599b0..c4727a746cf1 100644 --- a/js/xpconnect/src/xpcprivate.h +++ b/js/xpconnect/src/xpcprivate.h @@ -404,6 +404,9 @@ class XPCJSContext final : public mozilla::CycleCollectedJSContext, IDX_INTERFACE_ID, IDX_INITIALIZER, IDX_PRINT, + IDX_FETCH, + IDX_CRYPTO, + IDX_INDEXEDDB, IDX_TOTAL_COUNT // just a count of the above }; @@ -2850,6 +2853,9 @@ void InitializeValue(const nsXPTType& aType, void* aValue); void DestructValue(const nsXPTType& aType, void* aValue, uint32_t aArrayLen = 0); +bool SandboxCreateCrypto(JSContext* cx, JS::Handle obj); +bool SandboxCreateFetch(JSContext* cx, JS::Handle obj); + } // namespace xpc namespace mozilla { From 140100ba1c50d600168f4de10c55094325870891 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Thu, 16 Jun 2022 00:19:54 +0000 Subject: [PATCH 49/64] Bug 1608282 - Part 2: Update jsm environment definition to include fetch, crypto, indexedDB. r=mccr8 Differential Revision: https://phabricator.services.mozilla.com/D149195 --- .../eslint/eslint-plugin-mozilla/lib/environments/jsm.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js index 20478286d1fd..36c7b39fee05 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/jsm.js @@ -22,5 +22,10 @@ module.exports = { // JS can run. It's definitely available in JSMs. So even if this is not // the perfect place to add it, it's not wrong, and we can move it later. WebAssembly: false, + // These are hard-coded and available in .jsm scopes. + // See BackstagePass::Resolve. + fetch: false, + crypto: false, + indexedDB: false, }, }; From 4842565434265a347cc8c6950b2d73c531b67bf3 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Thu, 16 Jun 2022 00:19:54 +0000 Subject: [PATCH 50/64] Bug 1608282 - Part 3: Remove Cu.importGlobalProperties from JSM. r=extension-reviewers,kmag Depends on D149195 Differential Revision: https://phabricator.services.mozilla.com/D149196 --- browser/actors/AboutProtectionsParent.jsm | 2 -- browser/components/migration/ChromeMacOSLoginCrypto.jsm | 2 -- browser/components/migration/ChromeWindowsLoginCrypto.jsm | 2 -- browser/components/newtab/test/RemoteImagesTestUtils.jsm | 2 -- browser/components/pagedata/PageDataSchema.jsm | 2 -- browser/modules/PartnerLinkAttribution.jsm | 2 -- dom/base/IndexedDBHelper.jsm | 2 -- dom/indexedDB/test/unit/GlobalObjectsModule.jsm | 2 -- js/xpconnect/loader/XPCOMUtils.jsm | 3 --- services/settings/IDBHelpers.jsm | 6 ------ services/settings/SharedUtils.jsm | 5 ----- toolkit/actors/AboutHttpsOnlyErrorChild.jsm | 1 - .../tests/BackgroundTask_profile_is_slim.jsm | 2 -- toolkit/components/extensions/ExtensionStorageSyncKinto.jsm | 2 -- .../extensions/test/mochitest/webrequest_test.jsm | 2 -- toolkit/components/nimbus/test/NimbusTestUtils.jsm | 1 - toolkit/components/places/BookmarkJSONUtils.jsm | 2 -- toolkit/components/search/tests/SearchTestUtils.jsm | 2 -- toolkit/modules/IndexedDB.jsm | 2 -- toolkit/mozapps/extensions/AbuseReporter.jsm | 2 -- toolkit/mozapps/extensions/internal/AddonRepository.jsm | 2 -- toolkit/mozapps/extensions/internal/AddonTestUtils.jsm | 2 -- 22 files changed, 50 deletions(-) diff --git a/browser/actors/AboutProtectionsParent.jsm b/browser/actors/AboutProtectionsParent.jsm index 741f0592898b..948644efa5ea 100644 --- a/browser/actors/AboutProtectionsParent.jsm +++ b/browser/actors/AboutProtectionsParent.jsm @@ -4,8 +4,6 @@ "use strict"; -Cu.importGlobalProperties(["fetch"]); - var EXPORTED_SYMBOLS = ["AboutProtectionsParent"]; const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" diff --git a/browser/components/migration/ChromeMacOSLoginCrypto.jsm b/browser/components/migration/ChromeMacOSLoginCrypto.jsm index 7abb5cb1ae96..98b25f7a35bb 100644 --- a/browser/components/migration/ChromeMacOSLoginCrypto.jsm +++ b/browser/components/migration/ChromeMacOSLoginCrypto.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["ChromeMacOSLoginCrypto"]; -Cu.importGlobalProperties(["crypto"]); - const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); diff --git a/browser/components/migration/ChromeWindowsLoginCrypto.jsm b/browser/components/migration/ChromeWindowsLoginCrypto.jsm index bbe204132a9f..3cbb668f2ec6 100644 --- a/browser/components/migration/ChromeWindowsLoginCrypto.jsm +++ b/browser/components/migration/ChromeWindowsLoginCrypto.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["ChromeWindowsLoginCrypto"]; -Cu.importGlobalProperties(["atob", "crypto"]); - const { ChromeMigrationUtils } = ChromeUtils.import( "resource:///modules/ChromeMigrationUtils.jsm" ); diff --git a/browser/components/newtab/test/RemoteImagesTestUtils.jsm b/browser/components/newtab/test/RemoteImagesTestUtils.jsm index 2b9a0113ff50..e99646c620f0 100644 --- a/browser/components/newtab/test/RemoteImagesTestUtils.jsm +++ b/browser/components/newtab/test/RemoteImagesTestUtils.jsm @@ -14,8 +14,6 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const RS_SERVER_PREF = "services.settings.server"; -Cu.importGlobalProperties(["fetch"]); - const RemoteImagesTestUtils = { /** * Serve a mock Remote Settings server with content for Remote Images diff --git a/browser/components/pagedata/PageDataSchema.jsm b/browser/components/pagedata/PageDataSchema.jsm index 9fc37b5d33f9..29b757dbebec 100644 --- a/browser/components/pagedata/PageDataSchema.jsm +++ b/browser/components/pagedata/PageDataSchema.jsm @@ -6,8 +6,6 @@ var EXPORTED_SYMBOLS = ["PageDataSchema"]; -Cu.importGlobalProperties(["fetch"]); - const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); diff --git a/browser/modules/PartnerLinkAttribution.jsm b/browser/modules/PartnerLinkAttribution.jsm index cbb9e77a3c6a..1d8b2b8af5e7 100644 --- a/browser/modules/PartnerLinkAttribution.jsm +++ b/browser/modules/PartnerLinkAttribution.jsm @@ -4,8 +4,6 @@ "use strict"; -Cu.importGlobalProperties(["fetch"]); - var EXPORTED_SYMBOLS = [ "PartnerLinkAttribution", "CONTEXTUAL_SERVICES_PING_TYPES", diff --git a/dom/base/IndexedDBHelper.jsm b/dom/base/IndexedDBHelper.jsm index 170cfea6aa0f..3fd70668b115 100644 --- a/dom/base/IndexedDBHelper.jsm +++ b/dom/base/IndexedDBHelper.jsm @@ -16,8 +16,6 @@ if (DEBUG) { var EXPORTED_SYMBOLS = ["IndexedDBHelper"]; -Cu.importGlobalProperties(["indexedDB"]); - const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function getErrorName(err) { diff --git a/dom/indexedDB/test/unit/GlobalObjectsModule.jsm b/dom/indexedDB/test/unit/GlobalObjectsModule.jsm index c700bd8b180f..905e75c9ecef 100644 --- a/dom/indexedDB/test/unit/GlobalObjectsModule.jsm +++ b/dom/indexedDB/test/unit/GlobalObjectsModule.jsm @@ -3,8 +3,6 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ -Cu.importGlobalProperties(["indexedDB"]); - var EXPORTED_SYMBOLS = ["GlobalObjectsModule"]; function GlobalObjectsModule() {} diff --git a/js/xpconnect/loader/XPCOMUtils.jsm b/js/xpconnect/loader/XPCOMUtils.jsm index 789c3c5f961e..bcde97a9d9c7 100644 --- a/js/xpconnect/loader/XPCOMUtils.jsm +++ b/js/xpconnect/loader/XPCOMUtils.jsm @@ -21,10 +21,7 @@ let global = Cu.getGlobalForObject({}); // and `MessagePort`. This table maps those extra symbols to the main // import name. const EXTRA_GLOBAL_NAME_TO_IMPORT_NAME = { - Headers: "fetch", MessagePort: "MessageChannel", - Request: "fetch", - Response: "fetch", }; /** diff --git a/services/settings/IDBHelpers.jsm b/services/settings/IDBHelpers.jsm index 1199d87e943c..d58101caa4a2 100644 --- a/services/settings/IDBHelpers.jsm +++ b/services/settings/IDBHelpers.jsm @@ -7,12 +7,6 @@ var EXPORTED_SYMBOLS = ["IDBHelpers"]; const DB_NAME = "remote-settings"; const DB_VERSION = 3; -// `indexedDB` is accessible in the worker global, but not the JSM global, -// where we have to import it - and the worker global doesn't have Cu. -if (typeof indexedDB == "undefined") { - Cu.importGlobalProperties(["indexedDB"]); -} - /** * Wrap IndexedDB errors to catch them more easily. */ diff --git a/services/settings/SharedUtils.jsm b/services/settings/SharedUtils.jsm index 5d32fb38bd82..9804e80c91c4 100644 --- a/services/settings/SharedUtils.jsm +++ b/services/settings/SharedUtils.jsm @@ -8,11 +8,6 @@ var EXPORTED_SYMBOLS = ["SharedUtils"]; -// Import globals that are available by default in workers but not in JSMs. -if (typeof crypto == "undefined") { - Cu.importGlobalProperties(["fetch", "crypto"]); -} - var SharedUtils = { /** * Check that the specified content matches the expected size and SHA-256 hash. diff --git a/toolkit/actors/AboutHttpsOnlyErrorChild.jsm b/toolkit/actors/AboutHttpsOnlyErrorChild.jsm index 105bdb458453..4917e4d2fad8 100644 --- a/toolkit/actors/AboutHttpsOnlyErrorChild.jsm +++ b/toolkit/actors/AboutHttpsOnlyErrorChild.jsm @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -Cu.importGlobalProperties(["fetch"]); var EXPORTED_SYMBOLS = ["AboutHttpsOnlyErrorChild"]; diff --git a/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm b/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm index 550513a622a0..af7fac42606e 100644 --- a/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm +++ b/toolkit/components/backgroundtasks/tests/BackgroundTask_profile_is_slim.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["runBackgroundTask"]; -Cu.importGlobalProperties(["fetch"]); - const { EXIT_CODE } = ChromeUtils.import( "resource://gre/modules/BackgroundTasksManager.jsm" ).BackgroundTasksManager; diff --git a/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm b/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm index 4e49ce737c88..78d48c71726f 100644 --- a/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm +++ b/toolkit/components/extensions/ExtensionStorageSyncKinto.jsm @@ -16,8 +16,6 @@ var EXPORTED_SYMBOLS = [ "extensionStorageSync", ]; -Cu.importGlobalProperties(["atob", "btoa"]); - const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); diff --git a/toolkit/components/extensions/test/mochitest/webrequest_test.jsm b/toolkit/components/extensions/test/mochitest/webrequest_test.jsm index 6fc2fe3d7f1d..50496524fcfa 100644 --- a/toolkit/components/extensions/test/mochitest/webrequest_test.jsm +++ b/toolkit/components/extensions/test/mochitest/webrequest_test.jsm @@ -2,8 +2,6 @@ var EXPORTED_SYMBOLS = ["webrequest_test"]; -Cu.importGlobalProperties(["fetch"]); - var webrequest_test = { testFetch(url) { return fetch(url); diff --git a/toolkit/components/nimbus/test/NimbusTestUtils.jsm b/toolkit/components/nimbus/test/NimbusTestUtils.jsm index 5d73d924c45b..b60e71847ddd 100644 --- a/toolkit/components/nimbus/test/NimbusTestUtils.jsm +++ b/toolkit/components/nimbus/test/NimbusTestUtils.jsm @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -Cu.importGlobalProperties(["fetch"]); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); diff --git a/toolkit/components/places/BookmarkJSONUtils.jsm b/toolkit/components/places/BookmarkJSONUtils.jsm index f1b191eab50a..dd18a4074c46 100644 --- a/toolkit/components/places/BookmarkJSONUtils.jsm +++ b/toolkit/components/places/BookmarkJSONUtils.jsm @@ -9,8 +9,6 @@ const { PlacesUtils } = ChromeUtils.import( "resource://gre/modules/PlacesUtils.jsm" ); -Cu.importGlobalProperties(["fetch"]); - const lazy = {}; ChromeUtils.defineModuleGetter( diff --git a/toolkit/components/search/tests/SearchTestUtils.jsm b/toolkit/components/search/tests/SearchTestUtils.jsm index 709b00a9dd5b..693a8d4a1c56 100644 --- a/toolkit/components/search/tests/SearchTestUtils.jsm +++ b/toolkit/components/search/tests/SearchTestUtils.jsm @@ -20,8 +20,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { sinon: "resource://testing-common/Sinon.jsm", }); -Cu.importGlobalProperties(["fetch"]); - var EXPORTED_SYMBOLS = ["SearchTestUtils"]; var gTestScope; diff --git a/toolkit/modules/IndexedDB.jsm b/toolkit/modules/IndexedDB.jsm index c0f11635445f..ecc47361bfb0 100644 --- a/toolkit/modules/IndexedDB.jsm +++ b/toolkit/modules/IndexedDB.jsm @@ -15,8 +15,6 @@ /* exported IndexedDB */ var EXPORTED_SYMBOLS = ["IndexedDB"]; -Cu.importGlobalProperties(["indexedDB"]); - /** * Wraps the given request object, and returns a Promise which resolves when * the requests succeeds or rejects when it fails. diff --git a/toolkit/mozapps/extensions/AbuseReporter.jsm b/toolkit/mozapps/extensions/AbuseReporter.jsm index 4bfacca2e29a..74aa746df6ba 100644 --- a/toolkit/mozapps/extensions/AbuseReporter.jsm +++ b/toolkit/mozapps/extensions/AbuseReporter.jsm @@ -12,8 +12,6 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); -Cu.importGlobalProperties(["fetch"]); - const PREF_ABUSE_REPORT_URL = "extensions.abuseReport.url"; const PREF_AMO_DETAILS_API_URL = "extensions.abuseReport.amoDetailsURL"; diff --git a/toolkit/mozapps/extensions/internal/AddonRepository.jsm b/toolkit/mozapps/extensions/internal/AddonRepository.jsm index fa2471140c92..481701e4300b 100644 --- a/toolkit/mozapps/extensions/internal/AddonRepository.jsm +++ b/toolkit/mozapps/extensions/internal/AddonRepository.jsm @@ -43,8 +43,6 @@ XPCOMUtils.defineLazyGetter(lazy, "PLATFORM", () => { var EXPORTED_SYMBOLS = ["AddonRepository"]; -Cu.importGlobalProperties(["fetch"]); - const PREF_GETADDONS_CACHE_ENABLED = "extensions.getAddons.cache.enabled"; const PREF_GETADDONS_CACHE_TYPES = "extensions.getAddons.cache.types"; const PREF_GETADDONS_CACHE_ID_ENABLED = diff --git a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm index 77eee4ab2ad1..898132bba095 100644 --- a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm +++ b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm @@ -11,8 +11,6 @@ var EXPORTED_SYMBOLS = ["AddonTestUtils", "MockAsyncShutdown"]; const CERTDB_CONTRACTID = "@mozilla.org/security/x509certdb;1"; -Cu.importGlobalProperties(["fetch"]); - const { AddonManager, AddonManagerPrivate } = ChromeUtils.import( "resource://gre/modules/AddonManager.jsm" ); From 5e0731b2a414297b85e3666c7995f5def9c8932e Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Thu, 16 Jun 2022 00:19:54 +0000 Subject: [PATCH 51/64] Bug 1608282 - Part 4: Remove Cu.defineLazyGlobalGetters from JSM. r=webdriver-reviewers,extension-reviewers,jdescottes,kmag Depends on D149196 Differential Revision: https://phabricator.services.mozilla.com/D149197 --- browser/components/newtab/lib/ASRouter.jsm | 3 +- .../components/newtab/lib/CFRPageActions.jsm | 4 +- .../newtab/lib/DiscoveryStreamFeed.jsm | 6 +-- .../PersonalityProvider.jsm | 7 +-- browser/components/newtab/lib/Screenshots.jsm | 4 +- .../newtab/lib/TippyTopProvider.jsm | 9 +--- .../components/newtab/lib/TopSitesFeed.jsm | 4 +- .../components/newtab/lib/TopStoriesFeed.jsm | 10 ++-- .../urlbar/UrlbarProviderPreloadedSites.jsm | 2 - .../urlbar/UrlbarProviderQuickSuggest.jsm | 2 - dom/push/PushCrypto.jsm | 51 ++++++++----------- dom/system/NetworkGeolocationProvider.jsm | 4 +- .../android/actors/ContentDelegateChild.jsm | 4 +- remote/marionette/capture.js | 3 +- .../manager/ssl/RemoteSecuritySettings.jsm | 4 +- services/automation/ServicesAutomation.jsm | 4 +- services/crypto/modules/WeaveCrypto.js | 31 ++++------- services/crypto/modules/jwcrypto.jsm | 33 ++++-------- services/crypto/modules/utils.js | 17 +++---- .../fxaccounts/FxAccountsProfileClient.jsm | 9 +--- services/settings/Attachments.jsm | 3 +- services/settings/Utils.jsm | 6 +-- services/settings/remote-settings.js | 2 - services/sync/modules/bookmark_validator.js | 8 ++- services/sync/modules/resource.js | 8 ++- .../tps/resource/auth/fxaccounts.jsm | 10 +--- .../cleardata/SiteDataTestUtils.jsm | 14 +---- .../components/extensions/ExtensionCommon.jsm | 4 +- .../extensions/ExtensionContent.jsm | 4 +- .../components/extensions/ExtensionUtils.jsm | 4 +- .../components/featuregates/FeatureGate.jsm | 4 +- .../lib/RemoteSettingsExperimentLoader.jsm | 14 +++-- .../components/normandy/lib/NormandyApi.jsm | 7 +-- .../components/passwordmgr/LoginRecipes.jsm | 2 - .../passwordmgr/PasswordGenerator.jsm | 12 +---- toolkit/components/utils/Sampling.jsm | 8 +-- toolkit/modules/Region.jsm | 7 +-- toolkit/modules/UpdateUtils.jsm | 4 +- .../extensions/internal/XPIInstall.jsm | 5 +- 39 files changed, 97 insertions(+), 240 deletions(-) diff --git a/browser/components/newtab/lib/ASRouter.jsm b/browser/components/newtab/lib/ASRouter.jsm index d745083f8572..e5aa71694e1a 100644 --- a/browser/components/newtab/lib/ASRouter.jsm +++ b/browser/components/newtab/lib/ASRouter.jsm @@ -12,7 +12,6 @@ const { AppConstants } = ChromeUtils.import( "resource://gre/modules/AppConstants.jsm" ); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { SnippetsTestMessageProvider: "resource://activity-stream/lib/SnippetsTestMessageProvider.jsm", @@ -192,7 +191,7 @@ const MessageLoaderUtils = { let response; try { - response = await lazy.fetch(provider.url, { + response = await fetch(provider.url, { headers, credentials: "omit", }); diff --git a/browser/components/newtab/lib/CFRPageActions.jsm b/browser/components/newtab/lib/CFRPageActions.jsm index 0bd95b12d6b4..a6778d929992 100644 --- a/browser/components/newtab/lib/CFRPageActions.jsm +++ b/browser/components/newtab/lib/CFRPageActions.jsm @@ -10,8 +10,6 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyModuleGetters(lazy, { PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm", RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm", @@ -881,7 +879,7 @@ const CFRPageActions = { async _fetchLatestAddonVersion(id) { let url = null; try { - const response = await lazy.fetch(`${ADDONS_API_URL}/${id}/`, { + const response = await fetch(`${ADDONS_API_URL}/${id}/`, { credentials: "omit", }); if (response.status !== 204 && response.ok) { diff --git a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm index a32a2559485e..1abedd6767db 100644 --- a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm +++ b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm @@ -3,9 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const lazy = {}; ChromeUtils.defineModuleGetter( lazy, @@ -21,7 +18,6 @@ const { setTimeout, clearTimeout } = ChromeUtils.import( "resource://gre/modules/Timer.jsm" ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { actionTypes: at, actionCreators: ac } = ChromeUtils.import( "resource://activity-stream/common/Actions.jsm" ); @@ -287,7 +283,7 @@ class DiscoveryStreamFeed { const controller = new AbortController(); const { signal } = controller; - const fetchPromise = lazy.fetch(endpoint, { + const fetchPromise = fetch(endpoint, { ...options, credentials: "omit", signal, diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm index c34c2a896471..841d4c8ca30c 100644 --- a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm +++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm @@ -18,11 +18,6 @@ ChromeUtils.defineModuleGetter( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { BasePromiseWorker } = ChromeUtils.import( "resource://gre/modules/PromiseWorker.jsm" @@ -67,7 +62,7 @@ class PersonalityProvider { } const server = Services.prefs.getCharPref("services.settings.server"); const serverInfo = await ( - await lazy.fetch(`${server}/`, { + await fetch(`${server}/`, { credentials: "omit", }) ).json(); diff --git a/browser/components/newtab/lib/Screenshots.jsm b/browser/components/newtab/lib/Screenshots.jsm index a012ed62dbaf..ccf5c4c65070 100644 --- a/browser/components/newtab/lib/Screenshots.jsm +++ b/browser/components/newtab/lib/Screenshots.jsm @@ -11,8 +11,6 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - ChromeUtils.defineModuleGetter( lazy, "BackgroundPageThumbs", @@ -63,7 +61,7 @@ const Screenshots = { // Blob URIs for the screenshots. const imgPath = lazy.PageThumbs.getThumbnailPath(url); - const filePathResponse = await lazy.fetch(`file://${imgPath}`); + const filePathResponse = await fetch(`file://${imgPath}`); const fileContents = await filePathResponse.blob(); // Check if the file is empty, which indicates there isn't actually a diff --git a/browser/components/newtab/lib/TippyTopProvider.jsm b/browser/components/newtab/lib/TippyTopProvider.jsm index 138d9a7ef3c4..ab2895f35a5c 100644 --- a/browser/components/newtab/lib/TippyTopProvider.jsm +++ b/browser/components/newtab/lib/TippyTopProvider.jsm @@ -2,15 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const TIPPYTOP_PATH = "chrome://activity-stream/content/data/content/tippytop/"; const TIPPYTOP_JSON_PATH = "chrome://activity-stream/content/data/content/tippytop/top_sites.json"; @@ -43,7 +36,7 @@ class TippyTopProvider { // Load the Tippy Top sites from the json manifest. try { for (const site of await ( - await lazy.fetch(TIPPYTOP_JSON_PATH, { + await fetch(TIPPYTOP_JSON_PATH, { credentials: "omit", }) ).json()) { diff --git a/browser/components/newtab/lib/TopSitesFeed.jsm b/browser/components/newtab/lib/TopSitesFeed.jsm index ffb8a43ccb00..cc5438dac8e1 100644 --- a/browser/components/newtab/lib/TopSitesFeed.jsm +++ b/browser/components/newtab/lib/TopSitesFeed.jsm @@ -74,8 +74,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/Region.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyGetter(lazy, "log", () => { const { Logger } = ChromeUtils.import( "resource://messaging-system/lib/Logger.jsm" @@ -186,7 +184,7 @@ class ContileIntegration { } try { let url = Services.prefs.getStringPref(CONTILE_ENDPOINT_PREF); - const response = await lazy.fetch(url, { credentials: "omit" }); + const response = await fetch(url, { credentials: "omit" }); if (!response.ok) { lazy.log.warn( `Contile endpoint returned unexpected status: ${response.status}` diff --git a/browser/components/newtab/lib/TopStoriesFeed.jsm b/browser/components/newtab/lib/TopStoriesFeed.jsm index 1bcf027c4a2b..811159bbdaa3 100644 --- a/browser/components/newtab/lib/TopStoriesFeed.jsm +++ b/browser/components/newtab/lib/TopStoriesFeed.jsm @@ -3,15 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { NewTabUtils } = ChromeUtils.import( "resource://gre/modules/NewTabUtils.jsm" ); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); const { actionTypes: at, actionCreators: ac } = ChromeUtils.import( "resource://activity-stream/common/Actions.jsm" @@ -29,6 +24,7 @@ const { PersistentCache } = ChromeUtils.import( "resource://activity-stream/lib/PersistentCache.jsm" ); +const lazy = {}; ChromeUtils.defineModuleGetter( lazy, "pktApi", @@ -196,7 +192,7 @@ class TopStoriesFeed { return null; } try { - const response = await lazy.fetch(this.stories_endpoint, { + const response = await fetch(this.stories_endpoint, { credentials: "omit", }); if (!response.ok) { @@ -296,7 +292,7 @@ class TopStoriesFeed { return null; } try { - const response = await lazy.fetch(this.topics_endpoint, { + const response = await fetch(this.topics_endpoint, { credentials: "omit", }); if (!response.ok) { diff --git a/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm b/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm index dfd4b81ca544..aa76060865db 100644 --- a/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm +++ b/browser/components/urlbar/UrlbarProviderPreloadedSites.jsm @@ -17,8 +17,6 @@ const { XPCOMUtils } = ChromeUtils.import( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]); - XPCOMUtils.defineLazyModuleGetters(this, { ProfileAge: "resource://gre/modules/ProfileAge.jsm", UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm", diff --git a/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm b/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm index 1645f7448bdf..6b0ecf7463c4 100644 --- a/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm +++ b/browser/components/urlbar/UrlbarProviderQuickSuggest.jsm @@ -28,8 +28,6 @@ XPCOMUtils.defineLazyModuleGetters(this, { UrlbarUtils: "resource:///modules/UrlbarUtils.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(this, ["crypto", "fetch"]); - const TIMESTAMP_TEMPLATE = "%YYYYMMDDHH%"; const TIMESTAMP_LENGTH = 10; const TIMESTAMP_REGEXP = /^\d{10}$/; diff --git a/dom/push/PushCrypto.jsm b/dom/push/PushCrypto.jsm index 39e945a4527b..a1ace86a8c5f 100644 --- a/dom/push/PushCrypto.jsm +++ b/dom/push/PushCrypto.jsm @@ -15,8 +15,6 @@ XPCOMUtils.defineLazyGetter(lazy, "gDOMBundle", () => Services.strings.createBundle("chrome://global/locale/dom/dom.properties") ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - // getCryptoParamsFromHeaders is exported for test purposes. const EXPORTED_SYMBOLS = ["PushCrypto", "getCryptoParamsFromHeaders"]; @@ -243,17 +241,13 @@ function concatArray(arrays) { } function hmac(key) { - this.keyPromise = lazy.crypto.subtle.importKey( - "raw", - key, - HMAC_SHA256, - false, - ["sign"] - ); + this.keyPromise = crypto.subtle.importKey("raw", key, HMAC_SHA256, false, [ + "sign", + ]); } hmac.prototype.hash = function(input) { - return this.keyPromise.then(k => lazy.crypto.subtle.sign("HMAC", k, input)); + return this.keyPromise.then(k => crypto.subtle.sign("HMAC", k, input)); }; function hkdf(salt, ikm) { @@ -331,7 +325,7 @@ class Decoder { try { let ikm = await this.computeSharedSecret(); let [gcmBits, nonce] = await this.deriveKeyAndNonce(ikm); - let key = await lazy.crypto.subtle.importKey( + let key = await crypto.subtle.importKey( "raw", gcmBits, "AES-GCM", @@ -368,14 +362,14 @@ class Decoder { */ async computeSharedSecret() { let [appServerKey, subscriptionPrivateKey] = await Promise.all([ - lazy.crypto.subtle.importKey("raw", this.senderKey, ECDH_KEY, false, [ + crypto.subtle.importKey("raw", this.senderKey, ECDH_KEY, false, [ "deriveBits", ]), - lazy.crypto.subtle.importKey("jwk", this.privateKey, ECDH_KEY, false, [ + crypto.subtle.importKey("jwk", this.privateKey, ECDH_KEY, false, [ "deriveBits", ]), ]); - return lazy.crypto.subtle.deriveBits( + return crypto.subtle.deriveBits( { name: "ECDH", public: appServerKey }, subscriptionPrivateKey, 256 @@ -408,7 +402,7 @@ class Decoder { name: "AES-GCM", iv: generateNonce(nonce, index), }; - let decoded = await lazy.crypto.subtle.decrypt(params, key, slice); + let decoded = await crypto.subtle.decrypt(params, key, slice); return this.unpadChunk(new Uint8Array(decoded), last); } @@ -609,22 +603,22 @@ var PushCrypto = { concatArray, generateAuthenticationSecret() { - return lazy.crypto.getRandomValues(new Uint8Array(16)); + return crypto.getRandomValues(new Uint8Array(16)); }, validateAppServerKey(key) { - return lazy.crypto.subtle + return crypto.subtle .importKey("raw", key, ECDSA_KEY, true, ["verify"]) .then(_ => key); }, generateKeys() { - return lazy.crypto.subtle + return crypto.subtle .generateKey(ECDH_KEY, true, ["deriveBits"]) .then(cryptoKey => Promise.all([ - lazy.crypto.subtle.exportKey("raw", cryptoKey.publicKey), - lazy.crypto.subtle.exportKey("jwk", cryptoKey.privateKey), + crypto.subtle.exportKey("raw", cryptoKey.publicKey), + crypto.subtle.exportKey("jwk", cryptoKey.privateKey), ]) ); }, @@ -731,10 +725,9 @@ var PushCrypto = { // purposes we allow it to be specified. const senderKeyPair = options.senderKeyPair || - (await lazy.crypto.subtle.generateKey(ECDH_KEY, true, ["deriveBits"])); + (await crypto.subtle.generateKey(ECDH_KEY, true, ["deriveBits"])); // allowing a salt to be specified is useful for tests. - const salt = - options.salt || lazy.crypto.getRandomValues(new Uint8Array(16)); + const salt = options.salt || crypto.getRandomValues(new Uint8Array(16)); const rs = options.rs === undefined ? 4096 : options.rs; const encoder = new aes128gcmEncoder( @@ -773,7 +766,7 @@ class aes128gcmEncoder { this.senderKeyPair.privateKey ); - const rawSenderPublicKey = await lazy.crypto.subtle.exportKey( + const rawSenderPublicKey = await crypto.subtle.exportKey( "raw", this.senderKeyPair.publicKey ); @@ -782,7 +775,7 @@ class aes128gcmEncoder { rawSenderPublicKey ); - const contentEncryptionKey = await lazy.crypto.subtle.importKey( + const contentEncryptionKey = await crypto.subtle.importKey( "raw", gcmBits, "AES-GCM", @@ -808,7 +801,7 @@ class aes128gcmEncoder { if (this.plaintext.byteLength === 0) { // Send an authentication tag for empty messages. chunks = [ - await lazy.crypto.subtle.encrypt( + await crypto.subtle.encrypt( { name: "AES-GCM", iv: generateNonce(nonce, 0), @@ -826,7 +819,7 @@ class aes128gcmEncoder { let isLast = index == inChunks.length - 1; let padding = new Uint8Array([isLast ? 2 : 1]); let input = concatArray([slice, padding]); - return lazy.crypto.subtle.encrypt( + return crypto.subtle.encrypt( { name: "AES-GCM", iv: generateNonce(nonce, index), @@ -860,7 +853,7 @@ class aes128gcmEncoder { // Note: this duplicates some of Decoder.computeSharedSecret, but the key // management is slightly different. async computeSharedSecret(receiverPublicKey, senderPrivateKey) { - const receiverPublicCryptoKey = await lazy.crypto.subtle.importKey( + const receiverPublicCryptoKey = await crypto.subtle.importKey( "raw", receiverPublicKey, ECDH_KEY, @@ -868,7 +861,7 @@ class aes128gcmEncoder { ["deriveBits"] ); - return lazy.crypto.subtle.deriveBits( + return crypto.subtle.deriveBits( { name: "ECDH", public: receiverPublicCryptoKey }, senderPrivateKey, 256 diff --git a/dom/system/NetworkGeolocationProvider.jsm b/dom/system/NetworkGeolocationProvider.jsm index 9791f821eaab..96724258c9ba 100644 --- a/dom/system/NetworkGeolocationProvider.jsm +++ b/dom/system/NetworkGeolocationProvider.jsm @@ -17,8 +17,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { setTimeout: "resource://gre/modules/Timer.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - // GeolocationPositionError has no interface object, so we can't use that here. const POSITION_UNAVAILABLE = 2; @@ -492,7 +490,7 @@ NetworkGeolocationProvider.prototype = { Services.prefs.getIntPref("geo.provider.network.timeout") ); - let req = await lazy.fetch(url, fetchOpts); + let req = await fetch(url, fetchOpts); lazy.clearTimeout(timeoutId); let result = req.json(); return result; diff --git a/mobile/android/actors/ContentDelegateChild.jsm b/mobile/android/actors/ContentDelegateChild.jsm index af7ab51b8a5c..6616efa35858 100644 --- a/mobile/android/actors/ContentDelegateChild.jsm +++ b/mobile/android/actors/ContentDelegateChild.jsm @@ -14,8 +14,6 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["URL"]); - XPCOMUtils.defineLazyModuleGetters(lazy, { ManifestObtainer: "resource://gre/modules/ManifestObtainer.jsm", }); @@ -83,7 +81,7 @@ class ContentDelegateChild extends GeckoViewActorChild { let elementSrc = (isImage || isMedia) && (node.currentSrc || node.src); if (elementSrc) { const isBlob = elementSrc.startsWith("blob:"); - if (isBlob && !lazy.URL.isValidURL(elementSrc)) { + if (isBlob && !URL.isValidURL(elementSrc)) { elementSrc = null; } } diff --git a/remote/marionette/capture.js b/remote/marionette/capture.js index 3fae5490bc52..ffa9cc457211 100644 --- a/remote/marionette/capture.js +++ b/remote/marionette/capture.js @@ -19,7 +19,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get(lazy.Log.TYPES.MARIONETTE) ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); const CONTEXT_2D = "2d"; const BG_COLOUR = "rgb(255,255,255)"; @@ -185,7 +184,7 @@ capture.toBase64 = function(canvas) { capture.toHash = function(canvas) { let u = capture.toBase64(canvas); let buffer = new TextEncoder("utf-8").encode(u); - return lazy.crypto.subtle.digest("SHA-256", buffer).then(hash => hex(hash)); + return crypto.subtle.digest("SHA-256", buffer).then(hash => hex(hash)); }; /** diff --git a/security/manager/ssl/RemoteSecuritySettings.jsm b/security/manager/ssl/RemoteSecuritySettings.jsm index f1481ca7c719..aaea7178bdad 100644 --- a/security/manager/ssl/RemoteSecuritySettings.jsm +++ b/security/manager/ssl/RemoteSecuritySettings.jsm @@ -31,8 +31,6 @@ const CRLITE_FILTERS_ENABLED_PREF = const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyGetter(lazy, "gTextDecoder", () => new TextDecoder()); XPCOMUtils.defineLazyGetter(lazy, "log", () => { @@ -593,7 +591,7 @@ class CRLiteFilters { try { // If we've already downloaded this, the backend should just grab it from its cache. let localURI = await this.client.attachments.downloadToDisk(filter); - let buffer = await (await lazy.fetch(localURI)).arrayBuffer(); + let buffer = await (await fetch(localURI)).arrayBuffer(); let bytes = new Uint8Array(buffer); lazy.log.debug( `Downloaded ${filter.details.name}: ${bytes.length} bytes` diff --git a/services/automation/ServicesAutomation.jsm b/services/automation/ServicesAutomation.jsm index 4a05536dcd5d..6a0fbdd98507 100644 --- a/services/automation/ServicesAutomation.jsm +++ b/services/automation/ServicesAutomation.jsm @@ -49,8 +49,6 @@ XPCOMUtils.defineLazyGetter(lazy, "fxAccounts", () => { ).getFxAccountsSingleton(); }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const AUTOCONFIG_PREF = "identity.fxaccounts.autoconfig.uri"; /* @@ -207,7 +205,7 @@ var Authentication = { const tries = 10; const normalWait = 4000; for (let i = 0; i < tries; ++i) { - let resp = await lazy.fetch(restmailURI); + let resp = await fetch(restmailURI); let messages = await resp.json(); // Sort so that the most recent emails are first. messages.sort((a, b) => new Date(b.receivedAt) - new Date(a.receivedAt)); diff --git a/services/crypto/modules/WeaveCrypto.js b/services/crypto/modules/WeaveCrypto.js index 03551ea93b29..38956b42e03b 100644 --- a/services/crypto/modules/WeaveCrypto.js +++ b/services/crypto/modules/WeaveCrypto.js @@ -9,10 +9,6 @@ const { XPCOMUtils } = ChromeUtils.import( ); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const CRYPT_ALGO = "AES-CBC"; const CRYPT_ALGO_LENGTH = 256; const CRYPT_ALGO_USAGES = ["encrypt", "decrypt"]; @@ -78,7 +74,7 @@ WeaveCrypto.prototype = { // /!\ Only use this for tests! /!\ _getCrypto() { - return lazy.crypto; + return crypto; }, async encrypt(clearTextUCS2, symmetricKey, iv) { @@ -135,17 +131,12 @@ WeaveCrypto.prototype = { let iv = this.byteCompressInts(ivStr); let symKey = await this.importSymKey(symKeyStr, operation); let cryptMethod = (operation === OPERATIONS.ENCRYPT - ? lazy.crypto.subtle.encrypt - : lazy.crypto.subtle.decrypt - ).bind(lazy.crypto.subtle); + ? crypto.subtle.encrypt + : crypto.subtle.decrypt + ).bind(crypto.subtle); let algo = { name: CRYPT_ALGO, iv }; - let keyBytes = await cryptMethod.call( - lazy.crypto.subtle, - algo, - symKey, - data - ); + let keyBytes = await cryptMethod.call(crypto.subtle, algo, symKey, data); return new Uint8Array(keyBytes); }, @@ -155,12 +146,8 @@ WeaveCrypto.prototype = { name: CRYPT_ALGO, length: CRYPT_ALGO_LENGTH, }; - let key = await lazy.crypto.subtle.generateKey( - algo, - true, - CRYPT_ALGO_USAGES - ); - let keyBytes = await lazy.crypto.subtle.exportKey("raw", key); + let key = await crypto.subtle.generateKey(algo, true, CRYPT_ALGO_USAGES); + let keyBytes = await crypto.subtle.exportKey("raw", key); return this.encodeBase64(new Uint8Array(keyBytes)); }, @@ -172,7 +159,7 @@ WeaveCrypto.prototype = { this.log("generateRandomBytes() called"); let randBytes = new Uint8Array(byteCount); - lazy.crypto.getRandomValues(randBytes); + crypto.getRandomValues(randBytes); return this.encodeBase64(randBytes); }, @@ -208,7 +195,7 @@ WeaveCrypto.prototype = { let symmetricKeyBuffer = this.makeUint8Array(encodedKeyString, true); let algo = { name: CRYPT_ALGO }; let usages = [operation === OPERATIONS.ENCRYPT ? "encrypt" : "decrypt"]; - let symKey = await lazy.crypto.subtle.importKey( + let symKey = await crypto.subtle.importKey( "raw", symmetricKeyBuffer, algo, diff --git a/services/crypto/modules/jwcrypto.jsm b/services/crypto/modules/jwcrypto.jsm index 05da9978bcc6..f95e9509d862 100644 --- a/services/crypto/modules/jwcrypto.jsm +++ b/services/crypto/modules/jwcrypto.jsm @@ -4,14 +4,6 @@ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const EXPORTED_SYMBOLS = ["jwcrypto"]; const ECDH_PARAMS = { @@ -47,13 +39,10 @@ class JWCrypto { async generateJWE(key, data) { // Generate an ephemeral key to use just for this encryption. // The public component gets embedded in the JWE header. - const epk = await lazy.crypto.subtle.generateKey(ECDH_PARAMS, true, [ + const epk = await crypto.subtle.generateKey(ECDH_PARAMS, true, [ "deriveKey", ]); - const ownPublicJWK = await lazy.crypto.subtle.exportKey( - "jwk", - epk.publicKey - ); + const ownPublicJWK = await crypto.subtle.exportKey("jwk", epk.publicKey); // Remove properties added by our WebCrypto implementation but that aren't typically // used with JWE in the wild. This saves space in the resulting JWE, and makes it easier // to re-import the resulting JWK. @@ -61,7 +50,7 @@ class JWCrypto { delete ownPublicJWK.ext; let header = { alg: "ECDH-ES", enc: "A256GCM", epk: ownPublicJWK }; // Import the peer's public key. - const peerPublicKey = await lazy.crypto.subtle.importKey( + const peerPublicKey = await crypto.subtle.importKey( "jwk", key, ECDH_PARAMS, @@ -81,14 +70,14 @@ class JWCrypto { // Note that the IV is generated randomly, which *in general* is not safe to do with AES-GCM because // it's too short to guarantee uniqueness. But we know that the AES-GCM key itself is unique and will // only be used for this single encryption, making a random IV safe to use for this particular use-case. - let iv = lazy.crypto.getRandomValues(new Uint8Array(AES_GCM_IV_SIZE)); + let iv = crypto.getRandomValues(new Uint8Array(AES_GCM_IV_SIZE)); // Yes, additionalData is the byte representation of the base64 representation of the stringified header. const additionalData = UTF8_ENCODER.encode( ChromeUtils.base64URLEncode(UTF8_ENCODER.encode(JSON.stringify(header)), { pad: false, }) ); - const encrypted = await lazy.crypto.subtle.encrypt( + const encrypted = await crypto.subtle.encrypt( { name: "AES-GCM", iv, @@ -143,7 +132,7 @@ class JWCrypto { if ("apu" in header || "apv" in header) { throw new Error("apu and apv header values are not supported."); } - const peerPublicKey = await lazy.crypto.subtle.importKey( + const peerPublicKey = await crypto.subtle.importKey( "jwk", header.epk, ECDH_PARAMS, @@ -163,7 +152,7 @@ class JWCrypto { ); const bundle = new Uint8Array([...ciphertext, ...authTag]); - const decrypted = await lazy.crypto.subtle.decrypt( + const decrypted = await crypto.subtle.decrypt( { name: "AES-GCM", iv, @@ -190,7 +179,7 @@ class JWCrypto { */ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { const params = { ...ECDH_PARAMS, ...{ public: publicKey } }; - const sharedKey = await lazy.crypto.subtle.deriveKey( + const sharedKey = await crypto.subtle.deriveKey( params, privateKey, AES_PARAMS, @@ -200,7 +189,7 @@ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { // This is the NIST Concat KDF specialized to a specific set of parameters, // which basically turn it into a single application of SHA256. // The details are from the JWA RFC. - let sharedKeyBytes = await lazy.crypto.subtle.exportKey("raw", sharedKey); + let sharedKeyBytes = await crypto.subtle.exportKey("raw", sharedKey); sharedKeyBytes = new Uint8Array(sharedKeyBytes); const info = [ "\x00\x00\x00\x07A256GCM", // 7-byte algorithm identifier @@ -215,13 +204,13 @@ async function deriveECDHSharedAESKey(privateKey, publicKey, keyUsages) { const pkcsBuf = Uint8Array.from( Array.prototype.map.call(pkcs, c => c.charCodeAt(0)) ); - const derivedKeyBytes = await lazy.crypto.subtle.digest( + const derivedKeyBytes = await crypto.subtle.digest( { name: "SHA-256", }, pkcsBuf ); - return lazy.crypto.subtle.importKey( + return crypto.subtle.importKey( "raw", derivedKeyBytes, AES_PARAMS, diff --git a/services/crypto/modules/utils.js b/services/crypto/modules/utils.js index 48a82d337b89..47a2cd0dda03 100644 --- a/services/crypto/modules/utils.js +++ b/services/crypto/modules/utils.js @@ -14,7 +14,6 @@ const { XPCOMUtils } = ChromeUtils.import( "resource://gre/modules/XPCOMUtils.jsm" ); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); XPCOMUtils.defineLazyGetter(lazy, "textEncoder", function() { return new TextEncoder(); @@ -52,7 +51,7 @@ var CryptoUtils = { }, generateRandomBytes(length) { - return lazy.crypto.getRandomValues(new Uint8Array(length)); + return crypto.getRandomValues(new Uint8Array(length)); }, /** @@ -149,14 +148,14 @@ var CryptoUtils = { * @returns {Uint8Array} */ async hmac(alg, key, data) { - const hmacKey = await lazy.crypto.subtle.importKey( + const hmacKey = await crypto.subtle.importKey( "raw", key, { name: "HMAC", hash: alg }, false, ["sign"] ); - const result = await lazy.crypto.subtle.sign("HMAC", hmacKey, data); + const result = await crypto.subtle.sign("HMAC", hmacKey, data); return new Uint8Array(result); }, @@ -168,14 +167,14 @@ var CryptoUtils = { * @returns {Uint8Array} */ async hkdf(ikm, salt, info, len) { - const key = await lazy.crypto.subtle.importKey( + const key = await crypto.subtle.importKey( "raw", ikm, { name: "HKDF" }, false, ["deriveBits"] ); - const okm = await lazy.crypto.subtle.deriveBits( + const okm = await crypto.subtle.deriveBits( { name: "HKDF", hash: "SHA-256", @@ -199,14 +198,14 @@ var CryptoUtils = { async pbkdf2Generate(passphrase, salt, iterations, len) { passphrase = CommonUtils.byteStringToArrayBuffer(passphrase); salt = CommonUtils.byteStringToArrayBuffer(salt); - const key = await lazy.crypto.subtle.importKey( + const key = await crypto.subtle.importKey( "raw", passphrase, { name: "PBKDF2" }, false, ["deriveBits"] ); - const output = await lazy.crypto.subtle.deriveBits( + const output = await crypto.subtle.deriveBits( { name: "PBKDF2", hash: "SHA-256", @@ -473,7 +472,7 @@ var CryptoUtils = { const buffer = lazy.textEncoder.encode( `hawk.1.payload\n${contentType}\n${options.payload}\n` ); - const hash = await lazy.crypto.subtle.digest("SHA-256", buffer); + const hash = await crypto.subtle.digest("SHA-256", buffer); // HAWK specifies this .hash to use +/ (not _-) and include the // trailing "==" padding. artifacts.hash = ChromeUtils.base64URLEncode(hash, { pad: true }) diff --git a/services/fxaccounts/FxAccountsProfileClient.jsm b/services/fxaccounts/FxAccountsProfileClient.jsm index caa18497cb0d..c554699ef58b 100644 --- a/services/fxaccounts/FxAccountsProfileClient.jsm +++ b/services/fxaccounts/FxAccountsProfileClient.jsm @@ -32,13 +32,6 @@ const fxAccounts = getFxAccountsSingleton(); const { RESTRequest } = ChromeUtils.import( "resource://services-common/rest.js" ); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["URL"]); /** * Create a new FxAccountsProfileClient to be able to fetch Firefox Account profile information. @@ -59,7 +52,7 @@ var FxAccountsProfileClient = function(options) { this.fxai = options.fxai || fxAccounts._internal; try { - this.serverURL = new lazy.URL(options.serverURL); + this.serverURL = new URL(options.serverURL); } catch (e) { throw new Error("Invalid 'serverURL'"); } diff --git a/services/settings/Attachments.jsm b/services/settings/Attachments.jsm index 21fab90a8856..5ac6249f6774 100644 --- a/services/settings/Attachments.jsm +++ b/services/settings/Attachments.jsm @@ -13,7 +13,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { Utils: "resource://services-settings/Utils.jsm", }); ChromeUtils.defineModuleGetter(lazy, "OS", "resource://gre/modules/osfile.jsm"); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); class DownloadError extends Error { constructor(url, resp) { @@ -469,7 +468,7 @@ class Downloader { async _readAttachmentDump(attachmentId) { async function fetchResource(resourceUrl) { try { - return await lazy.fetch(resourceUrl); + return await fetch(resourceUrl); } catch (e) { throw new Downloader.DownloadError(resourceUrl); } diff --git a/services/settings/Utils.jsm b/services/settings/Utils.jsm index ce2d04ce92b1..21eacc72b586 100644 --- a/services/settings/Utils.jsm +++ b/services/settings/Utils.jsm @@ -34,8 +34,6 @@ XPCOMUtils.defineLazyServiceGetter( "nsINetworkLinkService" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - // Create a new instance of the ConsoleAPI so we can control the maxLogLevel with a pref. // See LOG_LEVELS in Console.jsm. Common examples: "all", "debug", "info", "warn", "error". XPCOMUtils.defineLazyGetter(lazy, "log", () => { @@ -303,7 +301,7 @@ var Utils = { */ async hasLocalDump(bucket, collection) { try { - await lazy.fetch( + await fetch( `resource://app/defaults/settings/${bucket}/${collection}.json`, { method: "HEAD", @@ -327,7 +325,7 @@ var Utils = { if (!this._dumpStatsInitPromise) { this._dumpStatsInitPromise = (async () => { try { - let res = await lazy.fetch( + let res = await fetch( "resource://app/defaults/settings/last_modified.json" ); this._dumpStats = await res.json(); diff --git a/services/settings/remote-settings.js b/services/settings/remote-settings.js index 350714a9ed2f..97aa802d7703 100644 --- a/services/settings/remote-settings.js +++ b/services/settings/remote-settings.js @@ -34,8 +34,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { RemoteSettingsWorker: "resource://services-settings/RemoteSettingsWorker.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const PREF_SETTINGS_BRANCH = "services.settings."; const PREF_SETTINGS_SERVER_BACKOFF = "server.backoff"; const PREF_SETTINGS_LAST_UPDATE = "last_update_seconds"; diff --git a/services/sync/modules/bookmark_validator.js b/services/sync/modules/bookmark_validator.js index 14ce10da993a..0405ee58caa7 100644 --- a/services/sync/modules/bookmark_validator.js +++ b/services/sync/modules/bookmark_validator.js @@ -32,8 +32,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/PlacesSyncUtils.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["URLSearchParams"]); - var EXPORTED_SYMBOLS = ["BookmarkValidator", "BookmarkProblemData"]; const QUERY_PROTOCOL = "place:"; @@ -48,12 +46,12 @@ function areURLsEqual(a, b) { // Tag queries are special because we rewrite them to point to the // local tag folder ID. It's expected that the folders won't match, // but all other params should. - let aParams = new lazy.URLSearchParams(a.slice(QUERY_PROTOCOL.length)); + let aParams = new URLSearchParams(a.slice(QUERY_PROTOCOL.length)); let aType = +aParams.get("type"); if (aType != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) { return false; } - let bParams = new lazy.URLSearchParams(b.slice(QUERY_PROTOCOL.length)); + let bParams = new URLSearchParams(b.slice(QUERY_PROTOCOL.length)); let bType = +bParams.get("type"); if (bType != Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_CONTENTS) { return false; @@ -683,7 +681,7 @@ class BookmarkValidator { ) { return; } - let params = new lazy.URLSearchParams( + let params = new URLSearchParams( entry.bmkUri.slice(QUERY_PROTOCOL.length) ); // Queries with `excludeQueries` won't form cycles because they'll diff --git a/services/sync/modules/resource.js b/services/sync/modules/resource.js index 33659c84a3c5..ae86ce596deb 100644 --- a/services/sync/modules/resource.js +++ b/services/sync/modules/resource.js @@ -18,8 +18,6 @@ const { Utils } = ChromeUtils.import("resource://services-sync/util.js"); const { setTimeout, clearTimeout } = ChromeUtils.import( "resource://gre/modules/Timer.jsm" ); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch", "Headers", "Request"]); /* global AbortController */ /* @@ -104,7 +102,7 @@ Resource.prototype = { * @returns {Headers} */ async _buildHeaders(method) { - const headers = new lazy.Headers(this._headers); + const headers = new Headers(this._headers); if (Resource.SEND_VERSION_INFO) { headers.append("user-agent", Utils.userAgent); @@ -168,7 +166,7 @@ Resource.prototype = { this._log.trace(`${method} Body: ${data}`); init.body = data; } - return new lazy.Request(this.uri.spec, init); + return new Request(this.uri.spec, init); }, /** @@ -179,7 +177,7 @@ Resource.prototype = { async _doRequest(method, data = null) { const controller = new AbortController(); const request = await this._createRequest(method, data, controller.signal); - const responsePromise = lazy.fetch(request); // Rejects on network failure. + const responsePromise = fetch(request); // Rejects on network failure. let didTimeout = false; const timeoutId = setTimeout(() => { didTimeout = true; diff --git a/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm b/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm index 3a9c54be8597..6c761bcc10ec 100644 --- a/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm +++ b/services/sync/tps/extensions/tps/resource/auth/fxaccounts.jsm @@ -21,14 +21,8 @@ const { FxAccountsConfig } = ChromeUtils.import( "resource://gre/modules/FxAccountsConfig.jsm" ); const { Logger } = ChromeUtils.import("resource://tps/logger.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - /** * Helper object for Firefox Accounts authentication */ @@ -98,7 +92,7 @@ var Authentication = { const tries = 10; const normalWait = 2000; for (let i = 0; i < tries; ++i) { - let resp = await lazy.fetch(restmailURI); + let resp = await fetch(restmailURI); let messages = await resp.json(); // Sort so that the most recent emails are first. messages.sort((a, b) => new Date(b.receivedAt) - new Date(a.receivedAt)); @@ -145,7 +139,7 @@ var Authentication = { )}`; try { // Clean up after ourselves. - let deleteResult = await lazy.fetch(restmailURI, { method: "DELETE" }); + let deleteResult = await fetch(restmailURI, { method: "DELETE" }); if (!deleteResult.ok) { Logger.logInfo( `Warning: Got non-success status ${deleteResult.status} when deleting emails` diff --git a/toolkit/components/cleardata/SiteDataTestUtils.jsm b/toolkit/components/cleardata/SiteDataTestUtils.jsm index 81277ac933ce..9741cfc85662 100644 --- a/toolkit/components/cleardata/SiteDataTestUtils.jsm +++ b/toolkit/components/cleardata/SiteDataTestUtils.jsm @@ -23,8 +23,6 @@ XPCOMUtils.defineLazyServiceGetter( "nsIServiceWorkerManager" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["indexedDB"]); - /** * This module assists with tasks around testing functionality that shows * or clears site data. @@ -63,11 +61,7 @@ var SiteDataTestUtils = { let principal = Services.scriptSecurityManager.createContentPrincipalFromOrigin( origin ); - let request = lazy.indexedDB.openForPrincipal( - principal, - "TestDatabase", - 1 - ); + let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1); request.onupgradeneeded = function(e) { let db = e.target.result; db.createObjectStore("TestStore"); @@ -256,11 +250,7 @@ var SiteDataTestUtils = { ); return new Promise(resolve => { let data = true; - let request = lazy.indexedDB.openForPrincipal( - principal, - "TestDatabase", - 1 - ); + let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1); request.onupgradeneeded = function(e) { data = false; }; diff --git a/toolkit/components/extensions/ExtensionCommon.jsm b/toolkit/components/extensions/ExtensionCommon.jsm index 50496643afaa..00c6f7ed48fc 100644 --- a/toolkit/components/extensions/ExtensionCommon.jsm +++ b/toolkit/components/extensions/ExtensionCommon.jsm @@ -25,8 +25,6 @@ const { AppConstants } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyModuleGetters(lazy, { ConsoleAPI: "resource://gre/modules/Console.jsm", PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm", @@ -1394,7 +1392,7 @@ class SchemaAPIManager extends EventEmitter { } async loadModuleJSON(urls) { - let promises = urls.map(url => lazy.fetch(url).then(resp => resp.json())); + let promises = urls.map(url => fetch(url).then(resp => resp.json())); return this.initModuleJSON(await Promise.all(promises)); } diff --git a/toolkit/components/extensions/ExtensionContent.jsm b/toolkit/components/extensions/ExtensionContent.jsm index 10ef689307cf..124dd3fc86ac 100644 --- a/toolkit/components/extensions/ExtensionContent.jsm +++ b/toolkit/components/extensions/ExtensionContent.jsm @@ -48,8 +48,6 @@ const { ExtensionUtils } = ChromeUtils.import( "resource://gre/modules/ExtensionUtils.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const { DefaultMap, DefaultWeakMap, @@ -373,7 +371,7 @@ class Script { } // Store the hash of the cssCode. - const buffer = await lazy.crypto.subtle.digest( + const buffer = await crypto.subtle.digest( "SHA-1", new TextEncoder().encode(cssCode) ); diff --git a/toolkit/components/extensions/ExtensionUtils.jsm b/toolkit/components/extensions/ExtensionUtils.jsm index 47c38a7f4d8f..8eae43d87297 100644 --- a/toolkit/components/extensions/ExtensionUtils.jsm +++ b/toolkit/components/extensions/ExtensionUtils.jsm @@ -20,8 +20,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/Timer.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - // xpcshell doesn't handle idle callbacks well. XPCOMUtils.defineLazyGetter(lazy, "idleTimeout", () => Services.appinfo.name === "XPCShell" ? 500 : undefined @@ -324,7 +322,7 @@ function parseMatchPatterns(patterns, options) { async function makeDataURI(iconUrl) { let response; try { - response = await lazy.fetch(iconUrl); + response = await fetch(iconUrl); } catch (e) { // Failed to fetch, ignore engine's favicon. Cu.reportError(e); diff --git a/toolkit/components/featuregates/FeatureGate.jsm b/toolkit/components/featuregates/FeatureGate.jsm index 5d0204c8d15b..3c8a8b9b927c 100644 --- a/toolkit/components/featuregates/FeatureGate.jsm +++ b/toolkit/components/featuregates/FeatureGate.jsm @@ -17,8 +17,6 @@ ChromeUtils.defineModuleGetter( "resource://featuregates/FeatureGateImplementation.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - var EXPORTED_SYMBOLS = ["FeatureGate"]; XPCOMUtils.defineLazyGetter(lazy, "gFeatureDefinitionsPromise", async () => { @@ -27,7 +25,7 @@ XPCOMUtils.defineLazyGetter(lazy, "gFeatureDefinitionsPromise", async () => { }); async function fetchFeatureDefinitions(url) { - const res = await lazy.fetch(url); + const res = await fetch(url); let definitionsJson = await res.json(); return new Map(Object.entries(definitionsJson)); } diff --git a/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm b/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm index 37434c3afb02..bb47dfefbc35 100644 --- a/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm +++ b/toolkit/components/nimbus/lib/RemoteSettingsExperimentLoader.jsm @@ -16,7 +16,6 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { ASRouterTargeting: "resource://activity-stream/lib/ASRouterTargeting.jsm", TargetingContext: "resource://messaging-system/targeting/Targeting.jsm", @@ -67,10 +66,9 @@ XPCOMUtils.defineLazyPreferenceGetter( const SCHEMAS = { get NimbusExperiment() { - return lazy - .fetch("resource://nimbus/schemas/NimbusExperiment.schema.json", { - credentials: "omit", - }) + return fetch("resource://nimbus/schemas/NimbusExperiment.schema.json", { + credentials: "omit", + }) .then(rsp => rsp.json()) .then(json => json.definitions.NimbusExperiment); }, @@ -375,9 +373,9 @@ class _RemoteSettingsExperimentLoader { } else if (lazy.NimbusFeatures[featureId].manifest.schema?.uri) { const uri = lazy.NimbusFeatures[featureId].manifest.schema.uri; try { - const schema = await lazy - .fetch(uri, { credentials: "omit" }) - .then(rsp => rsp.json()); + const schema = await fetch(uri, { credentials: "omit" }).then(rsp => + rsp.json() + ); validator = validatorCache[ featureId ] = new lazy.JsonSchema.Validator(schema); diff --git a/toolkit/components/normandy/lib/NormandyApi.jsm b/toolkit/components/normandy/lib/NormandyApi.jsm index 226ed050e73b..0ea744683acf 100644 --- a/toolkit/components/normandy/lib/NormandyApi.jsm +++ b/toolkit/components/normandy/lib/NormandyApi.jsm @@ -5,9 +5,6 @@ "use strict"; const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); const lazy = {}; @@ -17,8 +14,6 @@ ChromeUtils.defineModuleGetter( "resource://gre/modules/CanonicalJSON.jsm" ); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - var EXPORTED_SYMBOLS = ["NormandyApi"]; const prefs = Services.prefs.getBranch("app.normandy."); @@ -59,7 +54,7 @@ var NormandyApi = { url.searchParams.set(key, data[key]); } } - return lazy.fetch(url.href, { + return fetch(url.href, { method: "get", headers: { Accept: "application/json" }, credentials: "omit", diff --git a/toolkit/components/passwordmgr/LoginRecipes.jsm b/toolkit/components/passwordmgr/LoginRecipes.jsm index 898925d4b197..bea7be6d65aa 100644 --- a/toolkit/components/passwordmgr/LoginRecipes.jsm +++ b/toolkit/components/passwordmgr/LoginRecipes.jsm @@ -28,8 +28,6 @@ const { XPCOMUtils } = ChromeUtils.import( const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - ChromeUtils.defineModuleGetter( lazy, "LoginHelper", diff --git a/toolkit/components/passwordmgr/PasswordGenerator.jsm b/toolkit/components/passwordmgr/PasswordGenerator.jsm index b08cc5107f0a..b6b4754f303e 100644 --- a/toolkit/components/passwordmgr/PasswordGenerator.jsm +++ b/toolkit/components/passwordmgr/PasswordGenerator.jsm @@ -12,14 +12,6 @@ const EXPORTED_SYMBOLS = ["PasswordGenerator"]; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); - -const lazy = {}; - -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - const DEFAULT_PASSWORD_LENGTH = 15; const MAX_UINT8 = Math.pow(2, 8) - 1; const MAX_UINT32 = Math.pow(2, 32) - 1; @@ -169,7 +161,7 @@ const PasswordGenerator = { const randomValueArr = new Uint8Array(1); do { - lazy.crypto.getRandomValues(randomValueArr); + crypto.getRandomValues(randomValueArr); } while (randomValueArr[0] > MAX_ACCEPTABLE_VALUE); return randomValueArr[0] % range; }, @@ -183,7 +175,7 @@ const PasswordGenerator = { let arr = Array.from(str); // Generate all the random numbers that will be needed. const randomValues = new Uint32Array(arr.length - 1); - lazy.crypto.getRandomValues(randomValues); + crypto.getRandomValues(randomValues); // Fisher-Yates Shuffle // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle diff --git a/toolkit/components/utils/Sampling.jsm b/toolkit/components/utils/Sampling.jsm index 06a75689511b..c27d698dcd99 100644 --- a/toolkit/components/utils/Sampling.jsm +++ b/toolkit/components/utils/Sampling.jsm @@ -4,12 +4,6 @@ "use strict"; -const { XPCOMUtils } = ChromeUtils.import( - "resource://gre/modules/XPCOMUtils.jsm" -); -const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["crypto"]); - var EXPORTED_SYMBOLS = ["Sampling"]; const hashBits = 48; @@ -78,7 +72,7 @@ var Sampling = { * @promise A hash of `data`, truncated to the 12 most significant characters. */ async truncatedHash(data) { - const hasher = lazy.crypto.subtle; + const hasher = crypto.subtle; const input = new TextEncoder("utf-8").encode(JSON.stringify(data)); const hash = await hasher.digest("SHA-256", input); // truncate hash to 12 characters (2^48), because the full hash is larger diff --git a/toolkit/modules/Region.jsm b/toolkit/modules/Region.jsm index 9fbc02fa1dd1..3f0564a9c9b3 100644 --- a/toolkit/modules/Region.jsm +++ b/toolkit/modules/Region.jsm @@ -25,8 +25,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { setTimeout: "resource://gre/modules/Timer.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - XPCOMUtils.defineLazyPreferenceGetter( lazy, "wifiScanningEnabled", @@ -747,10 +745,7 @@ class RegionDetector { async _fetchTimeout(url, opts, timeout) { let controller = new AbortController(); opts.signal = controller.signal; - return Promise.race([ - lazy.fetch(url, opts), - this._timeout(timeout, controller), - ]); + return Promise.race([fetch(url, opts), this._timeout(timeout, controller)]); } /** diff --git a/toolkit/modules/UpdateUtils.jsm b/toolkit/modules/UpdateUtils.jsm index 74522d3f8b09..5257a5dcec0b 100644 --- a/toolkit/modules/UpdateUtils.jsm +++ b/toolkit/modules/UpdateUtils.jsm @@ -22,8 +22,6 @@ XPCOMUtils.defineLazyModuleGetters(lazy, { "resource://gre/modules/components-utils/WindowsVersionInfo.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); - const PER_INSTALLATION_PREFS_PLATFORMS = ["win"]; // The file that stores Application Update configuration settings. The file is @@ -131,7 +129,7 @@ var UpdateUtils = { const url = "resource://" + res + "/" + FILE_UPDATE_LOCALE; let data; try { - data = await lazy.fetch(url); + data = await fetch(url); } catch (e) { continue; } diff --git a/toolkit/mozapps/extensions/internal/XPIInstall.jsm b/toolkit/mozapps/extensions/internal/XPIInstall.jsm index ae9a7a56f6d4..5140c1b4175a 100644 --- a/toolkit/mozapps/extensions/internal/XPIInstall.jsm +++ b/toolkit/mozapps/extensions/internal/XPIInstall.jsm @@ -35,7 +35,6 @@ const { AddonManager, AddonManagerPrivate } = ChromeUtils.import( ); const lazy = {}; -XPCOMUtils.defineLazyGlobalGetters(lazy, ["fetch"]); XPCOMUtils.defineLazyModuleGetters(lazy, { AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", @@ -337,7 +336,7 @@ XPIPackage = class XPIPackage extends Package { } async readBinary(...path) { - let response = await lazy.fetch(this.rootURI.resolve(path.join("/"))); + let response = await fetch(this.rootURI.resolve(path.join("/"))); return response.arrayBuffer(); } @@ -388,7 +387,7 @@ function builtinPackage(baseURL) { }, async hasResource(path) { try { - let response = await lazy.fetch(this.rootURI.resolve(path)); + let response = await fetch(this.rootURI.resolve(path)); return response.ok; } catch (e) { return false; From 29989b4e2597a154eaeaf2e314645a0b06404420 Mon Sep 17 00:00:00 2001 From: Thomas Wisniewski Date: Thu, 16 Jun 2022 00:30:04 +0000 Subject: [PATCH 52/64] Bug 1774420 - fix a copy-paste typo from bz1717806 which enables a SmartBlock shim in inappropriate circumstances; r=webcompat-reviewers,denschub Differential Revision: https://phabricator.services.mozilla.com/D149459 --- browser/extensions/webcompat/data/shims.js | 4 ++-- browser/extensions/webcompat/manifest.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/browser/extensions/webcompat/data/shims.js b/browser/extensions/webcompat/data/shims.js index 49ef0dab512c..ae8e1d6b5569 100644 --- a/browser/extensions/webcompat/data/shims.js +++ b/browser/extensions/webcompat/data/shims.js @@ -165,7 +165,7 @@ const AVAILABLE_SHIMS = [ types: ["image", "imageset", "xmlhttprequest"], }, ], - onlyIfDFPIActive: true, + onlyIfBlockedByETP: true, }, { id: "AdSafeProtectedGoogleIMAAdapter", @@ -545,7 +545,7 @@ const AVAILABLE_SHIMS = [ types: ["image", "imageset", "xmlhttprequest"], }, ], - onlyIfDFPIActive: true, + onlyIfBlockedByETP: true, }, { id: "Vidible", diff --git a/browser/extensions/webcompat/manifest.json b/browser/extensions/webcompat/manifest.json index 2b831db2640e..4f5c3b0ed922 100644 --- a/browser/extensions/webcompat/manifest.json +++ b/browser/extensions/webcompat/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 2, "name": "Web Compatibility Interventions", "description": "Urgent post-release fixes for web compatibility.", - "version": "102.12.0", + "version": "102.13.0", "applications": { "gecko": { "id": "webcompat@mozilla.org", From 977aa3565347719f73818381cd503b5f22710130 Mon Sep 17 00:00:00 2001 From: James Teh Date: Thu, 16 Jun 2022 01:03:26 +0000 Subject: [PATCH 53/64] Bug 1774393: Support BoundsInCSSPixels for cached RemoteAccessible. r=morgan Our hit testing tests need this. This adds a base Accessible::BoundsInCSSPixels implementation which relies on BoundsInAppUnits. BoundsInAppUnits was also moved to Accessible, but it is implemented differently for local and remote, so the base method is abstract. I also did a drive-by removal of a pointless conditional in xpcAccessible::GetBounds. Differential Revision: https://phabricator.services.mozilla.com/D149374 --- accessible/basetypes/Accessible.cpp | 4 ++++ accessible/basetypes/Accessible.h | 10 ++++++++++ accessible/generic/LocalAccessible.cpp | 4 ---- accessible/generic/LocalAccessible.h | 10 +--------- accessible/ipc/RemoteAccessibleBase.cpp | 2 +- accessible/ipc/RemoteAccessibleBase.h | 2 +- accessible/ipc/RemoteAccessibleShared.h | 2 +- accessible/ipc/other/RemoteAccessible.cpp | 6 +++++- accessible/ipc/win/RemoteAccessible.cpp | 6 +++++- accessible/xpcom/xpcAccessible.cpp | 16 ++-------------- 10 files changed, 30 insertions(+), 32 deletions(-) diff --git a/accessible/basetypes/Accessible.cpp b/accessible/basetypes/Accessible.cpp index aa60800483d5..0699553cf3de 100644 --- a/accessible/basetypes/Accessible.cpp +++ b/accessible/basetypes/Accessible.cpp @@ -97,6 +97,10 @@ bool Accessible::HasGenericType(AccGenericType aType) const { (roleMapEntry && roleMapEntry->IsOfType(aType)); } +nsIntRect Accessible::BoundsInCSSPixels() const { + return BoundsInAppUnits().ToNearestPixels(AppUnitsPerCSSPixel()); +} + LayoutDeviceIntSize Accessible::Size() const { return Bounds().Size(); } LayoutDeviceIntPoint Accessible::Position(uint32_t aCoordType) { diff --git a/accessible/basetypes/Accessible.h b/accessible/basetypes/Accessible.h index 9842fec56543..70d9ed743f84 100644 --- a/accessible/basetypes/Accessible.h +++ b/accessible/basetypes/Accessible.h @@ -197,6 +197,16 @@ class Accessible { */ virtual LayoutDeviceIntRect Bounds() const = 0; + /** + * Return boundaries in screen coordinates in app units. + */ + virtual nsRect BoundsInAppUnits() const = 0; + + /** + * Return boundaries in screen coordinates in CSS pixels. + */ + virtual nsIntRect BoundsInCSSPixels() const; + /** * Returns text of accessible if accessible has text role otherwise empty * string. diff --git a/accessible/generic/LocalAccessible.cpp b/accessible/generic/LocalAccessible.cpp index 95f8b7f9f4ce..18a3116d9e25 100644 --- a/accessible/generic/LocalAccessible.cpp +++ b/accessible/generic/LocalAccessible.cpp @@ -789,10 +789,6 @@ LayoutDeviceIntRect LocalAccessible::Bounds() const { BoundsInAppUnits(), mDoc->PresContext()->AppUnitsPerDevPixel()); } -nsIntRect LocalAccessible::BoundsInCSSPixels() const { - return BoundsInAppUnits().ToNearestPixels(AppUnitsPerCSSPixel()); -} - void LocalAccessible::SetSelected(bool aSelect) { if (!HasOwnContent()) return; diff --git a/accessible/generic/LocalAccessible.h b/accessible/generic/LocalAccessible.h index f16f02b4b203..1fbfcd3b72fc 100644 --- a/accessible/generic/LocalAccessible.h +++ b/accessible/generic/LocalAccessible.h @@ -405,18 +405,10 @@ class LocalAccessible : public nsISupports, public Accessible { virtual void AppendTextTo(nsAString& aText, uint32_t aStartOffset = 0, uint32_t aLength = UINT32_MAX) override; - /** - * Return boundaries in screen coordinates in app units. - */ - virtual nsRect BoundsInAppUnits() const; + virtual nsRect BoundsInAppUnits() const override; virtual LayoutDeviceIntRect Bounds() const override; - /** - * Return boundaries in screen coordinates in CSS pixels. - */ - virtual nsIntRect BoundsInCSSPixels() const; - /** * Return boundaries rect relative the bounding frame. */ diff --git a/accessible/ipc/RemoteAccessibleBase.cpp b/accessible/ipc/RemoteAccessibleBase.cpp index 8defd80a082a..d343f5218ef2 100644 --- a/accessible/ipc/RemoteAccessibleBase.cpp +++ b/accessible/ipc/RemoteAccessibleBase.cpp @@ -457,7 +457,7 @@ void RemoteAccessibleBase::ApplyScrollOffset(nsRect& aBounds) const { } template -nsRect RemoteAccessibleBase::GetBoundsInAppUnits() const { +nsRect RemoteAccessibleBase::BoundsInAppUnits() const { dom::CanonicalBrowsingContext* cbc = static_cast(mDoc->Manager()) ->GetBrowsingContext() diff --git a/accessible/ipc/RemoteAccessibleBase.h b/accessible/ipc/RemoteAccessibleBase.h index 56412be95111..269e9b7c59df 100644 --- a/accessible/ipc/RemoteAccessibleBase.h +++ b/accessible/ipc/RemoteAccessibleBase.h @@ -181,7 +181,7 @@ class RemoteAccessibleBase : public Accessible, public HyperTextAccessibleBase { virtual LayoutDeviceIntRect Bounds() const override; - nsRect GetBoundsInAppUnits() const; + virtual nsRect BoundsInAppUnits() const override; virtual uint64_t State() override; diff --git a/accessible/ipc/RemoteAccessibleShared.h b/accessible/ipc/RemoteAccessibleShared.h index f5562ba73016..2bfce2ad593d 100644 --- a/accessible/ipc/RemoteAccessibleShared.h +++ b/accessible/ipc/RemoteAccessibleShared.h @@ -202,7 +202,7 @@ Accessible* ChildAtPoint( int32_t aX, int32_t aY, LocalAccessible::EWhichChildAtPoint aWhichChild) override; LayoutDeviceIntRect Bounds() const override; -nsIntRect BoundsInCSSPixels(); +virtual nsIntRect BoundsInCSSPixels() const override; void Language(nsString& aLocale); void DocType(nsString& aType); diff --git a/accessible/ipc/other/RemoteAccessible.cpp b/accessible/ipc/other/RemoteAccessible.cpp index c34dd6dc7f25..18e747f3b379 100644 --- a/accessible/ipc/other/RemoteAccessible.cpp +++ b/accessible/ipc/other/RemoteAccessible.cpp @@ -989,7 +989,11 @@ LayoutDeviceIntRect RemoteAccessible::Bounds() const { return rect; } -nsIntRect RemoteAccessible::BoundsInCSSPixels() { +nsIntRect RemoteAccessible::BoundsInCSSPixels() const { + if (StaticPrefs::accessibility_cache_enabled_AtStartup()) { + return RemoteAccessibleBase::BoundsInCSSPixels(); + } + nsIntRect rect; Unused << mDoc->SendExtentsInCSSPixels(mID, &rect.x, &rect.y, &rect.width, &rect.height); diff --git a/accessible/ipc/win/RemoteAccessible.cpp b/accessible/ipc/win/RemoteAccessible.cpp index f1fec834ac86..e1d1134b1a8f 100644 --- a/accessible/ipc/win/RemoteAccessible.cpp +++ b/accessible/ipc/win/RemoteAccessible.cpp @@ -252,7 +252,11 @@ LayoutDeviceIntRect RemoteAccessible::Bounds() const { return rect; } -nsIntRect RemoteAccessible::BoundsInCSSPixels() { +nsIntRect RemoteAccessible::BoundsInCSSPixels() const { + if (StaticPrefs::accessibility_cache_enabled_AtStartup()) { + return RemoteAccessibleBase::BoundsInCSSPixels(); + } + RefPtr custom = QueryInterface(this); if (!custom) { return nsIntRect(); diff --git a/accessible/xpcom/xpcAccessible.cpp b/accessible/xpcom/xpcAccessible.cpp index 574463f88ca6..ccd28a72e55f 100644 --- a/accessible/xpcom/xpcAccessible.cpp +++ b/accessible/xpcom/xpcAccessible.cpp @@ -435,13 +435,7 @@ xpcAccessible::GetBounds(int32_t* aX, int32_t* aY, int32_t* aWidth, if (!IntlGeneric()) return NS_ERROR_FAILURE; - LayoutDeviceIntRect rect; - if (LocalAccessible* acc = IntlGeneric()->AsLocal()) { - rect = acc->Bounds(); - } else { - rect = IntlGeneric()->AsRemote()->Bounds(); - } - + LayoutDeviceIntRect rect = IntlGeneric()->Bounds(); rect.GetRect(aX, aY, aWidth, aHeight); return NS_OK; } @@ -462,13 +456,7 @@ xpcAccessible::GetBoundsInCSSPixels(int32_t* aX, int32_t* aY, int32_t* aWidth, return NS_ERROR_FAILURE; } - nsIntRect rect; - if (LocalAccessible* acc = IntlGeneric()->AsLocal()) { - rect = acc->BoundsInCSSPixels(); - } else { - rect = IntlGeneric()->AsRemote()->BoundsInCSSPixels(); - } - + nsIntRect rect = IntlGeneric()->BoundsInCSSPixels(); rect.GetRect(aX, aY, aWidth, aHeight); return NS_OK; } From ffb927c32acbf20c900b9213aa0ec3ed3a13a159 Mon Sep 17 00:00:00 2001 From: Mark Hammond Date: Thu, 16 Jun 2022 01:41:19 +0000 Subject: [PATCH 54/64] Bug 1773609 - fix many lint warnings in services/ r=skhamis Differential Revision: https://phabricator.services.mozilla.com/D148883 --- services/automation/ServicesAutomation.jsm | 4 +- .../common/tests/unit/test_async_foreach.js | 1 - .../common/tests/unit/test_hawkrequest.js | 2 + services/common/tests/unit/test_kinto.js | 6 -- .../common/tests/unit/test_restrequest.js | 1 - .../crypto/tests/unit/test_crypto_crypt.js | 1 - services/crypto/tests/unit/test_jwcrypto.js | 4 - services/fxaccounts/FxAccounts.jsm | 4 +- services/fxaccounts/FxAccountsCommon.js | 4 +- .../tests/xpcshell/test_accounts.js | 3 - .../test_accounts_device_registration.js | 11 --- .../tests/xpcshell/test_credentials.js | 7 +- .../fxaccounts/tests/xpcshell/test_keys.js | 3 - .../fxaccounts/tests/xpcshell/test_pairing.js | 8 +- .../tests/xpcshell/test_push_service.js | 4 +- .../tests/xpcshell/test_telemetry.js | 23 ------ .../unit/test_remote_settings_signatures.js | 1 - services/sync/modules/engines/addons.js | 2 +- services/sync/tests/unit/test_addons_store.js | 2 - .../sync/tests/unit/test_addons_tracker.js | 5 +- .../tests/unit/test_bookmark_batch_fail.js | 5 +- .../sync/tests/unit/test_bookmark_engine.js | 3 - .../sync/tests/unit/test_bookmark_order.js | 2 +- .../test_bookmark_places_query_rewriting.js | 2 + .../sync/tests/unit/test_bookmark_store.js | 8 +- .../sync/tests/unit/test_bookmark_tracker.js | 76 +------------------ .../sync/tests/unit/test_errorhandler_2.js | 1 - .../tests/unit/test_errorhandler_filelog.js | 2 + .../unit/test_extension_storage_engine.js | 1 - services/sync/tests/unit/test_resource.js | 3 - services/sync/tests/unit/test_resource_ua.js | 1 - .../sync/tests/unit/test_sync_auth_manager.js | 8 -- services/sync/tests/unit/test_syncedtabs.js | 4 - 33 files changed, 25 insertions(+), 187 deletions(-) diff --git a/services/automation/ServicesAutomation.jsm b/services/automation/ServicesAutomation.jsm index 6a0fbdd98507..0163e8919dc1 100644 --- a/services/automation/ServicesAutomation.jsm +++ b/services/automation/ServicesAutomation.jsm @@ -194,7 +194,7 @@ var Authentication = { /* * This whole verification process may be bypassed if the - * account is whitelisted. + * account is allow-listed. */ async _completeVerification(username) { LOG("Fetching mail (from restmail) for user " + username); @@ -258,7 +258,7 @@ var Authentication = { LOG("Signed in, setting up the signed user in fxAccounts"); await lazy.fxAccounts._internal.setSignedInUser(credentials); - // If the account is not whitelisted for tests, we need to verify it + // If the account is not allow-listed for tests, we need to verify it if (!credentials.verified) { LOG("We need to verify the account"); await this._completeVerification(username); diff --git a/services/common/tests/unit/test_async_foreach.js b/services/common/tests/unit/test_async_foreach.js index 65412eccbb68..8388d756493f 100644 --- a/services/common/tests/unit/test_async_foreach.js +++ b/services/common/tests/unit/test_async_foreach.js @@ -2,7 +2,6 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ const { Async } = ChromeUtils.import("resource://services-common/async.js"); -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { sinon } = ChromeUtils.import("resource://testing-common/Sinon.jsm"); function makeArray(length) { diff --git a/services/common/tests/unit/test_hawkrequest.js b/services/common/tests/unit/test_hawkrequest.js index 9f8f018d79f9..aebed6d8d552 100644 --- a/services/common/tests/unit/test_hawkrequest.js +++ b/services/common/tests/unit/test_hawkrequest.js @@ -38,6 +38,8 @@ function do_register_cleanup() { } function run_test() { + registerCleanupFunction(do_register_cleanup); + Services.prefs.setStringPref( "services.common.log.logger.rest.request", "Trace" diff --git a/services/common/tests/unit/test_kinto.js b/services/common/tests/unit/test_kinto.js index 8bd9add5bc60..e9d216814c27 100644 --- a/services/common/tests/unit/test_kinto.js +++ b/services/common/tests/unit/test_kinto.js @@ -8,12 +8,6 @@ const { FirefoxAdapter } = ChromeUtils.import( "resource://services-common/kinto-storage-adapter.js" ); -const BinaryInputStream = Components.Constructor( - "@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream" -); - var server; // set up what we need to make storage adapters diff --git a/services/common/tests/unit/test_restrequest.js b/services/common/tests/unit/test_restrequest.js index 94ea1a51d38e..72eecf27459a 100644 --- a/services/common/tests/unit/test_restrequest.js +++ b/services/common/tests/unit/test_restrequest.js @@ -3,7 +3,6 @@ "use strict"; -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { RESTRequest } = ChromeUtils.import( "resource://services-common/rest.js" ); diff --git a/services/crypto/tests/unit/test_crypto_crypt.js b/services/crypto/tests/unit/test_crypto_crypt.js index b79f2d8daa74..34077dee5796 100644 --- a/services/crypto/tests/unit/test_crypto_crypt.js +++ b/services/crypto/tests/unit/test_crypto_crypt.js @@ -1,7 +1,6 @@ const { WeaveCrypto } = ChromeUtils.import( "resource://services-crypto/WeaveCrypto.js" ); -Cu.importGlobalProperties(["crypto"]); var cryptoSvc = new WeaveCrypto(); diff --git a/services/crypto/tests/unit/test_jwcrypto.js b/services/crypto/tests/unit/test_jwcrypto.js index 6d083d88bbca..45722b86eb43 100644 --- a/services/crypto/tests/unit/test_jwcrypto.js +++ b/services/crypto/tests/unit/test_jwcrypto.js @@ -13,10 +13,6 @@ ChromeUtils.defineModuleGetter( Cu.importGlobalProperties(["crypto"]); -const SECOND_MS = 1000; -const MINUTE_MS = SECOND_MS * 60; -const HOUR_MS = MINUTE_MS * 60; - // Enable logging from jwcrypto.jsm. Services.prefs.setCharPref("services.crypto.jwcrypto.log.level", "Debug"); diff --git a/services/fxaccounts/FxAccounts.jsm b/services/fxaccounts/FxAccounts.jsm index c208eceea41d..2e24f66f3f76 100644 --- a/services/fxaccounts/FxAccounts.jsm +++ b/services/fxaccounts/FxAccounts.jsm @@ -28,7 +28,7 @@ const { ERROR_UNKNOWN, ERROR_UNVERIFIED_ACCOUNT, FXA_PWDMGR_PLAINTEXT_FIELDS, - FXA_PWDMGR_REAUTH_WHITELIST, + FXA_PWDMGR_REAUTH_ALLOWLIST, FXA_PWDMGR_SECURE_FIELDS, FX_OAUTH_CLIENT_ID, ON_ACCOUNT_STATE_CHANGE_NOTIFICATION, @@ -1554,7 +1554,7 @@ FxAccountsInternal.prototype = { // reauthenticate. let updateData = {}; let clearField = field => { - if (!FXA_PWDMGR_REAUTH_WHITELIST.has(field)) { + if (!FXA_PWDMGR_REAUTH_ALLOWLIST.has(field)) { updateData[field] = null; } }; diff --git a/services/fxaccounts/FxAccountsCommon.js b/services/fxaccounts/FxAccountsCommon.js index 7985fd7d8e2c..643389a9b34e 100644 --- a/services/fxaccounts/FxAccountsCommon.js +++ b/services/fxaccounts/FxAccountsCommon.js @@ -302,9 +302,9 @@ exports.FXA_PWDMGR_SECURE_FIELDS = new Set([ "scopedKeys", ]); -// A whitelist of fields that remain in storage when the user needs to +// An allowlist of fields that remain in storage when the user needs to // reauthenticate. All other fields will be removed. -exports.FXA_PWDMGR_REAUTH_WHITELIST = new Set([ +exports.FXA_PWDMGR_REAUTH_ALLOWLIST = new Set([ "email", "uid", "profile", diff --git a/services/fxaccounts/tests/xpcshell/test_accounts.js b/services/fxaccounts/tests/xpcshell/test_accounts.js index 7034ed0d1503..e0d71ae8a2a4 100644 --- a/services/fxaccounts/tests/xpcshell/test_accounts.js +++ b/services/fxaccounts/tests/xpcshell/test_accounts.js @@ -14,7 +14,6 @@ const { FxAccountsClient } = ChromeUtils.import( ); const { ERRNO_INVALID_AUTH_TOKEN, - ERROR_NETWORK, ERROR_NO_ACCOUNT, FX_OAUTH_CLIENT_ID, ONLOGIN_NOTIFICATION, @@ -32,8 +31,6 @@ var { AccountState } = ChromeUtils.import( "resource://gre/modules/FxAccounts.jsm" ); -const ONE_HOUR_MS = 1000 * 60 * 60; -const ONE_DAY_MS = ONE_HOUR_MS * 24; const MOCK_TOKEN_RESPONSE = { access_token: "43793fdfffec22eb39fc3c44ed09193a6fde4c24e5d6a73f73178597b268af69", diff --git a/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js b/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js index 666ab220b1ae..5c603c09f7b2 100644 --- a/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js +++ b/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js @@ -960,17 +960,6 @@ add_task(async function test_checking_remote_availableCommands_match() { ); }); -function expandHex(two_hex) { - // Return a 64-character hex string, encoding 32 identical bytes. - let eight_hex = two_hex + two_hex + two_hex + two_hex; - let thirtytwo_hex = eight_hex + eight_hex + eight_hex + eight_hex; - return thirtytwo_hex + thirtytwo_hex; -} - -function expandBytes(two_hex) { - return CommonUtils.hexToBytes(expandHex(two_hex)); -} - function getTestUser(name) { return { email: name + "@example.com", diff --git a/services/fxaccounts/tests/xpcshell/test_credentials.js b/services/fxaccounts/tests/xpcshell/test_credentials.js index 381510c3c2d3..d41ef4ab42be 100644 --- a/services/fxaccounts/tests/xpcshell/test_credentials.js +++ b/services/fxaccounts/tests/xpcshell/test_credentials.js @@ -8,12 +8,7 @@ const { CryptoUtils } = ChromeUtils.import( "resource://services-crypto/utils.js" ); -var { - hexToBytes: h2b, - hexAsString: h2s, - stringAsHex: s2h, - bytesAsHex: b2h, -} = CommonUtils; +var { hexToBytes: h2b, hexAsString: h2s, bytesAsHex: b2h } = CommonUtils; // Test vectors for the "onepw" protocol: // https://github.com/mozilla/fxa-auth-server/wiki/onepw-protocol#wiki-test-vectors diff --git a/services/fxaccounts/tests/xpcshell/test_keys.js b/services/fxaccounts/tests/xpcshell/test_keys.js index 73cc65db8918..3af0dfa61717 100644 --- a/services/fxaccounts/tests/xpcshell/test_keys.js +++ b/services/fxaccounts/tests/xpcshell/test_keys.js @@ -3,9 +3,6 @@ "use strict"; -const { FX_OAUTH_CLIENT_ID } = ChromeUtils.import( - "resource://gre/modules/FxAccountsCommon.js" -); const { FxAccountsKeys } = ChromeUtils.import( "resource://gre/modules/FxAccountsKeys.jsm" ); diff --git a/services/fxaccounts/tests/xpcshell/test_pairing.js b/services/fxaccounts/tests/xpcshell/test_pairing.js index 3964d7d9bbfb..231bfe774aa2 100644 --- a/services/fxaccounts/tests/xpcshell/test_pairing.js +++ b/services/fxaccounts/tests/xpcshell/test_pairing.js @@ -9,16 +9,10 @@ const { FxAccountsPairingFlow } = ChromeUtils.import( const { EventEmitter } = ChromeUtils.import( "resource://gre/modules/EventEmitter.jsm" ); -const { PromiseUtils } = ChromeUtils.import( - "resource://gre/modules/PromiseUtils.jsm" -); -const { CryptoUtils } = ChromeUtils.import( - "resource://services-crypto/utils.js" -); XPCOMUtils.defineLazyModuleGetters(this, { jwcrypto: "resource://services-crypto/jwcrypto.jsm", }); -XPCOMUtils.defineLazyGlobalGetters(this, ["URL", "crypto"]); +XPCOMUtils.defineLazyGlobalGetters(this, ["crypto"]); const CHANNEL_ID = "sW-UA97Q6Dljqen7XRlYPw"; const CHANNEL_KEY = crypto.getRandomValues(new Uint8Array(32)); diff --git a/services/fxaccounts/tests/xpcshell/test_push_service.js b/services/fxaccounts/tests/xpcshell/test_push_service.js index 4fdea30054e1..3748d93511e9 100644 --- a/services/fxaccounts/tests/xpcshell/test_push_service.js +++ b/services/fxaccounts/tests/xpcshell/test_push_service.js @@ -43,8 +43,8 @@ const MOCK_ENDPOINT = "http://mochi.test:8888"; // tests do not allow external connections, mock the PushService let mockPushService = { - pushTopic: this.pushService.pushTopic, - subscriptionChangeTopic: this.pushService.subscriptionChangeTopic, + pushTopic: pushService.pushTopic, + subscriptionChangeTopic: pushService.subscriptionChangeTopic, subscribe(scope, principal, cb) { cb(Cr.NS_OK, { endpoint: MOCK_ENDPOINT, diff --git a/services/fxaccounts/tests/xpcshell/test_telemetry.js b/services/fxaccounts/tests/xpcshell/test_telemetry.js index deb82110fa13..6ecd0fad1196 100644 --- a/services/fxaccounts/tests/xpcshell/test_telemetry.js +++ b/services/fxaccounts/tests/xpcshell/test_telemetry.js @@ -8,29 +8,6 @@ const { getFxAccountsSingleton } = ChromeUtils.import( ); const fxAccounts = getFxAccountsSingleton(); -const { PREF_ACCOUNT_ROOT } = ChromeUtils.import( - "resource://gre/modules/FxAccountsCommon.js" -); - -const { FxAccountsProfile } = ChromeUtils.import( - "resource://gre/modules/FxAccountsProfile.jsm" -); - -const { FxAccountsProfileClient } = ChromeUtils.import( - "resource://gre/modules/FxAccountsProfileClient.jsm" -); - -const { FxAccountsTelemetry } = ChromeUtils.import( - "resource://gre/modules/FxAccountsTelemetry.jsm" -); - -XPCOMUtils.defineLazyModuleGetters(this, { - FxAccountsConfig: "resource://gre/modules/FxAccountsConfig.jsm", - jwcrypto: "resource://services-crypto/jwcrypto.jsm", - CryptoUtils: "resource://services-crypto/utils.js", - PromiseUtils: "resource://gre/modules/PromiseUtils.jsm", -}); - _("Misc tests for FxAccounts.telemetry"); const MOCK_HASHED_UID = "00112233445566778899aabbccddeeff"; diff --git a/services/settings/test/unit/test_remote_settings_signatures.js b/services/settings/test/unit/test_remote_settings_signatures.js index 5d920ccb41ba..eb74ff8b04e4 100644 --- a/services/settings/test/unit/test_remote_settings_signatures.js +++ b/services/settings/test/unit/test_remote_settings_signatures.js @@ -17,7 +17,6 @@ const { TelemetryTestUtils } = ChromeUtils.import( ); const PREF_SETTINGS_SERVER = "services.settings.server"; -const PREF_SIGNATURE_ROOT = "security.content.signature.root_hash"; const SIGNER_NAME = "onecrl.content-signature.mozilla.org"; const TELEMETRY_COMPONENT = "remotesettings"; diff --git a/services/sync/modules/engines/addons.js b/services/sync/modules/engines/addons.js index 28bf5c667f6d..71f0b5410164 100644 --- a/services/sync/modules/engines/addons.js +++ b/services/sync/modules/engines/addons.js @@ -606,7 +606,7 @@ AddonsStore.prototype = { if (!this._syncableTypes.includes(addon.type)) { this._log.debug( - addon.id + " not syncable: type not in whitelist: " + addon.type + addon.id + " not syncable: type not in allowed list: " + addon.type ); return false; } diff --git a/services/sync/tests/unit/test_addons_store.js b/services/sync/tests/unit/test_addons_store.js index 69647d9f3156..8c9ee9e02f09 100644 --- a/services/sync/tests/unit/test_addons_store.js +++ b/services/sync/tests/unit/test_addons_store.js @@ -144,7 +144,6 @@ for (let [name, files] of Object.entries(ADDONS)) { } let engine; -let tracker; let store; let reconciler; @@ -242,7 +241,6 @@ async function checkReconcilerUpToDate(addon) { add_task(async function setup() { await Service.engineManager.register(AddonsEngine); engine = Service.engineManager.get("addons"); - tracker = engine._tracker; store = engine._store; reconciler = engine._reconciler; diff --git a/services/sync/tests/unit/test_addons_tracker.js b/services/sync/tests/unit/test_addons_tracker.js index 0ff5e4fb6472..7c1ba811db34 100644 --- a/services/sync/tests/unit/test_addons_tracker.js +++ b/services/sync/tests/unit/test_addons_tracker.js @@ -23,9 +23,7 @@ Services.prefs.setBoolPref("extensions.experiments.enabled", true); Svc.Prefs.set("engine.addons", true); -let engine; let reconciler; -let store; let tracker; const addon1ID = "addon1@tests.mozilla.org"; @@ -57,9 +55,8 @@ add_task(async function setup() { XPIS[name] = AddonTestUtils.createTempWebExtensionFile(data); } await Service.engineManager.register(AddonsEngine); - engine = Service.engineManager.get("addons"); + let engine = Service.engineManager.get("addons"); reconciler = engine._reconciler; - store = engine._store; tracker = engine._tracker; await cleanup(); diff --git a/services/sync/tests/unit/test_bookmark_batch_fail.js b/services/sync/tests/unit/test_bookmark_batch_fail.js index 4d5d552d3e47..d214e3202884 100644 --- a/services/sync/tests/unit/test_bookmark_batch_fail.js +++ b/services/sync/tests/unit/test_bookmark_batch_fail.js @@ -2,9 +2,8 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ _("Making sure a failing sync reports a useful error"); -const { BookmarksEngine } = ChromeUtils.import( - "resource://services-sync/engines/bookmarks.js" -); +// `Service` is used as a global in head_helpers.js. +// eslint-disable-next-line no-unused-vars const { Service } = ChromeUtils.import("resource://services-sync/service.js"); add_bookmark_test(async function run_test(engine) { diff --git a/services/sync/tests/unit/test_bookmark_engine.js b/services/sync/tests/unit/test_bookmark_engine.js index 5e6d40908caa..303ce5279fc7 100644 --- a/services/sync/tests/unit/test_bookmark_engine.js +++ b/services/sync/tests/unit/test_bookmark_engine.js @@ -7,9 +7,6 @@ const { BookmarkHTMLUtils } = ChromeUtils.import( const { BookmarkJSONUtils } = ChromeUtils.import( "resource://gre/modules/BookmarkJSONUtils.jsm" ); -const { SyncedBookmarksMirror } = ChromeUtils.import( - "resource://gre/modules/SyncedBookmarksMirror.jsm" -); const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm"); const { Bookmark, diff --git a/services/sync/tests/unit/test_bookmark_order.js b/services/sync/tests/unit/test_bookmark_order.js index 8523f274777a..1f5455356e89 100644 --- a/services/sync/tests/unit/test_bookmark_order.js +++ b/services/sync/tests/unit/test_bookmark_order.js @@ -4,7 +4,7 @@ _( "Making sure after processing incoming bookmarks, they show up in the right order" ); -const { Bookmark, BookmarkFolder, BookmarksEngine } = ChromeUtils.import( +const { Bookmark, BookmarkFolder } = ChromeUtils.import( "resource://services-sync/engines/bookmarks.js" ); const { Weave } = ChromeUtils.import("resource://services-sync/main.js"); diff --git a/services/sync/tests/unit/test_bookmark_places_query_rewriting.js b/services/sync/tests/unit/test_bookmark_places_query_rewriting.js index 7bec58389ec3..c04925fb62cf 100644 --- a/services/sync/tests/unit/test_bookmark_places_query_rewriting.js +++ b/services/sync/tests/unit/test_bookmark_places_query_rewriting.js @@ -5,6 +5,8 @@ _("Rewrite place: URIs."); const { BookmarkQuery, BookmarkFolder } = ChromeUtils.import( "resource://services-sync/engines/bookmarks.js" ); +// `Service` is used as a global in head_helpers.js. +// eslint-disable-next-line no-unused-vars const { Service } = ChromeUtils.import("resource://services-sync/service.js"); function makeTagRecord(id, uri) { diff --git a/services/sync/tests/unit/test_bookmark_store.js b/services/sync/tests/unit/test_bookmark_store.js index afcb9252ee8d..90d0a817257a 100644 --- a/services/sync/tests/unit/test_bookmark_store.js +++ b/services/sync/tests/unit/test_bookmark_store.js @@ -5,9 +5,10 @@ const { Bookmark, BookmarkFolder, BookmarkQuery, - BookmarksEngine, PlacesItem, } = ChromeUtils.import("resource://services-sync/engines/bookmarks.js"); +// `Service` is used as a global in head_helpers.js. +// eslint-disable-next-line no-unused-vars const { Service } = ChromeUtils.import("resource://services-sync/service.js"); const BookmarksToolbarTitle = "toolbar"; @@ -394,11 +395,6 @@ add_bookmark_test(async function test_empty_query_doesnt_die(engine) { await apply_records(engine, [record]); }); -async function assertDeleted(guid) { - let item = await PlacesUtils.bookmarks.fetch(guid); - ok(!item); -} - add_bookmark_test(async function test_calculateIndex_for_invalid_url(engine) { let store = engine._store; diff --git a/services/sync/tests/unit/test_bookmark_tracker.js b/services/sync/tests/unit/test_bookmark_tracker.js index 2b0e76b07201..3f13ae9078db 100644 --- a/services/sync/tests/unit/test_bookmark_tracker.js +++ b/services/sync/tests/unit/test_bookmark_tracker.js @@ -32,36 +32,6 @@ async function resetTracker() { tracker.resetScore(); } -// We have some tests that uses Places "batch mode", which isn't async aware, -// so a couple of these tests spin an event loop waiting for a promise. -function promiseSpinningly(promise) { - let resolved = false; - let rv, rerror; - promise - .then( - result => { - rv = result; - }, - err => { - rerror = err || new Error("Promise rejected without explicit error"); - } - ) - .finally(() => { - resolved = true; - }); - let tm = Cc["@mozilla.org/thread-manager;1"].getService(); - - // Keep waiting until the promise resolves. - tm.spinEventLoopUntil( - "Test(test_bookmark_tracker.js:promiseSpinningly)", - () => resolved - ); - if (rerror) { - throw rerror; - } - return rv; -} - async function cleanup() { await engine.setLastSync(0); await store.wipe(); @@ -100,6 +70,8 @@ async function verifyTrackedCount(expected) { } // A debugging helper that dumps the full bookmarks tree. +// Currently unused, but might come in handy +// eslint-disable-next-line no-unused-vars async function dumpBookmarks() { let columns = [ "id", @@ -130,50 +102,6 @@ async function dumpBookmarks() { }); } -async function insertBookmarksToMigrate() { - await PlacesUtils.bookmarks.insert({ - guid: "0gtWTOgYcoJD", - parentGuid: PlacesUtils.bookmarks.menuGuid, - url: "https://mozilla.org", - }); - let fxBmk = await PlacesUtils.bookmarks.insert({ - guid: "0dbpnMdxKxfg", - parentGuid: PlacesUtils.bookmarks.menuGuid, - url: "http://getfirefox.com", - }); - let tbBmk = await PlacesUtils.bookmarks.insert({ - guid: "r5ouWdPB3l28", - parentGuid: PlacesUtils.bookmarks.menuGuid, - url: "http://getthunderbird.com", - }); - await PlacesUtils.bookmarks.insert({ - guid: "YK5Bdq5MIqL6", - parentGuid: PlacesUtils.bookmarks.menuGuid, - url: "https://bugzilla.mozilla.org", - }); - let exampleBmk = await PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - url: "https://example.com", - }); - - await PlacesTestUtils.setBookmarkSyncFields( - { - guid: fxBmk.guid, - syncStatus: PlacesUtils.bookmarks.SYNC_STATUS.NORMAL, - }, - { - guid: tbBmk.guid, - syncStatus: PlacesUtils.bookmarks.SYNC_STATUS.UNKNOWN, - }, - { - guid: exampleBmk.guid, - syncStatus: PlacesUtils.bookmarks.SYNC_STATUS.NORMAL, - } - ); - - await PlacesUtils.bookmarks.remove(exampleBmk.guid); -} - add_task(async function test_tracking() { _("Test starting and stopping the tracker"); diff --git a/services/sync/tests/unit/test_errorhandler_2.js b/services/sync/tests/unit/test_errorhandler_2.js index 7879b6c172d8..8462f84c8392 100644 --- a/services/sync/tests/unit/test_errorhandler_2.js +++ b/services/sync/tests/unit/test_errorhandler_2.js @@ -9,7 +9,6 @@ const { FileUtils } = ChromeUtils.import( const fakeServer = new SyncServer(); fakeServer.start(); -const fakeServerUrl = "http://localhost:" + fakeServer.port; registerCleanupFunction(function() { return promiseStopServer(fakeServer).finally(() => { diff --git a/services/sync/tests/unit/test_errorhandler_filelog.js b/services/sync/tests/unit/test_errorhandler_filelog.js index f85ec323f7f0..7edbecff3c6b 100644 --- a/services/sync/tests/unit/test_errorhandler_filelog.js +++ b/services/sync/tests/unit/test_errorhandler_filelog.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +// `Service` is used as a global in head_helpers.js. +// eslint-disable-next-line no-unused-vars const { Service } = ChromeUtils.import("resource://services-sync/service.js"); const { logManager } = ChromeUtils.import( "resource://gre/modules/FxAccountsCommon.js" diff --git a/services/sync/tests/unit/test_extension_storage_engine.js b/services/sync/tests/unit/test_extension_storage_engine.js index 37bc934ac093..c032486e37b3 100644 --- a/services/sync/tests/unit/test_extension_storage_engine.js +++ b/services/sync/tests/unit/test_extension_storage_engine.js @@ -4,7 +4,6 @@ "use strict"; XPCOMUtils.defineLazyModuleGetters(this, { - BridgedRecord: "resource://services-sync/bridged_engine.js", extensionStorageSync: "resource://gre/modules/ExtensionStorageSync.jsm", Service: "resource://services-sync/service.js", }); diff --git a/services/sync/tests/unit/test_resource.js b/services/sync/tests/unit/test_resource.js index 0d6e11baa65c..ccb8f6439e9a 100644 --- a/services/sync/tests/unit/test_resource.js +++ b/services/sync/tests/unit/test_resource.js @@ -9,8 +9,6 @@ const { SyncAuthManager } = ChromeUtils.import( "resource://services-sync/sync_auth.js" ); -var logger; - var fetched = false; function server_open(metadata, response) { let body; @@ -169,7 +167,6 @@ Observers.add("weave:service:quota:remaining", function(subject) { }); function run_test() { - logger = Log.repository.getLogger("Test"); Log.repository.rootLogger.addAppender(new Log.DumpAppender()); Svc.Prefs.set("network.numRetries", 1); // speed up test diff --git a/services/sync/tests/unit/test_resource_ua.js b/services/sync/tests/unit/test_resource_ua.js index 7c8ee0b23c36..bf4a334ada77 100644 --- a/services/sync/tests/unit/test_resource_ua.js +++ b/services/sync/tests/unit/test_resource_ua.js @@ -10,7 +10,6 @@ var httpProtocolHandler = Cc[ // Tracking info/collections. var collectionsHelper = track_collections_helper(); -var collections = collectionsHelper.collections; var meta_global; var server; diff --git a/services/sync/tests/unit/test_sync_auth_manager.js b/services/sync/tests/unit/test_sync_auth_manager.js index a5fd766915e1..85a861fc9acc 100644 --- a/services/sync/tests/unit/test_sync_auth_manager.js +++ b/services/sync/tests/unit/test_sync_auth_manager.js @@ -32,14 +32,6 @@ const SECOND_MS = 1000; const MINUTE_MS = SECOND_MS * 60; const HOUR_MS = MINUTE_MS * 60; -const MOCK_SCOPED_KEY = { - k: - "3TVYx0exDTbrc5SGMkNg_C_eoNfjV0elHClP7npHrAtrlJu-esNyTUQaR6UcJBVYilPr8-T4BqWlIp4TOpKavA", - kid: "1569964308879-5y6waestOxDDM-Ia4_2u1Q", - kty: "oct", - scope: "https://identity.mozilla.com/apps/oldsync", -}; - const MOCK_ACCESS_TOKEN = "e3c5caf17f27a0d9e351926a928938b3737df43e91d4992a5a5fca9a7bdef8ba"; diff --git a/services/sync/tests/unit/test_syncedtabs.js b/services/sync/tests/unit/test_syncedtabs.js index a148a02ed4d6..9caaff39c160 100644 --- a/services/sync/tests/unit/test_syncedtabs.js +++ b/services/sync/tests/unit/test_syncedtabs.js @@ -8,10 +8,6 @@ const { SyncedTabs } = ChromeUtils.import( "resource://services-sync/SyncedTabs.jsm" ); -const faviconService = Cc["@mozilla.org/browser/favicon-service;1"].getService( - Ci.nsIFaviconService -); - Log.repository.getLogger("Sync.RemoteTabs").addAppender(new Log.DumpAppender()); // A mock "Tabs" engine which the SyncedTabs module will use instead of the real From 544f97954aa2a5a3d0a320d62aaced3b15c2b308 Mon Sep 17 00:00:00 2001 From: Masayuki Nakano Date: Thu, 16 Jun 2022 01:57:57 +0000 Subject: [PATCH 55/64] Bug 1770877 - part 3: Make `HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer` stop touching `Selection` directly r=m_kato And this renames it to `RemoveBlockContainerElementWithTransactionBetween` to explain its job simpler. Differential Revision: https://phabricator.services.mozilla.com/D149067 --- editor/libeditor/HTMLEditHelpers.h | 10 ++ editor/libeditor/HTMLEditSubActionHandler.cpp | 127 +++++++++++------- editor/libeditor/HTMLEditor.h | 25 ++-- 3 files changed, 101 insertions(+), 61 deletions(-) diff --git a/editor/libeditor/HTMLEditHelpers.h b/editor/libeditor/HTMLEditHelpers.h index 2f9d6230c9de..faa1c678fea2 100644 --- a/editor/libeditor/HTMLEditHelpers.h +++ b/editor/libeditor/HTMLEditHelpers.h @@ -868,6 +868,16 @@ class MOZ_STACK_CLASS SplitRangeOffFromNodeResult final { mRightContent(aRightContent), mRv(NS_OK) {} + SplitRangeOffFromNodeResult(nsIContent* aLeftContent, + nsIContent* aMiddleContent, + nsIContent* aRightContent, + EditorDOMPoint&& aPointToPutCaret) + : mLeftContent(aLeftContent), + mMiddleContent(aMiddleContent), + mRightContent(aRightContent), + mCaretPoint(std::move(aPointToPutCaret)), + mRv(NS_OK) {} + SplitRangeOffFromNodeResult(SplitNodeResult&& aSplitResultAtLeftOfMiddleNode, SplitNodeResult&& aSplitResultAtRightOfMiddleNode) : mRv(NS_OK) { diff --git a/editor/libeditor/HTMLEditSubActionHandler.cpp b/editor/libeditor/HTMLEditSubActionHandler.cpp index 48f12c7944ee..a7efed8beced 100644 --- a/editor/libeditor/HTMLEditSubActionHandler.cpp +++ b/editor/libeditor/HTMLEditSubActionHandler.cpp @@ -5297,48 +5297,37 @@ SplitRangeOffFromNodeResult HTMLEditor::HandleOutdentAtSelectionInternal() { } SplitRangeOffFromNodeResult -HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer( - Element& aBlockElement, nsIContent& aStartOfRange, +HTMLEditor::RemoveBlockContainerElementWithTransactionBetween( + Element& aBlockContainerElement, nsIContent& aStartOfRange, nsIContent& aEndOfRange) { MOZ_ASSERT(IsEditActionDataAvailable()); - SplitRangeOffFromNodeResult splitResult = - SplitRangeOffFromBlock(aBlockElement, aStartOfRange, aEndOfRange); + EditorDOMPoint pointToPutCaret; + SplitRangeOffFromNodeResult splitResult = SplitRangeOffFromBlock( + aBlockContainerElement, aStartOfRange, aEndOfRange); if (splitResult.EditorDestroyed()) { NS_WARNING("HTMLEditor::SplitRangeOffFromBlock() failed"); return splitResult; } if (splitResult.isOk()) { - nsresult rv = splitResult.SuggestCaretPointTo( - *this, {SuggestCaret::OnlyIfHasSuggestion, - SuggestCaret::OnlyIfTransactionsAllowedToDoIt, - SuggestCaret::AndIgnoreTrivialError}); - if (NS_FAILED(rv)) { - NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); - return SplitRangeOffFromNodeResult(rv); - } - NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), - "SplitRangeOffFromNodeResult::SuggestCaretPointTo() " - "failed, but ignored"); + splitResult.MoveCaretPointTo(pointToPutCaret, + {SuggestCaret::OnlyIfHasSuggestion}); } else { NS_WARNING( "HTMLEditor::SplitRangeOffFromBlock() failed, but might be ignored"); } - const Result unwrapBlockElementResult = - RemoveBlockContainerWithTransaction(aBlockElement); - if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) { + Result unwrapBlockElementResult = + RemoveBlockContainerWithTransaction(aBlockContainerElement); + if (unwrapBlockElementResult.isErr()) { NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed"); return SplitRangeOffFromNodeResult(unwrapBlockElementResult.inspectErr()); } - const EditorDOMPoint& pointToPutCaret = unwrapBlockElementResult.inspect(); - if (AllowsTransactionsToChangeSelection() && pointToPutCaret.IsSet()) { - nsresult rv = CollapseSelectionTo(pointToPutCaret); - if (NS_FAILED(rv)) { - return SplitRangeOffFromNodeResult(rv); - } + if (unwrapBlockElementResult.inspect().IsSet()) { + pointToPutCaret = unwrapBlockElementResult.unwrap(); } return SplitRangeOffFromNodeResult(splitResult.GetLeftContent(), nullptr, - splitResult.GetRightContent()); + splitResult.GetRightContent(), + std::move(pointToPutCaret)); } SplitRangeOffFromNodeResult HTMLEditor::SplitRangeOffFromBlock( @@ -8352,14 +8341,22 @@ nsresult HTMLEditor::RemoveBlockContainerElements( if (HTMLEditUtils::IsFormatNode(content)) { // Process any partial progress saved if (blockElement) { - SplitRangeOffFromNodeResult removeMiddleContainerResult = - SplitRangeOffFromBlockAndRemoveMiddleContainer( + SplitRangeOffFromNodeResult unwrapBlockElementResult = + RemoveBlockContainerElementWithTransactionBetween( *blockElement, *firstContent, *lastContent); - if (removeMiddleContainerResult.isErr()) { + if (unwrapBlockElementResult.isErr()) { NS_WARNING( - "HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer() " + "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() " "failed"); - return removeMiddleContainerResult.unwrapErr(); + return unwrapBlockElementResult.unwrapErr(); + } + nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); + if (NS_FAILED(rv)) { + NS_WARNING( + "SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return rv; } firstContent = lastContent = blockElement = nullptr; } @@ -8393,14 +8390,22 @@ nsresult HTMLEditor::RemoveBlockContainerElements( HTMLEditUtils::IsAnyListElement(content)) { // Process any partial progress saved if (blockElement) { - SplitRangeOffFromNodeResult removeMiddleContainerResult = - SplitRangeOffFromBlockAndRemoveMiddleContainer( + SplitRangeOffFromNodeResult unwrapBlockElementResult = + RemoveBlockContainerElementWithTransactionBetween( *blockElement, *firstContent, *lastContent); - if (removeMiddleContainerResult.isErr()) { + if (unwrapBlockElementResult.isErr()) { NS_WARNING( - "HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer() " + "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() " "failed"); - return removeMiddleContainerResult.unwrapErr(); + return unwrapBlockElementResult.unwrapErr(); + } + nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); + if (NS_FAILED(rv)) { + NS_WARNING( + "SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return rv; } firstContent = lastContent = blockElement = nullptr; } @@ -8429,14 +8434,22 @@ nsresult HTMLEditor::RemoveBlockContainerElements( // Otherwise, we have progressed beyond end of blockElement, so let's // handle it now. We need to remove the portion of blockElement that // contains [firstContent - lastContent]. - SplitRangeOffFromNodeResult removeMiddleContainerResult = - SplitRangeOffFromBlockAndRemoveMiddleContainer( + SplitRangeOffFromNodeResult unwrapBlockElementResult = + RemoveBlockContainerElementWithTransactionBetween( *blockElement, *firstContent, *lastContent); - if (removeMiddleContainerResult.isErr()) { + if (unwrapBlockElementResult.isErr()) { NS_WARNING( - "HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer() " + "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() " "failed"); - return removeMiddleContainerResult.unwrapErr(); + return unwrapBlockElementResult.unwrapErr(); + } + nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); + if (NS_FAILED(rv)) { + NS_WARNING( + "SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return rv; } firstContent = lastContent = blockElement = nullptr; // Fall out and handle content @@ -8456,14 +8469,21 @@ nsresult HTMLEditor::RemoveBlockContainerElements( if (blockElement) { // Some node that is already sans block style. Skip over it and process // any partial progress saved. - SplitRangeOffFromNodeResult removeMiddleContainerResult = - SplitRangeOffFromBlockAndRemoveMiddleContainer( + SplitRangeOffFromNodeResult unwrapBlockElementResult = + RemoveBlockContainerElementWithTransactionBetween( *blockElement, *firstContent, *lastContent); - if (removeMiddleContainerResult.isErr()) { + if (unwrapBlockElementResult.isErr()) { NS_WARNING( - "HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer() " + "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() " "failed"); - return removeMiddleContainerResult.unwrapErr(); + return unwrapBlockElementResult.unwrapErr(); + } + nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); + if (NS_FAILED(rv)) { + NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return rv; } firstContent = lastContent = blockElement = nullptr; continue; @@ -8471,14 +8491,21 @@ nsresult HTMLEditor::RemoveBlockContainerElements( } // Process any partial progress saved if (blockElement) { - SplitRangeOffFromNodeResult removeMiddleContainerResult = - SplitRangeOffFromBlockAndRemoveMiddleContainer( + SplitRangeOffFromNodeResult unwrapBlockElementResult = + RemoveBlockContainerElementWithTransactionBetween( *blockElement, *firstContent, *lastContent); - if (removeMiddleContainerResult.isErr()) { + if (unwrapBlockElementResult.isErr()) { NS_WARNING( - "HTMLEditor::SplitRangeOffFromBlockAndRemoveMiddleContainer() " + "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() " "failed"); - return removeMiddleContainerResult.unwrapErr(); + return unwrapBlockElementResult.unwrapErr(); + } + nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo( + *this, {SuggestCaret::OnlyIfHasSuggestion, + SuggestCaret::OnlyIfTransactionsAllowedToDoIt}); + if (NS_FAILED(rv)) { + NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed"); + return rv; } firstContent = lastContent = blockElement = nullptr; } diff --git a/editor/libeditor/HTMLEditor.h b/editor/libeditor/HTMLEditor.h index eec213bc2280..2667a6b94e04 100644 --- a/editor/libeditor/HTMLEditor.h +++ b/editor/libeditor/HTMLEditor.h @@ -1553,26 +1553,29 @@ class HTMLEditor final : public EditorBase, nsIContent& aEndOfMiddleElement); /** - * SplitRangeOffFromBlockAndRemoveMiddleContainer() splits the nodes - * between aStartOfRange and aEndOfRange, then, removes the middle element - * and moves its content to where the middle element was. + * RemoveBlockContainerElementWithTransactionBetween() splits the nodes + * at aStartOfRange and aEndOfRange, then, removes the middle element which + * was split off from aBlockContainerElement and moves the ex-children to + * where the middle element was. I.e., all nodes between aStartOfRange and + * aEndOfRange (including themselves) will be unwrapped from + * aBlockContainerElement. * - * @param aBlockElement The node which will be split. + * @param aBlockContainerElement The node which will be split. * @param aStartOfRange The first node which will be unwrapped - * from aBlockElement. + * from aBlockContainerElement. * @param aEndOfRange The last node which will be unwrapped from - * aBlockElement. + * aBlockContainerElement. * @return The left content is new created left - * element of aBlockElement. + * element of aBlockContainerElement. * The right content is split element, - * i.e., must be aBlockElement. + * i.e., must be aBlockContainerElement. * The middle content is nullptr since * removing it is the job of this method. */ [[nodiscard]] MOZ_CAN_RUN_SCRIPT SplitRangeOffFromNodeResult - SplitRangeOffFromBlockAndRemoveMiddleContainer(Element& aBlockElement, - nsIContent& aStartOfRange, - nsIContent& aEndOfRange); + RemoveBlockContainerElementWithTransactionBetween( + Element& aBlockContainerElement, nsIContent& aStartOfRange, + nsIContent& aEndOfRange); /** * MoveNodesIntoNewBlockquoteElement() inserts at least one
From 09080ca40838cda37b50d194eb68898e806246a9 Mon Sep 17 00:00:00 2001 From: Lee Salzman Date: Thu, 16 Jun 2022 02:31:24 +0000 Subject: [PATCH 56/64] Bug 1769082 - Avoid divide-by-zero in Skia's luminosity blend mode. r=jrmuizel,gfx-reviewers This applies a fix that is present in Skia's HW luminosity blend mode to its CPU pipeline so that the luminosity mode no longer divides by zero, thus avoiding infs and nans. Differential Revision: https://phabricator.services.mozilla.com/D149030 --- .../skia/src/opts/SkRasterPipeline_opts.h | 4 ++-- layout/reftests/bugs/1769082-1-ref.html | 19 ++++++++++++++++++ layout/reftests/bugs/1769082-1.html | 20 +++++++++++++++++++ layout/reftests/bugs/reftest.list | 1 + 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 layout/reftests/bugs/1769082-1-ref.html create mode 100644 layout/reftests/bugs/1769082-1.html diff --git a/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h b/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h index 5731f5863de6..aea70141a6f4 100644 --- a/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h +++ b/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h @@ -1595,8 +1595,8 @@ SI void clip_color(F* r, F* g, F* b, F a) { l = lum(*r, *g, *b); auto clip = [=](F c) { - c = if_then_else(mn >= 0, c, l + (c - l) * ( l) / (l - mn) ); - c = if_then_else(mx > a, l + (c - l) * (a - l) / (mx - l), c); + c = if_then_else(mn < 0 && l != mn, l + (c - l) * ( l) / (l - mn), c); + c = if_then_else(mx > a && l != mx, l + (c - l) * (a - l) / (mx - l), c); c = max(c, 0); // Sometimes without this we may dip just a little negative. return c; }; diff --git a/layout/reftests/bugs/1769082-1-ref.html b/layout/reftests/bugs/1769082-1-ref.html new file mode 100644 index 000000000000..db9531d1a576 --- /dev/null +++ b/layout/reftests/bugs/1769082-1-ref.html @@ -0,0 +1,19 @@ + + + +
+ +
+ + diff --git a/layout/reftests/bugs/1769082-1.html b/layout/reftests/bugs/1769082-1.html new file mode 100644 index 000000000000..fd5c847f9e33 --- /dev/null +++ b/layout/reftests/bugs/1769082-1.html @@ -0,0 +1,20 @@ + + + +
+ +
+ + diff --git a/layout/reftests/bugs/reftest.list b/layout/reftests/bugs/reftest.list index 3752dcc60081..6d97c71b9a9b 100644 --- a/layout/reftests/bugs/reftest.list +++ b/layout/reftests/bugs/reftest.list @@ -2116,6 +2116,7 @@ pref(image.downscale-during-decode.enabled,true) == 1744468-1.html 1744468-1-ref == 1747272-1.html 1747272-1-ref.html == 1750146-1.html 1750146-1-ref.html == 1735265-1.html 1735265-1-ref.html +fuzzy(0-1,0-1000) == 1769082-1.html 1769082-1-ref.html == 1773484.html 1773484-ref.html # The following tests are skipped on Android since Android doesn't deal very From b7d6ae139a93eff8d44c8c9d068b5239a3847052 Mon Sep 17 00:00:00 2001 From: Tooru Fujisawa Date: Thu, 16 Jun 2022 02:59:25 +0000 Subject: [PATCH 57/64] Bug 1773603 - Support resource URI with *.js and *.jsm.js extension in ESM shim. r=jonco Differential Revision: https://phabricator.services.mozilla.com/D148880 --- js/xpconnect/loader/mozJSComponentLoader.cpp | 90 ++++++++++++++------ js/xpconnect/tests/unit/test_import_shim.js | 38 +++++++++ 2 files changed, 104 insertions(+), 24 deletions(-) diff --git a/js/xpconnect/loader/mozJSComponentLoader.cpp b/js/xpconnect/loader/mozJSComponentLoader.cpp index 4645880c6d3a..f19598b201b3 100644 --- a/js/xpconnect/loader/mozJSComponentLoader.cpp +++ b/js/xpconnect/loader/mozJSComponentLoader.cpp @@ -107,37 +107,75 @@ static LazyLogModule gJSCLLog("JSComponentLoader"); #define ERROR_UNINITIALIZED_SYMBOL \ "%s - Symbol '%s' accessed before initialization. Cyclic import?" -static constexpr char JSMSuffix[] = ".jsm"; -static constexpr size_t JSMSuffixLength = mozilla::ArrayLength(JSMSuffix) - 1; -static constexpr char MJSSuffix[] = ".sys.mjs"; -static constexpr size_t MJSSuffixLength = mozilla::ArrayLength(MJSSuffix) - 1; +static constexpr char JSM_Suffix[] = ".jsm"; +static constexpr size_t JSM_SuffixLength = mozilla::ArrayLength(JSM_Suffix) - 1; +static constexpr char JSM_JS_Suffix[] = ".jsm.js"; +static constexpr size_t JSM_JS_SuffixLength = + mozilla::ArrayLength(JSM_JS_Suffix) - 1; +static constexpr char JS_Suffix[] = ".js"; +static constexpr size_t JS_SuffixLength = mozilla::ArrayLength(JS_Suffix) - 1; +static constexpr char MJS_Suffix[] = ".sys.mjs"; +static constexpr size_t MJS_SuffixLength = mozilla::ArrayLength(MJS_Suffix) - 1; static bool IsJSM(const nsACString& aLocation) { - if (aLocation.Length() < JSMSuffixLength) { + if (aLocation.Length() < JSM_SuffixLength) { return false; } - const auto ext = Substring(aLocation, aLocation.Length() - JSMSuffixLength); - return ext == JSMSuffix; + const auto ext = Substring(aLocation, aLocation.Length() - JSM_SuffixLength); + return ext == JSM_Suffix; +} + +static bool IsJS(const nsACString& aLocation) { + if (aLocation.Length() < JS_SuffixLength) { + return false; + } + const auto ext = Substring(aLocation, aLocation.Length() - JS_SuffixLength); + return ext == JS_Suffix; +} + +static bool IsJSM_JS(const nsACString& aLocation) { + if (aLocation.Length() < JSM_JS_SuffixLength) { + return false; + } + const auto ext = + Substring(aLocation, aLocation.Length() - JSM_JS_SuffixLength); + return ext == JSM_JS_Suffix; } static bool IsMJS(const nsACString& aLocation) { - if (aLocation.Length() < MJSSuffixLength) { + if (aLocation.Length() < MJS_SuffixLength) { return false; } - const auto ext = Substring(aLocation, aLocation.Length() - MJSSuffixLength); - return ext == MJSSuffix; + const auto ext = Substring(aLocation, aLocation.Length() - MJS_SuffixLength); + return ext == MJS_Suffix; } -static void ToJSM(const nsACString& aLocation, nsAutoCString& aOut) { +static void MJSToJSM(const nsACString& aLocation, nsAutoCString& aOut) { MOZ_ASSERT(IsMJS(aLocation)); - aOut = Substring(aLocation, 0, aLocation.Length() - MJSSuffixLength); - aOut += JSMSuffix; + aOut = Substring(aLocation, 0, aLocation.Length() - MJS_SuffixLength); + aOut += JSM_Suffix; } -static void ToMJS(const nsACString& aLocation, nsAutoCString& aOut) { - MOZ_ASSERT(IsJSM(aLocation)); - aOut = Substring(aLocation, 0, aLocation.Length() - JSMSuffixLength); - aOut += MJSSuffix; +static bool TryToMJS(const nsACString& aLocation, nsAutoCString& aOut) { + if (IsJSM(aLocation)) { + aOut = Substring(aLocation, 0, aLocation.Length() - JSM_SuffixLength); + aOut += MJS_Suffix; + return true; + } + + if (IsJSM_JS(aLocation)) { + aOut = Substring(aLocation, 0, aLocation.Length() - JSM_JS_SuffixLength); + aOut += MJS_Suffix; + return true; + } + + if (IsJS(aLocation)) { + aOut = Substring(aLocation, 0, aLocation.Length() - JS_SuffixLength); + aOut += MJS_Suffix; + return true; + } + + return false; } static bool Dump(JSContext* cx, unsigned argc, Value* vp) { @@ -1128,9 +1166,12 @@ nsresult mozJSComponentLoader::IsModuleLoaded(const nsACString& aLocation, return NS_OK; } - if (IsJSM(aLocation) && mModuleLoader) { + if (mModuleLoader) { nsAutoCString mjsLocation; - ToMJS(aLocation, mjsLocation); + if (!TryToMJS(aLocation, mjsLocation)) { + *retval = false; + return NS_OK; + } ComponentLoaderInfo mjsInfo(mjsLocation); @@ -1171,7 +1212,10 @@ nsresult mozJSComponentLoader::GetLoadedJSAndESModules( for (const auto& location : modules) { if (IsMJS(location)) { nsAutoCString jsmLocation; - ToJSM(location, jsmLocation); + // NOTE: Unconditionally convert to *.jsm. This doesn't cover *.js case + // but given `Cu.loadedModules` is rarely used for system modules, + // this won't cause much compat issue. + MJSToJSM(location, jsmLocation); aLoadedModules.AppendElement(jsmLocation); } } @@ -1517,13 +1561,11 @@ nsresult mozJSComponentLoader::TryFallbackToImportModule( JSContext* aCx, const nsACString& aLocation, JS::MutableHandleObject aModuleGlobal, JS::MutableHandleObject aModuleExports, bool aIgnoreExports) { - if (!IsJSM(aLocation)) { + nsAutoCString mjsLocation; + if (!TryToMJS(aLocation, mjsLocation)) { return NS_ERROR_FILE_NOT_FOUND; } - nsAutoCString mjsLocation; - ToMJS(aLocation, mjsLocation); - JS::RootedObject moduleNamespace(aCx); nsresult rv = ImportModule(aCx, mjsLocation, &moduleNamespace); NS_ENSURE_SUCCESS(rv, rv); diff --git a/js/xpconnect/tests/unit/test_import_shim.js b/js/xpconnect/tests/unit/test_import_shim.js index af0b4b710f8c..e4623dbcd333 100644 --- a/js/xpconnect/tests/unit/test_import_shim.js +++ b/js/xpconnect/tests/unit/test_import_shim.js @@ -27,6 +27,30 @@ add_task(function test_Cu_import_shim_first() { Assert.equal(exports2.obj.value, 10); Assert.ok(exports2.obj === global2.obj); Assert.ok(exports2.obj === global.obj); + + // Also test with *.js extension. + const exports3 = {}; + const global3 = Components.utils.import( + "resource://test/esmified-1.js", exports3 + ); + Assert.equal(global3.loadCount, 1); + Assert.equal(global3.obj.value, 10); + Assert.equal(exports3.loadCount, 1); + Assert.equal(exports3.obj.value, 10); + Assert.ok(exports3.obj === global3.obj); + Assert.ok(exports3.obj === global.obj); + + // Also test with *.jsm.js extension. + const exports4 = {}; + const global4 = Components.utils.import( + "resource://test/esmified-1.js", exports4 + ); + Assert.equal(global4.loadCount, 1); + Assert.equal(global4.obj.value, 10); + Assert.equal(exports4.loadCount, 1); + Assert.equal(exports4.obj.value, 10); + Assert.ok(exports4.obj === global4.obj); + Assert.ok(exports4.obj === global.obj); }); add_task(function test_Cu_import_no_shim_first() { @@ -303,6 +327,8 @@ add_task(function test_Cu_import_not_exported_shim() { add_task(function test_Cu_isModuleLoaded_shim() { Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.jsm"), false); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.js"), false); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.jsm.js"), false); Assert.equal(Cu.loadedModules.includes("resource://test/esmified-5.jsm"), false); Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.sys.mjs"), false); Assert.equal(Cu.loadedModules.includes("resource://test/esmified-5.sys.mjs"), false); @@ -310,6 +336,8 @@ add_task(function test_Cu_isModuleLoaded_shim() { Cu.import("resource://test/esmified-5.jsm", {}); Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.jsm"), true); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.js"), true); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-5.jsm.js"), true); Assert.equal(Cu.loadedModules.includes("resource://test/esmified-5.jsm"), true); // This is false because Cu.isModuleLoaded does not support ESM directly @@ -320,7 +348,11 @@ add_task(function test_Cu_isModuleLoaded_shim() { add_task(function test_Cu_isModuleLoaded_no_shim() { Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.jsm"), false); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.js"), false); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.jsm.js"), false); Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.jsm"), false); + Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.js"), false); + Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.jsm.js"), false); Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.sys.mjs"), false); Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.sys.mjs"), false); @@ -330,8 +362,14 @@ add_task(function test_Cu_isModuleLoaded_no_shim() { // query that accesses the ESM-ified module returns the existence of // ESM. Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.jsm"), true); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.js"), true); + Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.jsm.js"), true); Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.jsm"), true); + // This is false because shim always use *.jsm. + Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.js"), false); + Assert.equal(Cu.loadedModules.includes("resource://test/esmified-6.jsm.js"), false); + // This is false because Cu.isModuleLoaded does not support ESM directly // (bug 1768819) Assert.equal(Cu.isModuleLoaded("resource://test/esmified-6.sys.mjs"), false); From 40f96f059514dbdd4c05538df01f1a38b36cea01 Mon Sep 17 00:00:00 2001 From: James Teow Date: Thu, 16 Jun 2022 03:10:54 +0000 Subject: [PATCH 58/64] Bug 1769074 - Convert iconuri to iconUri for JSON bookmark imports - r=Standard8 Replaced instances of `iconuri` with `iconUri` The added json file is a variant of `bookmarks.json` so it can be re-used with test_bookmarks_json. Differential Revision: https://phabricator.services.mozilla.com/D146636 --- .../components/places/BookmarkHTMLUtils.jsm | 2 +- toolkit/components/places/PlacesBackups.jsm | 2 +- toolkit/components/places/PlacesUtils.jsm | 6 +- .../places/tests/unit/bookmarks_iconuri.json | 307 ++++++++++++++++++ .../places/tests/unit/test_bookmarks_json.js | 35 ++ .../tests/unit/test_promiseBookmarksTree.js | 6 +- .../components/places/tests/unit/xpcshell.ini | 1 + 7 files changed, 351 insertions(+), 8 deletions(-) create mode 100644 toolkit/components/places/tests/unit/bookmarks_iconuri.json diff --git a/toolkit/components/places/BookmarkHTMLUtils.jsm b/toolkit/components/places/BookmarkHTMLUtils.jsm index 66dd98539c30..60e2cbae31de 100644 --- a/toolkit/components/places/BookmarkHTMLUtils.jsm +++ b/toolkit/components/places/BookmarkHTMLUtils.jsm @@ -1046,7 +1046,7 @@ BookmarkExporter.prototype = { }, async _writeFaviconAttribute(aItem) { - if (!aItem.iconuri) { + if (!aItem.iconUri) { return; } let favicon; diff --git a/toolkit/components/places/PlacesBackups.jsm b/toolkit/components/places/PlacesBackups.jsm index 70d9c072ed47..a3926678d286 100644 --- a/toolkit/components/places/PlacesBackups.jsm +++ b/toolkit/components/places/PlacesBackups.jsm @@ -500,7 +500,7 @@ var PlacesBackups = { * The following properties exist only for a subset of bookmarks: * * annos: array of annotations * * uri: url - * * iconuri: favicon's url + * * iconUri: favicon's url * * keyword: associated keyword * * charset: last known charset * * tags: csv string of tags diff --git a/toolkit/components/places/PlacesUtils.jsm b/toolkit/components/places/PlacesUtils.jsm index 0d25d199e1b3..8cfc92ddae8d 100644 --- a/toolkit/components/places/PlacesUtils.jsm +++ b/toolkit/components/places/PlacesUtils.jsm @@ -1690,7 +1690,7 @@ var PlacesUtils = { * - charset (string): the last known charset of the bookmark. * - keyword (string): the bookmark's keyword (unset if none). * - postData (string): the bookmark's keyword postData (unset if none). - * - iconuri (string): the bookmark's favicon url. + * - iconUri (string): the bookmark's favicon url. * The last four properties are not set at all if they're irrelevant (e.g. * |charset| is not set if no charset was previously set for the bookmark * url). @@ -1730,7 +1730,7 @@ var PlacesUtils = { let type = aRow.getResultByName("type"); item.typeCode = type; if (type == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { - copyProps("charset", "tags", "iconuri"); + copyProps("charset", "tags", "iconUri"); } switch (type) { @@ -1796,7 +1796,7 @@ var PlacesUtils = { JOIN moz_icons_to_pages ON icon_id = i.id JOIN moz_pages_w_icons pi ON page_id = pi.id WHERE pi.page_url_hash = hash(h.url) AND pi.page_url = h.url - ORDER BY width DESC LIMIT 1) AS iconuri, + ORDER BY width DESC LIMIT 1) AS iconUri, (SELECT GROUP_CONCAT(t.title, ',') FROM moz_bookmarks b2 JOIN moz_bookmarks t ON t.id = +b2.parent AND t.parent = :tags_folder diff --git a/toolkit/components/places/tests/unit/bookmarks_iconuri.json b/toolkit/components/places/tests/unit/bookmarks_iconuri.json new file mode 100644 index 000000000000..4059c1d53fc0 --- /dev/null +++ b/toolkit/components/places/tests/unit/bookmarks_iconuri.json @@ -0,0 +1,307 @@ +{ + "guid": "root________", + "title": "", + "id": 1, + "dateAdded": 1361551978957783, + "lastModified": 1361551978957783, + "type": "text/x-moz-place-container", + "root": "placesRoot", + "children": [ + { + "guid": "menu________", + "title": "Bookmarks Menu", + "id": 2, + "parent": 1, + "dateAdded": 1361551978957783, + "lastModified": 1361551979382837, + "type": "text/x-moz-place-container", + "root": "bookmarksMenuFolder", + "children": [ + { + "guid": "OCyeUO5uu9FF", + "title": "Mozilla Firefox", + "id": 6, + "parent": 2, + "dateAdded": 1361551979350273, + "lastModified": 1361551979376699, + "type": "text/x-moz-place-container", + "children": [ + { + "guid": "OCyeUO5uu9FG", + "title": "Help and Tutorials", + "id": 7, + "parent": 6, + "dateAdded": 1361551979356436, + "lastModified": 1361551979362718, + "type": "text/x-moz-place", + "uri": "http://en-us.www.mozilla.com/en-US/firefox/help/", + "iconUri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" + }, + { + "guid": "OCyeUO5uu9FH", + "index": 1, + "title": "Customize Firefox", + "id": 8, + "parent": 6, + "dateAdded": 1361551979365662, + "lastModified": 1361551979368077, + "type": "text/x-moz-place", + "uri": "http://en-us.www.mozilla.com/en-US/firefox/customize/", + "iconUri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" + }, + { + "guid": "OCyeUO5uu9FJ", + "index": 3, + "title": "About Us", + "id": 10, + "parent": 6, + "dateAdded": 1361551979376699, + "lastModified": 1361551979379060, + "type": "text/x-moz-place", + "uri": "http://en-us.www.mozilla.com/en-US/about/", + "iconUri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" + }, + { + "guid": "OCyeUO5uu9FI", + "index": 2, + "title": "Get Involved", + "id": 9, + "parent": 6, + "dateAdded": 1361551979371071, + "lastModified": 1361551979373745, + "type": "text/x-moz-place", + "uri": "http://en-us.www.mozilla.com/en-US/firefox/community/", + "iconUri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" + }, + { + "guid": "QFM-QnE2ZpMz", + "title": "Test null postData", + "index": 4, + "dateAdded": 1481639510868000, + "lastModified": 1489563704300000, + "id": 17, + "charset": "UTF-8", + "annos": [ + { + "name": "bookmarkProperties/description", + "flags": 0, + "expires": 4, + "value": "The best" + } + ], + "type": "text/x-moz-place", + "uri": "http://example.com/search?q=%s&suggid=", + "postData": null + } + ] + }, + { + "guid": "OCyeUO5uu9FK", + "index": 1, + "title": "", + "id": 11, + "parent": 2, + "dateAdded": 1361551979380988, + "lastModified": 1361551979380988, + "type": "text/x-moz-place-separator" + }, + { + "guid": "OCyeUO5uu9FL", + "index": 2, + "title": "test", + "id": 12, + "parent": 2, + "dateAdded": 1177541020000000, + "lastModified": 1177541050000000, + "annos": [ + { + "name": "bookmarkProperties/description", + "flags": 0, + "expires": 4, + "mimeType": null, + "type": 3, + "value": "folder test comment" + } + ], + "type": "text/x-moz-place-container", + "children": [ + { + "guid": "OCyeUO5uu9GX", + "title": "test post keyword", + "id": 13, + "parent": 12, + "dateAdded": 1177375336000000, + "lastModified": 1177375423000000, + "annos": [ + { + "name": "bookmarkProperties/description", + "flags": 0, + "expires": 4, + "mimeType": null, + "type": 3, + "value": "item description" + }, + { + "name": "bookmarkProperties/loadInSidebar", + "flags": 0, + "expires": 4, + "mimeType": null, + "type": 1, + "value": 1 + } + ], + "type": "text/x-moz-place", + "uri": "http://test/post", + "keyword": "test", + "charset": "ISO-8859-1", + "postData": "hidden1%3Dbar&text1%3D%25s" + } + ] + } + ] + }, + { + "index": 1, + "title": "Bookmarks Toolbar", + "id": 3, + "parent": 1, + "dateAdded": 1361551978957783, + "lastModified": 1177541050000000, + "annos": [ + { + "name": "bookmarkProperties/description", + "flags": 0, + "expires": 4, + "mimeType": null, + "type": 3, + "value": "Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar" + } + ], + "type": "text/x-moz-place-container", + "root": "toolbarFolder", + "children": [ + { + "guid": "OCyeUO5uu9FB", + "title": "Getting Started", + "id": 15, + "parent": 3, + "dateAdded": 1361551979409695, + "lastModified": 1361551979412080, + "type": "text/x-moz-place", + "uri": "http://en-us.www.mozilla.com/en-US/firefox/central/", + "iconUri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" + }, + { + "guid": "OCyeUO5uu9FR", + "index": 1, + "title": "Latest Headlines", + "id": 16, + "parent": 3, + "dateAdded": 1361551979451584, + "lastModified": 1361551979457086, + "livemark": 1, + "annos": [ + { + "name": "livemark/feedURI", + "flags": 0, + "expires": 4, + "mimeType": null, + "type": 3, + "value": "http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml" + }, + { + "name": "livemark/siteURI", + "flags": 0, + "expires": 4, + "mimeType": null, + "type": 3, + "value": "http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/" + } + ], + "type": "text/x-moz-place-container", + "children": [] + } + ] + }, + { + "index": 2, + "title": "Tags", + "id": 4, + "parent": 1, + "dateAdded": 1361551978957783, + "lastModified": 1361551978957783, + "type": "text/x-moz-place-container", + "root": "tagsFolder", + "children": [] + }, + { + "index": 3, + "title": "Unsorted Bookmarks", + "id": 5, + "parent": 1, + "dateAdded": 1361551978957783, + "lastModified": 1177541050000000, + "type": "text/x-moz-place-container", + "root": "unfiledBookmarksFolder", + "children": [ + { + "guid": "OCyeUO5uu9FW", + "title": "Example.tld", + "id": 14, + "parent": 5, + "dateAdded": 1361551979401846, + "lastModified": 1361551979402952, + "type": "text/x-moz-place", + "uri": "http://example.tld/" + }, + { + "guid": "Cfkety492Afk", + "title": "test tagged bookmark", + "id": 15, + "parent": 5, + "dateAdded": 1507025843703345, + "lastModified": 1507025844703124, + "type": "text/x-moz-place", + "uri": "http://example.tld/tagged", + "tags": "foo" + }, + { + "guid": "lOZGoFR1eXbl", + "title": "Bookmarks Toolbar Shortcut", + "dateAdded": 1507025843703345, + "lastModified": 1507025844703124, + "id": 16, + "type": "text/x-moz-place", + "uri": "place:folder=TOOLBAR" + }, + { + "guid": "7yJWnBVhjRtP", + "title": "Folder Shortcut", + "dateAdded": 1507025843703345, + "lastModified": 1507025844703124, + "id": 17, + "type": "text/x-moz-place", + "uri": "place:folder=6" + }, + { + "guid": "vm5QXWuWc12l", + "title": "Folder Shortcut 2", + "dateAdded": 1507025843703345, + "lastModified": 1507025844703124, + "id": 18, + "type": "text/x-moz-place", + "uri": "place:folder=6123443" + }, + { + "guid": "Icg1XlIozA1D", + "title": "Folder Shortcut 3", + "dateAdded": 1507025843703345, + "lastModified": 1507025844703124, + "id": 18, + "type": "text/x-moz-place", + "uri": "place:folder=6&folder=BOOKMARKS_MENU" + } + ] + } + ] +} diff --git a/toolkit/components/places/tests/unit/test_bookmarks_json.js b/toolkit/components/places/tests/unit/test_bookmarks_json.js index 71bc8cdf401b..37b155e1c0b0 100644 --- a/toolkit/components/places/tests/unit/test_bookmarks_json.js +++ b/toolkit/components/places/tests/unit/test_bookmarks_json.js @@ -190,6 +190,41 @@ add_task(async function test_import_ontop() { await testImportedBookmarks(); }); +add_task(async function test_import_iconuri() { + await PlacesUtils.bookmarks.eraseEverything(); + await PlacesUtils.history.clear(); + + let bookmarksFile = PathUtils.join( + do_get_cwd().path, + "bookmarks_iconuri.json" + ); + + await BookmarkJSONUtils.importFromFile(bookmarksFile, { + replace: true, + }); + await PlacesTestUtils.promiseAsyncUpdates(); + await testImportedBookmarks(); +}); + +add_task(async function test_export_bookmarks_with_iconuri() { + bookmarksExportedFile = PathUtils.join( + PathUtils.profileDir, + "bookmarks.exported.json" + ); + await BookmarkJSONUtils.exportToFile(bookmarksExportedFile); + await PlacesTestUtils.promiseAsyncUpdates(); +}); + +add_task(async function test_import_exported_bookmarks_with_iconuri() { + await PlacesUtils.bookmarks.eraseEverything(); + await PlacesUtils.history.clear(); + await BookmarkJSONUtils.importFromFile(bookmarksExportedFile, { + replace: true, + }); + await PlacesTestUtils.promiseAsyncUpdates(); + await testImportedBookmarks(); +}); + add_task(async function test_clean() { await PlacesUtils.bookmarks.eraseEverything(); }); diff --git a/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js b/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js index 2eab0656e15b..e85001713246 100644 --- a/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js +++ b/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js @@ -49,7 +49,7 @@ async function compareToNode(aItem, aNode, aIsRootItem, aExcludedGuids = []) { check_unset("parentGuid"); } - const BOOKMARK_ONLY_PROPS = ["uri", "iconuri", "tags", "charset", "keyword"]; + const BOOKMARK_ONLY_PROPS = ["uri", "iconUri", "tags", "charset", "keyword"]; const FOLDER_ONLY_PROPS = ["children", "root"]; let nodesCount = 1; @@ -119,13 +119,13 @@ async function compareToNode(aItem, aNode, aIsRootItem, aExcludedGuids = []) { if (aNode.icon) { try { - await compareFavicons(aNode.icon, aItem.iconuri); + await compareFavicons(aNode.icon, aItem.iconUri); } catch (ex) { info(ex); todo_check_true(false); } } else { - check_unset(aItem.iconuri); + check_unset(aItem.iconUri); } check_unset(...FOLDER_ONLY_PROPS); diff --git a/toolkit/components/places/tests/unit/xpcshell.ini b/toolkit/components/places/tests/unit/xpcshell.ini index cdf84f67eb3c..ba49194fa804 100644 --- a/toolkit/components/places/tests/unit/xpcshell.ini +++ b/toolkit/components/places/tests/unit/xpcshell.ini @@ -8,6 +8,7 @@ support-files = bookmarks.preplaces.html bookmarks_html_localized.html bookmarks_html_singleframe.html + bookmarks_iconuri.json mobile_bookmarks_folder_import.json mobile_bookmarks_folder_merge.json mobile_bookmarks_multiple_folders.json From 297c11141122cc29867daf2c754ed27b8b56e8ef Mon Sep 17 00:00:00 2001 From: Butkovits Atila Date: Thu, 16 Jun 2022 06:18:27 +0300 Subject: [PATCH 59/64] Backed out changeset f292760857f2 (bug 1769082) for causing build bustages at SkRasterPipeline_opts. CLOSED TREE --- .../skia/src/opts/SkRasterPipeline_opts.h | 4 ++-- layout/reftests/bugs/1769082-1-ref.html | 19 ------------------ layout/reftests/bugs/1769082-1.html | 20 ------------------- layout/reftests/bugs/reftest.list | 1 - 4 files changed, 2 insertions(+), 42 deletions(-) delete mode 100644 layout/reftests/bugs/1769082-1-ref.html delete mode 100644 layout/reftests/bugs/1769082-1.html diff --git a/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h b/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h index aea70141a6f4..5731f5863de6 100644 --- a/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h +++ b/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h @@ -1595,8 +1595,8 @@ SI void clip_color(F* r, F* g, F* b, F a) { l = lum(*r, *g, *b); auto clip = [=](F c) { - c = if_then_else(mn < 0 && l != mn, l + (c - l) * ( l) / (l - mn), c); - c = if_then_else(mx > a && l != mx, l + (c - l) * (a - l) / (mx - l), c); + c = if_then_else(mn >= 0, c, l + (c - l) * ( l) / (l - mn) ); + c = if_then_else(mx > a, l + (c - l) * (a - l) / (mx - l), c); c = max(c, 0); // Sometimes without this we may dip just a little negative. return c; }; diff --git a/layout/reftests/bugs/1769082-1-ref.html b/layout/reftests/bugs/1769082-1-ref.html deleted file mode 100644 index db9531d1a576..000000000000 --- a/layout/reftests/bugs/1769082-1-ref.html +++ /dev/null @@ -1,19 +0,0 @@ - - - -
- -
- - diff --git a/layout/reftests/bugs/1769082-1.html b/layout/reftests/bugs/1769082-1.html deleted file mode 100644 index fd5c847f9e33..000000000000 --- a/layout/reftests/bugs/1769082-1.html +++ /dev/null @@ -1,20 +0,0 @@ - - - -
- -
- - diff --git a/layout/reftests/bugs/reftest.list b/layout/reftests/bugs/reftest.list index 6d97c71b9a9b..3752dcc60081 100644 --- a/layout/reftests/bugs/reftest.list +++ b/layout/reftests/bugs/reftest.list @@ -2116,7 +2116,6 @@ pref(image.downscale-during-decode.enabled,true) == 1744468-1.html 1744468-1-ref == 1747272-1.html 1747272-1-ref.html == 1750146-1.html 1750146-1-ref.html == 1735265-1.html 1735265-1-ref.html -fuzzy(0-1,0-1000) == 1769082-1.html 1769082-1-ref.html == 1773484.html 1773484-ref.html # The following tests are skipped on Android since Android doesn't deal very From 853b00c6baf7ebb28c85a5d94c50b36711cfc35d Mon Sep 17 00:00:00 2001 From: Masayuki Nakano Date: Thu, 16 Jun 2022 03:34:19 +0000 Subject: [PATCH 60/64] Bug 1770877 - part 4: Make `HTMLEditor::RemoveBlockContainerElements` stop touching `Selection` directly r=m_kato For aligning the style of similar methods, this makes it suggest caret position, but nobody uses it. Differential Revision: https://phabricator.services.mozilla.com/D149068 --- editor/libeditor/HTMLEditSubActionHandler.cpp | 107 +++++++----------- editor/libeditor/HTMLEditor.h | 20 ++-- 2 files changed, 56 insertions(+), 71 deletions(-) diff --git a/editor/libeditor/HTMLEditSubActionHandler.cpp b/editor/libeditor/HTMLEditSubActionHandler.cpp index a7efed8beced..7a90dbf04b7f 100644 --- a/editor/libeditor/HTMLEditSubActionHandler.cpp +++ b/editor/libeditor/HTMLEditSubActionHandler.cpp @@ -3972,10 +3972,16 @@ nsresult HTMLEditor::FormatBlockContainerWithTransaction(nsAtom& blockType) { return rv; } if (&blockType == nsGkAtoms::normal || &blockType == nsGkAtoms::_empty) { - nsresult rv = RemoveBlockContainerElements(arrayOfContents); - NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), - "HTMLEditor::RemoveBlockContainerElements() failed"); - return rv; + Result removeBlockContainerElementsResult = + RemoveBlockContainerElementsWithTransaction(arrayOfContents); + if (MOZ_UNLIKELY(removeBlockContainerElementsResult.isErr())) { + NS_WARNING( + "HTMLEditor::RemoveBlockContainerElementsWithTransaction() failed"); + removeBlockContainerElementsResult.unwrapErr(); + } + // Selection will be restored by `restoreSelectionLater`. Therefore, we + // should ignore the suggested caret point. + return NS_OK; } Result wrapContentsInBlockElementResult = CreateOrChangeBlockContainerElement(arrayOfContents, blockType, @@ -8327,8 +8333,9 @@ nsresult HTMLEditor::MoveNodesIntoNewBlockquoteElement( return NS_OK; } -nsresult HTMLEditor::RemoveBlockContainerElements( - nsTArray>& aArrayOfContents) { +Result +HTMLEditor::RemoveBlockContainerElementsWithTransaction( + const nsTArray>& aArrayOfContents) { MOZ_ASSERT(IsEditActionDataAvailable()); // Intent of this routine is to be used for converting to/from headers, @@ -8336,6 +8343,7 @@ nsresult HTMLEditor::RemoveBlockContainerElements( // inline things... RefPtr blockElement; nsCOMPtr firstContent, lastContent; + EditorDOMPoint pointToPutCaret; for (auto& content : aArrayOfContents) { // If curNode is an
,

, , or

, remove it.
     if (HTMLEditUtils::IsFormatNode(content)) {
@@ -8348,37 +8356,25 @@ nsresult HTMLEditor::RemoveBlockContainerElements(
           NS_WARNING(
               "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
               "failed");
-          return unwrapBlockElementResult.unwrapErr();
-        }
-        nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo(
-            *this, {SuggestCaret::OnlyIfHasSuggestion,
-                    SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
-        if (NS_FAILED(rv)) {
-          NS_WARNING(
-              "SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed");
-          return rv;
+          return Err(unwrapBlockElementResult.unwrapErr());
         }
+        unwrapBlockElementResult.MoveCaretPointTo(
+            pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
         firstContent = lastContent = blockElement = nullptr;
       }
       if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
         continue;
       }
       // Remove current block
-      const Result unwrapFormatBlockResult =
+      Result unwrapFormatBlockResult =
           RemoveBlockContainerWithTransaction(
               MOZ_KnownLive(*content->AsElement()));
       if (MOZ_UNLIKELY(unwrapFormatBlockResult.isErr())) {
         NS_WARNING("HTMLEditor::RemoveBlockContainerWithTransaction() failed");
-        return unwrapFormatBlockResult.inspectErr();
+        return unwrapFormatBlockResult;
       }
-      const EditorDOMPoint& pointToPutCaret = unwrapFormatBlockResult.inspect();
-      if (!AllowsTransactionsToChangeSelection() || !pointToPutCaret.IsSet()) {
-        continue;
-      }
-      nsresult rv = CollapseSelectionTo(pointToPutCaret);
-      if (NS_FAILED(rv)) {
-        NS_WARNING("EditorBase::CollapseSelectionTo() failed");
-        return rv;
+      if (unwrapFormatBlockResult.inspect().IsSet()) {
+        pointToPutCaret = unwrapFormatBlockResult.unwrap();
       }
       continue;
     }
@@ -8397,16 +8393,10 @@ nsresult HTMLEditor::RemoveBlockContainerElements(
           NS_WARNING(
               "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
               "failed");
-          return unwrapBlockElementResult.unwrapErr();
-        }
-        nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo(
-            *this, {SuggestCaret::OnlyIfHasSuggestion,
-                    SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
-        if (NS_FAILED(rv)) {
-          NS_WARNING(
-              "SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed");
-          return rv;
+          return Err(unwrapBlockElementResult.unwrapErr());
         }
+        unwrapBlockElementResult.MoveCaretPointTo(
+            pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
         firstContent = lastContent = blockElement = nullptr;
       }
       if (!EditorUtils::IsEditableContent(content, EditorType::HTML)) {
@@ -8415,10 +8405,15 @@ nsresult HTMLEditor::RemoveBlockContainerElements(
       // Recursion time
       AutoTArray, 24> childContents;
       HTMLEditor::GetChildNodesOf(*content, childContents);
-      nsresult rv = RemoveBlockContainerElements(childContents);
-      if (NS_FAILED(rv)) {
-        NS_WARNING("HTMLEditor::RemoveBlockContainerElements() failed");
-        return rv;
+      Result removeBlockContainerElementsResult =
+          RemoveBlockContainerElementsWithTransaction(childContents);
+      if (MOZ_UNLIKELY(removeBlockContainerElementsResult.isErr())) {
+        NS_WARNING(
+            "HTMLEditor::RemoveBlockContainerElementsWithTransaction() failed");
+        return removeBlockContainerElementsResult;
+      }
+      if (removeBlockContainerElementsResult.inspect().IsSet()) {
+        pointToPutCaret = removeBlockContainerElementsResult.unwrap();
       }
       continue;
     }
@@ -8441,16 +8436,10 @@ nsresult HTMLEditor::RemoveBlockContainerElements(
           NS_WARNING(
               "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
               "failed");
-          return unwrapBlockElementResult.unwrapErr();
-        }
-        nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo(
-            *this, {SuggestCaret::OnlyIfHasSuggestion,
-                    SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
-        if (NS_FAILED(rv)) {
-          NS_WARNING(
-              "SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed");
-          return rv;
+          return Err(unwrapBlockElementResult.unwrapErr());
         }
+        unwrapBlockElementResult.MoveCaretPointTo(
+            pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
         firstContent = lastContent = blockElement = nullptr;
         // Fall out and handle content
       }
@@ -8476,15 +8465,10 @@ nsresult HTMLEditor::RemoveBlockContainerElements(
         NS_WARNING(
             "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
             "failed");
-        return unwrapBlockElementResult.unwrapErr();
-      }
-      nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo(
-          *this, {SuggestCaret::OnlyIfHasSuggestion,
-                  SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
-      if (NS_FAILED(rv)) {
-        NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed");
-        return rv;
+        return Err(unwrapBlockElementResult.unwrapErr());
       }
+      unwrapBlockElementResult.MoveCaretPointTo(
+          pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
       firstContent = lastContent = blockElement = nullptr;
       continue;
     }
@@ -8498,18 +8482,13 @@ nsresult HTMLEditor::RemoveBlockContainerElements(
       NS_WARNING(
           "HTMLEditor::RemoveBlockContainerElementWithTransactionBetween() "
           "failed");
-      return unwrapBlockElementResult.unwrapErr();
-    }
-    nsresult rv = unwrapBlockElementResult.SuggestCaretPointTo(
-        *this, {SuggestCaret::OnlyIfHasSuggestion,
-                SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
-    if (NS_FAILED(rv)) {
-      NS_WARNING("SplitRangeOffFromNodeResult::SuggestCaretPointTo() failed");
-      return rv;
+      return Err(unwrapBlockElementResult.unwrapErr());
     }
+    unwrapBlockElementResult.MoveCaretPointTo(
+        pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
     firstContent = lastContent = blockElement = nullptr;
   }
-  return NS_OK;
+  return pointToPutCaret;
 }
 
 Result
diff --git a/editor/libeditor/HTMLEditor.h b/editor/libeditor/HTMLEditor.h
index 2667a6b94e04..7c7306698fc2 100644
--- a/editor/libeditor/HTMLEditor.h
+++ b/editor/libeditor/HTMLEditor.h
@@ -1591,15 +1591,19 @@ class HTMLEditor final : public EditorBase,
       nsTArray>& aArrayOfContents);
 
   /**
-   * RemoveBlockContainerElements() removes all format blocks, table related
-   * element, etc in aArrayOfContents from the DOM tree.
-   * If aArrayOfContents has a format node, it will be removed and its contents
+   * RemoveBlockContainerElementsWithTransaction() removes all format blocks,
+   * table related element, etc in aArrayOfContents from the DOM tree. If
+   * aArrayOfContents has a format node, it will be removed and its contents
    * will be moved to where it was.
    * If aArrayOfContents has a table related element, 
  • ,
    or *
    , it will be removed and its contents will be moved to where it was. + * + * @return A suggest point to put caret if succeeded, but it may be + * unset if there is no suggestion. */ - [[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult RemoveBlockContainerElements( - nsTArray>& aArrayOfContents); + [[nodiscard]] MOZ_CAN_RUN_SCRIPT Result + RemoveBlockContainerElementsWithTransaction( + const nsTArray>& aArrayOfContents); /** * CreateOrChangeBlockContainerElement() formats all nodes in aArrayOfContents @@ -1633,10 +1637,12 @@ class HTMLEditor final : public EditorBase, * * @param aBlockType New block tag name. * If nsGkAtoms::normal or nsGkAtoms::_empty, - * RemoveBlockContainerElements() will be called. + * RemoveBlockContainerElementsWithTransaction() + * will be called. * If nsGkAtoms::blockquote, * MoveNodesIntoNewBlockquoteElement() will be - * called. Otherwise, + * called. + * Otherwise, * CreateOrChangeBlockContainerElement() will be * called. */ From 5cf73489a8ee6a4637ef2731a38fe792d19c08fb Mon Sep 17 00:00:00 2001 From: Lee Salzman Date: Thu, 16 Jun 2022 03:39:41 +0000 Subject: [PATCH 61/64] Bug 1769082 - Avoid divide-by-zero in Skia's luminosity blend mode. r=jrmuizel,gfx-reviewers This applies a fix that is present in Skia's HW luminosity blend mode to its CPU pipeline so that the luminosity mode no longer divides by zero, thus avoiding infs and nans. Differential Revision: https://phabricator.services.mozilla.com/D149030 --- gfx/skia/skia/include/private/SkNx.h | 2 ++ .../skia/src/opts/SkRasterPipeline_opts.h | 4 ++-- layout/reftests/bugs/1769082-1-ref.html | 19 ++++++++++++++++++ layout/reftests/bugs/1769082-1.html | 20 +++++++++++++++++++ layout/reftests/bugs/reftest.list | 1 + 5 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 layout/reftests/bugs/1769082-1-ref.html create mode 100644 layout/reftests/bugs/1769082-1.html diff --git a/gfx/skia/skia/include/private/SkNx.h b/gfx/skia/skia/include/private/SkNx.h index 4bc0cfa72e9f..06a6df9af2af 100644 --- a/gfx/skia/skia/include/private/SkNx.h +++ b/gfx/skia/skia/include/private/SkNx.h @@ -320,7 +320,9 @@ private: V operator* (const SkNx& x, T y) { return x * SkNx(y); } V operator/ (const SkNx& x, T y) { return x / SkNx(y); } V operator& (const SkNx& x, T y) { return x & SkNx(y); } + V operator&&(const SkNx& x, const SkNx& y) { return x & y; } V operator| (const SkNx& x, T y) { return x | SkNx(y); } + V operator||(const SkNx& x, const SkNx& y) { return x | y; } V operator^ (const SkNx& x, T y) { return x ^ SkNx(y); } V operator==(const SkNx& x, T y) { return x == SkNx(y); } V operator!=(const SkNx& x, T y) { return x != SkNx(y); } diff --git a/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h b/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h index 5731f5863de6..aea70141a6f4 100644 --- a/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h +++ b/gfx/skia/skia/src/opts/SkRasterPipeline_opts.h @@ -1595,8 +1595,8 @@ SI void clip_color(F* r, F* g, F* b, F a) { l = lum(*r, *g, *b); auto clip = [=](F c) { - c = if_then_else(mn >= 0, c, l + (c - l) * ( l) / (l - mn) ); - c = if_then_else(mx > a, l + (c - l) * (a - l) / (mx - l), c); + c = if_then_else(mn < 0 && l != mn, l + (c - l) * ( l) / (l - mn), c); + c = if_then_else(mx > a && l != mx, l + (c - l) * (a - l) / (mx - l), c); c = max(c, 0); // Sometimes without this we may dip just a little negative. return c; }; diff --git a/layout/reftests/bugs/1769082-1-ref.html b/layout/reftests/bugs/1769082-1-ref.html new file mode 100644 index 000000000000..db9531d1a576 --- /dev/null +++ b/layout/reftests/bugs/1769082-1-ref.html @@ -0,0 +1,19 @@ + + + +
    + +
    + + diff --git a/layout/reftests/bugs/1769082-1.html b/layout/reftests/bugs/1769082-1.html new file mode 100644 index 000000000000..fd5c847f9e33 --- /dev/null +++ b/layout/reftests/bugs/1769082-1.html @@ -0,0 +1,20 @@ + + + +
    + +
    + + diff --git a/layout/reftests/bugs/reftest.list b/layout/reftests/bugs/reftest.list index 3752dcc60081..6d97c71b9a9b 100644 --- a/layout/reftests/bugs/reftest.list +++ b/layout/reftests/bugs/reftest.list @@ -2116,6 +2116,7 @@ pref(image.downscale-during-decode.enabled,true) == 1744468-1.html 1744468-1-ref == 1747272-1.html 1747272-1-ref.html == 1750146-1.html 1750146-1-ref.html == 1735265-1.html 1735265-1-ref.html +fuzzy(0-1,0-1000) == 1769082-1.html 1769082-1-ref.html == 1773484.html 1773484-ref.html # The following tests are skipped on Android since Android doesn't deal very From a68bf5548f301843039521e0ec4ca4ace805c84b Mon Sep 17 00:00:00 2001 From: Mike Hommey Date: Thu, 16 Jun 2022 04:47:44 +0000 Subject: [PATCH 62/64] Bug 1774515 - Upgrade clang to 14.0.5. r=firefox-build-system-reviewers,andi Differential Revision: https://phabricator.services.mozilla.com/D149467 --- taskcluster/ci/fetch/toolchains.yml | 4 ++-- tools/clang-tidy/config.yaml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/taskcluster/ci/fetch/toolchains.yml b/taskcluster/ci/fetch/toolchains.yml index 838082ace680..63160e7ab4a7 100644 --- a/taskcluster/ci/fetch/toolchains.yml +++ b/taskcluster/ci/fetch/toolchains.yml @@ -347,11 +347,11 @@ clang-5.0: revision: 6a075b6de4cafebec9ca1ff9eec7229a617c93f6 clang-14: - description: clang 14.0.4 source code + description: clang 14.0.5 source code fetch: type: git repo: https://github.com/llvm/llvm-project - revision: 29f1039a7285a5c3a9c353d054140bf2556d4c4d + revision: 4bc1d0b51c8e488d78ab69c8b19cfbcd1f7db6a4 clang-trunk: description: clang main branch source code diff --git a/tools/clang-tidy/config.yaml b/tools/clang-tidy/config.yaml index a869f423b225..6b8654de8846 100644 --- a/tools/clang-tidy/config.yaml +++ b/tools/clang-tidy/config.yaml @@ -19,7 +19,7 @@ platforms: # Minimum clang-tidy version that is required for all the following checkers # to work properly. # This is also used by 'mach clang-format' -package_version: "14.0.4" +package_version: "14.0.5" clang_checkers: - name: -* publish: !!bool no From 7397449189c070e6ee54b2b1e8a28857864ee394 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Thu, 16 Jun 2022 05:03:04 +0000 Subject: [PATCH 63/64] Bug 1774511 - Use more typed units in AppWindow. r=tnikkel Doesn't change behavior but hopefully makes code easier to follow / prove correct. Differential Revision: https://phabricator.services.mozilla.com/D149462 --- xpfe/appshell/AppWindow.cpp | 144 +++++++++++++++--------------------- xpfe/appshell/AppWindow.h | 3 + 2 files changed, 62 insertions(+), 85 deletions(-) diff --git a/xpfe/appshell/AppWindow.cpp b/xpfe/appshell/AppWindow.cpp index 4636faf705ac..d5b6c0cf3baa 100644 --- a/xpfe/appshell/AppWindow.cpp +++ b/xpfe/appshell/AppWindow.cpp @@ -798,7 +798,7 @@ NS_IMETHODIMP AppWindow::GetPositionAndSize(int32_t* x, int32_t* y, int32_t* cx, NS_IMETHODIMP AppWindow::Center(nsIAppWindow* aRelative, bool aScreen, bool aAlert) { - int32_t left, top, width, height, ourWidth, ourHeight; + DesktopIntRect rect; bool screenCoordinates = false, windowCoordinates = false; nsresult result; @@ -812,34 +812,22 @@ NS_IMETHODIMP AppWindow::Center(nsIAppWindow* aRelative, bool aScreen, nsCOMPtr screenmgr = do_GetService("@mozilla.org/gfx/screenmanager;1", &result); - if (NS_FAILED(result)) return result; + if (NS_FAILED(result)) { + return result; + } nsCOMPtr screen; if (aRelative) { - nsCOMPtr base(do_QueryInterface(aRelative, &result)); + nsCOMPtr base(do_QueryInterface(aRelative)); if (base) { - // get window rect - result = base->GetPositionAndSize(&left, &top, &width, &height); - if (NS_SUCCEEDED(result)) { - double scale; - if (NS_SUCCEEDED(base->GetDevicePixelsPerDesktopPixel(&scale))) { - left = NSToIntRound(left / scale); - top = NSToIntRound(top / scale); - width = NSToIntRound(width / scale); - height = NSToIntRound(height / scale); - } - // if centering on screen, convert that to the corresponding screen - if (aScreen) - screenmgr->ScreenForRect(left, top, width, height, - getter_AddRefs(screen)); - else - windowCoordinates = true; + rect = RoundedToInt(base->GetPositionAndSize() / + base->DevicePixelsPerDesktopPixel()); + // if centering on screen, convert that to the corresponding screen + if (aScreen) { + screen = screenmgr->ScreenForRect(rect); } else { - // something's wrong with the reference window. - // fall back to the primary screen - aRelative = 0; - aScreen = true; + windowCoordinates = true; } } } @@ -852,35 +840,31 @@ NS_IMETHODIMP AppWindow::Center(nsIAppWindow* aRelative, bool aScreen, } if (aScreen && screen) { - screen->GetAvailRectDisplayPix(&left, &top, &width, &height); + rect = screen->GetAvailRectDisplayPix(); screenCoordinates = true; } - if (screenCoordinates || windowCoordinates) { - NS_ASSERTION(mWindow, "what, no window?"); - double scale = mWindow->GetDesktopToDeviceScale().scale; - GetSize(&ourWidth, &ourHeight); - int32_t scaledWidth, scaledHeight; - scaledWidth = NSToIntRound(ourWidth / scale); - scaledHeight = NSToIntRound(ourHeight / scale); - left += (width - scaledWidth) / 2; - top += (height - scaledHeight) / (aAlert ? 3 : 2); - if (windowCoordinates) { - mWindow->ConstrainPosition(false, &left, &top); - } - SetPosition(left * scale, top * scale); - - // If moving the window caused it to change size, - // re-do the centering. - int32_t newWidth, newHeight; - GetSize(&newWidth, &newHeight); - if (newWidth != ourWidth || newHeight != ourHeight) { - return Center(aRelative, aScreen, aAlert); - } - return NS_OK; + if (!screenCoordinates && !windowCoordinates) { + return NS_ERROR_FAILURE; } - return NS_ERROR_FAILURE; + NS_ASSERTION(mWindow, "what, no window?"); + const LayoutDeviceIntSize ourDevSize = GetSize(); + const DesktopIntSize ourSize = + RoundedToInt(ourDevSize / DevicePixelsPerDesktopPixel()); + rect.x += (rect.width - ourSize.width) / 2; + rect.y += (rect.height - ourSize.height) / (aAlert ? 3 : 2); + if (windowCoordinates) { + mWindow->ConstrainPosition(false, &rect.x, &rect.y); + } + + SetPositionDesktopPix(rect.x, rect.y); + + // If moving the window caused it to change size, re-do the centering. + if (GetSize() != ourDevSize) { + return Center(aRelative, aScreen, aAlert); + } + return NS_OK; } NS_IMETHODIMP AppWindow::Repaint(bool aForce) { @@ -1244,67 +1228,57 @@ bool AppWindow::LoadPositionFromXUL(int32_t aSpecWidth, int32_t aSpecHeight) { nsCOMPtr windowElement = GetWindowDOMElement(); NS_ENSURE_TRUE(windowElement, false); - int32_t currX = 0; - int32_t currY = 0; - int32_t currWidth = 0; - int32_t currHeight = 0; - nsresult errorCode; - int32_t temp; - - GetPositionAndSize(&currX, &currY, &currWidth, &currHeight); + const LayoutDeviceIntRect devRect = GetPositionAndSize(); // Convert to global display pixels for consistent window management across // screens with diverse resolutions - double devToDesktopScale = 1.0 / DevicePixelsPerDesktopPixel().scale; - currX = NSToIntRound(currX * devToDesktopScale); - currY = NSToIntRound(currY * devToDesktopScale); + const DesktopIntPoint curPoint = + RoundedToInt(devRect.TopLeft() / DevicePixelsPerDesktopPixel()); // For size, use specified value if > 0, else current value - double devToCSSScale = 1.0 / UnscaledDevicePixelsPerCSSPixel().scale; - int32_t cssWidth = - aSpecWidth > 0 ? aSpecWidth : NSToIntRound(currWidth * devToCSSScale); - int32_t cssHeight = - aSpecHeight > 0 ? aSpecHeight : NSToIntRound(currHeight * devToCSSScale); + CSSIntSize cssSize(aSpecWidth, aSpecHeight); + { + CSSIntSize currentSize = + RoundedToInt(devRect.Size() / UnscaledDevicePixelsPerCSSPixel()); + if (aSpecHeight <= 0) { + cssSize.height = currentSize.height; + } + if (aSpecWidth <= 0) { + cssSize.width = currentSize.width; + } + } // Obtain the position information from the element. - int32_t specX = currX; - int32_t specY = currY; nsAutoString posString; - + DesktopIntPoint specPoint = curPoint; + nsresult errorCode; windowElement->GetAttribute(SCREENX_ATTRIBUTE, posString); - temp = posString.ToInteger(&errorCode); + int32_t temp = posString.ToInteger(&errorCode); if (NS_SUCCEEDED(errorCode)) { - specX = temp; + specPoint.x = temp; gotPosition = true; } windowElement->GetAttribute(SCREENY_ATTRIBUTE, posString); temp = posString.ToInteger(&errorCode); if (NS_SUCCEEDED(errorCode)) { - specY = temp; + specPoint.y = temp; gotPosition = true; } if (gotPosition) { - // our position will be relative to our parent, if any + // Our position will be relative to our parent, if any nsCOMPtr parent(do_QueryReferent(mParentWindow)); if (parent) { - int32_t parentX, parentY; - if (NS_SUCCEEDED(parent->GetPosition(&parentX, &parentY))) { - double scale; - if (NS_SUCCEEDED(parent->GetDevicePixelsPerDesktopPixel(&scale))) { - parentX = NSToIntRound(parentX / scale); - parentY = NSToIntRound(parentY / scale); - } - specX += parentX; - specY += parentY; - } + const DesktopIntPoint parentPos = RoundedToInt( + parent->GetPosition() / parent->DevicePixelsPerDesktopPixel()); + specPoint += parentPos; } else { - StaggerPosition(specX, specY, cssWidth, cssHeight); + StaggerPosition(specPoint.x, specPoint.y, cssSize.width, cssSize.height); } } - mWindow->ConstrainPosition(false, &specX, &specY); - if (specX != currX || specY != currY) { - SetPositionDesktopPix(specX, specY); + mWindow->ConstrainPosition(false, &specPoint.x, &specPoint.y); + if (specPoint != curPoint) { + SetPositionDesktopPix(specPoint.x, specPoint.y); } return gotPosition; @@ -1392,7 +1366,7 @@ void AppWindow::SetSpecifiedSize(int32_t aSpecWidth, int32_t aSpecHeight) { // Convert specified values to device pixels, and resize if needed auto newSize = RoundedToInt(CSSIntSize(aSpecWidth, aSpecHeight) * UnscaledDevicePixelsPerCSSPixel()); - if (newSize != nsIBaseWindow::GetSize()) { + if (newSize != GetSize()) { SetSize(newSize.width, newSize.height, false); } } diff --git a/xpfe/appshell/AppWindow.h b/xpfe/appshell/AppWindow.h index d6c385ca201d..1d84d443bfa2 100644 --- a/xpfe/appshell/AppWindow.h +++ b/xpfe/appshell/AppWindow.h @@ -140,6 +140,9 @@ class AppWindow final : public nsIBaseWindow, void IgnoreXULSizeMode(bool aEnable) { mIgnoreXULSizeMode = aEnable; } void WasRegistered() { mRegistered = true; } + using nsIBaseWindow::GetSize; + using nsIBaseWindow::GetPositionAndSize; + // AppWindow methods... nsresult Initialize(nsIAppWindow* aParent, nsIAppWindow* aOpener, int32_t aInitialWidth, int32_t aInitialHeight, From 5bce79e64b407eefb02bc5e483488f501a8d94ac Mon Sep 17 00:00:00 2001 From: stransky Date: Thu, 16 Jun 2022 06:22:33 +0000 Subject: [PATCH 64/64] Bug 1758948 [FFmpeg] Use AVFrame::pts instead of AVFrame::pkt_pts on ffmpeg 4.x r=alwu AVFrame::pkt_pts has been deprecated and gives us wrong values for AV1 VA-API. Let's use AVFrame::pts instead on ffmpeg 4.x as well as we use on ffmpeg 5.0 where AVFrame::pkt_pts is removed. Differential Revision: https://phabricator.services.mozilla.com/D149386 --- dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp b/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp index a489539b5df3..68a6f270584c 100644 --- a/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp +++ b/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp @@ -774,7 +774,7 @@ void FFmpegVideoDecoder::InitVAAPICodecContext() { #endif static int64_t GetFramePts(AVFrame* aFrame) { -#if LIBAVCODEC_VERSION_MAJOR > 58 +#if LIBAVCODEC_VERSION_MAJOR > 57 return aFrame->pts; #else return aFrame->pkt_pts;