diff options
Diffstat (limited to 'js/xpconnect/tests/unit')
146 files changed, 5597 insertions, 0 deletions
diff --git a/js/xpconnect/tests/unit/CatRegistrationComponents.manifest b/js/xpconnect/tests/unit/CatRegistrationComponents.manifest new file mode 100644 index 0000000000..11646b0282 --- /dev/null +++ b/js/xpconnect/tests/unit/CatRegistrationComponents.manifest @@ -0,0 +1,2 @@ +category test-cat CatRegisteredComponent @unit.test.com/cat-registered-component;1
+category test-cat CatAppRegisteredComponent @unit.test.com/cat-app-registered-component;1 application={adb42a9a-0d19-4849-bf4d-627614ca19be}
diff --git a/js/xpconnect/tests/unit/bogus_element_type.jsm b/js/xpconnect/tests/unit/bogus_element_type.jsm new file mode 100644 index 0000000000..882ca56809 --- /dev/null +++ b/js/xpconnect/tests/unit/bogus_element_type.jsm @@ -0,0 +1 @@ +var EXPORTED_SYMBOLS = [{}]; diff --git a/js/xpconnect/tests/unit/bogus_exports_type.jsm b/js/xpconnect/tests/unit/bogus_exports_type.jsm new file mode 100644 index 0000000000..4b306e4e89 --- /dev/null +++ b/js/xpconnect/tests/unit/bogus_exports_type.jsm @@ -0,0 +1 @@ +var EXPORTED_SYMBOLS = "not an array"; diff --git a/js/xpconnect/tests/unit/bug451678_subscript.js b/js/xpconnect/tests/unit/bug451678_subscript.js new file mode 100644 index 0000000000..72ff49a2d6 --- /dev/null +++ b/js/xpconnect/tests/unit/bug451678_subscript.js @@ -0,0 +1,5 @@ +var tags = [];
+function makeTags() {}
+
+// This will be the return value of the script.
+42
diff --git a/js/xpconnect/tests/unit/component-blob.js b/js/xpconnect/tests/unit/component-blob.js new file mode 100644 index 0000000000..9224246dac --- /dev/null +++ b/js/xpconnect/tests/unit/component-blob.js @@ -0,0 +1,74 @@ +/* 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 {ComponentUtils} = ChromeUtils.import("resource://gre/modules/ComponentUtils.jsm"); +Cu.importGlobalProperties(['Blob', 'File']); + +const Assert = { + ok(cond, text) { + // we don't have the test harness' utilities in this scope, so we need this + // little helper. In the failure case, the exception is propagated to the + // caller in the main run_test() function, and the test fails. + if (!cond) + throw "Failed check: " + text; + } +}; + +function BlobComponent() { + this.wrappedJSObject = this; +} +BlobComponent.prototype = +{ + doTest: function() { + // throw if anything goes wrong + let testContent = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>"; + // should be able to construct a file + var f1 = new Blob([testContent], {"type" : "text/xml"}); + + // do some tests + Assert.ok(f1 instanceof Blob, "Should be a DOM Blob"); + + Assert.ok(!(f1 instanceof File), "Should not be a DOM File"); + + Assert.ok(f1.type == "text/xml", "Wrong type"); + + Assert.ok(f1.size == testContent.length, "Wrong content size"); + + var f2 = new Blob(); + Assert.ok(f2.size == 0, "Wrong size"); + Assert.ok(f2.type == "", "Wrong type"); + + var threw = false; + try { + // Needs a valid ctor argument + var f2 = new Blob(Date(132131532)); + } catch (e) { + threw = true; + } + Assert.ok(threw, "Passing a random object should fail"); + + return true; + }, + + // nsIClassInfo + information for XPCOM registration code in + // ComponentUtils.jsm + classDescription: "Blob in components scope code", + classID: Components.ID("{06215993-a3c2-41e3-bdfd-0a3a2cc0b65c}"), + contractID: "@mozilla.org/tests/component-blob;1", + + // nsIClassInfo + flags: 0, + + interfaces: [Ci.nsIClassInfo], + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: ChromeUtils.generateQI(["nsIClassInfo"]) +}; + +var gComponentsArray = [BlobComponent]; +this.NSGetFactory = ComponentUtils.generateNSGetFactory(gComponentsArray); diff --git a/js/xpconnect/tests/unit/component-blob.manifest b/js/xpconnect/tests/unit/component-blob.manifest new file mode 100644 index 0000000000..ac264c06d5 --- /dev/null +++ b/js/xpconnect/tests/unit/component-blob.manifest @@ -0,0 +1,2 @@ +component {06215993-a3c2-41e3-bdfd-0a3a2cc0b65c} component-blob.js +contract @mozilla.org/tests/component-blob;1 {06215993-a3c2-41e3-bdfd-0a3a2cc0b65c} diff --git a/js/xpconnect/tests/unit/component-file.js b/js/xpconnect/tests/unit/component-file.js new file mode 100644 index 0000000000..f78edfb3fc --- /dev/null +++ b/js/xpconnect/tests/unit/component-file.js @@ -0,0 +1,105 @@ +/* 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 {ComponentUtils} = ChromeUtils.import("resource://gre/modules/ComponentUtils.jsm"); +Cu.importGlobalProperties(['File']); + + +const Assert = { + ok(cond, text) { + // we don't have the test harness' utilities in this scope, so we need this + // little helper. In the failure case, the exception is propagated to the + // caller in the main run_test() function, and the test fails. + if (!cond) + throw "Failed check: " + text; + } +}; + +function FileComponent() { + this.wrappedJSObject = this; +} +FileComponent.prototype = +{ + doTest: function(cb) { + // throw if anything goes wrong + + // find the current directory path + var file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("CurWorkD", Ci.nsIFile); + file.append("xpcshell.ini"); + + // should be able to construct a file + var f1, f2; + Promise.all([ + File.createFromFileName(file.path).then(f => { f1 = f; }), + File.createFromNsIFile(file).then(f => { f2 = f; }), + ]) + .then(() => { + // do some tests + Assert.ok(f1 instanceof File, "Should be a DOM File"); + Assert.ok(f2 instanceof File, "Should be a DOM File"); + + Assert.ok(f1.name == "xpcshell.ini", "Should be the right file"); + Assert.ok(f2.name == "xpcshell.ini", "Should be the right file"); + + Assert.ok(f1.type == "", "Should be the right type"); + Assert.ok(f2.type == "", "Should be the right type"); + }) + .then(() => { + var threw = false; + try { + // Needs a ctor argument + var f7 = new File(); + } catch (e) { + threw = true; + } + Assert.ok(threw, "No ctor arguments should throw"); + + var threw = false; + try { + // Needs a valid ctor argument + var f7 = new File(Date(132131532)); + } catch (e) { + threw = true; + } + Assert.ok(threw, "Passing a random object should fail"); + + // Directories fail + var dir = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("CurWorkD", Ci.nsIFile); + return File.createFromNsIFile(dir) + }) + .then(() => { + Assert.ok(false, "Can't create a File object for a directory"); + }, () => { + Assert.ok(true, "Can't create a File object for a directory"); + }) + .then(() => { + cb(true); + }); + }, + + // nsIClassInfo + information for XPCOM registration code in + // ComponentUtils.jsm + classDescription: "File in components scope code", + classID: Components.ID("{da332370-91d4-464f-a730-018e14769cab}"), + contractID: "@mozilla.org/tests/component-file;1", + + // nsIClassInfo + flags: 0, + + interfaces: [Ci.nsIClassInfo], + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: ChromeUtils.generateQI(["nsIClassInfo"]) +}; + +var gComponentsArray = [FileComponent]; +this.NSGetFactory = ComponentUtils.generateNSGetFactory(gComponentsArray); diff --git a/js/xpconnect/tests/unit/component-file.manifest b/js/xpconnect/tests/unit/component-file.manifest new file mode 100644 index 0000000000..f865f333d8 --- /dev/null +++ b/js/xpconnect/tests/unit/component-file.manifest @@ -0,0 +1,2 @@ +component {da332370-91d4-464f-a730-018e14769cab} component-file.js +contract @mozilla.org/tests/component-file;1 {da332370-91d4-464f-a730-018e14769cab}
\ No newline at end of file diff --git a/js/xpconnect/tests/unit/component_import.js b/js/xpconnect/tests/unit/component_import.js new file mode 100644 index 0000000000..a3675e49dc --- /dev/null +++ b/js/xpconnect/tests/unit/component_import.js @@ -0,0 +1,84 @@ +/* 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 {ComponentUtils} = ChromeUtils.import("resource://gre/modules/ComponentUtils.jsm"); + +function FooComponent() { + this.wrappedJSObject = this; +} +FooComponent.prototype = +{ + // nsIClassInfo + information for XPCOM registration code in ComponentUtils.jsm + classDescription: "Foo Component", + classID: Components.ID("{6b933fe6-6eba-4622-ac86-e4f654f1b474}"), + contractID: "@mozilla.org/tests/module-importer;1", + + // nsIClassInfo + flags: 0, + + get interfaces() { + var interfaces = [Ci.nsIClassInfo]; + + // Guerilla test for line numbers hiding in this method + var threw = true; + try { + thereIsNoSuchIdentifier; + threw = false; + } catch (ex) { + Assert.ok(ex.lineNumber == 26); + } + Assert.ok(threw); + + return interfaces; + }, + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: function QueryInterface(aIID) { + if (aIID.equals(Ci.nsIClassInfo) || + aIID.equals(Ci.nsISupports)) + return this; + + throw Cr.NS_ERROR_NO_INTERFACE; + } +}; + +function BarComponent() { +} +BarComponent.prototype = +{ + // nsIClassInfo + information for XPCOM registration code in + // ComponentUtils.jsm + classDescription: "Module importer test 2", + classID: Components.ID("{708a896a-b48d-4bff-906e-fc2fd134b296}"), + contractID: "@mozilla.org/tests/module-importer;2", + + // nsIClassInfo + flags: 0, + + interfaces: [Ci.nsIClassInfo], + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: ChromeUtils.generateQI(["nsIClassInfo"]) +}; + +const Assert = { + ok(cond, text) { + // we don't have the test harness' utilities in this scope, so we need this + // little helper. In the failure case, the exception is propagated to the + // caller in the main run_test() function, and the test fails. + if (!cond) + throw "Failed check: " + text; + } +}; + +var gComponentsArray = [FooComponent, BarComponent]; +this.NSGetFactory = ComponentUtils.generateNSGetFactory(gComponentsArray); diff --git a/js/xpconnect/tests/unit/component_import.manifest b/js/xpconnect/tests/unit/component_import.manifest new file mode 100644 index 0000000000..952c2dd4d1 --- /dev/null +++ b/js/xpconnect/tests/unit/component_import.manifest @@ -0,0 +1,5 @@ +component {6b933fe6-6eba-4622-ac86-e4f654f1b474} component_import.js
+contract @mozilla.org/tests/module-importer;1 {6b933fe6-6eba-4622-ac86-e4f654f1b474}
+
+component {708a896a-b48d-4bff-906e-fc2fd134b296} component_import.js
+contract @mozilla.org/tests/module-importer;2 {708a896a-b48d-4bff-906e-fc2fd134b296}
diff --git a/js/xpconnect/tests/unit/environment_checkscript.jsm b/js/xpconnect/tests/unit/environment_checkscript.jsm new file mode 100644 index 0000000000..b4dc452b8e --- /dev/null +++ b/js/xpconnect/tests/unit/environment_checkscript.jsm @@ -0,0 +1,13 @@ +var EXPORTED_SYMBOLS = ["bound"]; + +var bound = ""; + +try { void vu; bound += "vu,"; } catch (e) {} +try { void vq; bound += "vq,"; } catch (e) {} +try { void vl; bound += "vl,"; } catch (e) {} +try { void gt; bound += "gt,"; } catch (e) {} +try { void ed; bound += "ed,"; } catch (e) {} +try { void ei; bound += "ei,"; } catch (e) {} +try { void fo; bound += "fo,"; } catch (e) {} +try { void fi; bound += "fi,"; } catch (e) {} +try { void fd; bound += "fd,"; } catch (e) {} diff --git a/js/xpconnect/tests/unit/environment_loadscript.jsm b/js/xpconnect/tests/unit/environment_loadscript.jsm new file mode 100644 index 0000000000..eb8b7070a5 --- /dev/null +++ b/js/xpconnect/tests/unit/environment_loadscript.jsm @@ -0,0 +1,18 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +var EXPORTED_SYMBOLS = ["target", "bound"]; + +var bound = ""; +var target = {}; +Services.scriptloader.loadSubScript("resource://test/environment_script.js", target); + +// Check global bindings +try { void vu; bound += "vu,"; } catch (e) {} +try { void vq; bound += "vq,"; } catch (e) {} +try { void vl; bound += "vl,"; } catch (e) {} +try { void gt; bound += "gt,"; } catch (e) {} +try { void ed; bound += "ed,"; } catch (e) {} +try { void ei; bound += "ei,"; } catch (e) {} +try { void fo; bound += "fo,"; } catch (e) {} +try { void fi; bound += "fi,"; } catch (e) {} +try { void fd; bound += "fd,"; } catch (e) {} diff --git a/js/xpconnect/tests/unit/environment_script.js b/js/xpconnect/tests/unit/environment_script.js new file mode 100644 index 0000000000..18490541ad --- /dev/null +++ b/js/xpconnect/tests/unit/environment_script.js @@ -0,0 +1,14 @@ +let strict = (function() { return this; })() === undefined; + +// Allow this to be used as a JSM +var EXPORTED_SYMBOLS = []; + +if (!strict) vu = 1; // Unqualified Variable +var vq = 2; // Qualified Variable +let vl = 3; // Lexical +this.gt = 4; // Global This +eval("this.ed = 5"); // Direct Eval +(1,eval)("this.ei = 6"); // Indirect Eval +(new Function("this.fo = 7"))(); // Dynamic Function Object +if (!strict) (function() { this.fi = 8; })(); // Indirect Function This +function fd_() { this.fd = 9; }; if (!strict) fd_(); // Direct Function Implicit diff --git a/js/xpconnect/tests/unit/file_simple_script.js b/js/xpconnect/tests/unit/file_simple_script.js new file mode 100644 index 0000000000..af20291400 --- /dev/null +++ b/js/xpconnect/tests/unit/file_simple_script.js @@ -0,0 +1 @@ +this.bar = ({foo: "®"}); diff --git a/js/xpconnect/tests/unit/head_ongc.js b/js/xpconnect/tests/unit/head_ongc.js new file mode 100644 index 0000000000..14caf7aa37 --- /dev/null +++ b/js/xpconnect/tests/unit/head_ongc.js @@ -0,0 +1,36 @@ +var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var {addDebuggerToGlobal, addSandboxedDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); + +const testingFunctions = Cu.getJSTestingFunctions(); +const systemPrincipal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal); + +function addTestingFunctionsToGlobal(global) { + for (let k in testingFunctions) { + global[k] = testingFunctions[k]; + } + global.print = info; + global.newGlobal = newGlobal; + addDebuggerToGlobal(global); +} + +function newGlobal() { + const global = new Cu.Sandbox(systemPrincipal, { freshZone: true }); + addTestingFunctionsToGlobal(global); + return global; +} + +addTestingFunctionsToGlobal(this); + +function executeSoon(f) { + Services.tm.dispatchToMainThread({ run: f }); +} + +// The onGarbageCollection tests don't play well gczeal settings and lead to +// intermittents. +if (typeof gczeal == "function") { + gczeal(0); +} + +// Make sure to GC before we start the test, so that no zones are scheduled for +// GC before we start testing onGarbageCollection hooks. +gc(); diff --git a/js/xpconnect/tests/unit/head_watchdog.js b/js/xpconnect/tests/unit/head_watchdog.js new file mode 100644 index 0000000000..a23b2f970f --- /dev/null +++ b/js/xpconnect/tests/unit/head_watchdog.js @@ -0,0 +1,116 @@ +/* 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/. */ + +// +// Pref management. +// + +var {PromiseTestUtils} = ChromeUtils.import("resource://testing-common/PromiseTestUtils.jsm"); + +/////////////////// +// +// Whitelisting these tests. +// As part of bug 1077403, the shutdown crash should be fixed. +// +// These tests may crash intermittently on shutdown if the DOM Promise uncaught +// rejection observers are still registered when the watchdog operates. +PromiseTestUtils.thisTestLeaksUncaughtRejectionsAndShouldBeFixed(); + +var gPrefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); + +function setWatchdogEnabled(enabled) { + gPrefs.setBoolPref("dom.use_watchdog", enabled); +} + +function isWatchdogEnabled() { + return gPrefs.getBoolPref("dom.use_watchdog"); +} + +function setScriptTimeout(seconds) { + var oldTimeout = gPrefs.getIntPref("dom.max_script_run_time"); + gPrefs.setIntPref("dom.max_script_run_time", seconds); + return oldTimeout; +} + +// +// Utilities. +// + +function busyWait(ms) { + var start = new Date(); + while ((new Date()) - start < ms) {} +} + +function do_log_info(aMessage) +{ + print("TEST-INFO | " + _TEST_FILE + " | " + aMessage); +} + +// We don't use do_execute_soon, because that inserts a +// do_test_{pending,finished} pair that gets screwed up when we terminate scripts +// from the operation callback. +function executeSoon(fn) { + var tm = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); + tm.dispatchToMainThread({run: fn}); +} + +// +// Asynchronous watchdog diagnostics. +// +// When running, the watchdog wakes up every second, and fires the operation +// callback if the script has been running for >= the minimum script timeout. +// As such, if the script timeout is 1 second, a script should never be able to +// run for two seconds or longer without servicing the operation callback. +// We wait 3 seconds, just to be safe. +// + +function checkWatchdog(expectInterrupt) { + var oldTimeout = setScriptTimeout(1); + var lastWatchdogWakeup = Cu.getWatchdogTimestamp("WatchdogWakeup"); + + return new Promise(resolve => { + let inBusyWait = false; + setInterruptCallback(function() { + // If the watchdog didn't actually trigger the operation callback, ignore + // this call. This allows us to test the actual watchdog behavior without + // interference from other sites where we trigger the operation callback. + if (lastWatchdogWakeup == Cu.getWatchdogTimestamp("WatchdogWakeup")) { + return true; + } + if (!inBusyWait) { + Assert.ok(true, "Not in busy wait, ignoring interrupt callback"); + return true; + } + + Assert.ok(expectInterrupt, "Interrupt callback fired"); + setInterruptCallback(undefined); + setScriptTimeout(oldTimeout); + // Schedule the promise for resolution before we kill this script. + executeSoon(resolve); + return false; + }); + + executeSoon(function() { + inBusyWait = true; + busyWait(3000); + inBusyWait = false; + Assert.ok(!expectInterrupt, "Interrupt callback didn't fire"); + setInterruptCallback(undefined); + setScriptTimeout(oldTimeout); + resolve(); + }); + }); +} + +function run_test() { + + // Run async. + do_test_pending(); + + // Run the async function. + testBody().then(() => { + do_test_finished(); + }); +} + diff --git a/js/xpconnect/tests/unit/importer.jsm b/js/xpconnect/tests/unit/importer.jsm new file mode 100644 index 0000000000..e6d2f184e6 --- /dev/null +++ b/js/xpconnect/tests/unit/importer.jsm @@ -0,0 +1 @@ +ChromeUtils.import("resource://test/syntax_error.jsm");
\ No newline at end of file diff --git a/js/xpconnect/tests/unit/recursive_importA.jsm b/js/xpconnect/tests/unit/recursive_importA.jsm new file mode 100644 index 0000000000..ac763354c4 --- /dev/null +++ b/js/xpconnect/tests/unit/recursive_importA.jsm @@ -0,0 +1,12 @@ +/* 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/. */ + +var EXPORTED_SYMBOLS = ["foo", "bar"]; + +function foo() { + return "foo"; +} + +var bar = {} +ChromeUtils.import("resource://test/recursive_importB.jsm", bar); diff --git a/js/xpconnect/tests/unit/recursive_importB.jsm b/js/xpconnect/tests/unit/recursive_importB.jsm new file mode 100644 index 0000000000..1bf84971b6 --- /dev/null +++ b/js/xpconnect/tests/unit/recursive_importB.jsm @@ -0,0 +1,13 @@ +/* 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/. */ + +var EXPORTED_SYMBOLS = ["baz", "qux"]; + +function baz() { + return "baz"; +} + +var qux = {} +ChromeUtils.import("resource://test/recursive_importA.jsm", qux); + diff --git a/js/xpconnect/tests/unit/syntax_error.jsm b/js/xpconnect/tests/unit/syntax_error.jsm new file mode 100644 index 0000000000..fca785bcdd --- /dev/null +++ b/js/xpconnect/tests/unit/syntax_error.jsm @@ -0,0 +1 @@ +bogusjs)( diff --git a/js/xpconnect/tests/unit/test_ComponentEnvironment.js b/js/xpconnect/tests/unit/test_ComponentEnvironment.js new file mode 100644 index 0000000000..97ea2d4567 --- /dev/null +++ b/js/xpconnect/tests/unit/test_ComponentEnvironment.js @@ -0,0 +1,22 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +let tgt = {}; + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +const a = ChromeUtils.import("resource://test/environment_script.js", tgt); +const b = ChromeUtils.import("resource://test/environment_checkscript.jsm", tgt); + +const isShared = Cu.getGlobalForObject(a) === Cu.getGlobalForObject(b); + + +// Components should not share namespace +if (isShared) { + todo_check_eq(tgt.bound, ""); + Assert.equal(tgt.bound, "ei,fo,", "Modules should have no shared non-eval bindings"); +} else { + Assert.equal(tgt.bound, "", "Modules should have no shared bindings"); +} diff --git a/js/xpconnect/tests/unit/test_FrameScriptEnvironment.js b/js/xpconnect/tests/unit/test_FrameScriptEnvironment.js new file mode 100644 index 0000000000..289a594a37 --- /dev/null +++ b/js/xpconnect/tests/unit/test_FrameScriptEnvironment.js @@ -0,0 +1,48 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +let ppmm = Services.ppmm.getChildAt(0); + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +add_task(async function test_bindings() { + let {strict, bound} = await new Promise(function(resolve) { + // Use a listener to get results from child + ppmm.addMessageListener("results", function listener(msg) { + ppmm.removeMessageListener("results", listener); + resolve(msg.data); + }); + + // Bind vars in first process script + ppmm.loadProcessScript("resource://test/environment_script.js", false); + + // Check visibility in second process script + ppmm.loadProcessScript(`data:, + let strict = (function() { return this; })() === undefined; + var bound = ""; + + try { void vu; bound += "vu,"; } catch (e) {} + try { void vq; bound += "vq,"; } catch (e) {} + try { void vl; bound += "vl,"; } catch (e) {} + try { void gt; bound += "gt,"; } catch (e) {} + try { void ed; bound += "ed,"; } catch (e) {} + try { void ei; bound += "ei,"; } catch (e) {} + try { void fo; bound += "fo,"; } catch (e) {} + try { void fi; bound += "fi,"; } catch (e) {} + try { void fd; bound += "fd,"; } catch (e) {} + + sendAsyncMessage("results", { strict, bound }); + `, false); + }); + + // FrameScript loader should share |this| access + if (strict) { + if (bound != "gt,ed,ei,fo,") + throw new Error("Unexpected global binding set - " + bound); + } else { + if (bound != "gt,ed,ei,fo,fi,fd,") + throw new Error("Unexpected global binding set - " + bound); + } +}); diff --git a/js/xpconnect/tests/unit/test_SubscriptLoaderEnvironment.js b/js/xpconnect/tests/unit/test_SubscriptLoaderEnvironment.js new file mode 100644 index 0000000000..e23fe1b68d --- /dev/null +++ b/js/xpconnect/tests/unit/test_SubscriptLoaderEnvironment.js @@ -0,0 +1,40 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +let tgt = {}; + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); + +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +Services.scriptloader.loadSubScript("resource://test/environment_script.js", tgt); + +var bound = ""; +var tgt_bound = ""; + +// Check global bindings +try { void vu; bound += "vu,"; } catch (e) {} +try { void vq; bound += "vq,"; } catch (e) {} +try { void vl; bound += "vl,"; } catch (e) {} +try { void gt; bound += "gt,"; } catch (e) {} +try { void ed; bound += "ed,"; } catch (e) {} +try { void ei; bound += "ei,"; } catch (e) {} +try { void fo; bound += "fo,"; } catch (e) {} +try { void fi; bound += "fi,"; } catch (e) {} +try { void fd; bound += "fd,"; } catch (e) {} + +// Check target bindings +for (var name of ["vu", "vq", "vl", "gt", "ed", "ei", "fo", "fi", "fd"]) + if (tgt.hasOwnProperty(name)) + tgt_bound += name + ","; + + +// Expected subscript loader behavior is as follows: +// - Qualified vars and |this| access occur on target object +// - Lexical vars occur on ExtensibleLexicalEnvironment of target object +// - Bareword assignments and global |this| access occur on caller's global +if (bound != "vu,ei,fo,fi,") + throw new Error("Unexpected global binding set - " + bound); +if (tgt_bound != "vq,gt,ed,fd,") + throw new Error("Unexpected target binding set - " + tgt_bound); diff --git a/js/xpconnect/tests/unit/test_SubscriptLoaderJSMEnvironment.js b/js/xpconnect/tests/unit/test_SubscriptLoaderJSMEnvironment.js new file mode 100644 index 0000000000..58f6dfc72d --- /dev/null +++ b/js/xpconnect/tests/unit/test_SubscriptLoaderJSMEnvironment.js @@ -0,0 +1,34 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +let tgt_load = {}; +let tgt_check = {}; + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); +const a = ChromeUtils.import("resource://test/environment_loadscript.jsm", tgt_load); +const b = ChromeUtils.import("resource://test/environment_checkscript.jsm", tgt_check); + +const isShared = Cu.getGlobalForObject(a) === Cu.getGlobalForObject(b); + +// Check target bindings +var tgt_subscript_bound = ""; +for (var name of ["vu", "vq", "vl", "gt", "ed", "ei", "fo", "fi", "fd"]) + if (tgt_load.target.hasOwnProperty(name)) + tgt_subscript_bound += name + ","; + +// Expected subscript loader behavior is as follows: +// - Qualified vars and |this| access occur on target object +// - Lexical vars occur on ExtensibleLexicalEnvironment of target object +// - Bareword assignments and global |this| access occur on caller's global +Assert.equal(tgt_load.bound, "vu,ei,fo,fi,", "Should have expected module binding set"); +Assert.equal(tgt_subscript_bound, "vq,gt,ed,fd,", "Should have expected subscript binding set"); + +// Components should not share namespace +if (isShared) { + todo_check_eq(tgt_check.bound, ""); + Assert.equal(tgt_check.bound, "ei,fo,", "Modules should have no shared non-eval bindings"); +} else { + Assert.equal(tgt_check.bound, "", "Modules should have no shared bindings"); +} diff --git a/js/xpconnect/tests/unit/test_SubscriptLoaderSandboxEnvironment.js b/js/xpconnect/tests/unit/test_SubscriptLoaderSandboxEnvironment.js new file mode 100644 index 0000000000..98ba5ef9c1 --- /dev/null +++ b/js/xpconnect/tests/unit/test_SubscriptLoaderSandboxEnvironment.js @@ -0,0 +1,37 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +let tgt = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal()); + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); +Services.scriptloader.loadSubScript("resource://test/environment_script.js", tgt); + +var bound = ""; +var tgt_bound = ""; + +// Check global bindings +try { void vu; bound += "vu,"; } catch (e) {} +try { void vq; bound += "vq,"; } catch (e) {} +try { void vl; bound += "vl,"; } catch (e) {} +try { void gt; bound += "gt,"; } catch (e) {} +try { void ed; bound += "ed,"; } catch (e) {} +try { void ei; bound += "ei,"; } catch (e) {} +try { void fo; bound += "fo,"; } catch (e) {} +try { void fi; bound += "fi,"; } catch (e) {} +try { void fd; bound += "fd,"; } catch (e) {} + +// Check target bindings +for (var name of ["vu", "vq", "vl", "gt", "ed", "ei", "fo", "fi", "fd"]) + if (tgt.hasOwnProperty(name)) + tgt_bound += name + ","; + + +// Expected subscript loader behavior with a Sandbox is as follows: +// - Lexicals occur on ExtensibleLexicalEnvironment of target +// - Everything else occurs on Sandbox global +if (bound != "") + throw new Error("Unexpected global binding set - " + bound); +if (tgt_bound != "vu,vq,gt,ed,ei,fo,fi,fd,") + throw new Error("Unexpected target binding set - " + tgt_bound); diff --git a/js/xpconnect/tests/unit/test_URLSearchParams.js b/js/xpconnect/tests/unit/test_URLSearchParams.js new file mode 100644 index 0000000000..fb2d203187 --- /dev/null +++ b/js/xpconnect/tests/unit/test_URLSearchParams.js @@ -0,0 +1,12 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["URLSearchParams"] }); + sb.equal = equal; + Cu.evalInSandbox('equal(new URLSearchParams("one=1&two=2").get("one"), "1");', + sb); + Cu.importGlobalProperties(["URLSearchParams"]); + Assert.equal(new URLSearchParams("one=1&two=2").get("one"), "1"); +} diff --git a/js/xpconnect/tests/unit/test_allowWaivers.js b/js/xpconnect/tests/unit/test_allowWaivers.js new file mode 100644 index 0000000000..b5a764e352 --- /dev/null +++ b/js/xpconnect/tests/unit/test_allowWaivers.js @@ -0,0 +1,29 @@ +function checkWaivers(from, allowed) { + var sb = new Cu.Sandbox('http://example.com'); + from.test = sb.eval('var o = {prop: 2, f: function() {return 42;}}; o'); + + // Make sure that |from| has Xrays to sb. + Assert.equal(from.eval('test.prop'), 2); + Assert.equal(from.eval('test.f'), undefined); + + // Make sure that waivability works as expected. + Assert.equal(from.eval('!!test.wrappedJSObject'), allowed); + Assert.equal(from.eval('XPCNativeWrapper.unwrap(test) !== test'), allowed); + + // Make a sandbox with the same principal as |from|, but without any waiver + // restrictions, and make sure that the waiver does not transfer. + var friend = new Cu.Sandbox(Cu.getObjectPrincipal(from)); + friend.test = from.test; + friend.eval('var waived = test.wrappedJSObject;'); + Assert.equal(friend.eval('waived.f()'), 42); + friend.from = from; + friend.eval('from.waived = waived'); + Assert.equal(from.eval('!!waived.f'), allowed); +} + +function run_test() { + checkWaivers(new Cu.Sandbox('http://example.com'), true); + checkWaivers(new Cu.Sandbox('http://example.com', {allowWaivers: false}), false); + checkWaivers(new Cu.Sandbox(['http://example.com']), true); + checkWaivers(new Cu.Sandbox(['http://example.com'], {allowWaivers: false}), false); +} diff --git a/js/xpconnect/tests/unit/test_allowedDomains.js b/js/xpconnect/tests/unit/test_allowedDomains.js new file mode 100644 index 0000000000..bc703a9f6d --- /dev/null +++ b/js/xpconnect/tests/unit/test_allowedDomains.js @@ -0,0 +1,41 @@ +function run_test() { + var sbMaster = Cu.Sandbox(["http://www.a.com", + "http://www.b.com", + "http://www.d.com"]); + var sbSubset = Cu.Sandbox(["http://www.d.com", + "http://www.a.com"]); + + var sbA = Cu.Sandbox("http://www.a.com"); + var sbB = Cu.Sandbox("http://www.b.com"); + var sbC = Cu.Sandbox("http://www.c.com"); + + sbMaster.objA = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbA); + sbMaster.objB = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbB); + sbMaster.objC = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbC); + sbMaster.objOwn = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbMaster); + + sbMaster.objSubset = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbSubset); + sbA.objMaster = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbMaster); + sbSubset.objMaster = Cu.evalInSandbox("var obj = {prop1:200}; obj", sbMaster); + + var ret; + ret = Cu.evalInSandbox("objA.prop1", sbMaster); + Assert.equal(ret, 200); + ret = Cu.evalInSandbox("objB.prop1", sbMaster); + Assert.equal(ret, 200); + ret = Cu.evalInSandbox("objSubset.prop1", sbMaster); + Assert.equal(ret, 200); + + function evalAndCatch(str, sb) { + try { + ret = Cu.evalInSandbox(str, sb); + Assert.ok(false, "unexpected pass") + } catch (e) { + Assert.ok(e.message && e.message.includes("Permission denied to access property")); + } + } + + evalAndCatch("objC.prop1", sbMaster); + evalAndCatch("objMaster.prop1", sbA); + evalAndCatch("objMaster.prop1", sbSubset); +} diff --git a/js/xpconnect/tests/unit/test_allowedDomainsXHR.js b/js/xpconnect/tests/unit/test_allowedDomainsXHR.js new file mode 100644 index 0000000000..86d1e836c3 --- /dev/null +++ b/js/xpconnect/tests/unit/test_allowedDomainsXHR.js @@ -0,0 +1,134 @@ +Cu.import("resource://testing-common/httpd.js"); + +var httpserver = new HttpServer(); +var httpserver2 = new HttpServer(); +var httpserver3 = new HttpServer(); +var testpath = "/simple"; +var redirectpath = "/redirect"; +var negativetestpath = "/negative"; +var httpbody = "<?xml version='1.0' ?><root>0123456789</root>"; + +var sb = Cu.Sandbox(["http://www.example.com", + "http://localhost:4444/redirect", + "http://localhost:4444/simple", + "http://localhost:4446/redirect"], + { wantGlobalProperties: ["XMLHttpRequest"] }); + +function createXHR(loc, async) +{ + var xhr = new XMLHttpRequest(); + xhr.open("GET", "http://localhost:" + loc, async); + return xhr; +} + +function checkResults(xhr) +{ + if (xhr.readyState != 4) + return false; + + equal(xhr.status, 200); + equal(xhr.responseText, httpbody); + + var root_node = xhr.responseXML.getElementsByTagName('root').item(0); + equal(root_node.firstChild.data, "0123456789"); + return true; +} + +var httpServersClosed = 0; +function finishIfDone() +{ + if (++httpServersClosed == 3) + do_test_finished(); +} + +function run_test() +{ + do_test_pending(); + + httpserver.registerPathHandler(testpath, serverHandler); + httpserver.registerPathHandler(redirectpath, redirectHandler1); + httpserver.start(4444); + + httpserver2.registerPathHandler(negativetestpath, serverHandler); + httpserver2.start(4445); + + httpserver3.registerPathHandler(redirectpath, redirectHandler2); + httpserver3.start(4446); + + // Test sync XHR sending + Cu.evalInSandbox('var createXHR = ' + createXHR.toString(), sb); + var res = Cu.evalInSandbox('var sync = createXHR("4444/simple"); sync.send(null); sync', sb); + Assert.ok(checkResults(res)); + + var principal = res.responseXML.nodePrincipal; + Assert.ok(principal.isContentPrincipal); + var requestURL = "http://localhost:4444/simple"; + Assert.equal(principal.spec, requestURL); + + // negative test sync XHR sending (to ensure that the xhr do not have chrome caps, see bug 779821) + try { + Cu.evalInSandbox('var createXHR = ' + createXHR.toString(), sb); + var res = Cu.evalInSandbox('var sync = createXHR("4445/negative"); sync.send(null); sync', sb); + Assert.equal(false, true, "XHR created from sandbox should not have chrome caps"); + } catch (e) { + Assert.ok(true); + } + + // Test redirect handling. + // This request bounces to server 2 and then back to server 1. Neither of + // these servers support CORS, but if the expanded principal is used as the + // triggering principal, this should work. + Cu.evalInSandbox('var createXHR = ' + createXHR.toString(), sb); + var res = Cu.evalInSandbox('var sync = createXHR("4444/redirect"); sync.send(null); sync', sb); + Assert.ok(checkResults(res)); + + var principal = res.responseXML.nodePrincipal; + Assert.ok(principal.isContentPrincipal); + var requestURL = "http://localhost:4444/simple"; + Assert.equal(principal.spec, requestURL); + + httpserver2.stop(finishIfDone); + httpserver3.stop(finishIfDone); + + // Test async XHR sending + sb.finish = function(){ + httpserver.stop(finishIfDone); + } + + // We want to execute checkResults from the scope of the sandbox as well to + // make sure that there are no permission errors related to nsEP. For that + // we need to clone the function into the sandbox and make a few things + // available for it. + Cu.evalInSandbox('var checkResults = ' + checkResults.toSource(), sb); + sb.equal = equal; + sb.httpbody = httpbody; + + function changeListener(event) { + if (checkResults(async)) + finish(); + } + + var async = Cu.evalInSandbox('var async = createXHR("4444/simple", true);' + + 'async.addEventListener("readystatechange", ' + + changeListener.toString() + ', false);' + + 'async', sb); + async.send(null); +} + +function serverHandler(request, response) +{ + response.setHeader("Content-Type", "text/xml", false); + response.bodyOutputStream.write(httpbody, httpbody.length); +} + +function redirectHandler1(request, response) +{ + response.setStatusLine(request.httpVersion, 302, "Found"); + response.setHeader("Location", "http://localhost:4446/redirect", false); +} + +function redirectHandler2(request, response) +{ + response.setStatusLine(request.httpVersion, 302, "Found"); + response.setHeader("Location", "http://localhost:4444/simple", false); +} diff --git a/js/xpconnect/tests/unit/test_attributes.js b/js/xpconnect/tests/unit/test_attributes.js new file mode 100644 index 0000000000..767eb77e38 --- /dev/null +++ b/js/xpconnect/tests/unit/test_attributes.js @@ -0,0 +1,78 @@ +/* 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/. */ + +function run_test() { + + // Load the component manifests. + registerXPCTestComponents(); + registerAppManifest(do_get_file('../components/js/xpctest.manifest')); + + // Test for each component. + test_component_readwrite("@mozilla.org/js/xpc/test/native/ObjectReadWrite;1"); + test_component_readwrite("@mozilla.org/js/xpc/test/js/ObjectReadWrite;1"); + test_component_readonly("@mozilla.org/js/xpc/test/native/ObjectReadOnly;1"); + test_component_readonly("@mozilla.org/js/xpc/test/js/ObjectReadOnly;1"); +} + +function test_component_readwrite(contractid) { + + // Instantiate the object. + var o = Cc[contractid].createInstance(Ci["nsIXPCTestObjectReadWrite"]); + + // Test the initial values. + Assert.equal("XPConnect Read-Writable String", o.stringProperty); + Assert.equal(true, o.booleanProperty); + Assert.equal(32767, o.shortProperty); + Assert.equal(2147483647, o.longProperty); + Assert.ok(5.25 < o.floatProperty && 5.75 > o.floatProperty); + Assert.equal("X", o.charProperty); + Assert.equal(-1, o.timeProperty); + + // Write new values. + o.stringProperty = "another string"; + o.booleanProperty = false; + o.shortProperty = -12345; + o.longProperty = 1234567890; + o.floatProperty = 10.2; + o.charProperty = "Z"; + o.timeProperty = 1; + + // Test the new values. + Assert.equal("another string", o.stringProperty); + Assert.equal(false, o.booleanProperty); + Assert.equal(-12345, o.shortProperty); + Assert.equal(1234567890, o.longProperty); + Assert.ok(10.15 < o.floatProperty && 10.25 > o.floatProperty); + Assert.equal("Z", o.charProperty); + Assert.equal(1, o.timeProperty); + + // Assign values that differ from the expected type to verify conversion. + + function SetAndTestBooleanProperty(newValue, expectedValue) { + o.booleanProperty = newValue; + Assert.equal(expectedValue, o.booleanProperty); + }; + SetAndTestBooleanProperty(false, false); + SetAndTestBooleanProperty(1, true); + SetAndTestBooleanProperty(null, false); + SetAndTestBooleanProperty("A", true); + SetAndTestBooleanProperty(undefined, false); + SetAndTestBooleanProperty([], true); + SetAndTestBooleanProperty({}, true); +} + +function test_component_readonly(contractid) { + + // Instantiate the object. + var o = Cc[contractid].createInstance(Ci["nsIXPCTestObjectReadOnly"]); + + // Test the initial values. + Assert.equal("XPConnect Read-Only String", o.strReadOnly); + Assert.equal(true, o.boolReadOnly); + Assert.equal(32767, o.shortReadOnly); + Assert.equal(2147483647, o.longReadOnly); + Assert.ok(5.25 < o.floatReadOnly && 5.75 > o.floatReadOnly); + Assert.equal("X", o.charReadOnly); + Assert.equal(-1, o.timeReadOnly); +} diff --git a/js/xpconnect/tests/unit/test_blob.js b/js/xpconnect/tests/unit/test_blob.js new file mode 100644 index 0000000000..8b106911fc --- /dev/null +++ b/js/xpconnect/tests/unit/test_blob.js @@ -0,0 +1,16 @@ +/* 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/. */ + +function run_test() { + do_load_manifest("component-blob.manifest"); + const contractID = "@mozilla.org/tests/component-blob;1"; + Assert.ok(contractID in Cc); + var foo = Cc[contractID] + .createInstance(Ci.nsIClassInfo); + Assert.ok(Boolean(foo)); + Assert.ok(foo.contractID == contractID); + Assert.ok(!!foo.wrappedJSObject); + Assert.ok(foo.wrappedJSObject.doTest()); + +} diff --git a/js/xpconnect/tests/unit/test_blob2.js b/js/xpconnect/tests/unit/test_blob2.js new file mode 100644 index 0000000000..90d4bdc1c6 --- /dev/null +++ b/js/xpconnect/tests/unit/test_blob2.js @@ -0,0 +1,34 @@ +/* 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/. */ + +Cu.importGlobalProperties(['Blob', 'File']); + +function run_test() { + // throw if anything goes wrong + let testContent = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>"; + // should be able to construct a file + var f1 = new Blob([testContent], {"type" : "text/xml"}); + + // do some tests + Assert.ok(f1 instanceof Blob, "Should be a DOM Blob"); + + Assert.ok(!(f1 instanceof File), "Should not be a DOM File"); + + Assert.ok(f1.type == "text/xml", "Wrong type"); + + Assert.ok(f1.size == testContent.length, "Wrong content size"); + + var f2 = new Blob(); + Assert.ok(f2.size == 0, "Wrong size"); + Assert.ok(f2.type == "", "Wrong type"); + + var threw = false; + try { + // Needs a valid ctor argument + var f2 = new Blob(Date(132131532)); + } catch (e) { + threw = true; + } + Assert.ok(threw, "Passing a random object should fail"); +} diff --git a/js/xpconnect/tests/unit/test_bogus_files.js b/js/xpconnect/tests/unit/test_bogus_files.js new file mode 100644 index 0000000000..3f33f1ef0d --- /dev/null +++ b/js/xpconnect/tests/unit/test_bogus_files.js @@ -0,0 +1,42 @@ +/* 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/. */ + +function test_BrokenFile(path, shouldThrow, expectedName) { + var didThrow = false; + try { + ChromeUtils.import(path); + } catch (ex) { + var exceptionName = ex.name; + print("ex: " + ex + "; name = " + ex.name); + didThrow = true; + } + + Assert.equal(didThrow, shouldThrow); + if (didThrow) + Assert.equal(exceptionName, expectedName); +} + +function run_test() { + test_BrokenFile("resource://test/bogus_exports_type.jsm", true, "Error"); + + test_BrokenFile("resource://test/bogus_element_type.jsm", true, "Error"); + + test_BrokenFile("resource://test/non_existing.jsm", + true, + "NS_ERROR_FILE_NOT_FOUND"); + + test_BrokenFile("chrome://test/content/test.jsm", + true, + "NS_ERROR_FILE_NOT_FOUND"); + + // check that we can access modules' global objects even if + // EXPORTED_SYMBOLS is missing or ill-formed: + Assert.equal(typeof(ChromeUtils.import("resource://test/bogus_exports_type.jsm", + null)), + "object"); + + Assert.equal(typeof(ChromeUtils.import("resource://test/bogus_element_type.jsm", + null)), + "object"); +} diff --git a/js/xpconnect/tests/unit/test_bug1001094.js b/js/xpconnect/tests/unit/test_bug1001094.js new file mode 100644 index 0000000000..ac06e4c0f3 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1001094.js @@ -0,0 +1,4 @@ +function run_test() { + // Make sure nsJSID implements classinfo. + Assert.equal(Components.ID("{a6e2a27f-5521-4b35-8b52-99799a744aee}").equals, Components.ID("{daa47351-7d2e-44a7-b8e3-281802a1eab7}").equals); +} diff --git a/js/xpconnect/tests/unit/test_bug1021312.js b/js/xpconnect/tests/unit/test_bug1021312.js new file mode 100644 index 0000000000..ccb9981b43 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1021312.js @@ -0,0 +1,15 @@ +/* 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/. */ + +function run_test() { + let sb = new Cu.Sandbox(this); + var called = false; + + Cu.exportFunction(function(str) { Assert.ok(/someString/.test(str)); called = true; }, + sb, { defineAs: "func" }); + // Do something weird with the string to make sure that it doesn't get interned. + Cu.evalInSandbox("var str = 'someString'; for (var i = 0; i < 10; ++i) str += i;", sb); + Cu.evalInSandbox("func(str);", sb); + Assert.ok(called); +} diff --git a/js/xpconnect/tests/unit/test_bug1033253.js b/js/xpconnect/tests/unit/test_bug1033253.js new file mode 100644 index 0000000000..e5860833b2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1033253.js @@ -0,0 +1,5 @@ +function run_test() { + var sb = Cu.Sandbox('http://www.example.com'); + var f = Cu.evalInSandbox('var f = function() {}; f;', sb); + Assert.equal(f.name, ""); +} diff --git a/js/xpconnect/tests/unit/test_bug1033920.js b/js/xpconnect/tests/unit/test_bug1033920.js new file mode 100644 index 0000000000..6e85ec4f1d --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1033920.js @@ -0,0 +1,6 @@ +function run_test() { + var sb = Cu.Sandbox('http://www.example.com'); + var o = new sb.Object(); + o.__proto__ = null; + Assert.equal(Object.getPrototypeOf(o), null); +} diff --git a/js/xpconnect/tests/unit/test_bug1033927.js b/js/xpconnect/tests/unit/test_bug1033927.js new file mode 100644 index 0000000000..cd2bb210e7 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1033927.js @@ -0,0 +1,8 @@ +function run_test() { + var sb = Cu.Sandbox('http://www.example.com', { wantGlobalProperties: ['XMLHttpRequest']}); + var xhr = Cu.evalInSandbox('new XMLHttpRequest()', sb); + Assert.equal(xhr[Symbol.toStringTag], "XMLHttpRequest"); + Assert.equal(xhr.toString(), '[object XMLHttpRequest]'); + Assert.equal((new sb.Object()).toString(), '[object Object]'); + Assert.equal(sb.Object.prototype.toString.call(new sb.Uint16Array()), '[object Uint16Array]'); +} diff --git a/js/xpconnect/tests/unit/test_bug1034262.js b/js/xpconnect/tests/unit/test_bug1034262.js new file mode 100644 index 0000000000..6bd598bd53 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1034262.js @@ -0,0 +1,8 @@ +function run_test() { + var sb1 = Cu.Sandbox('http://www.example.com', { wantXrays: true }); + var sb2 = Cu.Sandbox('http://www.example.com', { wantXrays: false }); + sb2.f = Cu.evalInSandbox('x => typeof x', sb1); + Assert.equal(Cu.evalInSandbox('f(dump)', sb2), 'function'); + Assert.equal(Cu.evalInSandbox('f.call(null, dump)', sb2), 'function'); + Assert.equal(Cu.evalInSandbox('f.apply(null, [dump])', sb2), 'function'); +} diff --git a/js/xpconnect/tests/unit/test_bug1081990.js b/js/xpconnect/tests/unit/test_bug1081990.js new file mode 100644 index 0000000000..80e37ac282 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1081990.js @@ -0,0 +1,9 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + sb.obj = {}; + sb.arr = []; + sb.fun = function() {}; + Assert.ok(sb.eval('Object.getPrototypeOf(obj) == null')); + Assert.ok(sb.eval('Object.getPrototypeOf(arr) == null')); + Assert.ok(sb.eval('Object.getPrototypeOf(fun) == null')); +} diff --git a/js/xpconnect/tests/unit/test_bug1082450.js b/js/xpconnect/tests/unit/test_bug1082450.js new file mode 100644 index 0000000000..116fe8aa32 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1082450.js @@ -0,0 +1,39 @@ +function run_test() { + + var sb = new Cu.Sandbox('http://www.example.com'); + function checkThrows(str, rgxp) { + try { + sb.eval(str); + Assert.ok(false, "eval should have thrown"); + } catch (e) { + Assert.ok(rgxp.test(e), "error message should match"); + } + } + + sb.exposed = { + get getterProp() { return 42; }, + set setterProp(x) { }, + get getterSetterProp() { return 42; }, + set getterSetterProp(x) { }, + simpleValueProp: 42, + objectValueProp: { val: 42, __exposedProps__: { val: 'r' } }, + contentCallableValueProp: new sb.Function('return 42'), + chromeCallableValueProp: function() {}, + __exposedProps__: { getterProp : 'r', + setterProp : 'w', + getterSetterProp: 'rw', + simpleValueProp: 'r', + objectValueProp: 'r', + contentCallableValueProp: 'r', + chromeCallableValueProp: 'r' } + }; + + Assert.equal(sb.eval('exposed.simpleValueProp'), undefined); + Assert.equal(sb.eval('exposed.objectValueProp'), undefined); + Assert.equal(sb.eval('exposed.getterProp;'), undefined); + Assert.equal(sb.eval('exposed.getterSetterProp;'), undefined); + checkThrows('exposed.setterProp = 42;', /Permission denied/i); + checkThrows('exposed.getterSetterProp = 42;', /Permission denied/i); + Assert.equal(sb.eval('exposed.contentCallableValueProp'), undefined); + checkThrows('exposed.chromeCallableValueProp();', /is not a function/i); +} diff --git a/js/xpconnect/tests/unit/test_bug1110546.js b/js/xpconnect/tests/unit/test_bug1110546.js new file mode 100644 index 0000000000..04e1add915 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1110546.js @@ -0,0 +1,4 @@ +function run_test() { + var sb = new Cu.Sandbox(null); + Assert.ok(Cu.getObjectPrincipal(sb).isNullPrincipal); +} diff --git a/js/xpconnect/tests/unit/test_bug1131707.js b/js/xpconnect/tests/unit/test_bug1131707.js new file mode 100644 index 0000000000..57ade9f8c8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1131707.js @@ -0,0 +1,20 @@ +function testStrict(sb) { + "use strict"; + Assert.equal(sb.eval("typeof wrappedCtor()"), "string"); + Assert.equal(sb.eval("typeof new wrappedCtor()"), "object"); +} + +function run_test() { + var sb = new Cu.Sandbox(null); + var dateCtor = sb.Date; + sb.wrappedCtor = Cu.exportFunction(function wrapper(val) { + "use strict"; + var constructing = this.constructor == wrapper; + return constructing ? new dateCtor(val) : dateCtor(val); + }, sb); + Assert.equal(typeof Date(), "string"); + Assert.equal(typeof new Date(), "object"); + Assert.equal(sb.eval("typeof wrappedCtor()"), "string"); + Assert.equal(sb.eval("typeof new wrappedCtor()"), "object"); + testStrict(sb); +} diff --git a/js/xpconnect/tests/unit/test_bug1150771.js b/js/xpconnect/tests/unit/test_bug1150771.js new file mode 100644 index 0000000000..433156d6f5 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1150771.js @@ -0,0 +1,12 @@ +function run_test() { +let sandbox1 = new Cu.Sandbox(null); +let sandbox2 = new Cu.Sandbox(null); +let arg = Cu.evalInSandbox('({ buf: new ArrayBuffer(2) })', sandbox1); + +let clonedArg = Cu.cloneInto(Cu.waiveXrays(arg), sandbox2); +Assert.equal(typeof Cu.waiveXrays(clonedArg).buf, "object"); + +clonedArg = Cu.cloneInto(arg, sandbox2); +Assert.equal(typeof Cu.waiveXrays(clonedArg).buf, "object"); +Assert.equal(Cu.waiveXrays(clonedArg).buf.constructor.name, "ArrayBuffer"); +} diff --git a/js/xpconnect/tests/unit/test_bug1151385.js b/js/xpconnect/tests/unit/test_bug1151385.js new file mode 100644 index 0000000000..913050248f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1151385.js @@ -0,0 +1,9 @@ +function run_test() +{ + try { + var sandbox = new Cu.Sandbox(null, {"sandboxPrototype" : {}}); + Assert.ok(false); + } catch (e) { + Assert.ok(/must subsume sandboxPrototype/.test(e)); + } +} diff --git a/js/xpconnect/tests/unit/test_bug1170311.js b/js/xpconnect/tests/unit/test_bug1170311.js new file mode 100644 index 0000000000..cdbe62407a --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1170311.js @@ -0,0 +1,4 @@ +function run_test() { + do_check_throws_nsIException(() => Cu.getObjectPrincipal({}).equals(null), "NS_ERROR_ILLEGAL_VALUE"); + do_check_throws_nsIException(() => Cu.getObjectPrincipal({}).subsumes(null), "NS_ERROR_ILLEGAL_VALUE"); +} diff --git a/js/xpconnect/tests/unit/test_bug1244222.js b/js/xpconnect/tests/unit/test_bug1244222.js new file mode 100644 index 0000000000..1adc0795eb --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1244222.js @@ -0,0 +1,30 @@ +/* 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 {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +function run_test() { + registerAppManifest(do_get_file('../components/js/xpctest.manifest')); + + // Generate a CCW to a function. + var sb = new Cu.Sandbox(this); + sb.eval('function fun(x) { return x; }'); + Assert.equal(sb.fun("foo"), "foo"); + + // Double-wrap the CCW. + var utils = Cc["@mozilla.org/js/xpc/test/js/TestUtils;1"].createInstance(Ci.nsIXPCTestUtils); + var doubleWrapped = utils.doubleWrapFunction(sb.fun); + Assert.equal(doubleWrapped.echo("foo"), "foo"); + + // GC. + Cu.forceGC(); + + // Make sure it still works. + Assert.equal(doubleWrapped.echo("foo"), "foo"); +} diff --git a/js/xpconnect/tests/unit/test_bug1617527.js b/js/xpconnect/tests/unit/test_bug1617527.js new file mode 100644 index 0000000000..3db33e60d9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1617527.js @@ -0,0 +1,17 @@ +/* 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/. */ + +function run_test() { + let sb1 = new Cu.Sandbox("https://example.org"); + let throwingFunc = Cu.evalInSandbox("new Function('throw new Error')", sb1); + // NOTE: Different origin from the other sandbox. + let sb2 = new Cu.Sandbox("https://example.com"); + Cu.exportFunction(function() { + // Call a different-compartment throwing function. + throwingFunc(); + }, sb2, { defineAs: "func" }); + let threw = Cu.evalInSandbox("var threw; try { func(); threw = false; } catch (e) { threw = true } threw", + sb2); + Assert.ok(threw); +} diff --git a/js/xpconnect/tests/unit/test_bug267645.js b/js/xpconnect/tests/unit/test_bug267645.js new file mode 100644 index 0000000000..6196a2165c --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug267645.js @@ -0,0 +1,62 @@ +/* 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/. */ + +function run_test() { + let sb = new Cu.Sandbox("https://example.com", + { wantGlobalProperties: ["DOMException"] }); + Cu.exportFunction(function() { + undefined.foo(); + }, sb, { defineAs: "func" }); + // By default, the stacks of things running in a sandbox will contain the + // actual evalInSandbox() call location. To override that, we have to pass an + // explicit filename. + let threw = Cu.evalInSandbox("var threw; try { func(); threw = false; } catch (e) { globalThis.exn = e; threw = true } threw", + sb, "", "FakeFile"); + Assert.ok(threw); + + // Check what the sandbox could see from this exception. + Assert.ok(!Cu.evalInSandbox("exn.filename", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.fileName", sb), undefined); + Assert.ok(!Cu.evalInSandbox("exn.stack", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.message", sb), "An exception was thrown"); + Assert.equal(Cu.evalInSandbox("exn.name", sb), "InvalidStateError"); + + Cu.exportFunction(function() { + throw new Error("Hello"); + }, sb, { defineAs: "func2" }); + threw = Cu.evalInSandbox("var threw; try { func2(); threw = false; } catch (e) { globalThis.exn = e; threw = true } threw", + sb, "", "FakeFile"); + Assert.ok(threw); + Assert.ok(!Cu.evalInSandbox("exn.filename", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.fileName", sb), undefined); + Assert.ok(!Cu.evalInSandbox("exn.stack", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.message", sb), "An exception was thrown"); + Assert.equal(Cu.evalInSandbox("exn.name", sb), "InvalidStateError"); + + let ctor = Cu.evalInSandbox("TypeError", sb); + Cu.exportFunction(function() { + throw new ctor("Hello"); + }, sb, { defineAs: "func3" }); + threw = Cu.evalInSandbox("var threw; try { func3(); threw = false; } catch (e) { globalThis.exn = e; threw = true } threw", + sb, "", "FakeFile"); + Assert.ok(threw); + Assert.ok(!Cu.evalInSandbox("exn.fileName", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.filename", sb), undefined); + Assert.ok(!Cu.evalInSandbox("exn.stack", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.message", sb), "Hello"); + Assert.equal(Cu.evalInSandbox("exn.name", sb), "TypeError"); + + ctor = Cu.evalInSandbox("DOMException", sb); + Cu.exportFunction(function() { + throw new ctor("Goodbye", "InvalidAccessError"); + }, sb, { defineAs: "func4" }); + threw = Cu.evalInSandbox("var threw; try { func4(); threw = false; } catch (e) { globalThis.exn = e; threw = true } threw", + sb, "", "FakeFile"); + Assert.ok(threw); + Assert.ok(!Cu.evalInSandbox("exn.filename", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.fileName", sb), undefined); + Assert.ok(!Cu.evalInSandbox("exn.stack", sb).includes("/unit/")); + Assert.equal(Cu.evalInSandbox("exn.message", sb), "Goodbye"); + Assert.equal(Cu.evalInSandbox("exn.name", sb), "InvalidAccessError"); +} diff --git a/js/xpconnect/tests/unit/test_bug408412.js b/js/xpconnect/tests/unit/test_bug408412.js new file mode 100644 index 0000000000..e73c15cab8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug408412.js @@ -0,0 +1,17 @@ +/* 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/. */ + +function run_test() { + var file = do_get_file("syntax_error.jsm"); + var ios = Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService); + var uri = ios.newFileURI(file); + + try { + ChromeUtils.import(uri.spec); + do_throw("Failed to report any error at all"); + } catch (e) { + Assert.notEqual(/^SyntaxError:/.exec(e + ''), null); + } +} diff --git a/js/xpconnect/tests/unit/test_bug451678.js b/js/xpconnect/tests/unit/test_bug451678.js new file mode 100644 index 0000000000..90c18a614c --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug451678.js @@ -0,0 +1,15 @@ +/* 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/. */ + +function run_test() { + var file = do_get_file("bug451678_subscript.js"); + var ios = Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService); + var uri = ios.newFileURI(file); + var scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"] + .getService(Ci.mozIJSSubScriptLoader); + var srvScope = {}; + scriptLoader.loadSubScript(uri.spec, srvScope); + Assert.ok('makeTags' in srvScope && srvScope.makeTags instanceof Function); +} diff --git a/js/xpconnect/tests/unit/test_bug604362.js b/js/xpconnect/tests/unit/test_bug604362.js new file mode 100644 index 0000000000..7adcfab96c --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug604362.js @@ -0,0 +1,10 @@ +function run_test() { + var sp = Cc["@mozilla.org/systemprincipal;1"]. + createInstance(Ci.nsIPrincipal); + var s = Cu.Sandbox(sp); + s.a = []; + s.Cu = Cu; + s.C = Components; + s.notEqual = notEqual; + Cu.evalInSandbox("notEqual(Cu.import, undefined);", s); +} diff --git a/js/xpconnect/tests/unit/test_bug677864.js b/js/xpconnect/tests/unit/test_bug677864.js new file mode 100644 index 0000000000..f92d15fe66 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug677864.js @@ -0,0 +1,9 @@ +function check_cl(iface, desc) { + Assert.equal(iface.QueryInterface(Ci.nsIClassInfo).classDescription, desc); +} + +function run_test() { + check_cl(Ci, 'XPCComponents_Interfaces'); + check_cl(Cc, 'XPCComponents_Classes'); + check_cl(Cr, 'XPCComponents_Results'); +} diff --git a/js/xpconnect/tests/unit/test_bug711404.js b/js/xpconnect/tests/unit/test_bug711404.js new file mode 100644 index 0000000000..f74b43316c --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug711404.js @@ -0,0 +1,7 @@ +function run_test() +{ + var p = Cc["@mozilla.org/hash-property-bag;1"]. + createInstance(Ci.nsIWritablePropertyBag2); + p.setPropertyAsInt64("a", -4000); + Assert.notEqual(p.getPropertyAsUint64("a"), -4000); +} diff --git a/js/xpconnect/tests/unit/test_bug742444.js b/js/xpconnect/tests/unit/test_bug742444.js new file mode 100644 index 0000000000..3b8262834f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug742444.js @@ -0,0 +1,16 @@ +function run_test() { + let sb1A = Cu.Sandbox('http://www.example.com'); + let sb1B = Cu.Sandbox('http://www.example.com'); + let sb2 = Cu.Sandbox('http://www.example.org'); + let sbChrome = Cu.Sandbox(this); + let obj = new sb1A.Object(); + sb1B.obj = obj; + sb1B.waived = Cu.waiveXrays(obj); + sb2.obj = obj; + sb2.waived = Cu.waiveXrays(obj); + sbChrome.obj = obj; + sbChrome.waived = Cu.waiveXrays(obj); + Assert.ok(Cu.evalInSandbox('obj === waived', sb1B)); + Assert.ok(Cu.evalInSandbox('obj === waived', sb2)); + Assert.ok(Cu.evalInSandbox('obj !== waived', sbChrome)); +} diff --git a/js/xpconnect/tests/unit/test_bug778409.js b/js/xpconnect/tests/unit/test_bug778409.js new file mode 100644 index 0000000000..4ca2ea6767 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug778409.js @@ -0,0 +1,10 @@ +function run_test() { + var sb1 = Cu.Sandbox('http://example.com'); + var sb2 = Cu.Sandbox('http://example.org'); + var chromeObj = {foo: 2}; + var sb1obj = Cu.evalInSandbox('new Object()', sb1); + chromeObj.__proto__ = sb1obj; + sb2.wrapMe = chromeObj; + Assert.ok(true, "Didn't crash"); + Assert.equal(sb2.wrapMe.__proto__, sb1obj, 'proto set correctly'); +} diff --git a/js/xpconnect/tests/unit/test_bug780370.js b/js/xpconnect/tests/unit/test_bug780370.js new file mode 100644 index 0000000000..1ee32d0616 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug780370.js @@ -0,0 +1,16 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=780370 */ + +// Use a COW to expose a function from a standard prototype, and make we deny +// access to it. + +function run_test() +{ + var sb = Cu.Sandbox("http://www.example.com"); + sb.obj = { foo: 42, __exposedProps__: { hasOwnProperty: 'r' } }; + Assert.equal(Cu.evalInSandbox('typeof obj.foo', sb), 'undefined', "COW works as expected"); + Assert.equal(Cu.evalInSandbox('obj.hasOwnProperty', sb), undefined); +} diff --git a/js/xpconnect/tests/unit/test_bug809652.js b/js/xpconnect/tests/unit/test_bug809652.js new file mode 100644 index 0000000000..6d63c6531f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug809652.js @@ -0,0 +1,62 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=813901 */ + +const TypedArrays = [ Int8Array, Uint8Array, Int16Array, Uint16Array, + Int32Array, Uint32Array, Float32Array, Float64Array, + Uint8ClampedArray ]; + +// Make sure that the correct nativecall-y stuff is denied on security wrappers. + +function run_test() { + + var sb = new Cu.Sandbox('http://www.example.org'); + sb.obj = {foo: 2}; + + /* Set up some typed arrays. */ + sb.ab = new ArrayBuffer(8); + for (var i = 0; i < 8; ++i) + new Uint8Array(sb.ab)[i] = i * 10; + sb.ta = []; + TypedArrays.forEach(f => sb.ta.push(new f(sb.ab))); + sb.dv = new DataView(sb.ab); + + /* Things that should throw. */ + checkThrows("Object.prototype.__lookupSetter__('__proto__').call(obj, {});", sb); + sb.re = /f/; + checkThrows("RegExp.prototype.exec.call(re, 'abcdefg').index", sb); + sb.d = new Date(); + checkThrows("Date.prototype.setYear.call(d, 2011)", sb); + sb.m = new Map(); + checkThrows("(new Map()).clear.call(m)", sb); + checkThrows("ArrayBuffer.prototype.__lookupGetter__('byteLength').call(ab);", sb); + checkThrows("ArrayBuffer.prototype.slice.call(ab, 0);", sb); + checkThrows("DataView.prototype.getInt8.call(dv, 0);", sb); + + /* Now that Date is on Xrays, these should all throw. */ + checkThrows("Date.prototype.getYear.call(d)", sb); + checkThrows("Date.prototype.valueOf.call(d)", sb); + checkThrows("d.valueOf()", sb); + checkThrows("d.toString()", sb); + + /* Typed arrays. */ + function testForTypedArray(t) { + sb.curr = t; + sb.currName = t.constructor.name; + checkThrows("this[currName].prototype.subarray.call(curr, 0)[0]", sb); + checkThrows("(new this[currName]).__lookupGetter__('length').call(curr)", sb); + checkThrows("(new this[currName]).__lookupGetter__('buffer').call(curr)", sb); + checkThrows("(new this[currName]).__lookupGetter__('byteOffset').call(curr)", sb); + checkThrows("(new this[currName]).__lookupGetter__('byteLength').call(curr)", sb); + } + sb.ta.forEach(testForTypedArray); +} + +function checkThrows(expression, sb) { + var result = Cu.evalInSandbox('(function() { try { ' + expression + '; return "allowed"; } catch (e) { return e.toString(); }})();', sb); + dump('result: ' + result + '\n\n\n'); + Assert.ok(!!/denied/.exec(result)); +} + diff --git a/js/xpconnect/tests/unit/test_bug809674.js b/js/xpconnect/tests/unit/test_bug809674.js new file mode 100644 index 0000000000..d6c386fdf2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug809674.js @@ -0,0 +1,50 @@ +/* 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/. */ + +function run_test() { + + // Load the component manifest. + Components.manager.autoRegister(do_get_file('../components/js/xpctest.manifest')); + + // Instantiate the object. + var o = Cc["@mozilla.org/js/xpc/test/js/Bug809674;1"].createInstance(Ci["nsIXPCTestBug809674"]); + + // Methods marked [implicit_jscontext]. + + Assert.equal(o.addArgs(12, 34), 46); + + var subRes = {}, mulRes = {}; + Assert.equal(o.addSubMulArgs(9, 7, subRes, mulRes), 16); + Assert.equal(subRes.value, 2); + Assert.equal(mulRes.value, 63); + + Assert.equal(o.addVals("foo", "x"), "foox"); + Assert.equal(o.addVals("foo", 1.2), "foo1.2"); + Assert.equal(o.addVals(1234, "foo"), "1234foo"); + + Assert.equal(o.addMany(1, 2, 4, 8, 16, 32, 64, 128), 255); + + Assert.equal(o.methodNoArgs(), 7); + Assert.equal(o.methodNoArgsNoRetVal(), undefined); + + // Attributes marked [implicit_jscontext]. + + Assert.equal(o.valProperty.value, 42); + o.valProperty = o; + Assert.equal(o.valProperty, o); + + Assert.equal(o.uintProperty, 123); + o.uintProperty++; + Assert.equal(o.uintProperty, 124); + + // [optional_argc] is not supported. + try { + o.methodWithOptionalArgc(); + Assert.ok(false); + } catch (e) { + Assert.ok(true); + Assert.ok(/optional_argc/.test(e)) + } + +} diff --git a/js/xpconnect/tests/unit/test_bug813901.js b/js/xpconnect/tests/unit/test_bug813901.js new file mode 100644 index 0000000000..9831dfb0ac --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug813901.js @@ -0,0 +1,23 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=813901 */ + +// Make sure that we can't inject __exposedProps__ via the proto of a COW-ed object. + +function checkThrows(expression, sb, regexp) { + var result = Cu.evalInSandbox('(function() { try { ' + expression + '; return "allowed"; } catch (e) { return e.toString(); }})();', sb); + dump('result: ' + result + '\n\n\n'); + Assert.ok(!!regexp.exec(result)); +} + +function run_test() { + + var sb = new Cu.Sandbox('http://www.example.org'); + sb.obj = {foo: 2}; + checkThrows('obj.foo = 3;', sb, /denied/); + Cu.evalInSandbox("var p = {__exposedProps__: {foo: 'rw'}};", sb); + sb.obj.__proto__ = sb.p; + checkThrows('obj.foo = 4;', sb, /denied/); +} diff --git a/js/xpconnect/tests/unit/test_bug845201.js b/js/xpconnect/tests/unit/test_bug845201.js new file mode 100644 index 0000000000..74253ccaed --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug845201.js @@ -0,0 +1,18 @@ +function sbTest() { + var threw = false; + try { + for (var x in Components) { } + ok(false, "Shouldn't be able to enumerate Components"); + } catch(e) { + ok(true, "Threw appropriately"); + threw = true; + } + ok(threw, "Shouldn't have thrown uncatchable exception"); +} + +function run_test() { + var sb = Cu.Sandbox('http://www.example.com', { wantComponents: true }); + sb.ok = ok; + Cu.evalInSandbox(sbTest.toSource(), sb); + Cu.evalInSandbox('sbTest();', sb); +} diff --git a/js/xpconnect/tests/unit/test_bug845862.js b/js/xpconnect/tests/unit/test_bug845862.js new file mode 100644 index 0000000000..41d799803f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug845862.js @@ -0,0 +1,7 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + Cu.evalInSandbox("this.foo = {}; Object.defineProperty(foo, 'bar', {get: function() {return {};}});", sb); + var desc = Object.getOwnPropertyDescriptor(Cu.waiveXrays(sb.foo), 'bar'); + var b = desc.get(); + Assert.ok(b != XPCNativeWrapper(b), "results from accessor descriptors are waived"); +} diff --git a/js/xpconnect/tests/unit/test_bug849730.js b/js/xpconnect/tests/unit/test_bug849730.js new file mode 100644 index 0000000000..9be55457bf --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug849730.js @@ -0,0 +1,5 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + sb.arr = [3, 4]; + Assert.ok(Cu.evalInSandbox('!Array.isArray(arr);', sb)); +} diff --git a/js/xpconnect/tests/unit/test_bug851895.js b/js/xpconnect/tests/unit/test_bug851895.js new file mode 100644 index 0000000000..1c3d0f461f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug851895.js @@ -0,0 +1,9 @@ +function run_test() { + // Make sure Components.utils gets its |this| fixed up. + var isXrayWrapper = Cu.isXrayWrapper; + Assert.ok(!isXrayWrapper({}), "Didn't throw"); + + // Even for classes without |this| fixup, make sure that we don't crash. + var isSuccessCode = Components.isSuccessCode; + try { isSuccessCode(Cr.NS_OK); } catch (e) {}; +} diff --git a/js/xpconnect/tests/unit/test_bug853709.js b/js/xpconnect/tests/unit/test_bug853709.js new file mode 100644 index 0000000000..6843195184 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug853709.js @@ -0,0 +1,30 @@ +function setupChromeSandbox() { + this.chromeObj = {a: 2, __exposedProps__: {a: "rw", b: "rw"} }; + this.chromeArr = [4, 2, 1]; +} + +function checkDefineThrows(sb, obj, prop, desc) { + var result = Cu.evalInSandbox('(function() { try { Object.defineProperty(' + obj + ', "' + prop + '", ' + desc.toSource() + '); return "nothrow"; } catch (e) { return e.toString(); }})();', sb); + Assert.notEqual(result, 'nothrow'); + Assert.ok(!!/denied|prohibited/.exec(result)); + Assert.ok(result.includes(prop)); // Make sure the prop name is in the error message. +} + +function run_test() { + var chromeSB = new Cu.Sandbox(this); + var contentSB = new Cu.Sandbox('http://www.example.org'); + Cu.evalInSandbox('(' + setupChromeSandbox.toSource() + ')()', chromeSB); + contentSB.chromeObj = chromeSB.chromeObj; + contentSB.chromeArr = chromeSB.chromeArr; + + Assert.equal(Cu.evalInSandbox('chromeObj.a', contentSB), undefined); + try { + Cu.evalInSandbox('chromeArr[1]', contentSB); + Assert.ok(false); + } catch (e) { Assert.ok(/denied|insecure/.test(e)); } + + checkDefineThrows(contentSB, 'chromeObj', 'a', {get: function() { return 2; }}); + checkDefineThrows(contentSB, 'chromeObj', 'a', {configurable: true, get: function() { return 2; }}); + checkDefineThrows(contentSB, 'chromeObj', 'b', {configurable: true, get: function() { return 2; }, set: function() {}}); + checkDefineThrows(contentSB, 'chromeArr', '1', {configurable: true, get: function() { return 2; }}); +} diff --git a/js/xpconnect/tests/unit/test_bug854558.js b/js/xpconnect/tests/unit/test_bug854558.js new file mode 100644 index 0000000000..04a876af0c --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug854558.js @@ -0,0 +1,10 @@ +function run_test() { + + var chromeSB = new Cu.Sandbox(this); + var contentSB = new Cu.Sandbox('http://www.example.com'); + Cu.evalInSandbox('this.foo = {a: 2}', chromeSB); + contentSB.foo = chromeSB.foo; + Assert.equal(Cu.evalInSandbox('foo.a', contentSB), undefined, "Default deny with no __exposedProps__"); + Cu.evalInSandbox('this.foo.__exposedProps__ = {a: "r"}', chromeSB); + Assert.equal(Cu.evalInSandbox('foo.a', contentSB), undefined, "Still not allowed with __exposedProps__"); +} diff --git a/js/xpconnect/tests/unit/test_bug856067.js b/js/xpconnect/tests/unit/test_bug856067.js new file mode 100644 index 0000000000..b724ba4b18 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug856067.js @@ -0,0 +1,8 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + let w = Cu.evalInSandbox('var w = new Map()[Symbol.iterator](); w.__proto__ = new Set(); w.foopy = 12; w', sb); + Assert.equal(Object.getPrototypeOf(w), sb.Object.prototype); + Assert.equal(Object.getOwnPropertyNames(w).length, 0); + Assert.equal(w.wrappedJSObject.foopy, 12); + Assert.equal(w.foopy, undefined); +} diff --git a/js/xpconnect/tests/unit/test_bug867486.js b/js/xpconnect/tests/unit/test_bug867486.js new file mode 100644 index 0000000000..c053ec27e1 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug867486.js @@ -0,0 +1,8 @@ +/* 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/. */ + +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com', { wantComponents: true } ); + Assert.ok(!Cu.evalInSandbox('"Components" in this', sb)); +} diff --git a/js/xpconnect/tests/unit/test_bug868675.js b/js/xpconnect/tests/unit/test_bug868675.js new file mode 100644 index 0000000000..df86e9b826 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug868675.js @@ -0,0 +1,24 @@ +function run_test() { + + // Make sure we don't throw for primitive values. + var result = "threw"; + try { result = XPCNativeWrapper.unwrap(2); } catch (e) {} + Assert.equal(result, 2); + result = "threw"; + try { result = XPCNativeWrapper(2); } catch (e) {} + Assert.equal(result, 2); + + // Make sure that we can waive on a non-Xrayable object, and that we preserve + // transitive waiving behavior. + var sb = new Cu.Sandbox('http://www.example.com', { wantGlobalProperties: ["XMLHttpRequest"] }); + Cu.evalInSandbox('this.xhr = new XMLHttpRequest();', sb); + Cu.evalInSandbox('this.jsobj = {mynative: xhr};', sb); + Assert.ok(!Cu.isXrayWrapper(XPCNativeWrapper.unwrap(sb.xhr))); + Assert.ok(Cu.isXrayWrapper(sb.jsobj.mynative)); + Assert.ok(!Cu.isXrayWrapper(XPCNativeWrapper.unwrap(sb.jsobj).mynative)); + + // Test the new Cu API. + var waived = Cu.waiveXrays(sb.xhr); + Assert.ok(!Cu.isXrayWrapper(waived)); + Assert.ok(Cu.isXrayWrapper(Cu.unwaiveXrays(waived))); +} diff --git a/js/xpconnect/tests/unit/test_bug872772.js b/js/xpconnect/tests/unit/test_bug872772.js new file mode 100644 index 0000000000..bfb0d7f4f8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug872772.js @@ -0,0 +1,33 @@ +function run_test() { + + // Make a content sandbox with an Xrayable object. + // NB: We use an nsEP here so that we can have access to Components, but still + // have Xray behavior from this scope. + var contentSB = new Cu.Sandbox(['http://www.google.com'], + { wantGlobalProperties: ["XMLHttpRequest"] }); + + // Make an XHR in the content sandbox. + Cu.evalInSandbox('xhr = new XMLHttpRequest();', contentSB); + + // Make sure that waivers can be set as Xray expandos. + var xhr = contentSB.xhr; + Assert.ok(Cu.isXrayWrapper(xhr)); + xhr.unwaivedExpando = xhr; + Assert.ok(Cu.isXrayWrapper(xhr.unwaivedExpando)); + var waived = xhr.wrappedJSObject; + Assert.ok(!Cu.isXrayWrapper(waived)); + xhr.waivedExpando = waived; + Assert.ok(!Cu.isXrayWrapper(xhr.waivedExpando)); + + // Try the same thing for getters/setters, even though that's kind of + // contrived. + Cu.evalInSandbox('function f() {}', contentSB); + var f = contentSB.f; + var fWaiver = Cu.waiveXrays(f); + Assert.ok(f != fWaiver); + Assert.ok(Cu.unwaiveXrays(fWaiver) === f); + Object.defineProperty(xhr, 'waivedAccessors', {get: fWaiver, set: fWaiver}); + var desc = Object.getOwnPropertyDescriptor(xhr, 'waivedAccessors'); + Assert.ok(desc.get === fWaiver); + Assert.ok(desc.set === fWaiver); +} diff --git a/js/xpconnect/tests/unit/test_bug885800.js b/js/xpconnect/tests/unit/test_bug885800.js new file mode 100644 index 0000000000..8e00b997b1 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug885800.js @@ -0,0 +1,11 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + var obj = Cu.evalInSandbox('this.obj = {foo: 2}; obj', sb); + var chromeSb = new Cu.Sandbox(this); + chromeSb.objRef = obj; + Assert.equal(Cu.evalInSandbox('objRef.foo', chromeSb), 2); + Cu.nukeSandbox(sb); + Assert.ok(Cu.isDeadWrapper(obj)); + // CCWs to nuked wrappers should be considered dead. + Assert.ok(Cu.isDeadWrapper(chromeSb.objRef)); +} diff --git a/js/xpconnect/tests/unit/test_bug930091.js b/js/xpconnect/tests/unit/test_bug930091.js new file mode 100644 index 0000000000..ae417293ba --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug930091.js @@ -0,0 +1,27 @@ +function checkThrows(fn) { + try { + fn(); + ok(false, "Should have thrown"); + } catch (e) { + ok(/denied|insecure|prohibited/.test(e)); + } +} + +function run_test() { + var xosb = new Cu.Sandbox('http://www.example.org'); + var sb = new Cu.Sandbox('http://www.example.com'); + sb.ok = ok; + sb.fun = function() { ok(false, "Shouldn't ever reach me"); }; + sb.cow = { foopy: 2, __exposedProps__: { foopy: 'rw' } }; + sb.payload = Cu.evalInSandbox('new Object()', xosb); + Cu.evalInSandbox(checkThrows.toSource(), sb); + Cu.evalInSandbox('checkThrows(function() { fun(payload); });', sb); + Cu.evalInSandbox('checkThrows(function() { Function.prototype.call.call(fun, payload); });', sb); + Cu.evalInSandbox('checkThrows(function() { Function.prototype.call.call(fun, null, payload); });', sb); + Cu.evalInSandbox('checkThrows(function() { new fun(payload); });', sb); + Cu.evalInSandbox('checkThrows(function() { cow.foopy = payload; });', sb); + Cu.evalInSandbox('checkThrows(function() { Object.defineProperty(cow, "foopy", { value: payload }); });', sb); + // These fail for a different reason, .bind can't access the length/name property on the function. + Cu.evalInSandbox('checkThrows(function() { Function.bind.call(fun, null, payload); });', sb); + Cu.evalInSandbox('checkThrows(function() { Function.bind.call(fun, payload); });', sb); +} diff --git a/js/xpconnect/tests/unit/test_bug976151.js b/js/xpconnect/tests/unit/test_bug976151.js new file mode 100644 index 0000000000..2e02c3c541 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug976151.js @@ -0,0 +1,23 @@ +/* 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/. */ + +function run_test() { + let unprivilegedSb = new Cu.Sandbox('http://www.example.com'); + function checkOpaqueWrapper(val) { + unprivilegedSb.prop = val; + try { + Cu.evalInSandbox('prop();', sb); + } catch (e) { + Assert.ok(/denied|insecure|/.test(e)); + } + } + let xoSb = new Cu.Sandbox('http://www.example.net'); + let epSb = new Cu.Sandbox(['http://www.example.com']); + checkOpaqueWrapper(eval); + checkOpaqueWrapper(xoSb.eval); + checkOpaqueWrapper(epSb.eval); + checkOpaqueWrapper(Function); + checkOpaqueWrapper(xoSb.Function); + checkOpaqueWrapper(epSb.Function); +} diff --git a/js/xpconnect/tests/unit/test_bug_442086.js b/js/xpconnect/tests/unit/test_bug_442086.js new file mode 100644 index 0000000000..ad1d8aabaa --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug_442086.js @@ -0,0 +1,36 @@ +/* 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/. */ + +// Bug 442086 - XPConnect creates doubles without checking for +// the INT_FITS_IN_JSVAL case + +var types = [ + 'PRUint8', + 'PRUint16', + 'PRUint32', + 'PRUint64', + 'PRInt16', + 'PRInt32', + 'PRInt64', + 'float', + 'double' +]; + +function run_test() +{ + var i; + for (i = 0; i < types.length; i++) { + var name = types[i]; + var cls = Cc["@mozilla.org/supports-" + name + ";1"]; + var ifname = ("nsISupports" + name.charAt(0).toUpperCase() + + name.substring(1)); + var f = cls.createInstance(Ci[ifname]); + + f.data = 0; + switch (f.data) { + case 0: /*ok*/ break; + default: do_throw("FAILED - bug 442086 (type=" + name + ")"); + } + } +} diff --git a/js/xpconnect/tests/unit/test_callFunctionWithAsyncStack.js b/js/xpconnect/tests/unit/test_callFunctionWithAsyncStack.js new file mode 100644 index 0000000000..87d98fc6ef --- /dev/null +++ b/js/xpconnect/tests/unit/test_callFunctionWithAsyncStack.js @@ -0,0 +1,30 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +function run_test() { + if (!Services.prefs.getBoolPref("javascript.options.asyncstack")) { + info("Async stacks are disabled."); + return; + } + + function getAsyncStack() { + return Components.stack; + } + + // asyncCause may contain non-ASCII characters. + let testAsyncCause = "Tes" + String.fromCharCode(355) + "String"; + + Cu.callFunctionWithAsyncStack(function asyncCallback() { + let stack = Components.stack; + + Assert.equal(stack.name, "asyncCallback"); + Assert.equal(stack.caller, null); + Assert.equal(stack.asyncCause, null); + + Assert.equal(stack.asyncCaller.name, "getAsyncStack"); + Assert.equal(stack.asyncCaller.asyncCause, testAsyncCause); + Assert.equal(stack.asyncCaller.asyncCaller, null); + + Assert.equal(stack.asyncCaller.caller.name, "run_test"); + Assert.equal(stack.asyncCaller.caller.asyncCause, null); + }, getAsyncStack(), testAsyncCause); +} diff --git a/js/xpconnect/tests/unit/test_cenums.js b/js/xpconnect/tests/unit/test_cenums.js new file mode 100644 index 0000000000..df929dc3d3 --- /dev/null +++ b/js/xpconnect/tests/unit/test_cenums.js @@ -0,0 +1,41 @@ +/* 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/. */ +function run_test() { + + // Load the component manifests. + registerXPCTestComponents(); + registerAppManifest(do_get_file('../components/js/xpctest.manifest')); + + // Test for each component. + test_interface_consts(); + test_component("@mozilla.org/js/xpc/test/native/CEnums;1"); + test_component("@mozilla.org/js/xpc/test/js/CEnums;1"); +} + +function test_interface_consts() { + Assert.equal(Ci.nsIXPCTestCEnums.testConst, 1); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe1Explicit, 1); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe2Explicit, 2); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe4Explicit, 4); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe8Explicit, 8); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe12Explicit, 12); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe1Implicit, 1); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe2Implicit, 2); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe3Implicit, 3); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe5Implicit, 5); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe6Implicit, 6); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe2AgainImplicit, 2); + Assert.equal(Ci.nsIXPCTestCEnums.shouldBe3AgainImplicit, 3); +} + +function test_component(contractid) { + + // Instantiate the object. + var o = Cc[contractid].createInstance(Ci["nsIXPCTestCEnums"]); + o.testCEnumInput(Ci.nsIXPCTestCEnums.shouldBe12Explicit); + o.testCEnumInput(Ci.nsIXPCTestCEnums.shouldBe8Explicit | Ci.nsIXPCTestCEnums.shouldBe4Explicit); + var a = o.testCEnumOutput(); + Assert.equal(a, Ci.nsIXPCTestCEnums.shouldBe8Explicit); +} + diff --git a/js/xpconnect/tests/unit/test_compileScript.js b/js/xpconnect/tests/unit/test_compileScript.js new file mode 100644 index 0000000000..8308df34d8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_compileScript.js @@ -0,0 +1,70 @@ +"use strict"; + +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +add_task(async function() { + let scriptUrl = Services.io.newFileURI(do_get_file("file_simple_script.js")).spec; + + + let script1 = await ChromeUtils.compileScript(scriptUrl, {hasReturnValue: true}); + let script2 = await ChromeUtils.compileScript(scriptUrl, {hasReturnValue: false}); + + equal(script1.url, scriptUrl, "Script URL is correct") + equal(script2.url, scriptUrl, "Script URL is correct") + + equal(script1.hasReturnValue, true, "Script hasReturnValue property is correct") + equal(script2.hasReturnValue, false, "Script hasReturnValue property is correct") + + + // Test return-value version. + + let sandbox1 = Cu.Sandbox("http://example.com"); + let sandbox2 = Cu.Sandbox("http://example.org"); + + let obj = script1.executeInGlobal(sandbox1); + equal(Cu.getObjectPrincipal(obj).origin, "http://example.com", "Return value origin is correct"); + equal(obj.foo, "\u00ae", "Return value has the correct charset"); + + obj = script1.executeInGlobal(sandbox2); + equal(Cu.getObjectPrincipal(obj).origin, "http://example.org", "Return value origin is correct"); + equal(obj.foo, "\u00ae", "Return value has the correct charset"); + + + // Test no-return-value version. + + sandbox1.bar = null; + equal(sandbox1.bar, null); + + obj = script2.executeInGlobal(sandbox1); + equal(obj, undefined, "No-return script has no return value"); + + equal(Cu.getObjectPrincipal(sandbox1.bar).origin, "http://example.com", "Object value origin is correct"); + equal(sandbox1.bar.foo, "\u00ae", "Object value has the correct charset"); + + + sandbox2.bar = null; + equal(sandbox2.bar, null); + + obj = script2.executeInGlobal(sandbox2); + equal(obj, undefined, "No-return script has no return value"); + + equal(Cu.getObjectPrincipal(sandbox2.bar).origin, "http://example.org", "Object value origin is correct"); + equal(sandbox2.bar.foo, "\u00ae", "Object value has the correct charset"); +}); + +add_task(async function test_syntaxError() { + // Generate an artificially large script to force off-main-thread + // compilation. + let scriptUrl = `data:,${";".repeat(1024 * 1024)}(`; + + await Assert.rejects( + ChromeUtils.compileScript(scriptUrl), + SyntaxError); + + // Generate a small script to force main thread compilation. + scriptUrl = `data:,;(`; + + await Assert.rejects( + ChromeUtils.compileScript(scriptUrl), + SyntaxError); +}); diff --git a/js/xpconnect/tests/unit/test_components.js b/js/xpconnect/tests/unit/test_components.js new file mode 100644 index 0000000000..e019b78f8f --- /dev/null +++ b/js/xpconnect/tests/unit/test_components.js @@ -0,0 +1,24 @@ +function run_test() { + var sb1 = Cu.Sandbox("http://www.blah.com"); + var sb2 = Cu.Sandbox(this); + var rv; + + // non-chrome accessing chrome Components + sb1.C = Components; + checkThrows("C.interfaces", sb1); + checkThrows("C.utils", sb1); + checkThrows("C.classes", sb1); + + // non-chrome accessing own Components: shouldn't exist. + Assert.equal(Cu.evalInSandbox("typeof Components", sb1), 'undefined'); + + // chrome accessing chrome + sb2.C = Components; + rv = Cu.evalInSandbox("C.utils", sb2); + Assert.equal(rv, Cu); +} + +function checkThrows(expression, sb) { + var result = Cu.evalInSandbox('(function() { try { ' + expression + '; return "allowed"; } catch (e) { return e.toString(); }})();', sb); + Assert.ok(!!/denied/.exec(result)); +} diff --git a/js/xpconnect/tests/unit/test_crypto.js b/js/xpconnect/tests/unit/test_crypto.js new file mode 100644 index 0000000000..ffaeba442d --- /dev/null +++ b/js/xpconnect/tests/unit/test_crypto.js @@ -0,0 +1,28 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + let sb = new Cu.Sandbox('https://www.example.com', + { wantGlobalProperties: + ["crypto", "TextEncoder", "TextDecoder", "isSecureContext"], + forceSecureContext: true, + }); + sb.ok = ok; + Cu.evalInSandbox('ok(this.crypto);', sb); + Cu.evalInSandbox('ok(this.crypto.subtle);', sb); + sb.equal = equal; + let innerPromise = new Promise(r => (sb.test_done = r)); + Cu.evalInSandbox('crypto.subtle.digest("SHA-256", ' + + ' new TextEncoder("utf-8").encode("abc"))' + + ' .then(h => equal(new Uint16Array(h)[0], 30906))' + + ' .then(test_done);', sb); + + Cu.importGlobalProperties(["crypto"]); + ok(crypto); + ok(crypto.subtle); + let outerPromise = crypto.subtle.digest("SHA-256", new TextEncoder("utf-8").encode("abc")) + .then(h => Assert.equal(new Uint16Array(h)[0], 30906)); + + do_test_pending(); + Promise.all([innerPromise, outerPromise]).then(() => do_test_finished()); +} diff --git a/js/xpconnect/tests/unit/test_css.js b/js/xpconnect/tests/unit/test_css.js new file mode 100644 index 0000000000..e6635d5293 --- /dev/null +++ b/js/xpconnect/tests/unit/test_css.js @@ -0,0 +1,9 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["CSS"] }); + sb.equal = equal; + Cu.evalInSandbox('equal(CSS.escape("$"), "\\\\$");', + sb); + Cu.importGlobalProperties(["CSS"]); + Assert.equal(CSS.escape("$"), "\\$"); +} diff --git a/js/xpconnect/tests/unit/test_deepFreezeClone.js b/js/xpconnect/tests/unit/test_deepFreezeClone.js new file mode 100644 index 0000000000..949b85f551 --- /dev/null +++ b/js/xpconnect/tests/unit/test_deepFreezeClone.js @@ -0,0 +1,31 @@ +function checkThrows(f, rgxp) { try { f(); do_check_false(); } catch (e) { Assert.ok(rgxp.test(e)); } } + +var o = { foo: 42, bar : { tick: 'tock' } }; +function checkClone(clone, frozen) { + var waived = Cu.waiveXrays(clone); + function touchFoo() { "use strict"; waived.foo = 12; Assert.equal(waived.foo, 12); } + function touchBar() { "use strict"; waived.bar.tick = 'tack'; Assert.equal(waived.bar.tick, 'tack'); } + function addProp() { "use strict"; waived.newProp = 100; Assert.equal(waived.newProp, 100); } + if (!frozen) { + touchFoo(); + touchBar(); + addProp(); + } else { + checkThrows(touchFoo, /read-only/); + checkThrows(touchBar, /read-only/); + checkThrows(addProp, /extensible/); + } + + var desc = Object.getOwnPropertyDescriptor(waived, 'foo'); + Assert.equal(desc.writable, !frozen); + Assert.equal(desc.configurable, !frozen); + desc = Object.getOwnPropertyDescriptor(waived.bar, 'tick'); + Assert.equal(desc.writable, !frozen); + Assert.equal(desc.configurable, !frozen); +} + +function run_test() { + var sb = new Cu.Sandbox(null); + checkClone(Cu.waiveXrays(Cu.cloneInto(o, sb)), false); + checkClone(Cu.cloneInto(o, sb, { deepFreeze: true }), true); +} diff --git a/js/xpconnect/tests/unit/test_defineModuleGetter.js b/js/xpconnect/tests/unit/test_defineModuleGetter.js new file mode 100644 index 0000000000..3af7508fae --- /dev/null +++ b/js/xpconnect/tests/unit/test_defineModuleGetter.js @@ -0,0 +1,115 @@ +"use strict"; + +function assertIsGetter(obj, prop) { + let desc = Object.getOwnPropertyDescriptor(obj, prop); + + ok(desc, `Property ${prop} exists on object`); + equal(typeof desc.get, "function", `Getter function exists for property ${prop}`); + equal(typeof desc.set, "function", `Setter function exists for property ${prop}`); + equal(desc.enumerable, true, `Property ${prop} is enumerable`); + equal(desc.configurable, true, `Property ${prop} is configurable`); +} + +function assertIsValue(obj, prop, value) { + let desc = Object.getOwnPropertyDescriptor(obj, prop); + + ok(desc, `Property ${prop} exists on object`); + + ok("value" in desc, `${prop} is a data property`); + equal(desc.value, value, `${prop} has the expected value`); + + equal(desc.enumerable, true, `Property ${prop} is enumerable`); + equal(desc.configurable, true, `Property ${prop} is configurable`); + equal(desc.writable, true, `Property ${prop} is writable`); +} + +add_task(async function() { + let temp = {}; + ChromeUtils.import("resource://gre/modules/Services.jsm", temp); + + let obj = {}; + let child = Object.create(obj); + let sealed = Object.seal(Object.create(obj)); + + + // Test valid import + + ChromeUtils.defineModuleGetter(obj, "Services", + "resource://gre/modules/Services.jsm"); + + assertIsGetter(obj, "Services"); + equal(child.Services, temp.Services, "Getter works on descendent object"); + assertIsValue(child, "Services", temp.Services); + assertIsGetter(obj, "Services"); + + Assert.throws(() => sealed.Services, /Object is not extensible/, + "Cannot access lazy getter from sealed object"); + Assert.throws(() => sealed.Services = null, /Object is not extensible/, + "Cannot access lazy setter from sealed object"); + assertIsGetter(obj, "Services"); + + equal(obj.Services, temp.Services, "Getter works on object"); + assertIsValue(obj, "Services", temp.Services); + + + // Test overwriting via setter + + child = Object.create(obj); + + ChromeUtils.defineModuleGetter(obj, "Services", + "resource://gre/modules/Services.jsm"); + + assertIsGetter(obj, "Services"); + + child.Services = "foo"; + assertIsValue(child, "Services", "foo"); + assertIsGetter(obj, "Services"); + + obj.Services = "foo"; + assertIsValue(obj, "Services", "foo"); + + + // Test import missing property + + ChromeUtils.defineModuleGetter(obj, "meh", + "resource://gre/modules/Services.jsm"); + assertIsGetter(obj, "meh"); + equal(obj.meh, undefined, "Missing property returns undefined"); + assertIsValue(obj, "meh", undefined); + + + // Test import broken module + + ChromeUtils.defineModuleGetter(obj, "broken", + "resource://test/bogus_exports_type.jsm"); + assertIsGetter(obj, "broken"); + + let errorPattern = /EXPORTED_SYMBOLS is not an array/; + Assert.throws(() => child.broken, errorPattern, + "Broken import throws on child"); + Assert.throws(() => child.broken, errorPattern, + "Broken import throws on child again"); + Assert.throws(() => sealed.broken, errorPattern, + "Broken import throws on sealed child"); + Assert.throws(() => obj.broken, errorPattern, + "Broken import throws on object"); + assertIsGetter(obj, "broken"); + + + // Test import missing module + + ChromeUtils.defineModuleGetter(obj, "missing", + "resource://test/does_not_exist.jsm"); + assertIsGetter(obj, "missing"); + + Assert.throws(() => obj.missing, /NS_ERROR_FILE_NOT_FOUND/, + "missing import throws on object"); + assertIsGetter(obj, "missing"); + + + // Test overwriting broken import via setter + + assertIsGetter(obj, "broken"); + obj.broken = "foo"; + assertIsValue(obj, "broken", "foo"); +}); diff --git a/js/xpconnect/tests/unit/test_exportFunction.js b/js/xpconnect/tests/unit/test_exportFunction.js new file mode 100644 index 0000000000..a7b2ca8056 --- /dev/null +++ b/js/xpconnect/tests/unit/test_exportFunction.js @@ -0,0 +1,152 @@ +function run_test() { + var epsb = new Cu.Sandbox(["http://example.com", "http://example.org"], { wantExportHelpers: true }); + var subsb = new Cu.Sandbox("http://example.com", { wantGlobalProperties: ["XMLHttpRequest"] }); + var subsb2 = new Cu.Sandbox("http://example.com", { wantGlobalProperties: ["XMLHttpRequest"] }); + var xorigsb = new Cu.Sandbox("http://test.com", { wantGlobalProperties: ["XMLHttpRequest"] }); + + epsb.subsb = subsb; + epsb.xorigsb = xorigsb; + epsb.ok = ok; + epsb.equal = equal; + subsb.ok = ok; + subsb.equal = equal; + + // Exporting should work if prinicipal of the source sandbox + // subsumes the principal of the target sandbox. + Cu.evalInSandbox("(" + function() { + var wasCalled = false; + this.funToExport = function(expectedThis, a, obj, native, mixed, callback) { + equal(arguments.callee.length, 6); + equal(a, 42); + equal(obj, subsb.tobecloned); + equal(obj.cloned, "cloned"); + equal(native, subsb.native); + equal(expectedThis, this); + equal(mixed.xrayed, subsb.xrayed); + equal(mixed.xrayed2, subsb.xrayed2); + if (typeof callback == 'function') { + equal(typeof subsb.callback, 'function'); + equal(callback, subsb.callback); + callback(); + } + wasCalled = true; + }; + this.checkIfCalled = function() { + ok(wasCalled); + wasCalled = false; + } + exportFunction(funToExport, subsb, { defineAs: "imported", allowCallbacks: true }); + exportFunction((x) => x, subsb, { defineAs: "echoAllowXO", allowCallbacks: true, allowCrossOriginArguments: true }); + }.toSource() + ")()", epsb); + + subsb.xrayed = Cu.evalInSandbox("(" + function () { + return new XMLHttpRequest(); + }.toSource() + ")()", subsb2); + + // Exported function should be able to be call from the + // target sandbox. Native arguments should be just wrapped + // every other argument should be cloned. + Cu.evalInSandbox("(" + function () { + native = new XMLHttpRequest(); + xrayed2 = XPCNativeWrapper(new XMLHttpRequest()); + mixed = { xrayed: xrayed, xrayed2: xrayed2 }; + tobecloned = { cloned: "cloned" }; + invokedCallback = false; + callback = function() { invokedCallback = true; }; + imported(this, 42, tobecloned, native, mixed, callback); + equal(imported.length, 6); + ok(invokedCallback); + }.toSource() + ")()", subsb); + + // Invoking an exported function with cross-origin arguments should throw. + subsb.xoNative = Cu.evalInSandbox('new XMLHttpRequest()', xorigsb); + try { + Cu.evalInSandbox('imported(this, xoNative)', subsb); + Assert.ok(false); + } catch (e) { + Assert.ok(/denied|insecure/.test(e)); + } + + // Callers can opt-out of the above. + subsb.xoNative = Cu.evalInSandbox('new XMLHttpRequest()', xorigsb); + try { + Assert.equal(Cu.evalInSandbox('echoAllowXO(xoNative)', subsb), subsb.xoNative); + Assert.ok(true); + } catch (e) { + Assert.ok(false); + } + + // Apply should work and |this| should carry over appropriately. + Cu.evalInSandbox("(" + function() { + var someThis = {}; + imported.apply(someThis, [someThis, 42, tobecloned, native, mixed]); + }.toSource() + ")()", subsb); + + Cu.evalInSandbox("(" + function() { + checkIfCalled(); + }.toSource() + ")()", epsb); + + // Exporting should throw if principal of the source sandbox does + // not subsume the principal of the target. + Cu.evalInSandbox("(" + function() { + try{ + exportFunction(function() {}, this.xorigsb, { defineAs: "denied" }); + ok(false); + } catch (e) { + ok(e.toString().indexOf('Permission denied') > -1); + } + }.toSource() + ")()", epsb); + + // Exporting should throw if the principal of the source sandbox does + // not subsume the principal of the function. + epsb.xo_function = new xorigsb.Function(); + Cu.evalInSandbox("(" + function() { + try{ + exportFunction(xo_function, this.subsb, { defineAs: "denied" }); + ok(false); + } catch (e) { + dump('Exception: ' + e); + ok(e.toString().indexOf('Permission denied') > -1); + } + }.toSource() + ")()", epsb); + + // Let's create an object in the target scope and add privileged + // function to it as a property. + Cu.evalInSandbox("(" + function() { + var newContentObject = createObjectIn(subsb, { defineAs: "importedObject" }); + exportFunction(funToExport, newContentObject, { defineAs: "privMethod" }); + }.toSource() + ")()", epsb); + + Cu.evalInSandbox("(" + function () { + importedObject.privMethod(importedObject, 42, tobecloned, native, mixed); + }.toSource() + ")()", subsb); + + Cu.evalInSandbox("(" + function() { + checkIfCalled(); + }.toSource() + ")()", epsb); + + // exportFunction and createObjectIn should be available from Cu too. + var newContentObject = Cu.createObjectIn(subsb, { defineAs: "importedObject2" }); + var wasCalled = false; + Cu.exportFunction(function(arg) { wasCalled = arg.wasCalled; }, + newContentObject, { defineAs: "privMethod" }); + + Cu.evalInSandbox("(" + function () { + importedObject2.privMethod({wasCalled: true}); + }.toSource() + ")()", subsb); + + // 3rd argument of exportFunction should be optional. + Cu.evalInSandbox("(" + function() { + subsb.imported2 = exportFunction(funToExport, subsb); + }.toSource() + ")()", epsb); + + Cu.evalInSandbox("(" + function () { + imported2(this, 42, tobecloned, native, mixed); + }.toSource() + ")()", subsb); + + Cu.evalInSandbox("(" + function() { + checkIfCalled(); + }.toSource() + ")()", epsb); + + Assert.ok(wasCalled); +} diff --git a/js/xpconnect/tests/unit/test_file.js b/js/xpconnect/tests/unit/test_file.js new file mode 100644 index 0000000000..f0a22ab45f --- /dev/null +++ b/js/xpconnect/tests/unit/test_file.js @@ -0,0 +1,19 @@ +/* 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/. */ + +add_task(function() { + do_load_manifest("component-file.manifest"); + const contractID = "@mozilla.org/tests/component-file;1"; + Assert.ok(contractID in Cc); + var foo = Cc[contractID] + .createInstance(Ci.nsIClassInfo); + Assert.ok(Boolean(foo)); + Assert.ok(foo.contractID == contractID); + Assert.ok(!!foo.wrappedJSObject); + + foo.wrappedJSObject.doTest(result => { + Assert.ok(result); + run_next_test(); + }); +}); diff --git a/js/xpconnect/tests/unit/test_file2.js b/js/xpconnect/tests/unit/test_file2.js new file mode 100644 index 0000000000..9c72eb4c62 --- /dev/null +++ b/js/xpconnect/tests/unit/test_file2.js @@ -0,0 +1,60 @@ +/* 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/. */ + +Cu.importGlobalProperties(['File']); + +add_task(async function() { + // throw if anything goes wrong + + // find the current directory path + var file = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("CurWorkD", Ci.nsIFile); + file.append("xpcshell.ini"); + + // should be able to construct a file + var f1 = await File.createFromFileName(file.path); + // and with nsIFiles + var f2 = await File.createFromNsIFile(file); + + // do some tests + Assert.ok(f1 instanceof File, "Should be a DOM File"); + Assert.ok(f2 instanceof File, "Should be a DOM File"); + + Assert.ok(f1.name == "xpcshell.ini", "Should be the right file"); + Assert.ok(f2.name == "xpcshell.ini", "Should be the right file"); + + Assert.ok(f1.type == "", "Should be the right type"); + Assert.ok(f2.type == "", "Should be the right type"); + + var threw = false; + try { + // Needs a ctor argument + var f7 = File(); + } catch (e) { + threw = true; + } + Assert.ok(threw, "No ctor arguments should throw"); + + var threw = false; + try { + // Needs a valid ctor argument + var f7 = File(Date(132131532)); + } catch (e) { + threw = true; + } + Assert.ok(threw, "Passing a random object should fail"); + + var threw = false + try { + // Directories fail + var dir = Cc["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("CurWorkD", Ci.nsIFile); + var f7 = await File.createFromNsIFile(dir) + } catch (e) { + threw = true; + } + Assert.ok(threw, "Can't create a File object for a directory"); +}); diff --git a/js/xpconnect/tests/unit/test_fileReader.js b/js/xpconnect/tests/unit/test_fileReader.js new file mode 100644 index 0000000000..ea86096319 --- /dev/null +++ b/js/xpconnect/tests/unit/test_fileReader.js @@ -0,0 +1,12 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["FileReader"] }); + sb.ok = ok; + Cu.evalInSandbox('ok((new FileReader()) instanceof FileReader);', + sb); + Cu.importGlobalProperties(["FileReader"]); + Assert.ok((new FileReader()) instanceof FileReader); +} diff --git a/js/xpconnect/tests/unit/test_function_names.js b/js/xpconnect/tests/unit/test_function_names.js new file mode 100644 index 0000000000..6eadc1fce7 --- /dev/null +++ b/js/xpconnect/tests/unit/test_function_names.js @@ -0,0 +1,37 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function callback() {} + +let sandbox = Cu.Sandbox(this); +let callbackWrapped = Cu.evalInSandbox("(function wrapped() {})", sandbox); + +function run_test() { + let functions = [ + [{ notify: callback }, "callback[test_function_names.js]:JS"], + [{ notify: { notify: callback } }, "callback[test_function_names.js]:JS"], + [callback, "callback[test_function_names.js]:JS"], + [function() {}, "run_test/functions<[test_function_names.js]:JS"], + [function foobar() {}, "foobar[test_function_names.js]:JS"], + [function Δ() {}, "Δ[test_function_names.js]:JS"], + [{ notify1: callback, notify2: callback }, "nonfunction:JS"], + [{ notify: 10 }, "nonfunction:JS"], + [{}, "nonfunction:JS"], + [{ notify: callbackWrapped }, "wrapped[test_function_names.js]:JS"], + ]; + + // Use the observer service so we can get double-wrapped functions. + var obs = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); + + function observer(subject, topic, data) + { + let named = subject.QueryInterface(Ci.nsINamed); + Assert.equal(named.name, data); + dump(`name: ${named.name}\n`); + } + obs.addObserver(observer, "test-obs-fun", false); + + for (let [f, requiredName] of functions) { + obs.notifyObservers(f, "test-obs-fun", requiredName); + } +} diff --git a/js/xpconnect/tests/unit/test_generateQI.js b/js/xpconnect/tests/unit/test_generateQI.js new file mode 100644 index 0000000000..d54ed53212 --- /dev/null +++ b/js/xpconnect/tests/unit/test_generateQI.js @@ -0,0 +1,29 @@ +"use strict"; + +add_task(async function test_generateQI() { + function checkQI(interfaces, iface) { + let obj = { + QueryInterface: ChromeUtils.generateQI(interfaces), + }; + equal(obj.QueryInterface(iface), obj, + `Correct return value for query to ${iface}`); + } + + // Test success scenarios. + checkQI([], Ci.nsISupports); + + checkQI([Ci.nsIPropertyBag, "nsIPropertyBag2"], Ci.nsIPropertyBag); + checkQI([Ci.nsIPropertyBag, "nsIPropertyBag2"], Ci.nsIPropertyBag2); + + checkQI([Ci.nsIPropertyBag, "nsIPropertyBag2", "nsINotARealInterface"], Ci.nsIPropertyBag2); + + // Non-IID values get stringified, and don't cause any errors as long + // as there isn't a non-IID property with the same name on Ci. + checkQI([Ci.nsIPropertyBag, "nsIPropertyBag2", null, Object], Ci.nsIPropertyBag2); + + ChromeUtils.generateQI([])(Ci.nsISupports); + + // Test failure scenarios. + Assert.throws(() => checkQI([], Ci.nsIPropertyBag), + e => e.result == Cr.NS_ERROR_NO_INTERFACE); +}); diff --git a/js/xpconnect/tests/unit/test_getCallerLocation.js b/js/xpconnect/tests/unit/test_getCallerLocation.js new file mode 100644 index 0000000000..1a6ce37357 --- /dev/null +++ b/js/xpconnect/tests/unit/test_getCallerLocation.js @@ -0,0 +1,86 @@ +/* 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"; + +Cu.importGlobalProperties(["ChromeUtils"]); + +const {AddonTestUtils} = ChromeUtils.import("resource://testing-common/AddonTestUtils.jsm"); + +add_task(async function() { + const sandbox = Cu.Sandbox("http://example.com/"); + + function foo() { + return bar(); + } + + function bar() { + return baz(); + } + + function baz() { + return ChromeUtils.getCallerLocation(Cu.getObjectPrincipal(sandbox)); + } + + Cu.evalInSandbox(` + function it() { + // Use map() to throw a self-hosted frame on the stack, which we + // should filter out. + return [0].map(foo)[0]; + } + function thing() { + return it(); + } + `, sandbox, undefined, "thing.js"); + + Cu.exportFunction(foo, sandbox, {defineAs: "foo"}); + + let frame = sandbox.thing(); + + equal(frame.source, "thing.js", "Frame source"); + equal(frame.line, 5, "Frame line"); + equal(frame.column, 18, "Frame column"); + equal(frame.functionDisplayName, "it", "Frame function name"); + equal(frame.parent, null, "Frame parent"); + + equal(String(frame), "it@thing.js:5:18\n", "Stringified frame"); + + + // reportError + + let {messages} = await AddonTestUtils.promiseConsoleOutput(() => { + Cu.reportError("Meh", frame); + }); + + let [msg] = messages.filter(m => m.message.includes("Meh")); + + equal(msg.stack, frame, "reportError stack frame"); + equal(msg.message, '[JavaScript Error: "Meh" {file: "thing.js" line: 5}]\nit@thing.js:5:18\n'); + + Assert.throws(() => { Cu.reportError("Meh", {}); }, + err => err.result == Cr.NS_ERROR_INVALID_ARG, + "reportError should throw when passed a non-SavedFrame object"); + + + // createError + + Assert.throws(() => { ChromeUtils.createError("Meh", {}); }, + err => err.result == Cr.NS_ERROR_INVALID_ARG, + "createError should throw when passed a non-SavedFrame object"); + + let cloned = Cu.cloneInto(frame, sandbox); + let error = ChromeUtils.createError("Meh", cloned); + + equal(String(cloned), String(frame), + "Cloning a SavedStack preserves its stringification"); + + equal(Cu.getGlobalForObject(error), sandbox, + "createError creates errors in the global of the SavedFrame"); + equal(error.stack, String(cloned), + "createError creates errors with the correct stack"); + + equal(error.message, "Meh", "Error message"); + equal(error.fileName, "thing.js", "Error filename"); + equal(error.lineNumber, 5, "Error line"); + equal(error.columnNumber, 18, "Error column"); +}); diff --git a/js/xpconnect/tests/unit/test_getObjectPrincipal.js b/js/xpconnect/tests/unit/test_getObjectPrincipal.js new file mode 100644 index 0000000000..03c6ffce3d --- /dev/null +++ b/js/xpconnect/tests/unit/test_getObjectPrincipal.js @@ -0,0 +1,6 @@ +function run_test() { + Assert.ok(Cu.getObjectPrincipal({}).isSystemPrincipal); + var sb = new Cu.Sandbox('http://www.example.com'); + Cu.evalInSandbox('var obj = { foo: 42 };', sb); + Assert.equal(Cu.getObjectPrincipal(sb.obj).origin, 'http://www.example.com'); +} diff --git a/js/xpconnect/tests/unit/test_import.js b/js/xpconnect/tests/unit/test_import.js new file mode 100644 index 0000000000..9be6158fd1 --- /dev/null +++ b/js/xpconnect/tests/unit/test_import.js @@ -0,0 +1,91 @@ +/* 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/. */ + +var XPCOMUtils; +function run_test() { + var scope = {}; + var exports = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", scope); + Assert.equal(typeof(scope.XPCOMUtils), "object"); + Assert.equal(typeof(scope.XPCOMUtils.defineLazyGetter), "function"); + + equal(scope.XPCOMUtils, exports.XPCOMUtils); + deepEqual(Object.keys(scope), ["XPCOMUtils"]); + deepEqual(Object.keys(exports), ["XPCOMUtils"]); + + exports = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); + equal(scope.XPCOMUtils, exports.XPCOMUtils); + deepEqual(Object.keys(exports), ["XPCOMUtils"]); + + // access module's global object directly without importing any + // symbols + var module = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", null); + Assert.equal(typeof(XPCOMUtils), "undefined"); + Assert.equal(typeof(module), "object"); + Assert.equal(typeof(module.XPCOMUtils), "object"); + Assert.equal(typeof(module.XPCOMUtils.defineLazyGetter), "function"); + Assert.ok(scope.XPCOMUtils == module.XPCOMUtils); + + // import symbols to our global object + Assert.equal(typeof(Cu.import), "function"); + ({XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm")); + Assert.equal(typeof(XPCOMUtils), "object"); + Assert.equal(typeof(XPCOMUtils.defineLazyGetter), "function"); + + // try on a new object + var scope2 = {}; + ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", scope2); + Assert.equal(typeof(scope2.XPCOMUtils), "object"); + Assert.equal(typeof(scope2.XPCOMUtils.defineLazyGetter), "function"); + + Assert.ok(scope2.XPCOMUtils == scope.XPCOMUtils); + + // try on a new object using the resolved URL + var res = Cc["@mozilla.org/network/protocol;1?name=resource"] + .getService(Ci.nsIResProtocolHandler); + var resURI = Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService) + .newURI("resource://gre/modules/XPCOMUtils.jsm"); + dump("resURI: " + resURI + "\n"); + var filePath = res.resolveURI(resURI); + var scope3 = {}; + Assert.throws(() => ChromeUtils.import(filePath, scope3), + /NS_ERROR_UNEXPECTED/); + + // make sure we throw when the second arg is bogus + var didThrow = false; + try { + ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", "wrong"); + } catch (ex) { + print("exception (expected): " + ex); + didThrow = true; + } + Assert.ok(didThrow); + + // try to create a component + do_load_manifest("component_import.manifest"); + const contractID = "@mozilla.org/tests/module-importer;"; + Assert.ok((contractID + "1") in Cc); + var foo = Cc[contractID + "1"] + .createInstance(Ci.nsIClassInfo); + Assert.ok(Boolean(foo)); + Assert.ok(foo.contractID == contractID + "1"); + // XXX the following check succeeds only if the test component wasn't + // already registered. Need to figure out a way to force registration + // (to manually force it, delete compreg.dat before running the test) + // do_check_true(foo.wrappedJSObject.postRegisterCalled); + + // Call getInterfaces to test line numbers in JS components. But as long as + // we're doing that, why not test what it returns too? + var interfaces = foo.interfaces; + Assert.ok(Array.isArray(interfaces)); + Assert.equal(interfaces.length, 1); + Assert.ok(interfaces[0].equals(Ci.nsIClassInfo)) + + // try to create another component which doesn't directly implement QI + Assert.ok((contractID + "2") in Cc); + var bar = Cc[contractID + "2"] + .createInstance(Ci.nsIClassInfo); + Assert.ok(Boolean(bar)); + Assert.ok(bar.contractID == contractID + "2"); +} diff --git a/js/xpconnect/tests/unit/test_import_fail.js b/js/xpconnect/tests/unit/test_import_fail.js new file mode 100644 index 0000000000..9ad7fcb072 --- /dev/null +++ b/js/xpconnect/tests/unit/test_import_fail.js @@ -0,0 +1,10 @@ +function run_test() +{ + try { + ChromeUtils.import("resource://test/importer.jsm"); + Assert.ok(false, "import should not succeed."); + } catch (x) { + Assert.notEqual(x.fileName.indexOf("syntax_error.jsm"), -1); + Assert.equal(x.lineNumber, 1); + } +}
\ No newline at end of file diff --git a/js/xpconnect/tests/unit/test_isModuleLoaded.js b/js/xpconnect/tests/unit/test_isModuleLoaded.js new file mode 100644 index 0000000000..338c283ad8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_isModuleLoaded.js @@ -0,0 +1,22 @@ +function run_test() { + // Existing module. + Assert.ok(Cu.isModuleLoaded("resource://gre/modules/NetUtil.jsm"), + "isModuleLoaded returned correct value for non-loaded module"); + ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); + Assert.ok(Cu.isModuleLoaded("resource://gre/modules/NetUtil.jsm"), + "isModuleLoaded returned true after loading that module"); + Cu.unload("resource://gre/modules/NetUtil.jsm"); + Assert.ok(!Cu.isModuleLoaded("resource://gre/modules/NetUtil.jsm"), + "isModuleLoaded returned false after unloading that module"); + + // Non-existing module + Assert.ok(!Cu.isModuleLoaded("resource://gre/modules/non-existing-module.jsm"), + "isModuleLoaded returned correct value for non-loaded module"); + try { + ChromeUtils.import("resource://gre/modules/non-existing-module.jsm"); + Assert.ok(false, + "Should have thrown while trying to load a non existing file"); + } catch (ex) {} + Assert.ok(!Cu.isModuleLoaded("resource://gre/modules/non-existing-module.jsm"), + "isModuleLoaded returned correct value for non-loaded module"); +} diff --git a/js/xpconnect/tests/unit/test_isProxy.js b/js/xpconnect/tests/unit/test_isProxy.js new file mode 100644 index 0000000000..996aa320b9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_isProxy.js @@ -0,0 +1,26 @@ +function run_test() { + var handler = { + get: function(target, name){ + return name in target? + target[name] : + 37; + } + }; + + var p = new Proxy({}, handler); + Assert.ok(Cu.isProxy(p)); + Assert.ok(!Cu.isProxy({})); + Assert.ok(!Cu.isProxy(42)); + + sb = new Cu.Sandbox(this, + { wantExportHelpers: true }); + + Assert.ok(!Cu.isProxy(sb)); + + sb.ok = ok; + sb.p = p; + Cu.evalInSandbox('ok(isProxy(p));' + + 'ok(!isProxy({}));' + + 'ok(!isProxy(42));', + sb); +} diff --git a/js/xpconnect/tests/unit/test_js_memory_telemetry.js b/js/xpconnect/tests/unit/test_js_memory_telemetry.js new file mode 100644 index 0000000000..d5ba4ab39d --- /dev/null +++ b/js/xpconnect/tests/unit/test_js_memory_telemetry.js @@ -0,0 +1,55 @@ +"use strict"; + +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +add_task(function test_compartment_realm_counts() { + const compsSystem = "MEMORY_JS_COMPARTMENTS_SYSTEM"; + const compsUser = "MEMORY_JS_COMPARTMENTS_USER"; + const realmsSystem = "MEMORY_JS_REALMS_SYSTEM"; + const realmsUser = "MEMORY_JS_REALMS_USER"; + + Cu.forceShrinkingGC(); + + Services.telemetry.gatherMemory(); + let snapshot1 = Services.telemetry.getSnapshotForHistograms("main", true).parent; + + // We can't hard code exact counts, but we can check some basic invariants: + // + // * Compartments must contain at least one realm, so there must be more + // realms than compartments. + // * There must be at least one system realm. + + Assert.ok(snapshot1[realmsSystem].sum <= snapshot1[compsSystem].sum, + "Number of system compartments can't exceed number of system realms"); + Assert.ok(snapshot1[realmsUser].sum <= snapshot1[compsUser].sum, + "Number of user compartments can't exceed number of user realms"); + Assert.ok(snapshot1[realmsSystem].sum > 0, + "There must be at least one system realm"); + + // Now we create a bunch of sandboxes (more than one to be more resilient + // against GCs happening in the meantime), so we can check: + // + // * There are now more realms and user compartments than before. Not system + // compartments, because system realms share a compartment. + // * The system compartment contains multiple realms. + + let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); + let arr = []; + for (let i = 0; i < 5; i++) { + arr.push(Cu.Sandbox(null)); + arr.push(Cu.Sandbox(systemPrincipal)); + } + + Services.telemetry.gatherMemory(); + let snapshot2 = Services.telemetry.getSnapshotForHistograms("main", true).parent; + + for (let k of [realmsSystem, realmsUser, compsUser]) { + Assert.ok(snapshot2[k].sum > snapshot1[k].sum, + "There must be more compartments/realms now: " + k); + } + + Assert.ok(snapshot2[realmsSystem].sum > snapshot2[compsSystem].sum, + "There must be more system realms than system compartments now"); + + arr[0].x = 10; // Ensure the JS engine keeps |arr| alive until this point. +}); diff --git a/js/xpconnect/tests/unit/test_js_weak_references.js b/js/xpconnect/tests/unit/test_js_weak_references.js new file mode 100644 index 0000000000..2603f24ee2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_js_weak_references.js @@ -0,0 +1,45 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=317304 */ + +function run_test() +{ + // Bug 712649: Calling getWeakReference(null) should work. + try { + var nullWeak = Cu.getWeakReference(null); + Assert.ok(nullWeak.get() === null); + } catch (e) { + Assert.ok(false); + } + + var obj = { num: 5, str: 'foo' }; + var weak = Cu.getWeakReference(obj); + + Assert.ok(weak.get() === obj); + Assert.ok(weak.get().num == 5); + Assert.ok(weak.get().str == 'foo'); + + // Force garbage collection + Cu.forceGC(); + + // obj still references the object, so it should still be accessible via weak + Assert.ok(weak.get() === obj); + Assert.ok(weak.get().num == 5); + Assert.ok(weak.get().str == 'foo'); + + // Clear obj's reference to the object and force garbage collection. To make + // sure that there are no instances of obj stored in the registers or on the + // native stack and the conservative GC would not find it we force the same + // code paths that we used for the initial allocation. + obj = { num: 6, str: 'foo2' }; + var weak2 = Cu.getWeakReference(obj); + Assert.ok(weak2.get() === obj); + + Cu.forceGC(); + + // The object should have been garbage collected and so should no longer be + // accessible via weak + Assert.ok(weak.get() === null); +} diff --git a/js/xpconnect/tests/unit/test_lazyproxy.js b/js/xpconnect/tests/unit/test_lazyproxy.js new file mode 100644 index 0000000000..0bea7385e0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_lazyproxy.js @@ -0,0 +1,113 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +/** + * This file tests the method defineLazyProxy from XPCOMUtils.jsm. + */ + +const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); + +add_task(function test_lazy_proxy() { + let tmp = {}; + let realObject = { + "prop1": "value1", + "prop2": "value2", + }; + + let evaluated = false; + let untrapCalled = false; + + let lazyProxy = XPCOMUtils.defineLazyProxy( + tmp, + "myLazyProxy", + + // Initiliazer function + function init() { + evaluated = true; + return realObject; + }, + + // Stub properties + { + "prop1": "stub" + }, + + // Untrap callback + function untrapCallback(obj) { + Assert.equal(obj, realObject, "The underlying object can be obtained in the untrap callback"); + untrapCalled = true; + } + ); + + // Check that the proxy returned and the one + // defined in tmp are the same. + // + // Note: Assert.strictEqual can't be used here + // because it wants to stringify the two objects + // compared, which defeats the lazy proxy. + Assert.ok(lazyProxy === tmp.myLazyProxy, "Return value and object defined are the same"); + + Assert.ok(Cu.isProxy(lazyProxy), "Returned value is in fact a proxy"); + + // Check that just using the proxy above didn't + // trigger the lazy getter evaluation. + Assert.ok(!evaluated, "The lazy proxy hasn't been evaluated yet"); + Assert.ok(!untrapCalled, "The untrap callback hasn't been called yet"); + + // Accessing a stubbed property returns the stub + // value and doesn't trigger evaluation. + Assert.equal(lazyProxy.prop1, "stub", "Accessing a stubbed property returns the stubbed value"); + + Assert.ok(!evaluated, "The access to the stubbed property above didn't evaluate the lazy proxy"); + Assert.ok(!untrapCalled, "The untrap callback hasn't been called yet"); + + // Now the access to another property will trigger + // the evaluation, as expected. + Assert.equal(lazyProxy.prop2, "value2", "Property access is correctly forwarded to the underlying object"); + + Assert.ok(evaluated, "Accessing a non-stubbed property triggered the proxy evaluation"); + Assert.ok(untrapCalled, "The untrap callback was called"); + + // The value of prop1 is now the real value and not the stub value. + Assert.equal(lazyProxy.prop1, "value1", "The value of prop1 is now the real value and not the stub one"); +}); + +add_task(function test_module_version() { + // Test that passing a string instead of an initialization function + // makes this behave like a lazy module getter. + const NET_UTIL_URI = "resource://gre/modules/NetUtil.jsm"; + let underlyingObject; + + Cu.unload(NET_UTIL_URI); + + let lazyProxy = XPCOMUtils.defineLazyProxy( + null, + "NetUtil", + NET_UTIL_URI, + null, /* no stubs */ + function untrapCallback(object) { + underlyingObject = object; + } + ); + + Assert.ok(!Cu.isModuleLoaded(NET_UTIL_URI), "The NetUtil module was not loaded by the lazy proxy definition"); + + // Access the object, which will evaluate the proxy. + lazyProxy.foo = "bar"; + + // Module was loaded. + Assert.ok(Cu.isModuleLoaded(NET_UTIL_URI), "The NetUtil module was loaded"); + + let { NetUtil } = ChromeUtils.import(NET_UTIL_URI, {}); + + // Avoids a gigantic stringification in the logs. + Assert.ok(NetUtil === underlyingObject, "The module loaded is the same as the one directly obtained by ChromeUtils.import"); + + // Proxy correctly passed the setter to the underlying object. + Assert.equal(NetUtil.foo, "bar", "Proxy correctly passed the setter to the underlying object"); + + delete lazyProxy.foo; + + // Proxy correctly passed the delete operation to the underlying object. + Assert.ok(!NetUtil.hasOwnProperty("foo"), "Proxy correctly passed the delete operation to the underlying object"); +}); diff --git a/js/xpconnect/tests/unit/test_localeCompare.js b/js/xpconnect/tests/unit/test_localeCompare.js new file mode 100644 index 0000000000..fa98d865e4 --- /dev/null +++ b/js/xpconnect/tests/unit/test_localeCompare.js @@ -0,0 +1,6 @@ +function run_test() { + Assert.ok("C".localeCompare("D") < 0); + Assert.ok("D".localeCompare("C") > 0); + Assert.ok("\u010C".localeCompare("D") < 0); + Assert.ok("D".localeCompare("\u010C") > 0); +} diff --git a/js/xpconnect/tests/unit/test_messageChannel.js b/js/xpconnect/tests/unit/test_messageChannel.js new file mode 100644 index 0000000000..685aa10e43 --- /dev/null +++ b/js/xpconnect/tests/unit/test_messageChannel.js @@ -0,0 +1,29 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +add_task(async function() { + let sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["MessageChannel"] }); + sb.ok = ok; + Cu.evalInSandbox('ok((new MessageChannel()) instanceof MessageChannel);', + sb); + Cu.evalInSandbox('ok((new MessageChannel()).port1 instanceof MessagePort);', + sb); + + Cu.importGlobalProperties(["MessageChannel"]); + + let mc = new MessageChannel(); + Assert.ok(mc instanceof MessageChannel); + Assert.ok(mc.port1 instanceof MessagePort); + Assert.ok(mc.port2 instanceof MessagePort); + + mc.port1.postMessage(42); + + let result = await new Promise(resolve => { + mc.port2.onmessage = e => { + resolve(e.data); + } + }); + + Assert.equal(result, 42); +}); diff --git a/js/xpconnect/tests/unit/test_nuke_sandbox.js b/js/xpconnect/tests/unit/test_nuke_sandbox.js new file mode 100644 index 0000000000..c555121306 --- /dev/null +++ b/js/xpconnect/tests/unit/test_nuke_sandbox.js @@ -0,0 +1,50 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=769273 */ + +const global = this; + +function run_test() +{ + var ifacePointer = Cc["@mozilla.org/supports-interface-pointer;1"] + .createInstance(Ci.nsISupportsInterfacePointer); + + var sb = Cu.Sandbox(global, {wantGlobalProperties: ["ChromeUtils"]}); + sb.prop = "prop" + sb.ifacePointer = ifacePointer + + var refToObjFromSb = Cu.evalInSandbox(` + ifacePointer.data = { + QueryInterface: ChromeUtils.generateQI([]), + wrappedJSObject: {foo: "bar"}, + }; + + var a = {prop2:'prop2'}; + a + `, sb); + + equal(ifacePointer.data.wrappedJSObject.foo, "bar", + "Got expected wrapper into sandbox") + + Cu.nukeSandbox(sb); + ok(Cu.isDeadWrapper(sb), "sb should be dead"); + ok(Cu.isDeadWrapper(ifacePointer.data.wrappedJSObject), + "Wrapper retrieved via XPConnect should be dead"); + + try{ + sb.prop; + Assert.ok(false); + } catch (e) { + Assert.ok(e.toString().indexOf("can't access dead object") > -1); + } + + Cu.isDeadWrapper(refToObjFromSb, "ref to object from sb should be dead"); + try{ + refToObjFromSb.prop2; + Assert.ok(false); + } catch (e) { + Assert.ok(e.toString().indexOf("can't access dead object") > -1); + } +} diff --git a/js/xpconnect/tests/unit/test_nuke_sandbox_event_listeners.js b/js/xpconnect/tests/unit/test_nuke_sandbox_event_listeners.js new file mode 100644 index 0000000000..159b583cc7 --- /dev/null +++ b/js/xpconnect/tests/unit/test_nuke_sandbox_event_listeners.js @@ -0,0 +1,91 @@ +/* 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/. */ + +// See https://bugzilla.mozilla.org/show_bug.cgi?id=1273251 + +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +function promiseEvent(target, event) { + return new Promise(resolve => { + target.addEventListener(event, resolve, {capture: true, once: true}); + }); +} + +add_task(async function() { + let principal = Services.scriptSecurityManager + .createContentPrincipalFromOrigin("http://example.com/"); + + let webnav = Services.appShell.createWindowlessBrowser(false); + + let docShell = webnav.docShell; + + docShell.createAboutBlankContentViewer(principal, principal); + + let window = webnav.document.defaultView; + let sandbox = Cu.Sandbox(window, {sandboxPrototype: window}); + + function sandboxContent() { + window.onload = function SandboxOnLoad() {}; + + window.addEventListener("FromTest", () => { + window.dispatchEvent(new CustomEvent("FromSandbox")); + }, true); + } + + Cu.evalInSandbox(`(${sandboxContent})()`, sandbox); + + + let fromTestPromise = promiseEvent(window, "FromTest"); + let fromSandboxPromise = promiseEvent(window, "FromSandbox"); + + equal(typeof window.onload, "function", + "window.onload should contain sandbox event listener"); + equal(window.onload.name, "SandboxOnLoad", + "window.onload have the correct function name"); + + info("Dispatch FromTest event"); + window.dispatchEvent(new window.CustomEvent("FromTest")); + + await fromTestPromise; + info("Got event from test"); + + await fromSandboxPromise; + info("Got response from sandbox"); + + + window.addEventListener("FromSandbox", () => { + ok(false, "Got unexpected reply from sandbox"); + }, true); + + info("Nuke sandbox"); + Cu.nukeSandbox(sandbox); + + + info("Dispatch FromTest event"); + fromTestPromise = promiseEvent(window, "FromTest"); + window.dispatchEvent(new window.CustomEvent("FromTest")); + await fromTestPromise; + info("Got event from test"); + + + // Force cycle collection, which should cause our callback reference + // to be dropped, and dredge up potential issues there. + Cu.forceGC(); + Cu.forceCC(); + + ok(Cu.isDeadWrapper(window.onload), + "window.onload should contain a dead wrapper after sandbox is nuked"); + + info("Dispatch FromTest event"); + fromTestPromise = promiseEvent(window, "FromTest"); + window.dispatchEvent(new window.CustomEvent("FromTest")); + await fromTestPromise; + info("Got event from test"); + + let listeners = Services.els.getListenerInfoFor(window); + ok(!listeners.some(info => info.type == "FromTest"), + "No 'FromTest' listeners returned for nuked sandbox"); + + webnav.close(); +}); diff --git a/js/xpconnect/tests/unit/test_nuke_webextension_wrappers.js b/js/xpconnect/tests/unit/test_nuke_webextension_wrappers.js new file mode 100644 index 0000000000..5664561778 --- /dev/null +++ b/js/xpconnect/tests/unit/test_nuke_webextension_wrappers.js @@ -0,0 +1,72 @@ +// See https://bugzilla.mozilla.org/show_bug.cgi?id=1273251 + +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const {TestUtils} = ChromeUtils.import("resource://testing-common/TestUtils.jsm"); + +function getWindowlessBrowser(url) { + let ssm = Services.scriptSecurityManager; + + let uri = NetUtil.newURI(url); + + let principal = ssm.createContentPrincipal(uri, {}); + + let webnav = Services.appShell.createWindowlessBrowser(false); + + let docShell = webnav.docShell; + + docShell.createAboutBlankContentViewer(principal, principal); + + return webnav; +} + +function StubPolicy(id) { + return new WebExtensionPolicy({ + id, + mozExtensionHostname: id, + baseURL: `file:///{id}`, + + allowedOrigins: new MatchPatternSet([]), + localizeCallback(string) {}, + }); +} + +add_task(async function() { + let policy = StubPolicy("foo"); + policy.active = true; + + let webnavA = getWindowlessBrowser("moz-extension://foo/a.html"); + let webnavB = getWindowlessBrowser("moz-extension://foo/b.html"); + + let winA = Cu.waiveXrays(webnavA.document.defaultView); + let winB = Cu.waiveXrays(webnavB.document.defaultView); + + winB.winA = winA; + winB.eval(`winA.thing = {foo: "bar"};`); + + let getThing = winA.eval(String(() => { + try { + return thing.foo; + } catch (e) { + return String(e); + } + })); + + // Check that the object can be accessed normally before windowB is closed. + equal(getThing(), "bar"); + + webnavB.close(); + + // Wrappers are nuked asynchronously, so wait for that to happen. + await TestUtils.topicObserved("inner-window-nuked"); + + // Check that it can't be accessed after he window has been closed. + let result = getThing(); + ok(/dead object/.test(result), + `Result should show a dead wrapper error: ${result}`); + + webnavA.close(); + + policy.active = false; +}); diff --git a/js/xpconnect/tests/unit/test_onGarbageCollection-01.js b/js/xpconnect/tests/unit/test_onGarbageCollection-01.js new file mode 100644 index 0000000000..81ac713865 --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-01.js @@ -0,0 +1,69 @@ +// Test basic usage of onGarbageCollection + +const root = newGlobal(); +const dbg = new Debugger(); +const wrappedRoot = dbg.addDebuggee(root) + +const NUM_SLICES = root.NUM_SLICES = 10; + +let fired = false; +let slicesFound = 0; + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +dbg.memory.onGarbageCollection = data => { + fired = true; + + print("Got onGarbageCollection: " + JSON.stringify(data, null, 2)); + + equal(typeof data.reason, "string"); + equal(typeof data.nonincrementalReason == "string" || data.nonincrementalReason === null, + true); + + let lastStartTimestamp = 0; + for (let i = 0; i < data.collections.length; i++) { + let slice = data.collections[i]; + + equal(slice.startTimestamp >= lastStartTimestamp, true); + equal(slice.startTimestamp <= slice.endTimestamp, true); + + lastStartTimestamp = slice.startTimestamp; + } + + equal(data.collections.length >= 1, true); + slicesFound += data.collections.length; +} + +function run_test() { + do_test_pending(); + + root.eval( + ` + this.allocs = []; + + // GC slices + for (var i = 0; i < NUM_SLICES; i++) { + this.allocs.push({}); + gcslice(); + } + + // Full GC + this.allocs.push({}); + gc(); + ` + ); + + executeSoon(() => { + equal(fired, true, "The GC hook should have fired at least once"); + + // NUM_SLICES + 1 full gc + however many were triggered naturally (due to + // whatever zealousness setting). + print("Found " + slicesFound + " slices"); + equal(slicesFound >= NUM_SLICES + 1, true); + + do_test_finished(); + }); +} diff --git a/js/xpconnect/tests/unit/test_onGarbageCollection-02.js b/js/xpconnect/tests/unit/test_onGarbageCollection-02.js new file mode 100644 index 0000000000..fc3bf685ef --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-02.js @@ -0,0 +1,99 @@ +// Test multiple debuggers, GCs, and zones interacting with each other. +// +// Note: when observing both globals, but GC'ing in only one, we don't test that +// we *didn't* GC in the other zone because GCs are finicky and unreliable. That +// used to work when this was a jit-test, but in the process of migrating to +// xpcshell, we lost some amount of reliability and determinism. + +const root1 = newGlobal(); +const dbg1 = new Debugger(); +dbg1.addDebuggee(root1) + +const root2 = newGlobal(); +const dbg2 = new Debugger(); +dbg2.addDebuggee(root2) + +let fired1 = false; +let fired2 = false; +dbg1.memory.onGarbageCollection = _ => fired1 = true; +dbg2.memory.onGarbageCollection = _ => fired2 = true; + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +function reset() { + fired1 = false; + fired2 = false; +} + +function run_test() { + do_test_pending(); + + gc(); + executeSoon(() => { + reset(); + + // GC 1 only + root1.eval(`gc(this)`); + executeSoon(() => { + equal(fired1, true); + + // GC 2 only + reset(); + root2.eval(`gc(this)`); + executeSoon(() => { + equal(fired2, true); + + // Full GC + reset(); + gc(); + executeSoon(() => { + equal(fired1, true); + equal(fired2, true); + + // Full GC with no debuggees + reset(); + dbg1.removeAllDebuggees(); + dbg2.removeAllDebuggees(); + gc(); + executeSoon(() => { + equal(fired1, false); + equal(fired2, false); + + // One debugger with multiple debuggees in different zones. + + dbg1.addDebuggee(root1); + dbg1.addDebuggee(root2); + + // Just debuggee 1 + reset(); + root1.eval(`gc(this)`); + executeSoon(() => { + equal(fired1, true); + equal(fired2, false); + + // Just debuggee 2 + reset(); + root2.eval(`gc(this)`); + executeSoon(() => { + equal(fired1, true); + equal(fired2, false); + + // All debuggees + reset(); + gc(); + executeSoon(() => { + equal(fired1, true); + equal(fired2, false); + do_test_finished(); + }); + }); + }); + }); + }); + }); + }); + }); +} diff --git a/js/xpconnect/tests/unit/test_onGarbageCollection-03.js b/js/xpconnect/tests/unit/test_onGarbageCollection-03.js new file mode 100644 index 0000000000..d983e2cd11 --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-03.js @@ -0,0 +1,39 @@ +// Test that the onGarbageCollection hook is not reentrant. + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +function run_test() { + do_test_pending(); + + const root = newGlobal(); + const dbg = new Debugger(); + const wrappedRoot = dbg.addDebuggee(root) + + let fired = true; + let depth = 0; + + dbg.memory.onGarbageCollection = _ => { + fired = true; + + equal(depth, 0); + depth++; + try { + root.eval(`gc()`); + } finally { + equal(depth, 1); + depth--; + } + } + + root.eval(`gc()`); + + executeSoon(() => { + ok(fired); + equal(depth, 0); + dbg.memory.onGarbageCollection = undefined; + do_test_finished(); + }); +} diff --git a/js/xpconnect/tests/unit/test_onGarbageCollection-04.js b/js/xpconnect/tests/unit/test_onGarbageCollection-04.js new file mode 100644 index 0000000000..72e6d32284 --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-04.js @@ -0,0 +1,72 @@ +// Test that the onGarbageCollection reentrancy guard is on a per Debugger +// basis. That is if our first Debugger is observing our second Debugger's +// compartment, and this second Debugger triggers a GC inside its +// onGarbageCollection hook, the first Debugger's onGarbageCollection hook is +// still called. +// +// This is the scenario we are setting up: top level debugging the `debuggeree` +// global, which is debugging the `debuggee` global. Then, we trigger the +// following events: +// +// debuggee gc +// | +// V +// debuggeree's onGarbageCollection +// | +// V +// debuggeree gc +// | +// V +// top level onGarbageCollection +// +// Note that the top level's onGarbageCollection hook should be fired, at the +// same time that we are preventing reentrancy into debuggeree's +// onGarbageCollection hook. + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +function run_test() { + do_test_pending(); + + const debuggeree = newGlobal(); + const debuggee = debuggeree.debuggee = newGlobal(); + + debuggeree.eval( + ` + var dbg = new Debugger(this.debuggee); + var fired = 0; + dbg.memory.onGarbageCollection = _ => { + fired++; + gc(this); + }; + ` + ); + + const dbg = new Debugger(debuggeree); + let fired = 0; + dbg.memory.onGarbageCollection = _ => { + fired++; + }; + + debuggee.eval(`gc(this)`); + + // Let first onGarbageCollection runnable get run. + executeSoon(() => { + + // Let second onGarbageCollection runnable get run. + executeSoon(() => { + + // Even though we request GC'ing a single zone, we can't rely on that + // behavior and both zones could have been scheduled for gc for both + // gc(this) calls. + ok(debuggeree.fired >= 1); + ok(fired >= 1); + + debuggeree.dbg.removeAllDebuggees(); + do_test_finished(); + }); + }); +} diff --git a/js/xpconnect/tests/unit/test_onGarbageCollection-05.js b/js/xpconnect/tests/unit/test_onGarbageCollection-05.js new file mode 100644 index 0000000000..e3b5e5fd9e --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-05.js @@ -0,0 +1,42 @@ +// Test that the onGarbageCollection hook reports its gc cycle's number (aka the +// major GC number) and that it is monotonically increasing. + +const root = newGlobal(); +const dbg = new Debugger(); +const wrappedRoot = dbg.addDebuggee(root) + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +function run_test() { + do_test_pending(); + + let numFired = 0; + let lastGCCycleNumber = undefined; + + (function loop() { + if (numFired == 10) { + dbg.memory.onGarbageCollection = undefined; + dbg.enabled = false; + return void do_test_finished(); + } + + dbg.memory.onGarbageCollection = data => { + print("onGarbageCollection: " + uneval(data)); + + if (numFired != 0) { + equal(typeof lastGCCycleNumber, "number"); + equal(data.gcCycleNumber - lastGCCycleNumber, 1); + } + + numFired++; + lastGCCycleNumber = data.gcCycleNumber; + + executeSoon(loop); + }; + + root.eval("gc(this)"); + }()); +} diff --git a/js/xpconnect/tests/unit/test_params.js b/js/xpconnect/tests/unit/test_params.js new file mode 100644 index 0000000000..84455cfb7c --- /dev/null +++ b/js/xpconnect/tests/unit/test_params.js @@ -0,0 +1,237 @@ +/* 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/. */ + +function run_test() { + + // Load the component manifests. + registerXPCTestComponents(); + registerAppManifest(do_get_file('../components/js/xpctest.manifest')); + + // Test for each component. + test_component("@mozilla.org/js/xpc/test/native/Params;1"); + test_component("@mozilla.org/js/xpc/test/js/Params;1"); +} + +function test_component(contractid) { + + // Instantiate the object. + info("Testing " + contractid); + var o = Cc[contractid].createInstance(Ci["nsIXPCTestParams"]); + + // Possible comparator functions. + var standardComparator = function(a,b) {return a == b;}; + var dotEqualsComparator = function(a,b) {return a.equals(b); } + var fuzzComparator = function(a,b) {return Math.abs(a - b) < 0.1;}; + var interfaceComparator = function(a,b) {return a.name == b.name; } + var arrayComparator = function(innerComparator) { + return function(a,b) { + if (a.length != b.length) + return false; + for (var i = 0; i < a.length; ++i) + if (!innerComparator(a[i], b[i])) + return false; + return true; + }; + }; + + // Helper test function - takes the name of test method and two values of + // the given type. + // + // The optional comparator argument can be used for alternative notions of + // equality. The comparator should return true on equality. + function doTest(name, val1, val2, comparator) { + if (!comparator) + comparator = standardComparator; + var a = val1; + var b = {value: val2}; + var rv = o[name].call(o, a, b); + Assert.ok(comparator(rv, val2)); + Assert.ok(comparator(val1, b.value)); + }; + + function doIsTest(name, val1, val1Is, val2, val2Is, valComparator, isComparator) { + if (!isComparator) + isComparator = standardComparator; + var a = val1; + var aIs = val1Is; + var b = {value: val2}; + var bIs = {value: val2Is}; + var rvIs = {}; + var rv = o[name].call(o, aIs, a, bIs, b, rvIs); + Assert.ok(valComparator(rv, val2)); + Assert.ok(isComparator(rvIs.value, val2Is)); + Assert.ok(valComparator(val1, b.value)); + Assert.ok(isComparator(val1Is, bIs.value)); + } + + // Special-purpose function for testing arrays of iid_is interfaces, where we + // have 2 distinct sets of dependent parameters. + function doIs2Test(name, val1, val1Size, val1IID, val2, val2Size, val2IID) { + var a = val1; + var aSize = val1Size; + var aIID = val1IID; + var b = {value: val2}; + var bSize = {value: val2Size}; + var bIID = {value: val2IID}; + var rvSize = {}; + var rvIID = {}; + var rv = o[name].call(o, aSize, aIID, a, bSize, bIID, b, rvSize, rvIID); + Assert.ok(arrayComparator(interfaceComparator)(rv, val2)); + Assert.ok(standardComparator(rvSize.value, val2Size)); + Assert.ok(dotEqualsComparator(rvIID.value, val2IID)); + Assert.ok(arrayComparator(interfaceComparator)(val1, b.value)); + Assert.ok(standardComparator(val1Size, bSize.value)); + Assert.ok(dotEqualsComparator(val1IID, bIID.value)); + } + + // Check that the given call (type mismatch) results in an exception being thrown. + function doTypedArrayMismatchTest(name, val1, val1Size, val2, val2Size) { + var comparator = arrayComparator(standardComparator); + var error = false; + try { + doIsTest(name, val1, val1Size, val2, val2Size, comparator); + + // An exception was not thrown as would have been expected. + Assert.ok(false); + } + catch (e) { + // An exception was thrown as expected. + Assert.ok(true); + } + } + + // Workaround for bug 687612 (inout parameters broken for dipper types). + // We do a simple test of copying a into b, and ignore the rv. + function doTestWorkaround(name, val1) { + var a = val1; + var b = {value: ""}; + o[name].call(o, a, b); + Assert.equal(val1, b.value); + } + + // Test all the different types + doTest("testBoolean", true, false); + doTest("testOctet", 4, 156); + doTest("testShort", -456, 1299); + doTest("testLong", 50060, -12121212); + doTest("testLongLong", 12345, -10000000000); + doTest("testUnsignedShort", 1532, 65000); + doTest("testUnsignedLong", 0, 4000000000); + doTest("testUnsignedLongLong", 215435, 3453492580348535809); + doTest("testFloat", 4.9, -11.2, fuzzComparator); + doTest("testDouble", -80.5, 15000.2, fuzzComparator); + doTest("testChar", "a", "2"); + doTest("testString", "someString", "another string"); + doTest("testWstring", "Why wasnt this", "turned on before? ಠ_ಠ"); + doTest("testWchar", "z", "ア"); + doTestWorkaround("testAString", "Frosty the ☃ ;-)"); + doTestWorkaround("testAUTF8String", "We deliver 〠!"); + doTestWorkaround("testACString", "Just a regular C string."); + doTest("testJsval", {aprop: 12, bprop: "str"}, 4.22); + + // Test out dipper parameters, since they're special and we can't really test + // inouts. + let outAString = {}; + o.testOutAString(outAString); + Assert.equal(outAString.value, "out"); + try { o.testOutAString(undefined); } catch (e) {} // Don't crash + try { o.testOutAString(null); } catch (e) {} // Don't crash + try { o.testOutAString("string"); } catch (e) {} // Don't crash + + // Helpers to instantiate various test XPCOM objects. + var numAsMade = 0; + function makeA() { + var a = Cc["@mozilla.org/js/xpc/test/js/InterfaceA;1"].createInstance(Ci['nsIXPCTestInterfaceA']); + a.name = 'testA' + numAsMade++; + return a; + }; + var numBsMade = 0; + function makeB() { + var b = Cc["@mozilla.org/js/xpc/test/js/InterfaceB;1"].createInstance(Ci['nsIXPCTestInterfaceB']); + b.name = 'testB' + numBsMade++; + return b; + }; + + // Test arrays. + doIsTest("testShortArray", [2, 4, 6], 3, [1, 3, 5, 7], 4, arrayComparator(standardComparator)); + doIsTest("testDoubleArray", [-10, -0.5], 2, [1, 3, 1e11, -8e-5 ], 4, arrayComparator(fuzzComparator)); + + doIsTest("testStringArray", ["mary", "hat", "hey", "lid", "tell", "lam"], 6, + ["ids", "fleas", "woes", "wide", "has", "know", "!"], 7, arrayComparator(standardComparator)); + doIsTest("testWstringArray", ["沒有語言", "的偉大嗎?]"], 2, + ["we", "are", "being", "sooo", "international", "right", "now"], 7, arrayComparator(standardComparator)); + doIsTest("testInterfaceArray", [makeA(), makeA()], 2, + [makeA(), makeA(), makeA(), makeA(), makeA(), makeA()], 6, arrayComparator(interfaceComparator)); + doIsTest("testJsvalArray", [{ cheese: 'whiz', apple: 8 }, [1, 5, '3'], /regex/], 3, + ['apple', 2.2e10, 3.3e30, { only: "wheedle", except: {} }], 4, arrayComparator(standardComparator)); + + // Test typed arrays and ArrayBuffer aliasing. + var arrayBuffer = new ArrayBuffer(16); + var int16Array = new Int16Array(arrayBuffer, 2, 3); + int16Array.set([-32768, 0, 32767]); + doIsTest("testShortArray", int16Array, 3, new Int16Array([1773, -32768, 32767, 7]), 4, arrayComparator(standardComparator)); + doIsTest("testDoubleArray", new Float64Array([-10, -0.5]), 2, new Float64Array([0, 3.2, 1.0e10, -8.33 ]), 4, arrayComparator(fuzzComparator)); + + // Test sized strings. + var ssTests = ["Tis not possible, I muttered", "give me back my free hardcore!", "quoth the server:", "4〠4"]; + doIsTest("testSizedString", ssTests[0], ssTests[0].length, ssTests[1], ssTests[1].length, standardComparator); + doIsTest("testSizedWstring", ssTests[2], ssTests[2].length, ssTests[3], ssTests[3].length, standardComparator); + + // Test iid_is. + doIsTest("testInterfaceIs", makeA(), Ci['nsIXPCTestInterfaceA'], + makeB(), Ci['nsIXPCTestInterfaceB'], + interfaceComparator, dotEqualsComparator); + + // Test arrays of iids. + doIs2Test("testInterfaceIsArray", [makeA(), makeA(), makeA(), makeA(), makeA()], 5, Ci['nsIXPCTestInterfaceA'], + [makeB(), makeB(), makeB()], 3, Ci['nsIXPCTestInterfaceB']); + + // Test optional array size. + Assert.equal(o.testStringArrayOptionalSize(["some", "string", "array"]), "somestringarray"); + + // Test incorrect (too big) array size parameter; this should throw NOT_ENOUGH_ELEMENTS. + doTypedArrayMismatchTest("testShortArray", new Int16Array([-3, 7, 4]), 4, + new Int16Array([1, -32, 6]), 3); + + // Test type mismatch (int16 <-> uint16); this should throw BAD_CONVERT_JS. + doTypedArrayMismatchTest("testShortArray", new Uint16Array([0, 7, 4, 3]), 4, + new Uint16Array([1, 5, 6]), 3); + + // Test Sequence<T> types. + doTest("testShortSequence", [2, 4, 6], [1, 3, 5, 7], arrayComparator(standardComparator)); + doTest("testDoubleSequence", [-10, -0.5], [1, 3, 1e11, -8e-5 ], arrayComparator(fuzzComparator)); + doTest("testACStringSequence", ["mary", "hat", "hey", "lid", "tell", "lam"], + ["ids", "fleas", "woes", "wide", "has", "know", "!"], + arrayComparator(standardComparator)); + doTest("testAStringSequence", ["沒有語言", "的偉大嗎?]"], + ["we", "are", "being", "sooo", "international", "right", "now"], + arrayComparator(standardComparator)); + + doTest("testInterfaceSequence", [makeA(), makeA()], + [makeA(), makeA(), makeA(), makeA(), makeA(), makeA()], arrayComparator(interfaceComparator)); + + doTest("testJsvalSequence", [{ cheese: 'whiz', apple: 8 }, [1, 5, '3'], /regex/], + ['apple', 2.2e10, 3.3e30, { only: "wheedle", except: {} }], arrayComparator(standardComparator)); + + doIsTest("testInterfaceIsSequence", [makeA(), makeA(), makeA(), makeA(), makeA()], Ci['nsIXPCTestInterfaceA'], + [makeB(), makeB(), makeB()], Ci['nsIXPCTestInterfaceB'], + arrayComparator(interfaceComparator), dotEqualsComparator); + + var ret = o.testOptionalSequence(); + Assert.ok(Array.isArray(ret)); + Assert.equal(ret.length, 0); + + ret = o.testOptionalSequence([]); + Assert.ok(Array.isArray(ret)); + Assert.equal(ret.length, 0); + + ret = o.testOptionalSequence([1, 2, 3]); + Assert.ok(Array.isArray(ret)); + Assert.equal(ret.length, 3); + + o.testOmittedOptionalOut(); + ret = {}; + o.testOmittedOptionalOut(ret); + Assert.equal(ret.value.spec, "http://example.com/") +} diff --git a/js/xpconnect/tests/unit/test_private_field_xrays.js b/js/xpconnect/tests/unit/test_private_field_xrays.js new file mode 100644 index 0000000000..c67652561c --- /dev/null +++ b/js/xpconnect/tests/unit/test_private_field_xrays.js @@ -0,0 +1,61 @@ +'use strict' + +ChromeUtils.import('resource://gre/modules/Preferences.jsm'); +const {Services} = ChromeUtils.import('resource://gre/modules/Services.jsm'); + +add_task(async function() { + let webnav = Services.appShell.createWindowlessBrowser(false); + + let docShell = webnav.docShell; + + docShell.createAboutBlankContentViewer(null, null); + + let window = webnav.document.defaultView; + let unwrapped = Cu.waiveXrays(window); + + class Base { + constructor(o) { + return o; + } + }; + + var A; + try { + A = eval(` + (function() { + class A extends Base { + #x = 12; + static gx(o) { + return o.#x; + } + + static sx(o, v) { + o.#x = v; + } + }; + return A})()`); + } catch (e) { + Assert.equal(e instanceof SyntaxError, true); + Assert.equal( + /private fields are not currently supported/.test(e.message), true); + // Early return if private fields aren't enabled. + return; + } + + new A(window); + Assert.equal(A.gx(window), 12); + A.sx(window, 'wrapped'); + + // Shouldn't tunnel past xray. + Assert.throws(() => A.gx(unwrapped), TypeError); + Assert.throws(() => A.sx(unwrapped, 'unwrapped'), TypeError); + + new A(unwrapped); + Assert.equal(A.gx(unwrapped), 12); + Assert.equal(A.gx(window), 'wrapped'); + + A.sx(window, 'modified'); + Assert.equal(A.gx(unwrapped), 12); + A.sx(unwrapped, 16); + Assert.equal(A.gx(window), 'modified'); +}); diff --git a/js/xpconnect/tests/unit/test_promise.js b/js/xpconnect/tests/unit/test_promise.js new file mode 100644 index 0000000000..305e016fb5 --- /dev/null +++ b/js/xpconnect/tests/unit/test_promise.js @@ -0,0 +1,7 @@ +function run_test() { + sb = new Cu.Sandbox('http://www.example.com'); + sb.equal = equal; + Cu.evalInSandbox('equal(typeof new Promise(function(resolve){resolve();}), "object");', + sb); + Assert.equal(typeof new Promise(function(resolve){resolve();}), "object"); +} diff --git a/js/xpconnect/tests/unit/test_recursive_import.js b/js/xpconnect/tests/unit/test_recursive_import.js new file mode 100644 index 0000000000..94c6b0b7e9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_recursive_import.js @@ -0,0 +1,17 @@ +/* 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/. */ + +function run_test() { + var scope = {}; + ChromeUtils.import("resource://test/recursive_importA.jsm", scope); + + // A imported correctly + Assert.ok(scope.foo() == "foo"); + + // Symbols from B are visible through A + Assert.ok(scope.bar.baz() == "baz"); + + // Symbols from A are visible through A, B, A. + Assert.ok(scope.bar.qux.foo() == "foo"); +} diff --git a/js/xpconnect/tests/unit/test_reflect_parse.js b/js/xpconnect/tests/unit/test_reflect_parse.js new file mode 100644 index 0000000000..a96ce0bb61 --- /dev/null +++ b/js/xpconnect/tests/unit/test_reflect_parse.js @@ -0,0 +1,27 @@ +/* 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/. */ + +/* +({ + loc:{start:{line:1, column:0}, end:{line:1, column:12}, source:null}, + type:"Program", + body:[ + { + loc:{start:{line:1, column:0}, end:{line:1, column:12}, source:null}, + type:"ExpressionStatement", + expression:{ + loc:{start:{line:1, column:0}, end:{line:1, column:12}, source:null}, + type:"Literal", + value:"use strict" + } + } + ] +}) +*/ + +function run_test() { + // Reflect.parse is better tested in js shell; this basically tests its presence. + var parseData = Reflect.parse('"use strict"'); + Assert.equal(parseData.body[0].expression.value, "use strict"); +} diff --git a/js/xpconnect/tests/unit/test_resolve_dead_promise.js b/js/xpconnect/tests/unit/test_resolve_dead_promise.js new file mode 100644 index 0000000000..70615b39c0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_resolve_dead_promise.js @@ -0,0 +1,39 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=1298597 */ + +function run_test() +{ + var sb = Cu.Sandbox("http://www.blah.com"); + var resolveFun; + var p1 = new sb.Promise((res, rej) => {resolveFun = res}); + var rejectFun; + var p2 = new sb.Promise((res, rej) => {rejectFun = rej}); + Cu.nukeSandbox(sb); + Assert.ok(Cu.isDeadWrapper(sb), "sb should be dead"); + Assert.ok(Cu.isDeadWrapper(p1), "p1 should be dead"); + Assert.ok(Cu.isDeadWrapper(p2), "p2 should be dead"); + + var exception; + + try{ + resolveFun(1); + Assert.ok(false); + } catch (e) { + exception = e; + } + Assert.ok(exception.toString().includes("can't access dead object"), + "Resolving dead wrapped promise should throw"); + + exception = undefined; + try{ + rejectFun(1); + Assert.ok(false); + } catch (e) { + exception = e; + } + Assert.ok(exception.toString().includes("can't access dead object"), + "Rejecting dead wrapped promise should throw"); +} diff --git a/js/xpconnect/tests/unit/test_returncode.js b/js/xpconnect/tests/unit/test_returncode.js new file mode 100644 index 0000000000..943e43fd01 --- /dev/null +++ b/js/xpconnect/tests/unit/test_returncode.js @@ -0,0 +1,78 @@ +/* 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 Cm = Components.manager; + +ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); + +function getConsoleMessages() { + let consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService); + let messages = consoleService.getMessageArray().map((m) => m.toString()); + // reset ready for the next call. + consoleService.reset(); + return messages; +} + +function run_test() { + // Load the component manifests. + registerXPCTestComponents(); + registerAppManifest(do_get_file('../components/js/xpctest.manifest')); + + // and the tests. + test_simple(); + test_nested(); +} + +function test_simple() { + let parent = Cc["@mozilla.org/js/xpc/test/native/ReturnCodeParent;1"] + .createInstance(Ci.nsIXPCTestReturnCodeParent); + let result; + + // flush existing messages before we start testing. + getConsoleMessages(); + + // Ask the C++ to call the JS object which will throw. + result = parent.callChild(Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_THROW); + Assert.equal(result, Cr.NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS, + "exception caused NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS"); + + let messages = getConsoleMessages(); + Assert.equal(messages.length, 1, "got a console message from the exception"); + Assert.ok(messages[0].includes("a requested error"), "got the message text"); + + // Ask the C++ to call the JS object which will return success. + result = parent.callChild(Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_RETURN_SUCCESS); + Assert.equal(result, Cr.NS_OK, "success is success"); + + Assert.deepEqual(getConsoleMessages(), [], "no messages reported on success."); + + // And finally the point of this test! + // Ask the C++ to call the JS object which will use .returnCode + result = parent.callChild(Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_RETURN_RESULTCODE); + Assert.equal(result, Cr.NS_ERROR_FAILURE, + "NS_ERROR_FAILURE was seen as the error code."); + + Assert.deepEqual(getConsoleMessages(), [], "no messages reported with .returnCode"); +} + +function test_nested() { + let parent = Cc["@mozilla.org/js/xpc/test/native/ReturnCodeParent;1"] + .createInstance(Ci.nsIXPCTestReturnCodeParent); + let result; + + // flush existing messages before we start testing. + getConsoleMessages(); + + // Ask the C++ to call the "outer" JS object, which will set .returnCode, but + // then create and call *another* component which itself sets the .returnCode + // to a different value. This checks the returnCode is correctly saved + // across call contexts. + result = parent.callChild(Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_NEST_RESULTCODES); + Assert.equal(result, Cr.NS_ERROR_UNEXPECTED, + "NS_ERROR_UNEXPECTED was seen as the error code."); + // We expect one message, which is the child reporting what it got as the + // return code - which should be NS_ERROR_FAILURE + let expected = ["nested child returned " + Cr.NS_ERROR_FAILURE]; + Assert.deepEqual(getConsoleMessages(), expected, "got the correct sub-error"); +} diff --git a/js/xpconnect/tests/unit/test_rewrap_dead_wrapper.js b/js/xpconnect/tests/unit/test_rewrap_dead_wrapper.js new file mode 100644 index 0000000000..10934f550b --- /dev/null +++ b/js/xpconnect/tests/unit/test_rewrap_dead_wrapper.js @@ -0,0 +1,31 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=1354733 */ + +const global = this; + +function run_test() +{ + var sb = Cu.Sandbox(global); + let obj = new sb.Object(); + Cu.nukeSandbox(sb); + + ok(Cu.isDeadWrapper(obj), "object should be a dead wrapper"); + + // Create a new sandbox to wrap objects for. + + var sb = Cu.Sandbox(global); + Cu.evalInSandbox(function echo(val) { return val; }, + sb); + + let echoed = sb.echo(obj); + ok(Cu.isDeadWrapper(echoed), "Rewrapped object should be a dead wrapper"); + ok(echoed !== obj, "Rewrapped object should be a new dead wrapper"); + + ok(obj === obj, "Dead wrapper object should be equal to itself"); + + let liveObj = {}; + ok(liveObj === sb.echo(liveObj), "Rewrapped live object should be equal to itself"); +} diff --git a/js/xpconnect/tests/unit/test_rtcIdentityProvider.js b/js/xpconnect/tests/unit/test_rtcIdentityProvider.js new file mode 100644 index 0000000000..7786691513 --- /dev/null +++ b/js/xpconnect/tests/unit/test_rtcIdentityProvider.js @@ -0,0 +1,34 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + let sb = new Cu.Sandbox('https://www.example.com', + { wantGlobalProperties: ['rtcIdentityProvider'] }); + + function exerciseInterface() { + equal(typeof rtcIdentityProvider, 'object'); + equal(typeof rtcIdentityProvider.register, 'function'); + rtcIdentityProvider.register({ + generateAssertion: function(a, b, c) { + return Promise.resolve({ + idp: { domain: 'example.com' }, + assertion: JSON.stringify([a, b, c]) + }); + }, + validateAssertion: function(d, e) { + return Promise.resolve({ + identity: 'user@example.com', + contents: JSON.stringify([d, e]) + }); + } + }); + } + + sb.equal = equal; + Cu.evalInSandbox('(' + exerciseInterface.toSource() + ')();', sb); + ok(sb.rtcIdentityProvider.hasIdp); + + Cu.importGlobalProperties(['rtcIdentityProvider']); + exerciseInterface(); + ok(rtcIdentityProvider.hasIdp); +} diff --git a/js/xpconnect/tests/unit/test_sandbox_DOMException.js b/js/xpconnect/tests/unit/test_sandbox_DOMException.js new file mode 100644 index 0000000000..04592c6db2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_DOMException.js @@ -0,0 +1,10 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + var Cu = Components.utils; + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["DOMException"] }); + sb.notEqual = Assert.notEqual.bind(Assert); + Cu.evalInSandbox('notEqual(DOMException, undefined);', sb); +} diff --git a/js/xpconnect/tests/unit/test_sandbox_atob.js b/js/xpconnect/tests/unit/test_sandbox_atob.js new file mode 100644 index 0000000000..a4bd75c13d --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_atob.js @@ -0,0 +1,9 @@ +function run_test() { + sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["atob", "btoa"] }); + sb.equal = equal; + Cu.evalInSandbox('var dummy = "Dummy test.";' + + 'equal(dummy, atob(btoa(dummy)));' + + 'equal(btoa("budapest"), "YnVkYXBlc3Q=");', + sb); +} diff --git a/js/xpconnect/tests/unit/test_sandbox_metadata.js b/js/xpconnect/tests/unit/test_sandbox_metadata.js new file mode 100644 index 0000000000..2d0ebe36b0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_metadata.js @@ -0,0 +1,57 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=898559 */ + +function run_test() +{ + let sandbox = Cu.Sandbox("http://www.blah.com", { + metadata: "test metadata", + }); + + Cu.importGlobalProperties(["XMLHttpRequest"]); + + Assert.equal(Cu.getSandboxMetadata(sandbox), "test metadata"); + + sandbox = Cu.Sandbox("http://www.blah.com", { + metadata: { foopy: { bar: 2 }, baz: "hi" } + }); + + let metadata = Cu.getSandboxMetadata(sandbox); + Assert.equal(metadata.baz, "hi"); + Assert.equal(metadata.foopy.bar, 2); + metadata.baz = "foo"; + + metadata = Cu.getSandboxMetadata(sandbox); + Assert.equal(metadata.baz, "foo"); + + metadata = { foo: "bar" }; + Cu.setSandboxMetadata(sandbox, metadata); + metadata.foo = "baz"; + metadata = Cu.getSandboxMetadata(sandbox); + Assert.equal(metadata.foo, "bar"); + + let thrown = false; + let reflector = new XMLHttpRequest(); + + try { + Cu.setSandboxMetadata(sandbox, { foo: reflector }); + } catch(e) { + thrown = true; + } + + Assert.equal(thrown, true); + + sandbox = Cu.Sandbox(this, { + metadata: { foopy: { bar: 2 }, baz: "hi" } + }); + + let inner = Cu.evalInSandbox("Components.utils.Sandbox('http://www.blah.com')", sandbox); + + metadata = Cu.getSandboxMetadata(inner); + Assert.equal(metadata.baz, "hi"); + Assert.equal(metadata.foopy.bar, 2); + metadata.baz = "foo"; +} + diff --git a/js/xpconnect/tests/unit/test_sandbox_name.js b/js/xpconnect/tests/unit/test_sandbox_name.js new file mode 100644 index 0000000000..1eaa971a9e --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_name.js @@ -0,0 +1,26 @@ +"use strict"; + +/** + * Test that the name of a sandbox contains the name of all principals. + */ +function test_sandbox_name() { + let names = [ + "http://example.com/?" + Math.random(), + "http://example.org/?" + Math.random() + ]; + let sandbox = Cu.Sandbox(names); + let fileName = Cu.evalInSandbox( + "(new Error()).fileName", + sandbox, + "latest" /*js version*/, + ""/*file name*/ + ); + + for (let name of names) { + Assert.ok(fileName.includes(name), `Name ${name} appears in ${fileName}`); + } +}; + +function run_test() { + test_sandbox_name(); +} diff --git a/js/xpconnect/tests/unit/test_subScriptLoader.js b/js/xpconnect/tests/unit/test_subScriptLoader.js new file mode 100644 index 0000000000..65947d4438 --- /dev/null +++ b/js/xpconnect/tests/unit/test_subScriptLoader.js @@ -0,0 +1,18 @@ +"use strict"; + +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +add_task(async function test_executeScriptAfterNuked() { + let scriptUrl = Services.io.newFileURI(do_get_file("file_simple_script.js")).spec; + + // Load the script for the first time into a sandbox, and then nuke + // that sandbox. + let sandbox = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal()); + Services.scriptloader.loadSubScript(scriptUrl, sandbox); + Cu.nukeSandbox(sandbox); + + // Load the script again into a new sandbox, and make sure it + // succeeds. + sandbox = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal()); + Services.scriptloader.loadSubScript(scriptUrl, sandbox); +}); diff --git a/js/xpconnect/tests/unit/test_tearoffs.js b/js/xpconnect/tests/unit/test_tearoffs.js new file mode 100644 index 0000000000..cdf1d1025b --- /dev/null +++ b/js/xpconnect/tests/unit/test_tearoffs.js @@ -0,0 +1,105 @@ +/* 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/. */ + +function run_test() { + + // Load the component manifest containing our test interface implementations. + Components.manager.autoRegister(do_get_file('../components/js/xpctest.manifest')); + + // Shortcut the interfaces we're using. + var ifs = { + a: Ci['nsIXPCTestInterfaceA'], + b: Ci['nsIXPCTestInterfaceB'], + c: Ci['nsIXPCTestInterfaceC'] + }; + + // Shortcut the class we're instantiating. This implements all three interfaces. + var cls = Cc["@mozilla.org/js/xpc/test/js/TestInterfaceAll;1"]; + + // Run through the logic a few times. + for (i = 0; i < 2; ++i) + play_with_tearoffs(ifs, cls); +} + +function play_with_tearoffs(ifs, cls) { + + // Allocate a bunch of objects, QI-ed to B. + var instances = []; + for (var i = 0; i < 300; ++i) + instances.push(cls.createInstance(ifs.b)); + + // Nothing to collect. + gc(); + + // QI them to A. + instances.forEach(function(v, i, a) { v.QueryInterface(ifs.a); }); + + // QI them to C. + instances.forEach(function(v, i, a) { v.QueryInterface(ifs.c); }); + + // Check + Assert.ok('name' in instances[10], 'Have the prop from A/B'); + Assert.ok('someInteger' in instances[10], 'Have the prop from C'); + + // Grab tearoff reflections for a and b. + var aTearOffs = instances.map(function(v, i, a) { return v.nsIXPCTestInterfaceA; } ); + var bTearOffs = instances.map(function(v, i, a) { return v.nsIXPCTestInterfaceB; } ); + + // Check + Assert.ok('name' in aTearOffs[1], 'Have the prop from A'); + Assert.ok(!('someInteger' in aTearOffs[1]), 'Dont have the prop from C'); + + // Nothing to collect. + gc(); + + // Null out every even instance pointer. + for (var i = 0; i < instances.length; ++i) + if (i % 2 == 0) + instances[i] = null; + + // Nothing to collect, since we still have the A and B tearoff reflections. + gc(); + + // Null out A tearoff reflections that are a multiple of 3. + for (var i = 0; i < aTearOffs.length; ++i) + if (i % 3 == 0) + aTearOffs[i] = null; + + // Nothing to collect, since we still have the B tearoff reflections. + gc(); + + // Null out B tearoff reflections that are a multiple of 5. + for (var i = 0; i < bTearOffs.length; ++i) + if (i % 5 == 0) + bTearOffs[i] = null; + + // This should collect every 30th object (indices that are multiples of 2, 3, and 5). + gc(); + + // Kill the b tearoffs entirely. + bTearOffs = 0; + + // Collect more. + gc(); + + // Get C tearoffs. + var cTearOffs = instances.map(function(v, i, a) { return v ? v.nsIXPCTestInterfaceC : null; } ); + + // Check. + Assert.ok(!('name' in cTearOffs[1]), 'Dont have the prop from A'); + Assert.ok('someInteger' in cTearOffs[1], 'have the prop from C'); + + // Null out the a tearoffs. + aTearOffs = null; + + // Collect all even indices. + gc(); + + // Collect all indices. + instances = null; + gc(); + + // Give ourselves a pat on the back. :-) + Assert.ok(true, "Got all the way through without crashing!"); +} diff --git a/js/xpconnect/tests/unit/test_textDecoder.js b/js/xpconnect/tests/unit/test_textDecoder.js new file mode 100644 index 0000000000..b97aab9f7c --- /dev/null +++ b/js/xpconnect/tests/unit/test_textDecoder.js @@ -0,0 +1,11 @@ +function run_test() { + sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["TextDecoder", "TextEncoder"] }); + sb.equal = equal; + Cu.evalInSandbox('equal(new TextDecoder().encoding, "utf-8");' + + 'equal(new TextEncoder().encoding, "utf-8");', + sb); + Cu.importGlobalProperties(["TextDecoder", "TextEncoder"]); + Assert.equal(new TextDecoder().encoding, "utf-8"); + Assert.equal(new TextEncoder().encoding, "utf-8"); +} diff --git a/js/xpconnect/tests/unit/test_uawidget_scope.js b/js/xpconnect/tests/unit/test_uawidget_scope.js new file mode 100644 index 0000000000..7aed7bdbb9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_uawidget_scope.js @@ -0,0 +1,57 @@ +/* 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/. */ + +ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const {TestUtils} = ChromeUtils.import("resource://testing-common/TestUtils.jsm"); + +function getWindowlessBrowser(url) { + let ssm = Services.scriptSecurityManager; + let uri = NetUtil.newURI(url); + let principal = ssm.createContentPrincipal(uri, {}); + let webnav = Services.appShell.createWindowlessBrowser(false); + + let docShell = webnav.docShell; + docShell.createAboutBlankContentViewer(principal, principal); + + let document = webnav.document; + let video = document.createElement("video"); + document.documentElement.appendChild(video); + + let shadowRoot = video.openOrClosedShadowRoot; + ok(shadowRoot, "should have shadowRoot"); + ok(shadowRoot.isUAWidget(), "ShadowRoot should be a UAWidget"); + equal(Cu.getGlobalForObject(shadowRoot), Cu.getUAWidgetScope(principal), + "shadowRoot should be in UAWidget scope"); + + return webnav; +} + +function StubPolicy(id) { + return new WebExtensionPolicy({ + id, + mozExtensionHostname: id, + baseURL: `file:///{id}`, + allowedOrigins: new MatchPatternSet([]), + localizeCallback(string) {}, + }); +} + +// See https://bugzilla.mozilla.org/show_bug.cgi?id=1588356 +add_task(async function() { + let policy = StubPolicy("foo"); + policy.active = true; + + let webnav = getWindowlessBrowser("moz-extension://foo/a.html"); + webnav.close(); + + // Wrappers are nuked asynchronously, so wait for that to happen. + await TestUtils.topicObserved("inner-window-nuked"); + + webnav = getWindowlessBrowser("moz-extension://foo/a.html"); + webnav.close(); + + policy.active = false; +}); diff --git a/js/xpconnect/tests/unit/test_uninitialized_lexical.js b/js/xpconnect/tests/unit/test_uninitialized_lexical.js new file mode 100644 index 0000000000..f5f2f254ee --- /dev/null +++ b/js/xpconnect/tests/unit/test_uninitialized_lexical.js @@ -0,0 +1,7 @@ +/* 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/. */ + +Assert.throws(() => ChromeUtils.import("resource://test/uninitialized_lexical.jsm"), + /Symbol 'foo' accessed before initialization/, + "Uninitialized lexicals result in an exception"); diff --git a/js/xpconnect/tests/unit/test_unload.js b/js/xpconnect/tests/unit/test_unload.js new file mode 100644 index 0000000000..6d6c7f4c69 --- /dev/null +++ b/js/xpconnect/tests/unit/test_unload.js @@ -0,0 +1,28 @@ +/* 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/. */ + +function run_test() { + var scope1 = {}; + var exports1 = ChromeUtils.import("resource://gre/modules/NetUtil.jsm", scope1); + + var scope2 = {}; + var exports2 = ChromeUtils.import("resource://gre/modules/NetUtil.jsm", scope2); + + Assert.ok(exports1 === exports2); + Assert.ok(scope1.NetUtil === scope2.NetUtil); + + Cu.unload("resource://gre/modules/NetUtil.jsm"); + + var scope3 = {}; + var exports3 = ChromeUtils.import("resource://gre/modules/NetUtil.jsm", scope3); + + Assert.equal(false, exports1 === exports3); + Assert.equal(false, scope1.NetUtil === scope3.NetUtil); + + // When the jsm was unloaded, the value of all its global's properties were + // set to undefined. While it must be safe (not crash) to call into the + // module, we expect it to throw an error (e.g., when trying to use Ci). + try { scope1.NetUtil.newURI("http://www.example.com"); } catch (e) {} + try { scope3.NetUtil.newURI("http://www.example.com"); } catch (e) {} +} diff --git a/js/xpconnect/tests/unit/test_url.js b/js/xpconnect/tests/unit/test_url.js new file mode 100644 index 0000000000..0f912d12e9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_url.js @@ -0,0 +1,9 @@ +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["URL"] }); + sb.equal = equal; + Cu.evalInSandbox('equal(new URL("http://www.example.com").host, "www.example.com");', + sb); + Cu.importGlobalProperties(["URL"]); + Assert.equal(new URL("http://www.example.com").host, "www.example.com"); +} diff --git a/js/xpconnect/tests/unit/test_want_components.js b/js/xpconnect/tests/unit/test_want_components.js new file mode 100644 index 0000000000..9865596143 --- /dev/null +++ b/js/xpconnect/tests/unit/test_want_components.js @@ -0,0 +1,6 @@ +function run_test() { + var sb = Cu.Sandbox(this, {wantComponents: false}); + + var rv = Cu.evalInSandbox("this.Components", sb); + Assert.equal(rv, undefined); +} diff --git a/js/xpconnect/tests/unit/test_watchdog_default.js b/js/xpconnect/tests/unit/test_watchdog_default.js new file mode 100644 index 0000000000..4634184f3c --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_default.js @@ -0,0 +1,9 @@ +/* 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/. */ + +function testBody() { + // Check that we properly implement whatever behavior is specified by the + // default profile for this configuration. + return checkWatchdog(isWatchdogEnabled()); +} diff --git a/js/xpconnect/tests/unit/test_watchdog_disable.js b/js/xpconnect/tests/unit/test_watchdog_disable.js new file mode 100644 index 0000000000..926edf2ffa --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_disable.js @@ -0,0 +1,8 @@ +/* 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/. */ + +function testBody() { + setWatchdogEnabled(false); + return checkWatchdog(false); +} diff --git a/js/xpconnect/tests/unit/test_watchdog_enable.js b/js/xpconnect/tests/unit/test_watchdog_enable.js new file mode 100644 index 0000000000..f39757dfae --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_enable.js @@ -0,0 +1,8 @@ +/* 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/. */ + +function testBody() { + setWatchdogEnabled(true); + return checkWatchdog(true); +} diff --git a/js/xpconnect/tests/unit/test_watchdog_hibernate.js b/js/xpconnect/tests/unit/test_watchdog_hibernate.js new file mode 100644 index 0000000000..119cc095e2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_hibernate.js @@ -0,0 +1,49 @@ +/* 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/. */ + +async function testBody() { + + setWatchdogEnabled(true); + + // It's unlikely that we've ever hibernated at this point, but the timestamps + // default to 0, so this should always be true. + var now = Date.now() * 1000; + var startHibernation = Cu.getWatchdogTimestamp("WatchdogHibernateStart"); + var stopHibernation = Cu.getWatchdogTimestamp("WatchdogHibernateStop"); + do_log_info("Pre-hibernation statistics:"); + do_log_info("now: " + now / 1000000); + do_log_info("startHibernation: " + startHibernation / 1000000); + do_log_info("stopHibernation: " + stopHibernation / 1000000); + Assert.less(startHibernation, now, "startHibernation ok"); + Assert.less(stopHibernation, now, "stopHibernation ok"); + + // When the watchdog runs, it hibernates if there's been no activity for the + // last 2 seconds, otherwise it sleeps for 1 second. As such, given perfect + // scheduling, we should never have more than 3 seconds of inactivity without + // hibernating. To add some padding for automation, we mandate that hibernation + // must begin between 2 and 5 seconds from now. + + // Sleep for 10 seconds. Note: we don't use nsITimer here because then we may run + // arbitrary (idle) events involving script before it fires. + simulateNoScriptActivity(10); + + busyWait(1000); // Give the watchdog time to wake up on the condvar. + var stateChange = Cu.getWatchdogTimestamp("ContextStateChange"); + startHibernation = Cu.getWatchdogTimestamp("WatchdogHibernateStart"); + stopHibernation = Cu.getWatchdogTimestamp("WatchdogHibernateStop"); + do_log_info("Post-hibernation statistics:"); + do_log_info("stateChange: " + stateChange / 1000000); + do_log_info("startHibernation: " + startHibernation / 1000000); + do_log_info("stopHibernation: " + stopHibernation / 1000000); + // XPCOM timers, JS times, and PR_Now() are apparently not directly + // comparable, as evidenced by certain seemingly-impossible timing values + // that occasionally get logged in windows automation. We're really just + // making sure this behavior is roughly as expected on the macro scale, + // so we add a 1 second fuzz factor here. + const FUZZ_FACTOR = 1 * 1000 * 1000; + Assert.greater(stateChange, now + 10*1000*1000 - FUZZ_FACTOR, "stateChange ok"); + Assert.greater(startHibernation, now + 2*1000*1000 - FUZZ_FACTOR, "startHibernation ok"); + Assert.less(startHibernation, now + 5*1000*1000 + FUZZ_FACTOR, "startHibernation ok"); + Assert.greater(stopHibernation, now + 10*1000*1000 - FUZZ_FACTOR, "stopHibernation ok"); +} diff --git a/js/xpconnect/tests/unit/test_watchdog_toggle.js b/js/xpconnect/tests/unit/test_watchdog_toggle.js new file mode 100644 index 0000000000..6f43a8b876 --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_toggle.js @@ -0,0 +1,10 @@ +/* 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/. */ + +function testBody() { + var defaultBehavior = isWatchdogEnabled(); + setWatchdogEnabled(!defaultBehavior); + setWatchdogEnabled(defaultBehavior); + return checkWatchdog(defaultBehavior); +} diff --git a/js/xpconnect/tests/unit/test_weak_keys.js b/js/xpconnect/tests/unit/test_weak_keys.js new file mode 100644 index 0000000000..58e3237bd8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_weak_keys.js @@ -0,0 +1,45 @@ +/* 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/. */ + +/* See https://bugzilla.mozilla.org/show_bug.cgi?id=1165807 */ + +function run_test() +{ + var bunnies = new String("bunnies"); + var lizards = new String("lizards"); + + var weakset = new WeakSet([bunnies, lizards]); + var weakmap = new WeakMap(); + weakmap.set(bunnies, 23); + weakmap.set(lizards, "oh no"); + + var keys = ChromeUtils.nondeterministicGetWeakMapKeys(bunnies); + equal(keys, undefined, "test nondeterministicGetWeakMapKeys on non-WeakMap"); + + keys = ChromeUtils.nondeterministicGetWeakMapKeys(weakmap); + equal(keys.length, 2, "length of nondeterministicGetWeakMapKeys"); + equal(weakmap.get(bunnies), 23, "check bunnies in weakmap"); + equal(weakmap.get(lizards), "oh no", "check lizards in weakmap"); + + keys = ChromeUtils.nondeterministicGetWeakSetKeys(bunnies); + equal(keys, undefined, "test nondeterministicGetWeakSetKeys on non-WeakMap"); + + keys = ChromeUtils.nondeterministicGetWeakSetKeys(weakset); + equal(keys.length, 2, "length of nondeterministicGetWeakSetKeys"); + ok(weakset.has(bunnies), "check bunnies in weakset"); + ok(weakset.has(lizards), "check lizards in weakset"); + + bunnies = null; + keys = null; + + Cu.forceGC(); + + keys = ChromeUtils.nondeterministicGetWeakMapKeys(weakmap); + equal(keys.length, 1, "length of nondeterministicGetWeakMapKeys after GC"); + equal(weakmap.get(lizards), "oh no", "check lizards still in weakmap"); + + keys = ChromeUtils.nondeterministicGetWeakSetKeys(weakset); + equal(keys.length, 1, "length of nondeterministicGetWeakSetKeys after GC"); + ok(weakset.has(lizards), "check lizards still in weakset"); +} diff --git a/js/xpconnect/tests/unit/test_wrapped_js_enumerator.js b/js/xpconnect/tests/unit/test_wrapped_js_enumerator.js new file mode 100644 index 0000000000..5a366ba25d --- /dev/null +++ b/js/xpconnect/tests/unit/test_wrapped_js_enumerator.js @@ -0,0 +1,71 @@ +"use strict"; + +// Tests that JS iterators are automatically wrapped into +// equivalent nsISimpleEnumerator objects. + +const Variant = Components.Constructor("@mozilla.org/variant;1", + "nsIWritableVariant", + "setFromVariant"); +const SupportsInterfacePointer = Components.Constructor( + "@mozilla.org/supports-interface-pointer;1", "nsISupportsInterfacePointer"); + +function wrapEnumerator1(iter) { + var ip = SupportsInterfacePointer(); + ip.data = iter; + return ip.data.QueryInterface(Ci.nsISimpleEnumerator); +} + +function wrapEnumerator2(iter) { + var ip = SupportsInterfacePointer(); + ip.data = { + QueryInterface: ChromeUtils.generateQI(["nsIFilePicker"]), + get files() { + return iter; + }, + }; + return ip.data.QueryInterface(Ci.nsIFilePicker).files; +} + + +function enumToArray(iter) { + let result = []; + while (iter.hasMoreElements()) { + result.push(iter.getNext().QueryInterface(Ci.nsIVariant)); + } + return result; +} + +add_task(async function test_wrapped_js_enumerator() { + let array = [1, 2, 3, 4]; + + for (let wrapEnumerator of [wrapEnumerator1, wrapEnumerator2]) { + // Test a plain JS iterator. This should automatically be wrapped into + // an equivalent nsISimpleEnumerator. + { + let iter = wrapEnumerator(array.values()); + let result = enumToArray(iter); + + deepEqual(result, array, "Got correct result"); + } + + // Test an object with a QueryInterface method, which implements + // nsISimpleEnumerator. This should be wrapped and used directly. + { + let obj = { + QueryInterface: ChromeUtils.generateQI(["nsISimpleEnumerator"]), + _idx: 0, + hasMoreElements() { + return this._idx < array.length; + }, + getNext() { + return Variant(array[this._idx++]); + }, + }; + + let iter = wrapEnumerator(obj); + let result = enumToArray(iter); + + deepEqual(result, array, "Got correct result"); + } + } +}); diff --git a/js/xpconnect/tests/unit/test_xpcomutils.js b/js/xpconnect/tests/unit/test_xpcomutils.js new file mode 100644 index 0000000000..5d751a335d --- /dev/null +++ b/js/xpconnect/tests/unit/test_xpcomutils.js @@ -0,0 +1,230 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- + * vim: sw=4 ts=4 sts=4 et + * 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/. */ + +/** + * This file tests the methods on XPCOMUtils.jsm. + * Also on ComponentUtils.jsm. Which is deprecated. + */ + +const {ComponentUtils} = ChromeUtils.import("resource://gre/modules/ComponentUtils.jsm"); +const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); + +//////////////////////////////////////////////////////////////////////////////// +//// Tests + +add_test(function test_generateQI_string_names() +{ + var x = { + QueryInterface: ChromeUtils.generateQI([ + "nsIClassInfo", + "nsIObserver" + ]) + }; + + try { + x.QueryInterface(Ci.nsIClassInfo); + } catch(e) { + do_throw("Should QI to nsIClassInfo"); + } + try { + x.QueryInterface(Ci.nsIObserver); + } catch(e) { + do_throw("Should QI to nsIObserver"); + } + try { + x.QueryInterface(Ci.nsIObserverService); + do_throw("QI should not have succeeded!"); + } catch(e) {} + run_next_test(); +}); + +add_test(function test_defineLazyGetter() +{ + let accessCount = 0; + let obj = { + inScope: false + }; + const TEST_VALUE = "test value"; + XPCOMUtils.defineLazyGetter(obj, "foo", function() { + accessCount++; + this.inScope = true; + return TEST_VALUE; + }); + Assert.equal(accessCount, 0); + + // Get the property, making sure the access count has increased. + Assert.equal(obj.foo, TEST_VALUE); + Assert.equal(accessCount, 1); + Assert.ok(obj.inScope); + + // Get the property once more, making sure the access count has not + // increased. + Assert.equal(obj.foo, TEST_VALUE); + Assert.equal(accessCount, 1); + run_next_test(); +}); + + +add_test(function test_defineLazyServiceGetter() +{ + let obj = { }; + XPCOMUtils.defineLazyServiceGetter(obj, "service", + "@mozilla.org/consoleservice;1", + "nsIConsoleService"); + let service = Cc["@mozilla.org/consoleservice;1"]. + getService(Ci.nsIConsoleService); + + // Check that the lazy service getter and the actual service have the same + // properties. + for (let prop in obj.service) + Assert.ok(prop in service); + for (let prop in service) + Assert.ok(prop in obj.service); + run_next_test(); +}); + + +add_test(function test_defineLazyPreferenceGetter() +{ + const PREF = "xpcomutils.test.pref"; + + let obj = {}; + XPCOMUtils.defineLazyPreferenceGetter(obj, "pref", PREF, "defaultValue"); + + + equal(obj.pref, "defaultValue", "Should return the default value before pref is set"); + + Preferences.set(PREF, "currentValue"); + + + info("Create second getter on new object"); + + obj = {}; + XPCOMUtils.defineLazyPreferenceGetter(obj, "pref", PREF, "defaultValue"); + + + equal(obj.pref, "currentValue", "Should return the current value on initial read when pref is already set"); + + Preferences.set(PREF, "newValue"); + + equal(obj.pref, "newValue", "Should return new value after preference change"); + + Preferences.set(PREF, "currentValue"); + + equal(obj.pref, "currentValue", "Should return new value after second preference change"); + + + Preferences.reset(PREF); + + equal(obj.pref, "defaultValue", "Should return default value after pref is reset"); + + obj = {}; + XPCOMUtils.defineLazyPreferenceGetter(obj, "pref", PREF, "a,b", + null, value => value.split(",")); + + deepEqual(obj.pref, ["a", "b"], "transform is applied to default value"); + + Preferences.set(PREF, "x,y,z"); + deepEqual(obj.pref, ["x", "y", "z"], "transform is applied to updated value"); + + Preferences.reset(PREF); + deepEqual(obj.pref, ["a", "b"], "transform is applied to reset default"); + + run_next_test(); +}); + + +add_test(function test_categoryRegistration() +{ + const CATEGORY_NAME = "test-cat"; + const XULAPPINFO_CONTRACTID = "@mozilla.org/xre/app-info;1"; + const XULAPPINFO_CID = Components.ID("{fc937916-656b-4fb3-a395-8c63569e27a8}"); + + // Create a fake app entry for our category registration apps filter. + let tmp = {}; + ChromeUtils.import("resource://testing-common/AppInfo.jsm", tmp); + let XULAppInfo = tmp.newAppInfo({ + name: "catRegTest", + ID: "{adb42a9a-0d19-4849-bf4d-627614ca19be}", + version: "1", + platformVersion: "", + }); + let XULAppInfoFactory = { + createInstance: function (outer, iid) { + if (outer != null) + throw Cr.NS_ERROR_NO_AGGREGATION; + return XULAppInfo.QueryInterface(iid); + } + }; + let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); + registrar.registerFactory( + XULAPPINFO_CID, + "XULAppInfo", + XULAPPINFO_CONTRACTID, + XULAppInfoFactory + ); + + // Load test components. + do_load_manifest("CatRegistrationComponents.manifest"); + + const EXPECTED_ENTRIES = new Map([ + ["CatRegisteredComponent", "@unit.test.com/cat-registered-component;1"], + ["CatAppRegisteredComponent", "@unit.test.com/cat-app-registered-component;1"], + ]); + + // Verify the correct entries are registered in the "test-cat" category. + for (let {entry, value} of Services.catMan.enumerateCategory(CATEGORY_NAME)) { + print("Verify that the name/value pair exists in the expected entries."); + ok(EXPECTED_ENTRIES.has(entry)); + Assert.equal(EXPECTED_ENTRIES.get(entry), value); + EXPECTED_ENTRIES.delete(entry); + } + print("Check that all of the expected entries have been deleted."); + Assert.equal(EXPECTED_ENTRIES.size, 0); + run_next_test(); +}); + +add_test(function test_generateSingletonFactory() +{ + const XPCCOMPONENT_CONTRACTID = "@mozilla.org/singletonComponentTest;1"; + const XPCCOMPONENT_CID = Components.ID("{31031c36-5e29-4dd9-9045-333a5d719a3e}"); + + function XPCComponent() {} + XPCComponent.prototype = { + classID: XPCCOMPONENT_CID, + _xpcom_factory: ComponentUtils.generateSingletonFactory(XPCComponent), + QueryInterface: ChromeUtils.generateQI([]) + }; + let NSGetFactory = ComponentUtils.generateNSGetFactory([XPCComponent]); + let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); + registrar.registerFactory( + XPCCOMPONENT_CID, + "XPCComponent", + XPCCOMPONENT_CONTRACTID, + NSGetFactory(XPCCOMPONENT_CID) + ); + + // First, try to instance the component. + let instance = Cc[XPCCOMPONENT_CONTRACTID].createInstance(Ci.nsISupports); + // Try again, check that it returns the same instance as before. + Assert.equal(instance, + Cc[XPCCOMPONENT_CONTRACTID].createInstance(Ci.nsISupports)); + // Now, for sanity, check that getService is also returning the same instance. + Assert.equal(instance, + Cc[XPCCOMPONENT_CONTRACTID].getService(Ci.nsISupports)); + + run_next_test(); +}); + +//////////////////////////////////////////////////////////////////////////////// +//// Test Runner + +function run_test() +{ + run_next_test(); +} diff --git a/js/xpconnect/tests/unit/test_xpcwn_tamperproof.js b/js/xpconnect/tests/unit/test_xpcwn_tamperproof.js new file mode 100644 index 0000000000..e712613d02 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xpcwn_tamperproof.js @@ -0,0 +1,168 @@ +// Test that it's not possible to create expando properties on XPCWNs. +// See <https://bugzilla.mozilla.org/show_bug.cgi?id=1143810#c5>. + +function check_throws(f) { + try { + f(); + } catch (exc) { + return; + } + throw new TypeError("Expected exception, no exception thrown"); +} + +/* + * Test that XPCWrappedNative objects do not permit expando properties to be created. + * + * This function is called twice. The first time, realObj is an nsITimer XPCWN + * and accessObj === realObj. + * + * The second time, accessObj is a scripted proxy with realObj as its target. + * So the second time we are testing that scripted proxies don't magically + * bypass whatever mechanism enforces the expando policy on XPCWNs. + */ +function test_tamperproof(realObj, accessObj, {method, constant, attribute}) { + // Assignment can't create an expando property. + check_throws(function () { accessObj.expando = 14; }); + Assert.equal(false, "expando" in realObj); + + // Strict assignment throws. + check_throws(function () { "use strict"; accessObj.expando = 14; }); + Assert.equal(false, "expando" in realObj); + + // Assignment to an inherited method name doesn't work either. + check_throws(function () { accessObj.hasOwnProperty = () => "lies"; }); + check_throws(function () { "use strict"; accessObj.hasOwnProperty = () => "lies"; }); + Assert.ok(!realObj.hasOwnProperty("hasOwnProperty")); + + // Assignment to a method name doesn't work either. + let originalMethod; + if (method) { + originalMethod = accessObj[method]; + accessObj[method] = "nope"; // non-writable data property, no exception in non-strict code + check_throws(function () { "use strict"; accessObj[method] = "nope"; }); + Assert.ok(realObj[method] === originalMethod); + } + + // A constant is the same thing. + let originalConstantValue; + if (constant) { + originalConstantValue = accessObj[constant]; + accessObj[constant] = "nope"; + Assert.equal(realObj[constant], originalConstantValue); + check_throws(function () { "use strict"; accessObj[constant] = "nope"; }); + Assert.equal(realObj[constant], originalConstantValue); + } + + // Assignment to a readonly accessor property with no setter doesn't work either. + let originalAttributeDesc; + if (attribute) { + originalAttributeDesc = Object.getOwnPropertyDescriptor(realObj, attribute); + Assert.ok("set" in originalAttributeDesc); + Assert.ok(originalAttributeDesc.set === undefined); + + accessObj[attribute] = "nope"; // accessor property with no setter: no exception in non-strict code + check_throws(function () { "use strict"; accessObj[attribute] = "nope"; }); + + let desc = Object.getOwnPropertyDescriptor(realObj, attribute); + Assert.ok("set" in desc); + Assert.equal(originalAttributeDesc.get, desc.get); + Assert.equal(undefined, desc.set); + } + + // Reflect.set doesn't work either. + if (method) { + Assert.ok(!Reflect.set({}, method, "bad", accessObj)); + Assert.equal(realObj[method], originalMethod); + } + if (attribute) { + Assert.ok(!Reflect.set({}, attribute, "bad", accessObj)); + Assert.equal(originalAttributeDesc.get, Object.getOwnPropertyDescriptor(realObj, attribute).get); + } + + // Object.defineProperty can't do anything either. + let names = ["expando"]; + if (method) names.push(method); + if (constant) names.push(constant); + if (attribute) names.push(attribute); + for (let name of names) { + let originalDesc = Object.getOwnPropertyDescriptor(realObj, name); + check_throws(function () { + Object.defineProperty(accessObj, name, {configurable: true}); + }); + check_throws(function () { + Object.defineProperty(accessObj, name, {writable: true}); + }); + check_throws(function () { + Object.defineProperty(accessObj, name, {get: function () { return "lies"; }}); + }); + check_throws(function () { + Object.defineProperty(accessObj, name, {value: "bad"}); + }); + let desc = Object.getOwnPropertyDescriptor(realObj, name); + if (originalDesc === undefined) { + Assert.equal(undefined, desc); + } else { + Assert.equal(originalDesc.configurable, desc.configurable); + Assert.equal(originalDesc.enumerable, desc.enumerable); + Assert.equal(originalDesc.writable, desc.writable); + Assert.equal(originalDesc.value, desc.value); + Assert.equal(originalDesc.get, desc.get); + Assert.equal(originalDesc.set, desc.set); + } + } + + // Existing properties can't be deleted. + if (method) { + Assert.equal(false, delete accessObj[method]); + check_throws(function () { "use strict"; delete accessObj[method]; }); + Assert.equal(realObj[method], originalMethod); + } + if (constant) { + Assert.equal(false, delete accessObj[constant]); + check_throws(function () { "use strict"; delete accessObj[constant]; }); + Assert.equal(realObj[constant], originalConstantValue); + } + if (attribute) { + Assert.equal(false, delete accessObj[attribute]); + check_throws(function () { "use strict"; delete accessObj[attribute]; }); + desc = Object.getOwnPropertyDescriptor(realObj, attribute); + Assert.equal(originalAttributeDesc.get, desc.get); + } +} + +function test_twice(obj, options) { + test_tamperproof(obj, obj, options); + + let handler = { + getPrototypeOf(t) { + return new Proxy(Object.getPrototypeOf(t), handler); + } + }; + test_tamperproof(obj, new Proxy(obj, handler), options); +} + +function run_test() { + let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + test_twice(timer, { + method: "init", + constant: "TYPE_ONE_SHOT", + attribute: "callback" + }); + + let cmdline = Cu.createCommandLine(); + test_twice(cmdline, {}); + + test_twice(Object.getPrototypeOf(cmdline), { + method: "getArgument", + constant: "STATE_INITIAL_LAUNCH", + attribute: "length" + }); + + // Test a tearoff object. + Components.manager.autoRegister(do_get_file('../components/js/xpctest.manifest')); + let b = Cc["@mozilla.org/js/xpc/test/js/TestInterfaceAll;1"].createInstance(Ci.nsIXPCTestInterfaceB); + let tearoff = b.nsIXPCTestInterfaceA; + test_twice(tearoff, { + method: "QueryInterface" + }); +} diff --git a/js/xpconnect/tests/unit/test_xray_SavedFrame-02.js b/js/xpconnect/tests/unit/test_xray_SavedFrame-02.js new file mode 100644 index 0000000000..bb93ceaf38 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_SavedFrame-02.js @@ -0,0 +1,71 @@ +// Test calling SavedFrame getters across wrappers from privileged and +// un-privileged globals. + +const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); +addDebuggerToGlobal(this); + +const lowP = Cc["@mozilla.org/nullprincipal;1"].createInstance(Ci.nsIPrincipal); +const highP = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal); + +const low = new Cu.Sandbox(lowP); +const high = new Cu.Sandbox(highP); + +function run_test() { + // Privileged compartment accessing unprivileged stack. + high.stack = getSavedFrameInstanceFromSandbox(low); + Cu.evalInSandbox("this.parent = stack.parent", high); + Cu.evalInSandbox("this.asyncParent = stack.asyncParent", high); + Cu.evalInSandbox("this.source = stack.source", high); + Cu.evalInSandbox("this.functionDisplayName = stack.functionDisplayName", high); + + // Un-privileged compartment accessing privileged stack. + low.stack = getSavedFrameInstanceFromSandbox(high); + try { + Cu.evalInSandbox("this.parent = stack.parent", low); + } catch (e) { } + try { + Cu.evalInSandbox("this.asyncParent = stack.asyncParent", low); + } catch (e) { } + try { + Cu.evalInSandbox("this.source = stack.source", low); + } catch (e) { } + try { + Cu.evalInSandbox("this.functionDisplayName = stack.functionDisplayName", low); + } catch (e) { } + + // Privileged compartment accessing privileged stack. + let stack = getSavedFrameInstanceFromSandbox(high); + let parent = stack.parent; + let asyncParent = stack.asyncParent; + let source = stack.source; + let functionDisplayName = stack.functionDisplayName; + + ok(true, "Didn't crash"); +} + +// Get a SavedFrame instance from inside the given sandbox. +// +// We can't use Cu.getJSTestingFunctions().saveStack() because Cu isn't +// available to sandboxes that don't have the system principal. The easiest way +// to get the SavedFrame is to use the Debugger API to track allocation sites +// and then do an allocation. +function getSavedFrameInstanceFromSandbox(sandbox) { + const dbg = new Debugger(sandbox); + + dbg.memory.trackingAllocationSites = true; + Cu.evalInSandbox("(function iife() { return new RegExp }())", sandbox); + const allocs = dbg.memory.drainAllocationsLog().filter(e => e.class === "RegExp"); + dbg.memory.trackingAllocationSites = false; + + ok(allocs[0], "We should observe the allocation"); + const { frame } = allocs[0]; + + if (sandbox !== high) { + ok(Cu.isXrayWrapper(frame), "`frame` should be an xray..."); + equal(Object.prototype.toString.call(Cu.waiveXrays(frame)), + "[object SavedFrame]", + "...and that xray should wrap a SavedFrame"); + } + + return frame; +} diff --git a/js/xpconnect/tests/unit/test_xray_SavedFrame.js b/js/xpconnect/tests/unit/test_xray_SavedFrame.js new file mode 100644 index 0000000000..826c6afce4 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_SavedFrame.js @@ -0,0 +1,104 @@ +// Bug 1117242: Test calling SavedFrame getters from globals that don't subsume +// that frame's principals. + +const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); +addDebuggerToGlobal(this); + +const lowP = Cc["@mozilla.org/nullprincipal;1"].createInstance(Ci.nsIPrincipal); +const midP = [lowP, "http://other.com"]; +const highP = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal); + +const low = new Cu.Sandbox(lowP); +const mid = new Cu.Sandbox(midP); +const high = new Cu.Sandbox(highP); + +function run_test() { + // Test that the priveleged view of a SavedFrame from a subsumed compartment + // is the same view that the subsumed compartment gets. Create the following + // chain of function calls (with some intermediate system-principaled frames + // due to implementation): + // + // low.lowF -> mid.midF -> high.highF -> high.saveStack + // + // Where high.saveStack gets monkey patched to create stacks in each of our + // sandboxes. + + Cu.evalInSandbox("function highF() { return saveStack(); }", high); + + mid.highF = () => high.highF(); + Cu.evalInSandbox("function midF() { return highF(); }", mid); + + low.midF = () => mid.midF(); + Cu.evalInSandbox("function lowF() { return midF(); }", low); + + const expected = [ + { + sandbox: low, + frames: ["lowF"], + }, + { + sandbox: mid, + frames: ["midF", "lowF"], + }, + { + sandbox: high, + frames: ["getSavedFrameInstanceFromSandbox", + "saveStack", + "highF", + "run_test/mid.highF", + "midF", + "run_test/low.midF", + "lowF", + "run_test", + "_execute_test", + null], + } + ]; + + for (let { sandbox, frames } of expected) { + high.saveStack = function saveStack() { + return getSavedFrameInstanceFromSandbox(sandbox); + }; + + const xrayStack = low.lowF(); + equal(xrayStack.functionDisplayName, "getSavedFrameInstanceFromSandbox", + "Xrays should always be able to see everything."); + + let waived = Cu.waiveXrays(xrayStack); + do { + ok(frames.length, + "There should still be more expected frames while we have actual frames."); + equal(waived.functionDisplayName, frames.shift(), + "The waived wrapper should give us the stack's compartment's view."); + waived = waived.parent; + } while (waived); + } +} + +// Get a SavedFrame instance from inside the given sandbox. +// +// We can't use Cu.getJSTestingFunctions().saveStack() because Cu isn't +// available to sandboxes that don't have the system principal. The easiest way +// to get the SavedFrame is to use the Debugger API to track allocation sites +// and then do an allocation. +function getSavedFrameInstanceFromSandbox(sandbox) { + const dbg = new Debugger(sandbox); + + dbg.memory.trackingAllocationSites = true; + Cu.evalInSandbox("new Object", sandbox); + const allocs = dbg.memory.drainAllocationsLog(); + dbg.memory.trackingAllocationSites = false; + + ok(allocs[0], "We should observe the allocation"); + const { frame } = allocs[0]; + + if (sandbox !== high) { + ok(Cu.isXrayWrapper(frame), "`frame` should be an xray..."); + equal(Object.prototype.toString.call(Cu.waiveXrays(frame)), + "[object SavedFrame]", + "...and that xray should wrap a SavedFrame"); + } + + return frame; +} + diff --git a/js/xpconnect/tests/unit/test_xray_instanceof.js b/js/xpconnect/tests/unit/test_xray_instanceof.js new file mode 100644 index 0000000000..69e18d160a --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_instanceof.js @@ -0,0 +1,210 @@ +/* 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 {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +add_task(function instanceof_xrays() { + let sandbox = Cu.Sandbox(null); + Cu.evalInSandbox(` + this.proxy = new Proxy([], { + getPrototypeOf() { + return Date.prototype; + }, + }); + + this.inheritedProxy = Object.create(this.proxy); + + this.FunctionProxy = new Proxy(function() {}, {}); + this.functionProxyInstance = new this.FunctionProxy(); + + this.CustomClass = class {}; + this.customClassInstance = new this.CustomClass(); + `, sandbox); + + { + // Sanity check that instanceof still works with standard constructors when xrays are present. + Assert.ok(Cu.evalInSandbox(`new Date()`, sandbox) instanceof sandbox.Date, + "async function result in sandbox instanceof sandbox.Date"); + Assert.ok(new sandbox.Date() instanceof sandbox.Date, + "sandbox.Date() instanceof sandbox.Date"); + + Assert.ok(sandbox.CustomClass instanceof sandbox.Function, + "Class constructor instanceof sandbox.Function"); + Assert.ok(sandbox.CustomClass instanceof sandbox.Object, + "Class constructor instanceof sandbox.Object"); + + // Both operands must have the same kind of Xray vision. + Assert.equal(Cu.waiveXrays(sandbox.CustomClass) instanceof sandbox.Function, false, + "Class constructor with waived xrays instanceof sandbox.Function"); + Assert.equal(Cu.waiveXrays(sandbox.CustomClass) instanceof sandbox.Object, false, + "Class constructor with waived xrays instanceof sandbox.Object"); + } + + { + let {proxy} = sandbox; + Assert.equal(proxy instanceof sandbox.Date, false, + "instanceof should ignore the proxy trap"); + Assert.equal(proxy instanceof sandbox.Array, false, + "instanceof should ignore the proxy target"); + Assert.equal(Cu.waiveXrays(proxy) instanceof sandbox.Date, false, + "instanceof should ignore the proxy trap despite the waived xrays on the proxy"); + Assert.equal(Cu.waiveXrays(proxy) instanceof sandbox.Array, false, + "instanceof should ignore the proxy target despite the waived xrays on the proxy"); + + Assert.equal(proxy instanceof Cu.waiveXrays(sandbox.Date), false, + "instanceof should ignore the proxy trap despite the waived xrays on the constructor"); + Assert.equal(proxy instanceof Cu.waiveXrays(sandbox.Array), false, + "instanceof should ignore the proxy target despite the waived xrays on the constructor"); + + Assert.ok(Cu.waiveXrays(proxy) instanceof Cu.waiveXrays(sandbox.Date), + "instanceof should trigger the proxy trap after waiving both Xrays"); + } + + + { + let {inheritedProxy} = sandbox; + Assert.equal(inheritedProxy instanceof sandbox.Date, false, + "instanceof should ignore the inherited proxy trap"); + Assert.equal(Cu.waiveXrays(inheritedProxy) instanceof sandbox.Date, false, + "instanceof should ignore the inherited proxy trap despite the waived xrays on the proxy"); + + Assert.equal(inheritedProxy instanceof Cu.waiveXrays(sandbox.Date), false, + "instanceof should ignore the inherited proxy trap despite the waived xrays on the constructor"); + + Assert.ok(Cu.waiveXrays(inheritedProxy) instanceof Cu.waiveXrays(sandbox.Date), + "instanceof should trigger the inherited proxy trap after waiving both Xrays"); + } + + { + let {FunctionProxy, functionProxyInstance} = sandbox; + + // Ideally, the next two test cases should both throw "... not a function". + // However, because the opaque XrayWrapper does not override isCallable, an + // opaque XrayWrapper is still considered callable if the proxy target is, + // and "instanceof" will try to look up the prototype of the wrapper (and + // fail because opaque XrayWrappers hide the properties). + Assert.throws( + () => functionProxyInstance instanceof FunctionProxy, + /'prototype' property of FunctionProxy is not an object/, + "Opaque constructor proxy should be hidden by Xrays"); + Assert.throws( + () => functionProxyInstance instanceof sandbox.proxy, + /sandbox.proxy is not a function/, + "Opaque non-constructor proxy should be hidden by Xrays"); + + Assert.equal(functionProxyInstance instanceof Cu.waiveXrays(FunctionProxy), false, + "Waiver on opaque constructor proxy should be ignored for XrayWrapped functionProxyInstance"); + Assert.ok(Cu.waiveXrays(functionProxyInstance) instanceof Cu.waiveXrays(FunctionProxy), + "instanceof should get through the proxy after waiving both Xrays"); + } + + { + let {CustomClass, customClassInstance} = sandbox; + // Under Xray vision, every JS object is either a plain object or array. + // Prototypical inheritance is invisible when the constructor is wrapped. + Assert.throws( + () => customClassInstance instanceof CustomClass, + /TypeError: 'prototype' property of CustomClass is not an object/, + "instanceof on a custom JS class with xrays should fail"); + Assert.equal(customClassInstance instanceof Cu.waiveXrays(CustomClass), false, + "instanceof should return false if the instance and constructor have distinct Xray vision"); + Assert.ok(Cu.waiveXrays(customClassInstance) instanceof Cu.waiveXrays(CustomClass), + "instanceof should see the true prototype of CustomClass after waiving Xrays"); + } +}); + +add_task(function instanceof_dom_xrays_hasInstance() { + const principal = Services.scriptSecurityManager.createNullPrincipal({}); + const webnav = Services.appShell.createWindowlessBrowser(false); + webnav.docShell.createAboutBlankContentViewer(principal, principal); + let window = webnav.document.defaultView; + + let sandbox = Cu.Sandbox(principal); + sandbox.DOMObjectWithHasInstance = window.document; + Cu.evalInSandbox(` + this.DOMObjectWithHasInstance[Symbol.hasInstance] = function() { + return true; + }; + this.ObjectWithHasInstance = { + [Symbol.hasInstance](v) { + v.throwsIfVCannotBeAccessed; + return true; + }, + }; + `, sandbox); + + // Override the hasInstance handler in the window, so that we can detect when + // we end up triggering hasInstance in the window's compartment. + window.eval(` + document[Symbol.hasInstance] = function() { + throw "hasInstance_in_window"; + }; + `); + + sandbox.domobj = window.document.body; + Assert.ok(sandbox.eval(`domobj.wrappedJSObject`), + "DOM object is a XrayWrapper"); + Assert.ok(sandbox.eval(`DOMObjectWithHasInstance.wrappedJSObject`), + "DOM object with Symbol.hasInstance is a XrayWrapper"); + + for (let Obj of ["ObjectWithHasInstance", "DOMObjectWithHasInstance"]) { + // Tests Xray vision *inside* the sandbox. The Symbol.hasInstance member + // is a property / expando object in the sandbox's compartment, so the + // "instanceof" operator should always trigger the hasInstance function. + Assert.ok(sandbox.eval(`[] instanceof ${Obj}`), + `Should call ${Obj}[Symbol.hasInstance] when left operand has no Xrays`); + Assert.ok(sandbox.eval(`domobj instanceof ${Obj}`), + `Should call ${Obj}[Symbol.hasInstance] when left operand has Xrays`); + Assert.ok(sandbox.eval(`domobj.wrappedJSObject instanceof ${Obj}`), + `Should call ${Obj}[Symbol.hasInstance] when left operand has waived Xrays`); + + // Tests Xray vision *outside* the sandbox. The Symbol.hasInstance member + // should be hidden by Xrays. + let sandboxObjWithHasInstance = sandbox[Obj]; + Assert.ok(Cu.isXrayWrapper(sandboxObjWithHasInstance), + `sandbox.${Obj} is a XrayWrapper`); + Assert.throws( + () => sandbox.Object() instanceof sandboxObjWithHasInstance, + /sandboxObjWithHasInstance is not a function/, + `sandbox.${Obj}[Symbol.hasInstance] should be hidden by Xrays`); + + Assert.throws( + () => Cu.waiveXrays(sandbox.Object()) instanceof sandboxObjWithHasInstance, + /sandboxObjWithHasInstance is not a function/, + `sandbox.${Obj}[Symbol.hasInstance] should be hidden by Xrays, despite the waived Xrays at the left`); + + // The Xay waiver on the right operand should be ignored if the left + // operand still has Xrays. + Assert.throws( + () => sandbox.Object() instanceof Cu.waiveXrays(sandboxObjWithHasInstance), + /Cu.waiveXrays\(\.\.\.\) is not a function/, + `Waiver on sandbox.${Obj} should be ignored when the left operand has Xrays`); + // (Cases where the left operand has no Xrays are checked below.) + } + + // hasInstance is expected to be called, but still trigger an error because + // properties of the object from the current context should not be readable + // by the hasInstance function in the sandbox with a different principal. + Assert.throws( + () => [] instanceof Cu.waiveXrays(sandbox.ObjectWithHasInstance), + /Permission denied to access property "throwsIfVCannotBeAccessed"/, + `Should call (waived) sandbox.ObjectWithHasInstance[Symbol.hasInstance] when the left operand has no Xrays`); + + Assert.ok(Cu.waiveXrays(sandbox.Object()) instanceof Cu.waiveXrays(sandbox.ObjectWithHasInstance), + `Should call (waived) sandbox.ObjectWithHasInstance[Symbol.hasInstance] when the left operand has waived Xrays`); + + // When Xrays of the DOM object are waived, we end up in the owner document's + // compartment (instead of the sandbox). + Assert.throws( + () => [] instanceof Cu.waiveXrays(sandbox.DOMObjectWithHasInstance), + /hasInstance_in_window/, + "Should call (waived) sandbox.DOMObjectWithHasInstance[Symbol.hasInstance] when the left operand has no Xrays"); + + Assert.throws( + () => Cu.waiveXrays(sandbox.Object()) instanceof Cu.waiveXrays(sandbox.DOMObjectWithHasInstance), + /hasInstance_in_window/, + "Should call (waived) sandbox.DOMObjectWithHasInstance[Symbol.hasInstance] when the left operand has waived Xrays"); + + webnav.close(); +}); diff --git a/js/xpconnect/tests/unit/test_xray_named_element_access.js b/js/xpconnect/tests/unit/test_xray_named_element_access.js new file mode 100644 index 0000000000..938d1575ca --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_named_element_access.js @@ -0,0 +1,24 @@ +// See https://bugzilla.mozilla.org/show_bug.cgi?id=1273251 +"use strict" + +ChromeUtils.import("resource://gre/modules/Preferences.jsm"); +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +add_task(async function() { + let webnav = Services.appShell.createWindowlessBrowser(false); + + let docShell = webnav.docShell; + + docShell.createAboutBlankContentViewer(null, null); + + let window = webnav.document.defaultView; + let unwrapped = Cu.waiveXrays(window); + + window.document.body.innerHTML = '<div id="foo"></div>'; + + equal(window.foo, undefined, "Should not have named X-ray property access"); + equal(typeof unwrapped.foo, "object", "Should always have non-X-ray named property access"); + + webnav.close(); +}); + diff --git a/js/xpconnect/tests/unit/test_xray_regexp.js b/js/xpconnect/tests/unit/test_xray_regexp.js new file mode 100644 index 0000000000..72eb9563d0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_regexp.js @@ -0,0 +1,7 @@ +function run_test() { + var sandbox = Cu.Sandbox('http://www.example.com'); + var regexp = Cu.evalInSandbox("/test/i", sandbox); + equal(RegExp.prototype.toString.call(regexp), "/test/i"); + var prototype = Cu.evalInSandbox("RegExp.prototype", sandbox); + equal(typeof prototype.lastIndex, "undefined"); +} diff --git a/js/xpconnect/tests/unit/test_xrayed_arguments.js b/js/xpconnect/tests/unit/test_xrayed_arguments.js new file mode 100644 index 0000000000..fae0a0c865 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xrayed_arguments.js @@ -0,0 +1,16 @@ +function run_test() { + var sbContent = Cu.Sandbox(null); + let xrayedArgs = sbContent.eval("(function(a, b) { return arguments; })('hi', 42)"); + + function checkArgs(a) { + Assert.equal(a.length, 2); + Assert.equal(a[0], 'hi'); + Assert.equal(a[1], 42); + } + + // Check Xrays to the args. + checkArgs(xrayedArgs); + + // Make sure the spread operator works. + checkArgs([...xrayedArgs]); +} diff --git a/js/xpconnect/tests/unit/test_xrayed_iterator.js b/js/xpconnect/tests/unit/test_xrayed_iterator.js new file mode 100644 index 0000000000..5cba0ea9ad --- /dev/null +++ b/js/xpconnect/tests/unit/test_xrayed_iterator.js @@ -0,0 +1,42 @@ +const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +Services.prefs.setBoolPref("security.allow_eval_with_system_principal", true); +registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_eval_with_system_principal"); +}); + +function run_test() { + + var toEval = [ + "var customIterator = {", + " _array: [6, 7, 8, 9]", + "};", + "customIterator[Symbol.iterator] = function* () {", + " for (var i = 0; i < this._array.length; ++i)", + " yield this._array[i];", + "};" + ].join('\n'); + + function checkIterator(iterator) { + var control = [6, 7, 8, 9]; + var i = 0; + for (var item of iterator) { + Assert.equal(item, control[i]); + ++i; + } + } + + // First, try in our own scope. + eval(toEval); + checkIterator(customIterator); + + // Next, try a vanilla CCW. + var sbChrome = Cu.Sandbox(this); + Cu.evalInSandbox(toEval, sbChrome, '1.7'); + checkIterator(sbChrome.customIterator); + + // Finally, try an Xray waiver. + var sbContent = Cu.Sandbox('http://www.example.com'); + Cu.evalInSandbox(toEval, sbContent, '1.7'); + checkIterator(Cu.waiveXrays(sbContent.customIterator)); +} diff --git a/js/xpconnect/tests/unit/uninitialized_lexical.jsm b/js/xpconnect/tests/unit/uninitialized_lexical.jsm new file mode 100644 index 0000000000..e0d661bcd4 --- /dev/null +++ b/js/xpconnect/tests/unit/uninitialized_lexical.jsm @@ -0,0 +1,2 @@ +var EXPORTED_SYMBOLS = ["foo"]; +const foo = ChromeUtils.import("resource://test/uninitialized_lexical.jsm"); diff --git a/js/xpconnect/tests/unit/xpcshell.ini b/js/xpconnect/tests/unit/xpcshell.ini new file mode 100644 index 0000000000..725a5f5591 --- /dev/null +++ b/js/xpconnect/tests/unit/xpcshell.ini @@ -0,0 +1,160 @@ +[DEFAULT] +head = +support-files = + CatRegistrationComponents.manifest + bogus_element_type.jsm + bogus_exports_type.jsm + bug451678_subscript.js + component-blob.js + component-blob.manifest + component-file.js + component-file.manifest + component_import.js + component_import.manifest + environment_script.js + environment_loadscript.jsm + environment_checkscript.jsm + file_simple_script.js + importer.jsm + recursive_importA.jsm + recursive_importB.jsm + syntax_error.jsm + uninitialized_lexical.jsm + +[test_allowWaivers.js] +[test_bogus_files.js] +[test_bug267645.js] +[test_bug408412.js] +[test_bug451678.js] +[test_bug604362.js] +[test_bug677864.js] +[test_bug711404.js] +[test_bug742444.js] +[test_bug778409.js] +[test_bug780370.js] +[test_bug809652.js] +[test_bug809674.js] +[test_bug813901.js] +[test_bug845201.js] +[test_bug845862.js] +[test_bug849730.js] +[test_bug851895.js] +[test_bug853709.js] +[test_bug854558.js] +[test_bug856067.js] +[test_bug868675.js] +[test_bug867486.js] +[test_bug872772.js] +[test_bug885800.js] +[test_bug930091.js] +[test_bug976151.js] +[test_bug1001094.js] +[test_bug1021312.js] +[test_bug1033253.js] +[test_bug1033920.js] +[test_bug1033927.js] +[test_bug1034262.js] +[test_bug1082450.js] +[test_bug1081990.js] +[test_bug1110546.js] +[test_bug1131707.js] +[test_bug1150771.js] +[test_bug1151385.js] +[test_bug1170311.js] +[test_bug1244222.js] +[test_bug1617527.js] +[test_bug_442086.js] +[test_callFunctionWithAsyncStack.js] +[test_cenums.js] +[test_compileScript.js] +[test_deepFreezeClone.js] +[test_defineModuleGetter.js] +[test_file.js] +skip-if = os == 'android' && processor == 'x86_64' +[test_blob.js] +[test_blob2.js] +[test_file2.js] +skip-if = os == 'android' && processor == 'x86_64' +[test_getCallerLocation.js] +[test_generateQI.js] +[test_import.js] +[test_import_fail.js] +[test_isModuleLoaded.js] +[test_js_weak_references.js] +[test_onGarbageCollection-01.js] +head = head_ongc.js +[test_onGarbageCollection-02.js] +head = head_ongc.js +[test_onGarbageCollection-03.js] +head = head_ongc.js +[test_onGarbageCollection-04.js] +head = head_ongc.js +[test_onGarbageCollection-05.js] +head = head_ongc.js +[test_reflect_parse.js] +[test_localeCompare.js] +[test_recursive_import.js] +[test_xpcomutils.js] +[test_unload.js] +[test_lazyproxy.js] +[test_attributes.js] +[test_params.js] +[test_tearoffs.js] +[test_want_components.js] +[test_components.js] +[test_allowedDomains.js] +[test_allowedDomainsXHR.js] +[test_nuke_sandbox.js] +[test_nuke_sandbox_event_listeners.js] +[test_nuke_webextension_wrappers.js] +[test_subScriptLoader.js] +[test_rewrap_dead_wrapper.js] +[test_sandbox_metadata.js] +[test_sandbox_DOMException.js] +[test_exportFunction.js] +[test_promise.js] +[test_returncode.js] +[test_textDecoder.js] +[test_url.js] +[test_URLSearchParams.js] +[test_fileReader.js] +[test_messageChannel.js] +[test_crypto.js] +[test_css.js] +[test_rtcIdentityProvider.js] +[test_sandbox_atob.js] +[test_isProxy.js] +[test_js_memory_telemetry.js] +[test_getObjectPrincipal.js] +[test_sandbox_name.js] +[test_watchdog_enable.js] +head = head_watchdog.js +[test_watchdog_disable.js] +head = head_watchdog.js +[test_watchdog_toggle.js] +head = head_watchdog.js +[test_watchdog_default.js] +head = head_watchdog.js +skip-if = (verify && debug && os == 'android') +[test_watchdog_hibernate.js] +head = head_watchdog.js +[test_weak_keys.js] +[test_xpcwn_tamperproof.js] +[test_xrayed_arguments.js] +[test_xrayed_iterator.js] +[test_xray_instanceof.js] +[test_xray_named_element_access.js] +[test_private_field_xrays.js] +[test_xray_SavedFrame.js] +[test_xray_SavedFrame-02.js] +[test_xray_regexp.js] +[test_resolve_dead_promise.js] +[test_function_names.js] +[test_FrameScriptEnvironment.js] +[test_SubscriptLoaderEnvironment.js] +[test_SubscriptLoaderSandboxEnvironment.js] +[test_SubscriptLoaderJSMEnvironment.js] +[test_ComponentEnvironment.js] +[test_wrapped_js_enumerator.js] +[test_uawidget_scope.js] +[test_uninitialized_lexical.js] |