1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/lib/sdk/loader/sandbox.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,74 @@ 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 +"use strict"; 1.8 + 1.9 +module.metadata = { 1.10 + "stability": "experimental" 1.11 +}; 1.12 + 1.13 +const { Cc, Ci, CC, Cu } = require('chrome'); 1.14 +const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); 1.15 +const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1']. 1.16 + getService(Ci.mozIJSSubScriptLoader); 1.17 +const self = require('sdk/self'); 1.18 +const { getTabId, getTabForContentWindow } = require('../tabs/utils'); 1.19 +const { getInnerId } = require('../window/utils'); 1.20 + 1.21 +const { gDevToolsExtensions: { 1.22 + addContentGlobal, removeContentGlobal 1.23 +} } = Cu.import("resource://gre/modules/devtools/DevToolsExtensions.jsm", {}); 1.24 + 1.25 +/** 1.26 + * Make a new sandbox that inherits given `source`'s principals. Source can be 1.27 + * URI string, DOMWindow or `null` for system principals. 1.28 + */ 1.29 +function sandbox(target, options) { 1.30 + options = options || {}; 1.31 + options.metadata = options.metadata ? options.metadata : {}; 1.32 + options.metadata.addonID = options.metadata.addonID ? 1.33 + options.metadata.addonID : self.id; 1.34 + 1.35 + let sandbox = Cu.Sandbox(target || systemPrincipal, options); 1.36 + Cu.setSandboxMetadata(sandbox, options.metadata); 1.37 + let innerWindowID = options.metadata['inner-window-id'] 1.38 + if (innerWindowID) { 1.39 + addContentGlobal({ 1.40 + global: sandbox, 1.41 + 'inner-window-id': innerWindowID 1.42 + }); 1.43 + } 1.44 + return sandbox; 1.45 +} 1.46 +exports.sandbox = sandbox; 1.47 + 1.48 +/** 1.49 + * Evaluates given `source` in a given `sandbox` and returns result. 1.50 + */ 1.51 +function evaluate(sandbox, code, uri, line, version) { 1.52 + return Cu.evalInSandbox(code, sandbox, version || '1.8', uri || '', line || 1); 1.53 +} 1.54 +exports.evaluate = evaluate; 1.55 + 1.56 +/** 1.57 + * Evaluates code under the given `uri` in the given `sandbox`. 1.58 + * 1.59 + * @param {String} uri 1.60 + * The URL pointing to the script to load. 1.61 + * It must be a local chrome:, resource:, file: or data: URL. 1.62 + */ 1.63 +function load(sandbox, uri) { 1.64 + if (uri.indexOf('data:') === 0) { 1.65 + let source = uri.substr(uri.indexOf(',') + 1); 1.66 + 1.67 + return evaluate(sandbox, decodeURIComponent(source), '1.8', uri, 0); 1.68 + } else { 1.69 + return scriptLoader.loadSubScript(uri, sandbox, 'UTF-8'); 1.70 + } 1.71 +} 1.72 +exports.load = load; 1.73 + 1.74 +/** 1.75 + * Forces the given `sandbox` to be freed immediately. 1.76 + */ 1.77 +exports.nuke = Cu.nukeSandbox