diff options
author | Matt A. Tobin <mattatobin@localhost.localdomain> | 2018-02-02 04:16:08 -0500 |
---|---|---|
committer | Matt A. Tobin <mattatobin@localhost.localdomain> | 2018-02-02 04:16:08 -0500 |
commit | 5f8de423f190bbb79a62f804151bc24824fa32d8 (patch) | |
tree | 10027f336435511475e392454359edea8e25895d /js/xpconnect/tests | |
parent | 49ee0794b5d912db1f95dce6eb52d781dc210db5 (diff) | |
download | UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar.gz UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar.lz UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar.xz UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.zip |
Add m-esr52 at 52.6.0
Diffstat (limited to 'js/xpconnect/tests')
346 files changed, 16705 insertions, 0 deletions
diff --git a/js/xpconnect/tests/browser/browser.ini b/js/xpconnect/tests/browser/browser.ini new file mode 100644 index 000000000..bf7271df0 --- /dev/null +++ b/js/xpconnect/tests/browser/browser.ini @@ -0,0 +1,4 @@ +[DEFAULT] +support-files = + browser_deadObjectOnUnload.html +[browser_dead_object.js] diff --git a/js/xpconnect/tests/browser/browser_deadObjectOnUnload.html b/js/xpconnect/tests/browser/browser_deadObjectOnUnload.html new file mode 100644 index 000000000..ceb40b20b --- /dev/null +++ b/js/xpconnect/tests/browser/browser_deadObjectOnUnload.html @@ -0,0 +1,18 @@ +<!DOCTYPE HTML> +<html> +<!-- +Test page for https://bugzilla.mozilla.org/show_bug.cgi?id=1242643 +--> +<head> + <meta charset="utf-8"> + <title>Test page for Bug 1242643</title> +</head> +<body onUnload="onUnload();"> +<p><span id="samplepage">sample page</span></p> +<script type="application/javascript"> + function onUnload() { + console.log('in unload'); + } +</script> +</body> +</html> diff --git a/js/xpconnect/tests/browser/browser_dead_object.js b/js/xpconnect/tests/browser/browser_dead_object.js new file mode 100644 index 000000000..71ec36f2d --- /dev/null +++ b/js/xpconnect/tests/browser/browser_dead_object.js @@ -0,0 +1,21 @@ +/* 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/. + */ + +// For bug 773980, test that Components.utils.isDeadWrapper works as expected. + +add_task(function* test() { + const url = "http://mochi.test:8888/browser/js/xpconnect/tests/browser/browser_deadObjectOnUnload.html"; + let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url); + let browser = gBrowser.selectedBrowser; + let contentDocDead = yield ContentTask.spawn(browser,{}, function*(browser){ + let doc = content.document; + let promise = ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true); + content.location = "about:home"; + yield promise; + return Components.utils.isDeadWrapper(doc); + }); + is(contentDocDead, true, "wrapper is dead"); + yield BrowserTestUtils.removeTab(newTab); +}); diff --git a/js/xpconnect/tests/browser/moz.build b/js/xpconnect/tests/browser/moz.build new file mode 100644 index 000000000..29412da46 --- /dev/null +++ b/js/xpconnect/tests/browser/moz.build @@ -0,0 +1,8 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +BROWSER_CHROME_MANIFESTS += ['browser.ini'] + diff --git a/js/xpconnect/tests/chrome/bug503926.xul b/js/xpconnect/tests/chrome/bug503926.xul new file mode 100644 index 000000000..ea5e02cbe --- /dev/null +++ b/js/xpconnect/tests/chrome/bug503926.xul @@ -0,0 +1,30 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=503926 +--> +<window title="Mozilla Bug 503926" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=503926" + target="_blank">Mozilla Bug 503926</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + var gWindowUtils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor). + getInterface(Components.interfaces.nsIDOMWindowUtils); + var passed = false; + var obj = { QueryInterface: function() { passed = true; } } + gWindowUtils.xpconnectArgument(obj); + var isDialog = location.hash != '#iframe'; + var outer = XPCNativeWrapper.unwrap(isDialog ? opener : parent); + outer.ok(passed, "chrome/chrome test passed: " + (isDialog ? "dialog" : "iframe")); + if (isDialog) + close(); + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/chrome.ini b/js/xpconnect/tests/chrome/chrome.ini new file mode 100644 index 000000000..5a7b98214 --- /dev/null +++ b/js/xpconnect/tests/chrome/chrome.ini @@ -0,0 +1,119 @@ +[DEFAULT] +skip-if = os == 'android' +support-files = + bug503926.xul + file_bug618176.xul + file_bug996069.html + file_bug1050049.xml + file_bug1281071.html + file_discardSystemSource.html + file_evalInSandbox.html + file_expandosharing.jsm + outoflinexulscript.js + subscript.js + utf8_subscript.js + worker_discardSystemSource.js + !/js/xpconnect/tests/mochitest/bug500931_helper.html + !/js/xpconnect/tests/mochitest/bug571849_helper.html + !/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html + !/js/xpconnect/tests/mochitest/file_bug706301.html + !/js/xpconnect/tests/mochitest/file_bug738244.html + !/js/xpconnect/tests/mochitest/file_bug760131.html + !/js/xpconnect/tests/mochitest/file_bug795275.html + !/js/xpconnect/tests/mochitest/file_bug795275.xml + !/js/xpconnect/tests/mochitest/file_bug799348.html + !/js/xpconnect/tests/mochitest/file_bug860494.html + !/js/xpconnect/tests/mochitest/file_documentdomain.html + !/js/xpconnect/tests/mochitest/file_doublewrappedcompartments.html + !/js/xpconnect/tests/mochitest/file_empty.html + !/js/xpconnect/tests/mochitest/file_exnstack.html + !/js/xpconnect/tests/mochitest/file_expandosharing.html + !/js/xpconnect/tests/mochitest/file_nodelists.html + !/js/xpconnect/tests/mochitest/file_evalInSandbox.html + +[test_APIExposer.xul] +[test_bug361111.xul] +[test_bug448587.xul] +[test_bug484459.xul] +skip-if = os == 'win' || os == 'mac' # bug 1131110 +[test_bug500931.xul] +[test_bug503926.xul] +[test_bug533596.xul] +[test_bug571849.xul] +[test_bug596580.xul] +[test_bug601803.xul] +[test_bug610390.xul] +[test_bug614757.xul] +[test_bug616992.xul] +[test_bug618176.xul] +[test_bug654370.xul] +[test_bug658560.xul] +[test_bug658909.xul] +[test_bug664689.xul] +[test_bug679861.xul] +[test_bug706301.xul] +[test_bug726949.xul] +[test_bug732665.xul] +[test_bug738244.xul] +[test_bug743843.xul] +[test_bug760076.xul] +[test_bug760131.html] +[test_bug763343.xul] +[test_bug771429.xul] +[test_bug773962.xul] +[test_bug792280.xul] +[test_bug793433.xul] +[test_bug795275.xul] +[test_bug799348.xul] +[test_bug801241.xul] +[test_bug812415.xul] +[test_bug853283.xul] +[test_bug853571.xul] +[test_bug858101.xul] +[test_bug860494.xul] +[test_bug865948.xul] +[test_bug866823.xul] +[test_bug895340.xul] +[test_bug932906.xul] +[test_bug996069.xul] +[test_bug1041626.xul] +[test_bug1042436.xul] +[test_bug1050049.html] +[test_bug1065185.html] +[test_bug1074863.html] +[test_bug1092477.xul] +[test_bug1124898.html] +[test_bug1126911.html] +[test_bug1281071.xul] +[test_chrometoSource.xul] +[test_cloneInto.xul] +[test_cows.xul] +[test_discardSystemSource.xul] +[test_documentdomain.xul] +[test_doublewrappedcompartments.xul] +[test_evalInSandbox.xul] +[test_evalInWindow.xul] +[test_exnstack.xul] +[test_expandosharing.xul] +[test_exposeInDerived.xul] +[test_getweakmapkeys.xul] +[test_localstorage_with_nsEp.xul] +[test_matches.xul] +[test_nodelists.xul] +[test_nsScriptErrorWithStack.html] +[test_onGarbageCollection.html] +[test_paris_weakmap_keys.xul] +[test_precisegc.xul] +[test_sandboxImport.xul] +[test_scriptSettings.xul] +[test_watchpoints.xul] +[test_weakmap_keys_preserved.xul] +[test_weakmap_keys_preserved2.xul] +[test_weakmaps.xul] +[test_weakref.xul] +[test_windowProxyDeadWrapper.html] +[test_wrappers.xul] +[test_wrappers-2.xul] +# Disabled until this test gets updated to test the new proxy based wrappers. +skip-if = true +[test_xrayToJS.xul] diff --git a/js/xpconnect/tests/chrome/file_bug1050049.xml b/js/xpconnect/tests/chrome/file_bug1050049.xml new file mode 100644 index 000000000..cc8653ea6 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_bug1050049.xml @@ -0,0 +1,10 @@ +<?xml version="1.0"?> +<bindings id="testBindings" xmlns="http://www.mozilla.org/xbl" + xmlns:html="http://www.w3.org/1999/xhtml"> + <binding id="regularChromeBinding"> + <content><html:p>Anonymous Paragraph</html:p></content> + </binding> + <binding id="whitelistedChromeBinding" bindToUntrustedContent="true"> + <content><html:p>Anonymous Paragraph</html:p></content> + </binding> +</bindings> diff --git a/js/xpconnect/tests/chrome/file_bug1281071.html b/js/xpconnect/tests/chrome/file_bug1281071.html new file mode 100644 index 000000000..2398ce4a5 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_bug1281071.html @@ -0,0 +1,13 @@ +<!DOCTYPE html> +<script> + function tryLocationGet() { + var desc = Object.getOwnPropertyDescriptor(window, "location"); + try { + desc.get.call(parent); + return "get succeeded"; + } catch (e) { + return e.message; + } + } +</script> + diff --git a/js/xpconnect/tests/chrome/file_bug618176.xul b/js/xpconnect/tests/chrome/file_bug618176.xul new file mode 100644 index 000000000..f95352ae1 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_bug618176.xul @@ -0,0 +1,44 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=618176 +--> +<window title="Mozilla Bug 618176" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" + onload="start()"> + <label value="Mozilla Bug 618176"/> + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + const TEST_PAGE = +"data:text/html,<script>var a=[1,2,3];</script>Hi"; + + const FRAME_SCRIPT = +"data:,addEventListener('pageshow', function() { sendAsyncMessage('test', content.wrappedJSObject.a) }, false);"; + // s/content.wrappedJSObject.a/[ 1, 2, 3]/ and the test passes + + function recvTest(m) { + var a = m.json; + opener.wrappedJSObject.is(a.length, 3, "array was serialized and deserialized"); + + messageManager.removeMessageListener("test", recvTest); + finish(); + } + + function start() { + messageManager.addMessageListener("test", recvTest); + messageManager.loadFrameScript(FRAME_SCRIPT, true); + setTimeout(function () { document.getElementById("browser").loadURI(TEST_PAGE); }, 0); + } + + function finish() { + opener.setTimeout("done()", 0); + window.close(); + } + + ]]></script> + + <browser id="browser" type="content" style="width: 200px; height: 200px;"/> +</window> diff --git a/js/xpconnect/tests/chrome/file_bug996069.html b/js/xpconnect/tests/chrome/file_bug996069.html new file mode 100644 index 000000000..e4bed0780 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_bug996069.html @@ -0,0 +1,11 @@ +<!DOCTYPE html> +<html> +<head></head> +<body> + <script> + if (window.opener && window.opener.finishTest) { + window.opener.finishTest(); + } + </script> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/file_discardSystemSource.html b/js/xpconnect/tests/chrome/file_discardSystemSource.html new file mode 100644 index 000000000..9f264ffe5 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_discardSystemSource.html @@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> +<head> +<script> + function canary() { + var someBitOfSource = 42; + } + function inner() { + throw new Error("some error"); + } + function throwSomething() { + inner(); + } +</script> +</head> +<body onload="someBitOfSource = 42"> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/file_evalInSandbox.html b/js/xpconnect/tests/chrome/file_evalInSandbox.html new file mode 100644 index 000000000..fb58f2bb4 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_evalInSandbox.html @@ -0,0 +1 @@ +<html><body><script>document.foo = 'bar';</script></body></html> diff --git a/js/xpconnect/tests/chrome/file_expandosharing.jsm b/js/xpconnect/tests/chrome/file_expandosharing.jsm new file mode 100644 index 000000000..2e7ffe541 --- /dev/null +++ b/js/xpconnect/tests/chrome/file_expandosharing.jsm @@ -0,0 +1,10 @@ +this.EXPORTED_SYMBOLS = ['checkFromJSM']; + +this.checkFromJSM = function checkFromJSM(target, is_op) { + is_op(target.numProp, 42, "Number expando works"); + is_op(target.strProp, "foo", "String expando works"); + // If is_op is todo_is, target.objProp will be undefined. + try { + is_op(target.objProp.bar, "baz", "Object expando works"); + } catch(e) { is_op(0, 1, "No object expando"); } +} diff --git a/js/xpconnect/tests/chrome/moz.build b/js/xpconnect/tests/chrome/moz.build new file mode 100644 index 000000000..7e310c9ea --- /dev/null +++ b/js/xpconnect/tests/chrome/moz.build @@ -0,0 +1,12 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +MOCHITEST_CHROME_MANIFESTS += ['chrome.ini'] + +TEST_HARNESS_FILES.testing.mochitest.tests.js.xpconnect.tests.chrome += [ + 'file_discardSystemSource.html', + 'worker_discardSystemSource.js', +] diff --git a/js/xpconnect/tests/chrome/outoflinexulscript.js b/js/xpconnect/tests/chrome/outoflinexulscript.js new file mode 100644 index 000000000..a06b633af --- /dev/null +++ b/js/xpconnect/tests/chrome/outoflinexulscript.js @@ -0,0 +1,6 @@ +// Some unicode characters that must be decoded: +// ……………………………………………………………………………………………………………………………… +function outoflinefunction() { + return 42; +} + diff --git a/js/xpconnect/tests/chrome/subscript.js b/js/xpconnect/tests/chrome/subscript.js new file mode 100644 index 000000000..3065694b9 --- /dev/null +++ b/js/xpconnect/tests/chrome/subscript.js @@ -0,0 +1,6 @@ +const Cu = Components.utils; +Cu.import("resource://gre/modules/Services.jsm"); + +var ns = {}; +Services.scriptloader.loadSubScript("resource://gre/modules/NetUtil.jsm", ns); +var NetUtil = ns.NetUtil; diff --git a/js/xpconnect/tests/chrome/test_APIExposer.xul b/js/xpconnect/tests/chrome/test_APIExposer.xul new file mode 100644 index 000000000..d89d19759 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_APIExposer.xul @@ -0,0 +1,51 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=634156 +--> +<window title="Testing API exposing capabilities" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=634156" + target="_blank">Mozilla Bug 634156</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + const Cu = Components.utils; + + var sandbox = new Cu.Sandbox("about:blank"); + sandbox.ok = ok; + sandbox.is = is; + Cu.evalInSandbox("Object.defineProperty(Object.prototype, 'getProp', { get: function() { throw 'FAIL: called getter' }, set: function() { throw 'FAIL: called setter'; } })", sandbox); + + var obj = Cu.createObjectIn(sandbox); + is(obj, Cu.waiveXrays(obj), "createObjectIn waives"); + is(Object.getPrototypeOf(obj), Cu.waiveXrays(Cu.evalInSandbox("Object.prototype", sandbox)), + "Object is a sandbox object"); + + function genPropDesc(value) { + return { enumerable: true, configurable: true, writable: true, + value: value }; + } + const props = { + 'getProp': genPropDesc(function() { ok(true, "called prop that shadowed a getter"); }), + 'argument': genPropDesc(function(arg) { is(arg, 42, "can pass arguments through"); }), + 'returnval': genPropDesc(function() { return 42; }) + }; + Object.defineProperties(obj, props); + Cu.makeObjectPropsNormal(obj); + + sandbox.api = obj; + Cu.evalInSandbox("ok(Object.getPrototypeOf(api) === Object.prototype, 'we have the object we expected'); \ + api.getProp(); api.argument(42); is(api.returnval(), 42, 'return value was correct');\ + ok(typeof api.getProp === 'function', 'functions are functions');\ + ok(Object.getPrototypeOf(api.getProp) === Function.prototype, 'functions come from our scope');", sandbox); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug1041626.xul b/js/xpconnect/tests/chrome/test_bug1041626.xul new file mode 100644 index 000000000..c7c7b7024 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1041626.xul @@ -0,0 +1,64 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1041626 +--> +<window title="Mozilla Bug 1041626" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1041626" + target="_blank">Mozilla Bug 1041626</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 1041626 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + function go() { + + // + // Location + // + + ok(Cu.isXrayWrapper(window[0].location), "Location is Xrayed"); + let xrayOwnProperties = Object.getOwnPropertyNames(window[0].location); + todo(xrayOwnProperties.indexOf('toJSON') != -1, + "dummy toJSON on Location should show up in Xrayable properties"); + xrayOwnProperties.push('toJSON'); + + let realOwnProperties = Object.getOwnPropertyNames(window[0].wrappedJSObject.location); + ok(realOwnProperties.length > 2); + + is(xrayOwnProperties.sort().toSource(), realOwnProperties.sort().toSource(), + "Xray enumerates location properties properly"); + + // + // Document + // + + ok(Cu.isXrayWrapper(window[0].document), "Document is Xrayed"); + xrayOwnProperties = Object.getOwnPropertyNames(window[0].document); + + realOwnProperties = Object.getOwnPropertyNames(window[0].wrappedJSObject.document); + ok(realOwnProperties.length > 0); + + is(xrayOwnProperties.sort().toSource(), realOwnProperties.sort().toSource(), + "Xray enumerates document properties properly"); + + + + SimpleTest.finish(); + } + + + + ]]> + </script> + <iframe onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug1042436.xul b/js/xpconnect/tests/chrome/test_bug1042436.xul new file mode 100644 index 000000000..355ffcfa4 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1042436.xul @@ -0,0 +1,49 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1042436 +--> +<window title="Mozilla Bug 1042436" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1042436" + target="_blank">Mozilla Bug 1042436</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 1042436 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + var contentSb = Cu.Sandbox('http://www.example.com'); + var nonXrayableObj = new contentSb.WeakMap(); + nonXrayableObj.wrappedJSObject.someExpandoProperty = 42; + nonXrayableObj.wrappedJSObject.someOtherExpandoProperty = 52; + + + SimpleTest.expectConsoleMessages(function() { + nonXrayableObj.someExpandoProperty; + nonXrayableObj.someOtherExpandoProperty; + + var chromeSb = Cu.Sandbox(this); + var contentObjWithGetter = contentSb.eval('({ get getterProp() {return 42;}, valueProp: 42 })'); + is(contentObjWithGetter.wrappedJSObject.getterProp, 42, "Getter prop set up correctly"); + is(contentObjWithGetter.getterProp, undefined, "Xrays work right"); + is(contentObjWithGetter.valueProp, 42, "Getter prop set up correctly"); + chromeSb.contentObjWithGetter = contentObjWithGetter; + Cu.evalInSandbox('contentObjWithGetter.getterProp; contentObjWithGetter.valueProp; contentObjWithGetter.getterProp;', + chromeSb, "1.7", "http://phony.example.com/file.js", 99); + }, + [{ errorMessage: /property "someExpandoProperty" \(reason: object is not safely Xrayable/, sourceName: /test_bug1042436/, isWarning: true }, + { errorMessage: /property "getterProp" \(reason: property has accessor/, sourceName: /phony/, lineNumber: 99, isWarning: true } ], + SimpleTest.finish.bind(SimpleTest)); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug1050049.html b/js/xpconnect/tests/chrome/test_bug1050049.html new file mode 100644 index 000000000..751ebd467 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1050049.html @@ -0,0 +1,56 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1050049 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1050049</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://global/skin"/> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 1050049 **/ + SimpleTest.waitForExplicitFinish(); + + var regularBindingURI = window.location.toString().replace("test_bug1050049.html", "file_bug1050049.xml") + "#regularChromeBinding"; + var whitelistedBindingURI = window.location.toString().replace("test_bug1050049.html", "file_bug1050049.xml") + "#whitelistedChromeBinding"; + + function testApplyBinding(doc, bindingURI, expectBind) { + var d = doc.createElement('div'); + doc.body.appendChild(d); + d.style.MozBinding = "url(" + bindingURI + ")"; + + return new Promise(function(resolve, reject) { + // Wait two ticks of the refresh driver for the binding to be applied. + function onceBindingWouldBeApplied() { + is(!!doc.getAnonymousNodes(d), expectBind, "Binding " + (expectBind ? "should" : "shouldn't") + + " be applied: " + bindingURI + ", " + doc.location); + resolve(); + } + window.requestAnimationFrame(function() { window.requestAnimationFrame(onceBindingWouldBeApplied); }); + }); + } + + function go() { + testApplyBinding(document, regularBindingURI, true) + .then(testApplyBinding.bind(null, window[0].document, regularBindingURI, false)) + .then(testApplyBinding.bind(null, document, whitelistedBindingURI, true)) + .then(testApplyBinding.bind(null, window[0].document, whitelistedBindingURI, true)) + .then(SimpleTest.finish.bind(SimpleTest)); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1050049">Mozilla Bug 1050049</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +<iframe onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_bug1065185.html b/js/xpconnect/tests/chrome/test_bug1065185.html new file mode 100644 index 000000000..cdd65326f --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1065185.html @@ -0,0 +1,64 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1065185 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1065185</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://global/skin"/> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 1065185 **/ + SimpleTest.waitForExplicitFinish(); + + function doMonitor(rgxps) { + var messages = rgxps.map((x) => ({ errorMessage: x, isWarning: true })); + info("Expecting console messages: " + messages.toSource()); + SimpleTest.monitorConsole(() => SimpleTest.executeSoon(() => window[0].location.reload()), messages, /* forbidUnexpected = */ true); + } + function endMonitor() { + SimpleTest.executeSoon(SimpleTest.endMonitorConsole.bind(SimpleTest)); + } + + var gLoadCount = 0; + function loaded() { + switch(++gLoadCount) { + case 0: + doMonitor([]); + window[0].wrappedJSObject.probe = { a: 2, __exposedProps__: { 'a': 'r' } }; + is(window[0].eval('probe.a'), 2, "Accessed exposed prop"); + endMonitor(); + break; + case 1: + doMonitor([/access to property "a"/i]); + window[0].wrappedJSObject.probe = { a: 2 }; + is(window[0].eval('probe.a'), undefined, "Non-exposed prop undefined"); + is(window[0].eval('probe.a'), undefined, "Non-exposed prop undefined again"); + endMonitor(); + break; + case 2: + SimpleTest.finish(); + break; + default: + ok(false, "Unexpected load"); + SimpleTest.finish(); + break; + } + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1065185">Mozilla Bug 1065185</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +<iframe onload="loaded();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_bug1074863.html b/js/xpconnect/tests/chrome/test_bug1074863.html new file mode 100644 index 000000000..c76301bdb --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1074863.html @@ -0,0 +1,32 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1074863 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1074863</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://global/skin"/> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 1074863 **/ + const Cu = Components.utils; + var sb = new Cu.Sandbox('http://www.example.com'); + sb.namedCtor = Image; + ok(true, "Didn't assert"); + + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1074863">Mozilla Bug 1074863</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_bug1092477.xul b/js/xpconnect/tests/chrome/test_bug1092477.xul new file mode 100644 index 000000000..060a15cec --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1092477.xul @@ -0,0 +1,36 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1092477 +--> +<window title="Mozilla Bug 1092477" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1092477" + target="_blank">Mozilla Bug 1092477</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + +var Cu = Components.utils; +Cu.import("resource://gre/modules/Services.jsm"); +var exn; +var url = "resource://non-existent/script.js"; +try { + Services.scriptloader.loadSubScript(url); + ok(false, "This line should never be reached!"); +} +catch (e) { + exn = String(e); +} +var msg = "loadSubscript should throw an exception for trying to load a non-existent script" +is(exn, "Error opening input stream (invalid filename?): " + url, msg); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug1124898.html b/js/xpconnect/tests/chrome/test_bug1124898.html new file mode 100644 index 000000000..40774cfdf --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1124898.html @@ -0,0 +1,47 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1124898 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1124898</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://global/skin"/> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 1124898 **/ + SimpleTest.waitForExplicitFinish(); + SimpleTest.expectAssertions(0, 1); // Dumb unrelated widget assertion - see bug 1126023. + var w = window.open("about:blank", "w", "chrome"); + is(w.eval('typeof getAttention'), 'function', 'getAttention exists on regular chrome window'); + is(w.eval('typeof messageManager'), 'object', 'messageManager exists on regular chrome window'); + var contentURL = "http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"; + w.location = contentURL; + tryWindow(); + + function tryWindow() { + if (w.document.title != 'empty test page') { + info("Document not loaded yet - retrying"); + SimpleTest.executeSoon(tryWindow); + return; + } + is(w.eval('typeof getAttention'), 'undefined', 'getAttention doesnt exist on content-in-chrome window'); + is(w.eval('typeof messageManager'), 'undefined', 'messageManager doesnt exist on content-in-chrome window'); + w.close(); + SimpleTest.finish(); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1124898">Mozilla Bug 1124898</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_bug1126911.html b/js/xpconnect/tests/chrome/test_bug1126911.html new file mode 100644 index 000000000..e9f5a0b2e --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1126911.html @@ -0,0 +1,41 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1126911 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1126911</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://global/skin"/> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 1126911 **/ + const Cu = Components.utils; + var sb = new Cu.Sandbox(null); + sb.win = window; + sb.loc = location; + function checkThrows(expr) { + try { + Cu.evalInSandbox(expr, sb); + ok(false, "Should have thrown: " + expr); + } catch (e) { + ok(/denied|insecure/.test(e), "should get security exception: " + e); + } + } + checkThrows('win.top'); + checkThrows('loc.replace'); + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1126911">Mozilla Bug 1126911</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_bug1281071.xul b/js/xpconnect/tests/chrome/test_bug1281071.xul new file mode 100644 index 000000000..3e88b3fde --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug1281071.xul @@ -0,0 +1,33 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1281071 +--> +<window title="Mozilla Bug 1281071" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + function go() { + var w = $('ifr').contentWindow.wrappedJSObject; + is(w.tryLocationGet(), "Permission to call 'get location' denied.", + "Trying to get our location object should throw"); + SimpleTest.finish(); + } + ]]></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <iframe type="content" + src="http://mochi.test:8888/chrome/js/xpconnect/tests/chrome/file_bug1281071.html" + onload="go()" + id="ifr"> + </iframe> + </body> + +</window> diff --git a/js/xpconnect/tests/chrome/test_bug361111.xul b/js/xpconnect/tests/chrome/test_bug361111.xul new file mode 100644 index 000000000..4b790ea2d --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug361111.xul @@ -0,0 +1,33 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=361111 +--> +<window title="Mozilla Bug 361111" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=361111" + target="_blank">Mozilla Bug 361111</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 361111 **/ + window.onerror = null; + SimpleTest.waitForExplicitFinish(); + document.documentElement.setAttribute("onclick", "%"); + is(1, 1, "Good, setting a bogus onclick did not throw."); + + // Bonus test - make sure that flushPrefEnv is appropriately + // called at the end of the test. It would be nice if there were + // somewhere in the harness that this could live, but there isn't. + SpecialPowers.pushPrefEnv({set: [['testing.some_arbitrary_pref', true]]}, + function() { SimpleTest.finish(); }); + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug448587.xul b/js/xpconnect/tests/chrome/test_bug448587.xul new file mode 100644 index 000000000..98ee5deda --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug448587.xul @@ -0,0 +1,37 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=448587.xul +--> +<window title="Mozilla Bug 503926" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=448587" + target="_blank">Mozilla Bug 448587</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + // Bonus test - collaborate with test_bug361111.xul to make sure that + // flushPrefEnv is appropriately called. + ok(!SpecialPowers.Services.prefs.prefHasUserValue('testing.some_arbitrary_pref'), + "Pref shouldn't carry over from previous test!"); + + + /** Test for Bug 448587 **/ + const Cu = Components.utils; + var sandbox = new Cu.Sandbox("about:blank"); + var fwrapper = Cu.evalInSandbox("function f() {} f", sandbox); + is(Cu.unwaiveXrays(Cu.waiveXrays(fwrapper).prototype), Cu.evalInSandbox("f.prototype", sandbox), + ".prototype visible through .wrappedJSObject"); + is(fwrapper.prototype, undefined, ".prototype invisible through Xrays"); + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug484459.xul b/js/xpconnect/tests/chrome/test_bug484459.xul new file mode 100644 index 000000000..621a8ae1d --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug484459.xul @@ -0,0 +1,38 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=484459 +--> +<window title="Mozilla Bug 484459" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <iframe type="content" + src="data:text/html,<script>var x=3</script>" + onload="go()" + id="ifr"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + var url = "chrome://mochitests/content/chrome/js/xpconnect/tests/chrome/test_bug484459.xul"; + function go() { + var w = $('ifr').contentWindow.wrappedJSObject; + var sandbox = new Components.utils.Sandbox(w); + sandbox.__proto__ = w; + is(location.href, url, "location.href is set properly"); + is(w.location.href, "data:text/html,<script>var%20x=3</script>", + "contents of w.location are correct"); + is(Components.utils.evalInSandbox("x * 4", sandbox), 12, + "Unexpected return from the sandbox"); + SimpleTest.finish(); + } + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug500931.xul b/js/xpconnect/tests/chrome/test_bug500931.xul new file mode 100644 index 000000000..28d51e362 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug500931.xul @@ -0,0 +1,41 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 500931" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=500931" + target="_blank">Mozilla Bug 500931</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 500931 **/ + + function go() { + var ifr = document.getElementById("ifr"); + var doc = ifr.contentDocument; + ok(Components.utils.isXrayWrapper(doc), "doc is an XrayWrapper"); + var weak = Components.utils.getWeakReference(doc); + ok(Components.utils.isXrayWrapper(weak.get()), "weak reference returns a wrapper"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" + src="http://example.org/tests/js/xpconnect/tests/mochitest/bug500931_helper.html" + onload="go()" + id="ifr"> + </iframe> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug503926.xul b/js/xpconnect/tests/chrome/test_bug503926.xul new file mode 100644 index 000000000..ab611e489 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug503926.xul @@ -0,0 +1,59 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=503926 +--> +<window title="Mozilla Bug 503926" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=503926" + target="_blank">Mozilla Bug 503926</a> + + <iframe id="ifr" type="content" onload="loaded()" src="bug503926.xul#iframe"/> + <iframe id="ifrContent" type="content" onload="loaded()" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"/> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + SimpleTest.expectAssertions(0, 1); + + var gLoadCount = 0; + function loaded() { + if (++gLoadCount == 2) + go(); + } + + /** Test for Bug 503926 **/ + function go() { + var gWindowUtils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor). + getInterface(Components.interfaces.nsIDOMWindowUtils); + + // Try with a chrome object. + var passed = false; + var obj = { QueryInterface: function() { passed = true; } }; + gWindowUtils.xpconnectArgument(obj); + ok(passed, "trusted QIs should be called"); + + // Try with a content object. + var contentWin = $('ifrContent').contentWindow.wrappedJSObject; + contentWin.passed = false; + var contentObj = contentWin.eval('({ QueryInterface: function() { passed = true; } })'); + gWindowUtils.xpconnectArgument(contentObj); + ok(!contentWin.passed, "untrusted QI should not be called"); + + // Try with a dialog. + openDialog("bug503926.xul", "chromeDialog", "modal"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug533596.xul b/js/xpconnect/tests/chrome/test_bug533596.xul new file mode 100644 index 000000000..6a1a00c01 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug533596.xul @@ -0,0 +1,56 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 533596" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=533596" + target="_blank">Mozilla Bug 533596</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 533596 **/ + + function go() { + try { XPCNativeWrapper.unwrap(); } catch (e) {} + try { XPCNativeWrapper.unwrap(0); } catch (e) {} + try { XPCNativeWrapper.unwrap(null); } catch (e) {} + + var o = {}; + is(o, XPCNativeWrapper.unwrap(o), "unwrap on a random object returns it"); + + var win = $('ifr').contentWindow; + var utils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) + .getInterface(Components.interfaces.nsIDOMWindowUtils); + is(utils.getClassName(win), "Proxy", "win is a Proxy"); + ok("x" in XPCNativeWrapper.unwrap(win), "actually unwrapped"); + is(utils.getClassName(XPCNativeWrapper.unwrap(win)), "Proxy", + "unwrap on an Proxy returns the same object"); + is(utils.getClassName(XPCNativeWrapper.unwrap(new XPCNativeWrapper(win))), "Proxy", + "unwrap on an explicit NW works too"); + + ok(utils.getClassName(window) !== "XPCNativeWrapper", "window is not a native wrapper"); + ok(utils.getClassName(XPCNativeWrapper.unwrap(new XPCNativeWrapper(window))) !== "XPCSafeJSObjectWrapper", + "unwrapping a chrome object returns the object itself"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" + src="http://example.org/tests/js/xpconnect/tests/mochitest/bug500931_helper.html" + onload="go()" + id="ifr"> + </iframe> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug571849.xul b/js/xpconnect/tests/chrome/test_bug571849.xul new file mode 100644 index 000000000..a5750b6d4 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug571849.xul @@ -0,0 +1,44 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 500931" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=500931" + target="_blank">Mozilla Bug 500931</a> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 500931 **/ + + function go() { + var ifr = document.getElementById('ifr'); + var docnodes = ifr.contentDocument.body.childNodes; + var index, value; + for (let i in Iterator(docnodes)) { + index = i[0], value = i[1]; + } + is(index, 0, "enumerated the 0th element"); + ok(value instanceof Text, "the 0th element was a text node"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" + src="http://example.org/tests/js/xpconnect/tests/mochitest/bug571849_helper.html" + onload="go()" + id="ifr"> + </iframe> + </body> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug596580.xul b/js/xpconnect/tests/chrome/test_bug596580.xul new file mode 100644 index 000000000..fab7058ac --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug596580.xul @@ -0,0 +1,48 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<window title="Mozilla Bug 596580" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=596580" + target="_blank">Mozilla Bug 596580</a> + </body> + + <!-- test code goes here --> + <script type="application/x-javascript;version=1.8"><![CDATA[ + function init() { + var f = new Function("let test = 'let is ok'; return test;"); + is(f(), 'let is ok', 'let should be ok'); + SimpleTest.finish(); + } + + Test = { + include: function(p) { + var sawError = false; + try { + Components.classes["@mozilla.org/moz/jssubscript-loader;1"]. + getService(Components.interfaces["mozIJSSubScriptLoader"]). + loadSubScript(p); + } catch (e) { + sawError = true; + } + ok(sawError, 'should receive an error loading a not-found file'); + } + }; + + // If the include method is defined as a global function, it works. + // try to load a non existing file to produce the error + Test.include("notfound.js"); + + // If init is called directly, it works. + setTimeout('init();', 0); + + SimpleTest.waitForExplicitFinish(); + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug601803.xul b/js/xpconnect/tests/chrome/test_bug601803.xul new file mode 100644 index 000000000..89c43f024 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug601803.xul @@ -0,0 +1,38 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 601803" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=601803" + target="_blank">Mozilla Bug 601803</a> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 601803 **/ + + function go() { + var ifr = document.getElementById('ifr'); + var elem = document.createElementNS("http://www.w3.org/1999/xhtml","html:div"); + elem.appendChild(document.createTextNode("hello, world")); + elem.expando = 42; + ifr.contentDocument.body.appendChild(elem); + is(elem.wrappedJSObject.expando, 42, "expando is preserved"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" src="about:blank" onload="go()" id="ifr" /> + </body> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug610390.xul b/js/xpconnect/tests/chrome/test_bug610390.xul new file mode 100644 index 000000000..d471c2f65 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug610390.xul @@ -0,0 +1,33 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=610390 +--> +<window title="Mozilla Bug 610390" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <iframe type="content" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" + src="data:text/html,<script>var x=3</script>" + onload="go()" + id="ifr"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + + function go() { + var w = $('ifr').contentWindow; + is(w.wrappedJSObject, w.wrappedJSObject, "wrappedJSObject identity not maintained"); + SimpleTest.finish(); + } + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug614757.xul b/js/xpconnect/tests/chrome/test_bug614757.xul new file mode 100644 index 000000000..c9a50be33 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug614757.xul @@ -0,0 +1,34 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=614757 +--> +<window title="Mozilla Bug 601803" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=614757" + target="_blank">Mozilla Bug 614757</a> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 614757 **/ + + function go() { + is($('ifr').contentDocument.wrappedJSObject.getElementsByTagName('body')[0].toString().indexOf('Xray'), + -1, "Properly deep wrap"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_evalInSandbox.html" onload="go()" id="ifr" /> + </body> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug616992.xul b/js/xpconnect/tests/chrome/test_bug616992.xul new file mode 100644 index 000000000..d5b428fda --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug616992.xul @@ -0,0 +1,32 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=616992 +--> +<window title="Mozilla Bug 601803" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=616992" + target="_blank">Mozilla Bug 616992</a> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 616992 **/ + + const Cu = Components.utils; + var sandbox = new Cu.Sandbox(window); + sandbox.w = window; + var actual = Cu.evalInSandbox("Object.keys(w.NodeFilter)", sandbox).sort().toString(); + var expected = Object.keys(NodeFilter).sort().toString(); + is(actual, expected, "interface constants are visible inside sandboxes"); + + ]]></script> + </body> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug618176.xul b/js/xpconnect/tests/chrome/test_bug618176.xul new file mode 100644 index 000000000..b4c94250c --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug618176.xul @@ -0,0 +1,31 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=618176 +--> +<window title="Mozilla Bug 618176" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=618176" + target="_blank">Mozilla Bug 618176</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + + function done() { + SimpleTest.finish(); + } + + addLoadEvent(function() { + window.open("file_bug618176.xul", "", "chrome"); + }); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug654370.xul b/js/xpconnect/tests/chrome/test_bug654370.xul new file mode 100644 index 000000000..c4e78f06b --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug654370.xul @@ -0,0 +1,29 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=654370 +--> +<window title="Mozilla Bug 654370" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=654370" + target="_blank">Mozilla Bug 654370</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + +var Cu = Components.utils; +var sandbox = new Cu.Sandbox(window); +var script = "(function (obj, type) { return obj instanceof type; })"; +var instanceOf = Cu.evalInSandbox(script, sandbox, "1.8", "Test", 1); +ok(!instanceOf({}, Window), "instanceOf from the sandbox gets the right result"); + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug658560.xul b/js/xpconnect/tests/chrome/test_bug658560.xul new file mode 100644 index 000000000..b53f7c00c --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug658560.xul @@ -0,0 +1,39 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=658560 +--> +<window title="Mozilla Bug 658560" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=658560" + target="_blank">Mozilla Bug 658560</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + SimpleTest.waitForExplicitFinish(); + function go() { + var win = $('ifr').contentWindow.wrappedJSObject; + let o = { prop: true }; + win.foo = o; + + is(win.foo, o, "should have === identity through a CrossOriginWrapper"); + SimpleTest.finish(); + } + + ]]></script> + + <iframe + src="http://example.org/tests/js/xpconnect/tests/mochitest/file_bug658560.html" + id="ifr" + type="content" + onload="go()" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug658909.xul b/js/xpconnect/tests/chrome/test_bug658909.xul new file mode 100644 index 000000000..7a5efb852 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug658909.xul @@ -0,0 +1,92 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=658909 +--> +<window title="Mozilla Bug 658909" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=658909" + target="_blank">Mozilla Bug 658909</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for call/apply-ing Xray methods.**/ + SimpleTest.waitForExplicitFinish(); + + gLoadCount = 0; + function frameLoaded() { + if (++gLoadCount == frames.length) + go(); + } + + function msg(a, b, testName) { + return "(" + a.name + ", " + b.name + "): " + testName; + } + + var testFunctions = { + testDocumentElement: function(a, b, name) { + var getter = Object.prototype.__lookupGetter__.call(a.document, 'documentElement'); + is(getter.call(b.document), b.document.documentElement, msg(a, b, name)); + }, + + testInvalidCall: function(a, b, name) { + var getter = Object.prototype.__lookupGetter__.call(a.document, 'documentElement'); + var threw = false; + try { getter.call(b.document.body); } catch (e) { threw = true; }; + ok(threw, msg(a, b, name)); + }, + + testStatus: function(a, b, name) { + var setter = Object.prototype.__lookupSetter__.call(a, 'status'); + is(b.status, "", "Empty status"); + setter.call(b, "foopy"); + is(b.status, "foopy", msg(a, b, name)); + b.status = ""; + }, + + testCreateElement: function(a, b, name) { + is(a.document.createElement.call(b.document, 'div').ownerDocument, b.document, msg(a, b, name)); + }, + + testWindowName: function(a, b, name) { + var getter = Object.prototype.__lookupGetter__.call(a, 'name'); + is(getter.call(b), b.name, msg(a, b, name)); + }, + + testCanvas: function(a, b, name) { + var canvasA = a.document.createElement('canvas'); + var canvasB = b.document.createElement('canvas'); + var contextA = canvasA.getContext('2d'); + var contextB = canvasB.getContext('2d'); + var getter = Object.prototype.__lookupGetter__.call(contextA, 'canvas'); + is(getter.call(contextB), canvasB, msg(a, b, name)); + } + }; + + function go() { + for (var i = 0; i < frames.length; ++i) + frames[i].name = 'frame' + i; + for (var i = 0; i < frames.length; ++i) { + for (var j = 0; j < frames.length; ++j) { + for (var k in testFunctions) + testFunctions[k](frames[i], frames[j], k); + } + } + + SimpleTest.finish(); + } + + + ]]> + </script> + <iframe id="frame1" onload="frameLoaded();" type="content" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> + <iframe id="frame2" onload="frameLoaded();" type="content" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> + <iframe id="frame3" onload="frameLoaded();" type="content" src="http://example.com/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug664689.xul b/js/xpconnect/tests/chrome/test_bug664689.xul new file mode 100644 index 000000000..355b25eb4 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug664689.xul @@ -0,0 +1,30 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=658560 +--> +<window title="Mozilla Bug 658560" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=658560" + target="_blank">Mozilla Bug 658560</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + const Cu = Components.utils; + var sandbox = new Cu.Sandbox("about:blank"); + var contentObj = Cu.evalInSandbox("({ get foo() { return 42 } })", sandbox); + var propdesc = Object.getOwnPropertyDescriptor(Cu.waiveXrays(contentObj), "foo"); + is(typeof propdesc, "object", "got a property descriptor back"); + ok("get" in propdesc, "getter exists"); + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug679861.xul b/js/xpconnect/tests/chrome/test_bug679861.xul new file mode 100644 index 000000000..e3ccb7aaf --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug679861.xul @@ -0,0 +1,39 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 601803" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=601803" + target="_blank">Mozilla Bug 601803</a> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 601803 **/ + + function go() { + var doc = document.getElementById('ifr').contentDocument; + var list = doc.getElementsByTagName("body"); + var zeroAsString = "0"; + is(typeof list[zeroAsString], "object", + "can lookup nodelist items by string"); + is(typeof list[0], "object", + "can lookup nodelist items by integer after the lookup by string"); + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" src="about:blank" onload="go()" id="ifr" /> + </body> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug706301.xul b/js/xpconnect/tests/chrome/test_bug706301.xul new file mode 100644 index 000000000..e597179ea --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug706301.xul @@ -0,0 +1,52 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=706301 +--> +<window title="Mozilla Bug 706301" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=706301" + target="_blank">Mozilla Bug 706301</a> + <iframe id="ifr" src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_bug706301.html" onload="doTest();" /> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 706301 **/ + + SimpleTest.waitForExplicitFinish(); + + function getLengthInChrome(nodelist) { + + // Make sure the object is Xray wrapped. + ok(nodelist === XPCNativeWrapper(nodelist), "object passed from content to chrome " + + "should be Xray-wrapped."); + + // Perform the operation. + Object.getOwnPropertyDescriptor(nodelist, 'length'); + return nodelist['length'] == 0; + } + + function finishTestInChrome() { + SimpleTest.finish(); + } + + function doTest() { + + // Set up the callbacks for content. + $('ifr').contentWindow.wrappedJSObject.getLengthInChrome = getLengthInChrome; + $('ifr').contentWindow.wrappedJSObject.finishTestInChrome = finishTestInChrome; + $('ifr').contentWindow.wrappedJSObject.ok = ok; + + // Kick off the test. + $('ifr').contentWindow.postMessage({}, '*'); + } + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug720619.xul b/js/xpconnect/tests/chrome/test_bug720619.xul new file mode 100644 index 000000000..28485434e --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug720619.xul @@ -0,0 +1,49 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=720619 +--> +<window title="Mozilla Bug 720619" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=720619" + target="_blank">Mozilla Bug 720619</a> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + /** Test for Bug 720619 **/ + const Cu = Components.utils; + + var obj = { + valueOf: function () { + return 42; + }, + toString: function () { + return 'str'; + } + }; + + var content = new Cu.Sandbox("about:blank"); + content.obj = obj; + + ok(Cu.evalInSandbox("obj + ''", content) == "[object Object]"); + ok(Cu.evalInSandbox("'' + obj", content) == "[object Object]"); + ok(isNaN(Cu.evalInSandbox("obj - 0", content))); + ok(Cu.evalInSandbox("String(obj)", content) == "[object Object]"); + + var chrome = new Cu.Sandbox(window); + chrome.obj = obj; + + ok(Cu.evalInSandbox("obj + ''", chrome) == "42"); + ok(Cu.evalInSandbox("'' + obj", chrome) == "42"); + ok(Cu.evalInSandbox("obj - 0", chrome) == 42); + ok(Cu.evalInSandbox("String(obj)", chrome) == "str"); + ]]></script> + </body> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug726949.xul b/js/xpconnect/tests/chrome/test_bug726949.xul new file mode 100644 index 000000000..3621a8366 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug726949.xul @@ -0,0 +1,41 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=726949 +--> +<window title="Mozilla Bug 726949" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=726949" + target="_blank">Mozilla Bug 726949</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 726949 **/ + var Cu = Components.utils; + var s = new Cu.Sandbox(window, { sandboxPrototype: window } ); + var t; + var desc; + try { + t = Cu.evalInSandbox('top', s); + is(t, window.top, "Should have gotten the right thing back"); + desc = Cu.evalInSandbox('Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), "Cu")', s); + isnot(desc, undefined, + "Should have an own 'Cu' property"); + is(desc.value, Cu, "Should have the right value"); + var loc = Cu.evalInSandbox('location', s); + is(loc.href, location.href, "Should have the right location"); + var display = Cu.evalInSandbox('getComputedStyle(document.documentElement, "").display', s); + is(display, "block", "Should be able to call getComputedStyle"); + } catch (e) { + ok(false, "Should not get an exception: " + e); + } + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug732665.xul b/js/xpconnect/tests/chrome/test_bug732665.xul new file mode 100644 index 000000000..e373c5a0f --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug732665.xul @@ -0,0 +1,81 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=732665 +--> +<window title="Mozilla Bug 732665" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=732665" + target="_blank">Mozilla Bug 732665</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + // + // Important! If this test starts failing after a tricky platform-y change, + // the stack quota numbers in XPCJSContext probably need twiddling. We want + // to maintain the invariants in this test (at least to some approximation) + // for security reasons. + // + + // Executes f() d steps from the probed native stack limit, and returns + // the number of steps to the recursion limit from the caller. + function nearNativeStackLimit(d, f) { + f = f || function() {}; + function inner() { + try { + with ({}) { // keep things predictable -- stay in the interpreter + var stepsFromLimit = eval("inner()"); // Use eval to force a number of native stackframes to be created. + } + if (stepsFromLimit == d) { + try { f(); } catch(e) { ok(false, 'nearNativeStackLimit callback threw: ' + e); } + } + return stepsFromLimit + 1; + } catch(e) { + // It would be nice to check here that the exception is actually an + // over-recursion here. But doing so would require toString()ing the + // exception, which we may not have the stack space to do. + return 0; + } + } + return inner(); + } + + const Cu = Components.utils; + var contentSb = new Cu.Sandbox('http://www.example.com'); + var chromeSb = new Cu.Sandbox(window); + chromeSb.ok = contentSb.ok = ok; + Cu.evalInSandbox(nearNativeStackLimit.toSource(), chromeSb); + Cu.evalInSandbox(nearNativeStackLimit.toSource(), contentSb); + var chromeLimit = Cu.evalInSandbox("nearNativeStackLimit(0);", chromeSb); + var contentLimit = Cu.evalInSandbox("nearNativeStackLimit(0)", contentSb); + ok(chromeLimit >= contentLimit + 10, + "Chrome should be able to have at least 10 heavy frames more stack than content: " + chromeLimit + ", " + contentLimit); + + // Exhaust the stack space in content, and then make sure we can still get 10 + // heavy frames in chrome. + // + // Note that sometimes, if we pass |0| to nearNativeStackLimit, we can end up + // so close to the border in content that we can't even get ourselves together + // enough to make the cross-compartment call. So rather than exhausting the + // stack entirely and then checking for 10 chrome frames, we leave ourselves + // one frame's worth, and check for 11. + // + // If this assertion fails, the current work-around so far is to measure + // again the worst frame size, by using the JS Shell to run + // test_bug732665_meta.js . This script will output numbers to update + // XPCJSContext.cpp comment, as well as the kTrustedScriptBuffer constant. + contentSb.nnslChrome = chromeSb.nearNativeStackLimit; + var nestedLimit = Cu.evalInSandbox("nearNativeStackLimit(1, function() { nestedLimit = nnslChrome(0);}); nestedLimit;", contentSb); + ok(nestedLimit >= 11, "Chrome should be invokable from content script with an exhausted stack: " + nestedLimit); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug732665_meta.js b/js/xpconnect/tests/chrome/test_bug732665_meta.js new file mode 100644 index 000000000..a2afddd98 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug732665_meta.js @@ -0,0 +1,26 @@ +var bottom = stackPointerInfo(); +var top = bottom; + +function nearNativeStackLimit() { + function inner() { + try { + with ({}) { // keep things predictable -- stay in the interpreter + top = stackPointerInfo(); + var stepsFromLimit = eval("inner()"); // Use eval to force a number of native stackframes to be created. + } + return stepsFromLimit + 1; + } catch(e) { + // It would be nice to check here that the exception is actually an + // over-recursion here. But doing so would require toString()ing the + // exception, which we may not have the stack space to do. + return 1; + } + } + return inner(); +} + +var nbFrames = nearNativeStackLimit(); +var frameSize = bottom - top; +print("Max stack size:", frameSize, "bytes", + "\nMaximum number of frames:", nbFrames, + "\nAverage frame size:", Math.ceil(frameSize / nbFrames), "bytes"); diff --git a/js/xpconnect/tests/chrome/test_bug738244.xul b/js/xpconnect/tests/chrome/test_bug738244.xul new file mode 100644 index 000000000..d5f73bb6b --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug738244.xul @@ -0,0 +1,59 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 533596" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + + <iframe src="http://example.org/tests/js/xpconnect/tests/mochitest/file_bug738244.html" + onload="xrayTest(this)"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + SimpleTest.waitForExplicitFinish(); + + function xrayTest(ifr) { + var win = ifr.contentWindow; + var doc = ifr.contentDocument; + + doc.getElementById = 42; + is(doc.getElementById, 42, + "Native property cannot be shadowed on the xray"); + + is(doc.form1.name, "form1", + "Form elements cannot be found by name on the document through xray"); + + is(doc.form1.input1.name, "input1", + "Input element cannot be found by name on a form element through xray"); + + is(typeof doc.form1.appendChild, "function", + "Input element shadows native property with its name through xray"); + + is(win.frame1.name, "frame1", + "IFrames cannot be found by name on the window through xray"); + + is(win[0].name, "frame1", + "IFrames cannot be found by index on the window through xray"); + + win["1000"] = "foopy"; + ok(!("1000" in win), "Shouldn't be able to add indexed expandos to xray"); + + win["1000a"] = "foopy"; + ok("1000a" in win, "Should be able to add named expandos to xray"); + + SimpleTest.finish(); + } + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug743843.xul b/js/xpconnect/tests/chrome/test_bug743843.xul new file mode 100644 index 000000000..df8df320b --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug743843.xul @@ -0,0 +1,39 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=743843 +--> +<window title="Mozilla Bug 743843" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=743843" + target="_blank">Mozilla Bug 743843</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Components.Exception options objects. **/ + + // Note: We pass |window| as the 'data' field here because Components.Exception + // doesn't handle JS Objects here all that nicely. See bug 743121. + + // Test the old interface. + var e1 = Components.Exception('foo', Components.results.NS_BINDING_ABORTED, null, window); + is(e1.result, Components.results.NS_BINDING_ABORTED, "Result should get set properly"); + is(e1.data, window, "User data should get set properly"); + + // Test the options object. + var e2 = Components.Exception('foo', { result: Components.results.NS_BINDING_ABORTED, + data: window, + foobar: 2 }); + is(e2.result, Components.results.NS_BINDING_ABORTED, "Result should get set properly"); + is(e2.data.window, window, "User data should get set properly"); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug760076.xul b/js/xpconnect/tests/chrome/test_bug760076.xul new file mode 100644 index 000000000..a0eb4904c --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug760076.xul @@ -0,0 +1,49 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=760076 +--> +<window title="Mozilla Bug 760076" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=760076" + target="_blank">Mozilla Bug 760076</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for constructing COW-ed functions in content. **/ + + // This gets decompiled and run in the sandbox. + function sandboxCode() { + try { + is(chromeFunction(), 42, "Should call successfully"); + } catch(e) { ok(false, "Shouldn't throw when calling"); } + + try { + ok(typeof (new chromeFunction()) !== 'undefined', + "Should construct successfully"); + } catch(e) { ok(false, "Shouldn't throw when constructing"); } + } + + // Set up the sandbox. + const Cu = Components.utils; + var sb = new Cu.Sandbox('http://www.example.com'); + + // Import the functions it needs. + sb.ok = ok; + sb.is = is; + sb.chromeFunction = function() { ok(true, "Called chrome function"); return 42; } + Cu.evalInSandbox(sandboxCode.toSource(), sb); + + // Do the test. + Cu.evalInSandbox("sandboxCode();", sb); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug760131.html b/js/xpconnect/tests/chrome/test_bug760131.html new file mode 100644 index 000000000..ee02a96eb --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug760131.html @@ -0,0 +1,44 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=760131 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 760131</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=760131">Mozilla Bug 760131</a> +<p id="display"></p> +<div id="content" style="display: none"> + <iframe id="frame"></iframe> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 760131 **/ + +var frame = document.getElementById("frame"); +function runTest() +{ + var win = frame.contentWindow; + win.wrappedJSObject.ok = ok; + var doc = win.document; + var empty = doc.createTouchList(); + var event = doc.createEvent("touchevent"); + event.initTouchEvent("touchstart", true, true, win, 0, false, false, false, false, empty, empty, empty); + doc.getElementById("target").dispatchEvent(event); + + SimpleTest.finish(); +} + +SimpleTest.waitForExplicitFinish(); +frame.onload = runTest; +frame.src = "http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_bug760131.html"; + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_bug763343.xul b/js/xpconnect/tests/chrome/test_bug763343.xul new file mode 100644 index 000000000..1519e1fbe --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug763343.xul @@ -0,0 +1,39 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=763343 +--> +<window title="Mozilla Bug 763343" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=763343" + target="_blank">Mozilla Bug 763343</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for Cross-compartment nsIClassInfo singleton wrapping. **/ + const Cc = Components.classes; + const Ci = Components.interfaces; + const Cu = Components.utils; + + // We need an object here that has singleton classinfo. For now, the console + // service works. + var singleton = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIClassInfo); + ok(singleton.flags & Ci.nsIClassInfo.SINGLETON_CLASSINFO, + "Should have singleton classinfo"); + var sb = new Cu.Sandbox(window); + + // Don't crash. + sb.singleton = singleton; + ok(true, "didn't crash"); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug771429.xul b/js/xpconnect/tests/chrome/test_bug771429.xul new file mode 100644 index 000000000..c6f14ee74 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug771429.xul @@ -0,0 +1,51 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=771429 +--> +<window title="Mozilla Bug 771429" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=771429" + target="_blank">Mozilla Bug 771429</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 771429 **/ + function f() {} + function g() { return this; } + function h() { "use strict"; return this; } + function ctor() { this.x = 1; } + f.x = 2; + f.g = g; + var Cu = Components.utils; + var s = new Cu.Sandbox(window, { sandboxPrototype: window } ); + try { + is(Cu.evalInSandbox('g()', s), window, + "Should get window as this object of non-strict global function"); + is(Cu.evalInSandbox('h()', s), undefined, + "Should get undefined as this object of strict global function"); + is(Cu.evalInSandbox('f.x', s), 2, + "Should have gotten the right thing back"); + is(Cu.evalInSandbox('f.g()', s), f, + "Should have the right function object"); + is(Cu.evalInSandbox('var x = { z: 7 }; g.call(x).z', s), 7, + "Should not rebind calls that are already bound"); + // And test what happens when we use the normal Function.prototype.call + // on g instead of whatever our proxies happen to return. + is(Cu.evalInSandbox('var x = { z: 7 }; Function.prototype.call.call(g, x).z', s), 7, + "Should not rebind calls that are already bound"); + is(Cu.evalInSandbox('new ctor();', s).x, 1, + "Should get a properly constructed object out of the sandbox"); + } catch (e) { + ok(false, "Should not get an exception: " + e); + } + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug773962.xul b/js/xpconnect/tests/chrome/test_bug773962.xul new file mode 100644 index 000000000..76a9b0713 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug773962.xul @@ -0,0 +1,82 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=773962 +--> +<window title="Mozilla Bug 773962" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=773962" + target="_blank">Mozilla Bug 773962</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for remapping Xray waivers during brain transplant. **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + var gFramesLoaded = 0; + function frameLoaded() { + ++gFramesLoaded; + if (gFramesLoaded == 2) + startTest(); + if (gFramesLoaded == 3) + finishTest(); + } + + function startTest() { + // grab the windows and the node. + win1 = document.getElementById('frame1').contentWindow; + win2 = document.getElementById('frame2').contentWindow; + node1 = win1.document.getElementById('text'); + loc1 = win1.location; + + // Grab some Xray waivers. + win1Waiver = win1.wrappedJSObject; + node1Waiver = node1.wrappedJSObject; + loc1Waiver = win1Waiver.location; + + // Adopt node1 into win2. This causes node1 to be transplanted. + win2.document.adoptNode(node1); + + // Navigate win1. This causes win1 to be transplanted. + win1.location = 'http://test2.example.org/tests/js/xpconnect/tests/mochitest/file_empty.html'; + + // The above happens async. Our onload handler will call finishTest() when we're ready. + } + + function finishTest() { + // Now, recompute some wrappers. + Cu.recomputeWrappers(); + + // First, pat ourselves on the back for not asserting/crashing. That's most of + // what we're really testing here. + ok(true, "Didnt crash!"); + + // Now, make sure everything is set up how we expect. + ok(win1Waiver === win1.wrappedJSObject, "waivers still work"); + ok(XPCNativeWrapper(win1Waiver) === win1, "waivers still work"); + ok(node1Waiver === node1.wrappedJSObject, "waivers still work"); + ok(XPCNativeWrapper(node1Waiver) === node1, "waivers still work"); + + // The semantics of location are tricky, because win1 now has a new location object. + // In fact, loc1 should be a dead object proxy. Let's make sure we get this right. + ok(loc1 !== win1.location, "navigation means different window.location"); + ok(loc1Waiver !== win1.location.wrappedJSObject, "navigation means different window.location"); + + // Whew. + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="frame1" onload="frameLoaded();" type="content" src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> + <iframe id="frame2" onload="frameLoaded();" type="content" src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug792280.xul b/js/xpconnect/tests/chrome/test_bug792280.xul new file mode 100644 index 000000000..bbc420aa2 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug792280.xul @@ -0,0 +1,45 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=792280 +--> +<window title="Mozilla Bug 792280" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=792280" + target="_blank">Mozilla Bug 792280</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 792280 **/ + const Cu = Components.utils; + + function checkSb(sb, expect) { + var target = new Cu.Sandbox('http://www.example.com'); + Cu.evalInSandbox('function fun() { return arguments.callee.caller; };', target); + sb.fun = target.fun; + let allowed = false; + try { + allowed = Cu.evalInSandbox('function doTest() { return fun() == doTest; }; doTest()', sb); + isnot(expect, "throw", "Should have thrown"); + } catch (e) { + is(expect, "throw", "Should expect exception"); + ok(/denied|insecure/.test(e), "Should be a security exception: " + e); + } + is(allowed, expect == "allow", "should censor appropriately"); + } + + // Note that COWs are callable, but XOWs are not. + checkSb(new Cu.Sandbox('http://www.example.com'), "allow"); + checkSb(new Cu.Sandbox('http://www.example.org'), "throw"); + checkSb(new Cu.Sandbox(window), "censor"); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug793433.xul b/js/xpconnect/tests/chrome/test_bug793433.xul new file mode 100644 index 000000000..f77c12aa1 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug793433.xul @@ -0,0 +1,48 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=793433 +--> +<window title="Mozilla Bug 793433" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=793433" + target="_blank">Mozilla Bug 793433</a> + <p id="display"></p> + <div id="content" style="display: none"/> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + +var Cc = Components.classes; +var Ci = Components.interfaces; + +function shouldThrow(fun, args, msg) { + try { + fun.apply(this, args); + ok(false, msg); + } catch (e) { + ok(true, msg+" -- "+e); + } +} + +function do_registerTopLevelWindow(win) { + Cc['@mozilla.org/appshell/appShellService;1']. + getService(Ci.nsIAppShellService).registerTopLevelWindow(win); +} + +shouldThrow( + do_registerTopLevelWindow, [null], + "registering null as a top-level window should throw"); + +shouldThrow( + do_registerTopLevelWindow, [{}], + "registering a void object as a top-level window should throw"); + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug795275.xul b/js/xpconnect/tests/chrome/test_bug795275.xul new file mode 100644 index 000000000..875743fd9 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug795275.xul @@ -0,0 +1,88 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=795275 +--> +<window title="Mozilla Bug 795275" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=795275" + target="_blank">Mozilla Bug 795275</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Warning in content scopes about Components. **/ + + SimpleTest.waitForExplicitFinish(); + SimpleTest.executeSoon(startLoad); + function startLoad() { + for (var i = 1; i <= document.getElementsByTagName('iframe').length; ++i) { + var frame = document.getElementById('frame' + i); + frame.contentWindow.location = 'http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_bug795275.html'; + frame.onload = frameLoaded; + } + } + + // Set up our console listener. + var gWarnings = 0; + function onWarning(consoleMessage) { + if (/soon be removed/.test(consoleMessage.message)) + gWarnings++; + } + var gListener = { + observe: onWarning, + QueryInterface: function (iid) { + if (!iid.equals(Components.interfaces.nsIConsoleListener) && + !iid.equals(Components.interfaces.nsISupports)) { + throw Components.results.NS_ERROR_NO_INTERFACE; + } + return this; + } + }; + var gConsoleService = Components.classes["@mozilla.org/consoleservice;1"] + .getService(Components.interfaces.nsIConsoleService); + gConsoleService.registerListener(gListener); + + // Wait for all four child frame to load. + var gLoadCount = 0; + function frameLoaded() { + if (++gLoadCount == document.getElementsByTagName('iframe').length) + go(); + } + + function getWin(id) { return document.getElementById(id).contentWindow.wrappedJSObject; } + function go() { + getWin('frame1').touchComponents(); + getWin('frame2').touchInterfaces(); + getWin('frame4').touchComponents(); + getWin('frame4').touchInterfaces(); + // This shouldn't warn. + getWin('frame5').touchViaXBL(); + + // Warnings are dispatched async, so stick ourselves at the end of the event + // queue. + setTimeout(done, 0); + } + + function done() { + gConsoleService.unregisterListener(gListener); + is(gWarnings, 3, "Got the right number of warnings"); + SimpleTest.finish(); + } + + ]]> + + </script> + <iframe id="frame1"/> + <iframe id="frame2"/> + <iframe id="frame3"/> + <iframe id="frame4"/> + <iframe id="frame5"/> + +</window> diff --git a/js/xpconnect/tests/chrome/test_bug799348.xul b/js/xpconnect/tests/chrome/test_bug799348.xul new file mode 100644 index 000000000..77f577c9b --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug799348.xul @@ -0,0 +1,50 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=799348 +--> +<window title="Mozilla Bug 799348" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=799348" + target="_blank">Mozilla Bug 799348</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 799348 **/ + SimpleTest.waitForExplicitFinish(); + Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + Components.utils.import("resource://gre/modules/Services.jsm"); + gCalledOnload = false; + var myObserver = { + QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]), + observe: function(win, topic, data) { + if (topic == "domwindowopened") { + ok(!gCalledOnload, "domwindowopened notification fired before onload"); + win.addEventListener("load", function(evt) { + gCalledOnload = true; + win.close(); + }, false); + } else if (topic == "domwindowclosed") { + ok(gCalledOnload, "should have called onload"); + Services.ww.unregisterNotification(myObserver); + SimpleTest.finish(); + } + else { + ok(false, "unknown topic"); + } + } + }; + Services.ww.registerNotification(myObserver); + + + ]]> + </script> + <iframe id="frame" type="content" src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_bug799348.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug801241.xul b/js/xpconnect/tests/chrome/test_bug801241.xul new file mode 100644 index 000000000..5c0dbd82e --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug801241.xul @@ -0,0 +1,46 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=801241 +--> +<window title="Mozilla Bug 801241" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=801241" + target="_blank">Mozilla Bug 801241</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 801241 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + // This is decompiled and run inside the sandbox; + function sbCode() { + try { + win.location = win.location; + ok(true, "Didn't throw setting from location"); + } catch (e) { + ok(false, "Threw setting location from sandbox"); + } + } + + function go() { + document.getElementById('ifr').onload = null; + var sb = new Cu.Sandbox(this); + sb.win = document.getElementById('ifr').contentWindow; + sb.ok = ok; + Cu.evalInSandbox('(' + sbCode.toSource() + ')()', sb); + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" onload="go();" type="content" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug812415.xul b/js/xpconnect/tests/chrome/test_bug812415.xul new file mode 100644 index 000000000..985413b6f --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug812415.xul @@ -0,0 +1,91 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=812415 +--> +<window title="Mozilla Bug 812415" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=812415" + target="_blank">Mozilla Bug 812415</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 812415 and Bug 823348 **/ + + const Cu = Components.utils; + SimpleTest.waitForExplicitFinish(); + + function testWaiving(iwin, sb) { + sb.win = iwin; + is(Cu.evalInSandbox('win', sb), iwin, "Basic identity works"); + is(Cu.evalInSandbox('win.wrappedJSObject.expando', sb), 42, "Waivers work via .wrappedJSObject"); + is(Cu.evalInSandbox('XPCNativeWrapper.unwrap(win).expando', sb), 42, "Waivers work via XPCNativeWrapper.unwrap"); + is(Cu.evalInSandbox('win.wrappedJSObject.document.defaultView.expando', sb), 42, "Waivers are deep"); + } + + function checkThrows(expression, sb, msg) { + var result = Cu.evalInSandbox('(function() { try { ' + expression + '; return "allowed"; } catch (e) { return e.toString(); }})();', sb); + ok(!!/denied/.exec(result), msg); + } + + function testAsymmetric(regular, expanded) { + + // Set up objects. + expanded.regFun = Cu.evalInSandbox('function reg() { return 42; }; reg', regular); + expanded.regObj = Cu.evalInSandbox('new Object({foo: 2})', regular); + regular.expFun = Cu.evalInSandbox('function exp() { return 41; }; exp', expanded); + regular.expObj = Cu.evalInSandbox('new Object({bar: 3})', expanded); + + // Check objects. + is(Cu.evalInSandbox('regObj.foo', expanded), 2, "Expanded can see regular object prop"); + checkThrows('expObj.bar', regular, "Regular shouldn't read properties"); + Cu.evalInSandbox('regObj.foo = 20', expanded); + is(expanded.regObj.foo, 20, "Expanded can set properties"); + checkThrows('expFun.bar = 0', regular, "Regular shouldn't write properties"); + + // Check functions. + is(Cu.evalInSandbox('regFun()', expanded), 42, "Expanded can call regular function"); + checkThrows('expFun()', regular, "Regular cannot call expanded function"); + is(Cu.evalInSandbox('regFun.name', expanded), 'reg', "Expanded can see regular function's name"); + checkThrows('expFun.name', regular, "Regular can't see expanded function's name"); + Cu.evalInSandbox('regFun.expando = 30', expanded); + is(Cu.evalInSandbox('regFun.expando', expanded), 30, "Expanded can set expandos"); + checkThrows('expFun.expando = 29', regular, "Regular can't set expandos"); + + // Check __proto__ stuff. + is(Cu.evalInSandbox('regFun.__proto__', expanded), regular.Function.prototype, "expanded can get __proto__"); + checkThrows('expFun.__proto__', regular, "regular can't use __proto__"); + checkThrows('expFun.__proto__ = {}', regular, "regular can't mutate __proto__"); + } + + function go() { + var iwin = document.getElementById('ifr').contentWindow; + iwin.wrappedJSObject.expando = 42; + + // Make our sandboxes. We pass wantXrays=false for the nsEP to ensure that + // the Xrays we get are the result of being an nsEP, not from the wantXrays + // flag. + var regular = new Components.utils.Sandbox(iwin); + var expanded = new Components.utils.Sandbox([iwin], {wantXrays: false}); + + // Because of the crazy secret life of wantXrays, passing wantXrays=false + // has the side effect of waiving Xrays on the returned sandbox. Undo that. + expanded = XPCNativeWrapper(expanded); + + testWaiving(iwin, regular); + testWaiving(iwin, expanded); + testAsymmetric(regular, expanded); + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug853283.xul b/js/xpconnect/tests/chrome/test_bug853283.xul new file mode 100644 index 000000000..ac59ad9a7 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug853283.xul @@ -0,0 +1,41 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=853283 +--> +<window title="Mozilla Bug 853283" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=853283" + target="_blank">Mozilla Bug 853283</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test nsNavigatorSH::Resolve in conjunction with Xrays.**/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + function go() { + // This chrome document already has Xrays to the content scope, but we use a + // a sandbox anyway to make sure that the global in play here isn't an + // nsIDOMWindow. Otherwise, the resolve hook might just end up squeaking by + // with the chrome window. + var iwin = $('ifr').contentWindow; + var sb = new Cu.Sandbox(window); + sb.iwin = iwin; + sb.ok = ok; + Cu.evalInSandbox('try {iwin.navigator.mozContacts; ok(true, "Didnt throw"); } catch (e) { ok(false, "Threw: " + e);}', sb); + SimpleTest.finish(); + } + + + ]]> + </script> + <iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug853571.xul b/js/xpconnect/tests/chrome/test_bug853571.xul new file mode 100644 index 000000000..e6d105e46 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug853571.xul @@ -0,0 +1,64 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=853571 +--> +<window title="Mozilla Bug 853571" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=853571" + target="_blank">Mozilla Bug 853571</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 853571 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + function mainTest() { + var iwin = $('ifr').contentWindow; + + // Test with a simple sandbox with no prototype. + checkSource(iwin, new Cu.Sandbox(iwin), null, "should get null source with no sandboxPrototype"); + yield; + + // Test with a sandboxPrototype. + checkSource(iwin, new Cu.Sandbox(iwin, { sandboxPrototype: iwin }), iwin, "should be able to impersonate the prototype"); + yield; + + SimpleTest.finish(); + yield; // Prevent StopIteration from being thrown. + } + + var gen; + function runTest() { + gen = mainTest(); + gen.next(); + } + + function checkSource(target, sb, expectedSource, message) { + target.addEventListener("message", function listener(event) { + target.removeEventListener("message", listener); + is(event.source, expectedSource, message); + try { + gen.next(); + } catch (e if e instanceof StopIteration) { + // We're done. + } + }); + + sb.target = target; + Cu.evalInSandbox("target.postMessage('foo', '*');", sb); + } + + + ]]> + </script> + <iframe id="ifr" type="content" onload="runTest()" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug858101.xul b/js/xpconnect/tests/chrome/test_bug858101.xul new file mode 100644 index 000000000..fc1dde056 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug858101.xul @@ -0,0 +1,55 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=858101 +--> +<window title="Mozilla Bug 858101" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=858101" + target="_blank">Mozilla Bug 858101</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for [[DefaultValue]] on XrayWrappers. **/ + SimpleTest.waitForExplicitFinish(); + + function muckWithToString() { + function tricky() { return "hah"; }; + + window.toString = document.toString = document.body.toString = tricky; + window.valueOf = document.valueOf = document.body.valueOf = tricky; + + Window.prototype.toString = Window.prototype.valueOf = tricky; + Document.prototype.toString = Document.prototype.valueOf = tricky; + HTMLBodyElement.toString = HTMLBodyElement.valueOf = tricky; + } + + function go() { + var iwin = $('ifr').contentWindow; + iwin.wrappedJSObject.eval('(' + muckWithToString.toSource() + ')()'); + + // Check behavior with vanilla CCWs. + ok(!!/hah/.exec(iwin.wrappedJSObject + ""), "Waivers should get content-defined window stringification"); + ok(!!/hah/.exec(iwin.document.wrappedJSObject + ""), "Waivers should get content-defined document stringification"); + ok(!!/hah/.exec(iwin.document.body.wrappedJSObject + ""), "Waivers should get content-defined body stringification"); + + // Check Xray behavior. + ok(!/hah/.exec(iwin + ""), "Xrays should not get content-defined window stringification"); + ok(!/hah/.exec(iwin.document + ""), "Xrays should not get content-defined document stringification"); + ok(!/hah/.exec(iwin.document.body + ""), "Xrays should not get content-defined body stringification"); + + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" onload="go();" type="content" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug860494.xul b/js/xpconnect/tests/chrome/test_bug860494.xul new file mode 100644 index 000000000..3b74b59d6 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug860494.xul @@ -0,0 +1,57 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=860494 +--> +<window title="Mozilla Bug 860494" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=860494" + target="_blank">Mozilla Bug 860494</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 860494 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + function go() { + var iwin = $('ifr').contentWindow; + // NB: mochitest-chrome actually runs the test as a content docshell. + is(iwin.top, window.top, "iframe names shouldn't shadow |top| via Xray"); + is(iwin.parent, window, "iframe names shouldn't shadow |parent| via Xray"); + ok(!!/http/.exec(iwin.location), "iframe names shouldn't shadow |location| via Xray"); + is(iwin.length, 7, "iframe names shouldn't shadow |length| via Xray"); + is(iwin.window, iwin, "iframe names shouldn't shadow |window| via Xray"); + is(iwin.navigator, XPCNativeWrapper(iwin.wrappedJSObject.navigator), + "iframe names shouldn't shadow |navigator| via Xray"); + ok(iwin.alert instanceof Function, + "iframe names shouldn't shadow |alert| via Xray"); + + // Now test XOWs. + var sb = new Cu.Sandbox('http://www.example.com'); + sb.win = iwin; + sb.topWin = top; + sb.parentWin = window; + sb.is = is; + sb.ok = ok; + Cu.evalInSandbox('ok(win.top === topWin, "iframe names shouldnt shadow |top| via cross-origin Xray");', sb); + Cu.evalInSandbox('ok(win.parent === parentWin, "iframe names shouldnt shadow |parent| via cross-origin Xray");', sb); + Cu.evalInSandbox('is(win.length, 7, "iframe names shouldnt shadow |length| via cross-origin Xray");', sb); + Cu.evalInSandbox('ok(win.window === win, "iframe names shouldnt shadow |window| via cross-origin Xray");', sb); + Cu.evalInSandbox('var exn = "nothrow"; try { win.navigator; } catch (e) { exn = e; } ok(!!/denied/.exec(exn), "cross-origin Xray blocks subframes that shadow: navigator: " + exn);', sb); + Cu.evalInSandbox('var exn = "nothrow"; try { win.alert; } catch (e) { exn = e; } ok(!!/denied/.exec(exn), "cross-origin Xray blocks subframes that shadow: alert: " + exn);', sb); + + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" type="content" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_bug860494.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug865948.xul b/js/xpconnect/tests/chrome/test_bug865948.xul new file mode 100644 index 000000000..c3ec0e473 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug865948.xul @@ -0,0 +1,36 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=865948 +--> +<window title="Mozilla Bug 865948" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=865948" + target="_blank">Mozilla Bug 865948</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for Bug 865948 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + function go() { + $('ifr').onload = null; + var sb = Cu.Sandbox(['http://example.com', 'http://example.org']); + sb.iwin = $('ifr').contentWindow; + sb.ok = ok; + Cu.evalInSandbox('try { iwin.location = "about:"; ok(false, "didnt throw"); } catch (e) { ok(!!/denied/.exec(e), "threw: " + e); }', sb); + SimpleTest.finish(); + } + + ]]> + </script> +<iframe id="ifr" type="content" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug866823.xul b/js/xpconnect/tests/chrome/test_bug866823.xul new file mode 100644 index 000000000..b2d7455fd --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug866823.xul @@ -0,0 +1,50 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=866823 +--> +<window title="Mozilla Bug 866823" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=866823" + target="_blank">Mozilla Bug 866823</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 866823 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + function go() { + var iwin = $('ifr').contentWindow; + + // Make sure that Xray waivers can't be transitively extended onto objects + // for whom the extender may not waive. + var sb = new Cu.Sandbox(iwin, { wantXrays: true }); + sb.iwin = iwin; + ok(Cu.evalInSandbox('iwin.wrappedJSObject.top == iwin.top', sb), "Waiver does not propagate"); + Cu.evalInSandbox('iwin.wrappedJSObject.waiver = iwin.wrappedJSObject', sb); + ok(iwin.wrappedJSObject.eval('waiver == window'), "Waivers disappear same-compartment"); + + // Make sure that standard prototypes don't get COWs. + sb.objProto = Object.prototype; + try { + sb.eval('objProto.toString;', sb); + ok(false, "Should have thrown"); + } catch (e) { + ok(/denied|insecure/, "No silent failure when accessing properties on forbidden prototype"); + } + + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" onload="go();" type="content" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug895340.xul b/js/xpconnect/tests/chrome/test_bug895340.xul new file mode 100644 index 000000000..370aa6ec6 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug895340.xul @@ -0,0 +1,64 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=895340 +--> +<window title="Mozilla Bug 895340" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=895340 " + target="_blank">Mozilla Bug 895340 </a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + SimpleTest.waitForExplicitFinish(); + SimpleTest.expectUncaughtException(); + + const Cu = Components.utils; + Cu.import("resource://gre/modules/Services.jsm", this); + + var finished = false; + + var console = Components.classes["@mozilla.org/consoleservice;1"] + .getService(Components.interfaces.nsIConsoleService); + + let listener = { + QueryInterface: function(iid) { + if (!iid.equals(Components.interfaces.nsIConsoleListener) && + !iid.equals(Components.interfaces.nsISupports)) + { + throw Components.results.NS_ERROR_NO_INTERFACE; + } + return this; + } + }; + + listener.observe = function(aMessage) { + if (aMessage.message.indexOf("Will you report me?") != -1 && !finished) { + finished = true; + ok(true, "exception reported"); + console.unregisterListener(listener); + SimpleTest.finish(); + } + }; + + console.registerListener(listener); + + /* Throw an exception and verify that it gets reported. */ + let foo_obs = function() { + throw new Error("Will you report me?"); + }; + + Services.obs.addObserver(foo_obs, "foo", false); + Services.obs.notifyObservers(null, "foo", "foo"); + Services.obs.removeObserver(foo_obs, "foo"); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug932906.xul b/js/xpconnect/tests/chrome/test_bug932906.xul new file mode 100644 index 000000000..29dce2392 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug932906.xul @@ -0,0 +1,72 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=932906 +--> +<window title="Mozilla Bug 932906" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=932906" + target="_blank">Mozilla Bug 932906</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + const Cu = Components.utils; + Cu.import('resource://gre/modules/Services.jsm'); + + /** Test for Bug 932906 **/ + SimpleTest.waitForExplicitFinish(); + + function passToContent(shouldThrow) { + try { + $('ifr').contentWindow.obs = Services.obs; + ok(!shouldThrow, "Didn't throw when passing non-DOM XPCWN to content"); + } catch (e) { + ok(shouldThrow, "Threw when passing non-DOM XPCWN to content"); + ok(/denied/.test(e), "Threw correct exception: " + e); + } + } + + var gLoadCount = 0; + function loaded() { + ++gLoadCount; + if (gLoadCount == 1) + part1(); + else if (gLoadCount == 2) + part2(); + else + ok(false, "Didn't expect three loads"); + } + + function part1() { + + // Make sure that the pref is what we expect for mochitests. + is(Services.prefs.getBoolPref('dom.use_xbl_scopes_for_remote_xul'), true, + "Test harness set up like we expect"); + + + // First, test that we can't normally pass non-DOM XPCWNs to content. + passToContent(/* shouldThrow = */ true); + + // Now, make sure we _can_ for the remote xul case. We use SpecialPowers + // for the pref munging because it cleans up after us. + SpecialPowers.pushPrefEnv({set: [['dom.use_xbl_scopes_for_remote_xul', false]]}, function() { + $('ifr').contentWindow.location.reload(); + }); + } + + function part2() { + passToContent(/* shouldThrow = */ false); + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" onload="loaded();" type="content" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_bug996069.xul b/js/xpconnect/tests/chrome/test_bug996069.xul new file mode 100644 index 000000000..f61003bb1 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_bug996069.xul @@ -0,0 +1,53 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=996069 +--> +<window title="Mozilla Bug 996069" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=996069" + target="_blank">Mozilla Bug 996069</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + const Cu = Components.utils; + /** Test for Bug 996069 **/ + SimpleTest.waitForExplicitFinish(); + + function loaded() { + var ifr = document.getElementById("ifr").contentWindow; + var sb = new Cu.Sandbox([ifr], + { sandboxPrototype: ifr }); + + ifr.wrappedJSObject.finishTest = function() { + // If we got here we did not hit the NS_ReleaseAssert... + ok(true, "nsExpandedPrincipal should not be inherited by content windows"); + + // But let's be sure that the new window does not have nsEP + newWin.wrappedJSObject.obj = Cu.evalInSandbox("var obj = { foo: 'bar' }; obj", sb); + try { + newWin.eval("obj.foo"); + ok(false, "newWin should not have access to object from a scope with nsExpandedPrincipal"); + } catch (e) { + ok(/Permission denied/.exec(e.message), "newWin should not have access to object from a scope with nsExpandedPrincipal"); + } + newWin.close(); + SimpleTest.finish(); + }; + + var newWin = Cu.evalInSandbox( + "window.open('http://example.org/chrome/js/xpconnect/tests/chrome/file_bug996069.html');", + sb); + } + + ]]> + </script> + <iframe id="ifr" onload="loaded();" type="content" src="http://example.org/chrome/js/xpconnect/tests/chrome/file_bug996069.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_chrometoSource.xul b/js/xpconnect/tests/chrome/test_chrometoSource.xul new file mode 100644 index 000000000..8d3933c0c --- /dev/null +++ b/js/xpconnect/tests/chrome/test_chrometoSource.xul @@ -0,0 +1,62 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<window title="Mozilla Bug 761723" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=761723" target="_blank">Mozilla Bug 761723</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript" src="outoflinexulscript.js"></script> + <script type="application/javascript"><![CDATA[ +var Cu = Components.utils; +var Cc = Components.classes; +var Ci = Components.interfaces; +Cu.import("resource://gre/modules/NetUtil.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +function inlinefunction() { + return 42; +} + +var src; +src = inlinefunction.toSource(); +isnot(src.indexOf("return 42"), -1, "inline XUL script should have source"); +is(src.charAt(src.length - 1), "}", "inline XUL source should end with '}'"); +src = outoflinefunction.toSource(); +isnot(src.indexOf("return 42"), -1, "out of line XUL script should have source") +is(src.charAt(src.length - 1), "}", "out of line XUL source should end with '}'"); +src = NetUtil.asyncFetch.toSource(); +isnot(src.indexOf("return"), -1, "JSM should have source"); +var ns = {}; +Services.scriptloader.loadSubScript("resource://gre/modules/NetUtil.jsm", ns); +src = ns.NetUtil.asyncFetch.toSource(); +isnot(src.indexOf("return"), -1, "subscript should have source"); + +var base = /.*\//.exec(window.location.href)[0]; +var reg = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIChromeRegistry); +var resolvedBase = reg.convertChromeURL(NetUtil.newURI(base)).spec; + +ns = {}; +Services.scriptloader.loadSubScript(resolvedBase + "subscript.js", ns); +src = ns.NetUtil.asyncFetch.toSource(); +isnot(src.indexOf("return"), -1, "subscript of a subscript should have source"); + +ns = {}; +Services.scriptloader.loadSubScript(resolvedBase + "utf8_subscript.js", ns, "UTF-8"); +src = ns.f.toSource(); +isnot(src.indexOf("return 42;"), -1, "encoded subscript should have correct source"); + +ns = {}; +Services.scriptloader.loadSubScriptWithOptions(resolvedBase + "utf8_subscript.js", + {target: ns, charset: "UTF-8", ignoreCache: true}); +src = ns.f.toSource(); +isnot(src.indexOf("return 42;"), -1, "encoded subscript should have correct source"); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_cloneInto.xul b/js/xpconnect/tests/chrome/test_cloneInto.xul new file mode 100644 index 000000000..db4c61b0f --- /dev/null +++ b/js/xpconnect/tests/chrome/test_cloneInto.xul @@ -0,0 +1,198 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<window title="Mozilla Bug 503926" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=964293" + target="_blank">Cu.cloneInto()</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + const Cu = Components.utils; + const Ci = Components.interfaces; + + const TypedArrayThings = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + ]; + + function checkThrows(f, msg, rgxp) { + try { + f(); + ok(false, "Should have thrown: " + msg); + } catch (e) { + ok(true, "Threw correctly - " + msg + " - " + e); + if (rgxp) + ok(rgxp.test(e), "Should throw correct exception: " + e); + } + } + + function getType(a) { + if (a === null || a === undefined) + return 'null'; + + if (Array.isArray(a)) + return 'array'; + + if (a instanceof File) + return 'file'; + + if (a instanceof Ci.nsIDOMBlob) + return 'blob'; + + if (TypedArrayThings.indexOf(a.constructor.name) !== -1) + return a.constructor.name; + + if (typeof a == 'object') + return 'object'; + + if (typeof a == 'function') + return 'function'; + + return 'primitive'; + } + + function compare(a, b) { + is (getType(a), getType(b), 'Type matches'); + + var type = getType(a); + if (type == 'array') { + is (a.length, b.length, 'Array.length matches'); + for (var i = 0; i < a.length; ++i) { + compare(a[i], b[i]); + } + + return; + } + + if (type == 'file' || type == 'blob') { + ok ( a === b, 'They should match'); + return; + } + + if (type == 'object') { + ok ( a !== b, 'They should not match'); + + var aProps = []; + for (var p in a) aProps.push(p); + + var bProps = []; + for (var p in b) bProps.push(p); + + is (aProps.length, bProps.length, 'Props match'); + is (aProps.sort().toSource(), bProps.sort().toSource(), 'Props match - using toSource()'); + + for (var p in a) { + compare(a[p], b[p]); + } + + return; + } + + if (type == 'function') { + ok ( a !== b, 'They should not match'); + return; + } + + if (type != 'null') { + is (a.toSource(), b.toSource(), 'Matching using toSource()'); + } + } + + var sandboxOptions = { + wantXrays: true, + wantExportHelpers: true, + }; + var sandbox = new Cu.Sandbox(window, sandboxOptions); + // The second sandbox is for testing the exportHelper version of the cloneInto + var sandbox2 = new Cu.Sandbox("http://example.com", sandboxOptions); + sandbox.sandbox2 = sandbox2; + sandbox2.sandbox = sandbox; + + function cloneAndTest(test) { + var output = sandbox.test = Cu.cloneInto(test, sandbox); + compare(test, output); + + output = Cu.evalInSandbox('cloneInto(test, sandbox2)', sandbox); + compare(test, output); + } + + function cloneAndTestWithFunctions(test) { + var output = sandbox.test = Cu.cloneInto(test, sandbox, { cloneFunctions: true }); + compare(test, output); + + output = Cu.evalInSandbox('cloneInto(test, sandbox2, { cloneFunctions: true })', sandbox); + // Note - We need to waive here, because functions are filtered out by object Xrays. + compare(test, Cu.waiveXrays(output)); + } + + var tests = [ + 1, + null, + true, + 'hello world', + [1, 2, 3], + { a: 1, b: 2 }, + new Date(), + { a: 1, b: {}, c: [1, 2, 3, {} ], e: 'hello world' }, + ]; + + for (var i = 0; i < tests.length; ++i) { + cloneAndTest(tests[i]); + } + + checkThrows(function() { Cu.cloneInto({ a: function() {} }, sandbox); }, + 'Function should not be cloned by default'); + + checkThrows(function() { Cu.cloneInto({ a: document }, sandbox); }, + 'Reflectors should not be wrapped by default'); + + var withReflectors = Cu.cloneInto({ doc: document, win: window }, sandbox, + { wrapReflectors: true }); + is(Cu.unwaiveXrays(Cu.waiveXrays(withReflectors).doc), document, "Document passes"); + is(Cu.unwaiveXrays(Cu.waiveXrays(withReflectors).win), window, "Window passes"); + + + checkThrows(function() { Cu.evalInSandbox('cloneInto({}, sandbox)', sandbox2); }, + 'CloneInto should only work on less privileged target scopes.', + /denied|insecure/); + + var cloneTarget = new Cu.Sandbox('http://example.com'); + var sameOriginSB = new Cu.Sandbox('http://example.com', { wantGlobalProperties: ['XMLHttpRequest'] }); + var crossOriginSB = new Cu.Sandbox('http://example.net', { wantGlobalProperties: ['XMLHttpRequest'] }); + sandbox2.cloneTarget = cloneTarget; + sandbox2.soXHR = Cu.evalInSandbox('new XMLHttpRequest()', sameOriginSB); + sandbox2.xoXHR = Cu.evalInSandbox('new XMLHttpRequest()', crossOriginSB); + sandbox2.chromeDoc = document; + Cu.evalInSandbox('function tryToClone(x) { return cloneInto({val: x}, cloneTarget, { wrapReflectors: true }).val; }', sandbox2); + is(Cu.evalInSandbox('tryToClone(soXHR)', sandbox2), sandbox2.soXHR, 'Same-origin wrapReflectors works'); + checkThrows(function() { Cu.evalInSandbox('tryToClone(chromeDoc)', sandbox2); }, + 'wrapReflectors may not wrap cross-origin reflectors', /unsupported value type/); + + + var test = { a: function() { return 42; } }; + cloneAndTestWithFunctions(test); + + // Check that inputs are properly passed through cloned functions: + test = { a: function(obj) { return obj; } }; + var clonedTest = Cu.cloneInto(test, sandbox, {cloneFunctions: true}); + var testInput = {}; + is(clonedTest.a(testInput), testInput, "Objects should be identical"); + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_cows.xul b/js/xpconnect/tests/chrome/test_cows.xul new file mode 100644 index 000000000..75c5250dd --- /dev/null +++ b/js/xpconnect/tests/chrome/test_cows.xul @@ -0,0 +1,266 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 522764" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=522764 " + target="_blank">Mozilla Bug 522764 </a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ +var Ci = Components.interfaces; +var Cu = Components.utils; + +var sandbox = new Cu.Sandbox("about:blank"); + +var test_utils = window.QueryInterface(Ci.nsIInterfaceRequestor). + getInterface(Ci.nsIDOMWindowUtils); + +function getCOW(x) { + if (typeof x != 'object' && typeof x != 'function') + return x; + x = Cu.waiveXrays(x); + var rval = {}; + if (typeof x == "function") + rval = eval(uneval(x)); + for (var i in x) { + if (x.__lookupGetter__(i)) + rval.__defineGetter__(i, eval(uneval(x.__lookupGetter__(i)))) + else + rval[i] = getCOW(x[i]); + } + return rval; +} + +// Give the sandbox a way to create ChromeObjectWrapped objects. +sandbox.getCOW = getCOW; + +// Define test API functions in the sandbox. +const TEST_API = ['is', 'isnot', 'ok', 'todo_is', 'todo_isnot', 'todo']; +TEST_API.forEach(function(name) { sandbox[name] = window[name]; }); + +sandbox.alienObject = { + __exposedProps__: {funProp: 'r'}, + funProp: function foo(x) { + return x + 1; + } +}; + +sandbox.chromeGet = function (obj, prop) { return obj[prop]; }; + +function COWTests() { + function getNames(cow) { + let names = []; + for (let name in cow) { + names.push(name); + } + return names; + } + + // This function is actually decompiled and run inside a + // sandbox with content privileges. + + // TODO: This could use some refactoring; creating helper + // functions like assertIsWritable(myObj, 'someproperty') might + // be useful. + + function isProp(obj, propName, value, desc) { + try { + is(obj[propName], value, "getting " + propName + " on " + desc); + ok(propName in obj, + propName + " on " + desc + " should exist"); + ok(Object.hasOwnProperty.call(obj, propName), + propName + " on " + desc + " should exist"); + } catch (e) { + ok(false, "getting " + propName + " on " + desc + " threw " + e); + } + } + function isPropHidden(obj, propName, desc) { + try { + is(obj[propName], undefined, + "getting " + propName + " on " + desc + " should return undefined"); + ok(!(propName in obj), + propName + " on " + desc + " should act as if it doesn't exist"); + ok(!Object.hasOwnProperty.call(obj, propName), + propName + " on " + desc + " should act as if it doesn't exist"); + } catch (e) { + ok(false, "getting " + propName + " on " + desc + " threw " + e); + } + } + + const PROPS_TO_TEST = ['foo', 'bar', 'prototype']; + + var empty = {}; + var nonempty = {foo: 42, bar: 33}; + is(getCOW(empty).foo, undefined, + "shouldn't throw when accessing exposed properties that doesn't exist"); + + PROPS_TO_TEST.forEach(function(name) { + isPropHidden(getCOW(nonempty), name, "object without exposedProps"); + }); + + // Test function objects. + var func = function(x) { return 42; }; + func.__exposedProps__ = { foo: "r" }; + func.foo = "foo property"; + var funcCOW = getCOW(func); + try { + funcCOW.foo; + ok(false, 'Functions are no longer COWable'); + } catch (e) { + ok(/denied|insecure/.test(e), 'Functions are no longer COWable'); + } + is(funcCOW(), 42, "Chrome functions should be callable"); + + // Test object with empty exposedProps + var strict = { __exposedProps__: {}, foo: "foo property" }; + var strictCOW = getCOW(strict); + PROPS_TO_TEST.forEach(function(name) { + isPropHidden(strictCOW, name, "object with empty exposedProps"); + }); + is(getNames(strictCOW).length, 0, + "object with empty exposedProps shouldn't have any properties"); + + // Test object with one exposed property + var strict = { __exposedProps__: { foo: "r" }, foo: "foo property" }; + var strictCOWr = getCOW(strict); + PROPS_TO_TEST.forEach(function(name) { + if (name == "foo") { + isProp(strictCOWr, name, "foo property", + "object with exposed 'foo'"); + } + else { + isPropHidden(strictCOW, name, "object with exposed 'foo'"); + } + }); + is(getNames(strictCOWr).length, 1, + "object with exposedProps only enumerate exposed props"); + is(getNames(strictCOWr)[0], "foo", + "object with exposedProps only enumerate exposed props"); + + // Test writable property + var writable = getCOW({ __exposedProps__: {foo: 'w'}}); + try { + ok(!("foo" in writable), + "non-existing write-only property shouldn't exist"); + writable.foo = 5; + is(chromeGet(writable, "foo"), 5, "writing to a write-only exposed prop works"); + todo("foo" in writable, + "existing write-only property should exist"); + } catch (e) { + ok(false, "writing to a write-only exposed prop shouldn't throw " + e); + } + try { + writable.foo; + todo(false, "reading from a write-only exposed prop should throw"); + } catch (e) { + todo(/Permission denied/.test(e), + "reading from a write-only exposed prop should throw"); + } + try { + delete writable.foo; + is(chromeGet(writable, "foo"), undefined, + "deleting a write-only exposed prop works"); + } catch (e) { + ok(false, "deleting a write-only exposed prop shouldn't throw " + e); + } + + // Test readable property + var readable = { __exposedProps__: {foo: 'r'}, + foo: 5, + bar: 6 }; + try { + isProp(getCOW(readable), "foo", 5, + "reading from a readable exposed prop works"); + } catch (e) { + ok(false, "reading from a readable exposed prop shouldn't throw " + e); + } + try { + getCOW(readable).foo = 1; + ok(false, "writing to a read-only exposed prop should fail"); + } catch (e) { + ok(/Permission denied/.test(e), + "writing to a read-only exposed prop should fail"); + } + try { + delete getCOW(readable).foo; + ok(false, "deleting a read-only exposed prop shouldn't work"); + } catch (e) { + ok(/Permission denied/.test(e), + "deleting a read-only exposed prop should throw error"); + } + + try { + var props = getNames(getCOW(readable)); + is(props.length, 1, "COW w/ one exposed prop should enumerate once"); + is(props[0], 'foo', "COW w/ one exposed prop should enumerate it"); + } catch (e) { + ok(false, "COW w/ a readable prop should not raise exc " + + "on enumeration: " + e); + } + + // Test read/write property + var readwrite = getCOW({ __exposedProps__: {foo: 'rw'}}); + try { + ok(!("foo" in readwrite), + "non-existing readwrite property shouldn't exist"); + readwrite.foo = 5; + is(readwrite.foo, 5, "writing to a readwrite exposed prop looks like it worked"); + is(chromeGet(readwrite, "foo"), 5, "writing to a readwrite exposed prop works"); + ok("foo" in readwrite, + "existing readwrite property should exist"); + } catch (e) { + ok(false, "writing to a readwrite exposed prop shouldn't throw " + e); + } + try { + delete readwrite.foo; + is(readwrite.foo, undefined, "deleting readwrite prop looks like it worked"); + ok(!("foo" in readwrite), "deleting readwrite prop looks like it really worked"); + is(chromeGet(readwrite, "foo"), undefined, + "deleting a readwrite exposed prop works"); + } catch (e) { + ok(false, "deleting a readwrite exposed prop shouldn't throw " + e); + } + + // Readables and functions + try { + var COWFunc = getCOW((function() { return 5; })); + is(COWFunc(), 5, "COWed functions should be callable"); + } catch (e) { + todo(false, "COWed functions should not raise " + e); + } +} + +// Decompile the COW test suite, re-evaluate it in the sandbox and execute it. +Cu.evalInSandbox('(' + uneval(COWTests) + ')()', sandbox); + +// Test that COWed objects passing from content to chrome get unwrapped. +function returnCOW() { + return getCOW({__exposedProps__: {}, + bar: 6}); +} + +var unwrapped = Cu.evalInSandbox( + '(' + uneval(returnCOW) + ')()', + sandbox +); + +try { + is(unwrapped.bar, 6, + "COWs should be unwrapped when entering chrome space"); +} catch (e) { + todo(false, "COWs should be unwrapped when entering chrome space, " + + "not raise " + e); +} + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_discardSystemSource.xul b/js/xpconnect/tests/chrome/test_discardSystemSource.xul new file mode 100644 index 000000000..81ff91f51 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_discardSystemSource.xul @@ -0,0 +1,81 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=990353 +--> +<window title="Mozilla Bug 990353" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=990353" + target="_blank">Mozilla Bug 990353</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 990353 **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + function canary() { + var someBitOfSource = 42; + } + + var gLoadCount = 0; + function frameLoaded() { + switch (++gLoadCount) { + case 1: + ok(/sourceless/.test(window[0].canary.toSource()), "System function should be sourceless: " + window[0].canary.toSource()); + ok(/sourceless/.test(window[0].onload.toSource()), "System event handler should be sourceless: " + window[0].onload.toSource()); + var sb = new Cu.Sandbox('http://www.example.com', { discardSource: true }); + Cu.evalInSandbox('function canary() { var someBitOfSource = 42; }', sb); + ok(/sourceless/.test(sb.canary.toSource()), "Function from sandbox with explicit discarding should be sourceless"); + try { + window[0].throwSomething(); + ok(false, "should have thrown"); + } catch (e) { + ok(/some error/.test(e), "Threw exception as expected: " + e); + ok(/throwSomething/.test(e.stack), "Exception stack trace works: " + e.stack); + } + window[0].location = "http://example.org/tests/js/xpconnect/tests/chrome/file_discardSystemSource.html"; + break; + case 2: + ok(/someBitOfSource/.test(Cu.waiveXrays(window[0]).canary.toSource()), "Content function should have source"); + ok(/someBitOfSource/.test(Cu.waiveXrays(window[0]).onload.toSource()), "Content event handler should have source"); + testWorker(); + break; + } + } + + function testWorker() { + var worker = new window[0].wrappedJSObject.Worker('worker_discardSystemSource.js'); + worker.onmessage = function(evt) { + ok(/someBitOfSource/.test(evt.data), "Non-chrome worker should have source: " + evt.data); + var chromeWorker = new Worker('worker_discardSystemSource.js'); + chromeWorker.onmessage = function(evt) { + ok(/sourceless/.test(evt.data), "Chrome worker should not have source: " + evt.data); + SimpleTest.finish(); + } + } + } + + function go() { + // We should have our own source, because the pref wasn't enabled when we + // were loaded. + ok(/someBitOfSource/.test(canary.toSource()), "Should have own source"); + + window[0].frameElement.onload = frameLoaded; + window[0].location = "file_discardSystemSource.html"; + } + addLoadEvent(function() { + SpecialPowers.pushPrefEnv({set: [['javascript.options.discardSystemSource', true]]}, go); + }); + + ]]> + </script> + <iframe></iframe> +</window> diff --git a/js/xpconnect/tests/chrome/test_documentdomain.xul b/js/xpconnect/tests/chrome/test_documentdomain.xul new file mode 100644 index 000000000..858d2c4f0 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_documentdomain.xul @@ -0,0 +1,101 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=601277 +--> +<window title="Mozilla Bug 601277" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=601277" + target="_blank">Mozilla Bug 601277</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Tests for document.domain. **/ + + const Cu = Components.utils; + SimpleTest.waitForExplicitFinish(); + + // Wait for the frames to load. + var gFramesLoaded = 0; + function frameLoaded() { + gFramesLoaded++; + if (gFramesLoaded == document.getElementsByTagName('iframe').length) + startTest(); + } + + function startTest() { + + // Grab all the content windows and waive Xray. Xray waivers only apply to + // chrome, so we can pass these references directly to content. + var win1A = document.getElementById('test1A').contentWindow.wrappedJSObject; + var win1B = document.getElementById('test1B').contentWindow.wrappedJSObject; + var win2 = document.getElementById('test2').contentWindow.wrappedJSObject; + var winBase = document.getElementById('base').contentWindow.wrappedJSObject; + + // Check the basics. + ok(win1A.tryToAccess(win1B), + "Same-origin windows should grant access"); + ok(!win1A.tryToAccess(win2), + "Cross-origin windows should not grant access"); + ok(!win1A.tryToAccess(winBase), + "Subdomain windows should not receive access"); + + // Store references now, while test1A and test1B are same-origin. + win1A.storeReference(win1B); + win1B.storeReference(win1A); + ok(win1A.tryToAccessStored(), "Stored references work when same-origin"); + win1A.evalFromB = Cu.unwaiveXrays(win1B.eval); // Crashtest for bug 1040181. + win1B.functionFromA = Cu.unwaiveXrays(win1A.Function); // Crashtest for bug 1040181. + ok(!win1A.invokingFunctionThrowsSecurityException('evalFromB'), "Should allow before document.domain"); + ok(!win1B.invokingFunctionThrowsSecurityException('functionFromA'), "Should allow before document.domain"); + + // Set document.domain on test1A. This should grant no access, since nobody + // else set it. + win1A.setDomain('example.org'); + ok(!win1A.tryToAccess(winBase), "base must collaborate too"); + ok(!winBase.tryToAccess(win1A), "base must collaborate too"); + ok(!win1A.tryToAccess(win1B), "No longer same-origin"); + ok(!win1A.tryToAccessStored(), "No longer same-origin"); + ok(!win1B.tryToAccess(win1A), "No longer same-origin"); + ok(!win1B.tryToAccessStored(), "No longer same-origin"); + ok(win1A.invokingFunctionThrowsSecurityException('evalFromB'), "No longer same-origin"); + ok(win1B.invokingFunctionThrowsSecurityException('functionFromA'), "No longer same-origin"); + + // Set document.domain on test1B. Now we're cooking with gas. + win1B.setDomain('example.org'); + ok(!win1B.tryToAccess(winBase), "base must collaborate too"); + ok(!winBase.tryToAccess(win1B), "base must collaborate too"); + ok(win1A.tryToAccess(win1B), "same-origin"); + ok(win1A.tryToAccessStored(), "same-origin"); + ok(win1B.tryToAccess(win1A), "same-origin"); + ok(win1B.tryToAccessStored(), "same-origin"); + + // Explicitly collaborate with base. + winBase.setDomain('example.org'); + ok(winBase.tryToAccess(win1A), "base collaborates"); + ok(win1A.tryToAccess(winBase), "base collaborates"); + + // All done. + SimpleTest.finish(); + } + + + ]]> + </script> + + <iframe id="test1A" onload="frameLoaded();" type="content" + src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_documentdomain.html" /> + <iframe id="test1B" onload="frameLoaded();" type="content" + src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_documentdomain.html" /> + <iframe id="test2" onload="frameLoaded();" type="content" + src="http://test2.example.org/tests/js/xpconnect/tests/mochitest/file_documentdomain.html" /> + <iframe id="base" onload="frameLoaded();" type="content" + src="http://example.org/tests/js/xpconnect/tests/mochitest/file_documentdomain.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_doublewrappedcompartments.xul b/js/xpconnect/tests/chrome/test_doublewrappedcompartments.xul new file mode 100644 index 000000000..ab2b2e09e --- /dev/null +++ b/js/xpconnect/tests/chrome/test_doublewrappedcompartments.xul @@ -0,0 +1,42 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 533596" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + + <iframe type="content" + src="http://example.org/tests/js/xpconnect/tests/mochitest/file_doublewrappedcompartments.html" + onload="go()" + id="ifr"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + const utils = SpecialPowers.DOMWindowUtils; + + function go() { + var wrappedWin = $('ifr').contentWindow; + is(typeof wrappedWin.expando, 'undefined', "Shouldn't be able to see the expando"); + + var unwrapped = wrappedWin.wrappedJSObject; + + var expando = unwrapped.expando; + isnot(expando, 'undefined', 'properly wrapped'); + is(typeof expando.querySelector, 'function', 'double wrapped'); + + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_evalInSandbox.xul b/js/xpconnect/tests/chrome/test_evalInSandbox.xul new file mode 100644 index 000000000..dc5e96998 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_evalInSandbox.xul @@ -0,0 +1,202 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 533596" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + + <iframe src="http://example.org/tests/js/xpconnect/tests/mochitest/file_evalInSandbox.html" + onload="checkCrossOrigin(this)"> + </iframe> + <iframe src="chrome://mochitests/content/chrome/js/xpconnect/tests/chrome/file_evalInSandbox.html" + onload="checkSameOrigin(this)"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + const Cu = Components.utils; + const Ci = Components.interfaces; + const utils = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + + function checkCrossOriginSandbox(sandbox) + { + is(utils.getClassName(sandbox), + "Proxy", + "sandbox was wrapped correctly"); + + is(utils.getClassName(Cu.evalInSandbox("this.document", sandbox)), + "Proxy", + "return value was rewrapped correctly"); + } + + function checkCrossOriginXrayedSandbox(sandbox) + { + ok(Cu.evalInSandbox("!('windowfoo' in window);", sandbox), + "the window itself Xray is an XrayWrapper"); + ok(Cu.evalInSandbox("('wrappedJSObject' in this.document);", sandbox), + "wrappers inside eIS are Xrays"); + ok(Cu.evalInSandbox("!('foo' in this.document);", sandbox), + "must not see expandos"); + ok('wrappedJSObject' in Cu.evalInSandbox("this.document", sandbox), + "wrappers returned from the sandbox are Xrays"); + ok(!("foo" in Cu.evalInSandbox("this.document", sandbox)), + "must not see expandos in wrappers returned from the sandbox"); + + ok('wrappedJSObject' in sandbox.document, + "values obtained from the sandbox are Xrays"); + ok(!("foo" in sandbox.document), + "must not see expandos in wrappers obtained from the sandbox"); + + } + + function checkCrossOrigin(ifr) { + var win = ifr.contentWindow; + var sandbox = + new Cu.Sandbox(win, { sandboxPrototype: win, wantXrays: true } ); + + checkCrossOriginSandbox(sandbox); + checkCrossOriginXrayedSandbox(sandbox); + + sandbox = + new Cu.Sandbox(win, { sandboxPrototype: win } ); + + checkCrossOriginSandbox(sandbox); + checkCrossOriginXrayedSandbox(sandbox); + + sandbox = + new Cu.Sandbox(win, { sandboxPrototype: win, wantXrays: false } ); + + checkCrossOriginSandbox(sandbox); + + ok(Cu.evalInSandbox("('foo' in this.document);", sandbox), + "can see expandos"); + ok(("foo" in Cu.evalInSandbox("this.document", sandbox)), + "must see expandos in wrappers returned from the sandbox"); + + ok(("foo" in sandbox.document), + "must see expandos in wrappers obtained from the sandbox"); + + testDone(); + } + + function checkSameOrigin(ifr) { + var win = ifr.contentWindow; + var sandbox = + new Cu.Sandbox(win, { sandboxPrototype: win, wantXrays: true } ); + + ok(Cu.evalInSandbox("('foo' in this.document);", sandbox), + "must see expandos for a chrome sandbox"); + + sandbox = + new Cu.Sandbox(win, { sandboxPrototype: win } ); + + ok(Cu.evalInSandbox("('foo' in this.document);", sandbox), + "must see expandos for a chrome sandbox"); + + sandbox = + new Cu.Sandbox(win, { sandboxPrototype: win, wantXrays: false } ); + + ok(Cu.evalInSandbox("('foo' in this.document);", sandbox), + "can see expandos for a chrome sandbox"); + + testDone(); + } + + var testsRun = 0; + function testDone() { + if (++testsRun == 2) + SimpleTest.finish(); + } + + SimpleTest.waitForExplicitFinish(); + + try { + var sandbox = new Cu.Sandbox(this, { sandboxPrototype: undefined } ); + ok(false, "undefined is not a valid prototype"); + } + catch (e) { + ok(true, "undefined is not a valid prototype"); + } + + try { + var sandbox = new Cu.Sandbox(this, { wantXrays: undefined } ); + ok(false, "undefined is not a valid value for wantXrays"); + } + catch (e) { + ok(true, "undefined is not a valid value for wantXrays"); + } + + // Crash test for bug 601829. + try { + Components.utils.evalInSandbox('', null); + } catch (e) { + ok(true, "didn't crash on a null sandbox object"); + } + + try { + var sandbox = new Cu.Sandbox(this, { sameZoneAs: this } ); + ok(true, "sameZoneAs works"); + } + catch (e) { + ok(false, "sameZoneAs works"); + } + + // The 'let' keyword only appears with JS 1.7 and above. We use this fact + // to make sure that sandboxes get explict JS versions and don't inherit + // them from the most recent scripted frame. + function checkExplicitVersions() { + const Cu = Components.utils; + var sb = new Cu.Sandbox(sop); + Cu.evalInSandbox('let someVariable = 42', sb, '1.7'); + ok(true, "Didn't throw with let"); + try { + Cu.evalInSandbox('let someVariable = 42', sb); + ok(false, "Should have thrown with let"); + } catch (e) { + ok(true, "Threw with let: " + e); + } + try { + Cu.evalInSandbox('let someVariable = 42', sb, '1.5'); + ok(false, "Should have thrown with let"); + } catch (e) { + ok(true, "Threw with let: " + e); + } + } + var outerSB = new Cu.Sandbox(this); + Cu.evalInSandbox(checkExplicitVersions.toSource(), outerSB, '1.7'); + outerSB.ok = ok; + outerSB.sop = this; + Cu.evalInSandbox('checkExplicitVersions();', outerSB); + + Cu.import("resource://gre/modules/jsdebugger.jsm"); + addDebuggerToGlobal(this); + + try { + let dbg = new Debugger(); + let sandbox = new Cu.Sandbox(this, { invisibleToDebugger: false }); + dbg.addDebuggee(sandbox); + ok(true, "debugger added visible value"); + } catch(e) { + ok(false, "debugger could not add visible value"); + } + + try { + let dbg = new Debugger(); + let sandbox = new Cu.Sandbox(this, { invisibleToDebugger: true }); + dbg.addDebuggee(sandbox); + ok(false, "debugger added invisible value"); + } catch(e) { + ok(true, "debugger did not add invisible value"); + } + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_evalInWindow.xul b/js/xpconnect/tests/chrome/test_evalInWindow.xul new file mode 100644 index 000000000..6c69af05c --- /dev/null +++ b/js/xpconnect/tests/chrome/test_evalInWindow.xul @@ -0,0 +1,73 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=877673 +--> +<window title="Mozilla Bug 877673" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + var sb = new Cu.Sandbox("http://example.org", {wantExportHelpers: true}); + sb.ok = ok; + + function executeIn(frame, script, exceptionCb) { + sb.frame = frame; + sb.exceptionCb = exceptionCb; + if (exceptionCb) { + return Cu.evalInSandbox("try {frame.eval('" + script + "'); ok(false, 'Exception should have been thrown.')} catch(e) {exceptionCb(e)}", sb); + } + + return Cu.evalInSandbox("frame.eval('" + script + "')", sb); + } + + function testSameOrigin(frame) { + frame.contentWindow.document.wrappedJSObject.str = "foobar"; + is(executeIn(frame.contentWindow, "document.str"), "foobar", + "Same origin string property access."); + + executeIn(frame.contentWindow, 'document.obj = {prop: "foobar"}'); + is((executeIn(frame.contentWindow, "document.obj")).prop, "foobar", + "Same origin object property access (cloning)."); + isnot(executeIn(frame.contentWindow, "document.obj"), frame.contentWindow.document.wrappedJSObject.obj, + "Ensure cloning for js objects."); + is(executeIn(frame.contentWindow, "document"), frame.contentWindow.document, + "Xrayables should just pass without cloning."); + is( executeIn(frame.contentWindow, "({a:{doc: document}})").a.doc, frame.contentWindow.document, + "Deep cloning works."); + + executeIn(frame.contentWindow, "throw 42", function(e){is(e, 42, + "Exception was thrown from script.")}); + + testDone(); + } + + function testCrossOrigin(frame) { + executeIn(frame.contentWindow, "var a = 42;", function(e){ok(e.toString().indexOf("Permission denied") > -1, + "Executing script in a window from cross origin should throw.");}); + testDone(); + } + + var testsRun = 0; + function testDone() { + if (++testsRun == 2) + SimpleTest.finish(); + } + ]]></script> + <iframe src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" + onload="testSameOrigin(this)"> + </iframe> + <iframe src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_empty.html" + onload="testCrossOrigin(this)"> + </iframe> +</window> diff --git a/js/xpconnect/tests/chrome/test_exnstack.xul b/js/xpconnect/tests/chrome/test_exnstack.xul new file mode 100644 index 000000000..8536cf8dc --- /dev/null +++ b/js/xpconnect/tests/chrome/test_exnstack.xul @@ -0,0 +1,68 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=735544 +--> +<window title="Mozilla Bug 735544" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=735544" + target="_blank">Mozilla Bug 735544</a> + <iframe id='ifr0' onload="frameDone(0);" src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_exnstack.html" /> + <iframe id='ifr1' onload="frameDone(1);" src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_exnstack.html" /> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 735544 - Allow exception stacks to cross compartment boundaries **/ + + SimpleTest.waitForExplicitFinish(); + + var gFramesDone = [false, false]; + function frameDone(idx) { + gFramesDone[idx] = true; + if (gFramesDone[0] && gFramesDone[1]) + startTest(); + } + + function throwAsChrome() { + + // Grab the iframe content windows. + var cwin0 = document.getElementById('ifr0').contentWindow; + var cwin1 = document.getElementById('ifr1').contentWindow; + + // Have cwin0 call a function on cwin1 that throws. + cwin0.wrappedJSObject.doThrow(cwin1); + } + + function startTest() { + + try { + throwAsChrome(); + ok(false, "should throw"); + } catch (e) { + + stackFrames = e.stack.split("\n"); + + ok(/throwAsInner/.exec(stackFrames[0]), + "The bottom frame should be thrown by the inner"); + + ok(/throwAsOuter/.exec(stackFrames[2]), + "The 3rd-from-bottom frame should be thrown by the other"); + + ok(!/throwAsChrome/.exec(e.stack), + "The entire stack should not cross into chrome."); + } + + SimpleTest.finish(); + } + + ]]> + </script> + +</window> diff --git a/js/xpconnect/tests/chrome/test_expandosharing.xul b/js/xpconnect/tests/chrome/test_expandosharing.xul new file mode 100644 index 000000000..93884a82f --- /dev/null +++ b/js/xpconnect/tests/chrome/test_expandosharing.xul @@ -0,0 +1,145 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=758415 +--> +<window title="Mozilla Bug 758415" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=758415" + target="_blank">Mozilla Bug 758415</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for Cross-Origin Xray Expando Sharing. **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + // Import our test JSM. We first strip the filename off + // the chrome url, then append the jsm filename. + var base = /.*\//.exec(window.location.href)[0]; + Cu.import(base + "file_expandosharing.jsm"); + + // Wait for all child frames to load. + var gLoadCount = 0; + function frameLoaded() { + if (++gLoadCount == window.frames.length) + go(); + } + + function go() { + + // Empower the content windows with some functions. + var wins = document.getElementsByTagName('iframe'); + for (var i = 0; i < wins.length; ++i) { + var win = wins[i].contentWindow.wrappedJSObject; + win.ok = ok; + win.is = is; + } + + // Grab references to the content windows. We abbreviate the origins as follows: + // A: test1.example.org + // B: test2.example.org + // C: sub1.test1.example.org + window.gWinA1 = document.getElementById('frameA1').contentWindow; + window.gWinA2 = document.getElementById('frameA2').contentWindow; + window.gWinA3 = document.getElementById('frameA3').contentWindow; + window.gWinB = document.getElementById('frameB').contentWindow; + window.gWinC = document.getElementById('frameC').contentWindow; + + // Test expando sharing with a JSM for different types of Xrays. + testJSM(XPCNativeWrapper(gWinC.wrappedJSObject.targetWN)); + testJSM(XPCNativeWrapper(gWinC.wrappedJSObject.targetDOM)); + testJSM(XPCNativeWrapper(gWinC.wrappedJSObject.targetJS)); + + // Make sure sandboxes never share expandos with anyone else. + testSandbox(XPCNativeWrapper(gWinB.wrappedJSObject.targetWN)); + testSandbox(XPCNativeWrapper(gWinB.wrappedJSObject.targetDOM)); + testSandbox(XPCNativeWrapper(gWinB.wrappedJSObject.targetJS)); + + // Test Content Xrays. + testContentXrays(); + + SimpleTest.finish(); + } + + // Make sure that expandos are shared between us and a JSM. + function testJSM(target) { + target.numProp = 42; + target.strProp = "foo"; + target.objProp = { bar: "baz" }; + checkFromJSM(target, is); + } + + function testSandbox(target) { + + // This gets both run in this scope and the sandbox scope. + var name = "harness"; + function placeExpando() { + target.prop = name; + } + + // Set up the sandboxes. + sb1 = Cu.Sandbox(window); + sb2 = Cu.Sandbox(window); + sb1.target = target; + sb2.target = target; + sb1.name = "sandbox1"; + sb2.name = "sandbox2"; + placeExpando(); + Cu.evalInSandbox(placeExpando.toSource() + "placeExpando();", sb1); + Cu.evalInSandbox(placeExpando.toSource() + "placeExpando();", sb2); + + // Make sure everyone sees a different value. + is(target.prop, "harness", "Harness sees its own value"); + is(Cu.evalInSandbox("target.prop", sb1), "sandbox1", "Sandbox 1 sees its own value"); + is(Cu.evalInSandbox("target.prop", sb2), "sandbox2", "Sandbox 2 sees its own value"); + } + + // Make sure that the origin tagging machinery works correctly and that we don't + // mix up chrome and content expandos. + function testContentXrays() { + + // Give A1 and A3 xrays to (same-origin) A2. + Components.utils.setWantXrays(gWinA1); + Components.utils.setWantXrays(gWinA3); + + gWinA1.wrappedJSObject.placeExpando('A1_expando', 11, gWinA2.document); + gWinA3.wrappedJSObject.placeExpando('A3_expando', 33, gWinA2.document); + gWinA2.document.Chrome_expando = 33; + + is(gWinA2.document.Chrome_expando, 33, "Read chrome expando properly"); + is(typeof gWinA2.document.A1_expando, 'undefined', "Chrome doesn't see content expandos"); + is(typeof gWinA2.document.A3_expando, 'undefined', "Chrome doesn't see content expandos"); + gWinA1.wrappedJSObject.checkExpando('A1_expando', 11, gWinA2.document, "Content sees proper expandos"); + gWinA3.wrappedJSObject.checkExpando('A1_expando', 11, gWinA2.document, "Content sees proper expandos"); + gWinA1.wrappedJSObject.checkExpando('A3_expando', 33, gWinA2.document, "Content sees proper expandos"); + gWinA3.wrappedJSObject.checkExpando('A3_expando', 33, gWinA2.document, "Content sees proper expandos"); + gWinA1.wrappedJSObject.checkExpando('Chrome_expando', null, gWinA2.document, "Content doesn't see chrome expandos"); + gWinA3.wrappedJSObject.checkExpando('Chrome_expando', null, gWinA2.document, "Content doesn't see chrome expandos"); + + // We very explicitly do not support expando sharing via document.domain. + // A comment in the implementation explains why. + gWinA1.document.domain = 'test1.example.org'; + gWinA2.document.domain = 'test1.example.org'; + gWinA3.document.domain = 'test1.example.org'; + gWinC.document.domain = 'test1.example.org'; + gWinC.wrappedJSObject.checkExpando('A1_expando', null, gWinA2.document, "document.domain should have no effect here"); + gWinC.wrappedJSObject.checkExpando('A3_expando', null, gWinA2.document, "document.domain should have no effect here"); + } + + ]]> + </script> + <iframe id="frameA1" onload="frameLoaded();" type="content" src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_expandosharing.html" /> + <iframe id="frameA2" onload="frameLoaded();" type="content" src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_expandosharing.html" /> + <iframe id="frameA3" onload="frameLoaded();" type="content" src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/file_expandosharing.html" /> + <iframe id="frameB" onload="frameLoaded();" type="content" src="http://test2.example.org/tests/js/xpconnect/tests/mochitest/file_expandosharing.html" /> + <iframe id="frameC" onload="frameLoaded();" type="content" src="http://sub1.test1.example.org/tests/js/xpconnect/tests/mochitest/file_expandosharing.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_exposeInDerived.xul b/js/xpconnect/tests/chrome/test_exposeInDerived.xul new file mode 100644 index 000000000..2ed3bb91e --- /dev/null +++ b/js/xpconnect/tests/chrome/test_exposeInDerived.xul @@ -0,0 +1,46 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=804630 +--> +<window title="Mozilla Bug 804630" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=804630" + target="_blank">Mozilla Bug 804630</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test to make sure that COWed objects can expose properties from their prototypes. **/ + const Cu = Components.utils; + + // Set up the sandbox. + var sb = new Cu.Sandbox('http://www.example.com'); + sb.ok = ok; + sb.is = is; + + // Make a chrome object that exposes objects off its prototype. + sb.proto = { read: 42, readWrite: 32, __exposedProps__: {} }; + sb.obj = { __exposedProps__: { read: 'r', readWrite: 'rw' } }; + sb.obj.__proto__ = sb.proto; + + // Make sure we can't access any of the properties on the prototype directly. + Cu.evalInSandbox('is(proto.read, undefined, "proto.read inaccessible");', sb); + Cu.evalInSandbox('var wrote = false; ' + + 'try { proto.readWrite = 12; wrote = true; } catch(e) {} ' + + ' ok(!wrote, "Should not write proto property");', sb); + + // Make sure we can access the exposed properties via the derived object. + Cu.evalInSandbox('is(obj.read, 42, "obj.read accessible");', sb); + Cu.evalInSandbox('is(obj.readWrite, 32, "obj.readWrite is readable");', sb); + Cu.evalInSandbox('obj.readWrite = 8; is(obj.readWrite, 8, "obj.readWrite is writable");', sb); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_getweakmapkeys.xul b/js/xpconnect/tests/chrome/test_getweakmapkeys.xul new file mode 100644 index 000000000..38edde562 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_getweakmapkeys.xul @@ -0,0 +1,67 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=688277 +--> +<window title="Mozilla Bug " + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=" + target="_blank">Mozilla Bug 688277</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 688277 **/ + + let Cu = Components.utils; + + /* Fail gracefully if junk is passed in. */ + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(11), undefined, + "nondeterministicGetWeakMapKeys should return undefined for non-objects"); + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys({}), undefined, + "nondeterministicGetWeakMapKeys should return undefined for non-weakmap objects"); + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(null), undefined, + "nondeterministicGetWeakMapKeys should return undefined for null"); + + /* return an empty array for an empty WeakMap */ + let mempty = new WeakMap(); + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(mempty).length, 0, + "nondeterministicGetWeakMapKeys should return empty array for empty weakmap"); + + /* Test freeing/nonfreeing. */ + let m = new WeakMap(); + let liveKeys = new Array(); + + let add_elements = function () { + let k1 = {}; + m.set(k1, "live1"); + liveKeys.push(k1); + + let k2 = {}; + m.set(k2, "dead1"); + + let k = {}; + m.set(k, k); /* simple cycle */ + }; + + add_elements(); + + Cu.schedulePreciseGC(function () { + let keys = ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(m); + is(liveKeys.length, 1, "Wrong number of live keys."); + is(keys.length, 1, "Should have one weak map key."); + is(m.get(keys[0]), "live1", "live1 should be live"); + SimpleTest.finish(); + }); + + SimpleTest.waitForExplicitFinish(); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_localstorage_with_nsEp.xul b/js/xpconnect/tests/chrome/test_localstorage_with_nsEp.xul new file mode 100644 index 000000000..ebebb3a16 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_localstorage_with_nsEp.xul @@ -0,0 +1,38 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=980023 +--> +<window title="Mozilla Bug 980023 " + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=980023" + target="_blank">Mozilla Bug 980023 </a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for localstorage access with expanded principal. **/ + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + function go() { + var iwin = document.getElementById('ifr').contentWindow; + var sb = new Cu.Sandbox([iwin], {sandboxPrototype: iwin}); + Cu.evalInSandbox("window.localStorage.test_localstorage_with_nsEp = 3",sb); + is(Cu.evalInSandbox("window.localStorage.test_localstorage_with_nsEp",sb), "3"); + is(iwin.localStorage.test_localstorage_with_nsEp, "3"); + iwin.localStorage.removeItem("test_localstorage_with_nsEp"); + SimpleTest.finish(); + } + + ]]> + </script> + <iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_matches.xul b/js/xpconnect/tests/chrome/test_matches.xul new file mode 100644 index 000000000..bf57f95c9 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_matches.xul @@ -0,0 +1,50 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 533596" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + + <iframe src="http://example.org/tests/js/xpconnect/tests/mochitest/file_matches.html" + onload="runTest(this)"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + function runTest(ifr) + { + var doc = ifr.contentDocument; + var docElem = doc.documentElement; + + var res = doc.createElement('div').matches('div'); + is(res, true, "matches call through xray, regular case"); + + res = docElem.matches.call( + doc.createElement('div'), 'div'); + is(res, true, "matches call through xray, with .call"); + + var sb = new Components.utils.Sandbox(ifr.contentWindow); + sb.doc = doc; + var str = "doc.documentElement.matches.call(doc.createElement( 'div' ),'div')"; + res = Components.utils.evalInSandbox(str, sb); + is(res, true, "matches call through xray (same origin), with .call"); + + docElem.matches = function(){return false}; + res = docElem.matches.call(doc.createElement( 'div' ),'div'); + is(res, false, "shadowing matches with an expando on the xray wrapper"); + + SimpleTest.finish(); + } + + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_nodelists.xul b/js/xpconnect/tests/chrome/test_nodelists.xul new file mode 100644 index 000000000..7b91d7887 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_nodelists.xul @@ -0,0 +1,52 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<window title="Test nodelists from chrome" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/MochiKit/packed.js"></script> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + + function go() { + var win = $('ifr').contentWindow; + var list = win.document.getElementsByTagName('p'); + is(list.length, 3, "can get the length"); + ok(list[0] instanceof HTMLParagraphElement, "can get list[0]"); + is(list[0], list.item(0), "list.item works"); + is(list.item, list.item, "don't recreate functions for each get"); + + var list2 = list[2]; + ok(list[2] instanceof HTMLParagraphElement, "list[2] exists"); + ok("2" in list, "in operator works"); + + is(win.document.body.removeChild(win.document.body.lastChild), list2, "remove last paragraph element"); + ok(!("2" in list), "in operator doesn't see phantom element"); + is(list[2], undefined, "no node there!"); + + var optionList = win.document.createElement("select").options; + var option = win.document.createElement("option"); + optionList[0] = option; + is(optionList.item(0), option, "Creators work"); + + option = win.document.createElement("option"); + optionList[0] = option; + is(optionList.item(0), option, "Setters work"); + + SimpleTest.finish(); + } + ]]></script> + + <iframe id="ifr" + src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_nodelists.html" + onload="go()" /> +</window> diff --git a/js/xpconnect/tests/chrome/test_nsScriptErrorWithStack.html b/js/xpconnect/tests/chrome/test_nsScriptErrorWithStack.html new file mode 100644 index 000000000..9179e3985 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_nsScriptErrorWithStack.html @@ -0,0 +1,63 @@ +<!DOCTYPE html> +<meta charset=utf-8> +<title>Test for 814497</title> +<script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> +<div id="log"></div> +<script> + var c = Components.classes; + var Ci = Components.interfaces; + var Cu = Components.utils; + + Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + Cu.import("resource://gre/modules/Services.jsm"); + + SimpleTest.waitForExplicitFinish(); + SimpleTest.expectUncaughtException(); + + // /!\ Line number is important in this test, + // we are asserting the following functions line # + function failingStack() { + nestedFunction(); + } + function nestedFunction() { + doesntExistsAndThrow(); + } + + var TestObserver = { + QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), + + observe: function test_observe(aSubject) + { + if (!(aSubject instanceof Ci.nsIScriptError)) { + return; + } + dump("stack: "+aSubject.stack+"\n"); + + // Main assertions + var s = aSubject.stack; + ok(!!s, "has first frame"); + ok(s.source.indexOf("test_nsScriptErrorWithStack.html") !== -1, "source is correct"); + is(s.line, 23, "line is correct"); + is(s.column, 5, "column is correct"); + is(s.functionDisplayName, "nestedFunction"); + s = s.parent; + ok(!!s, "has second frame"); + ok(s.source.indexOf("test_nsScriptErrorWithStack.html") !== -1, "source is correct"); + is(s.line, 20, "line is correct"); + is(s.column, 5, "column is correct"); + is(s.functionDisplayName, "failingStack"); + // We shouldn't have any more frame as we used setTimeout + ok(!s.parent, "has no more frames"); + + // Cleanup + Services.console.unregisterListener(TestObserver); + SimpleTest.finish(); + } + }; + + Services.console.registerListener(TestObserver); + + // use setTimeout in order to prevent throwing from test frame + // and so have a clean stack frame with just our method calls + setTimeout(failingStack, 0); +</script> diff --git a/js/xpconnect/tests/chrome/test_onGarbageCollection.html b/js/xpconnect/tests/chrome/test_onGarbageCollection.html new file mode 100644 index 000000000..84b5d90bd --- /dev/null +++ b/js/xpconnect/tests/chrome/test_onGarbageCollection.html @@ -0,0 +1,35 @@ +<!doctype html> +<html> + <head> + <title>Bug 1150253 - Sanity test for the SpiderMonkey Debugger API's onGarbageCollection hook</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"> + </script> + </head> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1150253" + target="_blank">Mozilla Bug 1150253</a> + + <script type="application/javascript"> + SimpleTest.waitForExplicitFinish(); + const Cu = Components.utils; + + Cu.import("resource://devtools/shared/Loader.jsm"); + const require = devtools.require; + + const { gc } = Cu.getJSTestingFunctions(); + + const Debugger = require("Debugger"); + const dbg = new Debugger(this); + + dbg.memory.onGarbageCollection = function (data) { + // Don't keep calling this hook after we finish. + dbg.enabled = false; + + ok(data, "The onGarbageCollection hook was fired."); + SimpleTest.finish(); + }; + + gc(); + </script> + </body> +</html> diff --git a/js/xpconnect/tests/chrome/test_paris_weakmap_keys.xul b/js/xpconnect/tests/chrome/test_paris_weakmap_keys.xul new file mode 100644 index 000000000..ac7ff041d --- /dev/null +++ b/js/xpconnect/tests/chrome/test_paris_weakmap_keys.xul @@ -0,0 +1,80 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=777385 +--> +<window title="Mozilla Bug 777385" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <div></div> + <div id="mydivname"></div> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=" + target="_blank">Mozilla Bug 777385</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 777385 **/ + + let Cu = Components.utils; + + let live_map = new WeakMap; + + let get_div_style = function () { + return document.getElementById("mydivname").style; + } + + let make_live_map = function () { + let my_div_style = get_div_style(); + let div_fail = false; + try { + live_map.set(my_div_style, 12345); + } catch (e) { + div_fail = true; + } + ok(!div_fail, "Using elem.style as a weak map key should not produce an exception."); + + is(live_map.get(get_div_style()), 12345, "Live map should have live style with right value before GC."); + + } + + make_live_map(); + + // RGBColor is a non-nsISupports refCounted class using WebIDL bindings. + + // non-nsISupports cycle-collected classes should fail as weak map keys. + let context = window.getComputedStyle(document.documentElement, null).getPropertyCSSValue("color").getRGBColorValue(); + let contextFail = false; + try { + live_map.set(context, 2); + } catch (e) { + contextFail = true; + } + + ok(contextFail, "Cycle collected non-nsISupports classes aren't allowed as weak map keys."); + + /* Set up for running precise GC/CC then check the results. */ + + SimpleTest.waitForExplicitFinish(); + + Cu.schedulePreciseGC(function () { + SpecialPowers.DOMWindowUtils.cycleCollect(); + SpecialPowers.DOMWindowUtils.garbageCollect(); + SpecialPowers.DOMWindowUtils.garbageCollect(); + + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(live_map).length, 1, + "Live nsISupports new DOM bindings wrappercached native weak map key should not be removed."); + + is(live_map.get(get_div_style()), 12345, "Live map should have live style with right value after GC."); + + SimpleTest.finish(); + }); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_precisegc.xul b/js/xpconnect/tests/chrome/test_precisegc.xul new file mode 100644 index 000000000..382e6b536 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_precisegc.xul @@ -0,0 +1,27 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 661927" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + Components.utils.schedulePreciseGC( + function() { + ok(true, "callback executed"); + SimpleTest.finish(); + }); + SimpleTest.waitForExplicitFinish(); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_sandboxImport.xul b/js/xpconnect/tests/chrome/test_sandboxImport.xul new file mode 100644 index 000000000..eb2f76e84 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_sandboxImport.xul @@ -0,0 +1,39 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=533596 +--> +<window title="Mozilla Bug 533596" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + function checkWrapped(obj) { + var utils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) + .getInterface(Components.interfaces.nsIDOMWindowUtils); + is(utils.getClassName(obj), "Proxy", "right type of wrapper"); + } + + var sandbox = new Components.utils.Sandbox("about:blank"); + sandbox.importFunction(function() { return "PASS"; }, "foo"); + sandbox.importFunction(function bar() { return "PASS"; }); + sandbox.importFunction(checkWrapped); + is(Components.utils.evalInSandbox("foo()", sandbox), "PASS", "importFunction works"); + is(Components.utils.evalInSandbox("bar()", sandbox), "PASS", "importFunction works"); + Components.utils.evalInSandbox("checkWrapped({})", sandbox); + + var importer = sandbox.importFunction; + importer(function() { return "PASS"; }, "bar"); + is(Components.utils.evalInSandbox("bar()", sandbox), "PASS", "unbound importFunction works"); + is(typeof this.bar, "undefined", "didn't import into our global"); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_scriptSettings.xul b/js/xpconnect/tests/chrome/test_scriptSettings.xul new file mode 100644 index 000000000..54d6b0198 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_scriptSettings.xul @@ -0,0 +1,127 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=937317 +--> +<window title="Mozilla Bug 937317" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=937317" + target="_blank">Mozilla Bug 937317</a> + </body> + + <!-- test code goes here --> + <iframe src="data:text/html,"></iframe> + <script type="application/javascript"> + <![CDATA[ + + /** Test for the script settings stack. **/ + SimpleTest.waitForExplicitFinish(); + addLoadEvent(function() { + const Cu = Components.utils; + Cu.import("resource://gre/modules/Promise.jsm"); + iwin = window[0]; + + // Smoketest. + is(Cu.getIncumbentGlobal(), window, "smoketest"); + + // Calling a cross-compartment non-scripted function changes the + // compartment, but not the incumbent script settings object. + var sb = new Cu.Sandbox(window, { wantComponents: true }); + is(sb.Components.utils.getIncumbentGlobal(), window, "cross-compartment sb non-scripted"); + is(iwin.Components.utils.getIncumbentGlobal(), window, "cross-compartment win non-scripted"); + + // If we call a scripted function in the other compartment, that becomes + // the incumbent script. + function gib() { return Components.utils.getIncumbentGlobal(); }; + Cu.evalInSandbox(gib.toSource(), sb); + iwin.eval(gib.toSource()); + is(sb.gib(), sb, "cross-compartment sb scripted"); + is(iwin.gib(), iwin, "cross-compartment win scripted"); + + // Eval-ing top-level script in another component makes that compartment the + // incumbent script. + is(Cu.evalInSandbox('Components.utils.getIncumbentGlobal()', sb), sb, 'eval sb'); + is(iwin.eval('Components.utils.getIncumbentGlobal()'), iwin, 'eval iwin'); + + // Make sure that the callback mechanism works. + function makeCallback(expectedGlobal, deferred, kind) { + function cb(incumbentGlobal) { + is(incumbentGlobal, expectedGlobal, "Callback got the right incumbent global: " + kind); + if (deferred) + deferred.resolve(); + } + info("Generated callback: " + kind); + return cb; + } + + var bound = Cu.getIncumbentGlobal.bind(Cu, makeCallback(window, undefined, "simple bound")); + is(bound(), window, "Bound method returns the right global"); + + // Callbacks grab the incumbent script at the time of invocation. + // + // Note - We avoid calling the initial defer |d| so that it's not in-scope for everything below. + let initialDefer = Promise.defer(); + setTimeout(Cu.getIncumbentGlobal.bind(Cu, makeCallback(window, initialDefer, "same-global setTimeout")), 0); + initialDefer.promise.then(function() { + + // Try cross-global setTimeout where |window| is the incumbent script when the callback is created. + let d = Promise.defer(); + iwin.setTimeout(Cu.getIncumbentGlobal.bind(Cu, makeCallback(window, d, "cross-global setTimeout by |window|")), 0); + return d.promise; + }).then(function() { + + // Try cross-global setTimeout where |iwin| is the incumbent script when the callback is created. + let d = Promise.defer(); + iwin.wrappedJSObject.timeoutFun = Cu.getIncumbentGlobal.bind(Cu, makeCallback(iwin, d, "cross-global setTimeout by |iwin|")); + iwin.eval('setTimeout(timeoutFun, 0);'); + return d.promise; + }).then(function() { + + // The incumbent script override doesn't take effect if the callback is scripted. + let d = Promise.defer(); + iwin.wrappedJSObject.timeoutFun2 = Cu.getIncumbentGlobal.bind(Cu, makeCallback(iwin, d, "cross-global setTimeout of scripted function")); + iwin.eval('var timeoutFun2Wrapper = function() { timeoutFun2(); }'); + setTimeout(iwin.wrappedJSObject.timeoutFun2Wrapper, 0); + return d.promise; + }).then(function() { + + // Try event listeners. + let d = Promise.defer(); + let body = iwin.document.body; + body.addEventListener('click', Cu.getIncumbentGlobal.bind(Cu, makeCallback(window, d, "cross-global event listener"))); + body.dispatchEvent(new iwin.MouseEvent('click')); + return d.promise; + + }).then(function() { + + // Try an event handler set by |iwin|. + let d = Promise.defer(); + let body = iwin.document.body; + iwin.wrappedJSObject.handler = Cu.getIncumbentGlobal.bind(Cu, makeCallback(iwin, d, "cross-global event handler")); + iwin.eval('document.body.onmousemove = handler'); + body.dispatchEvent(new iwin.MouseEvent('mousemove')); + return d.promise; + + }).then(function() { + + // Try an event handler compiled by a content attribute. + let d = Promise.defer(); + let body = iwin.document.body; + iwin.wrappedJSObject.innerHandler = Cu.getIncumbentGlobal.bind(Cu, makeCallback(iwin, d, "cross-global compiled event handler")); + iwin.eval("document.body.setAttribute('onmouseout', 'innerHandler()')"); + body.dispatchEvent(new iwin.MouseEvent('mouseout')); + return d.promise; + }).then(function() { + + SimpleTest.finish(); + }); + }); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_watchpoints.xul b/js/xpconnect/tests/chrome/test_watchpoints.xul new file mode 100644 index 000000000..2262b1a90 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_watchpoints.xul @@ -0,0 +1,75 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=693527 +--> +<window title="Mozilla Bug " + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=" + target="_blank">Mozilla Bug 693527</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 693527 **/ + + let Cu = Components.utils; + let Ci = Components.interfaces; + + /* Create a weak reference, with a single-element weak map. */ + let make_weak_ref = function (obj) { + let m = new WeakMap; + m.set(obj, {}); + return m; + }; + + /* Check to see if a weak reference is dead. */ + let weak_ref_dead = function (r) { + return ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(r).length == 0; + } + + + let make_cycle = function () { + var p = document.createElement("p"); + p.children.x = p; + var f = function() { }; + p.watch("y", f); + var d = document.createElement("div"); + d.appendChild(p); + f.loop = d; + f.bar = {}; // observing f directly makes the leak go away even without the CC somehow + return make_weak_ref(f.bar); + }; + + var cycle_ref = make_cycle(); + + + /* set up for running precise GC/CC then checking the results */ + + SimpleTest.waitForExplicitFinish(); + + Cu.schedulePreciseGC(function () { + window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils) + .cycleCollect(); + window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils) + .garbageCollect(); + window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils) + .garbageCollect(); + + ok(weak_ref_dead(cycle_ref), "Garbage gray watchpoint cycle should be collected."); + + SimpleTest.finish(); + }); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_weakmap_keys_preserved.xul b/js/xpconnect/tests/chrome/test_weakmap_keys_preserved.xul new file mode 100644 index 000000000..95908a7b1 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_weakmap_keys_preserved.xul @@ -0,0 +1,37 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=673468 +--> +<window title="Mozilla Bug " + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=" + target="_blank">Mozilla Bug 673468</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 673468 **/ + + let Cc = Components.classes; + let Cu = Components.utils; + let Ci = Components.interfaces; + + let system = Cc["@mozilla.org/systemprincipal;1"].createInstance(); + let sandbox = Cu.Sandbox(system); + let map = new sandbox.WeakMap(); + let obj = {}; + map.set(obj, {}); + + Cu.forceGC(); + + ok(map.has(obj), "Weakmap still contains our wrapper!"); + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_weakmap_keys_preserved2.xul b/js/xpconnect/tests/chrome/test_weakmap_keys_preserved2.xul new file mode 100644 index 000000000..c6931af36 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_weakmap_keys_preserved2.xul @@ -0,0 +1,84 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=673468 +--> +<window title="Mozilla Bug " + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a id="testelem" href="https://bugzilla.mozilla.org/show_bug.cgi?id=" + target="_blank">Mozilla Bug 673468</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 673468 **/ + + let Cc = Components.classes; + let Cu = Components.utils; + let Ci = Components.interfaces; + + SpecialPowers.DOMWindowUtils.garbageCollect(); + + let get_live_dom = function () { + return document.getElementById("testelem"); + }; + + let wrappers_as_keys_test = function () { + let e = new MessageEvent("foo", { bubbles: false, cancellable: false, + data: { dummy: document.createElement("foo") }}); + window.eeeevent = e; + + let live_dom = e.data.dummy; + let dead_dom = document.createElement("div"); + let dead_child = document.createElement("div"); + dead_dom.appendChild(dead_child); + is(dead_dom.children.length, 1, "children have wrong length"); + let wrappee = new Object(); + + dead_dom.abcxyz = wrappee; + + let system = Cc["@mozilla.org/systemprincipal;1"].createInstance(); + let sandbox = Cu.Sandbox(system); + + sandbox.wrapper = wrappee; + sandbox.value = dead_dom; + let map = Cu.evalInSandbox("wm = new WeakMap(); wm.set(wrapper, value); wm", sandbox); + sandbox.wrapper = null; + sandbox.value = null; + + live_dom.xyzabc = {wrappee: wrappee, m: map, sb: sandbox}; + + let key = ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(map)[0]; + let value = map.get(key); + is(value.children.length, 1, "children have wrong length"); + } + + wrappers_as_keys_test(); + + let check_wrappers_as_keys = function () { + let live_dom = window.eeeevent.data.dummy; + let live_map = live_dom.xyzabc.m; + let sandbox = live_dom.xyzabc.sb; + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(live_map).length, 1, + "Map should not be empty."); + let key = ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(live_map)[0]; + let value = live_map.get(key); + is(value.children.length, 1, "children have wrong length"); + } + + Cu.schedulePreciseGC(function () { + SpecialPowers.DOMWindowUtils.cycleCollect(); + SpecialPowers.DOMWindowUtils.garbageCollect(); + + check_wrappers_as_keys(); + }); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_weakmaps.xul b/js/xpconnect/tests/chrome/test_weakmaps.xul new file mode 100644 index 000000000..e741a41c6 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_weakmaps.xul @@ -0,0 +1,272 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=668855 +--> +<window title="Mozilla Bug " + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=" + target="_blank">Mozilla Bug 668855</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + /** Test for Bug 668855 **/ + + let Cu = Components.utils; + let Ci = Components.interfaces; + + /* Create a weak reference, with a single-element weak map. */ + let make_weak_ref = function (obj) { + let m = new WeakMap; + m.set(obj, {}); + return m; + }; + + /* Check to see if a weak reference is dead. */ + let weak_ref_dead = function (r) { + return ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(r).length == 0; + } + + /* Deterministically grab an arbitrary DOM element. */ + let get_live_dom = function () { + let elems = document.getElementsByTagName("a"); + return elems[0]; + }; + + + /* Test case from bug 653248, adapted into a standard test. + + This is a dead cycle involving a DOM edge, so the cycle collector can free it. Keys and + values reachable only from XPConnect must be marked gray for this to work, and the cycle collector + must know the proper structure of the heap. + + */ + let make_gray_loop = function () { + let map = new WeakMap; + let div = document.createElement("div"); + let key = {}; + div.setUserData("entrain", {m:map, k:key}, null); + //div.entrain = {m:map, k:key}; This is not sufficient to cause a leak in Fx9 + map.set(key, div); + return make_weak_ref(map); + }; + + let weakref = make_gray_loop(); + + + /* Combinations of live and dead gray maps/keys. */ + let basic_weak_ref = null; + let basic_map_weak_ref = null; + let black_map = new WeakMap; + let black_key = {}; + + let basic_unit_tests = function () { + let live_dom = get_live_dom(); + let dead_dom = document.createElement("div"); + let live_map = new WeakMap; + let dead_map = new WeakMap; + let live_key = {}; + let dead_key = {}; + + // put the live/dead maps/keys into the appropriate DOM elements + live_dom.basic_unit_tests = {m:live_map, k:live_key}; + dead_dom.setUserData("hook", {m:dead_map, k:dead_key}, null); + // dead_dom.hook = {m:dead_map, k:dead_key}; + + // Create a dead value, and a weak ref to it. + // The loop keeps dead_dom alive unless the CC is smart enough to kill it. + let dead_val = {loop:dead_dom}; + basic_weak_ref = make_weak_ref(dead_val); + basic_map_weak_ref = make_weak_ref(dead_map); + + // set up the actual entries. most will die. + live_map.set(live_key, {my_key:'live_live'}); + live_map.set(dead_key, dead_val); + live_map.set(black_key, {my_key:'live_black'}); + + dead_map.set(live_key, dead_val); + dead_map.set(dead_key, dead_val); + dead_map.set(black_key, dead_val); + + black_map.set(live_key, {my_key:'black_live'}); + black_map.set(dead_key, dead_val); + black_map.set(black_key, {my_key:'black_black'}); + + }; + + basic_unit_tests(); + + + let check_basic_unit = function () { + let live_dom = get_live_dom(); + let live_map = live_dom.basic_unit_tests.m; + let live_key = live_dom.basic_unit_tests.k; + + // check the dead elements + ok(weak_ref_dead(basic_weak_ref), "Dead value was kept alive."); + ok(weak_ref_dead(basic_map_weak_ref), "Dead map was kept alive."); + + // check the live gray map + is(live_map.get(live_key).my_key, 'live_live', + "Live key should have the same value in live map."); + is(live_map.get(black_key).my_key, 'live_black', + "Black key should have the same value in live map."); + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(live_map).length, 2, + "Live map should have two entries."); + + // check the live black map + is(black_map.get(live_key).my_key, 'black_live', + "Live key should have the same value in black map."); + is(black_map.get(black_key).my_key, 'black_black', + "Black key should have the same value in black map."); + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(black_map).length, 2, + "Black map should have two entries."); + + }; + + + /* live gray chained weak map entries, involving the cycle collector. */ + let chainm = new WeakMap; + let num_chains = 5; + + let nested_cc_maps = function () { + let dom = get_live_dom(); + for(let i = 0; i < num_chains; i++) { + let k = {count:i}; + dom.key = k; + dom0 = document.createElement("div"); + chainm.set(k, {d:dom0}); + dom = document.createElement("div"); + dom0.appendChild(dom); + }; + }; + + let check_nested_cc_maps = function () { + let dom = get_live_dom(); + let all_ok = true; + for(let i = 0; i < num_chains; i++) { + let k = dom.key; + all_ok = all_ok && k.count == i; + dom = chainm.get(k).d.firstChild; + }; + ok(all_ok, "Count was invalid on a key in chained weak map entries."); + }; + + nested_cc_maps(); + + + /* black weak map, chained garbage cycle involving DOM */ + let garbage_map = new WeakMap; + + let chained_garbage_maps = function () { + let dom0 = document.createElement("div"); + let dom = dom0; + for(let i = 0; i < num_chains; i++) { + let k = {}; + dom.key = k; + let new_dom = document.createElement("div"); + garbage_map.set(k, {val_child:new_dom}); + dom = document.createElement("div"); + new_dom.appendChild(dom); + }; + // tie the knot + dom.appendChild(dom0); + }; + + chained_garbage_maps(); + + + /* black weak map, chained garbage cycle involving DOM, XPCWN keys */ + let wn_garbage_map = new WeakMap; + + let wn_chained_garbage_maps = function () { + let dom0 = document.createElement("div"); + let dom = dom0; + for(let i = 0; i < num_chains; i++) { + let new_dom = document.createElement("div"); + wn_garbage_map.set(dom, {wn_val_child:new_dom}); + dom = document.createElement("div"); + new_dom.appendChild(dom); + }; + // tie the knot + dom.appendChild(dom0); + }; + + wn_chained_garbage_maps(); + + + /* The cycle collector shouldn't remove a live wrapped native key. */ + + let wn_live_map = new WeakMap; + + let make_live_map = function () { + let live = get_live_dom(); + wn_live_map.set(live, {}); + ok(wn_live_map.has(get_live_dom()), "Live map should have live DOM node before GC."); + } + + make_live_map(); + + let unpreservable_native_key = function () { + // We only allow natives that support wrapper preservation to be used as weak + // map keys. We should be able to try to add unpreservable natives as keys without + // crashing (bug 711616), but we should throw an error (bug 761620). + + let dummy_test_map = new WeakMap; + + let rule_fail = false; + let got_rule = false; + try { + var rule = document.styleSheets[0].cssRules[0]; + got_rule = true; + dummy_test_map.set(rule, 1); + } catch (e) { + rule_fail = true; + } + ok(got_rule, "Got the CSS rule"); + ok(rule_fail, "Using a CSS rule as a weak map key should produce an exception because it can't be wrapper preserved."); + + } + + unpreservable_native_key(); + + /* set up for running precise GC/CC then checking the results */ + + SimpleTest.waitForExplicitFinish(); + + Cu.schedulePreciseGC(function () { + SpecialPowers.DOMWindowUtils.cycleCollect(); + SpecialPowers.DOMWindowUtils.garbageCollect(); + SpecialPowers.DOMWindowUtils.garbageCollect(); + + ok(weak_ref_dead(weakref), "Garbage gray cycle should be collected."); + + check_nested_cc_maps(); + + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(garbage_map).length, 0, "Chained garbage weak map entries should not leak."); + + check_basic_unit(); + + // fixed by Bug 680937 + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(wn_garbage_map).length, 0, + "Chained garbage WN weak map entries should not leak."); + + // fixed by Bug 680937 + is(ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(wn_live_map).length, 1, + "Live weak map wrapped native key should not be removed."); + + ok(wn_live_map.has(get_live_dom()), "Live map should have live dom."); + + SimpleTest.finish(); + }); + + ]]> + </script> +</window> diff --git a/js/xpconnect/tests/chrome/test_weakref.xul b/js/xpconnect/tests/chrome/test_weakref.xul new file mode 100644 index 000000000..3950a0e35 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_weakref.xul @@ -0,0 +1,34 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=484459 +--> +<window title="Weakrefs" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <iframe type="content" id="ifr"> + </iframe> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + SimpleTest.waitForExplicitFinish(); + var util = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) + .getInterface(Components.interfaces.nsIDOMWindowUtils); + var weakUtil = Components.utils.getWeakReference(util); + util = null; + + function callback() { + ok(weakUtil.get(), "Should still be alive here"); + SimpleTest.finish(); + } + + SpecialPowers.exactGC(callback); + ]]></script> +</window> diff --git a/js/xpconnect/tests/chrome/test_windowProxyDeadWrapper.html b/js/xpconnect/tests/chrome/test_windowProxyDeadWrapper.html new file mode 100644 index 000000000..91f4037f7 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_windowProxyDeadWrapper.html @@ -0,0 +1,72 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1223372 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1223372</title> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="chrome://global/skin"/> + <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + +/** Test for Bug 1223372 **/ + +function go() { + SimpleTest.waitForExplicitFinish(); + + var frame = $('subframe'); + frame.onload = null; + + var w = frame.contentWindow; + + w.eval("checkDead = function() { return Components.utils.isDeadWrapper(this); };"); + var checkDead = w.checkDead; + + w.eval("getObject = function() { return {}; }"); + var getObject = w.getObject; + + ok(!checkDead(), "WindowProxy shouldn't be dead yet"); + + // Load a content page in the chrome frame. + w.location = "http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"; + tryWindow(); + + function tryWindow() { + if (w.document.title != 'empty test page') { + info("Document not loaded yet - retrying"); + SimpleTest.executeSoon(tryWindow); + return; + } + + // Remove the frame. This will nuke the WindowProxy wrapper from our chrome + // document's global, so evaluating 'this' in it will return a dead wrapper. + frame.remove(); + + SimpleTest.executeSoon(function() { + ok(checkDead(), "Expected a dead object wrapper"); + + // Wrapping the Window should throw now. + var exc; + try { + Components.utils.getGlobalForObject(getObject()); + } catch(e) { + exc = e; + } + is(exc.message, "Can't wrap dead object"); + + SimpleTest.finish(); + }); + } +} + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1223372">Mozilla Bug 1223372</a> + +<iframe id="subframe" src="data:text/html," onload="go()"></iframe> + +</body> +</html> diff --git a/js/xpconnect/tests/chrome/test_wrappers-2.xul b/js/xpconnect/tests/chrome/test_wrappers-2.xul new file mode 100644 index 000000000..abab47f80 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_wrappers-2.xul @@ -0,0 +1,215 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 500931" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=403005" + target="_blank">Mozilla Bug 403005</a> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=409298" + target="_blank">Mozilla Bug 409298</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 403005 and 409298 **/ + + SimpleTest.waitForExplicitFinish(); + + function go() + { + ok(window instanceof Object, "window is instanceof Object"); + + let wrap = $('ifr').contentWindow.wrappedJSObject; + ok(!('obj' in XPCNativeWrapper(wrap)), "XPCNativeWrapper constructor works"); + let iwin = $('ifr').contentWindow; + is(iwin.document.ELEMENT_NODE, 1, 'constants work through XrayWrapper'); + is(iwin.document.nodeName, "#document", 'attributes work through XrayWrappe + + location.foopy = 3; + + var xow_answer = []; + for (let i in location) + xow_answer.push(i); + + var xpcnw_answer = []; + var xpcnw = new XPCNativeWrapper(location); + xpcnw.barpy = 4; + for (let i in xpcnw) + xpcnw_answer.push(i); + + var expected = [ + "hash", + "host", + "hostname", + "href", + "pathname", + "port", + "protocol", + "search", + "reload", + "replace", + "assign", + "foopy" + ]; + + var xpcnw_expected = expected.slice(0, expected.length - 1); + xpcnw_expected.push("barpy"); + + is(xow_answer.sort().toString(), + expected.sort().toString(), + 'enumeration over XOWs walks the prototype chain'); + + is(xpcnw_answer.sort().toString(), + xpcnw_expected.sort().toString(), + 'enumeration over XPCNWs walks the prototype chain'); + + var for_each_expected = []; + for each (let i in new XPCNativeWrapper(location)) + for_each_expected.push(typeof i); + + var for_each_answer = []; + for each (let i in Iterator(new XPCNativeWrapper(location))) + for_each_answer.push(typeof i); + + is(for_each_answer.sort().toString(), + for_each_expected.sort().toString(), + 'wrapper iterators are properly iterators'); + + let sjow_answer = []; + let (obj = { a: 3, next:1 }) { + for (let i in wrap.to_iterate) + sjow_answer.push(i); + is(sjow_answer.sort().toString(), ['a', 'next'].sort().toString(), + 'enumeration over SJOWs walks the prototype chain'); + } + + sjow_answer = []; + for (let i in wrap.location) + sjow_answer.push(i); + + is(sjow_answer.sort().toString(), + expected.sort().toString(), + 'enumeration over SJOWs walks the prototype chain and works over XOWs'); + + for (let i in wrap.enumerate) { + is(typeof i, "string", "enumeration on wrappers only returns strings"); + } + + isnot(wrap, new XPCNativeWrapper(iwin), + 'SJOWs equality hook returns false correctly against XPCNW'); + + is(typeof(wrap.func), 'function', + 'SJOWs look like functions when they wrap functions'); + is(typeof(wrap.o), 'object', + 'SJOWs look like objects when they wrap objects'); + ok(wrap.o === wrap.o, + "Identity holds when accessing the same object twice"); + + var origProto = iwin.__proto__; + try { + iwin.__proto__ = iwin; + ok(false, 'cyclic proto value allowed'); + iwin.__proto__ = origProto; + } catch (e) { + is(e.toString(), + 'TypeError: cyclic __proto__ value', + 'throw the right exception for a cyclic proto'); + is(iwin.__proto__, origProto, 'reset __proto__ after a cyclic proto'); + } + + try { + is('PASS', iwin.eval("'PASS'"), 'iwin.eval throws an exception'); + } catch (e) { + ok(false, 'iwin.eval does not throw an exception'); + } + + try { + new XPCNativeWrapper(""); + ok(false, "How did we construct a wrapper around a primitive?"); + } catch (e) { + ok(true, "Unable to new XPCNativeWrapper(primitive)"); + } + + try { + is(XPCNativeWrapper(""), "", "XPCNativeWrapper as a function allows primitives"); + } catch (e) { + ok(false, "Unable to wrap a primitive, even without 'new'"); + } + + // Some tests for SJOWs too. + isnot(wrap.document.body != document.body, "body should not be the same"); + + XPCNativeWrapper.prototype = {}; + let (w = new XPCNativeWrapper(iwin)) { + ok(iwin.location, "able to set XPCNativeWrapper.prototype and do stuff with it"); + } + + is(new XPCNativeWrapper(iwin, Window).closed, false, + "able to wrap a window in a window XPCNativeWrapper"); + try { + new XPCNativeWrapper(document, Window); + todo(false, "Able to wrap a document in a Window XPCNativeWrapper?") + } catch (e) { + ok(/ILLEGAL_VALUE/(e), "not able to wrap a document in a Window XPCNativeWrapper"); + } + + let (w = new XPCNativeWrapper($('ifr').contentWindow)) { + w.foopybar = 5; + ok(!("foopybar" in iwin), "XPCNativeWrappers allow expandos through"); + is(w.foopybar, 5, "can set expandos on XPCNativeWrappers, though"); + + ok(delete w.foopybar, "deleting properties returns true correctly"); + ok(!("foopybar" in w), "Can delete properties from XPCNativeWrappers"); + + is(w.window, iwin, "w.window exists and is the window"); + ok(delete w.iwin, "can delete builtin properties"); + is(w.window, iwin, "w.window is automatically recreated"); + + iwin.foopy = 5; + ok(delete w.foopy, "delete returns true"); + is(iwin.foopy, 5, "delete doesn't delete underlying properties"); + ok(delete iwin.foopy, "can delete window.foopy"); + ok(!("foopy" in iwin), "foopy is no longer in window"); + } + + try { + is((function(x) { return x+1; }).apply(this, wrap.a), 2, + "able to call apply with an XPCSafeJSObjectWrapped array"); + } catch (e) { + ok(false, + "Unable to call apply() with a XPCSafeJSObjectWrapped array"); + } + + try { + iwin.__proto__ = null; + is(iwin.__proto__, null, + "allowed to update iwin.__proto__ to null"); + } catch (e) { + ok(false, "some crazy exception was thrown"); + } + + try { + new XPCSafeJSObjectWrapped(<x />).foo; + ok(false, "Allowed to wrap E4X in SJOWs?"); + } catch (e) { + } + + SimpleTest.finish(); + } + ]]></script> + <iframe type="content" + src="http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_wrappers-2.html" + onload="go()" + id="ifr"> + </iframe> +</window> diff --git a/js/xpconnect/tests/chrome/test_wrappers.xul b/js/xpconnect/tests/chrome/test_wrappers.xul new file mode 100644 index 000000000..41504d28f --- /dev/null +++ b/js/xpconnect/tests/chrome/test_wrappers.xul @@ -0,0 +1,96 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin" type="text/css"?> +<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" + type="text/css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500931 +--> +<window title="Mozilla Bug 500931" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" + src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=533596" + target="_blank">Mozilla Bug 533596</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"><![CDATA[ + + /** Test for Bug 533596 **/ + + function go() { + var win = $('ifr').contentWindow; + var utils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) + .getInterface(Components.interfaces.nsIDOMWindowUtils); + is(utils.getClassName(window), "Proxy", "our window is wrapped correctly") + is(utils.getClassName(location), "Location", "chrome doesn't have location wrappers") + is(utils.getClassName(win), "Proxy", "win is an Proxy"); + is(utils.getClassName(win.location), "Proxy", "deep wrapping works"); + is(win.location.href, "http://example.org/tests/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html", + "can still get strings out"); + + var unsafeWin = win.wrappedJSObject; + is(utils.getClassName(unsafeWin), "Proxy", "can get a Proxy"); + is(utils.getClassName(unsafeWin.location), "Proxy", "deep wrapping works"); + + Object.defineProperty(unsafeWin, "defprop1", { value: 1, writable: true, enumerable: true, configurable: true }); + /* TODO (bug 552854): the getter isn't visible in content. + function checkWrapper(val) { + ok(utils.getClassName(val) == "Proxy", "wrapped properly"); + } + Object.defineProperty(unsafeWin, "defprop2", { set: checkWrapper, enumerable: true, configurable: true }); + */ + unsafeWin.run_test(ok, win, unsafeWin); + + win.setTimeout(function() { + is(utils.getClassName(this), "Proxy", + "this is wrapped correctly"); + SimpleTest.finish(); + }, 0) + + var saw0 = false; + for (let i in $('ifr').contentDocument.getElementsByTagName('body')) { + if (i === "0") + saw0 = true; + } + ok(saw0, "properly enumerated the 0 value"); + + ok(win.XPathEvaluator.toString().indexOf("XPathEvaluator") >= 0, + "Can access content window.XPathEvaluator"); + + var nativeToString = + ("" + String.replace).replace("replace", "EventTarget"); + var eventTargetToString = "" + win.EventTarget; + ok(eventTargetToString.indexOf(nativeToString) > -1, + "Stringifying a DOM interface object should return the same string as " + + "stringifying a native function." + " " + eventTargetToString + " " + nativeToString); + + is(win.XPathResult.NUMBER_TYPE, 1, "can access constants on constructors"); + is(typeof win.IDBKeyRange.bound, "function", "can access crazy IDBKeyRange static functions"); + + // Test getter/setter lookup on Xray wrappers. + ok(Object.prototype.__lookupGetter__.call(win.document, 'title'), 'found getter on document'); + ok(Object.prototype.__lookupGetter__.call(win.document, 'title'), 'found getter on document'); + + // Test QI on new dom bindings. + var contentXHR = XPCNativeWrapper(win.wrappedJSObject.xhr); + try { + var QIed = contentXHR.QueryInterface(Components.interfaces.nsIClassInfo); + ok(false, "Should throw for new binding objects not having classinfo"); + } catch(e) { + ok(true, "Threw while QI-ing on wrapper"); + } + } + + SimpleTest.waitForExplicitFinish(); + + ]]></script> + <iframe type="content" + src="http://example.org/tests/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html" + onload="go()" + id="ifr"> + </iframe> +</window> diff --git a/js/xpconnect/tests/chrome/test_xrayToJS.xul b/js/xpconnect/tests/chrome/test_xrayToJS.xul new file mode 100644 index 000000000..2f4e70f47 --- /dev/null +++ b/js/xpconnect/tests/chrome/test_xrayToJS.xul @@ -0,0 +1,948 @@ +<?xml version="1.0"?> +<?xml-stylesheet type="text/css" href="chrome://global/skin"?> +<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=933681 +--> +<window title="Mozilla Bug 933681" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/> + + <!-- test results are displayed in the html:body --> + <body xmlns="http://www.w3.org/1999/xhtml"> + <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=933681" + target="_blank">Mozilla Bug 933681</a> + </body> + + <!-- test code goes here --> + <script type="application/javascript"> + <![CDATA[ + + /** Test for ES constructors on Xrayed globals. **/ + SimpleTest.waitForExplicitFinish(); + const Cc = Components.classes; + const Ci = Components.interfaces; + const Cu = Components.utils; + let global = Cu.getGlobalForObject.bind(Cu); + + function checkThrows(f, rgxp, msg) { + try { + f(); + ok(false, "Should have thrown: " + msg); + } catch (e) { + ok(true, "Threw as expected: " + msg); + ok(rgxp.test(e), "Message correct: " + e); + } + } + + typedArrayClasses = ['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', + 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array', + 'Uint8ClampedArray']; + errorObjectClasses = ['Error', 'InternalError', 'EvalError', 'RangeError', 'ReferenceError', + 'SyntaxError', 'TypeError', 'URIError']; + + // A simpleConstructors entry can either be the name of a constructor as a + // string, or an object containing the properties `name`, and `args`. + // In the former case, the constructor is invoked without any args; in the + // latter case, it is invoked with `args` as the arguments list. + simpleConstructors = ['Object', 'Function', 'Array', 'Boolean', 'Date', 'Number', + 'String', 'RegExp', 'ArrayBuffer', 'WeakMap', 'Map', 'Set', + {name: 'Promise', args: [function(){}]}].concat(typedArrayClasses) + .concat(errorObjectClasses); + + function go() { + window.iwin = document.getElementById('ifr').contentWindow; + + // Test constructors that can be instantiated with zero arguments, or with + // a fixed set of arguments provided using `...rest`. + for (var c of simpleConstructors) { + var args = []; + if (typeof c === 'object') { + args = c.args; + c = c.name; + } + ok(iwin[c], "Constructors appear: " + c); + is(iwin[c], Cu.unwaiveXrays(iwin.wrappedJSObject[c]), + "we end up with the appropriate constructor: " + c); + is(Cu.unwaiveXrays(Cu.waiveXrays(new iwin[c](...args)).constructor), iwin[c], + "constructor property is set up right: " + c); + let expectedProto = /Opaque/.test(new iwin[c](...args)) ? iwin['Object'].prototype + : iwin[c].prototype; + is(Object.getPrototypeOf(new iwin[c](...args)), expectedProto, + "prototype is correct: " + c); + is(global(new iwin[c](...args)), iwin, "Got the right global: " + c); + } + + // Test Object in more detail. + var num = new iwin.Object(4); + is(Cu.waiveXrays(num).valueOf(), 4, "primitive object construction works"); + is(global(num), iwin, "correct global for num"); + var obj = new iwin.Object(); + obj.foo = 2; + var withProto = Cu.unwaiveXrays(Cu.waiveXrays(iwin).Object.create(obj)); + is(global(withProto), iwin, "correct global for withProto"); + is(Cu.waiveXrays(withProto).foo, 2, "Inherits properly"); + + // Test Function. + var primitiveFun = new iwin.Function('return 2'); + is(global(primitiveFun), iwin, "function construction works"); + is(primitiveFun(), 2, "basic function works"); + var doSetFoo = new iwin.Function('arg', 'arg.foo = 2;'); + is(global(doSetFoo), iwin, "function with args works"); + try { + doSetFoo(new Object()); + ok(false, "should have thrown while setting property on object"); + } catch (e) { + ok(!!/denied/.test(e), "Threw correctly: " + e); + } + var factoryFun = new iwin.Function('return {foo: 32}'); + is(global(factoryFun), iwin, "proper global for factoryFun"); + is(factoryFun().foo, 32, "factoryFun invokable"); + is(global(factoryFun()), iwin, "minted objects live in the content scope"); + testXray('Function', factoryFun, new iwin.Function(), ['length', 'name']); + var echoThis = new iwin.Function('return this;'); + echoThis.wrappedJSObject.bind = 42; + var boundEchoThis = echoThis.bind(document); + is(boundEchoThis(), document, "bind() works correctly over Xrays"); + is(global(boundEchoThis), window, "bound functions live in the caller's scope"); + ok(/return this/.test(echoThis.toSource()), 'toSource works: ' + echoThis.toSource()); + ok(/return this/.test(echoThis.toString()), 'toString works: ' + echoThis.toString()); + is(iwin.Function.prototype, Object.getPrototypeOf(echoThis), "Function.prototype works for standard classes"); + is(echoThis.prototype, undefined, "Function.prototype not visible for non standard constructors"); + iwin.eval('var foopyFunction = function namedFoopyFunction(a, b, c) {}'); + var foopyFunction = Cu.unwaiveXrays(Cu.waiveXrays(iwin).foopyFunction); + ok(Cu.isXrayWrapper(foopyFunction), "Should be Xrays"); + is(foopyFunction.name, "namedFoopyFunction", ".name works over Xrays"); + is(foopyFunction.length, 3, ".length works over Xrays"); + ok(Object.getOwnPropertyNames(foopyFunction).indexOf('length') >= 0, "Should list length"); + ok(Object.getOwnPropertyNames(foopyFunction).indexOf('name') >= 0, "Should list name"); + ok(Object.getOwnPropertyNames(foopyFunction).indexOf('prototype') == -1, "Should not list prototype"); + ok(Object.getOwnPropertyNames(iwin.Array).indexOf('prototype') >= 0, "Should list prototype for standard constructor"); + + // Test proxies. + var targetObject = new iwin.Object(); + targetObject.foo = 9; + var forwardingProxy = new iwin.Proxy(targetObject, new iwin.Object()); + is(global(forwardingProxy), iwin, "proxy global correct"); + is(Cu.waiveXrays(forwardingProxy).foo, 9, "forwards correctly"); + + // Test eval. + var toEval = "({a: 2, b: {foo: 'bar'}, f: function() { return window; }})"; + is(global(iwin.eval(toEval)), iwin, "eval creates objects in the correct global"); + is(iwin.eval(toEval).b.foo, 'bar', "eval-ed object looks right"); + is(Cu.waiveXrays(iwin.eval(toEval)).f(), Cu.waiveXrays(iwin), "evaled function works right"); + + testDate(); + + testObject(); + + testArray(); + + testTypedArrays(); + + testErrorObjects(); + + testRegExp(); + + testPromise(); + + testArrayBuffer(); + + // We could also test DataView and Iterator here for completeness, but it's + // more trouble than it's worth. + + SimpleTest.finish(); + } + + // Maintain a static list of the properties that are available on each standard + // prototype, so that we make sure to audit any new ones to make sure they're + // Xray-safe. + // + // DO NOT CHANGE WTIHOUT REVIEW FROM AN XPCONNECT PEER. + var version = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).version; + var isNightlyBuild = version.endsWith("a1"); + var isReleaseOrBeta = !version.includes("a"); + var gPrototypeProperties = {}; + var gConstructorProperties = {}; + function constructorProps(arr) { + // Some props live on all constructors + return arr.concat(["prototype", "length", "name"]); + } + gPrototypeProperties['Date'] = + ["getTime", "getTimezoneOffset", "getYear", "getFullYear", "getUTCFullYear", + "getMonth", "getUTCMonth", "getDate", "getUTCDate", "getDay", "getUTCDay", + "getHours", "getUTCHours", "getMinutes", "getUTCMinutes", "getSeconds", + "getUTCSeconds", "getMilliseconds", "getUTCMilliseconds", "setTime", + "setYear", "setFullYear", "setUTCFullYear", "setMonth", "setUTCMonth", + "setDate", "setUTCDate", "setHours", "setUTCHours", "setMinutes", + "setUTCMinutes", "setSeconds", "setUTCSeconds", "setMilliseconds", + "setUTCMilliseconds", "toUTCString", "toLocaleFormat", "toLocaleString", + "toLocaleDateString", "toLocaleTimeString", "toDateString", "toTimeString", + "toISOString", "toJSON", "toSource", "toString", "valueOf", "constructor", + "toGMTString", Symbol.toPrimitive]; + gConstructorProperties['Date'] = constructorProps(["UTC", "parse", "now"]); + gPrototypeProperties['Object'] = + ["constructor", "toSource", "toString", "toLocaleString", "valueOf", "watch", + "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", + "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__", + "__proto__"]; + gConstructorProperties['Object'] = + constructorProps(["setPrototypeOf", "getOwnPropertyDescriptor", "getOwnPropertyDescriptors", + "keys", "is", "defineProperty", "defineProperties", "create", + "getOwnPropertyNames", "getOwnPropertySymbols", + "preventExtensions", "freeze", "isFrozen", "seal", + "isSealed", "assign", "getPrototypeOf", "values", + "entries", "isExtensible"]) + gPrototypeProperties['Array'] = + ["length", "toSource", "toString", "toLocaleString", "join", "reverse", "sort", "push", + "pop", "shift", "unshift", "splice", "concat", "slice", "lastIndexOf", "indexOf", + "includes", "forEach", "map", "reduce", "reduceRight", "filter", "some", "every", "find", + "findIndex", "copyWithin", "fill", Symbol.iterator, Symbol.unscopables, "entries", "keys", + "constructor"]; + if (isNightlyBuild) { + gPrototypeProperties['Array'].push("values"); + } + gConstructorProperties['Array'] = + constructorProps(["join", "reverse", "sort", "push", "pop", "shift", + "unshift", "splice", "concat", "slice", "isArray", + "lastIndexOf", "indexOf", "forEach", "map", "filter", + "every", "some", "reduce", "reduceRight", "from", "of", + Symbol.species]); + for (var c of typedArrayClasses) { + gPrototypeProperties[c] = ["constructor", "BYTES_PER_ELEMENT"]; + gConstructorProperties[c] = constructorProps(["BYTES_PER_ELEMENT"]); + } + gPrototypeProperties['TypedArray'] = + ["length", "buffer", "byteLength", "byteOffset", Symbol.iterator, "subarray", + "set", "copyWithin", "find", "findIndex", "forEach","indexOf", "lastIndexOf", "includes", + "reverse", "join", "every", "some", "reduce", "reduceRight", "entries", "keys", "values", + "slice", "map", "filter"]; + // There is no TypedArray constructor, looks like. + is(window.TypedArray, undefined, "If this ever changes, add to this test!"); + for (var c of errorObjectClasses) { + gPrototypeProperties[c] = ["constructor", "name", + // We don't actually resolve these empty data properties + // onto the Xray prototypes, but we list them here to make + // the test happy. + "lineNumber", "columnNumber", "fileName", "message", "stack"]; + gConstructorProperties[c] = constructorProps([]); + } + // toString and toSource only live on the parent proto (Error.prototype). + gPrototypeProperties['Error'].push('toString'); + gPrototypeProperties['Error'].push('toSource'); + + gPrototypeProperties['Function'] = + ["constructor", "toSource", "toString", "apply", "call", "bind", + "isGenerator", "length", "name", "arguments", "caller", Symbol.hasInstance]; + gConstructorProperties['Function'] = constructorProps([]) + + gPrototypeProperties['RegExp'] = + ["constructor", "toSource", "toString", "compile", "exec", "test", + Symbol.match, Symbol.replace, Symbol.search, Symbol.split, + "flags", "global", "ignoreCase", "multiline", "source", "sticky", "unicode", + "lastIndex"]; + gConstructorProperties['RegExp'] = + constructorProps(["input", "lastMatch", "lastParen", + "leftContext", "rightContext", "$1", "$2", "$3", "$4", + "$5", "$6", "$7", "$8", "$9", "$_", "$&", "$+", + "$`", "$'", Symbol.species]) + + gPrototypeProperties['Promise'] = + ["constructor", "catch", "then", Symbol.toStringTag]; + gConstructorProperties['Promise'] = + constructorProps(["resolve", "reject", "all", "race", Symbol.species]); + + gPrototypeProperties['ArrayBuffer'] = + ["constructor", "byteLength", "slice", Symbol.toStringTag]; + gConstructorProperties['ArrayBuffer'] = + constructorProps(["isView", "slice", Symbol.species]); + + if (!isReleaseOrBeta) { + gPrototypeProperties['SharedArrayBuffer'] = ["constructor", "slice", "byteLength", Symbol.toStringTag]; + gConstructorProperties['SharedArrayBuffer'] = constructorProps([Symbol.species]); + } else { + is(typeof SharedArrayBuffer, "undefined", "Enable tests!"); + } + + // Sort an array that may contain symbols as well as strings. + function sortProperties(arr) { + function sortKey(prop) { + return typeof prop + ":" + prop.toString(); + } + arr.sort((a, b) => sortKey(a) < sortKey(b) ? -1 : +1); + } + + // Sort all the lists so we don't need to mutate them later (or copy them + // again to sort them). + for (var c of Object.keys(gPrototypeProperties)) + sortProperties(gPrototypeProperties[c]); + for (var c of Object.keys(gConstructorProperties)) + sortProperties(gConstructorProperties[c]); + + function filterOut(array, props) { + return array.filter(p => props.indexOf(p) == -1); + } + + function isTypedArrayClass(classname) { + return typedArrayClasses.indexOf(classname) >= 0; + } + + function propertyIsGetter(obj, name, classname) { + return !!Object.getOwnPropertyDescriptor(obj, name).get; + } + + function testProtoCallables(protoCallables, xray, xrayProto, localProto) { + for (let name of protoCallables) { + info("Running tests for property: " + name); + // Test both methods and getter properties. + function lookupCallable(obj) { + let desc = null; + do { + desc = Object.getOwnPropertyDescriptor(obj, name); + obj = Object.getPrototypeOf(obj); + } while (!desc); + return desc.get || desc.value; + }; + ok(xrayProto.hasOwnProperty(name), "proto should have the property as own"); + ok(!xray.hasOwnProperty(name), "instance should not have the property as own"); + let method = lookupCallable(xrayProto); + is(typeof method, 'function', "Methods from Xrays are functions"); + is(global(method), window, "Methods from Xrays are local"); + ok(method instanceof Function, "instanceof works on methods from Xrays"); + is(lookupCallable(xrayProto), method, "Holder caching works properly"); + is(lookupCallable(xray), method, "Proto props resolve on the instance"); + let local = lookupCallable(localProto); + is(method.length, local.length, "Function.length identical"); + if (method.length == 0) { + is(method.call(xray) + "", local.call(xray) + "", + "Xray and local method results stringify identically"); + + // If invoking this method returns something non-Xrayable, the + // stringification is going to return [object Opaque]. + ok(!/Opaque/.test(method.call(xray)), "Method result is xrayable"); + is(method.call(xray) + "", + lookupCallable(xray.wrappedJSObject).call(xray.wrappedJSObject) + "", + "Xray and waived method results stringify identically"); + } + } + } + + function testCtorCallables(ctorCallables, xrayCtor, localCtor) { + for (let name of ctorCallables) { + // Don't try to test Function.prototype, since that is in fact a callable + // but doesn't really do the things we expect callables to do here + // (e.g. it's in the wrong global, since it gets Xrayed itself). + if (name == "prototype" && localCtor.name == "Function") { + continue; + } + info(`Running tests for property: ${localCtor.name}.${name}`); + // Test both methods and getter properties. + function lookupCallable(obj) { + let desc = null; + do { + desc = Object.getOwnPropertyDescriptor(obj, name); + obj = Object.getPrototypeOf(obj); + } while (!desc); + return desc.get || desc.value; + }; + + ok(xrayCtor.hasOwnProperty(name), "ctor should have the property as own"); + let method = lookupCallable(xrayCtor); + is(typeof method, 'function', "Methods from ctor Xrays are functions"); + is(global(method), window, "Methods from ctor Xrays are local"); + ok(method instanceof Function, + "instanceof works on methods from ctor Xrays"); + is(lookupCallable(xrayCtor), method, + "Holder caching works properly on ctors"); + let local = lookupCallable(localCtor); + is(method.length, local.length, + "Function.length identical for method from ctor"); + // Don't try to do the return-value check on Date.now(), since there is + // absolutely no reason it should return the same value each time. + // + // Also don't try to do the return-value check on Regexp.lastMatch and + // Regexp["$&"] (which are aliases), because they get state off the global + // they live in, as far as I can tell, so testing them over Xrays will be + // wrong: on the Xray they will actaully get the lastMatch of _our_ + // global, not the Xrayed one. + if (method.length == 0 && + !(localCtor.name == "Date" && name == "now") && + !(localCtor.name == "RegExp" && (name == "lastMatch" || name == "$&"))) { + is(method.call(xrayCtor) + "", local.call(xrayCtor) + "", + "Xray and local method results stringify identically on constructors"); + is(method.call(xrayCtor) + "", + lookupCallable(xrayCtor.wrappedJSObject).call(xrayCtor.wrappedJSObject) + "", + "Xray and waived method results stringify identically"); + } + } + } + + function testXray(classname, xray, xray2, propsToSkip, ctorPropsToSkip = []) { + propsToSkip = propsToSkip || []; + let xrayProto = Object.getPrototypeOf(xray); + let localProto = window[classname].prototype; + let desiredProtoProps = Object.getOwnPropertyNames(localProto).sort(); + + is(desiredProtoProps.toSource(), + gPrototypeProperties[classname].filter(id => typeof id === "string").toSource(), + "A property on the " + classname + + " prototype has changed! You need a security audit from an XPConnect peer"); + is(Object.getOwnPropertySymbols(localProto).map(uneval).sort().toSource(), + gPrototypeProperties[classname].filter(id => typeof id !== "string").map(uneval).sort().toSource(), + "A symbol-keyed property on the " + classname + + " prototype has been changed! You need a security audit from an XPConnect peer"); + + let protoProps = filterOut(desiredProtoProps, propsToSkip); + let protoCallables = protoProps.filter(name => propertyIsGetter(localProto, name, classname) || + typeof localProto[name] == 'function' && + name != 'constructor'); + ok(protoCallables.length > 0, "Need something to test"); + is(xrayProto, iwin[classname].prototype, "Xray proto is correct"); + is(xrayProto, xray.__proto__, "Proto accessors agree"); + var protoProto = classname == "Object" ? null : iwin.Object.prototype; + is(Object.getPrototypeOf(xrayProto), protoProto, "proto proto is correct"); + testProtoCallables(protoCallables, xray, xrayProto, localProto); + is(Object.getOwnPropertyNames(xrayProto).sort().toSource(), + protoProps.toSource(), "getOwnPropertyNames works"); + is(Object.getOwnPropertySymbols(xrayProto).map(uneval).sort().toSource(), + gPrototypeProperties[classname].filter(id => typeof id !== "string" && !propsToSkip.includes(id)) + .map(uneval).sort().toSource(), + "getOwnPropertySymbols works"); + + is(xrayProto.constructor, iwin[classname], "constructor property works"); + + xrayProto.expando = 42; + is(xray.expando, 42, "Xrayed instances see proto expandos"); + is(xray2.expando, 42, "Xrayed instances see proto expandos"); + + // Now test constructors + localCtor = window[classname]; + xrayCtor = xrayProto.constructor; + // We already checked that this is the same as iwin[classname] + + let desiredCtorProps = + Object.getOwnPropertyNames(localCtor).sort(); + is(desiredCtorProps.toSource(), + gConstructorProperties[classname].filter(id => typeof id === "string").toSource(), + "A property on the " + classname + + " constructor has changed! You need a security audit from an XPConnect peer"); + let desiredCtorSymbols = + Object.getOwnPropertySymbols(localCtor).map(uneval).sort() + is(desiredCtorSymbols.toSource(), + gConstructorProperties[classname].filter(id => typeof id !== "string").map(uneval).sort().toSource(), + "A symbol-keyed property on the " + classname + + " constructor has been changed! You need a security audit from an XPConnect peer"); + + let ctorProps = filterOut(desiredCtorProps, ctorPropsToSkip); + let ctorSymbols = filterOut(desiredCtorSymbols, ctorPropsToSkip.map(uneval)); + let ctorCallables = ctorProps.filter(name => propertyIsGetter(localCtor, name, classname) || + typeof localCtor[name] == 'function'); + testCtorCallables(ctorCallables, xrayCtor, localCtor); + is(Object.getOwnPropertyNames(xrayCtor).sort().toSource(), + ctorProps.toSource(), "getOwnPropertyNames works on Xrayed ctors"); + is(Object.getOwnPropertySymbols(xrayCtor).map(uneval).sort().toSource(), + ctorSymbols.toSource(), "getOwnPropertySymbols works on Xrayed ctors"); + } + + // We will need arraysEqual and testArrayIterators both in this global scope + // and in sandboxes, so define them as strings up front. + var arraysEqualSource = `function arraysEqual(arr1, arr2, reason) { + is(arr1.length, arr2.length, \`\${reason}; lengths should be equal\`) + for (var i = 0; i < arr1.length; ++i) { + if (Array.isArray(arr2[i])) { + arraysEqual(arr1[i], arr2[i], \`\${reason}; item at index \${i}\`); + } else { + is(arr1[i], arr2[i], \`\${reason}; item at index \${i} should be equal\`); + } + } + }`; + eval(arraysEqualSource); + + var testArrayIteratorsSource = ` + function testArrayIterators(arrayLike, equivalentArray, reason) { + arraysEqual([...arrayLike], equivalentArray, \`\${reason}; spread operator\`); + arraysEqual([...arrayLike.entries()], [...equivalentArray.entries()], + \`\${reason}; entries\`); + arraysEqual([...arrayLike.keys()], [...equivalentArray.keys()], + \`\${reason}; keys\`); + if (arrayLike.values) { + arraysEqual([...arrayLike.values()], equivalentArray, + \`\${reason}; values\`); + } + + var forEachCopy = []; + arrayLike.forEach(function(arg) { forEachCopy.push(arg); }); + arraysEqual(forEachCopy, equivalentArray, \`\${reason}; forEach copy\`); + + var everyCopy = []; + arrayLike.every(function(arg) { everyCopy.push(arg); return true; }); + arraysEqual(everyCopy, equivalentArray, \`\${reason}; every() copy\`); + + var filterCopy = []; + var filterResult = arrayLike.filter(function(arg) { + filterCopy.push(arg); + return true; + }); + arraysEqual(filterCopy, equivalentArray, \`\${reason}; filter copy\`); + arraysEqual([...filterResult], equivalentArray, \`\${reason}; filter result\`); + + var findCopy = []; + arrayLike.find(function(arg) { findCopy.push(arg); return false; }); + arraysEqual(findCopy, equivalentArray, \`\${reason}; find() copy\`); + + var findIndexCopy = []; + arrayLike.findIndex(function(arg) { findIndexCopy.push(arg); return false; }); + arraysEqual(findIndexCopy, equivalentArray, \`\${reason}; findIndex() copy\`); + + var mapCopy = []; + var mapResult = arrayLike.map(function(arg) { mapCopy.push(arg); return arg}); + arraysEqual(mapCopy, equivalentArray, \`\${reason}; map() copy\`); + arraysEqual([...mapResult], equivalentArray, \`\${reason}; map() result\`); + + var reduceCopy = []; + arrayLike.reduce(function(_, arg) { reduceCopy.push(arg); }, 0); + arraysEqual(reduceCopy, equivalentArray, \`\${reason}; reduce() copy\`); + + var reduceRightCopy = []; + arrayLike.reduceRight(function(_, arg) { reduceRightCopy.unshift(arg); }, 0); + arraysEqual(reduceRightCopy, equivalentArray, \`\${reason}; reduceRight() copy\`); + + var someCopy = []; + arrayLike.some(function(arg) { someCopy.push(arg); return false; }); + arraysEqual(someCopy, equivalentArray, \`\${reason}; some() copy\`); + }`; + eval(testArrayIteratorsSource); + + function testDate() { + // toGMTString is handled oddly in the engine. We don't bother to support + // it over Xrays. + let propsToSkip = ['toGMTString']; + + testXray('Date', new iwin.Date(), new iwin.Date(), propsToSkip); + + // Test the self-hosted toLocaleString. + var d = new iwin.Date(); + isnot(d.toLocaleString, Cu.unwaiveXrays(d.wrappedJSObject.toLocaleString), "Different function identities"); + is(Cu.getGlobalForObject(d.toLocaleString), window, "Xray global is correct"); + is(Cu.getGlobalForObject(d.wrappedJSObject.toLocaleString), iwin, "Underlying global is correct"); + is(d.toLocaleString('de-DE'), d.wrappedJSObject.toLocaleString('de-DE'), "Results match"); + } + + var uniqueSymbol; + + function testObject() { + testXray('Object', Cu.unwaiveXrays(Cu.waiveXrays(iwin).Object.create(new iwin.Object())), + new iwin.Object(), []); + + // Construct an object full of tricky things. + let symbolProps = ''; + uniqueSymbol = iwin.eval('var uniqueSymbol = Symbol("uniqueSymbol"); uniqueSymbol'); + symbolProps = `, [uniqueSymbol]: 43, + [Symbol.for("registrySymbolProp")]: 44`; + var trickyObject = + iwin.eval(`(function() { + var o = new Object({ + primitiveProp: 42, objectProp: { foo: 2 }, + xoProp: top, hasOwnProperty: 10, + get getterProp() { return 2; }, + set setterProp(x) { }, + get getterSetterProp() { return 3; }, + set getterSetterProp(x) { }, + callableProp: function() { }, + nonXrayableProp: new WeakMap() + ${symbolProps} + }); + Object.defineProperty(o, "nonConfigurableGetterSetterProp", + { get: function() { return 5; }, set: function() {} }); + return o; + })()`); + testTrickyObject(trickyObject); + } + + function testArray() { + // The |length| property is generally very weird, especially with respect + // to its behavior on the prototype. Array.prototype is actually an Array + // instance, and therefore has a vestigial .length. But we don't want to + // show that over Xrays, and generally want .length to just appear as an + // |own| data property. So we add it to the ignore list here, and check it + // separately. + // + // |Symbol.unscopables| should in principle be exposed, but it is + // inconvenient (as it's a data property, unsupported by ClassSpec) and + // low value. + let propsToSkip = ['length', Symbol.unscopables]; + + testXray('Array', new iwin.Array(20), new iwin.Array(), propsToSkip); + + let symbolProps = ''; + uniqueSymbol = iwin.eval('var uniqueSymbol = Symbol("uniqueSymbol"); uniqueSymbol'); + symbolProps = `trickyArray[uniqueSymbol] = 43; + trickyArray[Symbol.for("registrySymbolProp")] = 44;`; + var trickyArray = + iwin.eval(`var trickyArray = []; + trickyArray.primitiveProp = 42; + trickyArray.objectProp = { foo: 2 }; + trickyArray.xoProp = top; + trickyArray.hasOwnProperty = 10; + Object.defineProperty(trickyArray, 'getterProp', { get: function() { return 2; }}); + Object.defineProperty(trickyArray, 'setterProp', { set: function(x) {}}); + Object.defineProperty(trickyArray, 'getterSetterProp', { get: function() { return 3; }, set: function(x) {}, configurable: true}); + Object.defineProperty(trickyArray, 'nonConfigurableGetterSetterProp', { get: function() { return 5; }, set: function(x) {}}); + trickyArray.callableProp = function() {}; + trickyArray.nonXrayableProp = new WeakMap(); + ${symbolProps} + trickyArray;`); + + // Test indexed access. + trickyArray.wrappedJSObject[9] = "some indexed property"; + is(trickyArray[9], "some indexed property", "indexed properties work correctly over Xrays"); + is(trickyArray.length, 10, "Length works correctly over Xrays"); + checkThrows(function() { "use strict"; delete trickyArray.length; }, /config/, "Can't delete non-configurable 'length' property"); + delete trickyArray[9]; + is(trickyArray[9], undefined, "Delete works correctly over Xrays"); + is(trickyArray.wrappedJSObject[9], undefined, "Delete works correctly over Xrays (viewed via waiver)"); + is(trickyArray.length, 10, "length doesn't change"); + trickyArray[11] = "some other indexed property"; + is(trickyArray.length, 12, "length now changes"); + is(trickyArray.wrappedJSObject[11], "some other indexed property"); + trickyArray.length = 0; + is(trickyArray.length, 0, "Setting length works over Xray"); + is(trickyArray[11], undefined, "Setting length truncates over Xray"); + Object.defineProperty(trickyArray, 'length', { configurable: false, enumerable: false, writable: false, value: 0 }); + trickyArray[1] = "hi"; + is(trickyArray.length, 0, "Length remains non-writable"); + is(trickyArray[1], undefined, "Frozen length forbids new properties"); + is(trickyArray instanceof iwin.Array, true, "instanceof should work across xray wrappers."); + testTrickyObject(trickyArray); + + testArrayIterators(new iwin.Array(1, 1, 2, 3, 5), [1, 1, 2, 3, 5]); + } + + // Parts of this function are kind of specific to testing Object, but we factor + // it out so that we can re-use the trickyObject stuff on Arrays. + function testTrickyObject(trickyObject) { + + // Make sure it looks right under the hood. + is(trickyObject.wrappedJSObject.getterProp, 2, "Underlying object has getter"); + is(Cu.unwaiveXrays(trickyObject.wrappedJSObject.xoProp), top, "Underlying object has xo property"); + + // Test getOwnPropertyNames. + var expectedNames = ['objectProp', 'primitiveProp']; + if (trickyObject instanceof iwin.Array) + expectedNames.push('length'); + is(Object.getOwnPropertyNames(trickyObject).sort().toSource(), + expectedNames.sort().toSource(), "getOwnPropertyNames should be filtered correctly"); + var expectedSymbols = [Symbol.for("registrySymbolProp"), uniqueSymbol]; + is(Object.getOwnPropertySymbols(trickyObject).map(uneval).sort().toSource(), + expectedSymbols.map(uneval).sort().toSource(), + "getOwnPropertySymbols should be filtered correctly"); + + // Test that cloning uses the Xray view. + var cloned = Cu.cloneInto(trickyObject, this); + is(Object.getOwnPropertyNames(cloned).sort().toSource(), + expectedNames.sort().toSource(), "structured clone should use the Xray view"); + is(Object.getOwnPropertySymbols(cloned).map(uneval).sort().toSource(), + "[]", "structured cloning doesn't clone symbol-keyed properties yet"); + + // Test iteration and in-place modification. Beware of 'expando', which is the property + // we placed on the xray proto. + var propCount = 0; + for (let prop in trickyObject) { + if (prop == 'primitiveProp') + trickyObject[prop] = trickyObject[prop] - 10; + if (prop != 'expando') + trickyObject[prop] = trickyObject[prop]; + ++propCount; + } + is(propCount, 3, "Should iterate the correct number of times"); + + // Test Object.keys. + is(Object.keys(trickyObject).sort().toSource(), + ['objectProp', 'primitiveProp'].toSource(), "Object.keys should be filtered correctly"); + + // Test getOwnPropertyDescriptor. + is(trickyObject.primitiveProp, 32, "primitive prop works"); + is(trickyObject.objectProp.foo, 2, "object prop works"); + is(typeof trickyObject.callableProp, 'undefined', "filtering works correctly"); + is(Object.getOwnPropertyDescriptor(trickyObject, 'primitiveProp').value, 32, "getOwnPropertyDescriptor works"); + is(Object.getOwnPropertyDescriptor(trickyObject, 'xoProp'), undefined, "filtering works with getOwnPropertyDescriptor"); + + // Test defineProperty. + + trickyObject.primitiveSetByXray = 'fourty two'; + is(trickyObject.primitiveSetByXray, 'fourty two', "Can set primitive correctly over Xray (ready via Xray)"); + is(trickyObject.wrappedJSObject.primitiveSetByXray, 'fourty two', "Can set primitive correctly over Xray (ready via Waiver)"); + + var newContentObject = iwin.eval('new Object({prop: 99, get getterProp() { return 2; }})'); + trickyObject.objectSetByXray = newContentObject; + is(trickyObject.objectSetByXray.prop, 99, "Can set object correctly over Xray (ready via Xray)"); + is(trickyObject.wrappedJSObject.objectSetByXray.prop, 99, "Can set object correctly over Xray (ready via Waiver)"); + checkThrows(function() { trickyObject.rejectedProp = {foo: 33}}, /cross-origin object/, + "Should reject privileged object property definition"); + + // Test JSON.stringify. + var jsonStr = JSON.stringify(newContentObject); + ok(/prop/.test(jsonStr), "JSON stringification should work: " + jsonStr); + + // Test deletion. + delete newContentObject.prop; + ok(!newContentObject.hasOwnProperty('prop'), "Deletion should work"); + ok(!newContentObject.wrappedJSObject.hasOwnProperty('prop'), "Deletion should forward"); + delete newContentObject.getterProp; + ok(newContentObject.wrappedJSObject.hasOwnProperty('getterProp'), "Deletion be no-op for filtered property"); + + // We should be able to overwrite an existing accessor prop and convert it + // to a value prop. + is(trickyObject.wrappedJSObject.getterSetterProp, 3, "Underlying object has getter"); + is(trickyObject.getterSetterProp, undefined, "Filtering properly over Xray"); + trickyObject.getterSetterProp = 'redefined'; + is(trickyObject.getterSetterProp, 'redefined', "Redefinition works"); + is(trickyObject.wrappedJSObject.getterSetterProp, 'redefined', "Redefinition forwards"); + + // We should NOT be able to overwrite an existing non-configurable accessor + // prop, though. + is(trickyObject.wrappedJSObject.nonConfigurableGetterSetterProp, 5, + "Underlying object has getter"); + is(trickyObject.nonConfigurableGetterSetterProp, undefined, + "Filtering properly over Xray here too"); + is((trickyObject.nonConfigurableGetterSetterProp = 'redefined'), 'redefined', + "Assigning to non-configurable prop should fail silently in non-strict mode"); + checkThrows(function() { + "use strict"; + trickyObject.nonConfigurableGetterSetterProp = 'redefined'; + }, /config/, "Should throw when redefining non-configurable prop in strict mode"); + is(trickyObject.nonConfigurableGetterSetterProp, undefined, + "Redefinition should have failed"); + is(trickyObject.wrappedJSObject.nonConfigurableGetterSetterProp, 5, + "Redefinition really should have failed"); + + checkThrows(function() { trickyObject.hasOwnProperty = 33; }, /shadow/, + "Should reject shadowing of pre-existing inherited properties over Xrays"); + + checkThrows(function() { Object.defineProperty(trickyObject, 'rejectedProp', { get: function() {}}); }, + /accessor property/, "Should reject accessor property definition"); + } + + function testTypedArrays() { + // We don't invoke testXray with %TypedArray%, because that function isn't + // set up to deal with "anonymous" dependent classes (that is, classes not + // visible as a global property, which %TypedArray% is not), and fixing it + // up is more trouble than it's worth. + + var typedArrayProto = Object.getPrototypeOf(Int8Array.prototype); + + var desiredInheritedProps = Object.getOwnPropertyNames(typedArrayProto).sort(); + var inheritedProps = + filterOut(desiredInheritedProps, ["BYTES_PER_ELEMENT", "constructor"]); + + var inheritedCallables = + inheritedProps.filter(name => (propertyIsGetter(typedArrayProto, name) || + typeof typedArrayProto[name] === "function") && + name !== "constructor"); + + for (var c of typedArrayClasses) { + var t = new iwin[c](10); + checkThrows(function() { t[2]; }, /performant/, "direct property-wise reading of typed arrays forbidden over Xrays"); + checkThrows(function() { t[2] = 3; }, /performant/, "direct property-wise writing of typed arrays forbidden over Xrays"); + var wesb = new Cu.Sandbox([iwin], {isWebExtensionContentScript: true}); + wesb.t = t; + wesb.eval('t[2] = 3'); + is(wesb.eval('t.wrappedJSObject[2]'), 3, "direct property-wise writing of typed arrays allowed for WebExtension content scripts"); + is(wesb.eval('t[2]'), 3, "direct property-wise reading and writing of typed arrays allowed for WebExtensions content scripts"); + + t.wrappedJSObject[2] = 3; + is(t.wrappedJSObject[2], 3, "accessing elements over waivers works"); + t.wrappedJSObject.expando = 'hi'; + is(t.wrappedJSObject.expando, 'hi', "access expandos over waivers works"); + is(Cu.cloneInto(t, window)[2], 3, "cloneInto works"); + is(Cu.cloneInto(t, window).expando, undefined, "cloneInto does not copy expandos"); + is(Object.getOwnPropertyNames(t).sort().toSource(), + '["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]', + "Only indexed properties visible over Xrays"); + Object.defineProperty(t.wrappedJSObject, 'length', {value: 42}); + is(t.wrappedJSObject.length, 42, "Set tricky expando") + is(t.length, 10, "Length accessor works over Xrays") + is(t.byteLength, t.length * window[c].prototype.BYTES_PER_ELEMENT, "byteLength accessor works over Xrays") + + // Can create TypedArray from content ArrayBuffer + var buffer = new iwin.ArrayBuffer(8); + eval(`new ${c}(buffer);`); + + var xray = new iwin[c](0); + var xrayTypedArrayProto = Object.getPrototypeOf(Object.getPrototypeOf(xray)); + testProtoCallables(inheritedCallables, new iwin[c](0), xrayTypedArrayProto, typedArrayProto); + + // When testing iterators, make sure to do so from inside our web + // extension sandbox, since from chrome we can't poke their indices. Note + // that we have to actually recreate our functions that touch typed array + // indices inside the sandbox, not just export them, because otherwise + // they'll just run with our principal anyway. + // + // But we do want to export is(), since we want ours called. + wesb.eval(arraysEqualSource); + wesb.eval(testArrayIteratorsSource); + Cu.exportFunction(is, wesb, + { defineAs: "is" }); + wesb.eval('testArrayIterators(t, [0, 0, 3, 0, 0, 0, 0, 0, 0, 0])'); + } + } + + function testErrorObjects() { + // We only invoke testXray with Error, because that function isn't set up + // to deal with dependent classes and fixing it up is more trouble than + // it's worth. + testXray('Error', new iwin.Error('some error message'), new iwin.Error(), + ['fileName', 'lineNumber', 'columnNumber', 'message']); + + // Make sure that the dependent classes have their prototypes set up correctly. + for (let c of errorObjectClasses.filter(x => x != "Error")) { + var e = new iwin[c]('some message'); + is(Object.getPrototypeOf(e).name, c, "Prototype has correct name"); + is(Object.getPrototypeOf(Object.getPrototypeOf(e)), iwin.Error.prototype, "Dependent prototype set up correctly"); + is(e.name, c, "Exception name inherited correctly"); + + function testProperty(name, criterion, goodReplacement, faultyReplacement) { + ok(criterion(e[name]), name + " property is correct: " + e[name]); + e.wrappedJSObject[name] = goodReplacement; + is(e[name], goodReplacement, name + " property ok after replacement: " + goodReplacement); + e.wrappedJSObject[name] = faultyReplacement; + is(e[name], undefined, name + " property censored after suspicious replacement"); + } + testProperty('message', x => x == 'some message', 'some other message', 42); + testProperty('fileName', x => x == '', 'otherFilename.html', new iwin.Object()); + testProperty('columnNumber', x => x == 1, 99, 99.5); + testProperty('lineNumber', x => x == 0, 50, 'foo'); + + // Note - an Exception newed via Xrays is going to have an empty stack given the + // current semantics and implementation. This tests the current behavior, but that + // may change in bug 1036527 or similar. + // + // Furthermore, xrays should always return an error's original stack, and + // not overwrite it. + var stack = e.stack; + ok(/^\s*$/.test(stack), "stack property should be correct"); + e.wrappedJSObject.stack = "not a stack"; + is(e.stack, stack, "Xrays should never get an overwritten stack property."); + } + } + + function testRegExp() { + // RegExp statics are very weird, and in particular RegExp has static + // properties that have to do with the last regexp execution in the global. + // Xraying those makes no sense, so we just skip constructor properties for + // RegExp xrays. + // RegExp[@@species] is affected by above skip, but we don't fix it until + // compelling use-case appears, as supporting RegExp[@@species] while + // skipping other static properties makes things complicated. + let ctorPropsToSkip = ["input", "lastMatch", "lastParen", + "leftContext", "rightContext", "$1", "$2", "$3", + "$4", "$5", "$6", "$7", "$8", "$9", "$_", "$&", + "$+", "$`", "$'", Symbol.species]; + testXray('RegExp', new iwin.RegExp('foo'), new iwin.RegExp(), [], + ctorPropsToSkip); + + // Test the self-hosted |flags| property, toString, and toSource. + for (var flags of ["", "g", "i", "m", "y", "gimy"]) { + var re = new iwin.RegExp("foo", flags); + is(re.flags, re.wrappedJSObject.flags, "Results match"); + + isnot(re.toString, Cu.unwaiveXrays(re.wrappedJSObject.toString), "Different function identities"); + is(Cu.getGlobalForObject(re.toString), window, "Xray global is correct"); + is(Cu.getGlobalForObject(re.wrappedJSObject.toString), iwin, "Underlying global is correct"); + is(re.toString(), re.wrappedJSObject.toString(), "Results match"); + + isnot(re.toSource, Cu.unwaiveXrays(re.wrappedJSObject.toSource), "Different function identities"); + is(Cu.getGlobalForObject(re.toSource), window, "Xray global is correct"); + is(Cu.getGlobalForObject(re.wrappedJSObject.toSource), iwin, "Underlying global is correct"); + is(re.toSource(), re.wrappedJSObject.toSource(), "Results match"); + + // Test with modified flags accessors + iwin.eval(` +var props = ["global", "ignoreCase", "multiline", "sticky", "source", "unicode"]; +var origDescs = {}; +for (var prop of props) { + origDescs[prop] = Object.getOwnPropertyDescriptor(RegExp.prototype, prop); + Object.defineProperty(RegExp.prototype, prop, { + get: function() { + throw new Error("modified accessor is called"); + } + }); +} +`); + try { + is(re.flags, flags, "Unmodified flags accessors are called"); + is(re.toString(), "/foo/" + flags, "Unmodified flags and source accessors are called"); + is(re.toSource(), "/foo/" + flags, "Unmodified flags and source accessors are called"); + } finally { + iwin.eval(` +for (var prop of props) { + Object.defineProperty(RegExp.prototype, prop, origDescs[prop]); +} +`); + } + } + } + + // Note: this is a small set of basic tests. More in-depth tests are located + // in test_promise_xrays.html. + function testPromise() { + testXray('Promise', new iwin.Promise(function(){}), new iwin.Promise(function(){})); + + // Test catch and then. + var pr = new iwin.Promise(function(){}); + isnot(pr.catch, Cu.unwaiveXrays(pr.wrappedJSObject.catch), "Different function identities"); + is(Cu.getGlobalForObject(pr.catch), window, "Xray global is correct"); + is(Cu.getGlobalForObject(pr.wrappedJSObject.catch), iwin, "Underlying global is correct"); + + isnot(pr.then, Cu.unwaiveXrays(pr.wrappedJSObject.then), "Different function identities"); + is(Cu.getGlobalForObject(pr.then), window, "Xray global is correct"); + is(Cu.getGlobalForObject(pr.wrappedJSObject.then), iwin, "Underlying global is correct"); + } + + function testArrayBuffer() { + let constructors = ['ArrayBuffer']; + + if (!isReleaseOrBeta) { + constructors.push('SharedArrayBuffer'); + } + + for (const c of constructors) { + testXray(c, new iwin[c](0), new iwin[c](12)); + + var t = new iwin[c](12); + is(t.byteLength, 12, `${c} byteLength is correct`); + + is(t.slice(4).byteLength, 8, `${c} byteLength is correct after slicing`); + is(Cu.getGlobalForObject(t.slice(4)), iwin, "Slice results lives in the target compartment"); + is(Object.getPrototypeOf(t.slice(4)), iwin[c].prototype, "Slice results proto lives in target compartment") + + // SharedArrayBuffer does not have static slice method + if (c === 'ArrayBuffer') { + is(ArrayBuffer.slice(t, 4).byteLength, 8, `${c}.slice (deprecated) works`); + } + + var i32Array = new Int32Array(t); + // i32Array is going to be created in the buffer's target compartment, + // but usually this is unobservable, because the proto is set to + // the current compartment's prototype. + // However Xrays ignore the object's proto and claim its proto is + // the default proto for that class in the relevant compartment, + // so see through this proto hack. + todo_is(Object.getPrototypeOf(i32Array), Int32Array.prototype, "Int32Array has correct proto"); + is(i32Array.length, 3, `Int32Array created from Xray ${c} has the correct length`); + is(i32Array.buffer, t, "Int32Array has the correct buffer that we passed in"); + + i32Array = new iwin.Int32Array(t); + is(Object.getPrototypeOf(i32Array), iwin.Int32Array.prototype, "Xray Int32Array has correct proto"); + is(i32Array.length, 3, `Xray Int32Array created from Xray ${c} has the correct length`); + is(i32Array.buffer, t, "Xray Int32Array has the correct buffer that we passed in"); + + t = (new iwin.Int32Array(2)).buffer; + is(t.byteLength, 8, `Can access ${c} returned by buffer property`); + } + } + + ]]> + </script> + <iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html" /> +</window> diff --git a/js/xpconnect/tests/chrome/utf8_subscript.js b/js/xpconnect/tests/chrome/utf8_subscript.js new file mode 100644 index 000000000..d4051b1a8 --- /dev/null +++ b/js/xpconnect/tests/chrome/utf8_subscript.js @@ -0,0 +1,3 @@ +// -*- coding: utf-8; indent-tabs-mode: nil -*- +var str = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; +function f() { return 42; } diff --git a/js/xpconnect/tests/chrome/worker_discardSystemSource.js b/js/xpconnect/tests/chrome/worker_discardSystemSource.js new file mode 100644 index 000000000..9274505ee --- /dev/null +++ b/js/xpconnect/tests/chrome/worker_discardSystemSource.js @@ -0,0 +1,5 @@ +function canary() { + var someBitOfSource = 42; +} + +postMessage(canary.toSource()); diff --git a/js/xpconnect/tests/components/js/xpctest.manifest b/js/xpconnect/tests/components/js/xpctest.manifest new file mode 100644 index 000000000..ba28bf141 --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest.manifest @@ -0,0 +1,28 @@ +component {8ff41d9c-66e9-4453-924a-7d8de0a5e966} xpctest_attributes.js +contract @mozilla.org/js/xpc/test/js/ObjectReadWrite;1 {8ff41d9c-66e9-4453-924a-7d8de0a5e966} + +component {916c4247-253d-4ed0-a425-adfedf53ecc8} xpctest_attributes.js +contract @mozilla.org/js/xpc/test/js/ObjectReadOnly;1 {916c4247-253d-4ed0-a425-adfedf53ecc8} + +component {2df46559-da21-49bf-b863-0d7b7bbcbc73} xpctest_bug809674.js +contract @mozilla.org/js/xpc/test/js/Bug809674;1 {2df46559-da21-49bf-b863-0d7b7bbcbc73} + +component {e3b86f4e-49c0-487c-a2b0-3a986720a044} xpctest_params.js +contract @mozilla.org/js/xpc/test/js/Params;1 {e3b86f4e-49c0-487c-a2b0-3a986720a044} + +component {3c8fd2f5-970c-42c6-b5dd-cda1c16dcfd8} xpctest_interfaces.js +contract @mozilla.org/js/xpc/test/js/InterfaceA;1 {3c8fd2f5-970c-42c6-b5dd-cda1c16dcfd8} + +component {ff528c3a-2410-46de-acaa-449aa6403a33} xpctest_interfaces.js +contract @mozilla.org/js/xpc/test/js/InterfaceB;1 {ff528c3a-2410-46de-acaa-449aa6403a33} + +component {90ec5c9e-f6da-406b-9a38-14d00f59db76} xpctest_interfaces.js +contract @mozilla.org/js/xpc/test/js/TestInterfaceAll;1 {90ec5c9e-f6da-406b-9a38-14d00f59db76} + +component {38dd78aa-467f-4fad-8dcf-4383a743e235} xpctest_returncode_child.js +contract @mozilla.org/js/xpc/test/js/ReturnCodeChild;1 {38dd78aa-467f-4fad-8dcf-4383a743e235} + +component {e86573c4-a384-441a-8c92-7b99e8575b28} xpctest_utils.js +contract @mozilla.org/js/xpc/test/js/TestUtils;1 {e86573c4-a384-441a-8c92-7b99e8575b28} + +interfaces xpctest.xpt diff --git a/js/xpconnect/tests/components/js/xpctest_attributes.js b/js/xpconnect/tests/components/js/xpctest_attributes.js new file mode 100644 index 000000000..6576f9d55 --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest_attributes.js @@ -0,0 +1,48 @@ +/* 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/. */ +Components.utils.import("resource:///modules/XPCOMUtils.jsm"); + +function TestObjectReadWrite() {} +TestObjectReadWrite.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestObjectReadWrite"]]), + contractID: "@mozilla.org/js/xpc/test/js/ObjectReadWrite;1", + classID: Components.ID("{8ff41d9c-66e9-4453-924a-7d8de0a5e966}"), + + /* nsIXPCTestObjectReadWrite */ + stringProperty: "XPConnect Read-Writable String", + booleanProperty: true, + shortProperty: 32767, + longProperty: 2147483647, + floatProperty: 5.5, + charProperty: "X", + // timeProperty is PRTime and signed type. + // So it has to allow negative value. + timeProperty: -1 +}; + + +function TestObjectReadOnly() {} +TestObjectReadOnly.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestObjectReadOnly"]]), + contractID: "@mozilla.org/js/xpc/test/js/ObjectReadOnly;1", + classID: Components.ID("{916c4247-253d-4ed0-a425-adfedf53ecc8}"), + + /* nsIXPCTestObjectReadOnly */ + strReadOnly: "XPConnect Read-Only String", + boolReadOnly: true, + shortReadOnly: 32767, + longReadOnly: 2147483647, + floatReadOnly: 5.5, + charReadOnly: "X", + // timeProperty is PRTime and signed type. + // So it has to allow negative value. + timeReadOnly: -1 +}; + + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TestObjectReadWrite, TestObjectReadOnly]); diff --git a/js/xpconnect/tests/components/js/xpctest_bug809674.js b/js/xpconnect/tests/components/js/xpctest_bug809674.js new file mode 100644 index 000000000..4f018c128 --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest_bug809674.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/. */ +Components.utils.import("resource:///modules/XPCOMUtils.jsm"); + +function TestBug809674() {} +TestBug809674.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestBug809674"]]), + contractID: "@mozilla.org/js/xpc/test/js/Bug809674;1", + classID: Components.ID("{2df46559-da21-49bf-b863-0d7b7bbcbc73}"), + + /* nsIXPCTestBug809674 */ + jsvalProperty: {}, +}; + + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TestBug809674]); diff --git a/js/xpconnect/tests/components/js/xpctest_interfaces.js b/js/xpconnect/tests/components/js/xpctest_interfaces.js new file mode 100644 index 000000000..37d2eb407 --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest_interfaces.js @@ -0,0 +1,48 @@ +/* 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/. */ +Components.utils.import("resource:///modules/XPCOMUtils.jsm"); + +function TestInterfaceA() {} +TestInterfaceA.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestInterfaceA"]]), + contractID: "@mozilla.org/js/xpc/test/js/TestInterfaceA;1", + classID: Components.ID("{3c8fd2f5-970c-42c6-b5dd-cda1c16dcfd8}"), + + /* nsIXPCTestInterfaceA */ + name: "TestInterfaceADefaultName" +}; + +function TestInterfaceB() {} +TestInterfaceB.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestInterfaceB"]]), + contractID: "@mozilla.org/js/xpc/test/js/TestInterfaceB;1", + classID: Components.ID("{ff528c3a-2410-46de-acaa-449aa6403a33}"), + + /* nsIXPCTestInterfaceA */ + name: "TestInterfaceADefaultName" +}; + +function TestInterfaceAll() {} +TestInterfaceAll.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestInterfaceA"], + Components.interfaces["nsIXPCTestInterfaceB"], + Components.interfaces["nsIXPCTestInterfaceC"]]), + contractID: "@mozilla.org/js/xpc/test/js/TestInterfaceAll;1", + classID: Components.ID("{90ec5c9e-f6da-406b-9a38-14d00f59db76}"), + + /* nsIXPCTestInterfaceA / nsIXPCTestInterfaceB */ + name: "TestInterfaceAllDefaultName", + + /* nsIXPCTestInterfaceC */ + someInteger: 42 +}; + +var NSGetFactory = XPCOMUtils.generateNSGetFactory([TestInterfaceA, TestInterfaceB, TestInterfaceAll]); + diff --git a/js/xpconnect/tests/components/js/xpctest_params.js b/js/xpconnect/tests/components/js/xpctest_params.js new file mode 100644 index 000000000..f06e9c2b6 --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest_params.js @@ -0,0 +1,85 @@ +/* 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/. */ +Components.utils.import("resource:///modules/XPCOMUtils.jsm"); + +function TestParams() { +} + +/* For once I'm happy that JS is weakly typed. */ +function f(a, b) { + var rv = b.value; + b.value = a; + return rv; +}; + +/* Implementation for size_is and iid_is methods. */ +function f_is(aIs, a, bIs, b, rvIs) { + + // Set up the return value and its 'is' parameter. + var rv = b.value; + rvIs.value = bIs.value; + + // Set up b and its 'is' parameter. + b.value = a; + bIs.value = aIs; + + return rv; +} + +function f_size_and_iid(aSize, aIID, a, bSize, bIID, b, rvSize, rvIID) { + + // Copy the iids. + rvIID.value = bIID.value; + bIID.value = aIID; + + // Now that we've reduced the problem to one dependent variable, use f_is. + return f_is(aSize, a, bSize, b, rvSize); +} + +TestParams.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestParams"]]), + contractID: "@mozilla.org/js/xpc/test/js/Params;1", + classID: Components.ID("{e3b86f4e-49c0-487c-a2b0-3a986720a044}"), + + /* nsIXPCTestParams */ + testBoolean: f, + testOctet: f, + testShort: f, + testLong: f, + testLongLong: f, + testUnsignedShort: f, + testUnsignedLong: f, + testUnsignedLongLong: f, + testFloat: f, + testDouble: f, + testChar: f, + testString: f, + testWchar: f, + testWstring: f, + testDOMString: f, + testAString: f, + testAUTF8String: f, + testACString: f, + testJsval: f, + testShortArray: f_is, + testDoubleArray: f_is, + testStringArray: f_is, + testWstringArray: f_is, + testInterfaceArray: f_is, + testSizedString: f_is, + testSizedWstring: f_is, + testInterfaceIs: f_is, + testInterfaceIsArray: f_size_and_iid, + testOutAString: function(o) { o.value = "out"; }, + testStringArrayOptionalSize: function(arr, size) { + if (arr.length != size) { throw "bad size passed to test method"; } + var rv = ""; + arr.forEach((x) => rv += x); + return rv; + } +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TestParams]); diff --git a/js/xpconnect/tests/components/js/xpctest_returncode_child.js b/js/xpconnect/tests/components/js/xpctest_returncode_child.js new file mode 100644 index 000000000..ef1e48b2a --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest_returncode_child.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/. */ +const {interfaces: Ci, classes: Cc, utils: Cu, results: Cr} = Components; +Cu.import("resource:///modules/XPCOMUtils.jsm"); + +function TestReturnCodeChild() {} +TestReturnCodeChild.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Ci["nsIXPCTestReturnCodeChild"]]), + contractID: "@mozilla.org/js/xpc/test/js/ReturnCodeChild;1", + classID: Components.ID("{38dd78aa-467f-4fad-8dcf-4383a743e235}"), + + doIt(behaviour) { + switch (behaviour) { + case Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_THROW: + throw(new Error("a requested error")); + case Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_RETURN_SUCCESS: + return; + case Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_RETURN_RESULTCODE: + Components.returnCode = Cr.NS_ERROR_FAILURE; + return; + case Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_NEST_RESULTCODES: + // Use xpconnect to create another instance of *this* component and + // call that. This way we have crossed the xpconnect bridge twice. + + // We set *our* return code early - this should be what is returned + // to our caller, even though our "inner" component will set it to + // a different value that we will see (but our caller should not) + Components.returnCode = Cr.NS_ERROR_UNEXPECTED; + // call the child asking it to do the .returnCode set. + let sub = Cc[this.contractID].createInstance(Ci.nsIXPCTestReturnCodeChild); + let childResult = Cr.NS_OK; + try { + sub.doIt(Ci.nsIXPCTestReturnCodeChild.CHILD_SHOULD_RETURN_RESULTCODE); + } catch (ex) { + childResult = ex.result; + } + // write it to the console so the test can check it. + let consoleService = Cc["@mozilla.org/consoleservice;1"] + .getService(Ci.nsIConsoleService); + consoleService.logStringMessage("nested child returned " + childResult); + return; + } + } +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TestReturnCodeChild]); diff --git a/js/xpconnect/tests/components/js/xpctest_utils.js b/js/xpconnect/tests/components/js/xpctest_utils.js new file mode 100644 index 000000000..91d7f1839 --- /dev/null +++ b/js/xpconnect/tests/components/js/xpctest_utils.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/. */ + +Components.utils.import("resource:///modules/XPCOMUtils.jsm"); + +function TestUtils() {} +TestUtils.prototype = { + + /* Boilerplate */ + QueryInterface: XPCOMUtils.generateQI([Components.interfaces["nsIXPCTestUtils"]]), + contractID: "@mozilla.org/js/xpc/test/js/TestUtils;1", + classID: Components.ID("{e86573c4-a384-441a-8c92-7b99e8575b28}"), + doubleWrapFunction(fun) { return fun } +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TestUtils]); diff --git a/js/xpconnect/tests/components/native/moz.build b/js/xpconnect/tests/components/native/moz.build new file mode 100644 index 000000000..25d1cb942 --- /dev/null +++ b/js/xpconnect/tests/components/native/moz.build @@ -0,0 +1,19 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +FINAL_TARGET = '_tests/xpcshell/js/xpconnect/tests/components/native/' +EXTRA_COMPONENTS += [ + 'xpctest.manifest', +] + +UNIFIED_SOURCES += [ + 'xpctest_attributes.cpp', + 'xpctest_module.cpp', + 'xpctest_params.cpp', + 'xpctest_returncode.cpp', +] + +XPCOMBinaryComponent('xpctest') diff --git a/js/xpconnect/tests/components/native/xpctest.manifest b/js/xpconnect/tests/components/native/xpctest.manifest new file mode 100644 index 000000000..5b01aca44 --- /dev/null +++ b/js/xpconnect/tests/components/native/xpctest.manifest @@ -0,0 +1 @@ +interfaces xpctest.xpt diff --git a/js/xpconnect/tests/components/native/xpctest_attributes.cpp b/js/xpconnect/tests/components/native/xpctest_attributes.cpp new file mode 100644 index 000000000..6a844fee2 --- /dev/null +++ b/js/xpconnect/tests/components/native/xpctest_attributes.cpp @@ -0,0 +1,139 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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/. */ + +#include "xpctest_private.h" + +NS_IMPL_ISUPPORTS(xpcTestObjectReadOnly, nsIXPCTestObjectReadOnly) + +xpcTestObjectReadOnly :: xpcTestObjectReadOnly() { + boolProperty = true; + shortProperty = 32767; + longProperty = 2147483647; + floatProperty = 5.5f; + charProperty = 'X'; + // timeProperty is PRTime and signed type. + // So it has to allow negative value. + timeProperty = -1; +} + +NS_IMETHODIMP xpcTestObjectReadOnly :: GetStrReadOnly(char * *aStrReadOnly){ + char aString[] = "XPConnect Read-Only String"; + + if (!aStrReadOnly) + return NS_ERROR_NULL_POINTER; + *aStrReadOnly = (char*) nsMemory::Clone(aString, + sizeof(char)*(strlen(aString)+1)); + return *aStrReadOnly ? NS_OK : NS_ERROR_OUT_OF_MEMORY; +} + +NS_IMETHODIMP xpcTestObjectReadOnly :: GetBoolReadOnly(bool* aBoolReadOnly) { + *aBoolReadOnly = boolProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadOnly :: GetShortReadOnly(int16_t* aShortReadOnly){ + *aShortReadOnly = shortProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadOnly :: GetLongReadOnly(int32_t* aLongReadOnly){ + *aLongReadOnly = longProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadOnly :: GetFloatReadOnly(float* aFloatReadOnly){ + *aFloatReadOnly = floatProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadOnly :: GetCharReadOnly(char* aCharReadOnly){ + *aCharReadOnly = charProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadOnly :: GetTimeReadOnly(PRTime* aTimeReadOnly){ + *aTimeReadOnly = timeProperty; + return NS_OK; +} + +NS_IMPL_ISUPPORTS(xpcTestObjectReadWrite, nsIXPCTestObjectReadWrite) + +xpcTestObjectReadWrite :: xpcTestObjectReadWrite() { + const char s[] = "XPConnect Read-Writable String"; + stringProperty = (char*) nsMemory::Clone(s, sizeof(char)*(strlen(s)+1)); + boolProperty = true; + shortProperty = 32767; + longProperty = 2147483647; + floatProperty = 5.5f; + charProperty = 'X'; + // timeProperty is PRTime and signed type. + // So it has to allow negative value. + timeProperty = -1; +} + +xpcTestObjectReadWrite :: ~xpcTestObjectReadWrite() +{ + free(stringProperty); +} + +NS_IMETHODIMP xpcTestObjectReadWrite :: GetStringProperty(char * *aStringProperty) { + if (!aStringProperty) + return NS_ERROR_NULL_POINTER; + *aStringProperty = (char*) nsMemory::Clone(stringProperty, + sizeof(char)*(strlen(stringProperty)+1)); + return *aStringProperty ? NS_OK : NS_ERROR_OUT_OF_MEMORY; + +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetStringProperty(const char * aStringProperty) { + free(stringProperty); + stringProperty = (char*) nsMemory::Clone(aStringProperty, + sizeof(char)*(strlen(aStringProperty)+1)); + return NS_OK; +} + +NS_IMETHODIMP xpcTestObjectReadWrite :: GetBooleanProperty(bool* aBooleanProperty) { + *aBooleanProperty = boolProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetBooleanProperty(bool aBooleanProperty) { + boolProperty = aBooleanProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: GetShortProperty(int16_t* aShortProperty) { + *aShortProperty = shortProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetShortProperty(int16_t aShortProperty) { + shortProperty = aShortProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: GetLongProperty(int32_t* aLongProperty) { + *aLongProperty = longProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetLongProperty(int32_t aLongProperty) { + longProperty = aLongProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: GetFloatProperty(float* aFloatProperty) { + *aFloatProperty = floatProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetFloatProperty(float aFloatProperty) { + floatProperty = aFloatProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: GetCharProperty(char* aCharProperty) { + *aCharProperty = charProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetCharProperty(char aCharProperty) { + charProperty = aCharProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: GetTimeProperty(PRTime* aTimeProperty) { + *aTimeProperty = timeProperty; + return NS_OK; +} +NS_IMETHODIMP xpcTestObjectReadWrite :: SetTimeProperty(PRTime aTimeProperty) { + timeProperty = aTimeProperty; + return NS_OK; +} diff --git a/js/xpconnect/tests/components/native/xpctest_module.cpp b/js/xpconnect/tests/components/native/xpctest_module.cpp new file mode 100644 index 000000000..f6c29968b --- /dev/null +++ b/js/xpconnect/tests/components/native/xpctest_module.cpp @@ -0,0 +1,59 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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/. */ + +/* module registration and factory code. */ + +#include "mozilla/ModuleUtils.h" +#include "xpctest_private.h" + +#define NS_XPCTESTOBJECTREADONLY_CID \ +{ 0x492609a7, 0x2582, 0x436b, \ + { 0xb0, 0xef, 0x92, 0xe2, 0x9b, 0xb9, 0xe1, 0x43 } } + +#define NS_XPCTESTOBJECTREADWRITE_CID \ +{ 0x8f37f760, 0x3686, 0x4dbb, \ + { 0xb1, 0x21, 0x96, 0x93, 0xba, 0x81, 0x3f, 0x8f } } + +#define NS_XPCTESTPARAMS_CID \ +{ 0x1f11076a, 0x0fa2, 0x4f07, \ + { 0xb4, 0x7a, 0xa1, 0x54, 0x31, 0xf2, 0xce, 0xf7 } } + +#define NS_XPCTESTRETURNCODEPARENT_CID \ +{ 0x3818f744, 0x5445, 0x4e9c, \ + { 0x9b, 0xb8, 0x64, 0x62, 0xfe, 0x81, 0xb6, 0x19 } } + +NS_GENERIC_FACTORY_CONSTRUCTOR(xpcTestObjectReadOnly) +NS_GENERIC_FACTORY_CONSTRUCTOR(xpcTestObjectReadWrite) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsXPCTestParams) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsXPCTestReturnCodeParent) +NS_DEFINE_NAMED_CID(NS_XPCTESTOBJECTREADONLY_CID); +NS_DEFINE_NAMED_CID(NS_XPCTESTOBJECTREADWRITE_CID); +NS_DEFINE_NAMED_CID(NS_XPCTESTPARAMS_CID); +NS_DEFINE_NAMED_CID(NS_XPCTESTRETURNCODEPARENT_CID); + +static const mozilla::Module::CIDEntry kXPCTestCIDs[] = { + { &kNS_XPCTESTOBJECTREADONLY_CID, false, nullptr, xpcTestObjectReadOnlyConstructor }, + { &kNS_XPCTESTOBJECTREADWRITE_CID, false, nullptr, xpcTestObjectReadWriteConstructor }, + { &kNS_XPCTESTPARAMS_CID, false, nullptr, nsXPCTestParamsConstructor }, + { &kNS_XPCTESTRETURNCODEPARENT_CID, false, nullptr, nsXPCTestReturnCodeParentConstructor }, + { nullptr } +}; + +static const mozilla::Module::ContractIDEntry kXPCTestContracts[] = { + { "@mozilla.org/js/xpc/test/native/ObjectReadOnly;1", &kNS_XPCTESTOBJECTREADONLY_CID }, + { "@mozilla.org/js/xpc/test/native/ObjectReadWrite;1", &kNS_XPCTESTOBJECTREADWRITE_CID }, + { "@mozilla.org/js/xpc/test/native/Params;1", &kNS_XPCTESTPARAMS_CID }, + { "@mozilla.org/js/xpc/test/native/ReturnCodeParent;1", &kNS_XPCTESTRETURNCODEPARENT_CID }, + { nullptr } +}; + +static const mozilla::Module kXPCTestModule = { + mozilla::Module::kVersion, + kXPCTestCIDs, + kXPCTestContracts +}; + +NSMODULE_DEFN(xpconnect_test) = &kXPCTestModule; diff --git a/js/xpconnect/tests/components/native/xpctest_params.cpp b/js/xpconnect/tests/components/native/xpctest_params.cpp new file mode 100644 index 000000000..e88746d89 --- /dev/null +++ b/js/xpconnect/tests/components/native/xpctest_params.cpp @@ -0,0 +1,308 @@ +/* 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/. */ + +#include "xpctest_private.h" +#include "xpctest_interfaces.h" +#include "js/Value.h" + +NS_IMPL_ISUPPORTS(nsXPCTestParams, nsIXPCTestParams) + +nsXPCTestParams::nsXPCTestParams() +{ +} + +nsXPCTestParams::~nsXPCTestParams() +{ +} + +#define GENERIC_METHOD_IMPL { \ + *_retval = *b; \ + *b = a; \ + return NS_OK; \ +} + +#define STRING_METHOD_IMPL { \ + _retval.Assign(b); \ + b.Assign(a); \ + return NS_OK; \ +} + +#define TAKE_OWNERSHIP_NOOP(val) {} +#define TAKE_OWNERSHIP_INTERFACE(val) {static_cast<nsISupports*>(val)->AddRef();} +#define TAKE_OWNERSHIP_STRING(val) { \ + nsDependentCString vprime(val); \ + val = ToNewCString(vprime); \ +} +#define TAKE_OWNERSHIP_WSTRING(val) { \ + nsDependentString vprime(val); \ + val = ToNewUnicode(vprime); \ +} + +// Macro for our buffer-oriented types: +// 'type' is the type of element that the buffer contains. +// 'padding' is an offset added to length, allowing us to handle +// null-terminated strings. +// 'TAKE_OWNERSHIP' is one of the macros above. +#define BUFFER_METHOD_IMPL(type, padding, TAKE_OWNERSHIP) { \ + uint32_t elemSize = sizeof(type); \ + \ + /* Copy b into rv. */ \ + *rvLength = *bLength; \ + *rv = static_cast<type*>(moz_xmalloc(elemSize * (*bLength + padding))); \ + if (!*rv) \ + return NS_ERROR_OUT_OF_MEMORY; \ + memcpy(*rv, *b, elemSize * (*bLength + padding)); \ + \ + /* Copy a into b. */ \ + *bLength = aLength; \ + free(*b); \ + *b = static_cast<type*>(moz_xmalloc(elemSize * (aLength + padding))); \ + if (!*b) \ + return NS_ERROR_OUT_OF_MEMORY; \ + memcpy(*b, a, elemSize * (aLength + padding)); \ + \ + /* We need to take ownership of the data we got from a, \ + since the caller owns it. */ \ + for (unsigned i = 0; i < *bLength + padding; ++i) \ + TAKE_OWNERSHIP((*b)[i]); \ + \ + return NS_OK; \ +} + +NS_IMETHODIMP nsXPCTestParams::TestBoolean(bool a, bool* b, bool* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestOctet(uint8_t a, uint8_t* b, uint8_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestShort(int16_t a, int16_t* b, int16_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestLong(int32_t a, int32_t* b, int32_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestLongLong(int64_t a, int64_t* b, int64_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestUnsignedShort(uint16_t a, uint16_t* b, uint16_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestUnsignedLong(uint32_t a, uint32_t* b, uint32_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestUnsignedLongLong(uint64_t a, uint64_t* b, uint64_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestFloat(float a, float* b, float* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestDouble(double a, float* b, double* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestChar(char a, char* b, char* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestString(const char * a, char * *b, char * *_retval) +{ + nsDependentCString aprime(a); + nsDependentCString bprime(*b); + *_retval = ToNewCString(bprime); + *b = ToNewCString(aprime); + + // XPCOM ownership rules dictate that overwritten inout params must be callee-freed. + // See https://developer.mozilla.org/en/XPIDL + free(const_cast<char*>(bprime.get())); + + return NS_OK; +} + +NS_IMETHODIMP nsXPCTestParams::TestWchar(char16_t a, char16_t* b, char16_t* _retval) +{ + GENERIC_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestWstring(const char16_t * a, char16_t * *b, char16_t * *_retval) +{ + nsDependentString aprime(a); + nsDependentString bprime(*b); + *_retval = ToNewUnicode(bprime); + *b = ToNewUnicode(aprime); + + // XPCOM ownership rules dictate that overwritten inout params must be callee-freed. + // See https://developer.mozilla.org/en/XPIDL + free((void*)bprime.get()); + + return NS_OK; +} + +NS_IMETHODIMP nsXPCTestParams::TestDOMString(const nsAString & a, nsAString & b, nsAString & _retval) +{ + STRING_METHOD_IMPL; +} + + +NS_IMETHODIMP nsXPCTestParams::TestAString(const nsAString & a, nsAString & b, nsAString & _retval) +{ + STRING_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestAUTF8String(const nsACString & a, nsACString & b, nsACString & _retval) +{ + STRING_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestACString(const nsACString & a, nsACString & b, nsACString & _retval) +{ + STRING_METHOD_IMPL; +} + +NS_IMETHODIMP nsXPCTestParams::TestJsval(JS::Handle<JS::Value> a, + JS::MutableHandle<JS::Value> b, + JS::MutableHandle<JS::Value> _retval) +{ + _retval.set(b); + b.set(a); + return NS_OK; +} + +NS_IMETHODIMP nsXPCTestParams::TestShortArray(uint32_t aLength, int16_t* a, + uint32_t* bLength, int16_t** b, + uint32_t* rvLength, int16_t** rv) +{ + BUFFER_METHOD_IMPL(int16_t, 0, TAKE_OWNERSHIP_NOOP); +} + +NS_IMETHODIMP nsXPCTestParams::TestDoubleArray(uint32_t aLength, double* a, + uint32_t* bLength, double** b, + uint32_t* rvLength, double** rv) +{ + BUFFER_METHOD_IMPL(double, 0, TAKE_OWNERSHIP_NOOP); +} + +NS_IMETHODIMP nsXPCTestParams::TestStringArray(uint32_t aLength, const char * *a, + uint32_t* bLength, char * **b, + uint32_t* rvLength, char * **rv) +{ + BUFFER_METHOD_IMPL(char*, 0, TAKE_OWNERSHIP_STRING); +} + +NS_IMETHODIMP nsXPCTestParams::TestWstringArray(uint32_t aLength, const char16_t * *a, + uint32_t* bLength, char16_t * **b, + uint32_t* rvLength, char16_t * **rv) +{ + BUFFER_METHOD_IMPL(char16_t*, 0, TAKE_OWNERSHIP_WSTRING); +} + +NS_IMETHODIMP nsXPCTestParams::TestInterfaceArray(uint32_t aLength, nsIXPCTestInterfaceA** a, + uint32_t* bLength, nsIXPCTestInterfaceA * **b, + uint32_t* rvLength, nsIXPCTestInterfaceA * **rv) +{ + BUFFER_METHOD_IMPL(nsIXPCTestInterfaceA*, 0, TAKE_OWNERSHIP_INTERFACE); +} + +NS_IMETHODIMP nsXPCTestParams::TestSizedString(uint32_t aLength, const char * a, + uint32_t* bLength, char * *b, + uint32_t* rvLength, char * *rv) +{ + BUFFER_METHOD_IMPL(char, 1, TAKE_OWNERSHIP_NOOP); +} + +NS_IMETHODIMP nsXPCTestParams::TestSizedWstring(uint32_t aLength, const char16_t * a, + uint32_t* bLength, char16_t * *b, + uint32_t* rvLength, char16_t * *rv) +{ + BUFFER_METHOD_IMPL(char16_t, 1, TAKE_OWNERSHIP_NOOP); +} + +NS_IMETHODIMP nsXPCTestParams::TestInterfaceIs(const nsIID* aIID, void* a, + nsIID** bIID, void** b, + nsIID** rvIID, void** rv) +{ + // + // Getting the buffers and ownership right here can be a little tricky. + // + + // The interface pointers are heap-allocated, and b has been AddRef'd + // by XPConnect for the duration of the call. If we snatch it away from b + // and leave no trace, XPConnect won't Release it. Since we also need to + // return an already-AddRef'd pointer in rv, we don't need to do anything + // special here. + *rv = *b; + + // rvIID is out-only, so nobody allocated an IID buffer for us. Do that now, + // and store b's IID in the new buffer. + *rvIID = static_cast<nsIID*>(moz_xmalloc(sizeof(nsID))); + if (!*rvIID) + return NS_ERROR_OUT_OF_MEMORY; + **rvIID = **bIID; + + // Copy the interface pointer from a to b. Since a is in-only, XPConnect will + // release it upon completion of the call. AddRef it for b. + *b = a; + static_cast<nsISupports*>(*b)->AddRef(); + + // We already had a buffer allocated for b's IID, so we can re-use it. + **bIID = *aIID; + + return NS_OK; +} + +NS_IMETHODIMP nsXPCTestParams::TestInterfaceIsArray(uint32_t aLength, const nsIID* aIID, + void** a, + uint32_t* bLength, nsIID** bIID, + void*** b, + uint32_t* rvLength, nsIID** rvIID, + void*** rv) +{ + // Transfer the IIDs. See the comments in TestInterfaceIs (above) for an + // explanation of what we're doing. + *rvIID = static_cast<nsIID*>(moz_xmalloc(sizeof(nsID))); + if (!*rvIID) + return NS_ERROR_OUT_OF_MEMORY; + **rvIID = **bIID; + **bIID = *aIID; + + // The macro is agnostic to the actual interface types, so we can re-use code here. + // + // Do this second, since the macro returns. + BUFFER_METHOD_IMPL(void*, 0, TAKE_OWNERSHIP_INTERFACE); +} + +NS_IMETHODIMP nsXPCTestParams::TestOutAString(nsAString & o) +{ + o.AssignLiteral("out"); + return NS_OK; +} + +NS_IMETHODIMP nsXPCTestParams::TestStringArrayOptionalSize(const char * *a, uint32_t length, nsACString& out) +{ + out.Truncate(); + for (uint32_t i = 0; i < length; ++i) { + out.Append(a[i]); + } + + return NS_OK; +} diff --git a/js/xpconnect/tests/components/native/xpctest_private.h b/js/xpconnect/tests/components/native/xpctest_private.h new file mode 100644 index 000000000..45e3f12e4 --- /dev/null +++ b/js/xpconnect/tests/components/native/xpctest_private.h @@ -0,0 +1,80 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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/. */ + +/* local header for xpconnect tests components */ + +#ifndef xpctest_private_h___ +#define xpctest_private_h___ + +#include "nsISupports.h" +#include "nsMemory.h" +#include "nsStringGlue.h" +#include "xpctest_attributes.h" +#include "xpctest_params.h" +#include "xpctest_returncode.h" +#include "mozilla/Attributes.h" + +class xpcTestObjectReadOnly final : public nsIXPCTestObjectReadOnly { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSIXPCTESTOBJECTREADONLY + xpcTestObjectReadOnly(); + + private: + ~xpcTestObjectReadOnly() {} + + bool boolProperty; + int16_t shortProperty; + int32_t longProperty; + float floatProperty; + char charProperty; + PRTime timeProperty; +}; + +class xpcTestObjectReadWrite final : public nsIXPCTestObjectReadWrite { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSIXPCTESTOBJECTREADWRITE + + xpcTestObjectReadWrite(); + + private: + ~xpcTestObjectReadWrite(); + + bool boolProperty; + int16_t shortProperty; + int32_t longProperty; + float floatProperty; + char charProperty; + char* stringProperty; + PRTime timeProperty; +}; + +class nsXPCTestParams final : public nsIXPCTestParams +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_NSIXPCTESTPARAMS + + nsXPCTestParams(); + +private: + ~nsXPCTestParams(); +}; + +class nsXPCTestReturnCodeParent final : public nsIXPCTestReturnCodeParent +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_NSIXPCTESTRETURNCODEPARENT + + nsXPCTestReturnCodeParent(); + +private: + ~nsXPCTestReturnCodeParent(); +}; + +#endif /* xpctest_private_h___ */ diff --git a/js/xpconnect/tests/components/native/xpctest_returncode.cpp b/js/xpconnect/tests/components/native/xpctest_returncode.cpp new file mode 100644 index 000000000..3ae7d4279 --- /dev/null +++ b/js/xpconnect/tests/components/native/xpctest_returncode.cpp @@ -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/. */ + +#include "xpctest_private.h" +#include "xpctest_interfaces.h" +#include "nsComponentManagerUtils.h" + +NS_IMPL_ISUPPORTS(nsXPCTestReturnCodeParent, nsIXPCTestReturnCodeParent) + +nsXPCTestReturnCodeParent::nsXPCTestReturnCodeParent() +{ +} + +nsXPCTestReturnCodeParent::~nsXPCTestReturnCodeParent() +{ +} + +NS_IMETHODIMP nsXPCTestReturnCodeParent::CallChild(int32_t childBehavior, nsresult* _retval) +{ + nsresult rv; + nsCOMPtr<nsIXPCTestReturnCodeChild> child(do_CreateInstance("@mozilla.org/js/xpc/test/js/ReturnCodeChild;1", &rv)); + NS_ENSURE_SUCCESS(rv, rv); + rv = child->DoIt(childBehavior); + *_retval = rv; + return NS_OK; +} diff --git a/js/xpconnect/tests/idl/moz.build b/js/xpconnect/tests/idl/moz.build new file mode 100644 index 000000000..7ed9954b5 --- /dev/null +++ b/js/xpconnect/tests/idl/moz.build @@ -0,0 +1,25 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +XPIDL_SOURCES += [ + 'xpctest_attributes.idl', + 'xpctest_bug809674.idl', + 'xpctest_interfaces.idl', + 'xpctest_params.idl', + 'xpctest_returncode.idl', + 'xpctest_utils.idl', +] + +XPIDL_MODULE = 'xpctest' + +# XXX: This relies on xpctest.xpt being created in dist/bin/components/ during +# the export tier AND TEST_HARNESS_FILES being processed after that. +TEST_HARNESS_FILES.xpcshell.js.xpconnect.tests.components.native.components += [ + '!/dist/bin/components/xpctest.xpt', +] +TEST_HARNESS_FILES.xpcshell.js.xpconnect.tests.components.js += [ + '!/dist/bin/components/xpctest.xpt', +] diff --git a/js/xpconnect/tests/idl/xpctest_attributes.idl b/js/xpconnect/tests/idl/xpctest_attributes.idl new file mode 100644 index 000000000..cbecaa08e --- /dev/null +++ b/js/xpconnect/tests/idl/xpctest_attributes.idl @@ -0,0 +1,33 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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/. */ + +#include "nsISupports.idl" +/* + * This defines the interface for a test object. + * + */ + +[scriptable, uuid(42fbd9f6-b12d-47ef-b7a1-02d73c11fe53)] +interface nsIXPCTestObjectReadOnly : nsISupports { + readonly attribute string strReadOnly; + readonly attribute boolean boolReadOnly; + readonly attribute short shortReadOnly; + readonly attribute long longReadOnly; + readonly attribute float floatReadOnly; + readonly attribute char charReadOnly; + readonly attribute PRTime timeReadOnly; +}; + +[scriptable, uuid(f07529b0-a479-4954-aba5-ab3142c6b1cb)] +interface nsIXPCTestObjectReadWrite : nsISupports { + attribute string stringProperty; + attribute boolean booleanProperty; + attribute short shortProperty; + attribute long longProperty; + attribute float floatProperty; + attribute char charProperty; + attribute PRTime timeProperty; +}; diff --git a/js/xpconnect/tests/idl/xpctest_bug809674.idl b/js/xpconnect/tests/idl/xpctest_bug809674.idl new file mode 100644 index 000000000..c276f027f --- /dev/null +++ b/js/xpconnect/tests/idl/xpctest_bug809674.idl @@ -0,0 +1,18 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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/. */ + +#include "nsISupports.idl" +/* + * Test interface for https://bugzilla.mozilla.org/show_bug.cgi?id=809674 . + * + * This test makes sure that accessing an attribute marked with + * [implicit_jscontext] will throw without crashing. + */ + +[scriptable, uuid(2df46559-da21-49bf-b863-0d7b7bbcbc73)] +interface nsIXPCTestBug809674 : nsISupports { + [implicit_jscontext] attribute jsval jsvalProperty; +}; diff --git a/js/xpconnect/tests/idl/xpctest_interfaces.idl b/js/xpconnect/tests/idl/xpctest_interfaces.idl new file mode 100644 index 000000000..2abc14962 --- /dev/null +++ b/js/xpconnect/tests/idl/xpctest_interfaces.idl @@ -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/. */ + +/** + * Very simple test interfaces. + * + * This is used by the other test functionality when it needs to play around with + * interface pointers. + */ + +#include "nsISupports.idl" + +[scriptable, uuid(3c8fd2f5-970c-42c6-b5dd-cda1c16dcfd8)] +interface nsIXPCTestInterfaceA : nsISupports { + attribute string name; +}; + +[scriptable, uuid(ff528c3a-2410-46de-acaa-449aa6403a33)] +interface nsIXPCTestInterfaceB : nsISupports { + attribute string name; +}; + +[scriptable, uuid(401cf1b4-355b-4cee-b7b3-c7973aee49bd)] +interface nsIXPCTestInterfaceC : nsISupports { + attribute long someInteger; +}; diff --git a/js/xpconnect/tests/idl/xpctest_params.idl b/js/xpconnect/tests/idl/xpctest_params.idl new file mode 100644 index 000000000..f324a4595 --- /dev/null +++ b/js/xpconnect/tests/idl/xpctest_params.idl @@ -0,0 +1,90 @@ +/* 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/. */ + +/** + * Test pararameter passing and argument conversion. + * + * Each test method returns the value in 'b', and copies 'a' into 'b'. This lets + * us test return values, in params, and inout params (out params should be + * covered by the intersection of return values and inout). + */ + +#include "nsISupports.idl" + +interface nsIXPCTestInterfaceA; +interface nsIXPCTestInterfaceB; + +[scriptable, uuid(812145c7-9fcc-425e-a878-36ad1b7730b7)] +interface nsIXPCTestParams : nsISupports { + + // These types correspond to the ones in typelib.py + boolean testBoolean(in boolean a, inout boolean b); + octet testOctet(in octet a, inout octet b); + short testShort(in short a, inout short b); + long testLong(in long a, inout long b); + long long testLongLong(in long long a, inout long long b); + unsigned short testUnsignedShort(in unsigned short a, inout unsigned short b); + unsigned long testUnsignedLong(in unsigned long a, inout unsigned long b); + unsigned long long testUnsignedLongLong(in unsigned long long a, inout unsigned long long b); + float testFloat(in float a, inout float b); + double testDouble(in double a, inout float b); + char testChar(in char a, inout char b); + string testString(in string a, inout string b); + wchar testWchar(in wchar a, inout wchar b); + wstring testWstring(in wstring a, inout wstring b); + DOMString testDOMString(in DOMString a, inout DOMString b); + AString testAString(in AString a, inout AString b); + AUTF8String testAUTF8String(in AUTF8String a, inout AUTF8String b); + ACString testACString(in ACString a, inout ACString b); + jsval testJsval(in jsval a, inout jsval b); + + // + // Dependent parameters use the same types as above, but are handled much differently. + // + + // Test arrays. + void testShortArray(in unsigned long aLength, [array, size_is(aLength)] in short a, + inout unsigned long bLength, [array, size_is(bLength)] inout short b, + out unsigned long rvLength, [retval, array, size_is(rvLength)] out short rv); + void testDoubleArray(in unsigned long aLength, [array, size_is(aLength)] in double a, + inout unsigned long bLength, [array, size_is(bLength)] inout double b, + out unsigned long rvLength, [retval, array, size_is(rvLength)] out double rv); + void testStringArray(in unsigned long aLength, [array, size_is(aLength)] in string a, + inout unsigned long bLength, [array, size_is(bLength)] inout string b, + out unsigned long rvLength, [retval, array, size_is(rvLength)] out string rv); + void testWstringArray(in unsigned long aLength, [array, size_is(aLength)] in wstring a, + inout unsigned long bLength, [array, size_is(bLength)] inout wstring b, + out unsigned long rvLength, [retval, array, size_is(rvLength)] out wstring rv); + void testInterfaceArray(in unsigned long aLength, [array, size_is(aLength)] in nsIXPCTestInterfaceA a, + inout unsigned long bLength, [array, size_is(bLength)] inout nsIXPCTestInterfaceA b, + out unsigned long rvLength, [retval, array, size_is(rvLength)] out nsIXPCTestInterfaceA rv); + + // Test sized strings. + void testSizedString(in unsigned long aLength, [size_is(aLength)] in string a, + inout unsigned long bLength, [size_is(bLength)] inout string b, + out unsigned long rvLength, [retval, size_is(rvLength)] out string rv); + void testSizedWstring(in unsigned long aLength, [size_is(aLength)] in wstring a, + inout unsigned long bLength, [size_is(bLength)] inout wstring b, + out unsigned long rvLength, [retval, size_is(rvLength)] out wstring rv); + + // Test iid_is. + void testInterfaceIs(in nsIIDPtr aIID, [iid_is(aIID)] in nsQIResult a, + inout nsIIDPtr bIID, [iid_is(bIID)] inout nsQIResult b, + out nsIIDPtr rvIID, [retval, iid_is(rvIID)] out nsQIResult rv); + + // Test arrays of iid_is. According to khuey we don't use it for anything + // in mozilla-central, but calendar stuff depends on it. + void testInterfaceIsArray(in unsigned long aLength, in nsIIDPtr aIID, + [array, size_is(aLength), iid_is(aIID)] in nsQIResult a, + inout unsigned long bLength, inout nsIIDPtr bIID, + [array, size_is(bLength), iid_is(bIID)] inout nsQIResult b, + out unsigned long rvLength, out nsIIDPtr rvIID, + [retval, array, size_is(rvLength), iid_is(rvIID)] out nsQIResult rv); + + // Test for out dipper parameters + void testOutAString(out AString o); + + // Test for optional array size_is. + ACString testStringArrayOptionalSize([array, size_is(aLength)] in string a, [optional] in unsigned long aLength); +}; diff --git a/js/xpconnect/tests/idl/xpctest_returncode.idl b/js/xpconnect/tests/idl/xpctest_returncode.idl new file mode 100644 index 000000000..d6555b9e2 --- /dev/null +++ b/js/xpconnect/tests/idl/xpctest_returncode.idl @@ -0,0 +1,45 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * 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/. */ + +/** + * Test the use of Components.returnCode + * + * This ("parent") interface defines a method that in-turn calls another + * ("child") interface implemented in JS, and returns the nsresult from that + * child interface. The child interface manages the return code by way of + * Components.returnCode. + */ + +#include "nsISupports.idl" + + +[scriptable, uuid(479e4532-95cf-48b8-a99b-8a5881e47138)] +interface nsIXPCTestReturnCodeParent : nsISupports { + // Calls the "child" interface with the specified behavior flag. Returns + // the NSRESULT from the child interface. + nsresult callChild(in long childBehavior); +}; + +[scriptable, uuid(672cfd34-1fd1-455d-9901-d879fa6fdb95)] +interface nsIXPCTestReturnCodeChild : nsISupports { + void doIt(in long behavior); + + // Flags to control that the child does. + // child will throw a JS exception + const long CHILD_SHOULD_THROW = 0; + + // child will just return normally + const long CHILD_SHOULD_RETURN_SUCCESS = 1; + + // child will return after setting Components.returnCode to NS_ERROR_FAILURE + const long CHILD_SHOULD_RETURN_RESULTCODE = 2; + + // child will set Components.returnCode to NS_ERROR_UNEXPECTED, then create + // a new component that sets Components.returnCode to NS_ERROR_FAILURE. + // Our caller should see the NS_ERROR_UNEXPECTED we set rather than the + // value set later by the "inner" child. + const long CHILD_SHOULD_NEST_RESULTCODES = 3; +}; diff --git a/js/xpconnect/tests/idl/xpctest_utils.idl b/js/xpconnect/tests/idl/xpctest_utils.idl new file mode 100644 index 000000000..e59814272 --- /dev/null +++ b/js/xpconnect/tests/idl/xpctest_utils.idl @@ -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/. */ + +/** + * Utility interfaces for testing. + */ + +#include "nsISupports.idl" + +[scriptable, function, uuid(d58a82ab-d8f7-4ca9-9273-b3290d42a0cf)] +interface nsIXPCTestFunctionInterface : nsISupports { + string echo(in string arg); +}; + +[scriptable, uuid(1e9cddeb-510d-449a-b152-3c1b5b31d41d)] +interface nsIXPCTestUtils : nsISupports { + nsIXPCTestFunctionInterface doubleWrapFunction(in nsIXPCTestFunctionInterface f); +}; diff --git a/js/xpconnect/tests/mochitest/bug500931_helper.html b/js/xpconnect/tests/mochitest/bug500931_helper.html new file mode 100644 index 000000000..da268d99d --- /dev/null +++ b/js/xpconnect/tests/mochitest/bug500931_helper.html @@ -0,0 +1,8 @@ +<html> + <head> + <title>Inner frame for bug 500931 mochitest</title> + <script>x = 42;</script> + </head> + <body> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/bug504877_helper.html b/js/xpconnect/tests/mochitest/bug504877_helper.html new file mode 100644 index 000000000..dd4b4d166 --- /dev/null +++ b/js/xpconnect/tests/mochitest/bug504877_helper.html @@ -0,0 +1,10 @@ +<html> + <head> + <script> + function getblat() { + return blat; + } + foopy = 42; + </script> + </head> +</html> diff --git a/js/xpconnect/tests/mochitest/bug571849_helper.html b/js/xpconnect/tests/mochitest/bug571849_helper.html new file mode 100644 index 000000000..234cd57cc --- /dev/null +++ b/js/xpconnect/tests/mochitest/bug571849_helper.html @@ -0,0 +1,7 @@ +<html> + <head> + </head> + <body> + TEXT NODE TEXT NODE + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/bug589028_helper.html b/js/xpconnect/tests/mochitest/bug589028_helper.html new file mode 100644 index 000000000..dc56ecbc3 --- /dev/null +++ b/js/xpconnect/tests/mochitest/bug589028_helper.html @@ -0,0 +1,27 @@ +<html> + <head> + <script> + function getMyOption() { + return new Option(); + } + function getCallersOption(caller) { + return new caller.Option(); + } + function getMyAudio() { + return new Audio(); + } + function getCallersAudio(caller) { + return new caller.Audio(); + } + function getMyImage() { + return new Image(); + } + function getCallersImage(caller) { + return new caller.Image(); + } + </script> + </head> + <body> + the iframe + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/bug92773_helper.html b/js/xpconnect/tests/mochitest/bug92773_helper.html new file mode 100644 index 000000000..ac82c5d58 --- /dev/null +++ b/js/xpconnect/tests/mochitest/bug92773_helper.html @@ -0,0 +1,7 @@ +<html> + <head> + <script> + foo getter = function() { alert("FAIL"); } + </script> + </head> +</html> diff --git a/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html b/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html new file mode 100644 index 000000000..26973b713 --- /dev/null +++ b/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html @@ -0,0 +1,30 @@ +<html> + <head> + <script> + function check_wrapper(ok, wrapper, expected, note) { + + var utils = SpecialPowers.DOMWindowUtils; + ok(utils.getClassName(wrapper) === expected, note); + } + function run_test(ok, xpcnw, sjow) { + // both wrappers should point to our window: XOW + check_wrapper(ok, ok, "Proxy", "functions are wrapped properly") + check_wrapper(ok, xpcnw, "Proxy", "XPCNWs are transformed correctly"); + check_wrapper(ok, sjow, "Proxy", "SJOWs are transformed correctly"); + + check_wrapper(ok, window.location, "Proxy", + "Content needs a same-compartment security wrappers around location"); + + ok(defprop1 === 1, "defprop1 exists"); + window.defprop1 = 2; + ok(defprop1 === 2, "defprop1 is properly writable"); + + // defprop2 = {}; disabled because the test doesn't work + } + + window.xhr = new XMLHttpRequest(); + </script> + </head> + <body> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file1_bug629227.html b/js/xpconnect/tests/mochitest/file1_bug629227.html new file mode 100644 index 000000000..dd1248406 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file1_bug629227.html @@ -0,0 +1,32 @@ +<!DOCTYPE html> +<html> + <head> + <script> + function doIt() { + var doc = window.frames[0].document; + var ok = (doc.form1 == doc.getElementById("test1")); + window.parent.postMessage( + JSON.stringify({ ok: ok, + reason: "Should be able to get named items by name" }), + "*"); + window.parent.postMessage("finish", "*"); + } + + window.onmessage = function(ev) { + if (ev.data == "start") { + doIt(); + } + } + + document.domain = "example.org"; + </script> + </head> + <body> + <iframe id="subframe"></iframe> + <script> + document.getElementById("subframe").src = + "http://test2.example.org" + + location.pathname.replace(/file1_bug629227.html/, "file2_bug629227.html"); + </script> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file2_bug629227.html b/js/xpconnect/tests/mochitest/file2_bug629227.html new file mode 100644 index 000000000..02a054086 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file2_bug629227.html @@ -0,0 +1,11 @@ +<!DOCTYPE html> +<html> + <head> + <script> + document.domain = "example.org"; + </script> + </head> + <body> + <form name="form1" id="test1"></form> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug505915.html b/js/xpconnect/tests/mochitest/file_bug505915.html new file mode 100644 index 000000000..512912691 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug505915.html @@ -0,0 +1,10 @@ +<!DOCTYPE HTML> +<html> +<!-- +Inner frame for testing bug 505915. +https://bugzilla.mozilla.org/show_bug.cgi?id=505915 +--> +<head> +<body onload="parent.postMessage('', '*');"> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug650273.html b/js/xpconnect/tests/mochitest/file_bug650273.html new file mode 100644 index 000000000..5fe33e969 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug650273.html @@ -0,0 +1,31 @@ +<!-- test by moz_bug_r_a4@yahoo.com --> +<body onload="a()"> +<script> +var targetUrl = "http://example.com/"; +var l; + +function a() { + var o = {}; + o.toString = function() { + l(); + return "a"; + }; + var f = Object.getOwnPropertyDescriptor(Document.prototype, "title").set; + setTimeout(f.bind(document), 0, o); +} + +function l() { + var l = false; + onunload = function() { + l = true; + }; + location = targetUrl; + do { + var r = new XMLHttpRequest(); + r.open("GET", location.href, false); + r.overrideMimeType("text/plain"); + try { r.send(null); } + catch (e) {} + } while (!l); +} +</script> diff --git a/js/xpconnect/tests/mochitest/file_bug658560.html b/js/xpconnect/tests/mochitest/file_bug658560.html new file mode 100644 index 000000000..411d31ac7 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug658560.html @@ -0,0 +1,4 @@ +<html> + <body> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug706301.html b/js/xpconnect/tests/mochitest/file_bug706301.html new file mode 100644 index 000000000..805449b4a --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug706301.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> + <head> + <script type="application/javascript"> + window.addEventListener('message', doContentTest); + + function doContentTest() { + + // This has always worked. + var nodelist1 = document.getElementsByTagName('details'); + Object.getOwnPropertyDescriptor(nodelist1, 'length'); + ok(nodelist1['length'] == 0, "Content should be able to get the length of " + + "its own nodelist after calling getOwnPropertyDescriptor."); + + // This is bug 706301. + var nodelist2 = document.getElementsByTagName('section'); + ok(getLengthInChrome(nodelist2), "Chrome should be able to get the length of " + + "content nodelist after calling getOwnPropertyDescriptor."); + + // All done. + finishTestInChrome(); + } + </script> + </head> + <body> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug720619.html b/js/xpconnect/tests/mochitest/file_bug720619.html new file mode 100644 index 000000000..d198ba1fa --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug720619.html @@ -0,0 +1,10 @@ +<!DOCTYPE html> +<html> + <head> + <script> + valueOf = function() { return "v"; } + toString = function() { return "s"; } + </script> + </head> + <body></body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug738244.html b/js/xpconnect/tests/mochitest/file_bug738244.html new file mode 100644 index 000000000..a399d9f0e --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug738244.html @@ -0,0 +1,10 @@ +<html> +<body> +<form name="form1"> + <input name="input1" /> + <input name="appendChild" /> +</form> +<iframe name="frame1"> +</iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug760131.html b/js/xpconnect/tests/mochitest/file_bug760131.html new file mode 100644 index 000000000..736732a0a --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug760131.html @@ -0,0 +1,23 @@ +<html> +<div id="target" ontouchstart="alert();"></div> +<script type="application/javascript"> + +/** Test for Bug 760131 **/ + +function accessTouches(evt) +{ + var thrown = false; + try { + var a = evt.touches; + } catch (e) { + thrown = true; + } + ok(!thrown, "Unwrapping a TouchList shouldn't throw"); +} + +document.getElementById("target").ontouchstart = accessTouches; + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug781476.html b/js/xpconnect/tests/mochitest/file_bug781476.html new file mode 100644 index 000000000..745f8818e --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug781476.html @@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> +<head> +<script type="application/javascript"> +function makeEvent() { + var evt = new Event("MouseEvents"); + evt.expando = 42; + is(evt.expando, 42, "Expando properly visible in iframe"); + return evt; +} +</script> +</head> +<body> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug789713.html b/js/xpconnect/tests/mochitest/file_bug789713.html new file mode 100644 index 000000000..ea21dae6c --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug789713.html @@ -0,0 +1,44 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=789713 +--> +<head> + <meta charset="utf-8"> +</head> +<body> + +<script type="application/javascript"> + +/** Test for Bug 789713 **/ + +function go() { + var ifr = document.getElementById('ifr'); + var pass = true; + var doc = ifr.contentDocument; + + // Tree walkers use nsDOMGenericSH, which has a spineless PreCreate. + var walker = doc.createTreeWalker(doc.body); + pass = pass && (walker.root === doc.body); + + // Grab a reference to Object.prototype to make sure we test the machinery + // with respect to standard prototype remapping. + var objProto = ifr.contentWindow.Object.prototype; + + // First, do the document.domain operation. This shouldn't crash. + document.domain = "example.org"; + + // Now, make sure that we still can't access cross-origin properties despite + // the fact that the WN is shared under the hood. + try { + walker.root; + pass = false; + } catch (e) { pass = pass && /Permission denied/.exec(e.message); } + window.parent.postMessage(pass, '*'); +} + +</script> +<iframe id="ifr" src="file_empty.html" onload="go()"></iframe> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug795275.html b/js/xpconnect/tests/mochitest/file_bug795275.html new file mode 100644 index 000000000..95e9f2a8e --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug795275.html @@ -0,0 +1,28 @@ +<html> +<head> +<style> + .bound { + -moz-binding: url(file_bug795275.xml#xbltest); + } +</style> +<script type="application/javascript"> + function touchComponents() { + Components; + } + function touchInterfaces() { + Components.interfaces; + } + + function touchViaXBL() { + // Make sure none of this warns. + var div = document.getElementById('dummy'); + div.testProp; + div.testMethod(); + } + +</script> +</head> +<body> +<div id="dummy" class="bound"></div> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug795275.xml b/js/xpconnect/tests/mochitest/file_bug795275.xml new file mode 100644 index 000000000..f9e5e60f5 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug795275.xml @@ -0,0 +1,19 @@ +<?xml version="1.0"?> +<bindings id="xbltestBindings" xmlns="http://www.mozilla.org/xbl" + xmlns:html="http://www.w3.org/1999/xhtml"> +<binding id="xbltest"> +<implementation> +<method name="testMethod" exposeToUntrustedContent="true"> +<body> + Components.interfaces; +</body> +</method> +<property name="testProp" readonly="true" + onget="Components; return 3;" + exposeToUntrustedContent="true" /> +<constructor> + var foo = Components; +</constructor> +</implementation> +</binding> +</bindings> diff --git a/js/xpconnect/tests/mochitest/file_bug799348.html b/js/xpconnect/tests/mochitest/file_bug799348.html new file mode 100644 index 000000000..5800868db --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug799348.html @@ -0,0 +1,11 @@ +<!DOCTYPE HTML> +<html> +<head> +<script> + var foo = window.open('file_empty.html', '', 'width=550, height=420, status=no, resizable=yes, scrollbars=yes, toolbar=no, left=945, top=225'); +</script> +</head> +<body> +</body> +</html> + diff --git a/js/xpconnect/tests/mochitest/file_bug802557.html b/js/xpconnect/tests/mochitest/file_bug802557.html new file mode 100644 index 000000000..39f952bc5 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug802557.html @@ -0,0 +1,62 @@ +<!DOCTYPE html> +<html> +<head> +<script> +var gTS = window.location.toString; +var gGHR = Object.getOwnPropertyDescriptor(window.location, 'href').get; +function getTests(fromOuter) { + + function loc() { + return fromOuter ? window.location : location; + } + return { + getLocationImplicit: function() { + return loc() + ""; + }, + getLocationExplicit: function() { + return loc().toString(); + }, + getLocationApply1: function() { + return gTS.call(loc()); + }, + getLocationApply2: function() { + return gTS.apply(loc(), []); + }, + getLocationApply3: function() { + return Function.call.apply(gTS, [loc()]); + }, + getHref: function() { + return loc().href; + }, + getHrefViaApply: function() { + return Function.call.apply(gGHR, [loc()]); + }, + } +}; + +function mungeNames(obj, suffix) { + var rv = {}; + Object.getOwnPropertyNames(obj) + .forEach(name => rv[name + suffix] = obj[name]); + return rv; +} + +function mergeObjects(a, b) { + var rv = {}; + Object.getOwnPropertyNames(a).forEach(name => rv[name] = a[name]); + Object.getOwnPropertyNames(b).forEach(name => rv[name] = b[name]); + return rv; +} + +function getAllTests() { + var innerTests = getTests(false); + var outerTests = getTests(true); + return mergeObjects(mungeNames(innerTests, '_inner'), + mungeNames(outerTests, '_outer')); +} + +</script> +</head> +<body> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_bug860494.html b/js/xpconnect/tests/mochitest/file_bug860494.html new file mode 100644 index 000000000..63a700379 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_bug860494.html @@ -0,0 +1,16 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="UTF-8"> +<title></title> +</head> +<body> +<iframe name="top"></iframe> +<iframe name="parent"></iframe> +<iframe name="location"></iframe> +<iframe name="length"></iframe> +<iframe name="window"></iframe> +<iframe name="navigator"></iframe> +<iframe name="alert"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_crossOriginObjects.html b/js/xpconnect/tests/mochitest/file_crossOriginObjects.html new file mode 100644 index 000000000..c3093ebda --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_crossOriginObjects.html @@ -0,0 +1,35 @@ +<!doctype html> +<html> +<head> +<script> + // Override the |frames| property to test that such overrides are + // properly ignored cross-origin. + window.frames = "override"; + + // If we get a postMessage, we grab references to everything and set + // document.domain to trim off our topmost subdomain. + window.onmessage = function(evt) { + window.windowReferences = []; + window.locationReferences = []; + for (var i = 0; i < parent.length; ++i) { + windowReferences.push(parent[i]); + locationReferences.push(parent[i].location); + } + document.domain = document.domain.substring(document.domain.indexOf('.') + 1); + evt.source.postMessage('', '*'); + } + + function checkWindowReferences() { + for (var i = 0; i < parent.length; ++i) { + if (windowReferences[i] != parent[i]) + throw new Error("Window references don't match for " + i + " after document.domain"); + if (locationReferences[i] != parent[i].location) + throw new Error("Location references don't match for " + i + " after document.domain"); + } + return true; + } +</script> +</head> +<body> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_crossOriginObjects_documentDomain.html b/js/xpconnect/tests/mochitest/file_crossOriginObjects_documentDomain.html new file mode 100644 index 000000000..1c0f05bd2 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_crossOriginObjects_documentDomain.html @@ -0,0 +1,55 @@ +<!DOCTYPE html> +<html> +<head> + <script> + function loadFrames() { + window.A = document.getElementById('A').contentWindow; + window.B = document.getElementById('B').contentWindow; + window.C = document.getElementById('C').contentWindow; + window.D = document.getElementById('D').contentWindow; + + var path = location.pathname.substring(0, location.pathname.lastIndexOf('/')) + '/file_crossOriginObjects.html'; + A.location = 'file_crossOriginObjects.html'; + B.location = frameURI = 'http://test2.mochi.test:' + location.port + path; + C.location = frameURI = 'http://test1.mochi.test:' + location.port + path; + D.location = frameURI = 'http://test1.mochi.test:' + location.port + path; + + var loadCount = 0; + function frameLoaded() { + if (++loadCount == 4) + go(); + } + Array.forEach(document.getElementsByTagName('iframe'), function(ifr) { ifr.onload = frameLoaded; }); + } + + + var results = []; + function assert(cond, msg) { + results.push({pass: !!cond, message: msg}); + } + + function go() { + window.onmessage = function() { + assert(B.checkWindowReferences(), "B's Window references are still self-consistent after document.domain"); + for (var i = 0; i < window.length; ++i) { + assert(window[i] === B.windowReferences[i], + "Window reference " + i + " consistent between globals after document.domain"); + assert(window[i].location === B.locationReferences[i], + "Location reference " + i + " consistent between globals after document.domain"); + } + opener.postMessage(results, '*'); + }; + A.document.domain = A.document.domain; + document.domain = document.domain; + B.postMessage('', '*'); + } + + </script> +</head> +<body onload="loadFrames()"> + <iframe id="A"></iframe> + <iframe id="B"></iframe> + <iframe id="C"></iframe> + <iframe id="D"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_crosscompartment_weakmap.html b/js/xpconnect/tests/mochitest/file_crosscompartment_weakmap.html new file mode 100644 index 000000000..b25cdb2f9 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_crosscompartment_weakmap.html @@ -0,0 +1,9 @@ +<!DOCTYPE HTML> +<html> +<head> + <link rel="stylesheet" href="data:text/css,div {}"> + <title>Test Cross-Compartment DOM WeakMaps</title> +</head> +<body> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_documentdomain.html b/js/xpconnect/tests/mochitest/file_documentdomain.html new file mode 100644 index 000000000..784ed269d --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_documentdomain.html @@ -0,0 +1,41 @@ +<!DOCTYPE html> +<html> +<head> +<script type="application/javascript"> + + function setDomain(domain) { + document.domain = domain; + } + + function tryToAccess(otherWin) { + try { + var text = otherWin.document.getElementById('foo').innerHTML; + return /Better Late/.exec(text); + } catch (e) { return false; } + } + + var gRef = null; + function storeReference(otherWin) { + gRef = otherWin.document.getElementById('foo'); + } + + function tryToAccessStored() { + try { + return /Better Late/.exec(gRef.innerHTML); + } catch (e) { return false; } + } + + function invokingFunctionThrowsSecurityException(name) { + try { + window[name](); + return false; + } catch (e) { return /insecure|denied/.test(e); } + } + + +</script> +</head> +<body> +<span id="foo">Better Late than Never</span> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_doublewrappedcompartments.html b/js/xpconnect/tests/mochitest/file_doublewrappedcompartments.html new file mode 100644 index 000000000..f789a33d7 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_doublewrappedcompartments.html @@ -0,0 +1,10 @@ +<html> + <head> + <script> + // We want to put an expando on the object, but we want this object + // to be wrapped in other compartments. This means that the expando + // must implement precreate, which happens (in general) for nodes. + // So we just do a cyclic reference to the document body. + window.expando = document.documentElement; + </script> + </head> diff --git a/js/xpconnect/tests/mochitest/file_empty.html b/js/xpconnect/tests/mochitest/file_empty.html new file mode 100644 index 000000000..ebe8e56a6 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_empty.html @@ -0,0 +1,3 @@ +<!DOCTYPE html> +<!-- Note: other tests throughout the tree depend on the layout of this, including the title. Don't make big changes without a try run. --> +<html><head><title>empty test page</title></head><body><span id="text">Nothing to see here</span><iframe name="subframe"></iframe></body></html> diff --git a/js/xpconnect/tests/mochitest/file_evalInSandbox.html b/js/xpconnect/tests/mochitest/file_evalInSandbox.html new file mode 100644 index 000000000..f53aa1166 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_evalInSandbox.html @@ -0,0 +1,8 @@ +<html> + <body> + <script> + document.foo = "bar"; + windowfoo = "windowbar"; + </script> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_exnstack.html b/js/xpconnect/tests/mochitest/file_exnstack.html new file mode 100644 index 000000000..448e3c0a7 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_exnstack.html @@ -0,0 +1,23 @@ +<!DOCTYPE html> +<html> +<head> + <script type="application/javascript"> + window.doThrow = function(other) { + if (other) + throwAsOuter(other); + else + throwAsInner(); + } + + function throwAsInner() { + throw Error('look at me go!'); + } + + function throwAsOuter(other) { + other.doThrow(null); + } + </script> +</head> +<body> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_expandosharing.html b/js/xpconnect/tests/mochitest/file_expandosharing.html new file mode 100644 index 000000000..ceb4131bb --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_expandosharing.html @@ -0,0 +1,34 @@ +<!DOCTYPE html> +<html> +<head> +<script type="application/javascript"> + function setup() { + // Set up different target objects for expandos, one for each binding type. + window.targetWN = window; + window.targetDOM = new XMLHttpRequest(); + window.targetJS = new Date(); + } + + function placeExpando(name, val, target) { + target[name] = val; + } + + // If val === null, then we shouldn't have access. + function checkExpando(name, val, target, msg) { + if (val !== null) { + ok(name in target, msg); + try { + is(target[name], val, "Got the right expando value"); + } catch(e) { ok(false, "Threw when accessing same-origin expando"); } + } + else { + ok(!(name in target), msg); + } + } + +</script> +</head> +<body onload="setup();"> + <span>Salut, Ma Cherise. ;-)</span> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_matches.html b/js/xpconnect/tests/mochitest/file_matches.html new file mode 100644 index 000000000..0dc101b53 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_matches.html @@ -0,0 +1 @@ +<html><body></body></html> diff --git a/js/xpconnect/tests/mochitest/file_nodelists.html b/js/xpconnect/tests/mochitest/file_nodelists.html new file mode 100644 index 000000000..2195c62cc --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_nodelists.html @@ -0,0 +1,7 @@ +<html> + <body> + <p> + <p> + <p> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/file_wrappers-2.html b/js/xpconnect/tests/mochitest/file_wrappers-2.html new file mode 100644 index 000000000..e27b07ed6 --- /dev/null +++ b/js/xpconnect/tests/mochitest/file_wrappers-2.html @@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html> + <body> + <script> + var obj = {a: 3, next: 1}; + var to_iterate = Object.create(obj); + var enumerate = { 0: 0, "hi": "there" }; + function func () {}; + var o = {}; + var a = [1]; + </script> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/inner.html b/js/xpconnect/tests/mochitest/inner.html new file mode 100644 index 000000000..8021a5553 --- /dev/null +++ b/js/xpconnect/tests/mochitest/inner.html @@ -0,0 +1,7 @@ +<html> + <head> + <title>Inner frame for bug 39685 mochitest</title> + </head> + <body onload="x = 4"> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/mochitest.ini b/js/xpconnect/tests/mochitest/mochitest.ini new file mode 100644 index 000000000..de6759e7a --- /dev/null +++ b/js/xpconnect/tests/mochitest/mochitest.ini @@ -0,0 +1,107 @@ +[DEFAULT] +support-files = + bug500931_helper.html + bug504877_helper.html + bug571849_helper.html + bug589028_helper.html + bug92773_helper.html + chrome_wrappers_helper.html + file1_bug629227.html + file2_bug629227.html + file_bug505915.html + file_bug650273.html + file_bug658560.html + file_bug706301.html + file_bug720619.html + file_bug738244.html + file_bug760131.html + file_bug781476.html + file_bug789713.html + file_bug795275.html + file_bug795275.xml + file_bug799348.html + file_bug802557.html + file_bug860494.html + file_crossOriginObjects.html + file_crossOriginObjects_documentDomain.html + file_crosscompartment_weakmap.html + file_documentdomain.html + file_doublewrappedcompartments.html + file_empty.html + file_evalInSandbox.html + file_exnstack.html + file_expandosharing.html + file_matches.html + file_nodelists.html + file_wrappers-2.html + inner.html + test1_bug629331.html + test2_bug629331.html + +[test_bug384632.html] +[test_bug390488.html] +[test_bug393269.html] +[test_bug396851.html] +[test_bug428021.html] +[test_bug446584.html] +[test_bug462428.html] +[test_bug478438.html] +[test_bug500691.html] +[test_bug504877.html] +[test_bug505915.html] +[test_bug560351.html] +[test_bug585745.html] +[test_bug589028.html] +[test_bug601299.html] +[test_bug605167.html] +[test_bug618017.html] +[test_bug623437.html] +[test_bug628410.html] +[test_bug628794.html] +[test_bug629227.html] +[test_bug629331.html] +[test_bug636097.html] +[test_bug650273.html] +[test_bug655297-1.html] +[test_bug655297-2.html] +[test_bug661980.html] +[test_bug691059.html] +[test_bug720619.html] +[test_bug731471.html] +[test_bug764389.html] +[test_bug772288.html] +[test_bug781476.html] +[test_bug789713.html] +[test_bug790732.html] +[test_bug793969.html] +[test_bug800864.html] +[test_bug802557.html] +[test_bug803730.html] +[test_bug809547.html] +[test_bug829872.html] +[test_bug862380.html] +[test_bug865260.html] +[test_bug870423.html] +[test_bug871887.html] +[test_bug912322.html] +[test_bug916945.html] +[test_bug92773.html] +[test_bug940783.html] +[test_bug965082.html] +[test_bug960820.html] +[test_bug986542.html] +[test_bug993423.html] +[test_bug1005806.html] +[test_bug1094930.html] +[test_bug1158558.html] +[test_crossOriginObjects.html] +[test_crosscompartment_weakmap.html] +[test_frameWrapping.html] +# The JS test component we use below is only available in debug builds. +[test_getWebIDLCaller.html] +skip-if = (debug == false || os == "android") +[test_nac.xhtml] +[test_sameOriginPolicy.html] +[test_sandbox_fetch.html] + support-files = + ../../../../dom/tests/mochitest/fetch/test_fetch_basic.js diff --git a/js/xpconnect/tests/mochitest/moz.build b/js/xpconnect/tests/mochitest/moz.build new file mode 100644 index 000000000..8e5cb5d71 --- /dev/null +++ b/js/xpconnect/tests/mochitest/moz.build @@ -0,0 +1,8 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +MOCHITEST_MANIFESTS += ['mochitest.ini'] + diff --git a/js/xpconnect/tests/mochitest/test1_bug629331.html b/js/xpconnect/tests/mochitest/test1_bug629331.html new file mode 100644 index 000000000..18843e08d --- /dev/null +++ b/js/xpconnect/tests/mochitest/test1_bug629331.html @@ -0,0 +1,19 @@ +<body> +<iframe src="about:blank" id="ifr"></iframe> +<script> +/** Test for Bug 629331 **/ +function finish() { + parent.postMessage(JSON.stringify({fun: "finish"}), "*"); +} + +function is(a, b, description) { + parent.postMessage(JSON.stringify({ fun: "is", a: a, b: b, description: description }), "*"); +} + +document.domain = "example.org"; +var i = 0; +is(i, 0, 'i meets starting conditions'); +document.getElementById('ifr').src = 'http://test2.example.org/tests/js/xpconnect/tests/mochitest/test2_bug629331.html'; +</script> + + diff --git a/js/xpconnect/tests/mochitest/test2_bug629331.html b/js/xpconnect/tests/mochitest/test2_bug629331.html new file mode 100644 index 000000000..1bcf03739 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test2_bug629331.html @@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + <head> + </head> + <body> + <script> + document.domain = "example.org"; + + for (var j = 1; j <= 9; j++) { + parent.i = j; + var locali = parent.i; + parent.is(locali, j, 'step ' + j + ' worked'); + } + + parent.finish(); + </script> + </body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug1005806.html b/js/xpconnect/tests/mochitest/test_bug1005806.html new file mode 100644 index 000000000..4f041c4be --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug1005806.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1005806 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1005806</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1005806">Mozilla Bug 1005806</a> +<p id="display"></p> +<div id="content" style="display: none"> + <input id="ipt"></input> +</div> +<pre id="test"> +</pre> +<script type="application/javascript"> + +/** Test for Bug 1005806 **/ +is(typeof document.getElementById('ipt').controllers, 'undefined', "Controllers property should not appear for content"); + +</script> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug1094930.html b/js/xpconnect/tests/mochitest/test_bug1094930.html new file mode 100644 index 000000000..434949360 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug1094930.html @@ -0,0 +1,29 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1094930 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1094930</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <iframe id="ifr"></iframe> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1094930">Mozilla Bug 1094930</a> +<p id="display"></p> +<script type="application/javascript"> + SimpleTest.waitForExplicitFinish(); + var proto = { + createdCallback: function() { + ok(true, "createdCallback was called"); + SimpleTest.finish() + } + }; + + var f = document.registerElement.call(frames[0].document, "x-foo", { prototype: proto }); + var inst = new f(); +</script> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug1158558.html b/js/xpconnect/tests/mochitest/test_bug1158558.html new file mode 100644 index 000000000..3d142e44a --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug1158558.html @@ -0,0 +1,47 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=1158558 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 1158558</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1158558">Mozilla Bug 1158558</a> +<p id="display"></p> +<div id="content" style="display: none"> + <input id="ipt"></input> +</div> +<pre id="test"> +</pre> +<script type="application/javascript"> + +/** Test for Bug 1158558 **/ + +// Observers of cycle-collector-begin can be implemented in JS, and +// thus can end up starting an incremental GC while we're in the middle +// of a CC slice. + +SimpleTest.waitForExplicitFinish(); + +var observer = { + observe: function(subject, topic, data) { + SpecialPowers.removeObserver(observer, "cycle-collector-begin"); + SpecialPowers.Cu.getJSTestingFunctions().startgc(1); + + ok(true, "Do something so the test harness doesn't get angry"); + + SimpleTest.finish(); + } +}; + +SpecialPowers.addObserver(observer, "cycle-collector-begin", false); + +SpecialPowers.Cu.forceCC(); + +</script> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug384632.html b/js/xpconnect/tests/mochitest/test_bug384632.html new file mode 100644 index 000000000..a5e02e448 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug384632.html @@ -0,0 +1,34 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=384632 +--> +<head> + <title>Test for Bug 384632</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=384632">Mozilla Bug 384632</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 384632 **/ +var Cc = SpecialPowers.Cc, Ci = SpecialPowers.Ci; +var propBag = Cc["@mozilla.org/hash-property-bag;1"].createInstance(Ci.nsIWritablePropertyBag); +var obj = {}; +propBag.setProperty("foopy", obj); +ok(SpecialPowers.unwrap(propBag.getProperty("foopy")) === obj, + "nsIVariant works with regular objects"); +propBag.setProperty("foopy1", sidebar); +ok(SpecialPowers.unwrap(propBag.getProperty("foopy1")) === sidebar, + "nsIVariant works with bizarre objects"); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug390488.html b/js/xpconnect/tests/mochitest/test_bug390488.html new file mode 100644 index 000000000..18b4c141c --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug390488.html @@ -0,0 +1,64 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=390488 +--> +<head> + <title>Test for Bug 390488</title> + <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=390488">Mozilla Bug 390488</a> +<p id="display"> + <div id="testdiv" onclick="checkForStacks();" style="visibility:hidden"> + </div> +</p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script class="testbody" type="text/javascript"> + +/** Test for Bug 390488 **/ + function getStack1() { + var func = arguments.callee.caller; + var stack = ""; + for (var i = 1; func && i < 8; i++) { + stack += " " + i + ". " + func.name; + func = func.caller; + } + return stack; + } + + function getStack2() { + var stack = new Error().stack; + // Remove the two lines due to calling this + return stack.substring(stack.indexOf("\n", stack.indexOf("\n")+1)+1); + } + + function simulateClick() { + var evt = document.createEvent("MouseEvents"); + evt.initMouseEvent("click", true, true, window, + 0, 0, 0, 0, 0, false, false, false, false, 0, null); + $("testdiv").dispatchEvent(evt); + } + + function matches(s, p, name) { + ok(s.match(p) != null, name, + "got " + uneval(s) + ", expected a string matching " + uneval(p)); + } + + function checkForStacks() { + matches(getStack1(), /checkForStacks .* onclick .* simulateClick/, + "Stack from walking caller chain should be correct"); + isnot(getStack2().indexOf("simulateClick@"), -1, + "Stack from |new Error().stack| should include simulateClick"); + } + + simulateClick(); +</script> +</pre> +</body> +</html> + diff --git a/js/xpconnect/tests/mochitest/test_bug393269.html b/js/xpconnect/tests/mochitest/test_bug393269.html new file mode 100644 index 000000000..048698854 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug393269.html @@ -0,0 +1,46 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=393269 +--> +<head> + <title>Test for Bug 393269</title> + <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=393269">Mozilla Bug 393269</a> +<iframe id="ifr"></iframe> +<pre id="test"> +<script class="testbody" type="text/javascript"> + +(function () { + /** Test for Bug 393269 **/ + var doc = $("ifr").contentDocument; + is("UTF-8", doc.characterSet, "control, getting a property"); + doc.open(); + try { + is("UTF-8", doc.characterSet, + "can get a property after 1 document.open") + } catch (e) { + fail("Shouldn't have thrown: " + e); + return; + } finally { + doc.close(); + } + + doc.open(); + try { + is("UTF-8", doc.characterSet, + "can get a property after 2 document.opens") + } catch (e) { + fail("Shouldn't have thrown: " + e); + } finally { + doc.close(); + } +})(); +</script> +</pre> +</body> +</html> + diff --git a/js/xpconnect/tests/mochitest/test_bug396851.html b/js/xpconnect/tests/mochitest/test_bug396851.html new file mode 100644 index 000000000..aa7a98c08 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug396851.html @@ -0,0 +1,41 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=396851 +--> +<head> + <title>Test for Bug 396851</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + + <script type="text/javascript"> + function go() { + var iframe = $("ifr"); + var win = iframe.contentWindow; + try { + var doc = win.document; + fail("Allowed cross-origin access to the document"); + } catch (e) { + ok(e.toString().match("Permission denied") != null, "Weird exception thrown"); + } + + doc = SpecialPowers.wrap(win).document; + ok(doc != null, "Able to access the cross-origin document"); + SimpleTest.finish(); + } + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=396851">Mozilla Bug 396851</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<script type="text/javascript"> + SimpleTest.waitForExplicitFinish(); +</script> +<iframe id="ifr" + src="http://example.org/tests/js/xpconnect/tests/mochitest/inner.html" + onload="go()"> +</iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug428021.html b/js/xpconnect/tests/mochitest/test_bug428021.html new file mode 100644 index 000000000..75c9edfce --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug428021.html @@ -0,0 +1,40 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=428021 +--> +<head> + <title>Test for Bug 428021</title> + <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=428021">Mozilla Bug 428021</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script class="testbody" type="text/javascript"> + + /** Test for Bug 428021 **/ + var rangetter, ransetter; + this.__defineGetter__('x', function() { rangetter = true; }); + this.__defineSetter__('x', function(val) { ransetter = true; }); + + var exn; + try { + e = x; + x = false; + } catch (e) { + exn = e; + } + ok(!exn, "Exception caught: " + exn); + ok(rangetter, "Failed to run getter"); + ok(ransetter, "Failed to run setter"); + +</script> +</pre> +</body> +</html> + diff --git a/js/xpconnect/tests/mochitest/test_bug446584.html b/js/xpconnect/tests/mochitest/test_bug446584.html new file mode 100644 index 000000000..4ad1c1d3c --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug446584.html @@ -0,0 +1,47 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=446584 +--> +<head> + <title>Test for Bug 446584</title> + <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=446584">Mozilla Bug 446584</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script class="testbody" type="text/javascript"> + +/** Test for Bug 446584 **/ + +function test(val) { + try { + document.createNodeIterator(document.body, + NodeFilter.SHOW_ALL, + function() { throw val }).nextNode(); + ok(false, "NodeIterator::nextNode() should have thrown an exception."); + } catch (ex) { + ok(val === ex, "NodeIterator did not properly forward exception " + + val + " of type " + typeof val + ". Thrown value was " + ex + "."); + } +} + +test(0); +test(1); +test(3.14); +test('roses'); +test({}); +test(false); +test(true); +test([1,2,3]); +test(function(){}); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug462428.html b/js/xpconnect/tests/mochitest/test_bug462428.html new file mode 100644 index 000000000..8655bc359 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug462428.html @@ -0,0 +1,51 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=462428 +--> +<head> + <title>Test for Bug 462428</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=462428">Mozilla Bug 462428</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 462428 **/ +var getter = document.__lookupGetter__('documentElement'); +ok(getter !== undefined, "But able to look it up the normal way"); +ok(!document.hasOwnProperty('documentElement'), "property should still be on the prototype"); + +var sawProp = false; +for (var i in document) { + if (i === "documentElement") { + sawProp = true; + } +} + +ok(sawProp, "property should be enumerable"); + +is(getter.call(document), document.documentElement, "the getter actually works"); + +Document.prototype.__defineSetter__('documentElement', function() {}); +is(getter.call(document), document.documentElement, "the getter works after defineSetter"); + +var oldTitle = document.title; +try { + var setter = document.__lookupSetter__('title'); + setter.call(document, "title 1"); + is(document.title, "title 1", "the setter is bound correctly"); +} finally { + document.title = oldTitle +} + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug478438.html b/js/xpconnect/tests/mochitest/test_bug478438.html new file mode 100644 index 000000000..76faa706c --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug478438.html @@ -0,0 +1,65 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=478438 +--> +<head> + <title>Test for Bug 478438</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript;version=1.8"> + function fail(s, e) { ok(false, s + e) } + function pass(s, e) { ok(true, s) } + (pass.opposite = fail).opposite = pass; + + function test() { + if (test.calledAlready) + return; + test.calledAlready = true; + + var iwin = document.getElementById("f").contentWindow; + + function testOne(fn, onAllow, infinitive) { + try { fn(); onAllow("able " + infinitive, "") } + catch (e) { onAllow.opposite("unable " + infinitive, ": " + e) } + } + + testOne(() => iwin.focus, pass, + "to resolve/get allAccess property iwin.focus"); + + testOne(() => iwin.focus(), pass, + "to call allAccess method iwin.focus"); + + testOne(() => iwin.alert, fail, + "to resolve/get restricted property iwin.alert"); + + testOne(() => iwin.alert(), fail, + "to call restricted method iwin.alert"); + + testOne(() => iwin.location.toString(), fail, + "to call restricted method iwin.location.toString"); + + testOne(function() { iwin.location = "http://example.org" }, pass, + "to set writable property iwin.location"); + + SimpleTest.finish(); + } + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=478438">Mozilla Bug 478438</a> +<p id="display"></p> +<div id="content"> + <iframe id="f" src="http://example.com" onload="test()"></iframe> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 478438 **/ + +SimpleTest.waitForExplicitFinish(); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug484107.html b/js/xpconnect/tests/mochitest/test_bug484107.html new file mode 100644 index 000000000..3bb82947e --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug484107.html @@ -0,0 +1,99 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=484107 +--> +<head> + <title>Test for Bug 484107</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=484107">Mozilla Bug 484107</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 484107 **/ + + var text = "first group", + xpcWin = new XPCSafeJSObjectWrapper(window); + function get$1() { return RegExp.$1 }; + + function reset() { + var match = /(.*)/.exec(text); + if (!reset.skipStupidTests) { + reset.skipStupidTests = true; + ok(match, "No match?"); + is(match[1], text, "Bad match?"); + is(text, RegExp.$1, "RegExp.$1 missing?"); + is(text, get$1(), "RegExp.$1 inaccessible?"); + } + } + + function test_XPC_SJOW_Call() { + isnot(text, xpcWin.get$1(), "Able to see RegExp.$1 from wrapped method."); + is("", xpcWin.get$1(), "Saw something other than an empty string for " + + "RegExp.$1 from wrapped method."); + is(text, window.get$1(), "Unable to see RegExp.$1 from non-wrapped method."); + } + + function test_XPC_SJOW_Call_foreign_obj() { + var obj = { + xpcGet: xpcWin.get$1, + rawGet: window.get$1 + }; + isnot(text, obj.xpcGet(), "obj.xpcGet() returned matched text."); + is("", obj.xpcGet(), "obj.xpcGet() returned something other than the empty string."); + is(text, obj.rawGet(), "obj.rawGet() did not return matched text."); + } + + function test_XPC_SJOW_toString() { + var str = new XPCSafeJSObjectWrapper({ + toString: function() { return RegExp.$1 } + }) + ""; + isnot(text, str, "toString() returned the matched text."); + is("", str, "toString() returned something other than the empty string."); + } + + function test_XPC_SJOW_GetOrSetProperty() { + window.__defineGetter__("firstMatch", function() { return RegExp.$1 }); + isnot(text, xpcWin.firstMatch, "Getter xpcWin.firstMatch returned matched text."); + is("", xpcWin.firstMatch, + "Getter xpcWin.firstMatch returned something other than the empty string."); + is(text, window.firstMatch, "Getter window.firstMatch did not return matched text."); + } + + function test_XPC_SJOW_Create() { + function ctor() { + this.match = RegExp.$1; + return this; // XXX Why is this necessary? + } + ctor.prototype.getMatch = function() { return this.match }; + var xpcCtor = new XPCSafeJSObjectWrapper(ctor), + match = (new xpcCtor).getMatch(); + isnot(text, match, "(new xpcCtor).getMatch() was the matched text."); + is("", match, "(new xpcCtor).getMatch() was not the empty string."); + } + + var tests = [ + test_XPC_SJOW_Call, + test_XPC_SJOW_Call_foreign_obj, + test_XPC_SJOW_toString, + test_XPC_SJOW_GetOrSetProperty, + test_XPC_SJOW_Create + ]; + + for (var i = 0; i < tests.length; i++) { + reset(); + tests[i](); + is(text, RegExp.$1, "RegExp.$1 was clobbered."); + } + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug500691.html b/js/xpconnect/tests/mochitest/test_bug500691.html new file mode 100644 index 000000000..d543e4c03 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug500691.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=500691 +--> +<head> + <title>Test for Bug 500691</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=500691">Mozilla Bug 500691</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 500691 **/ +ok(Function === alert.constructor, "alert's constructor is our Function"); +ok(window.Function === alert.constructor, "window.Function is also correct"); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug504877.html b/js/xpconnect/tests/mochitest/test_bug504877.html new file mode 100644 index 000000000..3b9fe9a52 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug504877.html @@ -0,0 +1,64 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=504877 +--> +<head> + <title>Test for Bug 504877</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=504877">Mozilla Bug 504877</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 504877 **/ +SimpleTest.waitForExplicitFinish(); +var p = 0; +function go() { + var ifr = $('ifr').contentWindow; + function test1() { + try { + ifr.foopy; + ok(false, "should have thrown a cross-origin access exception"); + } catch (e) { + ok(/Permission denied/.test(e), "Threw a permission denied exception"); + } + + var loc = ifr.location; + (function() { + netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); + ifr.blat = 42; + + is(ifr.blat, 42, "able to set random properties") + is(ifr.getblat(), 42, "setting properties propagates"); + is(ifr.foopy, 42, "able to use UniversalXPConnect to get random properties"); + + loc.replace; // resolves the property onto the wrapper. + })(); + + loc.replace("http://mochi.test:8888/"); + ok(true, "able to set location on the cross origin(!) frame"); + } + + function test2() { + SimpleTest.finish(); + } + + switch (++p) { + case 1: return test1(); + case 2: return test2(); + } +} + + +</script> +</pre> +<iframe src="http://example.org/tests/js/xpconnect/tests/mochitest/bug504877_helper.html" id="ifr" onload="go()"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug505915.html b/js/xpconnect/tests/mochitest/test_bug505915.html new file mode 100644 index 000000000..04c5da82a --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug505915.html @@ -0,0 +1,50 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=505915 +--> +<head> + <title>Test for Bug 505915</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=505915">Mozilla Bug 505915</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript;version=1.7"> + +/** Test for Bug 505915 **/ +window.addEventListener("message", function () { gen.next() }, false); + +function go() { + var ifr = $('ifr'); + try { + // NB: the contentDocument getter now returns null for cross-origin + // frames, so use SpecialPowers to get a security wrapper to the document. + var xdoc = SpecialPowers.unwrap(SpecialPowers.wrap(ifr).contentDocument) + document.createTreeWalker(xdoc, 0, null); + ok(false, "should have thrown a security exception"); + } catch (e) { + ok(/NS_ERROR_XPC_SECURITY_MANAGER_VETO/.test(e) || + /TypeError: Argument 1 of Document.createTreeWalker does not implement interface Node/.test(e), + "threw a security exception or binding exception instead of an " + + "invalid child exception"); + } + + SimpleTest.finish(); + yield; +} + +SimpleTest.waitForExplicitFinish(); + +</script> +</pre> + +<iframe id="ifr" onload="gen = go(); gen.next();" src="http://example.org/"></iframe> + +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug560351.html b/js/xpconnect/tests/mochitest/test_bug560351.html new file mode 100644 index 000000000..27c26335f --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug560351.html @@ -0,0 +1,36 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=560351 +--> +<head> + <title>Test for Bug 560351</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=560351">Mozilla Bug 560351</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 560351 **/ +var pass = false; +try { + document.body.__lookupGetter__("lastChild")(); +} catch (e) { + pass = true; +} + +</script> +<script> + +ok(pass, "pass was set to true"); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug585745.html b/js/xpconnect/tests/mochitest/test_bug585745.html new file mode 100644 index 000000000..a910bf376 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug585745.html @@ -0,0 +1,43 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=585745 +--> +<head> + <title>Test for Bug 585745</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=585745">Mozilla Bug 585745</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 585745 **/ + + var a = document.createElementNS("http://www.w3.org/1998/Math/MathML", 'mrow'); + var b = document.createElementNS("http://www.w3.org/1999/xhtml", 'span'); + var htmlProto = Object.getPrototypeOf(b); + var mathMLProto = Object.getPrototypeOf(a); + // XXXbz once bug 560072 is fixed, we should be able to use + // getOwnPropertyDescriptor here. + Object.defineProperty(mathMLProto, "style", { + get: htmlProto.__lookupGetter__("style"), + }); + + var threw = false; + try { + a.style; + } catch(e) { + threw = true; + } + is(threw, true, + "Getting .style off a mathml element should throw in this case"); +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug589028.html b/js/xpconnect/tests/mochitest/test_bug589028.html new file mode 100644 index 000000000..d25c9a901 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug589028.html @@ -0,0 +1,62 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=589028 +--> +<head> + <title>Test for Bug 589028</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=589028">Mozilla Bug 589028</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<pre id="test"> +<script> + +/** Test for Bug 589028 **/ +SimpleTest.waitForExplicitFinish(); +var p = 0; +function go() { + var ifr = $('ifr'); + var ifrwin = ifr.contentWindow; + var ifrdoc = ifr.contentDocument; + + o1 = new ifrwin.Option(); + is(o1.ownerDocument, ifrdoc, "ownerDocument doesn't match iframe"); + + o2 = ifrwin.getMyOption(); + is(o2.ownerDocument, ifrdoc, "ownerDocument doesn't match iframe"); + + o3 = ifrwin.getCallersOption(this); + is(o3.ownerDocument, document); + + a1 = new ifrwin.Audio(); + is(a1.ownerDocument, ifrdoc, "ownerDocument doesn't match iframe"); + + a2 = ifrwin.getMyAudio(); + is(a2.ownerDocument, ifrdoc, "ownerDocument doesn't match iframe"); + + a3 = ifrwin.getCallersAudio(this); + is(a3.ownerDocument, document); + + i1 = new ifrwin.Image(); + is(i1.ownerDocument, ifrdoc, "ownerDocument doesn't match iframe"); + + i2 = ifrwin.getMyImage(); + is(i2.ownerDocument, ifrdoc, "ownerDocument doesn't match iframe"); + + i3 = ifrwin.getCallersImage(this); + is(i3.ownerDocument, document); + + SimpleTest.finish(); +} + + +</script> +</pre> +<iframe src="bug589028_helper.html" id="ifr" onload="go()"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug601299.html b/js/xpconnect/tests/mochitest/test_bug601299.html new file mode 100644 index 000000000..375c858a6 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug601299.html @@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=601299 + +Trigger a fastnative from a frameless context. +--> +<head> + <title>Test for Bug 601299</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body onload="window.setTimeout(RegExp, 0); window.setTimeout(function() { ok(true); SimpleTest.finish(); }, 0);"> +<script> +SimpleTest.waitForExplicitFinish(); +</script> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug605167.html b/js/xpconnect/tests/mochitest/test_bug605167.html new file mode 100644 index 000000000..eaa4d2f67 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug605167.html @@ -0,0 +1,56 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=505915 +--> +<head> + <title>Test for Bug 505915</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=505915">Mozilla Bug 505915</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript;version=1.7"> + +/** Test for Bug 505915 **/ +var dataUrl = "data:text/html,<script>parent.f = function() { return this; };<" + "/script>"; +var targetUrl = "http://example.com"; +var f; + +var p = 0; +function go() { + switch (++p) { + case 1: + frames[0].location = dataUrl; + break; + case 2: + frames[0].location = targetUrl; + break; + case 3: + try { + f().cross_origin_property; + ok(false, "should have thrown an exception"); + } catch (e) { + ok(/Permission denied/.test(e) || /attempt to run compile-and-go script/.test(e), + "threw the correct exception"); + } + SimpleTest.finish(); + break; + } +} + + +SimpleTest.waitForExplicitFinish(); + +</script> +</pre> + +<iframe id="ifr" onload="go();"></iframe> + +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug618017.html b/js/xpconnect/tests/mochitest/test_bug618017.html new file mode 100644 index 000000000..c5b815e8d --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug618017.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=618017 + +Parsing XML must not override the version. +--> +<head> + <title>Test for Bug 618017</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> + +<script type='application/javascript;version=1.7'> +let x = 12; +function doLetEval() { + ok(eval('let x = 13; x') === 13, 'let statement is valid syntax in version 1.7'); +} +</script> + +<script type='application/javascript;version=1.5'> +doLetEval(); // Call to a function with a different version. +</script> + +</body> +</html> + diff --git a/js/xpconnect/tests/mochitest/test_bug623437.html b/js/xpconnect/tests/mochitest/test_bug623437.html new file mode 100644 index 000000000..c925932a5 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug623437.html @@ -0,0 +1,43 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=623437 +--> +<head> + <title>Test for Bug 623437</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=623437">Mozilla Bug 623437</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 623437 **/ + var c = document.createElement("canvas").getContext("2d"); + var seenArcToFirst; + var seenArc = false; + var seenArcTo = false; + for (var i in c) { + if (i == "arc") { + seenArc = true; + if (!seenArcTo) + seenArcToFirst = false; + } + if (i == "arcTo") { + seenArcTo = true; + if (!seenArc) + seenArcToFirst = true; + } + } + is(seenArc, true, "Should see arc"); + is(seenArcTo, true, "Should see arcTo"); + is(seenArcToFirst, true, "Should see arcTo before arc"); +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug628410.html b/js/xpconnect/tests/mochitest/test_bug628410.html new file mode 100644 index 000000000..1708ae393 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug628410.html @@ -0,0 +1,31 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=628410 +--> +<head> + <title>Test for Bug 628410</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=628410">Mozilla Bug 628410</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> + +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 628410 **/ +window.toSource(); +window.toString(); +InstallTrigger + ""; +console + ""; +ok(true, "Things didn't throw"); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug628794.html b/js/xpconnect/tests/mochitest/test_bug628794.html new file mode 100644 index 000000000..115b6118f --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug628794.html @@ -0,0 +1,43 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=585745 +--> +<head> + <title>Test for Bug 585745</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=585745">Mozilla Bug 585745</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 585745 **/ + + var a = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); + var b = document.createElementNS("http://www.w3.org/1999/xhtml", 'span'); + var htmlProto = Object.getPrototypeOf(b); + var svgProto = Object.getPrototypeOf(a); + // XXXbz once bug 560072 is fixed, we should be able to use + // getOwnPropertyDescriptor here. + Object.defineProperty(svgProto, "style", { + get: htmlProto.__lookupGetter__("style"), + }); + + var threw = false; + try { + a.style; + } catch(e) { + threw = true; + } + is(threw, true, + "Getting .style off an svg element should throw in this case"); +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug629227.html b/js/xpconnect/tests/mochitest/test_bug629227.html new file mode 100644 index 000000000..0ed381285 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug629227.html @@ -0,0 +1,47 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=629227 +--> +<head> + <title>Test for Bug 629227</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=629227">Mozilla Bug 629227</a> +<p id="display"> + <iframe id="testTarget"></iframe> +</p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 629227 **/ +SimpleTest.waitForExplicitFinish(); + +$("testTarget").src = + "http://test1.example.org" + + location.pathname.replace(/test_bug629227.html/, "file1_bug629227.html"); + +window.onmessage = function(ev) { + if (ev.data == "finish") { + SimpleTest.finish(); + } else { + var data = JSON.parse(ev.data); + if ("ok" in data) { + ok(data.ok, data.reason); + } + } +} + +addLoadEvent(function() { + $("testTarget").contentWindow.postMessage("start", "*"); +}); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug629331.html b/js/xpconnect/tests/mochitest/test_bug629331.html new file mode 100644 index 000000000..413ec9d7b --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug629331.html @@ -0,0 +1,37 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=629331 +--> +<head> + <title>Test for Bug 629331</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=629331">Mozilla Bug 629331</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> +SimpleTest.waitForExplicitFinish(); + +function handler(event) { + var obj = JSON.parse(event.data); + if (obj.fun == "finish") { + SimpleTest.finish(); + } else { + is(obj.a, obj.b, obj.description); + } +} + +window.addEventListener('message', handler, false); + +</script> +<iframe src="http://test1.example.org/tests/js/xpconnect/tests/mochitest/test1_bug629331.html"> +</iframe> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug636097.html b/js/xpconnect/tests/mochitest/test_bug636097.html new file mode 100644 index 000000000..09fd695a8 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug636097.html @@ -0,0 +1,62 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=504877 +test by moz_bug_r_a4@yahoo.com +--> +<head> + <title>Test for Bug 504877</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=504877">Mozilla Bug 504877</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 504877 **/ +SimpleTest.waitForExplicitFinish(); + +var targetUrl = "http://example.com/"; +var l; + +function a() { + var r = "FAIL", s; + try { + s = l.toString(); + } + catch (e) { + if (/denied|insecure/.test(e)) + r = "PASS"; + s = e; + } + + is(r, "PASS", "should have thrown an exception"); + SimpleTest.finish(); +} + +var p = 0; +function b() { + switch (++p) { + case 1: + frames[0].location = "about:blank"; + break; + case 2: + l = frames[0].location; + frames[0].location = targetUrl; + break; + case 3: + a(); + break; + } +} +</script> + +</pre> +<iframe onload="b()"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug650273.html b/js/xpconnect/tests/mochitest/test_bug650273.html new file mode 100644 index 000000000..37f6609d8 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug650273.html @@ -0,0 +1,42 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=650273 +test by moz_bug_r_a4@yahoo.com +--> +<head> + <title>Test for Bug 650273</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" +href="https://bugzilla.mozilla.org/show_bug.cgi?id=650273">Mozilla Bug 650273</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 504877 **/ +SimpleTest.waitForExplicitFinish(); +var count = 0; +function done() { + if (++count == 2) { + try { + ok($('ifr').location.host === 'example.com', "shouldn't see this"); + } catch (e) { + ok(true, "navigation successfully happened"); + } + SimpleTest.finish(); + } +} + +</script> + +<iframe id="ifr" src="file_bug650273.html" onload="done()"></iframe> + +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug655297-1.html b/js/xpconnect/tests/mochitest/test_bug655297-1.html new file mode 100644 index 000000000..8f615762f --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug655297-1.html @@ -0,0 +1,49 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=655297 +--> +<head> + <title>Test for Bug 655297</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=655297">Mozilla Bug 655297</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> + <form>0</form> <form>1</form> <form>2</form> <form>3</form> <form>4</form> + <form>5</form> <form>6</form> <form>7</form> <form>8</form> <form>9</form> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 655297 **/ + +var map = new WeakMap(); +function f() { + var paras = document.getElementsByTagName("form"); + for (var i = 0; i < paras.length; i++) + map.set(paras[i], "ok"); +} +function g() { + var paras = document.getElementsByTagName("form"); + for (var i = 0; i < paras.length; i++) { + if (map.get(paras[i]) != "ok") { + return false; + } + } + return true; +} + +f(); +SpecialPowers.forceGC(); +ok(g(), "Failed to keep XPCWrappedNative used as WeakMap key alive."); + +</script> + + +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug655297-2.html b/js/xpconnect/tests/mochitest/test_bug655297-2.html new file mode 100644 index 000000000..2a99557d2 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug655297-2.html @@ -0,0 +1,49 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=655297 +--> +<head> + <title>Test for Bug 655297</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=655297">Mozilla Bug 655297</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> + <p>0</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> + <p>5</p> <p>6</p> <p>7</p> <p>8</p> <p>9</p> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 655297 **/ + +var map = new WeakMap(); +function f() { + var paras = document.getElementsByTagName("p"); + for (var i = 0; i < paras.length; i++) + map.set(paras[i], "ok"); +} +function g() { + var paras = document.getElementsByTagName("p"); + for (var i = 0; i < paras.length; i++) { + if (map.get(paras[i]) != "ok") { + return false; + } + } + return true; +} + +f(); +SpecialPowers.forceGC(); +ok(g(), "Failed to keep XPCWrappedNative used as WeakMap key alive."); + +</script> + + +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug661980.html b/js/xpconnect/tests/mochitest/test_bug661980.html new file mode 100644 index 000000000..e372c1ee0 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug661980.html @@ -0,0 +1,61 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=661980 +--> +<head> + <title>Test for Bug 661980</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=661980">Mozilla Bug 661980</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 661980 **/ + +// While not currently needed, make this as similar as possible to a real +// EventTarget just to make sure that we're tripping on the wrapping and +// nothing else. +var fakeTarget = { + addEventListener: function() {}, + removeEventListener: function() {}, + dispatchEvent: function() {} +} + +var mouseevent = document.createEvent("MouseEvent"); +var didThrow = false; +dump("hello nurse\n"); +try { + mouseevent.initMouseEvent("mouseover", + false, false, + window, + 1, 2, 3, 4, 5, + false, false, false, false, + 0, + fakeTarget); +} +catch (ex) { + didThrow = true; +} +ok(didThrow, "should not be able to implement EventTarget using script"); + +mouseevent.initMouseEvent("mouseout", + false, false, + window, + 1, 2, 3, 4, 5, + false, false, false, false, + 0, + document.body); +is(mouseevent.type, "mouseout", + "should able to implement EventTarget using Element"); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug691059.html b/js/xpconnect/tests/mochitest/test_bug691059.html new file mode 100644 index 000000000..830cf7b5d --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug691059.html @@ -0,0 +1,59 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=691059 +--> +<head> + <title>Test for Bug 691059</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=691059">Mozilla Bug 691059</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + + +/** Test for Bug 691059 **/ + +function f() {} + +function testEventTarget(obj) { + obj.onmouseenter = f; + is(obj.onmouseenter, f, + "onmouseenter should be settable"); + obj.onmouseleave = f; + is(obj.onmouseleave, f, + "onmouseenter should be settable"); +} + +function testInterface(obj) { + try { + obj.prototype.onmouseenter = f; + is("onmouseenter" in obj, false, + "setting <Interface>.prototype.onmouseenter has no effect on the " + + "non-existent <Interface>.onmouseenter"); + obj.prototype.onmouseleave = f; + is("onmouseleave" in obj, false, + "setting <Interface>.prototype.onmouseleave has no effect on the " + + "non-existent <Interface>.onmouseleave"); + } catch(ex) { + ok(false, ex); + } +} + +testEventTarget(window); +testEventTarget(document); +testEventTarget(document.documentElement); + +testInterface(Document); +testInterface(HTMLElement); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug720619.html b/js/xpconnect/tests/mochitest/test_bug720619.html new file mode 100644 index 000000000..bf973a30a --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug720619.html @@ -0,0 +1,55 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=720619 +--> +<head> + <title>Test for Bug 629227</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=720619">Mozilla Bug 720619</a> +<p id="display"> + <iframe id="testTarget"></iframe> +</p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 720619 **/ +SimpleTest.waitForExplicitFinish(); + +function checkThrows(f, exception) { + try { + f(); + ok(false, "should have thrown: " + f); + } catch (e) { + ok(exception.test(e.toString()), "correctly threw"); + } +} + +function go() { + var loc = $('ifr').contentWindow.location; + checkThrows(function() {loc + '';}, /Permission denied/); + checkThrows(function() {'' + loc;}, /Permission denied/); + checkThrows(function() {String(loc);}, /Permission denied/); + + var win = $('ifr').contentWindow; + checkThrows(function() {win + '';}, /Permission denied/); + checkThrows(function() {'' + win;}, /Permission denied/); + checkThrows(function() {String(win);}, /Permission denied/); + + SimpleTest.finish(); +} + +</script> + +<iframe id="ifr" onload="go()" + src="http://example.org/tests/js/xpconnect/tests/mochitest/file_bug720619.html"> +</iframe> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug731471.html b/js/xpconnect/tests/mochitest/test_bug731471.html new file mode 100644 index 000000000..02f50d401 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug731471.html @@ -0,0 +1,42 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=731471 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 731471</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body onload="setTimeout(boom, 0);"> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=731471">Mozilla Bug 731471</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 731471. This is effectively a crashtest, but it uses window.open, which + doesn't work in the crashtest harness. **/ +SimpleTest.waitForExplicitFinish(); +SimpleTest.requestFlakyTimeout("untriaged"); +function boom() +{ + w = window.open("data:text/html,1"); + setTimeout(function() { + w.document.write("2"); + w.document.close(); + w.document.write("3 - Done"); + w.document.close(); + w.close(); + ok(true, "Didn't assert!"); + SimpleTest.finish(); + }, 400); +} + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug764389.html b/js/xpconnect/tests/mochitest/test_bug764389.html new file mode 100644 index 000000000..3af46c51b --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug764389.html @@ -0,0 +1,40 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=764389 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 764389</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=764389">Mozilla Bug 764389</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 764389 **/ + +// This is basically a crash test, but we need to write a mochitest so that it +// runs with http:// urls instead of file:// urls. +SimpleTest.waitForExplicitFinish(); + +function go() { + var ifr = document.getElementById('ifr'); + ifr.contentDocument.open(); + ok(true, "Didn't crash"); + ifr.contentDocument.close(); + SimpleTest.finish(); +} + + + +</script> +<iframe id="ifr" onload="go();" src="file_empty.html"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug772288.html b/js/xpconnect/tests/mochitest/test_bug772288.html new file mode 100644 index 000000000..fba63f1a8 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug772288.html @@ -0,0 +1,50 @@ +<!DOCTYPE html> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=772288 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 772288</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body onload="doTest()"> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=772288">Mozilla Bug 772288</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 772288 **/ +SimpleTest.waitForExplicitFinish(); + +const Cu = SpecialPowers.Cu; + +function doTest() { + msg = "Services should be imported on window"; + try { + Cu.import("resource://gre/modules/Services.jsm", window); + ok(Services, msg); + } catch (ex) { + ok(false, msg + " : " + ex); + } + + msg = "Services should be imported on myObj"; + try { + var myObj = {}; + Cu.import("resource://gre/modules/Services.jsm", myObj); + ok(myObj.Services, msg); + } catch (ex) { + ok(false, msg + " : " + ex); + } + + SimpleTest.finish(); +} + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug781476.html b/js/xpconnect/tests/mochitest/test_bug781476.html new file mode 100644 index 000000000..f01cedfd4 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug781476.html @@ -0,0 +1,36 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=781476 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 781476</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=781476">Mozilla Bug 781476</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 781476 **/ +SimpleTest.waitForExplicitFinish(); + +function go() { + var iwin = document.getElementById('ifr').contentWindow; + iwin.is = is; + var evt = iwin.makeEvent(); + is(evt.expando, 42, "Expando properly visible in caller frame"); + SimpleTest.finish(); +} + + +</script> +</pre> +<iframe onload="go();" id="ifr" src="file_bug781476.html"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug789713.html b/js/xpconnect/tests/mochitest/test_bug789713.html new file mode 100644 index 000000000..58ebf2fb2 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug789713.html @@ -0,0 +1,39 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=789713 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 789713</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=789713">Mozilla Bug 789713</a> +<p id="display"></p> +<div id="content" style="display: none"> +<iframe id="ifr"></iframe> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 789713 **/ + +// We can't set document.domain on mochi.test, because it's forbidden to set +// document.domain to a TLD. +var ifr = document.getElementById('ifr'); + +SimpleTest.waitForExplicitFinish(); +ifr.src = window.location.toString().replace("mochi.test:8888", "test1.example.org") + .replace("test_bug789713", "file_bug789713") + .split('?')[0]; +window.onmessage = function(message) { + ok(message.data, "Test succeeded and didn't crash"); + SimpleTest.finish(); +} + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug790732.html b/js/xpconnect/tests/mochitest/test_bug790732.html new file mode 100644 index 000000000..48b7fdbb6 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug790732.html @@ -0,0 +1,62 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=790732 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 790732</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + // Basic stuff + ok(Components, "Components shim exists!"); + var Ci = Components.interfaces; + ok(Ci, "interfaces shim exists!"); + is(typeof Components.classes, 'undefined', "Shouldn't have a Cc"); + + // Check each interface that we shim. We start by checking specific + // constants for a couple of interfaces, and then once it's pretty clear that + // it's working as intended we just check that the objects themselves are the + // same. + is(Ci.nsIXMLHttpRequest.HEADERS_RECEIVED, XMLHttpRequest.HEADERS_RECEIVED); + is(Ci.nsIDOMDOMException.DATA_CLONE_ERR, DOMException.DATA_CLONE_ERR); + is(Ci.nsIDOMNode.DOCUMENT_NODE, Node.DOCUMENT_NODE); + is(Ci.nsIDOMCSSPrimitiveValue.CSS_PX, CSSPrimitiveValue.CSS_PX); + is(Ci.nsIDOMCSSRule.NAMESPACE_RULE, CSSRule.NAMESPACE_RULE); + is(Ci.nsIDOMCSSValue.CSS_PRIMITIVE_VALUE, CSSValue.CSS_PRIMITIVE_VALUE); + is(Ci.nsIDOMEvent.FOCUS, Event.FOCUS); + is(Ci.nsIDOMNSEvent.CLICK, Event.CLICK); + is(Ci.nsIDOMKeyEvent, KeyEvent); + is(Ci.nsIDOMMouseEvent, MouseEvent); + is(Ci.nsIDOMMouseScrollEvent, MouseScrollEvent); + is(Ci.nsIDOMMutationEvent, MutationEvent); + is(Ci.nsIDOMSimpleGestureEvent, SimpleGestureEvent); + is(Ci.nsIDOMUIEvent, UIEvent); + is(Ci.nsIDOMHTMLMediaElement, HTMLMediaElement); + is(Ci.nsIDOMOfflineResourceList, OfflineResourceList); + is(Ci.nsIDOMRange, Range); + is(Ci.nsIDOMSVGLength, SVGLength); + is(Ci.nsIDOMNodeFilter, NodeFilter); + is(Ci.nsIDOMXPathResult, XPathResult); + + // Test for Bug 895231 + for (var k of Object.keys(Components.interfaces)) { + ok(SpecialPowers.Ci.hasOwnProperty(k), + k + " should be removed from the Components shim"); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=790732">Mozilla Bug 790732</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +<iframe id="ifr"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug793969.html b/js/xpconnect/tests/mochitest/test_bug793969.html new file mode 100644 index 000000000..0936967bd --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug793969.html @@ -0,0 +1,53 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=793969 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 793969</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=793969">Mozilla Bug 793969</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 793969 **/ +function checkThrows(f, desc, skipMessageCheck) { + try { + f(); + ok(false, "Should have thrown for " + desc); + } catch (e) { + ok(true, "threw correctly"); + if (!skipMessageCheck) + ok(/denied/.exec(e) || + /can't redefine non-configurable property/.exec(e), + "Correctly threw a security exception: " + e); + } +} + +// NB: These sets will be no-ops (throw in strict mode) because setting an inherited readonly value prop has those semantics. +checkThrows(function() { "use strict"; location.valueOf = 'hah'; }, 'Shadow with string', /* skipMessageCheck = */ true); +checkThrows(function() { "use strict"; location.valueOf = function() { return {a: 'hah'};} }, 'Shadow with function', /* skipMessageCheck = */ true); +checkThrows(function() { Object.defineProperty(location, 'valueOf', { value: function() { return 'hah'; } }); }, 'defineProperty with value'); +checkThrows(function() { delete location.valueOf; Object.defineProperty(location, 'valueOf', { value: function() { return 'hah'; } }); }, 'delete + defineProperty with value'); +checkThrows(function() { Object.defineProperty(location, 'valueOf', { get: function() { return 'hah'; } }); }, 'defineProperty with getter'); +checkThrows(function() { delete location.valueOf; Object.defineProperty(location, 'valueOf', { get: function() { return 'hah'; } }); }, 'delete + defineProperty with getter'); + +Object.prototype.valueOf = function() { return 'hah'; }; +is(({}).valueOf(), 'hah', "Shadowing on Object.prototype works for vanilla objects"); +is(location.valueOf(), location, "Shadowing on Object.prototype and Location.prototype doesn't for location objects"); + +location[Symbol.toPrimitive] = function() { return 'hah'; } +is(location + "", location.toString(), "Should't be able to shadow with toPrimitive"); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug800864.html b/js/xpconnect/tests/mochitest/test_bug800864.html new file mode 100644 index 000000000..560dda072 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug800864.html @@ -0,0 +1,51 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=800864 +--> +<head> + <title>Test for Bug 800864</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=800864">Mozilla Bug 800864</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +SimpleTest.waitForExplicitFinish(); + +function checkThrows(f) { + try { + f(); + ok(false, "Didn't throw a security exception like we should"); + } catch(e) { + ok(/denied|insecure/.exec(e), "Should throw security exception. Got: " + e); + } +} + +function go() { + ifr = document.getElementById('ifr'); + win = ifr.contentWindow; + loc = win.location; + ifr.onload = check; + win.location = 'http://test1.example.com'; +} + +function check() { + checkThrows(function() { loc.toString(); }); + checkThrows(function() { loc.valueOf().toString(); }); + checkThrows(function() { loc.href; }); + checkThrows(function() { loc + ''; }); + SimpleTest.finish(); +} + +</script> +</pre> +</body> +<iframe id="ifr" onload="go()" src="file_empty.html"></iframe> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug802557.html b/js/xpconnect/tests/mochitest/test_bug802557.html new file mode 100644 index 000000000..073f22e72 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug802557.html @@ -0,0 +1,116 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=802557 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 802557</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 802557 **/ + SimpleTest.waitForExplicitFinish(); + + function checkThrows(fun, desc) { + try { + fun(); + ok(false, "Didn't throw when " + desc); + } catch(e) { + ok(true, "Threw when " + desc + " " + e); + ok(/denied|insecure/.exec(e), "Should be security exception"); + } + } + + var loadCount = 0; + function go() { + ++loadCount; + window.ifr = document.getElementById('ifr'); + window.iWin = ifr.contentWindow; + + if (loadCount == 1) { + gLoc = iWin.location; + // Note that accessors pulled off Xrays are currently bound. This is bug 658909. + // [getter, description, locationObj, bound] + gGetters = [[ location.toString, 'toString from LW' ], + [ gLoc.toString, 'toString from XLW' ], + [ Object.__lookupGetter__.call(location, 'href'), 'href getter from LW' ], + [ Object.__lookupGetter__.call(gLoc, 'href'), 'href getter from XLW' ], + [ Object.getOwnPropertyDescriptor(location, 'href').get, 'href getter from location' ], + [ Object.getOwnPropertyDescriptor(gLoc, 'href').get, 'href getter from iWin.location' ], + [ function() { return this + ''; }, 'implicit conversion via [[DefaultValue]]', /* doMessageCheck = */ true ]]; + gGetters.forEach(function(item) { + try { + is(item[0].call(location), location.toString(), 'Same-origin LW: ' + item[1]); + is(item[0].call(gLoc), gLoc.toString(), 'Same-origin XLW: ' + item[1]); + } catch (e) { + ok(false, "Threw while applying " + item[1] + " to same-origin location object: " + e); + } + }); + ifr.src = "http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"; + } + else if (loadCount == 2) { + gGetters.forEach(function(item) { + checkThrows(function() { item[0].call(gLoc); }, + 'call()ing ' + item[1] + ' after navigation cross-origin'); + }); + ifr.src = 'http://mochi.test:8888/tests/js/xpconnect/tests/mochitest/file_bug802557.html'; + } + else if (loadCount == 3) { + gTestFunctions = ifr.contentWindow.getAllTests(); + var win = ifr.contentWindow; + for (fun in gTestFunctions) + is(gTestFunctions[fun](), win.location.toString(), "allowed via " + fun); + win.location = 'http://example.org/tests/js/xpconnect/tests/mochitest/file_bug802557.html'; + } + else if (loadCount == 4) { + for (fun in gTestFunctions) { + var f = gTestFunctions[fun]; + checkThrows(f, "calling " + fun); + } + + // Verify that URL.prototype.toString can't be applied to Location + var threw = false; + try { + URL.prototype.toString.call(location); + } catch (e) { + threw = true; + } + ok(threw, + "Should not be able to use URL.prototype.toString on a Location instance"); + + // Verify that URL.prototype.href getter can't be applied to Location + threw = false; + var reachedTest = false; + try { + var get = Object.getOwnPropertyDescriptor(URL.prototype, "href").get; + is(typeof(get), "function", "Should have an href getter on URL.prototype"); + var reachedTest = true; + get.call(location); + } catch (e) { + threw = true; + } + ok(reachedTest, + "Should not be able to find URL.prototype.href getter"); + ok(threw, + "Should not be able to use URL.prototype.href getter on a Location instance"); + SimpleTest.finish(); + } + } + + + +</script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=802557">Mozilla Bug 802557</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<iframe id="ifr" onload="go();" src="file_empty.html"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug803730.html b/js/xpconnect/tests/mochitest/test_bug803730.html new file mode 100644 index 000000000..4a1552f4f --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug803730.html @@ -0,0 +1,41 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=803730 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 803730</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=803730">Mozilla Bug 803730</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 803730 **/ +var foo = { + isNode: function(obj) { + return !!(obj instanceof Node); + } +}; + +var elem = document.createElement("span"); +var trueCount = 0, + falseCount = 0; +for (var x = 0; x < 100000; x++) { + if (foo.isNode(elem)) + trueCount++; + else + falseCount++; +} +is(falseCount, 0, "elem instanceof Node working correctly."); + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug809547.html b/js/xpconnect/tests/mochitest/test_bug809547.html new file mode 100644 index 000000000..c2c87623f --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug809547.html @@ -0,0 +1,42 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=809547 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 809547</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body onload="go()"> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=809547">Mozilla Bug 809547</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 809547 **/ +SimpleTest.waitForExplicitFinish(); +var gObj = {}; +function go() { + window.location.expando = gObj; + is(window.location.expando, gObj, "Expando appears"); + SimpleTest.executeSoon(finish); +} + +function finish() { + SpecialPowers.forceGC(); + SpecialPowers.forceCC(); + SpecialPowers.forceGC(); + SpecialPowers.forceCC(); + is(window.location.expando, gObj, "Expando preserved"); + SimpleTest.finish(); +} + +</script> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug829872.html b/js/xpconnect/tests/mochitest/test_bug829872.html new file mode 100644 index 000000000..9c48983e8 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug829872.html @@ -0,0 +1,52 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=829872 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 829872</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 829872 and Bug 968003 **/ + SimpleTest.waitForExplicitFinish(); + + var gLoadCount = 0; + function loaded() { + if (++gLoadCount == 3) + go(); + } + + function check(elem, desc) { + is(elem.contentDocument, null, "null cross-origin contentDocument for " + desc); + ok(SpecialPowers.wrap(elem).contentWindow.eval('frameElement === null;'), + "null cross-origin frameElement for " + desc); + if (!(elem instanceof HTMLFrameElement)) + is(elem.getSVGDocument(), null, "null cross-origin getSVGDocument() for " + desc); + } + + function go() { + ok(true, "Starting test"); + check($('ifr'), "iframe element"); + check($('obj'), "object element"); + check($('framesetholder').contentDocument.getElementById('fr'), "frameset frame"); + SimpleTest.finish(); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=829872">Mozilla Bug 829872</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +<iframe id="ifr" onload="loaded();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +<object id="obj" onload="loaded();" data="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></object> +<iframe id="framesetholder" src="data:text/html,<html><head></head><frameset cols='100%'><frame id='fr' onload='parent.loaded();' src='http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html' /></frameset></html>"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug862380.html b/js/xpconnect/tests/mochitest/test_bug862380.html new file mode 100644 index 000000000..0d3fb7329 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug862380.html @@ -0,0 +1,43 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=862380 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 862380</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 862380 **/ + SimpleTest.waitForExplicitFinish(); + function go() { + checkNotEnumerable($('ifr').contentWindow); + checkNotEnumerable($('ifr').contentWindow.location); + SimpleTest.finish(); + } + + function checkNotEnumerable(obj) { + try { + is(Object.keys(obj).length, 0, "Object.keys gives empty array"); + for (var i in obj) + ok(false, "Enumerated something: " + i); + } catch (e) { + ok(false, "threw: " + e); + } + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=862380">Mozilla Bug 862380</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug865260.html b/js/xpconnect/tests/mochitest/test_bug865260.html new file mode 100644 index 000000000..8878e9df5 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug865260.html @@ -0,0 +1,33 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=865260 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 865260</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 865260 **/ + SimpleTest.waitForExplicitFinish(); + function go() { + var exn = "nothrow"; + try { $('ifr').contentWindow['Date']; } catch (e) { exn = e; }; + ok(!!/denied/.exec(exn), "Threw instead of crashing"); + SimpleTest.finish(); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=865260">Mozilla Bug 865260</a> +<p id="display"></p> +<div id="content"> +<iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug870423.html b/js/xpconnect/tests/mochitest/test_bug870423.html new file mode 100644 index 000000000..6fce43527 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug870423.html @@ -0,0 +1,51 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=870423 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 870423</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for cross-scope instanceof. **/ + SimpleTest.waitForExplicitFinish(); + + function go() { + var sowin = $('soifr').contentWindow; + var xowin = $('xoifr').contentWindow; + + check(window, sowin, 'HTMLBodyElement', function(win) { return win.document.body; }); + check(window, sowin, 'HTMLDocument', function(win) { return win.document; }); + check(window, sowin, 'Window', function(win) { return win; }); + check(window, sowin, 'Location', function(win) { return win.location; }); + + ok(xowin instanceof Window, "Cross-origin instanceof should work"); + ok(xowin.location instanceof Location, "Cross-origin instanceof should work"); + + SimpleTest.finish(); + } + + function check(win1, win2, constructorName, getInstance) { + ok(getInstance(win1) instanceof win2[constructorName], + "Cross-Scope instanceof works: " + constructorName + ", " + win1.location + ", " + win2.location); + ok(getInstance(win2) instanceof win1[constructorName], + "Cross-Scope instanceof works: " + constructorName + ", " + win2.location + ", " + win1.location); + } + + </script> +</head> +<body onload="go();"> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=870423">Mozilla Bug 870423</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<iframe id="soifr" src="file_empty.html"></iframe> +<iframe id="xoifr" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug871887.html b/js/xpconnect/tests/mochitest/test_bug871887.html new file mode 100644 index 000000000..89239eb44 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug871887.html @@ -0,0 +1,43 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=871887 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 871887</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript;version=1.7"> + + /** Test for Bug 871887 **/ + SimpleTest.waitForExplicitFinish(); + + // NB: onstart ends up getting invoked twice, for mysterious and potentially- + // IE6-related reasons. + function checkpoint(invocant) { + ok(true, "onstart called"); + is(invocant, $('llama'), "this-binding is correct"); + $('llama').loop = 1; + $('llama').scrollDelay = 1; + $('llama').scrollAmount = 500; + } + + function done(invocant) { + is(invocant, $('llama'), "this-binding is correct"); + ok(true, "onfinish called"); + SimpleTest.finish(); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=871887">Mozilla Bug 871887</a> +<p id="display"></p> +<div id="content"> +<marquee id="llama" onstart="checkpoint(this);" onfinish="done(this);">Watch the Llama</marquee> +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug912322.html b/js/xpconnect/tests/mochitest/test_bug912322.html new file mode 100644 index 000000000..c274b6afc --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug912322.html @@ -0,0 +1,36 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=912322 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 912322</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test that XBL functions aren't exposed to the web. **/ + funs = ['getAnonymousNodes', 'getAnonymousElementByAttribute', + 'getBindingParent', 'loadBindingDocument']; + for (var f of funs) { + ok(!(f in document), f + " should not be available to content"); + ok(f in SpecialPowers.wrap(document), f + " should be available to chrome via Xray"); + } + + // Test window.controllers. + ok(typeof window.controllers, 'undefined', "controllers should not be available to content"); + ok(typeof SpecialPowers.wrap(window).controllers, 'object', "controllers should be available over Xray"); + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=912322">Mozilla Bug 912322</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug916945.html b/js/xpconnect/tests/mochitest/test_bug916945.html new file mode 100644 index 000000000..078f2a445 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug916945.html @@ -0,0 +1,62 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=916945 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 916945</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 916945 **/ + SimpleTest.waitForExplicitFinish(); + + var gLoadCount = 0; + function loaded() { + if (++gLoadCount == 2) + go(); + } + function go() { + // Both same-origin and cross-origin names should be visible if they're set + // on the iframe element. + ok('winA' in window, "same-origin named access works"); + ok(winA instanceof Window, "same-origin named access works"); + ok('winB' in window, "cross-origin named access works when iframe name matches"); + // XXXbholley - flip me when Window moves to new bindings. + todo_is(winB instanceof Window, "cross-origin named access works when iframe name matches"); + + // Setting the 'name' attribute should propagate to the docshell. + var ifrB = document.getElementById('ifrB'); + ifrB.setAttribute('name', 'foo'); + is(SpecialPowers.wrap(ifrB).contentWindow.name, 'foo', 'attribute sets propagate to the docshell'); + ok('foo' in window, "names are dynamic if updated via setAttribute"); + // XXXbholley - flip me when Window moves to new bindings. + todo('foo' instanceof Window, "names are dynamic if updated via setAttribute"); + + // Setting window.name on the subframe should not propagate to the attribute. + SpecialPowers.wrap(ifrB).contentWindow.name = 'bar'; + is(ifrB.getAttribute('name'), 'foo', 'docshell updates dont propagate to the attribute'); + + // When the frame element attribute and docshell name don't match, nothing is returned. + ok(!('foo' in window), "frame element name not resolved if it doesn't match the docshell"); + ok(!('bar' in window), "docshell name not resolved if it doesn't match the frame element"); + + SimpleTest.finish(); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=916945">Mozilla Bug 916945</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<iframe id="ifrA" name="winA" onload="loaded();" src="file_empty.html"></iframe> +<iframe id="ifrB" name="winB" onload="loaded();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug92773.html b/js/xpconnect/tests/mochitest/test_bug92773.html new file mode 100644 index 000000000..4cec5eae6 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug92773.html @@ -0,0 +1,43 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=92773 +--> +<head> + <title>Test for Bug 92773</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=92773">Mozilla Bug 92773</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> + +<pre id="test"> +<script type="application/javascript"> + +/** Test for Bug 92773 **/ +function go() { + try { + $('ifr').contentWindow.foo; + ok(false, "able to access cross-origin getter"); + } catch (e) { + ok(/Permission denied/.exec(e), "unable to access cross-origin getter"); + } + + SimpleTest.finish(); +} +SimpleTest.waitForExplicitFinish(); + +</script> +</pre> + +<iframe id='ifr' + src='http://example.com/tests/js/xpconnect/tests/mochitest/bug92773_helper.html' + onload="go()"> +</iframe> + +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug940783.html b/js/xpconnect/tests/mochitest/test_bug940783.html new file mode 100644 index 000000000..9e9e49084 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug940783.html @@ -0,0 +1,62 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=940783 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 940783</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 940783 **/ + SimpleTest.waitForExplicitFinish(); + + function checkHistoryThrows(hist) { + checkThrows(function() { hist.length; }); + checkThrows(function() { hist.state; }); + checkThrows(function() { hist.go(); }); + checkThrows(function() { hist.back(); }); + checkThrows(function() { hist.forward(); }); + checkThrows(function() { hist.pushState({}, "foo"); }); + checkThrows(function() { hist.replaceState({}, "foo"); }); + + } + + window.gLoads = 0; + function load() { + var iwin = $('ifr').contentWindow; + ++gLoads; + if (gLoads == 1) { + window.gHist = iwin.history; + iwin.location = "file_empty.html"; + } else if (gLoads == 2) { + checkHistoryThrows(gHist); + window.gHist = iwin.history; + iwin.location = "http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"; + } else { + checkHistoryThrows(gHist); + $('ifr').setAttribute('onload', null); + SimpleTest.finish(); + } + } + + function checkThrows(fn) { + try { fn(); ok(false, "Should have thrown: " + fn.toSource()); } + catch (e) { ok(!!/denied|insecure/.exec(e), "Threw correctly: " + e); } + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=940783">Mozilla Bug 940783</a> +<p id="display"></p> +<div id="content" style="display: none"> +<iframe id="ifr" onload="load();" src="file_empty.html"></iframe> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug960820.html b/js/xpconnect/tests/mochitest/test_bug960820.html new file mode 100644 index 000000000..43310f589 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug960820.html @@ -0,0 +1,56 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=960820 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 960820</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for exception stacks crossing **/ + + // Synchronous event dispatch creates a new script entry point. At the time + // of this writing, an event listener defined in a Sandbox will cause the + // SafeJSContext to be pushed to the cx stack, which differs from the JSContext + // associated with this DOM window. So we test both kinds of boundaries. + var sb = new SpecialPowers.Cu.Sandbox(SpecialPowers.Services.scriptSecurityManager.getSystemPrincipal()); + sb.win = window; + SpecialPowers.Cu.evalInSandbox("win.document.addEventListener('click', " + + "function clickHandler() { win.wrappedJSObject.clickCallback(); });", sb); + function clickCallback() { + var stack = (new Error()).stack; + ok(true, "Invoked clickCallback. Stack: " + stack); + ok(/clickCallback/.test(stack), "clickCallback should be in the stack"); + ok(!/clickHandler/.test(stack), "clickHandler should not be in the stack"); + ok(/dispatchClick/.test(stack), "dispatchClick should be in the stack"); + + // Check Components.stack, but first filter through the SpecialPowers junk. + var stack = SpecialPowers.wrap(SpecialPowers.Components).stack; + while (/specialpowers/.test(stack)) { + stack = stack.caller; + } + ok(/clickCallback/.test(stack), "clickCallback should be reachable via Components.stack"); + ok(/clickHandler/.test(stack.caller), "clickHandler should be reachable via Components.stack"); + ok(/dispatchClick/.test(stack.caller.caller), "dispatchClick hould be reachable via Components.stack"); + } + function dispatchClick() { + document.dispatchEvent(new MouseEvent('click')); + } + dispatchClick(); + + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=960820">Mozilla Bug 960820</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug965082.html b/js/xpconnect/tests/mochitest/test_bug965082.html new file mode 100644 index 000000000..8f04cd3f8 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug965082.html @@ -0,0 +1,39 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=965082 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 965082</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 965082 **/ + SimpleTest.waitForExplicitFinish(); + + function checkThrows(f, msg) { + try { f(); ok(false, "Should have thrown: " + msg); } + catch (e) { ok(/denied|insecure/.test(e), "Should throw security exception: " + e + " (" + msg + ")"); } + } + + function go() { + var protoSetter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; + checkThrows(function() { protoSetter.call(window[0], new Object()); }, "Setting cross-origin Window prototype"); + checkThrows(function() { protoSetter.call(window[0].location, new Object()); }, "Setting cross-origin Location prototype"); + SimpleTest.finish(); + } + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=965082">Mozilla Bug 965082</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<iframe id="ifr" onload="go();" src="http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug986542.html b/js/xpconnect/tests/mochitest/test_bug986542.html new file mode 100644 index 000000000..a0759c43f --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug986542.html @@ -0,0 +1,45 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=986542 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 986542</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 986542 **/ + SimpleTest.waitForExplicitFinish(); + addLoadEvent(function() { + var ifr = document.getElementById("ifr"); + var doc = ifr.contentDocument; + var scr = doc.createElement("script"); + scr.textContent = "function f() { onF(); }"; + ifr.contentWindow.onF = function() { + ok(true, "Called event handler in detached window"); + SimpleTest.finish(); + } + doc.body.appendChild(scr); + var target = document.getElementById("target"); + target.onclick = ifr.contentWindow.f; + ifr.parentNode.removeChild(ifr); + info("Removed frame from document. Waiting for event handler to be called."); + target.dispatchEvent(new MouseEvent('click')); + }); + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=986542">Mozilla Bug 986542</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<div id="target"></div> +<iframe id="ifr"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_bug993423.html b/js/xpconnect/tests/mochitest/test_bug993423.html new file mode 100644 index 000000000..43c17a49a --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_bug993423.html @@ -0,0 +1,47 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=993423 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 993423</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Bug 993423 **/ + SimpleTest.waitForExplicitFinish(); + + var sCallbackInvocations = 0; + function callback(handlerIsInXBLScope) { + ok(!handlerIsInXBLScope, "Event handler should not be in XBL scope"); + if (++sCallbackInvocations == 2) + SimpleTest.finish(); + } + + function go() { + document.querySelector('use').setAttributeNS('http://www.w3.org/1999/xlink', + 'href', location.href + '#a'); + } + + </script> +</head> +<body onload="go()";> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=993423">Mozilla Bug 993423</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +<svg> + <symbol id="a"> + <foreignObject> + <img src="about:logo" onload="var isInXBL = (function() { return this; })() != window; if (isInXBL) callback = window.wrappedJSObject.callback; callback(isInXBL);"> + </foreignObject> + </symbol> + <use /> +</svg> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_crossOriginObjects.html b/js/xpconnect/tests/mochitest/test_crossOriginObjects.html new file mode 100644 index 000000000..adfd25869 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_crossOriginObjects.html @@ -0,0 +1,336 @@ +<!doctype html> +<meta charset=utf-8> +<meta name="timeout" content="long"> +<title>Cross-origin behavior of Window and Location</title> +<link rel="author" title="Bobby Holley (:bholley)" href="bobbyholley@gmail.com"> +<link rel="help" href="http://www.whatwg.org/specs/web-apps/current-work/#security-window"> +<link rel="help" href="http://www.whatwg.org/specs/web-apps/current-work/#security-location"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<div id=log></div> +<iframe id="B"></iframe> +<iframe id="C"></iframe> +<script> + +/* + * Setup boilerplate. This gives us a same-origin window "B" and a cross-origin + * window "C". + */ + +setup({explicit_done: true}); +path = location.pathname.substring(0, location.pathname.lastIndexOf('/')) + '/file_crossOriginObjects.html'; +var B = document.getElementById('B').contentWindow; +var C = document.getElementById('C').contentWindow; +B.frameElement.uriToLoad = path; +C.frameElement.uriToLoad = 'http://test1.mochi.test:' + location.port + path; + +function reloadSubframes(cb) { + var iframes = document.getElementsByTagName('iframe'); + iframes.forEach = Array.prototype.forEach; + var count = 0; + function frameLoaded() { + this.onload = null; + if (++count == iframes.length) + cb(); + } + iframes.forEach(function(ifr) { ifr.onload = frameLoaded; ifr.setAttribute('src', ifr.uriToLoad); }); +} +function isObject(x) { return Object(x) === x; } + +/* + * Note: we eschew assert_equals in a lot of these tests, since the harness ends + * up throwing when it tries to format a message involving a cross-origin object. + */ + +var testList = []; +function addTest(fun, desc) { testList.push([fun, desc]); } + + +/* + * Basic sanity testing. + */ + +addTest(function() { + assert_equals(location.host, 'mochi.test:8888', 'Need to run the top-level test from mochi.test:8888'); + assert_equals(B.parent, window, "window.parent works same-origin"); + assert_equals(C.parent, window, "window.parent works cross-origin"); + assert_equals(B.location.pathname, path, "location.href works same-origin"); + assert_throws(null, function() { C.location.pathname; }, "location.pathname throws cross-origin"); + assert_equals(B.frames, 'override', "Overrides visible in the same-origin case"); + assert_equals(C.frames, C, "Overrides invisible in the cross-origin case"); +}, "Basic sanity-checking"); + +/* + * Whitelist behavior. + * + * Also tests for [[GetOwnProperty]] and [[HasOwnProperty]] behavior. + */ + +var whitelistedWindowProps = ['location', 'postMessage', 'window', 'frames', 'self', 'top', 'parent', + 'opener', 'closed', 'close', 'blur', 'focus', 'length']; +addTest(function() { + for (var prop in window) { + if (whitelistedWindowProps.indexOf(prop) != -1) { + C[prop]; // Shouldn't throw. + Object.getOwnPropertyDescriptor(C, prop); // Shouldn't throw. + assert_true(Object.prototype.hasOwnProperty.call(C, prop), "hasOwnProperty for " + prop); + } else { + assert_throws(null, function() { C[prop]; }, "Should throw when accessing " + prop + " on Window"); + assert_throws(null, function() { Object.getOwnPropertyDescriptor(C, prop); }, + "Should throw when accessing property descriptor for " + prop + " on Window"); + assert_throws(null, function() { Object.prototype.hasOwnProperty.call(C, prop); }, + "Should throw when invoking hasOwnProperty for " + prop + " on Window"); + } + if (prop != 'location') + assert_throws(null, function() { C[prop] = undefined; }, "Should throw when writing to " + prop + " on Window"); + } + for (var prop in location) { + if (prop == 'replace') { + C.location[prop]; // Shouldn't throw. + Object.getOwnPropertyDescriptor(C.location, prop); // Shouldn't throw. + assert_true(Object.prototype.hasOwnProperty.call(C.location, prop), "hasOwnProperty for " + prop); + } + else { + assert_throws(null, function() { C[prop]; }, "Should throw when accessing " + prop + " on Location"); + assert_throws(null, function() { Object.getOwnPropertyDescriptor(C, prop); }, + "Should throw when accessing property descriptor for " + prop + " on Location"); + assert_throws(null, function() { Object.prototype.hasOwnProperty.call(C, prop); }, + "Should throw when invoking hasOwnProperty for " + prop + " on Location"); + } + if (prop != 'href') + assert_throws(null, function() { C[prop] = undefined; }, "Should throw when writing to " + prop + " on Location"); + } +}, "Only whitelisted properties are accessible cross-origin"); + +/* + * ES Internal Methods. + */ + +/* + * [[GetPrototypeOf]] + */ +addTest(function() { + assert_true(Object.getPrototypeOf(C) === null, "cross-origin Window proto is null"); + assert_true(Object.getPrototypeOf(C.location) === null, "cross-origin Location proto is null (__proto__)"); + var protoGetter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').get; + assert_true(protoGetter.call(C) === null, "cross-origin Window proto is null"); + assert_true(protoGetter.call(C.location) === null, "cross-origin Location proto is null (__proto__)"); + assert_throws(null, function() { C.__proto__; }, "__proto__ property not available cross-origin"); + assert_throws(null, function() { C.location.__proto__; }, "__proto__ property not available cross-origin"); + +}, "[[GetPrototypeOf]] should return null"); + +/* + * [[SetPrototypeOf]] + */ +addTest(function() { + assert_throws(null, function() { C.__proto__ = new Object(); }, "proto set on cross-origin Window"); + assert_throws(null, function() { C.location.__proto__ = new Object(); }, "proto set on cross-origin Location"); + var setters = [Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set]; + if (Object.setPrototypeOf) + setters.push(function(p) { Object.setPrototypeOf(this, p); }); + setters.forEach(function(protoSetter) { + assert_throws(null, function() { protoSetter.call(C, new Object()); }, "proto setter |call| on cross-origin Window"); + assert_throws(null, function() { protoSetter.call(C.location, new Object()); }, "proto setter |call| on cross-origin Location"); + }); +}, "[[SetPrototypeOf]] should throw"); + +/* + * [[IsExtensible]] + */ +addTest(function() { + assert_true(Object.isExtensible(C), "cross-origin Window should be extensible"); + assert_true(Object.isExtensible(C.location), "cross-origin Location should be extensible"); +}, "[[IsExtensible]] should return true for cross-origin objects"); + +/* + * [[PreventExtensions]] + */ +addTest(function() { + assert_throws(null, function() { Object.preventExtensions(C) }, + "preventExtensions on cross-origin Window should throw"); + assert_throws(null, function() { Object.preventExtensions(C.location) }, + "preventExtensions on cross-origin Location should throw"); +}, "[[PreventExtensions]] should throw for cross-origin objects"); + +/* + * [[GetOwnProperty]] + */ + +addTest(function() { + assert_true(isObject(Object.getOwnPropertyDescriptor(C, 'close')), "C.close is |own|"); + assert_true(isObject(Object.getOwnPropertyDescriptor(C, 'top')), "C.top is |own|"); + assert_true(isObject(Object.getOwnPropertyDescriptor(C.location, 'href')), "C.location.href is |own|"); + assert_true(isObject(Object.getOwnPropertyDescriptor(C.location, 'replace')), "C.location.replace is |own|"); +}, "[[GetOwnProperty]] - Properties on cross-origin objects should be reported |own|"); + +function checkPropertyDescriptor(desc, propName, expectWritable) { + assert_true(isObject(desc), "property descriptor for " + propName + " should exist"); + assert_equals(desc.enumerable, false, "property descriptor for " + propName + " should be non-enumerable"); + assert_equals(desc.configurable, true, "property descriptor for " + propName + " should be configurable"); + if ('value' in desc) + assert_equals(desc.writable, expectWritable, "property descriptor for " + propName + " should have writable: " + expectWritable); + else + assert_equals(typeof desc.set != 'undefined', expectWritable, + "property descriptor for " + propName + " should " + (expectWritable ? "" : "not ") + "have setter"); +} + +addTest(function() { + whitelistedWindowProps.forEach(function(prop) { + var desc = Object.getOwnPropertyDescriptor(C, prop); + checkPropertyDescriptor(desc, prop, prop == 'location'); + }); + checkPropertyDescriptor(Object.getOwnPropertyDescriptor(C.location, 'replace'), 'replace', false); + checkPropertyDescriptor(Object.getOwnPropertyDescriptor(C.location, 'href'), 'href', true); + assert_equals(typeof Object.getOwnPropertyDescriptor(C.location, 'href').get, 'undefined', "Cross-origin location should have no href getter"); +}, "[[GetOwnProperty]] - Property descriptors for cross-origin properties should be set up correctly"); + +/* + * [[Delete]] + */ +addTest(function() { + assert_throws(null, function() { delete C.location; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.parent; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.length; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.document; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.foopy; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.location.href; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.location.replace; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.location.port; }, "Can't delete cross-origin property"); + assert_throws(null, function() { delete C.location.foopy; }, "Can't delete cross-origin property"); +}, "[[Delete]] Should throw on cross-origin objects"); + +/* + * [[DefineOwnProperty]] + */ +function checkDefine(obj, prop) { + var valueDesc = { configurable: true, enumerable: false, writable: false, value: 2 }; + var accessorDesc = { configurable: true, enumerable: false, get: function() {} }; + assert_throws(null, function() { Object.defineProperty(obj, prop, valueDesc); }, "Can't define cross-origin value property " + prop); + assert_throws(null, function() { Object.defineProperty(obj, prop, accessorDesc); }, "Can't define cross-origin accessor property " + prop); +} +addTest(function() { + checkDefine(C, 'length'); + checkDefine(C, 'parent'); + checkDefine(C, 'location'); + checkDefine(C, 'document'); + checkDefine(C, 'foopy'); + checkDefine(C.location, 'href'); + checkDefine(C.location, 'replace'); + checkDefine(C.location, 'port'); + checkDefine(C.location, 'foopy'); +}, "[[DefineOwnProperty]] Should throw for cross-origin objects"); + +/* + * [[Enumerate]] + */ + +addTest(function() { + for (var prop in C) + assert_unreached("Shouldn't have been able to enumerate " + prop + " on cross-origin Window"); + for (var prop in C.location) + assert_unreached("Shouldn't have been able to enumerate " + prop + " on cross-origin Location"); +}, "[[Enumerate]] should return an empty iterator"); + +/* + * [[OwnPropertyKeys]] + */ + +addTest(function() { + assert_array_equals(whitelistedWindowProps.sort(), Object.getOwnPropertyNames(C).sort(), + "Object.getOwnPropertyNames() gives the right answer for cross-origin Window"); + assert_array_equals(Object.getOwnPropertyNames(C.location).sort(), ['href', 'replace'], + "Object.getOwnPropertyNames() gives the right answer for cross-origin Location"); +}, "[[OwnPropertyKeys]] should return all properties from cross-origin objects"); + +addTest(function() { + assert_true(B.eval('parent.C') === C, "A and B observe the same identity for C's Window"); + assert_true(B.eval('parent.C.location') === C.location, "A and B observe the same identity for C's Location"); +}, "A and B jointly observe the same identity for cross-origin Window and Location"); + +function checkFunction(f, proto) { + var name = f.name || '<missing name>'; + assert_equals(typeof f, 'function', name + " is a function"); + assert_equals(Object.getPrototypeOf(f), proto, f.name + " has the right prototype"); +} + +addTest(function() { + checkFunction(C.close, Function.prototype); + checkFunction(C.location.replace, Function.prototype); +}, "Cross-origin functions get local Function.prototype"); + +addTest(function() { + assert_true(isObject(Object.getOwnPropertyDescriptor(C, 'parent')), + "Need to be able to use Object.getOwnPropertyDescriptor do this test"); + checkFunction(Object.getOwnPropertyDescriptor(C, 'parent').get, Function.prototype); + checkFunction(Object.getOwnPropertyDescriptor(C.location, 'href').set, Function.prototype); +}, "Cross-origin Window accessors get local Function.prototype"); + +addTest(function() { + checkFunction(close, Function.prototype); + assert_true(close != B.close, 'same-origin Window functions get their own object'); + assert_true(close != C.close, 'cross-origin Window functions get their own object'); + var close_B = B.eval('parent.C.close'); + assert_true(close != close_B, 'close_B is unique when viewed by the parent'); + assert_true(close_B != C.close, 'different Window functions per-incumbent script settings object'); + checkFunction(close_B, B.Function.prototype); + + checkFunction(location.replace, Function.prototype); + assert_true(location.replace != C.location.replace, "cross-origin Location functions get their own object"); + var replace_B = B.eval('parent.C.location.replace'); + assert_true(replace_B != C.location.replace, 'different Location functions per-incumbent script settings object'); + checkFunction(replace_B, B.Function.prototype); +}, "Same-origin observers get different functions for cross-origin objects"); + +addTest(function() { + assert_true(isObject(Object.getOwnPropertyDescriptor(C, 'parent')), + "Need to be able to use Object.getOwnPropertyDescriptor do this test"); + var get_self_parent = Object.getOwnPropertyDescriptor(window, 'parent').get; + var get_parent_A = Object.getOwnPropertyDescriptor(C, 'parent').get; + var get_parent_B = B.eval('Object.getOwnPropertyDescriptor(parent.C, "parent").get'); + assert_true(get_self_parent != get_parent_A, 'different Window accessors per-incumbent script settings object'); + assert_true(get_parent_A != get_parent_B, 'different Window accessors per-incumbent script settings object'); + checkFunction(get_self_parent, Function.prototype); + checkFunction(get_parent_A, Function.prototype); + checkFunction(get_parent_B, B.Function.prototype); +}, "Same-origin obsevers get different accessors for cross-origin Window"); + +addTest(function() { + var set_self_href = Object.getOwnPropertyDescriptor(window.location, 'href').set; + var set_href_A = Object.getOwnPropertyDescriptor(C.location, 'href').set; + var set_href_B = B.eval('Object.getOwnPropertyDescriptor(parent.C.location, "href").set'); + assert_true(set_self_href != set_href_A, 'different Location accessors per-incumbent script settings object'); + assert_true(set_href_A != set_href_B, 'different Location accessors per-incumbent script settings object'); + checkFunction(set_self_href, Function.prototype); + checkFunction(set_href_A, Function.prototype); + checkFunction(set_href_B, B.Function.prototype); +}, "Same-origin observers get different accessors for cross-origin Location"); + +function doDocumentDomainTest(cb) { + window.addEventListener('message', function onmessage(evt) { + window.removeEventListener('message', onmessage); + test(function() { + var results = evt.data; + assert_true(results.length > 0, 'Need results'); + results.forEach(function(r) { assert_true(r.pass, r.message); }); + }, "Cross-origin object identity preserved across document.domain"); + win.close(); + cb(); + }); + var win = window.open('file_crossOriginObjects_documentDomain.html'); +} + +// We do a fresh load of the subframes for each test to minimize side-effects. +// It would be nice to reload ourselves as well, but we can't do that without +// disrupting the test harness. +function runNextTest() { + var entry = testList.shift(); + test(entry[0], entry[1]); + if (testList.length != 0) + reloadSubframes(runNextTest); + else + doDocumentDomainTest(done); // Asynchronous. +} +reloadSubframes(runNextTest); + +</script> diff --git a/js/xpconnect/tests/mochitest/test_crosscompartment_weakmap.html b/js/xpconnect/tests/mochitest/test_crosscompartment_weakmap.html new file mode 100644 index 000000000..e50b1f1bd --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_crosscompartment_weakmap.html @@ -0,0 +1,44 @@ +<!DOCTYPE HTML> +<html> +<head> + <title>Test Cross-Compartment DOM WeakMaps</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<p id="display"></p> +<script type="application/javascript"> + +var my_map = new WeakMap(); + +function setup() { + var item = window.frames[0].document.querySelector("body"); + + my_map.set(item, "success_string"); + + var rule_fail = false; + try { + my_map.set(window.frames[0].document.styleSheets[0].cssRules[0], 1); + } catch (e) { + rule_fail = true; + } + ok(rule_fail, "Using rule as a weak map key across compartments should produce an exception because it can't be wrapper preserved."); +} + +function runTest() { + setup(); + SpecialPowers.forceGC(); + SpecialPowers.forceCC(); + SpecialPowers.forceGC(); + SpecialPowers.forceCC(); + var item = window.frames[0].document.querySelector("body"); + is(my_map.get(item), "success_string", "Preserve reflectors used cross-compartment as weak map keys."); +} + +</script> +<iframe src="file_crosscompartment_weakmap.html" onload="runTest()"></iframe> + + +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_frameWrapping.html b/js/xpconnect/tests/mochitest/test_frameWrapping.html new file mode 100644 index 000000000..7aecf1c3e --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_frameWrapping.html @@ -0,0 +1,37 @@ +<!DOCTYPE HTML> +<html> +<!-- +No bug. +--> +<head> + <title>Test for Bug </title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=">Mozilla Bug </a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +<script type="application/javascript"> + +/** No bug for this test **/ + +function go() { + var win = frames[0]; + (function() { + var utils = SpecialPowers.getDOMWindowUtils(window); + is(utils.getClassName(win), "Proxy", "correctly wrap frame elements"); + })() + SimpleTest.finish(); +} + +SimpleTest.waitForExplicitFinish(); + +</script> +</pre> +<iframe id="ifr" src="inner.html" onload="go()"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_getWebIDLCaller.html b/js/xpconnect/tests/mochitest/test_getWebIDLCaller.html new file mode 100644 index 000000000..0627eb659 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_getWebIDLCaller.html @@ -0,0 +1,49 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=968335 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 968335</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <script type="application/javascript"> + + /** Test for Cu.getCallerPrincipal (within JS-implemented WebIDL). **/ + + SimpleTest.waitForExplicitFinish(); + SpecialPowers.pushPrefEnv({set: [['dom.expose_test_interfaces', true]]}, go); + + + function go() { + var t = new TestInterfaceJS(); + is(t.getCallerPrincipal(), location.origin, + "Cu.getCallerPrincipal works right within JS-implemented WebIDL"); + + try { + SpecialPowers.Cu.getWebIDLCallerPrincipal(); + ok(false, "Should have thrown"); + } catch (e) { + ok(/NOT_AVAILABLE/.test(SpecialPowers.wrap(e)), + "API should throw when invoked outside of JS-implemented WebIDL"); + } + + SimpleTest.finish(); + } + + + + + </script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=968335">Mozilla Bug 968335</a> +<p id="display"></p> +<div id="content" style="display: none"> + +</div> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_nac.xhtml b/js/xpconnect/tests/mochitest/test_nac.xhtml new file mode 100644 index 000000000..0f18fe489 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_nac.xhtml @@ -0,0 +1,64 @@ +<html xmlns="http://www.w3.org/1999/xhtml"> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=914618 +--> +<head> + <title>Test for Bug 914618</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> + <bindings xmlns="http://www.mozilla.org/xbl" + xmlns:html="http://www.w3.org/1999/xhtml"> + <binding id="testBinding" chromeOnlyContent="true"> + <!-- The root of the anonymous subtree is special, and is not allowed to + be adopted, among other things. Work with a child of the root. --> + <content><html:div><html:span id="nac">hidden text</html:span></html:div></content> + <implementation> + <constructor> + var win = XPCNativeWrapper.unwrap(window); + var nac = document.getAnonymousNodes(this)[0].firstChild; + win.is(nac.textContent, "hidden text", "XBL can see NAC"); + win.playWithNAC(nac); + </constructor> + </implementation> + </binding> + </bindings> + <script type="application/javascript"> + <![CDATA[ + + /** Test for Bug 914618 **/ + SimpleTest.waitForExplicitFinish(); + + function checkThrows(fn) { + try { + fn(); + ok(false, "Should have thrown"); + } catch (e) { + ok(/denied|insecure|/.test(e), "Should have thrown security error"); + } + } + + function playWithNAC(nac) { + checkThrows(function() { nac.toString(); }); + checkThrows(function() { nac.textContent; }); + var iwin = document.getElementById('ifr').contentWindow; + iwin.nac = window.nac = nac; + checkThrows(new iwin.Function('nac.toString();')); + checkThrows(new iwin.Function('nac.textContent;')); + + SimpleTest.finish(); + } + + ]]> +</script> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=914618">Mozilla Bug 914618</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<div id="bindingSink" style="-moz-binding: url(#testBinding);"></div> +<iframe id="ifr"></iframe> +<pre id="test"> +</pre> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_sameOriginPolicy.html b/js/xpconnect/tests/mochitest/test_sameOriginPolicy.html new file mode 100644 index 000000000..1969e517c --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_sameOriginPolicy.html @@ -0,0 +1,109 @@ +<!DOCTYPE HTML> +<html> +<!-- +https://bugzilla.mozilla.org/show_bug.cgi?id=801576 +--> +<head> + <meta charset="utf-8"> + <title>Test for Bug 801576</title> + <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> +</head> +<body> +<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=801576">Mozilla Bug 801576</a> +<p id="display"></p> +<div id="content" style="display: none"> +</div> +<pre id="test"> +<script type="application/javascript"> + +/** Test for the same-origin policy. **/ +SimpleTest.waitForExplicitFinish(); + +function check(obj, prop, allowed, write) { + var accessed = false; + try { + if (write) { + try { + obj[prop] = 2; + accessed = true; + } catch (e) {} + Object.defineProperty(obj, 'prop', {getter: function() {}, setter: null}); + } + else + obj[prop]; + accessed = true; + } catch (e) {} + is(accessed, allowed, prop + " is correctly (in)accessible for " + (write ? 'write' : 'read')); +} + +var crossOriginReadableWindowProps = ['blur', 'close', 'closed', 'focus', + 'frames', 'location', 'length', + 'opener', 'parent', 'postMessage', + 'self', 'top', 'window', + /* indexed and named accessors */ + '0', 'subframe']; + +function isCrossOriginReadable(obj, prop) { + if (obj == "Window") + return crossOriginReadableWindowProps.indexOf(prop) != -1; + if (obj == "Location") + return prop == 'replace'; + return false; +} + +function isCrossOriginWritable(obj, prop) { + if (obj == "Window") + return prop == 'location'; + if (obj == "Location") + return prop == 'href'; +} + +// NB: we don't want to succeed with writes, so we only check them when it should be denied. +function testAll(sameOrigin) { + var win = document.getElementById('ifr').contentWindow; + + // Build a list of properties to check from the properties available on our + // window. + var props = []; + for (var prop in window) { props.push(prop); } + + // On android, this appears to be on the window but not on the iframe. It's + // not really relevant to this test, so just skip it. + if (props.indexOf('crypto') != -1) + props.splice(props.indexOf('crypto'), 1); + + // Add the named grand-child, since that won't appear on our window. + props.push('subframe'); + + for (var prop of props) { + check(win, prop, sameOrigin || isCrossOriginReadable('Window', prop), /* write = */ false); + if (!sameOrigin && !isCrossOriginWritable('Window', prop)) + check(win, prop, false, /* write = */ true); + } + for (var prop in window.location) { + check(win.location, prop, sameOrigin || isCrossOriginReadable('Location', prop)); + if (!sameOrigin && !isCrossOriginWritable('Location', prop)) + check(win.location, prop, false, /* write = */ true); + } +} + +var loadCount = 0; +function go() { + ++loadCount; + if (loadCount == 1) { + testAll(true); + document.getElementById('ifr').contentWindow.location = 'http://example.org/tests/js/xpconnect/tests/mochitest/file_empty.html'; + } + else { + is(loadCount, 2); + testAll(false); + SimpleTest.finish(); + } +} + +</script> +</pre> +<iframe id="ifr" onload="go();" src="file_empty.html"></iframe> +</body> +</html> diff --git a/js/xpconnect/tests/mochitest/test_sandbox_fetch.html b/js/xpconnect/tests/mochitest/test_sandbox_fetch.html new file mode 100644 index 000000000..b206efdb8 --- /dev/null +++ b/js/xpconnect/tests/mochitest/test_sandbox_fetch.html @@ -0,0 +1,54 @@ +<!doctype html> +<html> +<head> + <title>Fetch in JS Sandbox</title> + <script src="/tests/SimpleTest/SimpleTest.js"></script> + <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"></link> + <script src="test_fetch_basic.js"></script> +</head> +<body> +<script type="application/javascript"> + +SimpleTest.waitForExplicitFinish(); + +function testHttpFetch(url) { + info('fetch: ' + url); + return fetch(new Request(url, { method: 'GET' })) + .then(response => { + is(response.status, 200, 'Response is 200'); + is(response.url, url, 'Response URL matches'); + }); +} + +function runSandboxTest(testFunc, argString) { + is(typeof testFunc, 'function'); + var resolvePromise; + var testPromise = new Promise(r => resolvePromise = r); + var finishFuncName = 'finish_' + testFunc.name; + SpecialPowers.Cu.exportFunction(_ => resolvePromise(), sb, + { defineAs: finishFuncName }); + SpecialPowers.Cu.evalInSandbox('(' + testFunc.toSource() + ')' + + '(' + argString + ')' + + '.then(' + finishFuncName + ');', sb); + return testPromise; +} + +var origin = 'https://example.com'; +var properties = ['fetch', 'Blob', 'URL']; +var sb = new SpecialPowers.Cu.Sandbox(origin, + { wantGlobalProperties: properties }); + +sb.ok = SpecialPowers.Cu.exportFunction(ok, sb); +sb.is = SpecialPowers.Cu.exportFunction(is, sb); +sb.info = SpecialPowers.Cu.exportFunction(info, sb); + +Promise.resolve() + .then(_ => runSandboxTest(testHttpFetch, '"' + origin + window.location.pathname + '"')) + .then(_ => runSandboxTest(testAboutURL)) + .then(_ => runSandboxTest(testDataURL)) + .then(_ => runSandboxTest(testSameOriginBlobURL)) + .then(_ => SimpleTest.finish()); + +</script> +</body> +</html> diff --git a/js/xpconnect/tests/moz.build b/js/xpconnect/tests/moz.build new file mode 100644 index 000000000..f767c210d --- /dev/null +++ b/js/xpconnect/tests/moz.build @@ -0,0 +1,31 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +TEST_DIRS += [ + 'mochitest', + 'chrome', + 'browser', + 'components/native', +] + +if CONFIG['COMPILE_ENVIRONMENT']: + TEST_DIRS += [ + 'idl', + ] + +XPCSHELL_TESTS_MANIFESTS += [ + 'unit/xpcshell.ini', +] + +TEST_HARNESS_FILES.xpcshell.js.xpconnect.tests.components.js += [ + 'components/js/xpctest.manifest', + 'components/js/xpctest_attributes.js', + 'components/js/xpctest_bug809674.js', + 'components/js/xpctest_interfaces.js', + 'components/js/xpctest_params.js', + 'components/js/xpctest_returncode_child.js', + 'components/js/xpctest_utils.js', +] diff --git a/js/xpconnect/tests/unit/CatRegistrationComponents.manifest b/js/xpconnect/tests/unit/CatRegistrationComponents.manifest new file mode 100644 index 000000000..11646b028 --- /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 000000000..ba6583bba --- /dev/null +++ b/js/xpconnect/tests/unit/bogus_element_type.jsm @@ -0,0 +1 @@ +this.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 000000000..4ec23b215 --- /dev/null +++ b/js/xpconnect/tests/unit/bogus_exports_type.jsm @@ -0,0 +1 @@ +this.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 000000000..72ff49a2d --- /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 000000000..7c50f7c92 --- /dev/null +++ b/js/xpconnect/tests/unit/component-blob.js @@ -0,0 +1,79 @@ +/* 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/. */ + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.importGlobalProperties(['Blob', 'File']); + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +function do_check_true(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 + do_check_true(f1 instanceof Ci.nsIDOMBlob, "Should be a DOM Blob"); + + do_check_true(!(f1 instanceof File), "Should not be a DOM File"); + + do_check_true(f1.type == "text/xml", "Wrong type"); + + do_check_true(f1.size == testContent.length, "Wrong content size"); + + var f2 = new Blob(); + do_check_true(f2.size == 0, "Wrong size"); + do_check_true(f2.type == "", "Wrong type"); + + var threw = false; + try { + // Needs a valid ctor argument + var f2 = new Blob(Date(132131532)); + } catch (e) { + threw = true; + } + do_check_true(threw, "Passing a random object should fail"); + + return true; + }, + + // nsIClassInfo + information for XPCOM registration code in XPCOMUtils.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, + + getInterfaces: function getInterfaces(aCount) { + var interfaces = [Components.interfaces.nsIClassInfo]; + aCount.value = interfaces.length; + return interfaces; + }, + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIClassInfo]) +}; + +var gComponentsArray = [BlobComponent]; +this.NSGetFactory = XPCOMUtils.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 000000000..ac264c06d --- /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 000000000..a05ae94e2 --- /dev/null +++ b/js/xpconnect/tests/unit/component-file.js @@ -0,0 +1,104 @@ +/* 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/. */ + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.importGlobalProperties(['File']); + + +const Ci = Components.interfaces; + +function do_check_true(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() { + // throw if anything goes wrong + + // find the current directory path + var file = Components.classes["@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 = File.createFromFileName(file.path); + // and with nsIFiles + var f2 = File.createFromNsIFile(file); + + // do some tests + do_check_true(f1 instanceof File, "Should be a DOM File"); + do_check_true(f2 instanceof File, "Should be a DOM File"); + + do_check_true(f1.name == "xpcshell.ini", "Should be the right file"); + do_check_true(f2.name == "xpcshell.ini", "Should be the right file"); + + do_check_true(f1.type == "", "Should be the right type"); + do_check_true(f2.type == "", "Should be the right type"); + + var threw = false; + try { + // Needs a ctor argument + var f7 = new File(); + } catch (e) { + threw = true; + } + do_check_true(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; + } + do_check_true(threw, "Passing a random object should fail"); + + var threw = false + try { + // Directories fail + var dir = Components.classes["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("CurWorkD", Ci.nsIFile); + var f7 = File.createFromNsIFile(dir) + } catch (e) { + threw = true; + } + do_check_true(threw, "Can't create a File object for a directory"); + + return true; + }, + + // nsIClassInfo + information for XPCOM registration code in XPCOMUtils.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, + + getInterfaces: function getInterfaces(aCount) { + var interfaces = [Components.interfaces.nsIClassInfo]; + aCount.value = interfaces.length; + return interfaces; + }, + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIClassInfo]) +}; + +var gComponentsArray = [FileComponent]; +this.NSGetFactory = XPCOMUtils.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 000000000..f865f333d --- /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 000000000..8d7e3d0cf --- /dev/null +++ b/js/xpconnect/tests/unit/component_import.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/. */ + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + +function FooComponent() { + this.wrappedJSObject = this; +} +FooComponent.prototype = +{ + // nsIClassInfo + information for XPCOM registration code in XPCOMUtils.jsm + classDescription: "Foo Component", + classID: Components.ID("{6b933fe6-6eba-4622-ac86-e4f654f1b474}"), + contractID: "@mozilla.org/tests/module-importer;1", + + // nsIClassInfo + flags: 0, + + getInterfaces: function getInterfaces(aCount) { + var interfaces = [Components.interfaces.nsIClassInfo]; + aCount.value = interfaces.length; + + // Guerilla test for line numbers hiding in this method + var threw = true; + try { + thereIsNoSuchIdentifier; + threw = false; + } catch (ex) { + do_check_true(ex.lineNumber == 27); + } + do_check_true(threw); + + return interfaces; + }, + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: function QueryInterface(aIID) { + if (aIID.equals(Components.interfaces.nsIClassInfo) || + aIID.equals(Components.interfaces.nsISupports)) + return this; + + throw Components.results.NS_ERROR_NO_INTERFACE; + } +}; + +function BarComponent() { +} +BarComponent.prototype = +{ + // nsIClassInfo + information for XPCOM registration code in XPCOMUtils.jsm + classDescription: "Module importer test 2", + classID: Components.ID("{708a896a-b48d-4bff-906e-fc2fd134b296}"), + contractID: "@mozilla.org/tests/module-importer;2", + + // nsIClassInfo + flags: 0, + + getInterfaces: function getInterfaces(aCount) { + var interfaces = [Components.interfaces.nsIClassInfo]; + aCount.value = interfaces.length; + return interfaces; + }, + + getScriptableHelper: function getScriptableHelper() { + return null; + }, + + // nsISupports + QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIClassInfo]) +}; + +function do_check_true(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 = XPCOMUtils.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 000000000..952c2dd4d --- /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/head_ongc.js b/js/xpconnect/tests/unit/head_ongc.js new file mode 100644 index 000000000..85989f1d9 --- /dev/null +++ b/js/xpconnect/tests/unit/head_ongc.js @@ -0,0 +1,41 @@ +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.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 = do_print; + 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.mainThread.dispatch({ run: f }, + Ci.nsIThread.DISPATCH_NORMAL); +} + +// 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 000000000..cf006303a --- /dev/null +++ b/js/xpconnect/tests/unit/head_watchdog.js @@ -0,0 +1,112 @@ +/* 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. +// + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +Cu.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.mainThread.dispatch({run: fn}, Ci.nsIThread.DISPATCH_NORMAL); +} + +// +// 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, continuation) { + var oldTimeout = setScriptTimeout(1); + var lastWatchdogWakeup = Cu.getWatchdogTimestamp("WatchdogWakeup"); + 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; + } + do_check_true(expectInterrupt); + setInterruptCallback(undefined); + setScriptTimeout(oldTimeout); + // Schedule our continuation before we kill this script. + executeSoon(continuation); + return false; + }); + executeSoon(function() { + busyWait(3000); + do_check_true(!expectInterrupt); + setInterruptCallback(undefined); + setScriptTimeout(oldTimeout); + continuation(); + }); +} + +var gGenerator; +function continueTest() { + gGenerator.next(); +} + +function run_test() { + + // Run async. + do_test_pending(); + + // Instantiate the generator and kick it off. + gGenerator = testBody(); + gGenerator.next(); +} + diff --git a/js/xpconnect/tests/unit/importer.jsm b/js/xpconnect/tests/unit/importer.jsm new file mode 100644 index 000000000..f5f40d30b --- /dev/null +++ b/js/xpconnect/tests/unit/importer.jsm @@ -0,0 +1 @@ +Components.utils.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 000000000..ebd9a2ddd --- /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/. */ + +this.EXPORTED_SYMBOLS = ["foo", "bar"]; + +function foo() { + return "foo"; +} + +var bar = {} +Components.utils.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 000000000..6ef2b8644 --- /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/. */ + +this.EXPORTED_SYMBOLS = ["baz", "qux"]; + +function baz() { + return "baz"; +} + +var qux = {} +Components.utils.import("resource://test/recursive_importA.jsm", qux); + diff --git a/js/xpconnect/tests/unit/subScriptWithEarlyError.js b/js/xpconnect/tests/unit/subScriptWithEarlyError.js new file mode 100644 index 000000000..45b904d1f --- /dev/null +++ b/js/xpconnect/tests/unit/subScriptWithEarlyError.js @@ -0,0 +1 @@ +var ; diff --git a/js/xpconnect/tests/unit/syntax_error.jsm b/js/xpconnect/tests/unit/syntax_error.jsm new file mode 100644 index 000000000..fca785bcd --- /dev/null +++ b/js/xpconnect/tests/unit/syntax_error.jsm @@ -0,0 +1 @@ +bogusjs)( diff --git a/js/xpconnect/tests/unit/test_URLSearchParams.js b/js/xpconnect/tests/unit/test_URLSearchParams.js new file mode 100644 index 000000000..0031a5ab6 --- /dev/null +++ b/js/xpconnect/tests/unit/test_URLSearchParams.js @@ -0,0 +1,13 @@ +/* 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: ["URLSearchParams"] }); + sb.do_check_eq = do_check_eq; + Cu.evalInSandbox('do_check_eq(new URLSearchParams("one=1&two=2").get("one"), "1");', + sb); + Cu.importGlobalProperties(["URLSearchParams"]); + do_check_eq(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 000000000..66f70694a --- /dev/null +++ b/js/xpconnect/tests/unit/test_allowWaivers.js @@ -0,0 +1,30 @@ +const Cu = Components.utils; +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. + do_check_eq(from.eval('test.prop'), 2); + do_check_eq(from.eval('test.f'), undefined); + + // Make sure that waivability works as expected. + do_check_eq(from.eval('!!test.wrappedJSObject'), allowed); + do_check_eq(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;'); + do_check_true(friend.eval('waived.f()'), 42); + friend.from = from; + friend.eval('from.waived = waived'); + do_check_eq(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 000000000..a85d9d75a --- /dev/null +++ b/js/xpconnect/tests/unit/test_allowedDomains.js @@ -0,0 +1,47 @@ +function run_test() { + var cu = Components.utils; + 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); + do_check_eq(ret, 200); + ret = cu.evalInSandbox("objB.prop1", sbMaster); + do_check_eq(ret, 200); + ret = cu.evalInSandbox("objSubset.prop1", sbMaster); + do_check_eq(ret, 200); + + function evalAndCatch(str, sb) { + try { + ret = cu.evalInSandbox(str, sb); + do_check_true(false, "unexpected pass") + } catch (e) { + do_check_true(e.message && e.message.indexOf("Permission denied to access property") != -1); + } + } + + evalAndCatch("objC.prop1", sbMaster); + evalAndCatch("objMaster.prop1", sbA); + evalAndCatch("objMaster.prop1", sbSubset); + + // Bug 777705: + sbMaster.Components = cu.getComponentsForScope(sbMaster); + Components.utils.evalInSandbox("Components.interfaces", sbMaster); + do_check_true(true); +} diff --git a/js/xpconnect/tests/unit/test_allowedDomainsXHR.js b/js/xpconnect/tests/unit/test_allowedDomainsXHR.js new file mode 100644 index 000000000..71bfe942b --- /dev/null +++ b/js/xpconnect/tests/unit/test_allowedDomainsXHR.js @@ -0,0 +1,136 @@ + +var cu = Components.utils; +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; + + do_check_eq(xhr.status, 200); + do_check_eq(xhr.responseText, httpbody); + + var root_node = xhr.responseXML.getElementsByTagName('root').item(0); + do_check_eq(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); + do_check_true(checkResults(res)); + + var principal = res.responseXML.nodePrincipal; + do_check_true(principal.isCodebasePrincipal); + var requestURL = "http://localhost:4444/simple"; + do_check_eq(principal.URI.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); + do_check_false(true, "XHR created from sandbox should not have chrome caps"); + } catch (e) { + do_check_true(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); + do_check_true(checkResults(res)); + + var principal = res.responseXML.nodePrincipal; + do_check_true(principal.isCodebasePrincipal); + var requestURL = "http://localhost:4444/simple"; + do_check_eq(principal.URI.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.do_check_eq = do_check_eq; + 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_asyncLoadSubScriptError.js b/js/xpconnect/tests/unit/test_asyncLoadSubScriptError.js new file mode 100644 index 000000000..0c27392d8 --- /dev/null +++ b/js/xpconnect/tests/unit/test_asyncLoadSubScriptError.js @@ -0,0 +1,33 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; + +var srvScope = {}; + +function success(result) { + ok(false, "script should not have loaded successfully"); + do_test_finished(); +} + +function error(err) { + ok(err instanceof SyntaxError, "loading script with early error asynchronously resulted in error"); + do_test_finished(); +} + +function run_test() { + do_test_pending(); + + var file = do_get_file("subScriptWithEarlyError.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 p = scriptLoader.loadSubScriptWithOptions(uri.spec, + { target: srvScope, + async: true }); + p.then(success, error); +} diff --git a/js/xpconnect/tests/unit/test_attributes.js b/js/xpconnect/tests/unit/test_attributes.js new file mode 100644 index 000000000..52dbb59e6 --- /dev/null +++ b/js/xpconnect/tests/unit/test_attributes.js @@ -0,0 +1,81 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; + +function run_test() { + + // Load the component manifests. + registerAppManifest(do_get_file('../components/native/chrome.manifest')); + 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. + do_check_eq("XPConnect Read-Writable String", o.stringProperty); + do_check_eq(true, o.booleanProperty); + do_check_eq(32767, o.shortProperty); + do_check_eq(2147483647, o.longProperty); + do_check_true(5.25 < o.floatProperty && 5.75 > o.floatProperty); + do_check_eq("X", o.charProperty); + do_check_eq(-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. + do_check_eq("another string", o.stringProperty); + do_check_eq(false, o.booleanProperty); + do_check_eq(-12345, o.shortProperty); + do_check_eq(1234567890, o.longProperty); + do_check_true(10.15 < o.floatProperty && 10.25 > o.floatProperty); + do_check_eq("Z", o.charProperty); + do_check_eq(1, o.timeProperty); + + // Assign values that differ from the expected type to verify conversion. + + function SetAndTestBooleanProperty(newValue, expectedValue) { + o.booleanProperty = newValue; + do_check_eq(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. + do_check_eq("XPConnect Read-Only String", o.strReadOnly); + do_check_eq(true, o.boolReadOnly); + do_check_eq(32767, o.shortReadOnly); + do_check_eq(2147483647, o.longReadOnly); + do_check_true(5.25 < o.floatReadOnly && 5.75 > o.floatReadOnly); + do_check_eq("X", o.charReadOnly); + do_check_eq(-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 000000000..039f45102 --- /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"; + do_check_true(contractID in Components.classes); + var foo = Components.classes[contractID] + .createInstance(Components.interfaces.nsIClassInfo); + do_check_true(Boolean(foo)); + do_check_true(foo.contractID == contractID); + do_check_true(!!foo.wrappedJSObject); + do_check_true(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 000000000..e031d0813 --- /dev/null +++ b/js/xpconnect/tests/unit/test_blob2.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/. */ + +Components.utils.importGlobalProperties(['Blob', 'File']); + +const Ci = Components.interfaces; + +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 + do_check_true(f1 instanceof Ci.nsIDOMBlob, "Should be a DOM Blob"); + + do_check_true(!(f1 instanceof File), "Should not be a DOM File"); + + do_check_true(f1.type == "text/xml", "Wrong type"); + + do_check_true(f1.size == testContent.length, "Wrong content size"); + + var f2 = new Blob(); + do_check_true(f2.size == 0, "Wrong size"); + do_check_true(f2.type == "", "Wrong type"); + + var threw = false; + try { + // Needs a valid ctor argument + var f2 = new Blob(Date(132131532)); + } catch (e) { + threw = true; + } + do_check_true(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 000000000..dc24a5fbd --- /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 { + Components.utils.import(path); + } catch (ex) { + var exceptionName = ex.name; + print("ex: " + ex + "; name = " + ex.name); + didThrow = true; + } + + do_check_eq(didThrow, shouldThrow); + if (didThrow) + do_check_eq(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: + do_check_eq(typeof(Components.utils.import("resource://test/bogus_exports_type.jsm", + null)), + "object"); + + do_check_eq(typeof(Components.utils.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 000000000..f324e6b3f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1001094.js @@ -0,0 +1,4 @@ +function run_test() { + // Make sure nsJSID implements classinfo. + do_check_eq(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 000000000..90009ed14 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1021312.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/. */ + +const Cu = Components.utils; +function run_test() { + let sb = new Cu.Sandbox(this); + var called = false; + + Cu.exportFunction(function(str) { do_check_true(/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); + do_check_true(called); +} diff --git a/js/xpconnect/tests/unit/test_bug1033253.js b/js/xpconnect/tests/unit/test_bug1033253.js new file mode 100644 index 000000000..9bae251ba --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1033253.js @@ -0,0 +1,6 @@ +const Cu = Components.utils; +function run_test() { + var sb = Cu.Sandbox('http://www.example.com'); + var f = Cu.evalInSandbox('var f = function() {}; f;', sb); + do_check_eq(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 000000000..dc3834ecb --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1033920.js @@ -0,0 +1,7 @@ +const Cu = Components.utils; +function run_test() { + var sb = Cu.Sandbox('http://www.example.com'); + var o = new sb.Object(); + o.__proto__ = null; + do_check_eq(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 000000000..8c3ce7c26 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1033927.js @@ -0,0 +1,8 @@ +const Cu = Components.utils; +function run_test() { + var sb = Cu.Sandbox('http://www.example.com', { wantGlobalProperties: ['XMLHttpRequest']}); + var xhr = Cu.evalInSandbox('new XMLHttpRequest()', sb); + do_check_eq(xhr.toString(), '[object XMLHttpRequest]'); + do_check_eq((new sb.Object()).toString(), '[object Object]'); + do_check_eq(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 000000000..a77df56a9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1034262.js @@ -0,0 +1,9 @@ +const Cu = Components.utils; +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); + do_check_eq(Cu.evalInSandbox('f(dump)', sb2), 'function'); + do_check_eq(Cu.evalInSandbox('f.call(null, dump)', sb2), 'function'); + do_check_eq(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 000000000..30f7a80d9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1081990.js @@ -0,0 +1,10 @@ +const Cu = Components.utils; +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + sb.obj = {}; + sb.arr = []; + sb.fun = function() {}; + do_check_true(sb.eval('Object.getPrototypeOf(obj) == null')); + do_check_true(sb.eval('Object.getPrototypeOf(arr) == null')); + do_check_true(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 000000000..07f45f06b --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1082450.js @@ -0,0 +1,40 @@ +const Cu = Components.utils; +function run_test() { + + var sb = new Cu.Sandbox('http://www.example.com'); + function checkThrows(str, rgxp) { + try { + sb.eval(str); + do_check_true(false); + } catch (e) { + do_check_true(rgxp.test(e)); + } + } + + 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' } + }; + + do_check_eq(sb.eval('exposed.simpleValueProp'), 42); + do_check_eq(sb.eval('exposed.objectValueProp.val'), 42); + checkThrows('exposed.getterProp;', /privileged accessor/i); + checkThrows('exposed.setterProp = 42;', /privileged accessor/i); + checkThrows('exposed.getterSetterProp;', /privileged accessor/i); + checkThrows('exposed.getterSetterProp = 42;', /privileged accessor/i); + do_check_eq(sb.eval('exposed.contentCallableValueProp()'), 42); + checkThrows('exposed.chromeCallableValueProp();', /privileged or cross-origin callable/i); +} diff --git a/js/xpconnect/tests/unit/test_bug1110546.js b/js/xpconnect/tests/unit/test_bug1110546.js new file mode 100644 index 000000000..02687296d --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1110546.js @@ -0,0 +1,5 @@ +const Cu = Components.utils; +function run_test() { + var sb = new Cu.Sandbox(null); + do_check_true(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 000000000..4ae4404a0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1131707.js @@ -0,0 +1,22 @@ +const Cu = Components.utils; + +function testStrict(sb) { + "use strict"; + do_check_eq(sb.eval("typeof wrappedCtor()"), "string"); + do_check_eq(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); + do_check_eq(typeof Date(), "string"); + do_check_eq(typeof new Date(), "object"); + do_check_eq(sb.eval("typeof wrappedCtor()"), "string"); + do_check_eq(sb.eval("typeof new wrappedCtor()"), "object"); + testStrict(sb); +} diff --git a/js/xpconnect/tests/unit/test_bug1150106.js b/js/xpconnect/tests/unit/test_bug1150106.js new file mode 100644 index 000000000..0a93fb588 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1150106.js @@ -0,0 +1,35 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; + +var srvScope = {}; + +function success(result) { + equal(result, 42, "Result of script is correct"); + ok('makeTags' in srvScope && srvScope.makeTags instanceof Function, + "makeTags is a function."); + do_test_finished(); +} + +function error() { + ok(false, "error loading the script asynchronously."); + do_test_finished(); +} + +function run_test() { + do_test_pending(); + + 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 p = scriptLoader.loadSubScriptWithOptions(uri.spec, + { target: srvScope, + async: true }); + p.then(success, error); +} diff --git a/js/xpconnect/tests/unit/test_bug1150771.js b/js/xpconnect/tests/unit/test_bug1150771.js new file mode 100644 index 000000000..8387b2cdf --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1150771.js @@ -0,0 +1,13 @@ +function run_test() { +let Cu = Components.utils; +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); +do_check_eq(typeof Cu.waiveXrays(clonedArg).buf, "object"); + +clonedArg = Cu.cloneInto(arg, sandbox2); +do_check_eq(typeof Cu.waiveXrays(clonedArg).buf, "object"); +do_check_eq(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 000000000..fdf979fe0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1151385.js @@ -0,0 +1,9 @@ +function run_test() +{ + try { + var sandbox = new Components.utils.Sandbox(null, {"sandboxPrototype" : {}}); + do_check_true(false); + } catch (e) { + do_check_true(/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 000000000..0c58c75d7 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1170311.js @@ -0,0 +1,5 @@ +const Cu = Components.utils; +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 000000000..a5cc39a41 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug1244222.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/. */ + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +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; }'); + do_check_eq(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); + do_check_eq(doubleWrapped.echo("foo"), "foo"); + + // GC. + Cu.forceGC(); + + // Make sure it still works. + do_check_eq(doubleWrapped.echo("foo"), "foo"); +} diff --git a/js/xpconnect/tests/unit/test_bug408412.js b/js/xpconnect/tests/unit/test_bug408412.js new file mode 100644 index 000000000..d3d60cd23 --- /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 = Components.classes["@mozilla.org/network/io-service;1"] + .getService(Components.interfaces.nsIIOService); + var uri = ios.newFileURI(file); + + try { + Components.utils.import(uri.spec); + do_throw("Failed to report any error at all"); + } catch (e) { + do_check_neq(/^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 000000000..a9454a26b --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug451678.js @@ -0,0 +1,18 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; + +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); + do_check_true('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 000000000..f158d9497 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug604362.js @@ -0,0 +1,12 @@ +function run_test() { + var Cc = Components.classes; + var Ci = Components.interfaces; + var sp = Cc["@mozilla.org/systemprincipal;1"]. + createInstance(Ci.nsIPrincipal); + var s = Components.utils.Sandbox(sp); + s.a = []; + s.Cu = Components.utils; + s.C = Components; + s.do_check_neq = do_check_neq; + Components.utils.evalInSandbox("do_check_neq(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 000000000..a90a7b137 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug677864.js @@ -0,0 +1,11 @@ +function check_cl(iface, desc) { + do_check_eq(iface.QueryInterface(Components.interfaces.nsIClassInfo).classDescription, desc); +} + +function run_test() { + check_cl(Components.interfaces, 'XPCComponents_Interfaces'); + check_cl(Components.interfacesByID, 'XPCComponents_InterfacesByID'); + check_cl(Components.classes, 'XPCComponents_Classes'); + check_cl(Components.classesByID, 'XPCComponents_ClassesByID'); + check_cl(Components.results, '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 000000000..77a5ce40a --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug711404.js @@ -0,0 +1,10 @@ +const Cc = Components.classes; +const Ci = Components.interfaces; + +function run_test() +{ + var p = Cc["@mozilla.org/hash-property-bag;1"]. + createInstance(Ci.nsIWritablePropertyBag2); + p.setPropertyAsInt64("a", -4000); + do_check_neq(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 000000000..8d8b5643a --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug742444.js @@ -0,0 +1,17 @@ +const Cu = Components.utils; +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); + do_check_true(Cu.evalInSandbox('obj === waived', sb1B)); + do_check_true(Cu.evalInSandbox('obj === waived', sb2)); + do_check_true(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 000000000..4a905ad0f --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug778409.js @@ -0,0 +1,11 @@ +function run_test() { + var Cu = Components.utils; + 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; + do_check_true(true, "Didn't crash"); + do_check_eq(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 000000000..40d6f9748 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug780370.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=780370 */ + +const Cu = Components.utils; + +// 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' } }; + do_check_eq(Cu.evalInSandbox('typeof obj.foo', sb), 'undefined', "COW works as expected"); + try { + Cu.evalInSandbox('obj.hasOwnProperty', sb); + do_check_true(false); + } catch (e) { + do_check_true(/privileged or cross-origin callable/i.test(e)); + } +} diff --git a/js/xpconnect/tests/unit/test_bug809652.js b/js/xpconnect/tests/unit/test_bug809652.js new file mode 100644 index 000000000..66dd6d550 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug809652.js @@ -0,0 +1,63 @@ +/* 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 Cu = Components.utils; +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'); + do_check_true(!!/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 000000000..76bfdf742 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug809674.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/. */ + +const Cc = Components.classes; +const Ci = Components.interfaces; + +function run_test() { + + // Load the component manifest. + Components.manager.autoRegister(do_get_file('../components/js/xpctest.manifest')); + + // Test for each component. + test_property_throws("@mozilla.org/js/xpc/test/js/Bug809674;1"); +} + +function test_property_throws(contractid) { + + // Instantiate the object. + var o = Cc[contractid].createInstance(Ci["nsIXPCTestBug809674"]); + + // Test the initial values. + try { + o.jsvalProperty; + do_check_true(false); + } catch (e) { + do_check_true(true); + do_check_true(/implicit_jscontext/.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 000000000..42f981581 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug813901.js @@ -0,0 +1,25 @@ +/* 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 Cu = Components.utils; + +// 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'); + do_check_true(!!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, /__exposedProps__/); +} diff --git a/js/xpconnect/tests/unit/test_bug845201.js b/js/xpconnect/tests/unit/test_bug845201.js new file mode 100644 index 000000000..8b0d143be --- /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) { } + do_check_true(false, "Shouldn't be able to enumerate Components"); + } catch(e) { + do_check_true(true, "Threw appropriately"); + threw = true; + } + do_check_true(threw, "Shouldn't have thrown uncatchable exception"); +} + +function run_test() { + var sb = Components.utils.Sandbox('http://www.example.com', { wantComponents: true }); + sb.do_check_true = do_check_true; + Components.utils.evalInSandbox(sbTest.toSource(), sb); + Components.utils.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 000000000..650bdf3cd --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug845862.js @@ -0,0 +1,13 @@ +const Cu = Components.utils; + +function run_test() { + // We rely on the crazy "wantXrays:false also causes values return from the + // sandbox to be waived" behavior, because it's the simplest way to get + // waivers out of the sandbox (which has no native objects). :-( + var sb = new Cu.Sandbox('http://www.example.com', {wantXrays: false}); + Cu.evalInSandbox("this.foo = {}; Object.defineProperty(foo, 'bar', {get: function() {return {};}});", sb); + do_check_true(sb.foo != XPCNativeWrapper(sb.foo), "sb.foo is waived"); + var desc = Object.getOwnPropertyDescriptor(sb.foo, 'bar'); + var b = desc.get(); + do_check_true(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 000000000..8622b5bca --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug849730.js @@ -0,0 +1,7 @@ +const Cu = Components.utils; + +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + sb.arr = [3, 4]; + do_check_true(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 000000000..7cab5b12d --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug851895.js @@ -0,0 +1,11 @@ +const Cu = Components.utils; + +function run_test() { + // Make sure Components.utils gets its |this| fixed up. + var isXrayWrapper = Components.utils.isXrayWrapper; + do_check_true(!isXrayWrapper({}), "Didn't throw"); + + // Even for classes without |this| fixup, make sure that we don't crash. + var isSuccessCode = Components.isSuccessCode; + try { isSuccessCode(Components.results.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 000000000..c7e51757d --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug853709.js @@ -0,0 +1,32 @@ +const Cu = Components.utils; + +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); + do_check_neq(result, 'nothrow'); + do_check_true(!!/denied/.exec(result)); + do_check_true(result.indexOf(prop) != -1); // 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; + + do_check_eq(Cu.evalInSandbox('chromeObj.a', contentSB), 2); + try { + Cu.evalInSandbox('chromeArr[1]', contentSB); + do_check_true(false); + } catch (e) { do_check_true(/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 000000000..d60d23a5b --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug854558.js @@ -0,0 +1,11 @@ +const Cu = Components.utils; +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; + do_check_eq(Cu.evalInSandbox('foo.a', contentSB), undefined, "Default deny with no __exposedProps__"); + Cu.evalInSandbox('this.foo.__exposedProps__ = {a: "r"}', chromeSB); + do_check_eq(Cu.evalInSandbox('foo.a', contentSB), 2, "works 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 000000000..b23cd45fb --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug856067.js @@ -0,0 +1,10 @@ +const Cu = Components.utils; + +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com'); + let w = Cu.evalInSandbox('var w = new WeakMap(); w.__proto__ = new Set(); w.foopy = 12; w', sb); + do_check_eq(Object.getPrototypeOf(w), sb.Object.prototype); + do_check_eq(Object.getOwnPropertyNames(w).length, 0); + do_check_eq(w.wrappedJSObject.foopy, 12); + do_check_eq(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 000000000..a807fa44e --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug867486.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/. */ + +const Cu = Components.utils; + +function run_test() { + var sb = new Cu.Sandbox('http://www.example.com', { wantComponents: true } ); + do_check_false(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 000000000..5aac9c7d6 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug868675.js @@ -0,0 +1,25 @@ +const Cu = Components.utils; +function run_test() { + + // Make sure we don't throw for primitive values. + var result = "threw"; + try { result = XPCNativeWrapper.unwrap(2); } catch (e) {} + do_check_eq(result, 2); + result = "threw"; + try { result = XPCNativeWrapper(2); } catch (e) {} + do_check_eq(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); + do_check_true(!Cu.isXrayWrapper(XPCNativeWrapper.unwrap(sb.xhr))); + do_check_true(Cu.isXrayWrapper(sb.jsobj.mynative)); + do_check_true(!Cu.isXrayWrapper(XPCNativeWrapper.unwrap(sb.jsobj).mynative)); + + // Test the new Cu API. + var waived = Cu.waiveXrays(sb.xhr); + do_check_true(!Cu.isXrayWrapper(waived)); + do_check_true(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 000000000..dc2e0db29 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug872772.js @@ -0,0 +1,43 @@ +const Cu = Components.utils; +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"], wantComponents: true }); + + // 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; + do_check_true(Cu.isXrayWrapper(xhr)); + xhr.unwaivedExpando = xhr; + do_check_true(Cu.isXrayWrapper(xhr.unwaivedExpando)); + var waived = xhr.wrappedJSObject; + do_check_true(!Cu.isXrayWrapper(waived)); + xhr.waivedExpando = waived; + do_check_true(!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); + do_check_true(f != fWaiver); + do_check_true(Cu.unwaiveXrays(fWaiver) === f); + Object.defineProperty(xhr, 'waivedAccessors', {get: fWaiver, set: fWaiver}); + var desc = Object.getOwnPropertyDescriptor(xhr, 'waivedAccessors'); + do_check_true(desc.get === fWaiver); + do_check_true(desc.set === fWaiver); + + // Make sure we correctly handle same-compartment security wrappers. + var unwaivedC = contentSB.Components; + do_check_true(Cu.isXrayWrapper(unwaivedC)); + var waivedC = unwaivedC.wrappedJSObject; + do_check_true(waivedC && unwaivedC && (waivedC != unwaivedC)); + xhr.waivedC = waivedC; + do_check_true(xhr.waivedC === waivedC); + do_check_true(Cu.unwaiveXrays(xhr.waivedC) === unwaivedC); +} diff --git a/js/xpconnect/tests/unit/test_bug885800.js b/js/xpconnect/tests/unit/test_bug885800.js new file mode 100644 index 000000000..bb859141d --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug885800.js @@ -0,0 +1,13 @@ +const Cu = Components.utils; + +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; + do_check_eq(Cu.evalInSandbox('objRef.foo', chromeSb), 2); + Cu.nukeSandbox(sb); + do_check_true(Cu.isDeadWrapper(obj)); + // CCWs to nuked wrappers should be considered dead. + do_check_true(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 000000000..aa11d5db2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug930091.js @@ -0,0 +1,29 @@ +const Cu = Components.utils; + +function checkThrows(fn) { + try { + fn(); + ok(false, "Should have thrown"); + } catch (e) { + do_check_true(/denied|insecure/.test(e)); + } +} + +function run_test() { + var xosb = new Cu.Sandbox('http://www.example.org'); + var sb = new Cu.Sandbox('http://www.example.com'); + sb.do_check_true = do_check_true; + 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 000000000..af4a22d3e --- /dev/null +++ b/js/xpconnect/tests/unit/test_bug976151.js @@ -0,0 +1,24 @@ +/* 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 Cu = Components.utils; +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) { + do_check_true(/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 000000000..8de098121 --- /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 = Components.classes["@mozilla.org/supports-" + name + ";1"]; + var ifname = ("nsISupports" + name.charAt(0).toUpperCase() + + name.substring(1)); + var f = cls.createInstance(Components.interfaces[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 000000000..aaf6e849b --- /dev/null +++ b/js/xpconnect/tests/unit/test_callFunctionWithAsyncStack.js @@ -0,0 +1,30 @@ +Components.utils.import("resource://gre/modules/Services.jsm"); + +function run_test() { + if (!Services.prefs.getBoolPref("javascript.options.asyncstack")) { + do_print("Async stacks are disabled."); + return; + } + + function getAsyncStack() { + return Components.stack; + } + + // asyncCause may contain non-ASCII characters. + let testAsyncCause = "Tes" + String.fromCharCode(355) + "String"; + + Components.utils.callFunctionWithAsyncStack(function asyncCallback() { + let stack = Components.stack; + + do_check_eq(stack.name, "asyncCallback"); + do_check_eq(stack.caller, null); + do_check_eq(stack.asyncCause, null); + + do_check_eq(stack.asyncCaller.name, "getAsyncStack"); + do_check_eq(stack.asyncCaller.asyncCause, testAsyncCause); + do_check_eq(stack.asyncCaller.asyncCaller, null); + + do_check_eq(stack.asyncCaller.caller.name, "run_test"); + do_check_eq(stack.asyncCaller.caller.asyncCause, null); + }, getAsyncStack(), testAsyncCause); +} diff --git a/js/xpconnect/tests/unit/test_classesByID_instanceof.js b/js/xpconnect/tests/unit/test_classesByID_instanceof.js new file mode 100644 index 000000000..b0acf8016 --- /dev/null +++ b/js/xpconnect/tests/unit/test_classesByID_instanceof.js @@ -0,0 +1,79 @@ +function testActual(SimpleURIClassByID) +{ + var simpleURI = + Components.classes["@mozilla.org/network/simple-uri;1"].createInstance(); + + do_check_eq(simpleURI instanceof SimpleURIClassByID, true); +} + +function testInherited(SimpleURIClassByID) +{ + var simpleURI = + Components.classes["@mozilla.org/network/simple-uri;1"].createInstance(); + + var inherited = Object.create(simpleURI); + + do_check_eq(inherited instanceof SimpleURIClassByID, true); +} + +function testInheritedCrossGlobal(SimpleURIClassByID) +{ + var simpleURI = + Components.classes["@mozilla.org/network/simple-uri;1"].createInstance(); + + var sb = new Components.utils.Sandbox(this, { wantComponents: true }); + var inheritedCross = sb.Object.create(simpleURI); + + do_check_eq(inheritedCross instanceof SimpleURIClassByID, true); +} + +function testCrossGlobalArbitraryGetPrototype(SimpleURIClassByID) +{ + var simpleURI = + Components.classes["@mozilla.org/network/simple-uri;1"].createInstance(); + + var sb = new Components.utils.Sandbox(this, { wantComponents: true }); + var firstLevel = Object.create(simpleURI); + + var obj = { shouldThrow: false }; + var secondLevel = + new sb.Proxy(Object.create(firstLevel), + { + getPrototypeOf: new sb.Function("obj", `return function(t) { + if (obj.shouldThrow) + throw 42; + return Reflect.getPrototypeOf(t); + };`)(obj) + }); + var thirdLevel = Object.create(secondLevel); + + obj.shouldThrow = true; + + var threw = false; + var err; + try + { + void (thirdLevel instanceof SimpleURIClassByID); + } + catch (e) + { + threw = true; + err = e; + } + + do_check_eq(threw, true); + do_check_eq(err, 42); + + obj.shouldThrow = false; + + do_check_eq(thirdLevel instanceof SimpleURIClassByID, true); +} + +function run_test() { + var SimpleURIClassByID = Components.classesByID["{e0da1d70-2f7b-11d3-8cd0-0060b0fc14a3}"]; + + testActual(SimpleURIClassByID); + testInherited(SimpleURIClassByID); + testInheritedCrossGlobal(SimpleURIClassByID); + testCrossGlobalArbitraryGetPrototype(SimpleURIClassByID); +} diff --git a/js/xpconnect/tests/unit/test_components.js b/js/xpconnect/tests/unit/test_components.js new file mode 100644 index 000000000..623a365c0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_components.js @@ -0,0 +1,54 @@ +const Cu = Components.utils; + +function run_test() { + var sb1 = Cu.Sandbox("http://www.blah.com"); + var sb2 = Cu.Sandbox("http://www.blah.com"); + var sb3 = Cu.Sandbox(this); + var sb4 = Cu.Sandbox("http://www.other.com"); + var rv; + + // Components is normally hidden from content on the XBL scope chain, but we + // expose it to content here to make sure that the security wrappers work + // regardless. + [sb1, sb2, sb4].forEach(function(x) { x.Components = Cu.getComponentsForScope(x); }); + + // non-chrome accessing chrome Components + sb1.C = Components; + checkThrows("C.utils", sb1); + checkThrows("C.classes", sb1); + + // non-chrome accessing own Components + do_check_eq(Cu.evalInSandbox("typeof Components.interfaces", sb1), 'object'); + do_check_eq(Cu.evalInSandbox("typeof Components.utils", sb1), 'undefined'); + do_check_eq(Cu.evalInSandbox("typeof Components.classes", sb1), 'undefined'); + + // Make sure an unprivileged Components is benign. + var C2 = Cu.evalInSandbox("Components", sb2); + var whitelist = ['interfaces', 'interfacesByID', 'results', 'isSuccessCode', 'QueryInterface']; + for (var prop in Components) { + do_print("Checking " + prop); + do_check_eq((prop in C2), whitelist.indexOf(prop) != -1); + } + + // non-chrome same origin + sb1.C2 = C2; + do_check_eq(Cu.evalInSandbox("typeof C2.interfaces", sb1), 'object'); + do_check_eq(Cu.evalInSandbox("typeof C2.utils", sb1), 'undefined'); + do_check_eq(Cu.evalInSandbox("typeof C2.classes", sb1), 'undefined'); + + // chrome accessing chrome + sb3.C = Components; + rv = Cu.evalInSandbox("C.utils", sb3); + do_check_eq(rv, Cu); + + // non-chrome cross origin + sb4.C2 = C2; + checkThrows("C2.interfaces", sb4); + checkThrows("C2.utils", sb4); + checkThrows("C2.classes", sb4); +} + +function checkThrows(expression, sb) { + var result = Cu.evalInSandbox('(function() { try { ' + expression + '; return "allowed"; } catch (e) { return e.toString(); }})();', sb); + do_check_true(!!/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 000000000..90c0f9ed2 --- /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 Cu = Components.utils; + let sb = new Cu.Sandbox('https://www.example.com', + { wantGlobalProperties: + ["crypto", "TextEncoder", "TextDecoder"] + }); + sb.ok = ok; + Cu.evalInSandbox('ok(this.crypto);', sb); + Cu.evalInSandbox('ok(this.crypto.subtle);', sb); + sb.do_check_eq = do_check_eq; + let innerPromise = new Promise(r => (sb.test_done = r)); + Cu.evalInSandbox('crypto.subtle.digest("SHA-256", ' + + ' new TextEncoder("utf-8").encode("abc"))' + + ' .then(h => do_check_eq(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 => do_check_eq(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 000000000..5af9d74b6 --- /dev/null +++ b/js/xpconnect/tests/unit/test_css.js @@ -0,0 +1,10 @@ +function run_test() { + var Cu = Components.utils; + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["CSS"] }); + sb.do_check_eq = do_check_eq; + Cu.evalInSandbox('do_check_eq(CSS.escape("$"), "\\\\$");', + sb); + Cu.importGlobalProperties(["CSS"]); + do_check_eq(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 000000000..67ea4e66d --- /dev/null +++ b/js/xpconnect/tests/unit/test_deepFreezeClone.js @@ -0,0 +1,33 @@ +const Cu = Components.utils; + +function checkThrows(f, rgxp) { try { f(); do_check_false(); } catch (e) { do_check_true(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; do_check_eq(waived.foo, 12); } + function touchBar() { "use strict"; waived.bar.tick = 'tack'; do_check_eq(waived.bar.tick, 'tack'); } + function addProp() { "use strict"; waived.newProp = 100; do_check_eq(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'); + do_check_eq(desc.writable, !frozen); + do_check_eq(desc.configurable, !frozen); + desc = Object.getOwnPropertyDescriptor(waived.bar, 'tick'); + do_check_eq(desc.writable, !frozen); + do_check_eq(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_exportFunction.js b/js/xpconnect/tests/unit/test_exportFunction.js new file mode 100644 index 000000000..830816342 --- /dev/null +++ b/js/xpconnect/tests/unit/test_exportFunction.js @@ -0,0 +1,150 @@ +function run_test() { + var Cu = Components.utils; + 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.do_check_true = do_check_true; + epsb.do_check_eq = do_check_eq; + subsb.do_check_true = do_check_true; + + // 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) { + do_check_eq(a, 42); + do_check_eq(obj, subsb.tobecloned); + do_check_eq(obj.cloned, "cloned"); + do_check_eq(native, subsb.native); + do_check_eq(expectedThis, this); + do_check_eq(mixed.xrayed, subsb.xrayed); + do_check_eq(mixed.xrayed2, subsb.xrayed2); + if (typeof callback == 'function') { + do_check_eq(typeof subsb.callback, 'function'); + do_check_eq(callback, subsb.callback); + callback(); + } + wasCalled = true; + }; + this.checkIfCalled = function() { + do_check_true(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); + do_check_true(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); + do_check_true(false); + } catch (e) { + do_check_true(/denied|insecure/.test(e)); + } + + // Callers can opt-out of the above. + subsb.xoNative = Cu.evalInSandbox('new XMLHttpRequest()', xorigsb); + try { + do_check_eq(Cu.evalInSandbox('echoAllowXO(xoNative)', subsb), subsb.xoNative); + do_check_true(true); + } catch (e) { + do_check_true(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" }); + do_check_true(false); + } catch (e) { + do_check_true(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" }); + do_check_true(false); + } catch (e) { + dump('Exception: ' + e); + do_check_true(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); + + do_check_true(wasCalled, true); +} diff --git a/js/xpconnect/tests/unit/test_file.js b/js/xpconnect/tests/unit/test_file.js new file mode 100644 index 000000000..a06a4208d --- /dev/null +++ b/js/xpconnect/tests/unit/test_file.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() { + do_load_manifest("component-file.manifest"); + const contractID = "@mozilla.org/tests/component-file;1"; + do_check_true(contractID in Components.classes); + var foo = Components.classes[contractID] + .createInstance(Components.interfaces.nsIClassInfo); + do_check_true(Boolean(foo)); + do_check_true(foo.contractID == contractID); + do_check_true(!!foo.wrappedJSObject); + do_check_true(foo.wrappedJSObject.doTest()); +} diff --git a/js/xpconnect/tests/unit/test_file2.js b/js/xpconnect/tests/unit/test_file2.js new file mode 100644 index 000000000..6ebe7b822 --- /dev/null +++ b/js/xpconnect/tests/unit/test_file2.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/. */ + +Components.utils.importGlobalProperties(['File']); + +const Ci = Components.interfaces; + +function run_test() { + // throw if anything goes wrong + + // find the current directory path + var file = Components.classes["@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 = File.createFromFileName(file.path); + // and with nsIFiles + var f2 = File.createFromNsIFile(file); + + // do some tests + do_check_true(f1 instanceof File, "Should be a DOM File"); + do_check_true(f2 instanceof File, "Should be a DOM File"); + + do_check_true(f1.name == "xpcshell.ini", "Should be the right file"); + do_check_true(f2.name == "xpcshell.ini", "Should be the right file"); + + do_check_true(f1.type == "", "Should be the right type"); + do_check_true(f2.type == "", "Should be the right type"); + + var threw = false; + try { + // Needs a ctor argument + var f7 = File(); + } catch (e) { + threw = true; + } + do_check_true(threw, "No ctor arguments should throw"); + + var threw = false; + try { + // Needs a valid ctor argument + var f7 = File(Date(132131532)); + } catch (e) { + threw = true; + } + do_check_true(threw, "Passing a random object should fail"); + + var threw = false + try { + // Directories fail + var dir = Components.classes["@mozilla.org/file/directory_service;1"] + .getService(Ci.nsIProperties) + .get("CurWorkD", Ci.nsIFile); + var f7 = File.createFromNsIFile(dir) + } catch (e) { + threw = true; + } + do_check_true(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 000000000..cd4859301 --- /dev/null +++ b/js/xpconnect/tests/unit/test_fileReader.js @@ -0,0 +1,13 @@ +/* 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: ["FileReader"] }); + sb.do_check_true = do_check_true; + Cu.evalInSandbox('do_check_true((new FileReader()) instanceof FileReader);', + sb); + Cu.importGlobalProperties(["FileReader"]); + do_check_true((new FileReader()) instanceof FileReader); +} diff --git a/js/xpconnect/tests/unit/test_getObjectPrincipal.js b/js/xpconnect/tests/unit/test_getObjectPrincipal.js new file mode 100644 index 000000000..509c9a5d4 --- /dev/null +++ b/js/xpconnect/tests/unit/test_getObjectPrincipal.js @@ -0,0 +1,11 @@ +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +function run_test() { + var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager); + do_check_true(secMan.isSystemPrincipal(Cu.getObjectPrincipal({}))); + var sb = new Cu.Sandbox('http://www.example.com'); + Cu.evalInSandbox('var obj = { foo: 42 };', sb); + do_check_eq(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 000000000..5475c9011 --- /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/. */ + +function run_test() { + var scope = {}; + Components.utils.import("resource://gre/modules/XPCOMUtils.jsm", scope); + do_check_eq(typeof(scope.XPCOMUtils), "object"); + do_check_eq(typeof(scope.XPCOMUtils.generateNSGetFactory), "function"); + + // access module's global object directly without importing any + // symbols + var module = Components.utils.import("resource://gre/modules/XPCOMUtils.jsm", + null); + do_check_eq(typeof(XPCOMUtils), "undefined"); + do_check_eq(typeof(module), "object"); + do_check_eq(typeof(module.XPCOMUtils), "object"); + do_check_eq(typeof(module.XPCOMUtils.generateNSGetFactory), "function"); + do_check_true(scope.XPCOMUtils == module.XPCOMUtils); + + // import symbols to our global object + do_check_eq(typeof(Components.utils.import), "function"); + Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + do_check_eq(typeof(XPCOMUtils), "object"); + do_check_eq(typeof(XPCOMUtils.generateNSGetFactory), "function"); + + // try on a new object + var scope2 = {}; + Components.utils.import("resource://gre/modules/XPCOMUtils.jsm", scope2); + do_check_eq(typeof(scope2.XPCOMUtils), "object"); + do_check_eq(typeof(scope2.XPCOMUtils.generateNSGetFactory), "function"); + + do_check_true(scope2.XPCOMUtils == scope.XPCOMUtils); + + // try on a new object using the resolved URL + var res = Components.classes["@mozilla.org/network/protocol;1?name=resource"] + .getService(Components.interfaces.nsIResProtocolHandler); + var resURI = res.newURI("resource://gre/modules/XPCOMUtils.jsm", null, null); + dump("resURI: " + resURI + "\n"); + var filePath = res.resolveURI(resURI); + var scope3 = {}; + Components.utils.import(filePath, scope3); + do_check_eq(typeof(scope3.XPCOMUtils), "object"); + do_check_eq(typeof(scope3.XPCOMUtils.generateNSGetFactory), "function"); + + do_check_true(scope3.XPCOMUtils == scope.XPCOMUtils); + + // make sure we throw when the second arg is bogus + var didThrow = false; + try { + Components.utils.import("resource://gre/modules/XPCOMUtils.jsm", "wrong"); + } catch (ex) { + print("exception (expected): " + ex); + didThrow = true; + } + do_check_true(didThrow); + + // try to create a component + do_load_manifest("component_import.manifest"); + const contractID = "@mozilla.org/tests/module-importer;"; + do_check_true((contractID + "1") in Components.classes); + var foo = Components.classes[contractID + "1"] + .createInstance(Components.interfaces.nsIClassInfo); + do_check_true(Boolean(foo)); + do_check_true(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? + // Kind of odd that this is not returning an array containing the + // number... Or for that matter not returning an array containing an object? + var interfaces = foo.getInterfaces({}); + do_check_eq(interfaces, Components.interfaces.nsIClassInfo.number); + + // try to create a component by CID + const cid = "{6b933fe6-6eba-4622-ac86-e4f654f1b474}"; + do_check_true(cid in Components.classesByID); + foo = Components.classesByID[cid] + .createInstance(Components.interfaces.nsIClassInfo); + do_check_true(foo.contractID == contractID + "1"); + + // try to create another component which doesn't directly implement QI + do_check_true((contractID + "2") in Components.classes); + var bar = Components.classes[contractID + "2"] + .createInstance(Components.interfaces.nsIClassInfo); + do_check_true(Boolean(bar)); + do_check_true(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 000000000..d297fa01d --- /dev/null +++ b/js/xpconnect/tests/unit/test_import_fail.js @@ -0,0 +1,10 @@ +function run_test() +{ + try { + Components.utils.import("resource://test/importer.jsm"); + do_check_true(false, "import should not succeed."); + } catch (x) { + do_check_neq(x.fileName.indexOf("syntax_error.jsm"), -1); + do_check_eq(x.lineNumber, 1); + } +}
\ No newline at end of file diff --git a/js/xpconnect/tests/unit/test_interposition.js b/js/xpconnect/tests/unit/test_interposition.js new file mode 100644 index 000000000..f755bbd7d --- /dev/null +++ b/js/xpconnect/tests/unit/test_interposition.js @@ -0,0 +1,165 @@ +const Cu = Components.utils; +const Ci = Components.interfaces; +const Cc = Components.classes; + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + +const ADDONID = "bogus-addon@mozilla.org"; + +let gExpectedProp; +function expectAccess(prop, f) +{ + gExpectedProp = prop; + f(); + do_check_eq(gExpectedProp, undefined); +} + +let getter_run = false; +function test_getter() +{ + do_check_eq(getter_run, false); + getter_run = true; + return 200; +} + +let setter_run = false; +function test_setter(v) +{ + do_check_eq(setter_run, false); + do_check_eq(v, 300); + setter_run = true; +} + +let TestInterposition = { + QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, + Ci.nsISupportsWeakReference]), + + getWhitelist: function() { + return ["abcxyz", "utils", "dataprop", "getterprop", "setterprop", + "objprop", "defineprop", "configurableprop"]; + }, + + interposeProperty: function(addonId, target, iid, prop) { + do_check_eq(addonId, ADDONID); + do_check_eq(gExpectedProp, prop); + gExpectedProp = undefined; + + if (prop == "dataprop") { + return { configurable: false, enumerable: true, writable: false, value: 100 }; + } else if (prop == "getterprop") { + return { configurable: false, enumerable: true, get: test_getter }; + } else if (prop == "setterprop") { + return { configurable: false, enumerable: true, get: test_getter, set: test_setter }; + } else if (prop == "utils") { + do_check_eq(iid, Ci.nsIXPCComponents.number); + return null; + } else if (prop == "objprop") { + gExpectedProp = "objprop"; // allow recursive access here + return { configurable: false, enumerable: true, writable: false, value: { objprop: 1 } }; + } else if (prop == "configurableprop") { + return { configurable: true, enumerable: true, writable: false, value: 10 }; + } + + return null; + }, + + interposeCall: function(addonId, originalFunc, originalThis, args) { + do_check_eq(addonId, ADDONID); + args.splice(0, 0, addonId); + return originalFunc.apply(originalThis, args); + } +}; + +function run_test() +{ + Cu.setAddonInterposition(ADDONID, TestInterposition); + + Cu.importGlobalProperties(["XMLHttpRequest"]); + + let sandbox = Cu.Sandbox(this, {addonId: ADDONID}); + sandbox.outerObj = new XMLHttpRequest(); + + expectAccess("abcxyz", () => { + Cu.evalInSandbox("outerObj.abcxyz = 12;", sandbox); + }); + + expectAccess("utils", () => { + Cu.evalInSandbox("Components.utils;", sandbox); + }); + + expectAccess("dataprop", () => { + do_check_eq(Cu.evalInSandbox("outerObj.dataprop;", sandbox), 100); + }); + + expectAccess("dataprop", () => { + try { + Cu.evalInSandbox("'use strict'; outerObj.dataprop = 400;", sandbox); + do_check_true(false); // it should throw + } catch (e) {} + }); + + expectAccess("objprop", () => { + Cu.evalInSandbox("outerObj.objprop.objprop;", sandbox); + gExpectedProp = undefined; + }); + + expectAccess("getterprop", () => { + do_check_eq(Cu.evalInSandbox("outerObj.getterprop;", sandbox), 200); + do_check_eq(getter_run, true); + getter_run = false; + }); + + expectAccess("getterprop", () => { + try { + Cu.evalInSandbox("'use strict'; outerObj.getterprop = 400;", sandbox); + do_check_true(false); // it should throw + } catch (e) {} + do_check_eq(getter_run, false); + }); + + expectAccess("setterprop", () => { + do_check_eq(Cu.evalInSandbox("outerObj.setterprop;", sandbox), 200); + do_check_eq(getter_run, true); + getter_run = false; + do_check_eq(setter_run, false); + }); + + expectAccess("setterprop", () => { + Cu.evalInSandbox("'use strict'; outerObj.setterprop = 300;", sandbox); + do_check_eq(getter_run, false); + do_check_eq(setter_run, true); + setter_run = false; + }); + + // Make sure that calling Object.defineProperty succeeds as long as + // we're not interposing on that property. + expectAccess("defineprop", () => { + Cu.evalInSandbox("'use strict'; Object.defineProperty(outerObj, 'defineprop', {configurable:true, enumerable:true, writable:true, value:10});", sandbox); + }); + + // Related to above: make sure we can delete those properties too. + expectAccess("defineprop", () => { + Cu.evalInSandbox("'use strict'; delete outerObj.defineprop;", sandbox); + }); + + // Make sure we get configurable=false even if the interposition + // sets it to true. + expectAccess("configurableprop", () => { + let desc = Cu.evalInSandbox("Object.getOwnPropertyDescriptor(outerObj, 'configurableprop')", sandbox); + do_check_eq(desc.configurable, false); + }); + + let moduleScope = Cu.Sandbox(this); + moduleScope.ADDONID = ADDONID; + moduleScope.do_check_eq = do_check_eq; + function funToIntercept(addonId) { + do_check_eq(addonId, ADDONID); + counter++; + } + sandbox.moduleFunction = Cu.evalInSandbox(funToIntercept.toSource() + "; funToIntercept", moduleScope); + Cu.evalInSandbox("var counter = 0;", moduleScope); + Cu.evalInSandbox("Components.utils.setAddonCallInterposition(this);", moduleScope); + Cu.evalInSandbox("moduleFunction()", sandbox); + do_check_eq(Cu.evalInSandbox("counter", moduleScope), 1); + Cu.setAddonInterposition(ADDONID, null); +} diff --git a/js/xpconnect/tests/unit/test_isModuleLoaded.js b/js/xpconnect/tests/unit/test_isModuleLoaded.js new file mode 100644 index 000000000..8b1f9eb3d --- /dev/null +++ b/js/xpconnect/tests/unit/test_isModuleLoaded.js @@ -0,0 +1,33 @@ +const Cu = Components.utils; + +function run_test() { + // Existing module. + do_check_true(!Cu.isModuleLoaded("resource://gre/modules/ISO8601DateUtils.jsm"), + "isModuleLoaded returned correct value for non-loaded module"); + Cu.import("resource://gre/modules/ISO8601DateUtils.jsm"); + do_check_true(Cu.isModuleLoaded("resource://gre/modules/ISO8601DateUtils.jsm"), + "isModuleLoaded returned true after loading that module"); + Cu.unload("resource://gre/modules/ISO8601DateUtils.jsm"); + do_check_true(!Cu.isModuleLoaded("resource://gre/modules/ISO8601DateUtils.jsm"), + "isModuleLoaded returned false after unloading that module"); + + // Non-existing module + do_check_true(!Cu.isModuleLoaded("resource://gre/modules/ISO8601DateUtils1.jsm"), + "isModuleLoaded returned correct value for non-loaded module"); + try { + Cu.import("resource://gre/modules/ISO8601DateUtils1.jsm"); + do_check_true(false, + "Should have thrown while trying to load a non existing file"); + } catch (ex) {} + do_check_true(!Cu.isModuleLoaded("resource://gre/modules/ISO8601DateUtils1.jsm"), + "isModuleLoaded returned correct value for non-loaded module"); + + // incorrect url + try { + Cu.isModuleLoaded("resource://modules/ISO8601DateUtils1.jsm"); + do_check_true(false, + "Should have thrown while trying to load a non existing file"); + } catch (ex) { + do_check_true(true, "isModuleLoaded threw an exception while loading incorrect uri"); + } +} diff --git a/js/xpconnect/tests/unit/test_isProxy.js b/js/xpconnect/tests/unit/test_isProxy.js new file mode 100644 index 000000000..7cc526226 --- /dev/null +++ b/js/xpconnect/tests/unit/test_isProxy.js @@ -0,0 +1,29 @@ +function run_test() { + var Cu = Components.utils; + + var handler = { + get: function(target, name){ + return name in target? + target[name] : + 37; + } + }; + + var p = new Proxy({}, handler); + do_check_true(Cu.isProxy(p)); + do_check_false(Cu.isProxy({})); + do_check_false(Cu.isProxy(42)); + + sb = new Cu.Sandbox(this, + { wantExportHelpers: true }); + + do_check_false(Cu.isProxy(sb)); + + sb.do_check_true = do_check_true; + sb.do_check_false = do_check_false; + sb.p = p; + Cu.evalInSandbox('do_check_true(isProxy(p));' + + 'do_check_false(isProxy({}));' + + 'do_check_false(isProxy(42));', + sb); +} 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 000000000..837fdb38b --- /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 = Components.utils.getWeakReference(null); + do_check_true(nullWeak.get() === null); + } catch (e) { + do_check_true(false); + } + + var obj = { num: 5, str: 'foo' }; + var weak = Components.utils.getWeakReference(obj); + + do_check_true(weak.get() === obj); + do_check_true(weak.get().num == 5); + do_check_true(weak.get().str == 'foo'); + + // Force garbage collection + Components.utils.forceGC(); + + // obj still references the object, so it should still be accessible via weak + do_check_true(weak.get() === obj); + do_check_true(weak.get().num == 5); + do_check_true(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 = Components.utils.getWeakReference(obj); + do_check_true(weak2.get() === obj); + + Components.utils.forceGC(); + + // The object should have been garbage collected and so should no longer be + // accessible via weak + do_check_true(weak.get() === null); +} diff --git a/js/xpconnect/tests/unit/test_localeCompare.js b/js/xpconnect/tests/unit/test_localeCompare.js new file mode 100644 index 000000000..08560d1ae --- /dev/null +++ b/js/xpconnect/tests/unit/test_localeCompare.js @@ -0,0 +1,6 @@ +function run_test() { + do_check_true("C".localeCompare("D") < 0); + do_check_true("D".localeCompare("C") > 0); + do_check_true("\u010C".localeCompare("D") < 0); + do_check_true("D".localeCompare("\u010C") > 0); +} 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 000000000..a4dd25498 --- /dev/null +++ b/js/xpconnect/tests/unit/test_nuke_sandbox.js @@ -0,0 +1,29 @@ +/* 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 */ + +function run_test() +{ + var sb = Components.utils.Sandbox("http://www.blah.com"); + sb.prop = "prop" + var refToObjFromSb = Components.utils.evalInSandbox("var a = {prop2:'prop2'}; a", sb); + Components.utils.nukeSandbox(sb); + do_check_true(Components.utils.isDeadWrapper(sb), "sb should be dead"); + try{ + sb.prop; + do_check_true(false); + } catch (e) { + do_check_true(e.toString().indexOf("can't access dead object") > -1); + } + + Components.utils.isDeadWrapper(refToObjFromSb, "ref to object from sb should be dead"); + try{ + refToObjFromSb.prop2; + do_check_true(false); + } catch (e) { + do_check_true(e.toString().indexOf("can't access dead object") > -1); + } + +} 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 000000000..138f699f9 --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-01.js @@ -0,0 +1,64 @@ +// 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; + +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 000000000..a8bf22c67 --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-02.js @@ -0,0 +1,94 @@ +// 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; + +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 000000000..1c7f158a7 --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-03.js @@ -0,0 +1,35 @@ +// Test that the onGarbageCollection hook is not reentrant. + + +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 000000000..a7c71b82a --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-04.js @@ -0,0 +1,67 @@ +// 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. + +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.enabled = dbg.enabled = false; + 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 000000000..a34859ceb --- /dev/null +++ b/js/xpconnect/tests/unit/test_onGarbageCollection-05.js @@ -0,0 +1,37 @@ +// 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) + +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 000000000..dfe4b822a --- /dev/null +++ b/js/xpconnect/tests/unit/test_params.js @@ -0,0 +1,201 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; + +function run_test() { + + // Load the component manifests. + registerAppManifest(do_get_file('../components/native/chrome.manifest')); + 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. + 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); + do_check_true(comparator(rv, val2)); + do_check_true(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); + do_check_true(valComparator(rv, val2)); + do_check_true(isComparator(rvIs.value, val2Is)); + do_check_true(valComparator(val1, b.value)); + do_check_true(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); + do_check_true(arrayComparator(interfaceComparator)(rv, val2)); + do_check_true(standardComparator(rvSize.value, val2Size)); + do_check_true(dotEqualsComparator(rvIID.value, val2IID)); + do_check_true(arrayComparator(interfaceComparator)(val1, b.value)); + do_check_true(standardComparator(val1Size, bSize.value)); + do_check_true(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. + do_check_true(false); + } + catch (e) { + // An exception was thrown as expected. + do_check_true(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); + do_check_eq(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("testDOMString", "Beware: ☠ s"); + 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); + do_check_eq(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)); + + // 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. + do_check_eq(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); +} diff --git a/js/xpconnect/tests/unit/test_promise.js b/js/xpconnect/tests/unit/test_promise.js new file mode 100644 index 000000000..46c34a9bc --- /dev/null +++ b/js/xpconnect/tests/unit/test_promise.js @@ -0,0 +1,8 @@ +function run_test() { + var Cu = Components.utils; + sb = new Cu.Sandbox('http://www.example.com'); + sb.do_check_eq = do_check_eq; + Cu.evalInSandbox('do_check_eq(typeof new Promise(function(resolve){resolve();}), "object");', + sb); + do_check_eq(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 000000000..4145ca49f --- /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 = {}; + Components.utils.import("resource://test/recursive_importA.jsm", scope); + + // A imported correctly + do_check_true(scope.foo() == "foo"); + + // Symbols from B are visible through A + do_check_true(scope.bar.baz() == "baz"); + + // Symbols from A are visible through A, B, A. + do_check_true(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 000000000..48d84d91c --- /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"'); + do_check_eq(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 000000000..818ab5b58 --- /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 = Components.utils.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}); + Components.utils.nukeSandbox(sb); + do_check_true(Components.utils.isDeadWrapper(sb), "sb should be dead"); + do_check_true(Components.utils.isDeadWrapper(p1), "p1 should be dead"); + do_check_true(Components.utils.isDeadWrapper(p2), "p2 should be dead"); + + var exception; + + try{ + resolveFun(1); + do_check_true(false); + } catch (e) { + exception = e; + } + do_check_true(exception.toString().includes("can't access dead object"), + "Resolving dead wrapped promise should throw"); + + exception = undefined; + try{ + rejectFun(1); + do_check_true(false); + } catch (e) { + exception = e; + } + do_check_true(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 000000000..8ba76c976 --- /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 {interfaces: Ci, classes: Cc, utils: Cu, manager: Cm, results: Cr} = Components; + +Cu.import("resource:///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. + registerAppManifest(do_get_file('../components/native/chrome.manifest')); + 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].indexOf("a requested error") != -1, "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_rtcIdentityProvider.js b/js/xpconnect/tests/unit/test_rtcIdentityProvider.js new file mode 100644 index 000000000..d6918d3b6 --- /dev/null +++ b/js/xpconnect/tests/unit/test_rtcIdentityProvider.js @@ -0,0 +1,35 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function run_test() { + let Cu = Components.utils; + 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_atob.js b/js/xpconnect/tests/unit/test_sandbox_atob.js new file mode 100644 index 000000000..0c7586fe2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_atob.js @@ -0,0 +1,10 @@ +function run_test() { + var Cu = Components.utils; + sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["atob", "btoa"] }); + sb.do_check_eq = do_check_eq; + Cu.evalInSandbox('var dummy = "Dummy test.";' + + 'do_check_eq(dummy, atob(btoa(dummy)));' + + 'do_check_eq(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 000000000..c3db2c1b2 --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_metadata.js @@ -0,0 +1,58 @@ +/* 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 = Components.utils.Sandbox("http://www.blah.com", { + metadata: "test metadata", + addonId: "12345" + }); + + do_check_eq(Components.utils.getSandboxMetadata(sandbox), "test metadata"); + do_check_eq(Components.utils.getSandboxAddonId(sandbox), "12345"); + + sandbox = Components.utils.Sandbox("http://www.blah.com", { + metadata: { foopy: { bar: 2 }, baz: "hi" } + }); + + let metadata = Components.utils.getSandboxMetadata(sandbox); + do_check_eq(metadata.baz, "hi"); + do_check_eq(metadata.foopy.bar, 2); + metadata.baz = "foo"; + + metadata = Components.utils.getSandboxMetadata(sandbox); + do_check_eq(metadata.baz, "foo"); + + metadata = { foo: "bar" }; + Components.utils.setSandboxMetadata(sandbox, metadata); + metadata.foo = "baz"; + metadata = Components.utils.getSandboxMetadata(sandbox); + do_check_eq(metadata.foo, "bar"); + + let thrown = false; + let reflector = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] + .createInstance(Components.interfaces.nsIXMLHttpRequest); + + try { + Components.utils.setSandboxMetadata(sandbox, { foo: reflector }); + } catch(e) { + thrown = true; + } + + do_check_eq(thrown, true); + + sandbox = Components.utils.Sandbox(this, { + metadata: { foopy: { bar: 2 }, baz: "hi" } + }); + + let inner = Components.utils.evalInSandbox("Components.utils.Sandbox('http://www.blah.com')", sandbox); + + metadata = Components.utils.getSandboxMetadata(inner); + do_check_eq(metadata.baz, "hi"); + do_check_eq(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 000000000..44e6bbcd4 --- /dev/null +++ b/js/xpconnect/tests/unit/test_sandbox_name.js @@ -0,0 +1,28 @@ +"use strict"; + +const { utils: Cu, interfaces: Ci, classes: Cc } = Components; + +/** + * 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.indexOf(name) != -1, `Name ${name} appears in ${fileName}`); + } +}; + +function run_test() { + test_sandbox_name(); +} diff --git a/js/xpconnect/tests/unit/test_tearoffs.js b/js/xpconnect/tests/unit/test_tearoffs.js new file mode 100644 index 000000000..02f0a6329 --- /dev/null +++ b/js/xpconnect/tests/unit/test_tearoffs.js @@ -0,0 +1,108 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; + +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 + do_check_true('name' in instances[10], 'Have the prop from A/B'); + do_check_true('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 + do_check_true('name' in aTearOffs[1], 'Have the prop from A'); + do_check_true(!('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. + do_check_true(!('name' in cTearOffs[1]), 'Dont have the prop from A'); + do_check_true('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. :-) + do_check_true(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 000000000..0b31750a4 --- /dev/null +++ b/js/xpconnect/tests/unit/test_textDecoder.js @@ -0,0 +1,12 @@ +function run_test() { + var Cu = Components.utils; + sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["TextDecoder", "TextEncoder"] }); + sb.do_check_eq = do_check_eq; + Cu.evalInSandbox('do_check_eq(new TextDecoder().encoding, "utf-8");' + + 'do_check_eq(new TextEncoder().encoding, "utf-8");', + sb); + Cu.importGlobalProperties(["TextDecoder", "TextEncoder"]); + do_check_eq(new TextDecoder().encoding, "utf-8"); + do_check_eq(new TextEncoder().encoding, "utf-8"); +} diff --git a/js/xpconnect/tests/unit/test_unload.js b/js/xpconnect/tests/unit/test_unload.js new file mode 100644 index 000000000..e3ca8ce88 --- /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 global1 = Components.utils.import("resource://gre/modules/NetUtil.jsm", scope1); + + var scope2 = {}; + var global2 = Components.utils.import("resource://gre/modules/NetUtil.jsm", scope2); + + do_check_true(global1 === global2); + do_check_true(scope1.NetUtil === scope2.NetUtil); + + Components.utils.unload("resource://gre/modules/NetUtil.jsm"); + + var scope3 = {}; + var global3 = Components.utils.import("resource://gre/modules/NetUtil.jsm", scope3); + + do_check_false(global1 === global3); + do_check_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 000000000..da2502800 --- /dev/null +++ b/js/xpconnect/tests/unit/test_url.js @@ -0,0 +1,10 @@ +function run_test() { + var Cu = Components.utils; + var sb = new Cu.Sandbox('http://www.example.com', + { wantGlobalProperties: ["URL"] }); + sb.do_check_eq = do_check_eq; + Cu.evalInSandbox('do_check_eq(new URL("http://www.example.com").host, "www.example.com");', + sb); + Cu.importGlobalProperties(["URL"]); + do_check_eq(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 000000000..5ccebcf9c --- /dev/null +++ b/js/xpconnect/tests/unit/test_want_components.js @@ -0,0 +1,8 @@ +function run_test() { + var cu = Components.utils; + var sb = cu.Sandbox(this, + {wantComponents: false}); + + var rv = cu.evalInSandbox("this.Components", sb); + do_check_eq(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 000000000..d5dac7b6a --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_default.js @@ -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/. */ + +function testBody() { + // Check that we properly implement whatever behavior is specified by the + // default profile for this configuration. + checkWatchdog(isWatchdogEnabled(), continueTest); + yield; + do_test_finished(); + yield; +} 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 000000000..dcdf21ce4 --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_disable.js @@ -0,0 +1,11 @@ +/* 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); + checkWatchdog(false, continueTest); + yield; + do_test_finished(); + yield; +} 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 000000000..8e31e1316 --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_enable.js @@ -0,0 +1,11 @@ +/* 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); + checkWatchdog(true, continueTest); + yield; + do_test_finished(); + yield; +} 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 000000000..ce3642963 --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_hibernate.js @@ -0,0 +1,53 @@ +/* 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); + + // 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); + do_check_true(startHibernation < now); + do_check_true(stopHibernation < now); + + // 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. + var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + timer.initWithCallback(continueTest, 10000, Ci.nsITimer.TYPE_ONE_SHOT); + simulateActivityCallback(false); + yield; + + simulateActivityCallback(true); + 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; + do_check_true(stateChange > now + 10*1000*1000 - FUZZ_FACTOR); + do_check_true(startHibernation > now + 2*1000*1000 - FUZZ_FACTOR); + do_check_true(startHibernation < now + 5*1000*1000 + FUZZ_FACTOR); + do_check_true(stopHibernation > now + 10*1000*1000 - FUZZ_FACTOR); + + do_test_finished(); + yield; +} 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 000000000..f0d14c2df --- /dev/null +++ b/js/xpconnect/tests/unit/test_watchdog_toggle.js @@ -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/. */ + +function testBody() { + var defaultBehavior = isWatchdogEnabled(); + setWatchdogEnabled(!defaultBehavior); + setWatchdogEnabled(defaultBehavior); + checkWatchdog(defaultBehavior, continueTest); + yield; + do_test_finished(); + yield; +} 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 000000000..e70983e9c --- /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 = ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(bunnies); + equal(keys, undefined, "test nondeterministicGetWeakMapKeys on non-WeakMap"); + + keys = ThreadSafeChromeUtils.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 = ThreadSafeChromeUtils.nondeterministicGetWeakSetKeys(bunnies); + equal(keys, undefined, "test nondeterministicGetWeakSetKeys on non-WeakMap"); + + keys = ThreadSafeChromeUtils.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; + + Components.utils.forceGC(); + + keys = ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(weakmap); + equal(keys.length, 1, "length of nondeterministicGetWeakMapKeys after GC"); + equal(weakmap.get(lizards), "oh no", "check lizards still in weakmap"); + + keys = ThreadSafeChromeUtils.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_writeToGlobalPrototype.js b/js/xpconnect/tests/unit/test_writeToGlobalPrototype.js new file mode 100644 index 000000000..0062861eb --- /dev/null +++ b/js/xpconnect/tests/unit/test_writeToGlobalPrototype.js @@ -0,0 +1,76 @@ +var G = 3; + +const Cu = Components.utils; + +function run_test() +{ + let s = Cu.Sandbox(this, {sandboxPrototype: this, writeToGlobalPrototype: true}); + + Cu.evalInSandbox("a = 3", s); + Cu.evalInSandbox("var b = 3", s); + Cu.evalInSandbox("const c = 3", s); + Cu.evalInSandbox("this.d = 3", s); + Cu.evalInSandbox("function e() { return 3; }", s); + + do_check_eq(Cu.evalInSandbox("a", s), 3); + do_check_eq(Cu.evalInSandbox("b", s), 3); + do_check_eq(Cu.evalInSandbox("c", s), 3); + do_check_eq(Cu.evalInSandbox("d", s), 3); + do_check_eq(Cu.evalInSandbox("e()", s), 3); + + do_check_eq(a, 3); + do_check_eq(b, 3); + // c is a lexical binding and does not write to the global prototype + do_check_eq(d, 3); + do_check_eq(e(), 3); + + a = 12; + do_check_eq(Cu.evalInSandbox("a", s), 12); + b = 12; + do_check_eq(Cu.evalInSandbox("b", s), 12); + d = 12; + do_check_eq(Cu.evalInSandbox("d", s), 12); + + this.q = 3; + do_check_eq(Cu.evalInSandbox("q", s), 3); + Cu.evalInSandbox("q = 12", s); + do_check_eq(q, 12); + + do_check_eq(Cu.evalInSandbox("G", s), 3); + Cu.evalInSandbox("G = 12", s); + do_check_eq(G, 12); + + Cu.evalInSandbox("Object.defineProperty(this, 'x', {enumerable: false, value: 3})", s); + do_check_eq(Cu.evalInSandbox("x", s), 3); + do_check_eq(x, 3); + for (var p in this) { + do_check_neq(p, "x"); + } + + Cu.evalInSandbox("Object.defineProperty(this, 'y', {get: function() { this.gotten = true; return 3; }})", s); + do_check_eq(y, 3); + do_check_eq(Cu.evalInSandbox("gotten", s), true); + do_check_eq(gotten, true); + + Cu.evalInSandbox("this.gotten = false", s); + do_check_eq(Cu.evalInSandbox("y", s), 3); + do_check_eq(Cu.evalInSandbox("gotten", s), true); + do_check_eq(gotten, true); + + Cu.evalInSandbox("Object.defineProperty(this, 'z', {get: function() { this.gotten = true; return 3; }, set: function(v) { this.setTo = v; }})", s); + z = 12; + do_check_eq(setTo, 12); + do_check_eq(z, 3); + do_check_eq(gotten, true); + do_check_eq(Cu.evalInSandbox("gotten", s), true); + gotten = false; + do_check_eq(Cu.evalInSandbox("gotten", s), false); + + Cu.evalInSandbox("z = 20", s); + do_check_eq(setTo, 20); + do_check_eq(Cu.evalInSandbox("z", s), 3); + do_check_eq(gotten, true); + do_check_eq(Cu.evalInSandbox("gotten", s), true); + gotten = false; + do_check_eq(Cu.evalInSandbox("gotten", s), false); +} diff --git a/js/xpconnect/tests/unit/test_xpcomutils.js b/js/xpconnect/tests/unit/test_xpcomutils.js new file mode 100644 index 000000000..f43454253 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xpcomutils.js @@ -0,0 +1,246 @@ +/* -*- 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. + */ + +Components.utils.import("resource://gre/modules/Preferences.jsm"); +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + +const Cc = Components.classes; +const Ci = Components.interfaces; + + +//////////////////////////////////////////////////////////////////////////////// +//// Tests + +add_test(function test_generateQI_string_names() +{ + var x = { + QueryInterface: XPCOMUtils.generateQI([ + Components.interfaces.nsIClassInfo, + "nsIDOMNode" + ]) + }; + + try { + x.QueryInterface(Components.interfaces.nsIClassInfo); + } catch(e) { + do_throw("Should QI to nsIClassInfo"); + } + try { + x.QueryInterface(Components.interfaces.nsIDOMNode); + } catch(e) { + do_throw("Should QI to nsIDOMNode"); + } + try { + x.QueryInterface(Components.interfaces.nsIDOMDocument); + do_throw("QI should not have succeeded!"); + } catch(e) {} + run_next_test(); +}); + + +add_test(function test_generateCI() +{ + const classID = Components.ID("562dae2e-7cff-432b-995b-3d4c03fa2b89"); + const classDescription = "generateCI test component"; + const flags = Components.interfaces.nsIClassInfo.DOM_OBJECT; + var x = { + QueryInterface: XPCOMUtils.generateQI([]), + classInfo: XPCOMUtils.generateCI({classID: classID, + interfaces: [], + flags: flags, + classDescription: classDescription}) + }; + + try { + var ci = x.QueryInterface(Components.interfaces.nsIClassInfo); + ci = ci.QueryInterface(Components.interfaces.nsISupports); + ci = ci.QueryInterface(Components.interfaces.nsIClassInfo); + do_check_eq(ci.classID, classID); + do_check_eq(ci.flags, flags); + do_check_eq(ci.classDescription, classDescription); + } catch(e) { + do_throw("Classinfo for x should not be missing or broken"); + } + 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; + }); + do_check_eq(accessCount, 0); + + // Get the property, making sure the access count has increased. + do_check_eq(obj.foo, TEST_VALUE); + do_check_eq(accessCount, 1); + do_check_true(obj.inScope); + + // Get the property once more, making sure the access count has not + // increased. + do_check_eq(obj.foo, TEST_VALUE); + do_check_eq(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) + do_check_true(prop in service); + for (let prop in service) + do_check_true(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"); + + + do_print("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"); + + 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 = {}; + Components.utils.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 [name, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_NAME)) { + print("Verify that the name/value pair exists in the expected entries."); + ok(EXPECTED_ENTRIES.has(name)); + do_check_eq(EXPECTED_ENTRIES.get(name), value); + EXPECTED_ENTRIES.delete(name); + } + print("Check that all of the expected entries have been deleted."); + do_check_eq(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: XPCOMUtils.generateSingletonFactory(XPCComponent), + QueryInterface: XPCOMUtils.generateQI([]) + }; + let NSGetFactory = XPCOMUtils.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. + do_check_eq(instance, + Cc[XPCCOMPONENT_CONTRACTID].createInstance(Ci.nsISupports)); + // Now, for sanity, check that getService is also returning the same instance. + do_check_eq(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 000000000..bf7b65927 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xpcwn_tamperproof.js @@ -0,0 +1,171 @@ +// Test that it's not possible to create expando properties on XPCWNs. +// See <https://bugzilla.mozilla.org/show_bug.cgi?id=1143810#c5>. + +const Cc = Components.classes; +const Ci = Components.interfaces; + +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; }); + do_check_false("expando" in realObj); + + // Strict assignment throws. + check_throws(function () { "use strict"; accessObj.expando = 14; }); + do_check_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"; }); + do_check_false(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"; }); + do_check_true(realObj[method] === originalMethod); + } + + // A constant is the same thing. + let originalConstantValue; + if (constant) { + originalConstantValue = accessObj[constant]; + accessObj[constant] = "nope"; + do_check_eq(realObj[constant], originalConstantValue); + check_throws(function () { "use strict"; accessObj[constant] = "nope"; }); + do_check_eq(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); + do_check_true("set" in originalAttributeDesc); + do_check_true(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); + do_check_true("set" in desc); + do_check_eq(originalAttributeDesc.get, desc.get); + do_check_eq(undefined, desc.set); + } + + // Reflect.set doesn't work either. + if (method) { + do_check_false(Reflect.set({}, method, "bad", accessObj)); + do_check_eq(realObj[method], originalMethod); + } + if (attribute) { + do_check_false(Reflect.set({}, attribute, "bad", accessObj)); + do_check_eq(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) { + do_check_eq(undefined, desc); + } else { + do_check_eq(originalDesc.configurable, desc.configurable); + do_check_eq(originalDesc.enumerable, desc.enumerable); + do_check_eq(originalDesc.writable, desc.writable); + do_check_eq(originalDesc.value, desc.value); + do_check_eq(originalDesc.get, desc.get); + do_check_eq(originalDesc.set, desc.set); + } + } + + // Existing properties can't be deleted. + if (method) { + do_check_false(delete accessObj[method]); + check_throws(function () { "use strict"; delete accessObj[method]; }); + do_check_eq(realObj[method], originalMethod); + } + if (constant) { + do_check_false(delete accessObj[constant]); + check_throws(function () { "use strict"; delete accessObj[constant]; }); + do_check_eq(realObj[constant], originalConstantValue); + } + if (attribute) { + do_check_false(delete accessObj[attribute]); + check_throws(function () { "use strict"; delete accessObj[attribute]; }); + desc = Object.getOwnPropertyDescriptor(realObj, attribute); + do_check_eq(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 principal = Cc["@mozilla.org/nullprincipal;1"].createInstance(Ci.nsIPrincipal); + test_twice(principal, {}); + + test_twice(Object.getPrototypeOf(principal), { + method: "subsumes", + constant: "APP_STATUS_INSTALLED", + attribute: "origin" + }); + + // 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 000000000..5c3397670 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_SavedFrame-02.js @@ -0,0 +1,75 @@ +// Test calling SavedFrame getters across wrappers from privileged and +// un-privileged globals. + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +Cu.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 000000000..6a931cff0 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xray_SavedFrame.js @@ -0,0 +1,108 @@ +// Bug 1117242: Test calling SavedFrame getters from globals that don't subsume +// that frame's principals. + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +Cu.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_xrayed_iterator.js b/js/xpconnect/tests/unit/test_xrayed_iterator.js new file mode 100644 index 000000000..1f82fd890 --- /dev/null +++ b/js/xpconnect/tests/unit/test_xrayed_iterator.js @@ -0,0 +1,36 @@ +const Cu = Components.utils; +function run_test() { + + var toEval = [ + "var customIterator = {", + " _array: [6, 7, 8, 9],", + " __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 in iterator) { + do_check_eq(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/xpcshell.ini b/js/xpconnect/tests/unit/xpcshell.ini new file mode 100644 index 000000000..99d44b975 --- /dev/null +++ b/js/xpconnect/tests/unit/xpcshell.ini @@ -0,0 +1,137 @@ +[DEFAULT] +head = +tail = +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 + importer.jsm + recursive_importA.jsm + recursive_importB.jsm + subScriptWithEarlyError.js + syntax_error.jsm + +[test_allowWaivers.js] +[test_bogus_files.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_bug1150106.js] +[test_bug1150771.js] +[test_bug1151385.js] +[test_bug1170311.js] +[test_bug1244222.js] +[test_bug_442086.js] +[test_callFunctionWithAsyncStack.js] +[test_classesByID_instanceof.js] +[test_deepFreezeClone.js] +[test_file.js] +[test_blob.js] +[test_blob2.js] +[test_file2.js] +[test_import.js] +[test_import_fail.js] +[test_interposition.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] +# Bug 676965: test fails consistently on Android +fail-if = os == "android" +[test_recursive_import.js] +[test_xpcomutils.js] +[test_unload.js] +[test_attributes.js] +# Bug 676965: test fails consistently on Android +fail-if = os == "android" +[test_params.js] +# Bug 676965: test fails consistently on Android +fail-if = os == "android" +[test_tearoffs.js] +[test_want_components.js] +[test_components.js] +[test_allowedDomains.js] +[test_allowedDomainsXHR.js] +[test_nuke_sandbox.js] +[test_sandbox_metadata.js] +[test_exportFunction.js] +[test_promise.js] +[test_returncode.js] +skip-if = os == "android" # native test components aren't available on Android +[test_textDecoder.js] +[test_url.js] +[test_URLSearchParams.js] +[test_fileReader.js] +[test_crypto.js] +[test_css.js] +[test_rtcIdentityProvider.js] +[test_sandbox_atob.js] +[test_isProxy.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 +[test_watchdog_hibernate.js] +head = head_watchdog.js +[test_weak_keys.js] +[test_writeToGlobalPrototype.js] +[test_xpcwn_tamperproof.js] +[test_xrayed_iterator.js] +[test_xray_SavedFrame.js] +[test_xray_SavedFrame-02.js] +[test_resolve_dead_promise.js] +[test_asyncLoadSubScriptError.js] |