1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/test/addons/simple-prefs-regression/app-extension/bootstrap.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,337 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +// @see http://mxr.mozilla.org/mozilla-central/source/js/src/xpconnect/loader/mozJSComponentLoader.cpp 1.9 + 1.10 +'use strict'; 1.11 + 1.12 +// IMPORTANT: Avoid adding any initialization tasks here, if you need to do 1.13 +// something before add-on is loaded consider addon/runner module instead! 1.14 + 1.15 +const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, 1.16 + results: Cr, manager: Cm } = Components; 1.17 +const ioService = Cc['@mozilla.org/network/io-service;1']. 1.18 + getService(Ci.nsIIOService); 1.19 +const resourceHandler = ioService.getProtocolHandler('resource'). 1.20 + QueryInterface(Ci.nsIResProtocolHandler); 1.21 +const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); 1.22 +const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1']. 1.23 + getService(Ci.mozIJSSubScriptLoader); 1.24 +const prefService = Cc['@mozilla.org/preferences-service;1']. 1.25 + getService(Ci.nsIPrefService). 1.26 + QueryInterface(Ci.nsIPrefBranch); 1.27 +const appInfo = Cc["@mozilla.org/xre/app-info;1"]. 1.28 + getService(Ci.nsIXULAppInfo); 1.29 +const vc = Cc["@mozilla.org/xpcom/version-comparator;1"]. 1.30 + getService(Ci.nsIVersionComparator); 1.31 + 1.32 + 1.33 +const REASON = [ 'unknown', 'startup', 'shutdown', 'enable', 'disable', 1.34 + 'install', 'uninstall', 'upgrade', 'downgrade' ]; 1.35 + 1.36 +const bind = Function.call.bind(Function.bind); 1.37 + 1.38 +let loader = null; 1.39 +let unload = null; 1.40 +let cuddlefishSandbox = null; 1.41 +let nukeTimer = null; 1.42 + 1.43 +// Utility function that synchronously reads local resource from the given 1.44 +// `uri` and returns content string. 1.45 +function readURI(uri) { 1.46 + let ioservice = Cc['@mozilla.org/network/io-service;1']. 1.47 + getService(Ci.nsIIOService); 1.48 + let channel = ioservice.newChannel(uri, 'UTF-8', null); 1.49 + let stream = channel.open(); 1.50 + 1.51 + let cstream = Cc['@mozilla.org/intl/converter-input-stream;1']. 1.52 + createInstance(Ci.nsIConverterInputStream); 1.53 + cstream.init(stream, 'UTF-8', 0, 0); 1.54 + 1.55 + let str = {}; 1.56 + let data = ''; 1.57 + let read = 0; 1.58 + do { 1.59 + read = cstream.readString(0xffffffff, str); 1.60 + data += str.value; 1.61 + } while (read != 0); 1.62 + 1.63 + cstream.close(); 1.64 + 1.65 + return data; 1.66 +} 1.67 + 1.68 +// We don't do anything on install & uninstall yet, but in a future 1.69 +// we should allow add-ons to cleanup after uninstall. 1.70 +function install(data, reason) {} 1.71 +function uninstall(data, reason) {} 1.72 + 1.73 +function startup(data, reasonCode) { 1.74 + try { 1.75 + let reason = REASON[reasonCode]; 1.76 + // URI for the root of the XPI file. 1.77 + // 'jar:' URI if the addon is packed, 'file:' URI otherwise. 1.78 + // (Used by l10n module in order to fetch `locale` folder) 1.79 + let rootURI = data.resourceURI.spec; 1.80 + 1.81 + // TODO: Maybe we should perform read harness-options.json asynchronously, 1.82 + // since we can't do anything until 'sessionstore-windows-restored' anyway. 1.83 + let options = JSON.parse(readURI(rootURI + './harness-options.json')); 1.84 + 1.85 + let id = options.jetpackID; 1.86 + let name = options.name; 1.87 + 1.88 + // Clean the metadata 1.89 + options.metadata[name]['permissions'] = options.metadata[name]['permissions'] || {}; 1.90 + 1.91 + // freeze the permissionss 1.92 + Object.freeze(options.metadata[name]['permissions']); 1.93 + // freeze the metadata 1.94 + Object.freeze(options.metadata[name]); 1.95 + 1.96 + // Register a new resource 'domain' for this addon which is mapping to 1.97 + // XPI's `resources` folder. 1.98 + // Generate the domain name by using jetpack ID, which is the extension ID 1.99 + // by stripping common characters that doesn't work as a domain name: 1.100 + let uuidRe = 1.101 + /^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/; 1.102 + 1.103 + let domain = id. 1.104 + toLowerCase(). 1.105 + replace(/@/g, '-at-'). 1.106 + replace(/\./g, '-dot-'). 1.107 + replace(uuidRe, '$1'); 1.108 + 1.109 + let prefixURI = 'resource://' + domain + '/'; 1.110 + let resourcesURI = ioService.newURI(rootURI + '/resources/', null, null); 1.111 + resourceHandler.setSubstitution(domain, resourcesURI); 1.112 + 1.113 + // Create path to URLs mapping supported by loader. 1.114 + let paths = { 1.115 + // Relative modules resolve to add-on package lib 1.116 + './': prefixURI + name + '/lib/', 1.117 + './tests/': prefixURI + name + '/tests/', 1.118 + '': 'resource://gre/modules/commonjs/' 1.119 + }; 1.120 + 1.121 + // Maps addon lib and tests ressource folders for each package 1.122 + paths = Object.keys(options.metadata).reduce(function(result, name) { 1.123 + result[name + '/'] = prefixURI + name + '/lib/' 1.124 + result[name + '/tests/'] = prefixURI + name + '/tests/' 1.125 + return result; 1.126 + }, paths); 1.127 + 1.128 + // We need to map tests folder when we run sdk tests whose package name 1.129 + // is stripped 1.130 + if (name == 'addon-sdk') 1.131 + paths['tests/'] = prefixURI + name + '/tests/'; 1.132 + 1.133 + let useBundledSDK = options['force-use-bundled-sdk']; 1.134 + if (!useBundledSDK) { 1.135 + try { 1.136 + useBundledSDK = prefService.getBoolPref("extensions.addon-sdk.useBundledSDK"); 1.137 + } 1.138 + catch (e) { 1.139 + // Pref doesn't exist, allow using Firefox shipped SDK 1.140 + } 1.141 + } 1.142 + 1.143 + // Starting with Firefox 21.0a1, we start using modules shipped into firefox 1.144 + // Still allow using modules from the xpi if the manifest tell us to do so. 1.145 + // And only try to look for sdk modules in xpi if the xpi actually ship them 1.146 + if (options['is-sdk-bundled'] && 1.147 + (vc.compare(appInfo.version, '21.0a1') < 0 || useBundledSDK)) { 1.148 + // Maps sdk module folders to their resource folder 1.149 + paths[''] = prefixURI + 'addon-sdk/lib/'; 1.150 + // test.js is usually found in root commonjs or SDK_ROOT/lib/ folder, 1.151 + // so that it isn't shipped in the xpi. Keep a copy of it in sdk/ folder 1.152 + // until we no longer support SDK modules in XPI: 1.153 + paths['test'] = prefixURI + 'addon-sdk/lib/sdk/test.js'; 1.154 + } 1.155 + 1.156 + // Retrieve list of module folder overloads based on preferences in order to 1.157 + // eventually used a local modules instead of files shipped into Firefox. 1.158 + let branch = prefService.getBranch('extensions.modules.' + id + '.path'); 1.159 + paths = branch.getChildList('', {}).reduce(function (result, name) { 1.160 + // Allows overloading of any sub folder by replacing . by / in pref name 1.161 + let path = name.substr(1).split('.').join('/'); 1.162 + // Only accept overloading folder by ensuring always ending with `/` 1.163 + if (path) path += '/'; 1.164 + let fileURI = branch.getCharPref(name); 1.165 + 1.166 + // On mobile, file URI has to end with a `/` otherwise, setSubstitution 1.167 + // takes the parent folder instead. 1.168 + if (fileURI[fileURI.length-1] !== '/') 1.169 + fileURI += '/'; 1.170 + 1.171 + // Maps the given file:// URI to a resource:// in order to avoid various 1.172 + // failure that happens with file:// URI and be close to production env 1.173 + let resourcesURI = ioService.newURI(fileURI, null, null); 1.174 + let resName = 'extensions.modules.' + domain + '.commonjs.path' + name; 1.175 + resourceHandler.setSubstitution(resName, resourcesURI); 1.176 + 1.177 + result[path] = 'resource://' + resName + '/'; 1.178 + return result; 1.179 + }, paths); 1.180 + 1.181 + // Make version 2 of the manifest 1.182 + let manifest = options.manifest; 1.183 + 1.184 + // Import `cuddlefish.js` module using a Sandbox and bootstrap loader. 1.185 + let cuddlefishPath = 'loader/cuddlefish.js'; 1.186 + let cuddlefishURI = 'resource://gre/modules/commonjs/sdk/' + cuddlefishPath; 1.187 + if (paths['sdk/']) { // sdk folder has been overloaded 1.188 + // (from pref, or cuddlefish is still in the xpi) 1.189 + cuddlefishURI = paths['sdk/'] + cuddlefishPath; 1.190 + } 1.191 + else if (paths['']) { // root modules folder has been overloaded 1.192 + cuddlefishURI = paths[''] + 'sdk/' + cuddlefishPath; 1.193 + } 1.194 + 1.195 + cuddlefishSandbox = loadSandbox(cuddlefishURI); 1.196 + let cuddlefish = cuddlefishSandbox.exports; 1.197 + 1.198 + // Normalize `options.mainPath` so that it looks like one that will come 1.199 + // in a new version of linker. 1.200 + let main = options.mainPath; 1.201 + 1.202 + unload = cuddlefish.unload; 1.203 + loader = cuddlefish.Loader({ 1.204 + paths: paths, 1.205 + // modules manifest. 1.206 + manifest: manifest, 1.207 + 1.208 + // Add-on ID used by different APIs as a unique identifier. 1.209 + id: id, 1.210 + // Add-on name. 1.211 + name: name, 1.212 + // Add-on version. 1.213 + version: options.metadata[name].version, 1.214 + // Add-on package descriptor. 1.215 + metadata: options.metadata[name], 1.216 + // Add-on load reason. 1.217 + loadReason: reason, 1.218 + 1.219 + prefixURI: prefixURI, 1.220 + // Add-on URI. 1.221 + rootURI: rootURI, 1.222 + // options used by system module. 1.223 + // File to write 'OK' or 'FAIL' (exit code emulation). 1.224 + resultFile: options.resultFile, 1.225 + // Arguments passed as --static-args 1.226 + staticArgs: options.staticArgs, 1.227 + 1.228 + // Arguments related to test runner. 1.229 + modules: { 1.230 + '@test/options': { 1.231 + allTestModules: options.allTestModules, 1.232 + iterations: options.iterations, 1.233 + filter: options.filter, 1.234 + profileMemory: options.profileMemory, 1.235 + stopOnError: options.stopOnError, 1.236 + verbose: options.verbose, 1.237 + parseable: options.parseable, 1.238 + checkMemory: options.check_memory, 1.239 + } 1.240 + } 1.241 + }); 1.242 + 1.243 + let module = cuddlefish.Module('sdk/loader/cuddlefish', cuddlefishURI); 1.244 + let require = cuddlefish.Require(loader, module); 1.245 + 1.246 + require('sdk/addon/runner').startup(reason, { 1.247 + loader: loader, 1.248 + main: main, 1.249 + prefsURI: rootURI + 'defaults/preferences/prefs.js' 1.250 + }); 1.251 + } catch (error) { 1.252 + dump('Bootstrap error: ' + 1.253 + (error.message ? error.message : String(error)) + '\n' + 1.254 + (error.stack || error.fileName + ': ' + error.lineNumber) + '\n'); 1.255 + throw error; 1.256 + } 1.257 +}; 1.258 + 1.259 +function loadSandbox(uri) { 1.260 + let proto = { 1.261 + sandboxPrototype: { 1.262 + loadSandbox: loadSandbox, 1.263 + ChromeWorker: ChromeWorker 1.264 + } 1.265 + }; 1.266 + let sandbox = Cu.Sandbox(systemPrincipal, proto); 1.267 + // Create a fake commonjs environnement just to enable loading loader.js 1.268 + // correctly 1.269 + sandbox.exports = {}; 1.270 + sandbox.module = { uri: uri, exports: sandbox.exports }; 1.271 + sandbox.require = function (id) { 1.272 + if (id !== "chrome") 1.273 + throw new Error("Bootstrap sandbox `require` method isn't implemented."); 1.274 + 1.275 + return Object.freeze({ Cc: Cc, Ci: Ci, Cu: Cu, Cr: Cr, Cm: Cm, 1.276 + CC: bind(CC, Components), components: Components, 1.277 + ChromeWorker: ChromeWorker }); 1.278 + }; 1.279 + scriptLoader.loadSubScript(uri, sandbox, 'UTF-8'); 1.280 + return sandbox; 1.281 +} 1.282 + 1.283 +function unloadSandbox(sandbox) { 1.284 + if ("nukeSandbox" in Cu) 1.285 + Cu.nukeSandbox(sandbox); 1.286 +} 1.287 + 1.288 +function setTimeout(callback, delay) { 1.289 + let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); 1.290 + timer.initWithCallback({ notify: callback }, delay, 1.291 + Ci.nsITimer.TYPE_ONE_SHOT); 1.292 + return timer; 1.293 +} 1.294 + 1.295 +function shutdown(data, reasonCode) { 1.296 + let reason = REASON[reasonCode]; 1.297 + if (loader) { 1.298 + unload(loader, reason); 1.299 + unload = null; 1.300 + 1.301 + // Don't waste time cleaning up if the application is shutting down 1.302 + if (reason != "shutdown") { 1.303 + // Avoid leaking all modules when something goes wrong with one particular 1.304 + // module. Do not clean it up immediatly in order to allow executing some 1.305 + // actions on addon disabling. 1.306 + // We need to keep a reference to the timer, otherwise it is collected 1.307 + // and won't ever fire. 1.308 + nukeTimer = setTimeout(nukeModules, 1000); 1.309 + } 1.310 + } 1.311 +}; 1.312 + 1.313 +function nukeModules() { 1.314 + nukeTimer = null; 1.315 + // module objects store `exports` which comes from sandboxes 1.316 + // We should avoid keeping link to these object to avoid leaking sandboxes 1.317 + for (let key in loader.modules) { 1.318 + delete loader.modules[key]; 1.319 + } 1.320 + // Direct links to sandboxes should be removed too 1.321 + for (let key in loader.sandboxes) { 1.322 + let sandbox = loader.sandboxes[key]; 1.323 + delete loader.sandboxes[key]; 1.324 + // Bug 775067: From FF17 we can kill all CCW from a given sandbox 1.325 + unloadSandbox(sandbox); 1.326 + } 1.327 + loader = null; 1.328 + 1.329 + // both `toolkit/loader` and `system/xul-app` are loaded as JSM's via 1.330 + // `cuddlefish.js`, and needs to be unloaded to avoid memory leaks, when 1.331 + // the addon is unload. 1.332 + 1.333 + unloadSandbox(cuddlefishSandbox.loaderSandbox); 1.334 + unloadSandbox(cuddlefishSandbox.xulappSandbox); 1.335 + 1.336 + // Bug 764840: We need to unload cuddlefish otherwise it will stay alive 1.337 + // and keep a reference to this compartment. 1.338 + unloadSandbox(cuddlefishSandbox); 1.339 + cuddlefishSandbox = null; 1.340 +}