Files
palemoon27/js/xpconnect/loader/mozJSSubScriptLoader.cpp
T
roytam1 b3541682d0 import changes from `dev' branch of rmottola/Arctic-Fox:
- bug 1157569 part 1 - Rename BC_BORDER_{TOP,RIGHT,BOTTOM,LEFT}_HALF* to BC_BORDER_{START,END}_HALF*. r=roc (2ef82ce76)
- Bug 1157569 part 2 - Convert output parameters of GetColorAndStyle/GetPaintStyleInfo in nsTableFrame to use pointers. r=roc (c58bbe734)
- Bug 1157569 part 3 - Merge two GetColorAndStyle functions in nsTableFrame. r=roc (009df4d97)
- Bug 1157569 part 4 - Replace mTableIsLTR with mTableWM in BCMapCellInfo & BCPaintBorderIterator. r=roc (9784a46eb)
- Bug 1157569 part 5 - Convert GetColorAndStyle, GetPaintStyleInfo, and CompareBorders in nsTableFrame to accept writing mode and logical side. r=roc (aaddc4a80)
- Bug 1157569 part 6 - Rename methods and fields in BCMapCellInfo from physicals to logicals. r=roc (aeaa0b18c)
- Bug 1157569 part 7 - Rename methods and fields in nsTableColFrame from physicals to logicals. r=roc (fd4e1e667)
- Bug 1157569 part 8 - Move some code in BCPaintBorderIterator::SetDamageArea for less computation. r=roc (634f19ca7)
- missing bit of Bug 895096 - Part 1 (a96e3d35c)
- Bug 1157569 part 9 - Rename methods and fields in nsTableRowFrame from physicals to logicals. r=roc (d097f1e4f)
- Bug 1157569 part 10 - Add operator+= for LogicalMargin. r=jfkthame (c651b685f)
- Bug 1159101 part 4 - Override GetWritingMode() in nsTable{{Col,Row}{,Group},Cell}Frame. r=roc (34d90d10b)
- Bug 1159101 part 5 - Initialize writing mode of desired mode of table cell frame from its table frame on a CLOSED TREE. r=roc (8bc6978ca)
- Bug 1157569 part 11 - Rename methods and fields in nsTableCellFrame from physicals to logicals. r=roc (bcfd4514b)
- Bug 1157569 part 12 - Remove useless m{Start,End}Side from BCMapCellInfo. r=roc (1df59d670)
- Bug 1159127 - Always redirect inserting col group frame to first-in-flow table frame. r=mats (2e41bbeeb)
- Bug 1167765: Misc whitespace cleanup in nsTableFrame.cpp. whitespace/rewrapping-only, no review, DONTBUILD (f256939c9)
- Bug 1167696 part 1: Remove nsTableReflowState's unused constructor & nsPresContext arg. r=mats (5b8beadb9)
- Bug 1167696 part 2: Remove nsTableReflowState's frame constructor-arg; get it from passed-in reflow state instead. r=mats (205dad74f)
- Bug 1155412: Use mozilla::Maybe instead of hardcoded placement-new, for reflow state created in nsTableOuterFrame::OuterBeginReflowChild() and used by its caller. r=dbaron (ebf9e9891)
- Bug 1147834: Use abstract coordinates in nsHTMLReflowState, r=jfkthame (30e644a14)
- Bug 1169432 part 2: Refactor nsTableFrame::Init. r=mats (779928597)
- Bug 1169432 part 3: Use nsTArray::Contains instead of nsTArray::IndexOf(), for brevity, in nsTableFrame. r=mats (aa6aee3c4)
- Bug 1169432 part 4: Convert NS_ASSERTION(false, ...) to NS_ERROR(...) in nsTableFrame. r=mats (9cbb2f53f)
- Bug 1169432 part 5: Use range-based 'for' loops when walking frame lists, in nsTableFrame. r=mats (bd4e7d0d4)
- Bug 1171328 - Convert nsTableFrame::GetChildAreaOffset() and its friends to use LogicalMargin. r=dholbert (196955d0c)
- Remove unneeded code from SmoothScrollAnimation. (bug 1139220 part 4, r=kats) (68c6af9f8)
- Use stronger typing for GetScrollWheelDelta. (bug 1139220 part 5, r=kats) (4669d1f38)
- When APZ is enabled, only apply the root scroll delta override to root frames. (bug 1155800, r=kats) (2a738ee82)
- Bug 1168629. Clear frame metrics on the root layer if we aren't setting new frame metrics because the layer may be recycled and still have frame metrics from last time. r=mstange (dc0889fae)
- Bug 1158424 - Rename FrameMetrics::mIsRoot to mIsRootContent. r=kats (0005fb016)
- Bug 1148078: Replace the word "Logical" with "Flex-Relative" in some vars & functions in flexbox layout. r=mats (601497c55)
- Bug 1148298 part 1: Convert most flexbox-layout IsAxisHorizontal() calls into IsMainAxisHorizontal()/IsCrossAxisHorizontal(). r=mats (ff2aaa5b3)
- Bug 1148298 part 3: Make flexbox helper GetBaselineOffsetFromOuterCrossEdge take a FlexboxAxisTracker instead of an explicit axis. r=mats (009dd9f7e)
- Bug 1148298 part 4: Convert flexbox helper-function IsAxisHorizontal() to be a private implementation detail of FlexboxAxisTracker. r=mats (901f830d6)
- Bug 1148298 part 2: Replace flexbox static helper-function GetSizeProBug 1148298 part 2: Replace flexbox static helper-function GetSizePro (3d2940f88)
- Bug 1158290 part 1: Use AvailableBSize instead of AvailableHeight, throughout flex layout. r=mats (49e2075f8)
- Bug 1148294 part 1: Determine flex axes (in FlexboxAxisTracker) using the flex container's writing mode. r=mats (67f12cf58)
- Bug 1148294 part 2: Add one reftest for writing-mode & direction properties' influence on flex axes. (85e0ede9d)
- Bug 1148294 part 3: Add more reftests for writing-mode & direction properties' influence on flex axes (as modified copies of first test). (fac965a24)
- Bug 1148294 followup: fix spec links in reftests flexbox-writing-mode-* to point to TR instead of ED spec version. (no review) (84333c728)
- Bug 1158290 part 2: Use logical (not physical) skipsides & borderpadding when chipping away from available BSize. r=mats (987b4edfa)
- Bug 1152913 part 1: Make FlexboxAxisTracker store the WritingMode & representation of how flex axes map to it. r=mats (675737981)
- Bug 1152951: Delete the copy-constructor and reassignment operator for FlexboxAxisTracker & PositionTracker state-management classes. r=mats (71c88e7e9)
- Bug 1152913 part 2: Convert flexbox 'IsAxisHorizontal' checks to use new logical-axis member data. r=mats (122b434a5)
- Bug 1158290 part 3: Convert GenerateFlexLines to use logical axes & sizes. r=mats (367cb1c01)
- Bug 1158290 part 4: Clarify documentation & naming of ClampFlexContainerMainSize (now called ResolveFlexContainerMainSize). r=mats (5af11ff23)
- Bug 1149383 part 1: Make flexbox writing-mode tests use different widths vs. heights to reveal bug with vertical writing-modes. (test-only) (c4782feaa)
- Bug 1149383 part 2: Reorder width/height decls in flexbox-writing-mode reftests for consistency. (test-only) (bba907b70)
- Bug 1158290 part 5: Use logical coords & axes in methods that computeBug 1158290 part 5: Use logical coords & axes in methods that compute (b78726528)
- Bug 1158290 part 6: Use new GET_[MAIN|CROSS]_COMPONENT_LOGICAL macros, to reduce explicit width/height usage. r=mats (25d2e20a3)
- Bug 1152913 part 3: Make flexbox's PositionTracker classes track whether axis is reversed, & directly convert flex item final sizes/positions to logical coords. r=mats (1feee7e6d)
- Bug 1174507 - Replace the frame flag CONTAINS_RELATIVE_HEIGHT with CONTAINS_RELATIVE_BSIZE, and adjust callsites appropriately. r=dholbert (0e981d5ac)
- Clip async scrollframes based on the displaylist clip, not the composition bounds. (bug 1148582 part 4, r=tn) (f2b1196ed)
- Bug 1148582 - Add mask layers to FrameMetrics for ancestor scroll frame clips. r=mattwoodrow (008239305)
- Bug 1148582 - Factor mask layer creation out of ContainerState::SetupMaskLayer. r=mstange (1d739614e)
- piece of Bug 1138442 (e98de18dd)
- Bug 1173307 - Convert nsTableCellFrame to work with logical coordinates. r=dholbert (81d0aa811)
- Bug 1174700 - patch 1 - Convert nsTableRowFrame and nsTableRowGroupFrame to work with logical coordinates. r=dholbert (09ee9c814)
- Bug 1174700 - patch 2 - Convert nsTableFrame::SetColumnDimensions to work with logical-order iteration over the table, so that column coordinates and collapsed borders are correct. r=dholbert (7957e377b)
- Bug 1129040 - Provide a way for content processes to query the chrome side blocklist service. r=billm (5ea750b8b)
- Bug 1174711 - patch 1 - Rename nsIPercentHeightObserver to nsIPercentBSizeObserver, and update related frame methods to match. r=dholbert (7a17fbe4f)
- Bug 1174711 - patch 2 - Convert nsTableFrame to work with logical coordinates. r=dholbert (329776abe)
- Bug 1174711 - patch 3 - Rename a couple more frame-state bits from physical to logical. r=dholbert (d61c9624d)
- Bug 1174711 - patch 4 - Rename mSpecialHeightReflow to mSpecialBSizeReflow, and update comments to match. r=dholbert (49969e512)
- Bug 1174711 patch 5 - Copy inline-size rather than width from prev-in-flow when initializing nsTableFrame. r=dholbert (7afb6c80a)
- pointer style (52cd6f9af)
- pointer style (ba99b3f74)
- Bug 1149797 - Use the loop's *static* block object when freshening a loop's block object, then copy in values from the old cloned block. Using the old cloned block directly isn't valid when the cloned block might be extended with additional variables created by eval or added by nested function statements. r=shu (deba22790)
- Bug 1165486 - Cleanup: use standard object allocation functions when allocating scope objects. (r=terrence) (b35a4d7aa)
- pointer style (74ea6d085)
- Bug 1165486 - Add StaticNonSyntacticScopeObjects and teach scope iterators about it. (r=luke) (18a526ed3)
- Bug 1144371: Implement DEBUG-only JS shell function |dumpStringRepresentation|. r=jandem (35524cf42)
- Bug 1148963 - OdinMonkey: add CompileOptions::lazyParsingDisabled and testing function setDiscardSource (r=bz) (53f9c8fe6)
- pointer style (edaa05d69)
- Bug 1165486 - Rename hasPollutedGlobalScope to hasNonSyntacticScope. (r=luke) (505fc8d05)
- pointer style (3c4435038)
- Bug 1165486 - Remove PollutedGlobalScopeOption in favor of using the static scope chain to detect non-syntactic scopes. (r=luke) (73ca126f5)
- Bug 1150106 - Async loadSubscript - Part 1, add `async` to loadSubscriptWithOptions r=bholley,mcrr8 (a0ffeed0d)
- Bug 1150106 - Add an async version of loadSubscript - Part 2, tests r=bholley (6aeaa93e4)
- Bug 1165486 - Use JS::CompileForNonSyntacticScope in Gecko where we used to set polluted global scope. (r=bz, rs=bholley) (073332ac9)
- Bug 1165486 - Split JS::Compile into JS::Compile and JS::CompileForNonSyntacticScope. (r=luke) (0b82c73c4)
- Bug 1165486 - Restructure function and script cloning in light of PollutingGlobal scope changes. (r=Waldo) (b4e39652c)
- Bug 1141865 - Part 7: Make new.target work in generator functions. (r=jorendorff, r=jandem) (a9f5ce1ad)
- Bug 1165486 - Detect with scopes at parse time using the static scope chain for non-function scripts. Also cache static scope properties on SharedGlobalContext. (r=efaust) (a7d4283cb)
- Bug 1176070 - Optimize nsTableFrame's FirstInFlow() lookups from calls to GetColumnISize(). r=dholbert (beed47b93)
- fix misspatch of Bug 1141862 - Part 6 (d091f70a2)
- Bug 1169736 - Temporarily disallow eval and arrow functions inside derived class constructors. (r=jorendorff) (6cf8a2db1)
- Bug 1150855 - Disallow method syntax without curly brackets. r=efaust (26086ee95)
- part of Bug 1150855 - Remove uses of the curly syntax. (bfe86ea19)
- Bug 1169853 - Require semicolon after export default AssignmentExpression. r=shu (580ff7e30)
- Bug 1174009 - Remove a couple of unused AutoRooter types; r=sfink (113aee16a)
2020-12-21 14:13:41 +08:00

888 lines
28 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=8 sts=4 et sw=4 tw=99: */
/* 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 "mozJSSubScriptLoader.h"
#include "mozJSComponentLoader.h"
#include "mozJSLoaderUtils.h"
#include "nsIURI.h"
#include "nsIIOService.h"
#include "nsIChannel.h"
#include "nsIInputStream.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsIFileURL.h"
#include "nsScriptLoader.h"
#include "nsIScriptSecurityManager.h"
#include "nsThreadUtils.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "nsJSPrincipals.h"
#include "xpcprivate.h" // For xpc::OptionsBase
#include "jswrapper.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/scache/StartupCache.h"
#include "mozilla/scache/StartupCacheUtils.h"
#include "mozilla/unused.h"
#include "nsContentUtils.h"
#include "nsStringGlue.h"
#include "nsCycleCollectionParticipant.h"
using namespace mozilla::scache;
using namespace JS;
using namespace xpc;
using namespace mozilla;
using namespace mozilla::dom;
class MOZ_STACK_CLASS LoadSubScriptOptions : public OptionsBase {
public:
explicit LoadSubScriptOptions(JSContext* cx = xpc_GetSafeJSContext(),
JSObject* options = nullptr)
: OptionsBase(cx, options)
, target(cx)
, charset(NullString())
, ignoreCache(false)
, async(false)
{ }
virtual bool Parse() {
return ParseObject("target", &target) &&
ParseString("charset", charset) &&
ParseBoolean("ignoreCache", &ignoreCache) &&
ParseBoolean("async", &async);
}
RootedObject target;
nsString charset;
bool ignoreCache;
bool async;
};
/* load() error msgs, XXX localize? */
#define LOAD_ERROR_NOSERVICE "Error creating IO Service."
#define LOAD_ERROR_NOURI "Error creating URI (invalid URL scheme?)"
#define LOAD_ERROR_NOSCHEME "Failed to get URI scheme. This is bad."
#define LOAD_ERROR_URI_NOT_LOCAL "Trying to load a non-local URI."
#define LOAD_ERROR_NOSTREAM "Error opening input stream (invalid filename?)"
#define LOAD_ERROR_NOCONTENT "ContentLength not available (not a local URL?)"
#define LOAD_ERROR_BADCHARSET "Error converting to specified charset"
#define LOAD_ERROR_BADREAD "File Read Error."
#define LOAD_ERROR_READUNDERFLOW "File Read Error (underflow.)"
#define LOAD_ERROR_NOPRINCIPALS "Failed to get principals."
#define LOAD_ERROR_NOSPEC "Failed to get URI spec. This is bad."
#define LOAD_ERROR_CONTENTTOOBIG "ContentLength is too large"
mozJSSubScriptLoader::mozJSSubScriptLoader() : mSystemPrincipal(nullptr)
{
}
mozJSSubScriptLoader::~mozJSSubScriptLoader()
{
/* empty */
}
NS_IMPL_ISUPPORTS(mozJSSubScriptLoader, mozIJSSubScriptLoader)
static nsresult
ReportError(JSContext* cx, const char* msg)
{
RootedValue exn(cx, JS::StringValue(JS_NewStringCopyZ(cx, msg)));
JS_SetPendingException(cx, exn);
return NS_OK;
}
static nsresult
ReportError(JSContext* cx, const char* origMsg, nsIURI* uri)
{
if (!uri)
return ReportError(cx, origMsg);
nsAutoCString spec;
nsresult rv = uri->GetSpec(spec);
if (NS_FAILED(rv))
spec.Assign("(unknown)");
nsAutoCString msg(origMsg);
msg.Append(": ");
msg.Append(spec);
return ReportError(cx, msg.get());
}
nsresult
PrepareScript(nsIURI* uri,
JSContext* cx,
RootedObject& targetObj,
const char* uriStr,
const nsAString& charset,
const char* buf,
int64_t len,
bool reuseGlobal,
MutableHandleScript script,
MutableHandleFunction function)
{
JS::CompileOptions options(cx);
options.setFileAndLine(uriStr, 1);
if (!charset.IsVoid()) {
char16_t* scriptBuf = nullptr;
size_t scriptLength = 0;
nsresult rv =
nsScriptLoader::ConvertToUTF16(nullptr, reinterpret_cast<const uint8_t*>(buf), len,
charset, nullptr, scriptBuf, scriptLength);
JS::SourceBufferHolder srcBuf(scriptBuf, scriptLength,
JS::SourceBufferHolder::GiveOwnership);
if (NS_FAILED(rv)) {
return ReportError(cx, LOAD_ERROR_BADCHARSET, uri);
}
if (!reuseGlobal) {
if (JS_IsGlobalObject(targetObj))
JS::Compile(cx, options, srcBuf, script);
else
JS::CompileForNonSyntacticScope(cx, options, srcBuf, script);
} else {
AutoObjectVector scopeChain(cx);
if (!JS_IsGlobalObject(targetObj) &&
!scopeChain.append(targetObj)) {
return NS_ERROR_OUT_OF_MEMORY;
}
// XXXbz do we really not care if the compile fails???
JS::CompileFunction(cx, scopeChain, options, nullptr, 0, nullptr,
srcBuf, function);
}
} else {
// We only use lazy source when no special encoding is specified because
// the lazy source loader doesn't know the encoding.
if (!reuseGlobal) {
options.setSourceIsLazy(true);
if (JS_IsGlobalObject(targetObj))
JS::Compile(cx, options, buf, len, script);
else
JS::CompileForNonSyntacticScope(cx, options, buf, len, script);
} else {
AutoObjectVector scopeChain(cx);
if (!JS_IsGlobalObject(targetObj) &&
!scopeChain.append(targetObj)) {
return NS_ERROR_OUT_OF_MEMORY;
}
// XXXbz do we really not care if the compile fails???
JS::CompileFunction(cx, scopeChain, options, nullptr, 0, nullptr,
buf, len, function);
}
}
return NS_OK;
}
nsresult
EvalScript(JSContext* cx,
RootedObject& target_obj,
MutableHandleValue retval,
nsIURI* uri,
bool cache,
RootedScript& script,
RootedFunction& function)
{
if (function) {
script = JS_GetFunctionScript(cx, function);
}
bool ok = false;
if (function) {
ok = JS_CallFunction(cx, target_obj, function, JS::HandleValueArray::empty(),
retval);
} else {
if (JS_IsGlobalObject(target_obj)) {
ok = JS_ExecuteScript(cx, script, retval);
} else {
JS::AutoObjectVector scopeChain(cx);
ok = scopeChain.append(target_obj) &&
JS_ExecuteScript(cx, scopeChain, script, retval);
}
}
if (ok) {
JSAutoCompartment rac(cx, target_obj);
if (!JS_WrapValue(cx, retval))
return NS_ERROR_UNEXPECTED;
}
nsAutoCString cachePath;
JSVersion version = JS_GetVersion(cx);
cachePath.AppendPrintf("jssubloader/%d", version);
PathifyURI(uri, cachePath);
nsCOMPtr<nsIScriptSecurityManager> secman =
do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
if (!secman)
return NS_OK;
nsCOMPtr<nsIPrincipal> principal;
nsresult rv = secman->GetSystemPrincipal(getter_AddRefs(principal));
if (NS_FAILED(rv) || !principal)
return rv;
if (cache && ok && !!script) {
WriteCachedScript(StartupCache::GetSingleton(),
cachePath, cx, principal, script);
}
return NS_OK;
}
class AsyncScriptLoader : public nsIStreamLoaderObserver
{
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_NSISTREAMLOADEROBSERVER
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(AsyncScriptLoader)
AsyncScriptLoader(nsIChannel* aChannel, bool aReuseGlobal,
JSObject* aTargetObj, const nsAString& aCharset,
bool aCache, Promise* aPromise)
: mChannel(aChannel)
, mTargetObj(aTargetObj)
, mPromise(aPromise)
, mCharset(aCharset)
, mReuseGlobal(aReuseGlobal)
, mCache(aCache)
{
// Needed for the cycle collector to manage mTargetObj.
mozilla::HoldJSObjects(this);
}
private:
virtual ~AsyncScriptLoader() {
mozilla::DropJSObjects(this);
}
nsRefPtr<nsIChannel> mChannel;
Heap<JSObject*> mTargetObj;
nsRefPtr<Promise> mPromise;
nsString mCharset;
bool mReuseGlobal;
bool mCache;
};
NS_IMPL_CYCLE_COLLECTION_CLASS(AsyncScriptLoader)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AsyncScriptLoader)
NS_INTERFACE_MAP_ENTRY(nsIStreamLoaderObserver)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(AsyncScriptLoader)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPromise)
tmp->mTargetObj = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(AsyncScriptLoader)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPromise)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(AsyncScriptLoader)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mTargetObj)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(AsyncScriptLoader)
NS_IMPL_CYCLE_COLLECTING_RELEASE(AsyncScriptLoader)
class MOZ_STACK_CLASS AutoRejectPromise
{
public:
AutoRejectPromise(JSContext* cx,
Promise* aPromise,
nsIGlobalObject* aGlobalObject)
: mCx(cx)
, mPromise(aPromise)
, mGlobalObject(aGlobalObject) {}
~AutoRejectPromise() {
if (mPromise) {
JS::Rooted<JS::Value> undefined(mCx, JS::UndefinedValue());
mPromise->MaybeReject(mCx, undefined);
}
}
void ResolvePromise(HandleValue aResolveValue) {
mPromise->MaybeResolve(aResolveValue);
mPromise = nullptr;
}
private:
JSContext* mCx;
nsRefPtr<Promise> mPromise;
nsCOMPtr<nsIGlobalObject> mGlobalObject;
};
NS_IMETHODIMP
AsyncScriptLoader::OnStreamComplete(nsIStreamLoader* aLoader,
nsISupports* aContext,
nsresult aStatus,
uint32_t aLength,
const uint8_t* aBuf)
{
nsCOMPtr<nsIURI> uri;
mChannel->GetURI(getter_AddRefs(uri));
nsCOMPtr<nsIGlobalObject> globalObject = xpc::NativeGlobal(mTargetObj);
AutoEntryScript aes(globalObject, "async loadSubScript");
JSContext* cx = aes.cx();
AutoRejectPromise autoPromise(cx, mPromise, globalObject);
if (NS_FAILED(aStatus)) {
ReportError(cx, "Unable to load script.", uri);
}
// Just notify that we are done with this load.
NS_ENSURE_SUCCESS(aStatus, NS_OK);
if (aLength == 0) {
return ReportError(cx, LOAD_ERROR_NOCONTENT, uri);
}
if (aLength > INT32_MAX) {
return ReportError(cx, LOAD_ERROR_CONTENTTOOBIG, uri);
}
RootedFunction function(cx);
RootedScript script(cx);
nsAutoCString spec;
uri->GetSpec(spec);
RootedObject target_obj(cx, mTargetObj);
nsresult rv = PrepareScript(uri, cx, target_obj, spec.get(),
mCharset,
reinterpret_cast<const char*>(aBuf), aLength,
mReuseGlobal, &script, &function);
if (NS_FAILED(rv)) {
return rv;
}
JS::Rooted<JS::Value> retval(cx);
rv = EvalScript(cx, target_obj, &retval, uri, mCache, script, function);
if (NS_SUCCEEDED(rv)) {
autoPromise.ResolvePromise(retval);
}
return rv;
}
nsresult
mozJSSubScriptLoader::ReadScriptAsync(nsIURI* uri, JSObject* targetObjArg,
const nsAString& charset,
nsIIOService* serv, bool reuseGlobal,
bool cache, MutableHandleValue retval)
{
RootedObject target_obj(nsContentUtils::RootingCx(), targetObjArg);
nsCOMPtr<nsIGlobalObject> globalObject = xpc::NativeGlobal(target_obj);
ErrorResult result;
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.Init(globalObject))) {
return NS_ERROR_UNEXPECTED;
}
nsRefPtr<Promise> promise = Promise::Create(globalObject, result);
if (result.Failed()) {
promise = nullptr;
}
DebugOnly<bool> asJS = ToJSValue(jsapi.cx(), promise, retval);
MOZ_ASSERT(asJS, "Should not fail to convert the promise to a JS value");
// We create a channel and call SetContentType, to avoid expensive MIME type
// lookups (bug 632490).
nsCOMPtr<nsIChannel> channel;
nsresult rv;
rv = NS_NewChannel(getter_AddRefs(channel),
uri,
nsContentUtils::GetSystemPrincipal(),
nsILoadInfo::SEC_NORMAL,
nsIContentPolicy::TYPE_OTHER,
nullptr, // aLoadGroup
nullptr, // aCallbacks
nsIRequest::LOAD_NORMAL,
serv);
if (!NS_SUCCEEDED(rv)) {
return rv;
}
channel->SetContentType(NS_LITERAL_CSTRING("application/javascript"));
nsRefPtr<AsyncScriptLoader> loadObserver =
new AsyncScriptLoader(channel,
reuseGlobal,
target_obj,
charset,
cache,
promise);
nsCOMPtr<nsIStreamLoader> loader;
rv = NS_NewStreamLoader(getter_AddRefs(loader), loadObserver);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIStreamListener> listener = loader.get();
return channel->AsyncOpen(listener, nullptr);
}
nsresult
mozJSSubScriptLoader::ReadScript(nsIURI* uri, JSContext* cx, JSObject* targetObjArg,
const nsAString& charset, const char* uriStr,
nsIIOService* serv, nsIPrincipal* principal,
bool reuseGlobal, JS::MutableHandleScript script,
JS::MutableHandleFunction function)
{
script.set(nullptr);
function.set(nullptr);
RootedObject target_obj(cx, targetObjArg);
// We create a channel and call SetContentType, to avoid expensive MIME type
// lookups (bug 632490).
nsCOMPtr<nsIChannel> chan;
nsCOMPtr<nsIInputStream> instream;
nsresult rv;
rv = NS_NewChannel(getter_AddRefs(chan),
uri,
nsContentUtils::GetSystemPrincipal(),
nsILoadInfo::SEC_NORMAL,
nsIContentPolicy::TYPE_OTHER,
nullptr, // aLoadGroup
nullptr, // aCallbacks
nsIRequest::LOAD_NORMAL,
serv);
if (NS_SUCCEEDED(rv)) {
chan->SetContentType(NS_LITERAL_CSTRING("application/javascript"));
rv = chan->Open(getter_AddRefs(instream));
}
if (NS_FAILED(rv)) {
return ReportError(cx, LOAD_ERROR_NOSTREAM, uri);
}
int64_t len = -1;
rv = chan->GetContentLength(&len);
if (NS_FAILED(rv) || len == -1) {
return ReportError(cx, LOAD_ERROR_NOCONTENT, uri);
}
if (len > INT32_MAX) {
return ReportError(cx, LOAD_ERROR_CONTENTTOOBIG, uri);
}
nsCString buf;
rv = NS_ReadInputStreamToString(instream, buf, len);
NS_ENSURE_SUCCESS(rv, rv);
rv = PrepareScript(uri, cx, target_obj, uriStr, charset,
buf.get(), len,
reuseGlobal,
script, function);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP
mozJSSubScriptLoader::LoadSubScript(const nsAString& url,
HandleValue target,
const nsAString& charset,
JSContext* cx,
MutableHandleValue retval)
{
/*
* Loads a local url and evals it into the current cx
* Synchronous (an async version would be cool too.)
* url: The url to load. Must be local so that it can be loaded
* synchronously.
* target_obj: Optional object to eval the script onto (defaults to context
* global)
* charset: Optional character set to use for reading
* returns: Whatever jsval the script pointed to by the url returns.
* Should ONLY (O N L Y !) be called from JavaScript code.
*/
LoadSubScriptOptions options(cx);
options.charset = charset;
options.target = target.isObject() ? &target.toObject() : nullptr;
return DoLoadSubScriptWithOptions(url, options, cx, retval);
}
NS_IMETHODIMP
mozJSSubScriptLoader::LoadSubScriptWithOptions(const nsAString& url,
HandleValue optionsVal,
JSContext* cx,
MutableHandleValue retval)
{
if (!optionsVal.isObject())
return NS_ERROR_INVALID_ARG;
LoadSubScriptOptions options(cx, &optionsVal.toObject());
if (!options.Parse())
return NS_ERROR_INVALID_ARG;
return DoLoadSubScriptWithOptions(url, options, cx, retval);
}
nsresult
mozJSSubScriptLoader::DoLoadSubScriptWithOptions(const nsAString& url,
LoadSubScriptOptions& options,
JSContext* cx,
MutableHandleValue retval)
{
nsresult rv = NS_OK;
/* set the system principal if it's not here already */
if (!mSystemPrincipal) {
nsCOMPtr<nsIScriptSecurityManager> secman =
do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
if (!secman)
return NS_OK;
rv = secman->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal));
if (NS_FAILED(rv) || !mSystemPrincipal)
return rv;
}
RootedObject targetObj(cx);
mozJSComponentLoader* loader = mozJSComponentLoader::Get();
rv = loader->FindTargetObject(cx, &targetObj);
NS_ENSURE_SUCCESS(rv, rv);
// We base reusingGlobal off of what the loader told us, but we may not
// actually be using that object.
bool reusingGlobal = !JS_IsGlobalObject(targetObj);
if (options.target)
targetObj = options.target;
// Remember an object out of the calling compartment so that we
// can properly wrap the result later.
nsCOMPtr<nsIPrincipal> principal = mSystemPrincipal;
RootedObject result_obj(cx, targetObj);
targetObj = JS_FindCompilationScope(cx, targetObj);
if (!targetObj)
return NS_ERROR_FAILURE;
if (targetObj != result_obj)
principal = GetObjectPrincipal(targetObj);
JSAutoCompartment ac(cx, targetObj);
/* load up the url. From here on, failures are reflected as ``custom''
* js exceptions */
nsCOMPtr<nsIURI> uri;
nsAutoCString uriStr;
nsAutoCString scheme;
// Figure out who's calling us
JS::AutoFilename filename;
if (!JS::DescribeScriptedCaller(cx, &filename)) {
// No scripted frame means we don't know who's calling, bail.
return NS_ERROR_FAILURE;
}
// Suppress caching if we're compiling as content.
StartupCache* cache = (principal == mSystemPrincipal)
? StartupCache::GetSingleton()
: nullptr;
nsCOMPtr<nsIIOService> serv = do_GetService(NS_IOSERVICE_CONTRACTID);
if (!serv) {
return ReportError(cx, LOAD_ERROR_NOSERVICE);
}
// Make sure to explicitly create the URI, since we'll need the
// canonicalized spec.
rv = NS_NewURI(getter_AddRefs(uri), NS_LossyConvertUTF16toASCII(url).get(), nullptr, serv);
if (NS_FAILED(rv)) {
return ReportError(cx, LOAD_ERROR_NOURI);
}
rv = uri->GetSpec(uriStr);
if (NS_FAILED(rv)) {
return ReportError(cx, LOAD_ERROR_NOSPEC);
}
rv = uri->GetScheme(scheme);
if (NS_FAILED(rv)) {
return ReportError(cx, LOAD_ERROR_NOSCHEME, uri);
}
if (!scheme.EqualsLiteral("chrome") && !scheme.EqualsLiteral("app")) {
// This might be a URI to a local file, though!
nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(uri);
nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(innerURI);
if (!fileURL) {
return ReportError(cx, LOAD_ERROR_URI_NOT_LOCAL, uri);
}
// For file URIs prepend the filename with the filename of the
// calling script, and " -> ". See bug 418356.
nsAutoCString tmp(filename.get());
tmp.AppendLiteral(" -> ");
tmp.Append(uriStr);
uriStr = tmp;
}
JSVersion version = JS_GetVersion(cx);
nsAutoCString cachePath;
cachePath.AppendPrintf("jssubloader/%d", version);
PathifyURI(uri, cachePath);
RootedFunction function(cx);
RootedScript script(cx);
if (cache && !options.ignoreCache)
rv = ReadCachedScript(cache, cachePath, cx, mSystemPrincipal, &script);
// If we are doing an async load, trigger it and bail out.
if (!script && options.async) {
return ReadScriptAsync(uri, targetObj, options.charset, serv,
reusingGlobal, !!cache, retval);
}
if (!script) {
rv = ReadScript(uri, cx, targetObj, options.charset,
static_cast<const char*>(uriStr.get()), serv,
principal, reusingGlobal, &script, &function);
} else {
cache = nullptr;
}
if (NS_FAILED(rv) || (!script && !function))
return rv;
return EvalScript(cx, targetObj, retval, uri, !!cache, script, function);
}
/**
* Let us compile scripts from a URI off the main thread.
*/
class ScriptPrecompiler : public nsIStreamLoaderObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMLOADEROBSERVER
ScriptPrecompiler(nsIObserver* aObserver,
nsIPrincipal* aPrincipal,
nsIChannel* aChannel)
: mObserver(aObserver)
, mPrincipal(aPrincipal)
, mChannel(aChannel)
, mScriptBuf(nullptr)
, mScriptLength(0)
{}
static void OffThreadCallback(void* aToken, void* aData);
/* Sends the "done" notification back. Main thread only. */
void SendObserverNotification();
private:
virtual ~ScriptPrecompiler()
{
if (mScriptBuf) {
js_free(mScriptBuf);
}
}
nsRefPtr<nsIObserver> mObserver;
nsRefPtr<nsIPrincipal> mPrincipal;
nsRefPtr<nsIChannel> mChannel;
char16_t* mScriptBuf;
size_t mScriptLength;
};
NS_IMPL_ISUPPORTS(ScriptPrecompiler, nsIStreamLoaderObserver);
class NotifyPrecompilationCompleteRunnable : public nsRunnable
{
public:
NS_DECL_NSIRUNNABLE
explicit NotifyPrecompilationCompleteRunnable(ScriptPrecompiler* aPrecompiler)
: mPrecompiler(aPrecompiler)
, mToken(nullptr)
{}
void SetToken(void* aToken) {
MOZ_ASSERT(aToken && !mToken);
mToken = aToken;
}
protected:
nsRefPtr<ScriptPrecompiler> mPrecompiler;
void* mToken;
};
/* RAII helper class to send observer notifications */
class AutoSendObserverNotification {
public:
explicit AutoSendObserverNotification(ScriptPrecompiler* aPrecompiler)
: mPrecompiler(aPrecompiler)
{}
~AutoSendObserverNotification() {
if (mPrecompiler) {
mPrecompiler->SendObserverNotification();
}
}
void Disarm() {
mPrecompiler = nullptr;
}
private:
ScriptPrecompiler* mPrecompiler;
};
NS_IMETHODIMP
NotifyPrecompilationCompleteRunnable::Run(void)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mPrecompiler);
AutoSendObserverNotification notifier(mPrecompiler);
if (mToken) {
JSRuntime* rt = XPCJSRuntime::Get()->Runtime();
NS_ENSURE_TRUE(rt, NS_ERROR_FAILURE);
JS::FinishOffThreadScript(nullptr, rt, mToken);
}
return NS_OK;
}
NS_IMETHODIMP
ScriptPrecompiler::OnStreamComplete(nsIStreamLoader* aLoader,
nsISupports* aContext,
nsresult aStatus,
uint32_t aLength,
const uint8_t* aString)
{
AutoSendObserverNotification notifier(this);
// Just notify that we are done with this load.
NS_ENSURE_SUCCESS(aStatus, NS_OK);
// Convert data to char16_t* and prepare to call CompileOffThread.
nsAutoString hintCharset;
nsresult rv =
nsScriptLoader::ConvertToUTF16(mChannel, aString, aLength,
hintCharset, nullptr,
mScriptBuf, mScriptLength);
NS_ENSURE_SUCCESS(rv, NS_OK);
// Our goal is to cache persistently the compiled script and to avoid quota
// checks. Since the caching mechanism decide the persistence type based on
// the principal, we create a new global with the app's principal.
// We then enter its compartment to compile with its principal.
AutoSafeJSContext cx;
RootedValue v(cx);
SandboxOptions sandboxOptions;
sandboxOptions.sandboxName.AssignASCII("asm.js precompilation");
sandboxOptions.invisibleToDebugger = true;
sandboxOptions.discardSource = true;
rv = CreateSandboxObject(cx, &v, mPrincipal, sandboxOptions);
NS_ENSURE_SUCCESS(rv, NS_OK);
JSAutoCompartment ac(cx, js::UncheckedUnwrap(&v.toObject()));
JS::CompileOptions options(cx, JSVERSION_DEFAULT);
options.forceAsync = true;
options.installedFile = true;
nsCOMPtr<nsIURI> uri;
mChannel->GetURI(getter_AddRefs(uri));
nsAutoCString spec;
uri->GetSpec(spec);
options.setFile(spec.get());
if (!JS::CanCompileOffThread(cx, options, mScriptLength)) {
NS_WARNING("Can't compile script off thread!");
return NS_OK;
}
nsRefPtr<NotifyPrecompilationCompleteRunnable> runnable =
new NotifyPrecompilationCompleteRunnable(this);
if (!JS::CompileOffThread(cx, options,
mScriptBuf, mScriptLength,
OffThreadCallback,
static_cast<void*>(runnable))) {
NS_WARNING("Failed to compile script off thread!");
return NS_OK;
}
unused << runnable.forget();
notifier.Disarm();
return NS_OK;
}
/* static */
void
ScriptPrecompiler::OffThreadCallback(void* aToken, void* aData)
{
nsRefPtr<NotifyPrecompilationCompleteRunnable> runnable =
dont_AddRef(static_cast<NotifyPrecompilationCompleteRunnable*>(aData));
runnable->SetToken(aToken);
NS_DispatchToMainThread(runnable);
}
void
ScriptPrecompiler::SendObserverNotification()
{
MOZ_ASSERT(mChannel && mObserver);
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIURI> uri;
mChannel->GetURI(getter_AddRefs(uri));
mObserver->Observe(uri, "script-precompiled", nullptr);
}
NS_IMETHODIMP
mozJSSubScriptLoader::PrecompileScript(nsIURI* aURI,
nsIPrincipal* aPrincipal,
nsIObserver* aObserver)
{
nsCOMPtr<nsIChannel> channel;
nsresult rv = NS_NewChannel(getter_AddRefs(channel),
aURI,
nsContentUtils::GetSystemPrincipal(),
nsILoadInfo::SEC_NORMAL,
nsIContentPolicy::TYPE_OTHER);
NS_ENSURE_SUCCESS(rv, rv);
nsRefPtr<ScriptPrecompiler> loadObserver =
new ScriptPrecompiler(aObserver, aPrincipal, channel);
nsCOMPtr<nsIStreamLoader> loader;
rv = NS_NewStreamLoader(getter_AddRefs(loader), loadObserver);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIStreamListener> listener = loader.get();
rv = channel->AsyncOpen(listener, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}