Bug 1910698 - Add a struct to represent JS caller location and more general warning source location. r=smaug,necko-reviewers,anti-tracking-reviewers,dom-storage-reviewers,pbz,kershaw,janv

Use it liberally across the tree. This could be cleaned up even more in the future.

Differential Revision: https://phabricator.services.mozilla.com/D218114
This commit is contained in:
Emilio Cobos Álvarez 2024-08-01 17:12:48 +00:00
Родитель bbe59855a6
Коммит 198c331213
90 изменённых файлов: 666 добавлений и 901 удалений

Просмотреть файл

@ -7,6 +7,7 @@
#include "nsScriptSecurityManager.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/SourceLocation.h"
#include "mozilla/StaticPrefs_extensions.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/StoragePrincipalHelper.h"
@ -542,18 +543,7 @@ bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
}
if (reportViolation) {
JS::AutoFilename scriptFilename;
nsAutoString fileName;
uint32_t lineNum = 0;
JS::ColumnNumberOneOrigin columnNum;
if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum, &columnNum)) {
if (const char* file = scriptFilename.get()) {
CopyUTF8toUTF16(nsDependentCString(file), fileName);
}
} else {
MOZ_ASSERT(!JS_IsExceptionPending(cx));
}
auto caller = JSCallingLocation::Get(cx);
nsAutoJSString scriptSample;
if (aKind == JS::RuntimeCode::JS &&
NS_WARN_IF(!scriptSample.init(cx, aCode))) {
@ -566,8 +556,8 @@ bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
: nsIContentSecurityPolicy::VIOLATION_TYPE_WASM_EVAL;
csp->LogViolationDetails(violationType,
nullptr, // triggering element
cspEventListener, fileName, scriptSample, lineNum,
columnNum.oneOriginValue(), u""_ns, u""_ns);
cspEventListener, caller.FileName(), scriptSample,
caller.mLine, caller.mColumn, u""_ns, u""_ns);
}
return evalOK;

Просмотреть файл

@ -3490,11 +3490,11 @@ static void WarnIfSandboxIneffective(nsIDocShell* aDocShell,
nsCOMPtr<Document> parentDocument = parentDocShell->GetDocument();
nsCOMPtr<nsIURI> iframeUri;
parentChannel->GetURI(getter_AddRefs(iframeUri));
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
"Iframe Sandbox"_ns, parentDocument,
nsContentUtils::eSECURITY_PROPERTIES,
"BothAllowScriptsAndSameOriginPresent",
nsTArray<nsString>(), iframeUri);
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Iframe Sandbox"_ns, parentDocument,
nsContentUtils::eSECURITY_PROPERTIES,
"BothAllowScriptsAndSameOriginPresent", nsTArray<nsString>(),
SourceLocation(iframeUri.get()));
}
}

Просмотреть файл

@ -346,9 +346,7 @@ class EventSourceImpl final : public nsIChannelEventSink,
// be the same as the Event Source owner window.
// These attributes are used for error reporting. Should only be accessed on
// target thread
nsString mScriptFile;
uint32_t mScriptLine;
uint32_t mScriptColumn;
JSCallingLocation mCallingLocation;
uint64_t mInnerWindowID;
private:
@ -389,8 +387,6 @@ EventSourceImpl::EventSourceImpl(EventSource* aEventSource,
mIsMainThread(NS_IsMainThread()),
mIsShutDown(false),
mSharedData(SharedData{aEventSource}, "EventSourceImpl::mSharedData"),
mScriptLine(0),
mScriptColumn(1),
mInnerWindowID(0),
mCookieJarSettings(aCookieJarSettings),
mTargetThread(NS_GetCurrentThread()) {
@ -645,8 +641,7 @@ void EventSourceImpl::Init(nsIGlobalObject* aWindowGlobal,
}
// The conditional here is historical and not necessarily sane.
if (JSContext* cx = nsContentUtils::GetCurrentJSContext()) {
nsJSUtils::GetCallingLocation(cx, mScriptFile, &mScriptLine,
&mScriptColumn);
mCallingLocation = JSCallingLocation::Get();
mInnerWindowID = nsJSUtils::GetCurrentlyRunningCodeInnerWindowID(cx);
}
@ -1296,9 +1291,10 @@ nsresult EventSourceImpl::PrintErrorOnConsole(
}
NS_ENSURE_SUCCESS(rv, rv);
rv = errObj->InitWithWindowID(message, mScriptFile, u""_ns, mScriptLine,
mScriptColumn, nsIScriptError::errorFlag,
"Event Source", mInnerWindowID);
rv = errObj->InitWithWindowID(
message, NS_ConvertUTF8toUTF16(mCallingLocation.FileName()), u""_ns,
mCallingLocation.mLine, mCallingLocation.mColumn,
nsIScriptError::errorFlag, "Event Source", mInnerWindowID);
NS_ENSURE_SUCCESS(rv, rv);
// print the error message directly to the JS console

Просмотреть файл

@ -0,0 +1,55 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "mozilla/SourceLocation.h"
#include "nsContentUtils.h"
#include "jsapi.h"
namespace mozilla {
SourceLocation::SourceLocation() = default;
SourceLocation::~SourceLocation() = default;
SourceLocation::SourceLocation(nsCString&& aResource, uint32_t aLine,
uint32_t aCol, nsCString&& aSourceLine)
: mResource(std::move(aResource)),
mLine(aLine),
mColumn(aCol),
mSourceLine(std::move(aSourceLine)) {}
SourceLocation::SourceLocation(nsCOMPtr<nsIURI>&& aResource, uint32_t aLine,
uint32_t aCol, nsCString&& aSourceLine)
: mResource(std::move(aResource)),
mLine(aLine),
mColumn(aCol),
mSourceLine(std::move(aSourceLine)) {}
JSCallingLocation JSCallingLocation::Get() {
return Get(nsContentUtils::GetCurrentJSContext());
}
JSCallingLocation JSCallingLocation::Get(JSContext* aCx) {
JSCallingLocation result;
if (!aCx) {
return result;
}
JS::AutoFilename filename;
uint32_t line;
JS::ColumnNumberOneOrigin column;
if (!JS::DescribeScriptedCaller(aCx, &filename, &line, &column)) {
return result;
}
nsCString file;
if (!file.Assign(filename.get(), fallible)) {
return result;
}
result.mResource = AsVariant(std::move(file));
result.mLine = line;
result.mColumn = column.oneOriginValue();
return result;
}
} // namespace mozilla

49
dom/base/SourceLocation.h Normal file
Просмотреть файл

@ -0,0 +1,49 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
#ifndef mozilla_SourceLocation_h
#define mozilla_SourceLocation_h
#include "nsString.h"
#include "mozilla/Variant.h"
#include "nsCOMPtr.h"
struct JSContext;
class nsIURI;
namespace mozilla {
struct SourceLocation {
mozilla::Variant<nsCString, nsCOMPtr<nsIURI>> mResource{VoidCString()};
uint32_t mLine = 0;
uint32_t mColumn = 1;
nsCString mSourceLine;
SourceLocation();
explicit SourceLocation(nsCString&&, uint32_t aLine = 0, uint32_t aCol = 1,
nsCString&& aSourceLine = {});
explicit SourceLocation(nsCOMPtr<nsIURI>&&, uint32_t aLine = 0,
uint32_t aCol = 1, nsCString&& aSourceLine = {});
~SourceLocation();
bool IsEmpty() const {
return mResource.is<nsCString>() ? mResource.as<nsCString>().IsEmpty()
: !mResource.as<nsCOMPtr<nsIURI>>();
}
explicit operator bool() const { return !IsEmpty(); }
};
struct JSCallingLocation : SourceLocation {
const nsCString& FileName() const { return mResource.as<nsCString>(); }
static JSCallingLocation Get();
static JSCallingLocation Get(JSContext*);
};
} // namespace mozilla
#endif

Просмотреть файл

@ -8,7 +8,6 @@
#include "mozilla/Assertions.h"
#include "mozilla/HoldDropJSObjects.h"
#include "nsJSUtils.h"
namespace mozilla::dom {
@ -16,22 +15,12 @@ namespace mozilla::dom {
// TimeoutHandler
//-----------------------------------------------------------------------------
TimeoutHandler::TimeoutHandler(JSContext* aCx) : TimeoutHandler() {
nsJSUtils::GetCallingLocation(aCx, mFileName, &mLineNo, &mColumn);
}
bool TimeoutHandler::Call(const char* /* unused */) { return false; }
void TimeoutHandler::GetLocation(const char** aFileName, uint32_t* aLineNo,
uint32_t* aColumn) {
*aFileName = mFileName.get();
*aLineNo = mLineNo;
*aColumn = mColumn;
}
void TimeoutHandler::GetDescription(nsACString& aOutString) {
aOutString.AppendPrintf("<generic handler> (%s:%d:%d)", mFileName.get(),
mLineNo, mColumn);
aOutString.AppendPrintf("<generic handler> (%s:%d:%d)",
mCaller.FileName().get(), mCaller.mLine,
mCaller.mColumn);
}
//-----------------------------------------------------------------------------
@ -53,11 +42,11 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(ScriptTimeoutHandler)
if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
nsAutoCString name("ScriptTimeoutHandler");
name.AppendLiteral(" [");
name.Append(tmp->mFileName);
name.Append(tmp->mCaller.FileName());
name.Append(':');
name.AppendInt(tmp->mLineNo);
name.AppendInt(tmp->mCaller.mLine);
name.Append(':');
name.AppendInt(tmp->mColumn);
name.AppendInt(tmp->mCaller.mColumn);
name.Append(']');
cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name.get());
} else {
@ -82,12 +71,13 @@ void ScriptTimeoutHandler::GetDescription(nsACString& aOutString) {
if (mExpr.Length() > 15) {
aOutString.AppendPrintf(
"<string handler (truncated): \"%s...\"> (%s:%d:%d)",
NS_ConvertUTF16toUTF8(Substring(mExpr, 0, 13)).get(), mFileName.get(),
mLineNo, mColumn);
NS_ConvertUTF16toUTF8(Substring(mExpr, 0, 13)).get(),
mCaller.FileName().get(), mCaller.mLine, mCaller.mColumn);
} else {
aOutString.AppendPrintf("<string handler: \"%s\"> (%s:%d:%d)",
NS_ConvertUTF16toUTF8(mExpr).get(), mFileName.get(),
mLineNo, mColumn);
NS_ConvertUTF16toUTF8(mExpr).get(),
mCaller.FileName().get(), mCaller.mLine,
mCaller.mColumn);
}
}

Просмотреть файл

@ -13,6 +13,7 @@
#include "nsCycleCollectionParticipant.h"
#include "nsString.h"
#include "mozilla/Attributes.h"
#include "mozilla/SourceLocation.h"
#include "mozilla/dom/FunctionBinding.h"
namespace mozilla::dom {
@ -23,11 +24,6 @@ namespace mozilla::dom {
class TimeoutHandler : public nsISupports {
public:
MOZ_CAN_RUN_SCRIPT virtual bool Call(const char* /* unused */);
// Get the location of the script.
// Note: The memory pointed to by aFileName is owned by the
// nsITimeoutHandler and should not be freed by the caller.
virtual void GetLocation(const char** aFileName, uint32_t* aLineNo,
uint32_t* aColumn);
// Append a UTF-8 string to aOutString that describes the callback function,
// for use in logging or profiler markers.
// The string contains the function name and its source location, if
@ -37,16 +33,15 @@ class TimeoutHandler : public nsISupports {
virtual void MarkForCC() {}
protected:
TimeoutHandler() : mFileName(""), mLineNo(0), mColumn(1) {}
explicit TimeoutHandler(JSContext* aCx);
TimeoutHandler() = default;
explicit TimeoutHandler(JSContext* aCx)
: mCaller(JSCallingLocation::Get(aCx)) {}
virtual ~TimeoutHandler() = default;
// filename, line number and JS language version string of the
// caller of setTimeout()
nsCString mFileName;
uint32_t mLineNo;
uint32_t mColumn;
const JSCallingLocation mCaller;
private:
TimeoutHandler(const TimeoutHandler&) = delete;

Просмотреть файл

@ -137,6 +137,7 @@ EXPORTS.mozilla += [
"ScriptableContentIterator.h",
"ScrollingMetrics.h",
"SelectionChangeEventDispatcher.h",
"SourceLocation.h",
"TextInputProcessor.h",
"UseCounter.h",
]
@ -461,6 +462,7 @@ UNIFIED_SOURCES += [
"SelectionChangeEventDispatcher.cpp",
"SerializedStackHolder.cpp",
"ShadowRoot.cpp",
"SourceLocation.cpp",
"StaticRange.cpp",
"StorageAccessPermissionRequest.cpp",
"StructuredCloneBlob.cpp",

Просмотреть файл

@ -4542,8 +4542,7 @@ void nsContentUtils::LogSimpleConsoleError(const nsAString& aErrorText,
nsresult nsContentUtils::ReportToConsole(
uint32_t aErrorFlags, const nsACString& aCategory,
const Document* aDocument, PropertiesFile aFile, const char* aMessageName,
const nsTArray<nsString>& aParams, nsIURI* aURI,
const nsString& aSourceLine, uint32_t aLineNumber, uint32_t aColumnNumber) {
const nsTArray<nsString>& aParams, const SourceLocation& aLoc) {
nsresult rv;
nsAutoString errorText;
if (!aParams.IsEmpty()) {
@ -4552,10 +4551,8 @@ nsresult nsContentUtils::ReportToConsole(
rv = GetLocalizedString(aFile, aMessageName, errorText);
}
NS_ENSURE_SUCCESS(rv, rv);
return ReportToConsoleNonLocalized(errorText, aErrorFlags, aCategory,
aDocument, aURI, aSourceLine, aLineNumber,
aColumnNumber);
aDocument, aLoc);
}
/* static */
@ -4567,55 +4564,44 @@ void nsContentUtils::ReportEmptyGetElementByIdArg(const Document* aDoc) {
/* static */
nsresult nsContentUtils::ReportToConsoleNonLocalized(
const nsAString& aErrorText, uint32_t aErrorFlags,
const nsACString& aCategory, const Document* aDocument, nsIURI* aURI,
const nsString& aSourceLine, uint32_t aLineNumber, uint32_t aColumnNumber,
MissingErrorLocationMode aLocationMode) {
uint64_t innerWindowID = 0;
if (aDocument) {
if (!aURI) {
aURI = aDocument->GetDocumentURI();
}
innerWindowID = aDocument->InnerWindowID();
const nsACString& aCategory, const Document* aDocument,
const SourceLocation& aLoc) {
uint64_t innerWindowID = aDocument ? aDocument->InnerWindowID() : 0;
if (aLoc || !aDocument || !aDocument->GetDocumentURI()) {
return ReportToConsoleByWindowID(aErrorText, aErrorFlags, aCategory,
innerWindowID, aLoc);
}
return ReportToConsoleByWindowID(aErrorText, aErrorFlags, aCategory,
innerWindowID, aURI, aSourceLine,
aLineNumber, aColumnNumber, aLocationMode);
innerWindowID,
SourceLocation(aDocument->GetDocumentURI()));
}
/* static */
nsresult nsContentUtils::ReportToConsoleByWindowID(
const nsAString& aErrorText, uint32_t aErrorFlags,
const nsACString& aCategory, uint64_t aInnerWindowID, nsIURI* aURI,
const nsString& aSourceLine, uint32_t aLineNumber, uint32_t aColumnNumber,
MissingErrorLocationMode aLocationMode) {
const nsACString& aCategory, uint64_t aInnerWindowID,
const SourceLocation& aLocation) {
nsresult rv;
if (!sConsoleService) { // only need to bother null-checking here
rv = CallGetService(NS_CONSOLESERVICE_CONTRACTID, &sConsoleService);
NS_ENSURE_SUCCESS(rv, rv);
}
nsAutoString spec;
if (!aLineNumber && aLocationMode == eUSE_CALLING_LOCATION) {
JSContext* cx = GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, spec, &aLineNumber, &aColumnNumber);
}
}
nsCOMPtr<nsIScriptError> errorObject =
do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
if (!spec.IsEmpty()) {
rv = errorObject->InitWithWindowID(aErrorText,
spec, // file name
aSourceLine, aLineNumber, aColumnNumber,
aErrorFlags, aCategory, aInnerWindowID);
NS_ConvertUTF8toUTF16 sourceLine(aLocation.mSourceLine);
if (aLocation.mResource.is<nsCOMPtr<nsIURI>>()) {
nsIURI* uri = aLocation.mResource.as<nsCOMPtr<nsIURI>>();
rv = errorObject->InitWithSourceURI(aErrorText, uri, sourceLine,
aLocation.mLine, aLocation.mColumn,
aErrorFlags, aCategory, aInnerWindowID);
} else {
rv = errorObject->InitWithSourceURI(aErrorText, aURI, aSourceLine,
aLineNumber, aColumnNumber, aErrorFlags,
aCategory, aInnerWindowID);
rv = errorObject->InitWithWindowID(
aErrorText, NS_ConvertUTF8toUTF16(aLocation.mResource.as<nsCString>()),
sourceLine, aLocation.mLine, aLocation.mColumn, aErrorFlags, aCategory,
aInnerWindowID);
}
NS_ENSURE_SUCCESS(rv, rv);

Просмотреть файл

@ -31,6 +31,7 @@
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/SourceLocation.h"
#include "mozilla/CORSMode.h"
#include "mozilla/CallState.h"
#include "mozilla/Maybe.h"
@ -1274,29 +1275,13 @@ class nsContentUtils {
* @param aErrorFlags See nsIScriptError.
* @param aCategory Name of module reporting error.
* @param aDocument Reference to the document which triggered the message.
* @param [aURI=nullptr] (Optional) URI of resource containing error.
* @param [aSourceLine=u""_ns] (Optional) The text of the line that
contains the error (may be empty).
* @param [aLineNumber=0] (Optional) Line number within resource
containing error.
* @param [aColumnNumber=0] (Optional) Column number within resource
containing error.
If aURI is null, then aDocument->GetDocumentURI() is used.
* @param [aLocationMode] (Optional) Specifies the behavior if
error location information is omitted.
* @param aLocation message location. Pass the empty location to omit it.
*/
enum MissingErrorLocationMode {
// Don't show location information in the error console.
eOMIT_LOCATION,
// Get location information from the currently executing script.
eUSE_CALLING_LOCATION
};
static nsresult ReportToConsoleNonLocalized(
const nsAString& aErrorText, uint32_t aErrorFlags,
const nsACString& aCategory, const Document* aDocument,
nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
const mozilla::SourceLocation& aLocation =
mozilla::JSCallingLocation::Get());
/**
* Report a non-localized error message to the error console base on the
@ -1306,23 +1291,13 @@ class nsContentUtils {
* @param aCategory Name of module reporting error.
* @param [aInnerWindowID] Inner window ID for document which triggered the
* message.
* @param [aURI=nullptr] (Optional) URI of resource containing error.
* @param [aSourceLine=u""_ns] (Optional) The text of the line that
contains the error (may be empty).
* @param [aLineNumber=0] (Optional) Line number within resource
containing error.
* @param [aColumnNumber=1] (Optional) Column number within resource
containing error.
If aURI is null, then aDocument->GetDocumentURI() is used.
* @param [aLocationMode] (Optional) Specifies the behavior if
error location information is omitted.
* @param aLocation message location. Pass the empty location to omit it.
*/
static nsresult ReportToConsoleByWindowID(
const nsAString& aErrorText, uint32_t aErrorFlags,
const nsACString& aCategory, uint64_t aInnerWindowID,
nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
uint32_t aLineNumber = 0, uint32_t aColumnNumber = 1,
MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
const mozilla::SourceLocation& aLocation =
mozilla::JSCallingLocation::Get());
/**
* Report a localized error message to the error console.
@ -1333,14 +1308,7 @@ class nsContentUtils {
* @param aMessageName Name of localized message.
* @param [aParams=empty-array] (Optional) Parameters to be substituted into
localized message.
* @param [aURI=nullptr] (Optional) URI of resource containing error.
* @param [aSourceLine=u""_ns] (Optional) The text of the line that
contains the error (may be empty).
* @param [aLineNumber=0] (Optional) Line number within resource
containing error.
* @param [aColumnNumber=0] (Optional) Column number within resource
containing error.
If aURI is null, then aDocument->GetDocumentURI() is used.
* @param aLocation message location. Pass the empty location to omit it.
*/
enum PropertiesFile {
eCSS_PROPERTIES,
@ -1364,8 +1332,8 @@ class nsContentUtils {
uint32_t aErrorFlags, const nsACString& aCategory,
const Document* aDocument, PropertiesFile aFile, const char* aMessageName,
const nsTArray<nsString>& aParams = nsTArray<nsString>(),
nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0);
const mozilla::SourceLocation& aLocation =
mozilla::JSCallingLocation::Get());
static void ReportEmptyGetElementByIdArg(const Document* aDoc);

Просмотреть файл

@ -1478,7 +1478,7 @@ void LogWarningFullscreenWindowRaise(Element* aElement) {
Unused << nsContentUtils::ReportToConsoleByWindowID(
localizedMsg, nsIScriptError::warningFlag, "DOM"_ns,
windowGlobalParent->InnerWindowId(),
windowGlobalParent->GetDocumentURI());
SourceLocation(windowGlobalParent->GetDocumentURI()));
}
// Ensure that when an embedded popup with a noautofocus attribute

Просмотреть файл

@ -455,17 +455,15 @@ bool nsFrameMessageManager::GetParamsForMessage(JSContext* aCx,
nsCOMPtr<nsIConsoleService> console(
do_GetService(NS_CONSOLESERVICE_CONTRACTID));
if (console) {
nsAutoString filename;
uint32_t lineno = 0, column = 1;
nsJSUtils::GetCallingLocation(aCx, filename, &lineno, &column);
auto location = JSCallingLocation::Get(aCx);
nsCOMPtr<nsIScriptError> error(
do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
error->Init(
u"Sending message that cannot be cloned. Are "
"you trying to send an XPCOM object?"_ns,
filename, u""_ns, lineno, column, nsIScriptError::warningFlag,
"chrome javascript"_ns, false /* from private window */,
true /* from chrome context */);
NS_ConvertUTF8toUTF16(location.FileName()), u""_ns, location.mLine,
location.mColumn, nsIScriptError::warningFlag, "chrome javascript"_ns,
false /* from private window */, true /* from chrome context */);
console->LogMessage(error);
}

Просмотреть файл

@ -6063,7 +6063,7 @@ bool WindowScriptTimeoutHandler::Call(const char* aExecutionReason) {
nsAutoMicroTask mt;
AutoEntryScript aes(mGlobal, aExecutionReason, true);
JS::CompileOptions options(aes.cx());
options.setFileAndLine(mFileName.get(), mLineNo);
options.setFileAndLine(mCaller.FileName().get(), mCaller.mLine);
options.setNoScriptRval(true);
options.setIntroductionType("domTimer");
JS::Rooted<JSObject*> global(aes.cx(), mGlobal->GetGlobalJSObject());

Просмотреть файл

@ -48,34 +48,6 @@
using namespace mozilla;
using namespace mozilla::dom;
bool nsJSUtils::GetCallingLocation(JSContext* aContext, nsACString& aFilename,
uint32_t* aLineno, uint32_t* aColumn) {
JS::AutoFilename filename;
JS::ColumnNumberOneOrigin column;
if (!JS::DescribeScriptedCaller(aContext, &filename, aLineno, &column)) {
return false;
}
if (aColumn) {
*aColumn = column.oneOriginValue();
}
return aFilename.Assign(filename.get(), fallible);
}
bool nsJSUtils::GetCallingLocation(JSContext* aContext, nsAString& aFilename,
uint32_t* aLineno, uint32_t* aColumn) {
JS::AutoFilename filename;
JS::ColumnNumberOneOrigin column;
if (!JS::DescribeScriptedCaller(aContext, &filename, aLineno, &column)) {
return false;
}
if (aColumn) {
*aColumn = column.oneOriginValue();
}
return aFilename.Assign(NS_ConvertUTF8toUTF16(filename.get()), fallible);
}
uint64_t nsJSUtils::GetCurrentlyRunningCodeInnerWindowID(JSContext* aContext) {
if (!aContext) return 0;

Просмотреть файл

@ -19,7 +19,6 @@
#include "jsapi.h"
#include "js/CompileOptions.h"
#include "js/Conversions.h"
#include "js/SourceText.h"
#include "js/String.h" // JS::{,Lossy}CopyLinearStringChars, JS::CopyStringChars, JS::Get{,Linear}StringLength, JS::MaxStringLength, JS::StringHasLatin1Chars
#include "js/Utility.h" // JS::FreePolicy
#include "nsString.h"
@ -41,13 +40,6 @@ class Element;
class nsJSUtils {
public:
static bool GetCallingLocation(JSContext* aContext, nsACString& aFilename,
uint32_t* aLineno = nullptr,
uint32_t* aColumn = nullptr);
static bool GetCallingLocation(JSContext* aContext, nsAString& aFilename,
uint32_t* aLineno = nullptr,
uint32_t* aColumn = nullptr);
/**
* Retrieve the inner window ID based on the given JSContext.
*

Просмотреть файл

@ -4048,7 +4048,7 @@ static const char* kDeprecatedOperations[] = {
void ReportDeprecation(nsIGlobalObject* aGlobal, nsIURI* aURI,
DeprecatedOperations aOperation,
const nsAString& aFileName,
const nsACString& aFileName,
const Nullable<uint32_t>& aLineNumber,
const Nullable<uint32_t>& aColumnNumber) {
MOZ_ASSERT(aURI);
@ -4156,21 +4156,18 @@ void MaybeReportDeprecation(const GlobalObject& aGlobal,
return;
}
nsAutoString fileName;
auto location = JSCallingLocation::Get(aGlobal.Context());
Nullable<uint32_t> lineNumber;
Nullable<uint32_t> columnNumber;
uint32_t line = 0;
uint32_t column = 1;
if (nsJSUtils::GetCallingLocation(aGlobal.Context(), fileName, &line,
&column)) {
lineNumber.SetValue(line);
columnNumber.SetValue(column);
if (location) {
lineNumber.SetValue(location.mLine);
columnNumber.SetValue(location.mColumn);
}
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
MOZ_ASSERT(global);
ReportDeprecation(global, uri, aOperation, fileName, lineNumber,
ReportDeprecation(global, uri, aOperation, location.FileName(), lineNumber,
columnNumber);
}

Просмотреть файл

@ -16,7 +16,7 @@ dictionary ConsoleEvent {
DOMString consoleID = "";
DOMString addonId = "";
DOMString level = "";
DOMString filename = "";
UTF8String filename = "";
// Unique identifier within the process for the script source this event is
// associated with, or zero.
unsigned long sourceId = 0;
@ -52,7 +52,7 @@ dictionary ConsoleProfileEvent {
// This dictionary is used to manage stack trace data.
[GenerateConversionToJS]
dictionary ConsoleStackEntry {
DOMString filename = "";
UTF8String filename = "";
// Unique identifier within the process for the script source this entry is
// associated with, or zero.
unsigned long sourceId = 0;
@ -173,7 +173,8 @@ enum ConsoleLevel { "log", "warning", "error" };
partial interface ConsoleInstance {
[ChromeOnly]
undefined reportForServiceWorkerScope(DOMString scope, DOMString message,
DOMString filename, unsigned long lineNumber,
UTF8String filename,
unsigned long lineNumber,
unsigned long columnNumber,
ConsoleLevel level);
};

Просмотреть файл

@ -682,7 +682,7 @@ class ConsoleCallDataWorkerRunnable final : public ConsoleWorkerRunnable {
frame = *mCallData->mTopStackFrame;
}
nsString id = frame.mFilename;
nsCString id = frame.mFilename;
nsString innerID;
if (aWorkerPrivate->IsSharedWorker()) {
innerID = u"SharedWorker"_ns;
@ -690,12 +690,12 @@ class ConsoleCallDataWorkerRunnable final : public ConsoleWorkerRunnable {
innerID = u"ServiceWorker"_ns;
// Use scope as ID so the webconsole can decide if the message should
// show up per tab
CopyASCIItoUTF16(aWorkerPrivate->ServiceWorkerScope(), id);
id = aWorkerPrivate->ServiceWorkerScope();
} else {
innerID = u"Worker"_ns;
}
mCallData->SetIDs(id, innerID);
mCallData->SetIDs(NS_ConvertUTF8toUTF16(id), innerID);
}
mClonedData.mGlobal = aGlobal;
@ -1223,7 +1223,9 @@ void StackFrameToStackEntry(JSContext* aCx, nsIStackFrame* aStackFrame,
ConsoleStackEntry& aStackEntry) {
MOZ_ASSERT(aStackFrame);
aStackFrame->GetFilename(aCx, aStackEntry.mFilename);
nsAutoString filename;
aStackFrame->GetFilename(aCx, filename);
CopyUTF16toUTF8(filename, aStackEntry.mFilename);
aStackEntry.mSourceId = aStackFrame->GetSourceId(aCx);
aStackEntry.mLineNumber = aStackFrame->GetLineNumber(aCx);
@ -1412,12 +1414,12 @@ void Console::MethodInternal(JSContext* aCx, MethodName aMethodName,
} else if (!mPassedInnerID.IsEmpty()) {
callData->SetIDs(u"jsm"_ns, mPassedInnerID);
} else {
nsAutoString filename;
nsAutoCString filename;
if (callData->mTopStackFrame.isSome()) {
filename = callData->mTopStackFrame->mFilename;
}
callData->SetIDs(u"jsm"_ns, filename);
callData->SetIDs(u"jsm"_ns, NS_ConvertUTF8toUTF16(filename));
}
GetOrCreateMainThreadData()->ProcessCallData(aCx, callData, aData);
@ -1604,7 +1606,7 @@ bool Console::PopulateConsoleNotificationInTheTargetScope(
do_QueryInterface(filenameURI);
nsAutoCString spec;
if (safeURI && NS_SUCCEEDED(safeURI->GetSensitiveInfoHiddenSpec(spec))) {
CopyUTF8toUTF16(spec, event.mFilename);
event.mFilename = spec;
}
}

Просмотреть файл

@ -268,7 +268,7 @@ bool ConsoleInstance::ShouldLog(ConsoleLogLevel aLevel) {
void ConsoleInstance::ReportForServiceWorkerScope(const nsAString& aScope,
const nsAString& aMessage,
const nsAString& aFilename,
const nsACString& aFilename,
uint32_t aLineNumber,
uint32_t aColumnNumber,
ConsoleLevel aLevel) {

Просмотреть файл

@ -102,7 +102,7 @@ class ConsoleInstance final : public nsISupports, public nsWrapperCache {
// For testing only.
void ReportForServiceWorkerScope(const nsAString& aScope,
const nsAString& aMessage,
const nsAString& aFilename,
const nsACString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber,
ConsoleLevel aLevel);

Просмотреть файл

@ -79,9 +79,11 @@ void ConsoleReportCollector::FlushReportsToConsole(uint64_t aInnerWindowID,
}
}
SourceLocation loc{std::move(uri), report.mLineNumber,
report.mColumnNumber};
nsContentUtils::ReportToConsoleByWindowID(
errorText, report.mErrorFlags, report.mCategory, aInnerWindowID, uri,
u""_ns, report.mLineNumber, report.mColumnNumber);
errorText, report.mErrorFlags, report.mCategory, aInnerWindowID, loc);
}
}
@ -129,9 +131,8 @@ void ConsoleReportCollector::FlushReportsToConsoleForServiceWorkerScope(
}
ConsoleUtils::ReportForServiceWorkerScope(
NS_ConvertUTF8toUTF16(aScope), errorText,
NS_ConvertUTF8toUTF16(report.mSourceFileURI), report.mLineNumber,
report.mColumnNumber, level);
NS_ConvertUTF8toUTF16(aScope), errorText, report.mSourceFileURI,
report.mLineNumber, report.mColumnNumber, level);
}
}

Просмотреть файл

@ -45,7 +45,7 @@ ConsoleUtils::~ConsoleUtils() = default;
/* static */
void ConsoleUtils::ReportForServiceWorkerScope(const nsAString& aScope,
const nsAString& aMessage,
const nsAString& aFilename,
const nsACString& aFilename,
uint32_t aLineNumber,
uint32_t aColumnNumber,
Level aLevel) {
@ -62,7 +62,7 @@ void ConsoleUtils::ReportForServiceWorkerScope(const nsAString& aScope,
void ConsoleUtils::ReportForServiceWorkerScopeInternal(
const nsAString& aScope, const nsAString& aMessage,
const nsAString& aFilename, uint32_t aLineNumber, uint32_t aColumnNumber,
const nsACString& aFilename, uint32_t aLineNumber, uint32_t aColumnNumber,
Level aLevel) {
MOZ_ASSERT(NS_IsMainThread());

Просмотреть файл

@ -26,7 +26,7 @@ class ConsoleUtils final {
// Main-thread only, reports a console message from a ServiceWorker.
static void ReportForServiceWorkerScope(const nsAString& aScope,
const nsAString& aMessage,
const nsAString& aFilename,
const nsACString& aFilename,
uint32_t aLineNumber,
uint32_t aColumnNumber, Level aLevel);
@ -40,7 +40,7 @@ class ConsoleUtils final {
void ReportForServiceWorkerScopeInternal(const nsAString& aScope,
const nsAString& aMessage,
const nsAString& aFilename,
const nsACString& aFilename,
uint32_t aLineNumber,
uint32_t aColumnNumber,
Level aLevel);

Просмотреть файл

@ -667,10 +667,9 @@ void KeyEventHandler::ReportKeyConflict(const char16_t* aKey,
params.AppendElement(aKey);
params.AppendElement(aModifiers);
params.AppendElement(id);
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
"Key dom::Event Handler"_ns, doc,
nsContentUtils::eDOM_PROPERTIES, aMessageName,
params, nullptr, u""_ns, 0);
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Key dom::Event Handler"_ns, doc,
nsContentUtils::eDOM_PROPERTIES, aMessageName, params);
}
bool KeyEventHandler::ModifiersMatchMask(

Просмотреть файл

@ -232,7 +232,7 @@ void HTMLFormElement::ReportInvalidUnfocusableElements(
nsContentUtils::ReportToConsole(
nsIScriptError::errorFlag, "DOM"_ns, element->GetOwnerDocument(),
nsContentUtils::eDOM_PROPERTIES, messageName.get(), params,
element->GetBaseURI());
SourceLocation(element->GetBaseURI()));
}
}
}
@ -1659,7 +1659,7 @@ nsresult HTMLFormElement::GetActionURL(nsIURI** aActionURL,
CSP_LogLocalizedStr(
"upgradeInsecureRequest", params,
u""_ns, // aSourceFile
""_ns, // aSourceFile
u""_ns, // aScriptSample
0, // aLineNumber
1, // aColumnNumber

Просмотреть файл

@ -185,6 +185,8 @@ void HTMLScriptElement::FreezeExecutionAttrs(const Document* aOwnerDoc) {
// because it will return the base URL when the attr value is "".
nsAutoString src;
if (GetAttr(nsGkAtoms::src, src)) {
SourceLocation loc{OwnerDoc()->GetDocumentURI(), GetScriptLineNumber(),
GetScriptColumnNumber().oneOriginValue()};
// Empty src should be treated as invalid URL.
if (!src.IsEmpty()) {
nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(mUri), src,
@ -193,20 +195,16 @@ void HTMLScriptElement::FreezeExecutionAttrs(const Document* aOwnerDoc) {
if (!mUri) {
AutoTArray<nsString, 2> params = {u"src"_ns, src};
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "HTML"_ns, OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES, "ScriptSourceInvalidUri", params,
nullptr, u""_ns, GetScriptLineNumber(),
GetScriptColumnNumber().oneOriginValue());
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "HTML"_ns,
OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES,
"ScriptSourceInvalidUri", params, loc);
}
} else {
AutoTArray<nsString, 1> params = {u"src"_ns};
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "HTML"_ns, OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES, "ScriptSourceEmpty", params, nullptr,
u""_ns, GetScriptLineNumber(),
GetScriptColumnNumber().oneOriginValue());
nsContentUtils::eDOM_PROPERTIES, "ScriptSourceEmpty", params, loc);
}
// At this point mUri will be null for invalid URLs.

Просмотреть файл

@ -732,12 +732,7 @@ void IDBDatabase::AbortTransactions(bool aShouldWarn) {
for (IDBTransaction* transaction : transactionsThatNeedWarning) {
MOZ_ASSERT(transaction);
nsString filename;
uint32_t lineNo, column;
transaction->GetCallerLocation(filename, &lineNo, &column);
LogWarning(kWarningMessage, filename, lineNo, column);
LogWarning(kWarningMessage, transaction->GetCallerLocation());
}
}
@ -879,15 +874,13 @@ void IDBDatabase::NoteInactiveTransactionDelayed() {
}
void IDBDatabase::LogWarning(const char* aMessageName,
const nsAString& aFilename, uint32_t aLineNumber,
uint32_t aColumnNumber) {
const JSCallingLocation& aLoc) {
AssertIsOnOwningThread();
MOZ_ASSERT(aMessageName);
ScriptErrorHelper::DumpLocalizedMessage(
nsDependentCString(aMessageName), aFilename, aLineNumber, aColumnNumber,
nsIScriptError::warningFlag, mFactory->IsChrome(),
mFactory->InnerWindowID());
nsDependentCString(aMessageName), aLoc, nsIScriptError::warningFlag,
mFactory->IsChrome(), mFactory->InnerWindowID());
}
NS_IMPL_ADDREF_INHERITED(IDBDatabase, DOMEventTargetHelper)

Просмотреть файл

@ -23,6 +23,7 @@ class nsIGlobalObject;
namespace mozilla {
struct JSCallingLocation;
class ErrorResult;
class EventChainPostVisitor;
@ -229,8 +230,7 @@ class IDBDatabase final : public DOMEventTargetHelper {
void NoteInactiveTransactionDelayed();
void LogWarning(const char* aMessageName, const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber);
void LogWarning(const char* aMessageName, const JSCallingLocation&);
// Only accessed by IDBObjectStore.
nsresult RenameObjectStore(int64_t aObjectStoreId, const nsAString& aName);

Просмотреть файл

@ -44,8 +44,6 @@ using namespace mozilla::ipc;
IDBRequest::IDBRequest(IDBDatabase* aDatabase)
: DOMEventTargetHelper(aDatabase),
mLoggingSerialNumber(0),
mLineNo(0),
mColumn(0),
mHaveResultOrErrorCode(false) {
MOZ_ASSERT(aDatabase);
aDatabase->AssertIsOnOwningThread();
@ -56,8 +54,6 @@ IDBRequest::IDBRequest(IDBDatabase* aDatabase)
IDBRequest::IDBRequest(nsIGlobalObject* aGlobal)
: DOMEventTargetHelper(aGlobal),
mLoggingSerialNumber(0),
mLineNo(0),
mColumn(0),
mHaveResultOrErrorCode(false) {
InitMembers();
}
@ -73,8 +69,6 @@ void IDBRequest::InitMembers() {
mResultVal.setUndefined();
mLoggingSerialNumber = NextSerialNumber();
mErrorCode = NS_OK;
mLineNo = 0;
mColumn = 0;
mHaveResultOrErrorCode = false;
}
@ -87,7 +81,7 @@ MovingNotNull<RefPtr<IDBRequest>> IDBRequest::Create(
aDatabase->AssertIsOnOwningThread();
RefPtr<IDBRequest> request = new IDBRequest(aDatabase);
CaptureCaller(aCx, request->mFilename, &request->mLineNo, &request->mColumn);
request->mCallerLocation = JSCallingLocation::Get(aCx);
request->mTransaction = std::move(aTransaction);
@ -143,15 +137,6 @@ void IDBRequest::SetLoggingSerialNumber(uint64_t aLoggingSerialNumber) {
mLoggingSerialNumber = aLoggingSerialNumber;
}
void IDBRequest::CaptureCaller(JSContext* aCx, nsAString& aFilename,
uint32_t* aLineNo, uint32_t* aColumn) {
MOZ_ASSERT(aFilename.IsEmpty());
MOZ_ASSERT(aLineNo);
MOZ_ASSERT(aColumn);
nsJSUtils::GetCallingLocation(aCx, aFilename, aLineNo, aColumn);
}
void IDBRequest::GetSource(
Nullable<OwningIDBObjectStoreOrIDBIndexOrIDBCursor>& aSource) const {
AssertIsOnOwningThread();
@ -213,17 +198,6 @@ DOMException* IDBRequest::GetErrorAfterResult() const {
#endif // DEBUG
void IDBRequest::GetCallerLocation(nsAString& aFilename, uint32_t* aLineNo,
uint32_t* aColumn) const {
AssertIsOnOwningThread();
MOZ_ASSERT(aLineNo);
MOZ_ASSERT(aColumn);
aFilename = mFilename;
*aLineNo = mLineNo;
*aColumn = mColumn;
}
IDBRequestReadyState IDBRequest::ReadyState() const {
AssertIsOnOwningThread();
@ -335,7 +309,7 @@ RefPtr<IDBOpenDBRequest> IDBOpenDBRequest::Create(
RefPtr<IDBOpenDBRequest> request =
new IDBOpenDBRequest(std::move(aFactory), aGlobal);
CaptureCaller(aCx, request->mFilename, &request->mLineNo, &request->mColumn);
request->mCallerLocation = JSCallingLocation::Get(aCx);
if (!NS_IsMainThread()) {
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();

Просмотреть файл

@ -10,6 +10,7 @@
#include "js/RootingAPI.h"
#include "mozilla/Attributes.h"
#include "mozilla/EventForwards.h"
#include "mozilla/SourceLocation.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/IDBRequestBinding.h"
#include "mozilla/dom/ScriptSettings.h"
@ -69,11 +70,9 @@ class IDBRequest : public DOMEventTargetHelper {
JS::Heap<JS::Value> mResultVal;
RefPtr<DOMException> mError;
nsString mFilename;
JSCallingLocation mCallerLocation;
uint64_t mLoggingSerialNumber;
nsresult mErrorCode;
uint32_t mLineNo;
uint32_t mColumn;
bool mHaveResultOrErrorCode;
public:
@ -89,9 +88,6 @@ class IDBRequest : public DOMEventTargetHelper {
JSContext* aCx, IDBIndex* aSource, IDBDatabase* aDatabase,
SafeRefPtr<IDBTransaction> aTransaction);
static void CaptureCaller(JSContext* aCx, nsAString& aFilename,
uint32_t* aLineNo, uint32_t* aColumn);
static uint64_t NextSerialNumber();
// EventTarget
@ -174,8 +170,7 @@ class IDBRequest : public DOMEventTargetHelper {
DOMException* GetError(ErrorResult& aRv);
void GetCallerLocation(nsAString& aFilename, uint32_t* aLineNo,
uint32_t* aColumn) const;
const JSCallingLocation& GetCallerLocation() const { return mCallerLocation; }
bool IsPending() const { return !mHaveResultOrErrorCode; }

Просмотреть файл

@ -90,8 +90,7 @@ auto IDBTransaction::DoWithTransactionChild(const Func& aFunc) const {
IDBTransaction::IDBTransaction(IDBDatabase* const aDatabase,
const nsTArray<nsString>& aObjectStoreNames,
const Mode aMode, const Durability aDurability,
nsString aFilename, const uint32_t aLineNo,
const uint32_t aColumn,
JSCallingLocation&& aCallerLocation,
CreatedFromFactoryFunction /*aDummy*/)
: DOMEventTargetHelper(aDatabase),
mDatabase(aDatabase),
@ -102,9 +101,7 @@ IDBTransaction::IDBTransaction(IDBDatabase* const aDatabase,
mNextRequestId(0),
mAbortCode(NS_OK),
mPendingRequestCount(0),
mFilename(std::move(aFilename)),
mLineNo(aLineNo),
mColumn(aColumn),
mCallerLocation(std::move(aCallerLocation)),
mMode(aMode),
mDurability(aDurability),
mRegistered(false),
@ -177,13 +174,10 @@ SafeRefPtr<IDBTransaction> IDBTransaction::CreateVersionChange(
const nsTArray<nsString> emptyObjectStoreNames;
nsString filename;
uint32_t lineNo, column;
aOpenRequest->GetCallerLocation(filename, &lineNo, &column);
// XXX: What should we have as durability hint here?
auto transaction = MakeSafeRefPtr<IDBTransaction>(
aDatabase, emptyObjectStoreNames, Mode::VersionChange,
Durability::Default, std::move(filename), lineNo, column,
Durability::Default, JSCallingLocation(aOpenRequest->GetCallerLocation()),
CreatedFromFactoryFunction{});
transaction->NoteActiveTransaction();
@ -209,12 +203,9 @@ SafeRefPtr<IDBTransaction> IDBTransaction::Create(
MOZ_ASSERT(aMode == Mode::ReadOnly || aMode == Mode::ReadWrite ||
aMode == Mode::ReadWriteFlush || aMode == Mode::Cleanup);
nsString filename;
uint32_t lineNo, column;
IDBRequest::CaptureCaller(aCx, filename, &lineNo, &column);
auto transaction = MakeSafeRefPtr<IDBTransaction>(
aDatabase, aObjectStoreNames, aMode, aDurability, std::move(filename),
lineNo, column, CreatedFromFactoryFunction{});
aDatabase, aObjectStoreNames, aMode, aDurability,
JSCallingLocation::Get(aCx), CreatedFromFactoryFunction{});
if (!NS_IsMainThread()) {
WorkerPrivate* const workerPrivate = GetCurrentThreadWorkerPrivate();
@ -462,18 +453,6 @@ void IDBTransaction::MaybeNoteInactiveTransaction() {
}
}
void IDBTransaction::GetCallerLocation(nsAString& aFilename,
uint32_t* const aLineNo,
uint32_t* const aColumn) const {
AssertIsOnOwningThread();
MOZ_ASSERT(aLineNo);
MOZ_ASSERT(aColumn);
aFilename = mFilename;
*aLineNo = mLineNo;
*aColumn = mColumn;
}
RefPtr<IDBObjectStore> IDBTransaction::CreateObjectStore(
ObjectStoreSpec& aSpec) {
AssertIsOnOwningThread();

Просмотреть файл

@ -9,6 +9,7 @@
#include "FlippedOnce.h"
#include "mozilla/Attributes.h"
#include "mozilla/SourceLocation.h"
#include "mozilla/dom/IDBTransactionBinding.h"
#include "mozilla/dom/quota/CheckedUnsafePtr.h"
#include "mozilla/DOMEventTargetHelper.h"
@ -115,9 +116,7 @@ class IDBTransaction final
///< transaction can auto-commit when the last
///< pending request finished.
const nsString mFilename;
const uint32_t mLineNo;
const uint32_t mColumn;
const JSCallingLocation mCallerLocation;
ReadyState mReadyState = ReadyState::Active;
FlippedOnce<false> mStarted;
@ -239,8 +238,10 @@ class IDBTransaction final
return mAbortCode;
}
void GetCallerLocation(nsAString& aFilename, uint32_t* aLineNo,
uint32_t* aColumn) const;
const JSCallingLocation& GetCallerLocation() const {
AssertIsOnOwningThread();
return mCallerLocation;
}
// 'Get' prefix is to avoid name collisions with the enum
Mode GetMode() const {
@ -349,8 +350,8 @@ class IDBTransaction final
public:
IDBTransaction(IDBDatabase* aDatabase,
const nsTArray<nsString>& aObjectStoreNames, Mode aMode,
Durability aDurability, nsString aFilename, uint32_t aLineNo,
uint32_t aColumn, CreatedFromFactoryFunction aDummy);
Durability aDurability, JSCallingLocation&& aCallerLocation,
CreatedFromFactoryFunction aDummy);
private:
~IDBTransaction();

Просмотреть файл

@ -7,13 +7,7 @@
#include "ScriptErrorHelper.h"
#include "MainThreadUtils.h"
#include "nsCOMPtr.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsIConsoleService.h"
#include "nsIScriptError.h"
#include "nsServiceManagerUtils.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "mozilla/SchedulerGroup.h"
@ -23,23 +17,19 @@ namespace {
class ScriptErrorRunnable final : public mozilla::Runnable {
nsString mMessage;
nsCString mMessageName;
nsString mFilename;
uint32_t mLineNumber;
uint32_t mColumnNumber;
mozilla::JSCallingLocation mCallingLocation;
uint32_t mSeverityFlag;
uint64_t mInnerWindowID;
bool mIsChrome;
public:
ScriptErrorRunnable(const nsAString& aMessage, const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber,
ScriptErrorRunnable(const nsAString& aMessage,
const mozilla::JSCallingLocation& aCallingLocation,
uint32_t aSeverityFlag, bool aIsChrome,
uint64_t aInnerWindowID)
: mozilla::Runnable("ScriptErrorRunnable"),
mMessage(aMessage),
mFilename(aFilename),
mLineNumber(aLineNumber),
mColumnNumber(aColumnNumber),
mCallingLocation(aCallingLocation),
mSeverityFlag(aSeverityFlag),
mInnerWindowID(aInnerWindowID),
mIsChrome(aIsChrome) {
@ -48,14 +38,12 @@ class ScriptErrorRunnable final : public mozilla::Runnable {
}
ScriptErrorRunnable(const nsACString& aMessageName,
const nsAString& aFilename, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aSeverityFlag,
bool aIsChrome, uint64_t aInnerWindowID)
const mozilla::JSCallingLocation& aCallingLocation,
uint32_t aSeverityFlag, bool aIsChrome,
uint64_t aInnerWindowID)
: mozilla::Runnable("ScriptErrorRunnable"),
mMessageName(aMessageName),
mFilename(aFilename),
mLineNumber(aLineNumber),
mColumnNumber(aColumnNumber),
mCallingLocation(aCallingLocation),
mSeverityFlag(aSeverityFlag),
mInnerWindowID(aInnerWindowID),
mIsChrome(aIsChrome) {
@ -63,11 +51,10 @@ class ScriptErrorRunnable final : public mozilla::Runnable {
mMessage.SetIsVoid(true);
}
static void DumpLocalizedMessage(const nsACString& aMessageName,
const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber,
uint32_t aSeverityFlag, bool aIsChrome,
uint64_t aInnerWindowID) {
static void DumpLocalizedMessage(
const nsACString& aMessageName,
const mozilla::JSCallingLocation& aCallingLocation, uint32_t aSeverityFlag,
bool aIsChrome, uint64_t aInnerWindowID) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(!aMessageName.IsEmpty());
@ -77,13 +64,12 @@ class ScriptErrorRunnable final : public mozilla::Runnable {
localizedMessage)))) {
return;
}
Dump(localizedMessage, aFilename, aLineNumber, aColumnNumber, aSeverityFlag,
aIsChrome, aInnerWindowID);
Dump(localizedMessage, aCallingLocation, aSeverityFlag, aIsChrome,
aInnerWindowID);
}
static void Dump(const nsAString& aMessage, const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber,
static void Dump(const nsAString& aMessage,
const mozilla::JSCallingLocation& aCallingLocation,
uint32_t aSeverityFlag, bool aIsChrome,
uint64_t aInnerWindowID) {
MOZ_ASSERT(NS_IsMainThread());
@ -95,37 +81,8 @@ class ScriptErrorRunnable final : public mozilla::Runnable {
category.AssignLiteral("content ");
}
category.AppendLiteral("javascript");
nsCOMPtr<nsIConsoleService> consoleService =
do_GetService(NS_CONSOLESERVICE_CONTRACTID);
nsCOMPtr<nsIScriptError> scriptError =
do_CreateInstance(NS_SCRIPTERROR_CONTRACTID);
// We may not be able to create the script error object when we're shutting
// down.
if (!scriptError) {
return;
}
if (aInnerWindowID) {
MOZ_ALWAYS_SUCCEEDS(scriptError->InitWithWindowID(
aMessage, aFilename,
/* aSourceLine */ u""_ns, aLineNumber, aColumnNumber, aSeverityFlag,
category, aInnerWindowID));
} else {
MOZ_ALWAYS_SUCCEEDS(scriptError->Init(
aMessage, aFilename,
/* aSourceLine */ u""_ns, aLineNumber, aColumnNumber, aSeverityFlag,
category,
/* IDB doesn't run on Private browsing mode */ false,
/* from chrome context */ aIsChrome));
}
// We may not be able to obtain the console service when we're shutting
// down.
if (consoleService) {
MOZ_ALWAYS_SUCCEEDS(consoleService->LogMessage(scriptError));
}
nsContentUtils::ReportToConsoleByWindowID(aMessage, aSeverityFlag, category,
aInnerWindowID, aCallingLocation);
}
NS_IMETHOD
@ -134,13 +91,13 @@ class ScriptErrorRunnable final : public mozilla::Runnable {
MOZ_ASSERT(mMessage.IsVoid() != mMessageName.IsVoid());
if (!mMessage.IsVoid()) {
Dump(mMessage, mFilename, mLineNumber, mColumnNumber, mSeverityFlag,
mIsChrome, mInnerWindowID);
Dump(mMessage, mCallingLocation, mSeverityFlag, mIsChrome,
mInnerWindowID);
return NS_OK;
}
DumpLocalizedMessage(mMessageName, mFilename, mLineNumber, mColumnNumber,
mSeverityFlag, mIsChrome, mInnerWindowID);
DumpLocalizedMessage(mMessageName, mCallingLocation, mSeverityFlag,
mIsChrome, mInnerWindowID);
return NS_OK;
}
@ -155,33 +112,30 @@ namespace mozilla::dom::indexedDB {
/*static*/
void ScriptErrorHelper::Dump(const nsAString& aMessage,
const nsAString& aFilename, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aSeverityFlag,
const JSCallingLocation& aCallingLocation, uint32_t aSeverityFlag,
bool aIsChrome, uint64_t aInnerWindowID) {
if (NS_IsMainThread()) {
ScriptErrorRunnable::Dump(aMessage, aFilename, aLineNumber, aColumnNumber,
aSeverityFlag, aIsChrome, aInnerWindowID);
ScriptErrorRunnable::Dump(aMessage, aCallingLocation, aSeverityFlag, aIsChrome,
aInnerWindowID);
} else {
RefPtr<ScriptErrorRunnable> runnable =
new ScriptErrorRunnable(aMessage, aFilename, aLineNumber, aColumnNumber,
aSeverityFlag, aIsChrome, aInnerWindowID);
RefPtr<ScriptErrorRunnable> runnable = new ScriptErrorRunnable(
aMessage, aCallingLocation, aSeverityFlag, aIsChrome, aInnerWindowID);
MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(runnable.forget()));
}
}
/*static*/
void ScriptErrorHelper::DumpLocalizedMessage(
const nsACString& aMessageName, const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber, uint32_t aSeverityFlag,
bool aIsChrome, uint64_t aInnerWindowID) {
void ScriptErrorHelper::DumpLocalizedMessage(const nsACString& aMessageName,
const JSCallingLocation& aCallingLocation,
uint32_t aSeverityFlag,
bool aIsChrome,
uint64_t aInnerWindowID) {
if (NS_IsMainThread()) {
ScriptErrorRunnable::DumpLocalizedMessage(
aMessageName, aFilename, aLineNumber, aColumnNumber, aSeverityFlag,
aIsChrome, aInnerWindowID);
ScriptErrorRunnable::DumpLocalizedMessage(aMessageName, aCallingLocation, aSeverityFlag,
aIsChrome, aInnerWindowID);
} else {
RefPtr<ScriptErrorRunnable> runnable = new ScriptErrorRunnable(
aMessageName, aFilename, aLineNumber, aColumnNumber, aSeverityFlag,
aIsChrome, aInnerWindowID);
aMessageName, aCallingLocation, aSeverityFlag, aIsChrome, aInnerWindowID);
MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(runnable.forget()));
}
}

Просмотреть файл

@ -10,19 +10,21 @@
#include <inttypes.h>
#include "nsStringFwd.h"
namespace mozilla {
struct JSCallingLocation;
}
namespace mozilla::dom::indexedDB {
// Helper to report a script error to the main thread.
class ScriptErrorHelper {
public:
static void Dump(const nsAString& aMessage, const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber,
static void Dump(const nsAString& aMessage, const JSCallingLocation&,
uint32_t aSeverityFlag, /* nsIScriptError::xxxFlag */
bool aIsChrome, uint64_t aInnerWindowID);
static void DumpLocalizedMessage(
const nsACString& aMessageName, const nsAString& aFilename,
uint32_t aLineNumber, uint32_t aColumnNumber,
const nsACString& aMessageName, const JSCallingLocation&,
uint32_t aSeverityFlag, /* nsIScriptError::xxxFlag */
bool aIsChrome, uint64_t aInnerWindowID);
};

Просмотреть файл

@ -230,7 +230,7 @@ interface nsIContentSecurityPolicy : nsISerializable
void logViolationDetails(in unsigned short violationType,
in Element triggeringElement,
in nsICSPEventListener aCSPEventListener,
in AString sourceFile,
in ACString sourceFile,
in AString scriptSample,
in int32_t lineNum,
in int32_t columnNum,

Просмотреть файл

@ -73,41 +73,17 @@ void WebAudioUtils::LogToDeveloperConsole(uint64_t aWindowID,
return;
}
nsCOMPtr<nsIConsoleService> console(
do_GetService("@mozilla.org/consoleservice;1"));
if (!console) {
NS_WARNING("Failed to log message to console.");
return;
}
nsAutoString spec;
uint32_t aLineNumber = 0, aColumnNumber = 1;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, spec, &aLineNumber, &aColumnNumber);
}
nsresult rv;
nsCOMPtr<nsIScriptError> errorObject =
do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
if (!errorObject) {
NS_WARNING("Failed to log message to console.");
return;
}
nsAutoString result;
rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES, aKey,
result);
nsresult rv = nsContentUtils::GetLocalizedString(
nsContentUtils::eDOM_PROPERTIES, aKey, result);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to log message to console.");
return;
}
errorObject->InitWithWindowID(result, spec, u""_ns, aLineNumber,
aColumnNumber, nsIScriptError::warningFlag,
"Web Audio", aWindowID);
console->LogMessage(errorObject);
nsContentUtils::ReportToConsoleByWindowID(result, nsIScriptError::warningFlag,
"Web Audio"_ns, aWindowID);
}
} // namespace dom

Просмотреть файл

@ -453,7 +453,7 @@ nsresult PrototypeDocumentContentSink::ResumeWalk() {
nsContentUtils::ReportToConsoleNonLocalized(
u"Failed to load document from prototype document."_ns,
nsIScriptError::errorFlag, "Prototype Document"_ns, mDocument,
mDocumentURI);
SourceLocation{mDocumentURI.get()});
}
return rv;
}
@ -594,10 +594,10 @@ nsresult PrototypeDocumentContentSink::ResumeWalkInternal() {
if (piProto->mTarget.EqualsLiteral("xml-stylesheet")) {
AutoTArray<nsString, 1> params = {piProto->mTarget};
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
"XUL Document"_ns, nullptr,
nsContentUtils::eXUL_PROPERTIES,
"PINotInProlog", params, docURI);
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "XUL Document"_ns, nullptr,
nsContentUtils::eXUL_PROPERTIES, "PINotInProlog", params,
SourceLocation(docURI.get()));
}
nsIContent* parent = element.get();

Просмотреть файл

@ -390,21 +390,16 @@ nsresult PushErrorDispatcher::NotifyWorkers() {
// For system subscriptions, log the error directly to the browser console.
return nsContentUtils::ReportToConsoleNonLocalized(
mMessage, mFlags, "Push"_ns, nullptr, /* aDocument */
nullptr, /* aURI */
u""_ns, /* aLine */
0, /* aLineNumber */
0, /* aColumnNumber */
nsContentUtils::eOMIT_LOCATION);
SourceLocation());
}
// For service worker subscriptions, report the error to all clients.
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (swm) {
swm->ReportToAllClients(mScope, mMessage,
NS_ConvertUTF8toUTF16(mScope), /* aFilename */
u""_ns, /* aLine */
0, /* aLineNumber */
0, /* aColumnNumber */
swm->ReportToAllClients(mScope, mMessage, mScope, /* aFilename */
u""_ns, /* aLine */
0, /* aLineNumber */
0, /* aColumnNumber */
mFlags);
}
return NS_OK;
@ -426,12 +421,8 @@ nsresult PushErrorDispatcher::HandleNoChildProcesses() {
return rv;
}
return nsContentUtils::ReportToConsoleNonLocalized(
mMessage, mFlags, "Push"_ns, nullptr, /* aDocument */
scopeURI, /* aURI */
u""_ns, /* aLine */
0, /* aLineNumber */
0, /* aColumnNumber */
nsContentUtils::eOMIT_LOCATION);
mMessage, mFlags, "Push"_ns, /* aDocument = */ nullptr,
SourceLocation(scopeURI.get()));
}
} // namespace mozilla::dom

Просмотреть файл

@ -19,7 +19,7 @@ CSPViolationReportBody::CSPViolationReportBody(
mReferrer(aEvent.mReferrer),
mEffectiveDirective(aEvent.mEffectiveDirective),
mOriginalPolicy(aEvent.mOriginalPolicy),
mSourceFile(aEvent.mSourceFile),
mSourceFile(NS_ConvertUTF16toUTF8(aEvent.mSourceFile)),
mSample(aEvent.mSample),
mDisposition(aEvent.mDisposition),
mStatusCode(aEvent.mStatusCode),
@ -54,7 +54,7 @@ void CSPViolationReportBody::GetOriginalPolicy(nsAString& aPolicy) const {
aPolicy = mOriginalPolicy;
}
void CSPViolationReportBody::GetSourceFile(nsAString& aFile) const {
void CSPViolationReportBody::GetSourceFile(nsACString& aFile) const {
aFile = mSourceFile;
}
@ -115,8 +115,7 @@ void CSPViolationReportBody::ToJSON(JSONWriter& aJSONWriter) const {
if (mSourceFile.IsEmpty()) {
aJSONWriter.NullProperty("sourceFile");
} else {
aJSONWriter.StringProperty("sourceFile",
NS_ConvertUTF16toUTF8(mSourceFile));
aJSONWriter.StringProperty("sourceFile", mSourceFile);
}
if (mSample.IsEmpty()) {

Просмотреть файл

@ -32,7 +32,7 @@ class CSPViolationReportBody final : public ReportBody {
void GetOriginalPolicy(nsAString& aPolicy) const;
void GetSourceFile(nsAString& aFile) const;
void GetSourceFile(nsACString& aFile) const;
void GetSample(nsAString& aSample) const;
@ -55,7 +55,7 @@ class CSPViolationReportBody final : public ReportBody {
const nsString mReferrer;
const nsString mEffectiveDirective;
const nsString mOriginalPolicy;
const nsString mSourceFile;
const nsCString mSourceFile;
const nsString mSample;
const mozilla::dom::SecurityPolicyViolationEventDisposition mDisposition;
const uint16_t mStatusCode;

Просмотреть файл

@ -13,7 +13,7 @@ namespace mozilla::dom {
DeprecationReportBody::DeprecationReportBody(
nsIGlobalObject* aGlobal, const nsAString& aId,
const Nullable<uint64_t>& aDate, const nsAString& aMessage,
const nsAString& aSourceFile, const Nullable<uint32_t>& aLineNumber,
const nsACString& aSourceFile, const Nullable<uint32_t>& aLineNumber,
const Nullable<uint32_t>& aColumnNumber)
: ReportBody(aGlobal),
mId(aId),
@ -42,7 +42,7 @@ void DeprecationReportBody::GetMessage(nsAString& aMessage) const {
aMessage = mMessage;
}
void DeprecationReportBody::GetSourceFile(nsAString& aSourceFile) const {
void DeprecationReportBody::GetSourceFile(nsACString& aSourceFile) const {
aSourceFile = mSourceFile;
}
@ -62,7 +62,7 @@ void DeprecationReportBody::ToJSON(JSONWriter& aWriter) const {
if (mSourceFile.IsEmpty()) {
aWriter.NullProperty("sourceFile");
} else {
aWriter.StringProperty("sourceFile", NS_ConvertUTF16toUTF8(mSourceFile));
aWriter.StringProperty("sourceFile", mSourceFile);
}
if (mLineNumber.IsNull()) {

Просмотреть файл

@ -17,7 +17,8 @@ class DeprecationReportBody final : public ReportBody {
public:
DeprecationReportBody(nsIGlobalObject* aGlobal, const nsAString& aId,
const Nullable<uint64_t>& aDate,
const nsAString& aMessage, const nsAString& aSourceFile,
const nsAString& aMessage,
const nsACString& aSourceFile,
const Nullable<uint32_t>& aLineNumber,
const Nullable<uint32_t>& aColumnNumber);
@ -30,7 +31,7 @@ class DeprecationReportBody final : public ReportBody {
void GetMessage(nsAString& aMessage) const;
void GetSourceFile(nsAString& aSourceFile) const;
void GetSourceFile(nsACString& aSourceFile) const;
Nullable<uint32_t> GetLineNumber() const;
@ -45,7 +46,7 @@ class DeprecationReportBody final : public ReportBody {
const nsString mId;
const Nullable<uint64_t> mDate;
const nsString mMessage;
const nsString mSourceFile;
const nsCString mSourceFile;
const Nullable<uint32_t> mLineNumber;
const Nullable<uint32_t> mColumnNumber;
};

Просмотреть файл

@ -13,7 +13,7 @@ namespace mozilla::dom {
FeaturePolicyViolationReportBody::FeaturePolicyViolationReportBody(
nsIGlobalObject* aGlobal, const nsAString& aFeatureId,
const nsAString& aSourceFile, const Nullable<int32_t>& aLineNumber,
const nsACString& aSourceFile, const Nullable<int32_t>& aLineNumber,
const Nullable<int32_t>& aColumnNumber, const nsAString& aDisposition)
: ReportBody(aGlobal),
mFeatureId(aFeatureId),
@ -35,7 +35,7 @@ void FeaturePolicyViolationReportBody::GetFeatureId(
}
void FeaturePolicyViolationReportBody::GetSourceFile(
nsAString& aSourceFile) const {
nsACString& aSourceFile) const {
aSourceFile = mSourceFile;
}
@ -58,7 +58,7 @@ void FeaturePolicyViolationReportBody::ToJSON(JSONWriter& aWriter) const {
if (mSourceFile.IsEmpty()) {
aWriter.NullProperty("sourceFile");
} else {
aWriter.StringProperty("sourceFile", NS_ConvertUTF16toUTF8(mSourceFile));
aWriter.StringProperty("sourceFile", mSourceFile);
}
if (mLineNumber.IsNull()) {

Просмотреть файл

@ -17,7 +17,7 @@ class FeaturePolicyViolationReportBody final : public ReportBody {
public:
FeaturePolicyViolationReportBody(nsIGlobalObject* aGlobal,
const nsAString& aFeatureId,
const nsAString& aSourceFile,
const nsACString& aSourceFile,
const Nullable<int32_t>& aLineNumber,
const Nullable<int32_t>& aColumnNumber,
const nsAString& aDisposition);
@ -27,7 +27,7 @@ class FeaturePolicyViolationReportBody final : public ReportBody {
void GetFeatureId(nsAString& aFeatureId) const;
void GetSourceFile(nsAString& aSourceFile) const;
void GetSourceFile(nsACString& aSourceFile) const;
Nullable<int32_t> GetLineNumber() const;
@ -42,7 +42,7 @@ class FeaturePolicyViolationReportBody final : public ReportBody {
~FeaturePolicyViolationReportBody();
const nsString mFeatureId;
const nsString mSourceFile;
const nsCString mSourceFile;
const Nullable<int32_t> mLineNumber;
const Nullable<int32_t> mColumnNumber;
const nsString mDisposition;

Просмотреть файл

@ -577,7 +577,8 @@ void ReportingHeader::LogToConsoleInternal(nsIHttpChannel* aChannel,
}
rv = nsContentUtils::ReportToConsoleByWindowID(
localizedMsg, nsIScriptError::infoFlag, "Reporting"_ns, windowID, aURI);
localizedMsg, nsIScriptError::infoFlag, "Reporting"_ns, windowID,
SourceLocation(aURI));
Unused << NS_WARN_IF(NS_FAILED(rv));
}

Просмотреть файл

@ -3627,8 +3627,9 @@ void ScriptLoader::ReportErrorToConsole(ScriptLoadRequest* aRequest,
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Script Loader"_ns, mDocument,
nsContentUtils::eDOM_PROPERTIES, message, params, nullptr, u""_ns, lineNo,
columnNo.oneOriginValue());
nsContentUtils::eDOM_PROPERTIES, message, params,
SourceLocation{mDocument->GetDocumentURI(), lineNo,
columnNo.oneOriginValue()});
}
void ScriptLoader::ReportWarningToConsole(
@ -3639,8 +3640,9 @@ void ScriptLoader::ReportWarningToConsole(
aRequest->GetScriptLoadContext()->GetScriptColumnNumber();
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Script Loader"_ns, mDocument,
nsContentUtils::eDOM_PROPERTIES, aMessageName, aParams, nullptr, u""_ns,
lineNo, columnNo.oneOriginValue());
nsContentUtils::eDOM_PROPERTIES, aMessageName, aParams,
SourceLocation{mDocument->GetDocumentURI(), lineNo,
columnNo.oneOriginValue()});
}
void ScriptLoader::ReportPreloadErrorsToConsole(ScriptLoadRequest* aRequest) {

Просмотреть файл

@ -8,14 +8,11 @@
#include "mozilla/dom/Document.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ErrorResult.h"
#include "nsIParentChannel.h"
#include "nsGlobalWindowInner.h"
#include "nsContentSecurityUtils.h"
#include "nsContentUtils.h"
#include "nsCOMPtr.h"
#include "nsJSUtils.h"
using namespace mozilla;
using namespace mozilla::dom;
@ -28,8 +25,7 @@ nsresult CheckInternal(nsIContentSecurityPolicy* aCSP,
nsICSPEventListener* aCSPEventListener,
nsIPrincipal* aSubjectPrincipal,
const nsAString& aExpression,
const nsAString& aFileNameString, uint32_t aLineNum,
uint32_t aColumnNum, bool* aAllowed) {
const JSCallingLocation& aCaller, bool* aAllowed) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aAllowed);
@ -61,8 +57,9 @@ nsresult CheckInternal(nsIContentSecurityPolicy* aCSP,
if (reportViolation) {
aCSP->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
nullptr, // triggering element
aCSPEventListener, aFileNameString, aExpression,
aLineNum, aColumnNum, u""_ns, u""_ns);
aCSPEventListener, aCaller.FileName(),
aExpression, aCaller.mLine, aCaller.mColumn,
u""_ns, u""_ns);
}
return NS_OK;
@ -72,22 +69,19 @@ class WorkerCSPCheckRunnable final : public WorkerMainThreadRunnable {
public:
WorkerCSPCheckRunnable(WorkerPrivate* aWorkerPrivate,
const nsAString& aExpression,
const nsAString& aFileNameString, uint32_t aLineNum,
uint32_t aColumnNum)
JSCallingLocation&& aCaller)
: WorkerMainThreadRunnable(aWorkerPrivate, "CSP Eval Check"_ns),
mExpression(aExpression),
mFileNameString(aFileNameString),
mLineNum(aLineNum),
mColumnNum(aColumnNum),
mCaller(std::move(aCaller)),
mEvalAllowed(false) {}
bool MainThreadRun() override {
MOZ_ASSERT(mWorkerRef);
WorkerPrivate* workerPrivate = mWorkerRef->Private();
mResult = CheckInternal(
workerPrivate->GetCsp(), workerPrivate->CSPEventListener(),
workerPrivate->GetLoadingPrincipal(), mExpression, mFileNameString,
mLineNum, mColumnNum, &mEvalAllowed);
mResult = CheckInternal(workerPrivate->GetCsp(),
workerPrivate->CSPEventListener(),
workerPrivate->GetLoadingPrincipal(), mExpression,
mCaller, &mEvalAllowed);
return true;
}
@ -99,9 +93,7 @@ class WorkerCSPCheckRunnable final : public WorkerMainThreadRunnable {
private:
const nsString mExpression;
const nsString mFileNameString;
const uint32_t mLineNum;
const uint32_t mColumnNum;
const JSCallingLocation mCaller;
bool mEvalAllowed;
nsresult mResult;
};
@ -131,19 +123,10 @@ nsresult CSPEvalChecker::CheckForWindow(JSContext* aCx,
nsresult rv = NS_OK;
// Get the calling location.
uint32_t lineNum = 0;
uint32_t columnNum = 1;
nsAutoString fileNameString;
if (!nsJSUtils::GetCallingLocation(aCx, fileNameString, &lineNum,
&columnNum)) {
fileNameString.AssignLiteral("unknown");
}
auto location = JSCallingLocation::Get(aCx);
nsCOMPtr<nsIContentSecurityPolicy> csp = doc->GetCsp();
rv = CheckInternal(csp, nullptr /* no CSPEventListener for window */,
doc->NodePrincipal(), aExpression, fileNameString, lineNum,
columnNum, aAllowEval);
doc->NodePrincipal(), aExpression, location, aAllowEval);
if (NS_WARN_IF(NS_FAILED(rv))) {
*aAllowEval = false;
return rv;
@ -164,17 +147,8 @@ nsresult CSPEvalChecker::CheckForWorker(JSContext* aCx,
// The value is set at any "return", but better to have a default value here.
*aAllowEval = false;
// Get the calling location.
uint32_t lineNum = 0;
uint32_t columnNum = 1;
nsAutoString fileNameString;
if (!nsJSUtils::GetCallingLocation(aCx, fileNameString, &lineNum,
&columnNum)) {
fileNameString.AssignLiteral("unknown");
}
RefPtr<WorkerCSPCheckRunnable> r = new WorkerCSPCheckRunnable(
aWorkerPrivate, aExpression, fileNameString, lineNum, columnNum);
aWorkerPrivate, aExpression, JSCallingLocation::Get(aCx));
ErrorResult error;
r->Dispatch(aWorkerPrivate, Canceling, error);
if (NS_WARN_IF(error.Failed())) {

Просмотреть файл

@ -35,7 +35,7 @@ static nsString MaybeTruncateSample(const nsAString& aSample) {
CSPViolationData::CSPViolationData(uint32_t aViolatedPolicyIndex,
Resource&& aResource,
const CSPDirective aEffectiveDirective,
const nsAString& aSourceFile,
const nsACString& aSourceFile,
uint32_t aLineNumber, uint32_t aColumnNumber,
Element* aElement, const nsAString& aSample)
: mViolatedPolicyIndex{aViolatedPolicyIndex},

Просмотреть файл

@ -38,7 +38,7 @@ struct CSPViolationData {
// @param aSample Will be truncated if necessary.
CSPViolationData(uint32_t aViolatedPolicyIndex, Resource&& aResource,
const CSPDirective aEffectiveDirective,
const nsAString& aSourceFile, uint32_t aLineNumber,
const nsACString& aSourceFile, uint32_t aLineNumber,
uint32_t aColumnNumber, Element* aElement,
const nsAString& aSample);
@ -50,7 +50,7 @@ struct CSPViolationData {
const Resource mResource;
const CSPDirective mEffectiveDirective;
// String representation of the URL. The empty string represents a null-URL.
const nsString mSourceFile;
const nsCString mSourceFile;
const uint32_t mLineNumber;
const uint32_t mColumnNumber;
RefPtr<Element> mElement;

Просмотреть файл

@ -34,12 +34,8 @@ void DOMSecurityMonitor::AuditParsingOfHTMLXMLFragments(
// check if there is a JS caller, if not, then we can can return early here
// because we only care about calls to the fragment parser (e.g. innerHTML)
// originating from JS code.
nsAutoString filename;
uint32_t lineNum = 0;
uint32_t columnNum = 1;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (!cx ||
!nsJSUtils::GetCallingLocation(cx, filename, &lineNum, &columnNum)) {
auto loc = mozilla::JSCallingLocation::Get();
if (!loc) {
return;
}
@ -88,7 +84,7 @@ void DOMSecurityMonitor::AuditParsingOfHTMLXMLFragments(
};
for (const nsLiteralCString& allowlistEntry : htmlFragmentAllowlist) {
if (StringBeginsWith(NS_ConvertUTF16toUTF8(filename), allowlistEntry)) {
if (StringBeginsWith(loc.FileName(), allowlistEntry)) {
return;
}
}
@ -104,8 +100,8 @@ void DOMSecurityMonitor::AuditParsingOfHTMLXMLFragments(
"Do not call the fragment parser (e.g innerHTML()) in chrome code "
"or in about: pages, (uri: %s), (caller: %s, line: %d, col: %d), "
"(fragment: %s)",
uriSpec.get(), NS_ConvertUTF16toUTF8(filename).get(), lineNum,
columnNum, NS_ConvertUTF16toUTF8(aFragment).get());
uriSpec.get(), loc.FileName().get(), loc.mLine, loc.mColumn,
NS_ConvertUTF16toUTF8(aFragment).get());
xpc_DumpJSStack(true, true, false);
MOZ_ASSERT(false);

Просмотреть файл

@ -860,7 +860,8 @@ void ReferrerInfo::LogMessageToConsole(
}
rv = nsContentUtils::ReportToConsoleByWindowID(
localizedMsg, nsIScriptError::infoFlag, "Security"_ns, windowID, uri);
localizedMsg, nsIScriptError::infoFlag, "Security"_ns, windowID,
SourceLocation(std::move(uri)));
Unused << NS_WARN_IF(NS_FAILED(rv));
}

Просмотреть файл

@ -222,14 +222,12 @@ void FeaturePolicyUtils::ReportViolation(Document* aDocument,
return;
}
nsAutoString fileName;
Nullable<int32_t> lineNumber;
Nullable<int32_t> columnNumber;
uint32_t line = 0;
uint32_t column = 0;
if (nsJSUtils::GetCallingLocation(cx, fileName, &line, &column)) {
lineNumber.SetValue(static_cast<int32_t>(line));
columnNumber.SetValue(static_cast<int32_t>(column));
auto loc = JSCallingLocation::Get();
if (loc) {
lineNumber.SetValue(static_cast<int32_t>(loc.mLine));
columnNumber.SetValue(static_cast<int32_t>(loc.mColumn));
}
nsPIDOMWindowInner* window = aDocument->GetInnerWindow();
@ -239,8 +237,8 @@ void FeaturePolicyUtils::ReportViolation(Document* aDocument,
RefPtr<FeaturePolicyViolationReportBody> body =
new FeaturePolicyViolationReportBody(window->AsGlobal(), aFeatureName,
fileName, lineNumber, columnNumber,
u"enforce"_ns);
loc.FileName(), lineNumber,
columnNumber, u"enforce"_ns);
ReportingUtils::Report(window->AsGlobal(), nsGkAtoms::featurePolicyViolation,
u"default"_ns, NS_ConvertUTF8toUTF16(spec), body);

Просмотреть файл

@ -212,15 +212,7 @@ bool nsCSPContext::permitsInternal(
// preload - the decision may be wrong due to the inability to get the
// nonce, and will incorrectly fail the unit tests.
if (aSendViolationReports) {
uint32_t lineNumber = 0;
uint32_t columnNumber = 1;
nsAutoString spec;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, spec, &lineNumber, &columnNumber);
// If GetCallingLocation fails linenumber & columnNumber are set to
// (0, 1) anyway so we can skip checking if that is the case.
}
auto loc = JSCallingLocation::Get();
using Resource = CSPViolationData::Resource;
Resource resource =
@ -231,9 +223,9 @@ bool nsCSPContext::permitsInternal(
CSPViolationData cspViolationData{p,
std::move(resource),
aDir,
spec,
lineNumber,
columnNumber,
loc.FileName(),
loc.mLine,
loc.mColumn,
aTriggeringElement,
/* aSample */ u""_ns};
@ -553,21 +545,16 @@ void nsCSPContext::reportInlineViolation(
STYLE_HASH_VIOLATION_OBSERVER_TOPIC);
}
nsAutoString sourceFile;
uint32_t lineNumber;
uint32_t columnNumber;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (!cx || !nsJSUtils::GetCallingLocation(cx, sourceFile, &lineNumber,
&columnNumber)) {
// use selfURI as the sourceFile
auto loc = JSCallingLocation::Get();
if (!loc) {
nsCString sourceFile;
// use selfURI as the source
if (mSelfURI) {
nsAutoCString cSourceFile;
mSelfURI->GetSpec(cSourceFile);
sourceFile.Assign(NS_ConvertUTF8toUTF16(cSourceFile));
mSelfURI->GetSpec(sourceFile);
loc.mResource = AsVariant(std::move(sourceFile));
}
lineNumber = aLineNumber;
columnNumber = aColumnNumber;
loc.mLine = aLineNumber;
loc.mColumn = aColumnNumber;
}
CSPViolationData cspViolationData{
@ -575,9 +562,9 @@ void nsCSPContext::reportInlineViolation(
CSPViolationData::Resource{
CSPViolationData::BlockedContentSource::Inline},
aEffectiveDirective,
sourceFile,
lineNumber,
columnNumber,
loc.FileName(),
loc.mLine,
loc.mColumn,
aTriggeringElement,
aSample};
@ -730,7 +717,7 @@ nsCSPContext::GetAllowsInline(CSPDirective aDirective, bool aHasUnsafeHash,
NS_IMETHODIMP
nsCSPContext::LogViolationDetails(
uint16_t aViolationType, Element* aTriggeringElement,
nsICSPEventListener* aCSPEventListener, const nsAString& aSourceFile,
nsICSPEventListener* aCSPEventListener, const nsACString& aSourceFile,
const nsAString& aScriptSample, int32_t aLineNum, int32_t aColumnNum,
const nsAString& aNonce, const nsAString& aContent) {
EnsureIPCPoliciesRead();
@ -895,7 +882,7 @@ nsCSPContext::EnsureEventTarget(nsIEventTarget* aEventTarget) {
struct ConsoleMsgQueueElem {
nsString mMsg;
nsString mSourceName;
nsCString mSourceName;
nsString mSourceLine;
uint32_t mLineNumber;
uint32_t mColumnNumber;
@ -927,7 +914,7 @@ void nsCSPContext::flushConsoleMessages() {
void nsCSPContext::logToConsole(const char* aName,
const nsTArray<nsString>& aParams,
const nsAString& aSourceName,
const nsACString& aSourceName,
const nsAString& aSourceLine,
uint32_t aLineNumber, uint32_t aColumnNumber,
uint32_t aSeverityFlag) {
@ -936,20 +923,20 @@ void nsCSPContext::logToConsole(const char* aName,
nsDependentCString category(aName);
// Fallback
nsAutoString sourceName(aSourceName);
if (sourceName.IsEmpty() && mSelfURI) {
nsAutoCString spec;
nsAutoCString spec;
if (aSourceName.IsEmpty() && mSelfURI) {
mSelfURI->GetSpec(spec);
CopyUTF8toUTF16(spec, sourceName);
}
const auto& sourceName = aSourceName.IsEmpty() ? spec : aSourceName;
// let's check if we have to queue up console messages
if (mQueueUpMessages) {
nsAutoString msg;
CSP_GetLocalizedStr(aName, aParams, msg);
ConsoleMsgQueueElem& elem = *mConsoleMsgQueue.AppendElement();
elem.mMsg = msg;
elem.mSourceName = PromiseFlatString(sourceName);
elem.mSourceName = sourceName;
elem.mSourceLine = PromiseFlatString(aSourceLine);
elem.mLineNumber = aLineNumber;
elem.mColumnNumber = aColumnNumber;
@ -959,8 +946,7 @@ void nsCSPContext::logToConsole(const char* aName,
}
bool privateWindow = false;
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
if (doc) {
if (nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext)) {
privateWindow =
doc->NodePrincipal()->OriginAttributesRef().IsPrivateBrowsing();
}
@ -1082,11 +1068,12 @@ nsresult nsCSPContext::GatherSecurityPolicyViolationEventData(
nsCOMPtr<nsIURI> sourceURI;
NS_NewURI(getter_AddRefs(sourceURI), aCSPViolationData.mSourceFile);
if (sourceURI) {
nsAutoCString spec;
StripURIForReporting(mSelfURI, sourceURI, aEffectiveDirective, spec);
CopyUTF8toUTF16(spec, aViolationEventInit.mSourceFile);
nsAutoCString stripped;
StripURIForReporting(mSelfURI, sourceURI, aEffectiveDirective, stripped);
CopyUTF8toUTF16(stripped, aViolationEventInit.mSourceFile);
} else {
aViolationEventInit.mSourceFile = aCSPViolationData.mSourceFile;
CopyUTF8toUTF16(aCSPViolationData.mSourceFile,
aViolationEventInit.mSourceFile);
}
}
@ -1160,7 +1147,8 @@ bool nsCSPContext::ShouldThrottleReport(
// Rate limit reached
if (!mWarnedAboutTooManyReports) {
logToConsole("tooManyReports", {}, aViolationEventInit.mSourceFile,
logToConsole("tooManyReports", {},
NS_ConvertUTF16toUTF8(aViolationEventInit.mSourceFile),
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber, nsIScriptError::errorFlag);
mWarnedAboutTooManyReports = true;
@ -1251,7 +1239,8 @@ nsresult nsCSPContext::SendReportsToURIs(
// source-file
if (!aViolationEventInit.mSourceFile.IsEmpty()) {
report.mCsp_report.mSource_file.Construct();
report.mCsp_report.mSource_file.Value() = aViolationEventInit.mSourceFile;
CopyUTF16toUTF8(aViolationEventInit.mSourceFile,
report.mCsp_report.mSource_file.Value());
}
// script-sample
@ -1291,7 +1280,8 @@ nsresult nsCSPContext::SendReportsToURIs(
AutoTArray<nsString, 1> params = {reportURIs[r]};
CSPCONTEXTLOG(("Could not create nsIURI for report URI %s",
reportURICstring.get()));
logToConsole("triedToSendReport", params, aViolationEventInit.mSourceFile,
logToConsole("triedToSendReport", params,
NS_ConvertUTF16toUTF8(aViolationEventInit.mSourceFile),
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber,
nsIScriptError::errorFlag);
@ -1323,10 +1313,11 @@ nsresult nsCSPContext::SendReportsToURIs(
if (!isHttpScheme) {
AutoTArray<nsString, 1> params = {reportURIs[r]};
logToConsole(
"reportURInotHttpsOrHttp2", params, aViolationEventInit.mSourceFile,
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber, nsIScriptError::errorFlag);
logToConsole("reportURInotHttpsOrHttp2", params,
NS_ConvertUTF16toUTF8(aViolationEventInit.mSourceFile),
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber,
nsIScriptError::errorFlag);
continue;
}
@ -1396,7 +1387,8 @@ nsresult nsCSPContext::SendReportsToURIs(
AutoTArray<nsString, 1> params = {reportURIs[r]};
CSPCONTEXTLOG(("AsyncOpen failed for report URI %s",
NS_ConvertUTF16toUTF8(params[0]).get()));
logToConsole("triedToSendReport", params, aViolationEventInit.mSourceFile,
logToConsole("triedToSendReport", params,
NS_ConvertUTF16toUTF8(aViolationEventInit.mSourceFile),
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber,
nsIScriptError::errorFlag);
@ -1907,7 +1899,7 @@ nsCSPContext::GetCSPSandboxFlags(uint32_t* aOutSandboxFlags) {
NS_ConvertUTF16toUTF8(policy).get()));
AutoTArray<nsString, 1> params = {policy};
logToConsole("ignoringReportOnlyDirective", params, u""_ns, u""_ns, 0, 1,
logToConsole("ignoringReportOnlyDirective", params, ""_ns, u""_ns, 0, 1,
nsIScriptError::warningFlag);
}
}

Просмотреть файл

@ -74,7 +74,7 @@ class nsCSPContext : public nsIContentSecurityPolicy {
void flushConsoleMessages();
void logToConsole(const char* aName, const nsTArray<nsString>& aParams,
const nsAString& aSourceName, const nsAString& aSourceLine,
const nsACString& aSourceName, const nsAString& aSourceLine,
uint32_t aLineNumber, uint32_t aColumnNumber,
uint32_t aSeverityFlag);

Просмотреть файл

@ -183,7 +183,7 @@ void nsCSPParser::logWarningErrorToConsole(uint32_t aSeverityFlag,
// send console messages off to the context and let the context
// deal with it (potentially messages need to be queued up)
mCSPContext->logToConsole(aProperty, aParams,
u""_ns, // aSourceName
""_ns, // aSourceName
u""_ns, // aSourceLine
0, // aLineNumber
1, // aColumnNumber

Просмотреть файл

@ -191,7 +191,7 @@ void CSP_LogStrMessage(const nsAString& aMsg) {
console->LogStringMessage(msg.get());
}
void CSP_LogMessage(const nsAString& aMessage, const nsAString& aSourceName,
void CSP_LogMessage(const nsAString& aMessage, const nsACString& aSourceName,
const nsAString& aSourceLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags,
const nsACString& aCategory, uint64_t aInnerWindowID,
@ -230,13 +230,13 @@ void CSP_LogMessage(const nsAString& aMessage, const nsAString& aSourceName,
nsresult rv;
if (aInnerWindowID > 0) {
rv = error->InitWithWindowID(cspMsg, aSourceName, aSourceLine, aLineNumber,
aColumnNumber, aFlags, category,
aInnerWindowID);
rv = error->InitWithWindowID(cspMsg, NS_ConvertUTF8toUTF16(aSourceName),
aSourceLine, aLineNumber, aColumnNumber,
aFlags, category, aInnerWindowID);
} else {
rv = error->Init(cspMsg, aSourceName, aSourceLine, aLineNumber,
aColumnNumber, aFlags, category, aFromPrivateWindow,
true /* from chrome context */);
rv = error->Init(cspMsg, NS_ConvertUTF8toUTF16(aSourceName), aSourceLine,
aLineNumber, aColumnNumber, aFlags, category,
aFromPrivateWindow, true /* from chrome context */);
}
if (NS_FAILED(rv)) {
return;
@ -262,7 +262,7 @@ CSPDirective CSP_StringToCSPDirective(const nsAString& aDir) {
* Combines CSP_LogMessage and CSP_GetLocalizedStr into one call.
*/
void CSP_LogLocalizedStr(const char* aName, const nsTArray<nsString>& aParams,
const nsAString& aSourceName,
const nsACString& aSourceName,
const nsAString& aSourceLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags,
const nsACString& aCategory, uint64_t aInnerWindowID,

Просмотреть файл

@ -27,7 +27,7 @@ class Document;
/* =============== Logging =================== */
void CSP_LogLocalizedStr(const char* aName, const nsTArray<nsString>& aParams,
const nsAString& aSourceName,
const nsACString& aSourceName,
const nsAString& aSourceLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags,
const nsACString& aCategory, uint64_t aInnerWindowID,
@ -38,7 +38,7 @@ void CSP_GetLocalizedStr(const char* aName, const nsTArray<nsString>& aParams,
void CSP_LogStrMessage(const nsAString& aMsg);
void CSP_LogMessage(const nsAString& aMessage, const nsAString& aSourceName,
void CSP_LogMessage(const nsAString& aMessage, const nsACString& aSourceName,
const nsAString& aSourceLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags,
const nsACString& aCategory, uint64_t aInnerWindowID,

Просмотреть файл

@ -810,17 +810,13 @@ void nsContentSecurityManager::MeasureUnexpectedPrivilegedLoads(
nsAutoCString uriString;
if (aFinalURI) {
aFinalURI->GetAsciiSpec(uriString);
} else {
uriString.AssignLiteral("");
}
FilenameTypeAndDetails fileNameTypeAndDetails =
nsContentSecurityUtils::FilenameToFilenameType(
NS_ConvertUTF8toUTF16(uriString), true);
nsContentSecurityUtils::FilenameToFilenameType(uriString, true);
nsCString loggedFileDetails = "unknown"_ns;
if (fileNameTypeAndDetails.second.isSome()) {
loggedFileDetails.Assign(
NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value()));
loggedFileDetails.Assign(fileNameTypeAndDetails.second.value());
}
// sanitize remoteType because it may contain sensitive
// info, like URLs. e.g. `webIsolated=https://example.com`

Просмотреть файл

@ -272,23 +272,21 @@ nsCString nsContentSecurityUtils::SmartFormatCrashString(
* Telemetry Events extra data only supports 80 characters, so we optimize the
* filename to be smaller and collect more data.
*/
nsString OptimizeFileName(const nsAString& aFileName) {
nsString optimizedName(aFileName);
nsCString OptimizeFileName(const nsAString& aFileName) {
NS_ConvertUTF16toUTF8 optimizedName(aFileName);
MOZ_LOG(
sCSMLog, LogLevel::Verbose,
("Optimizing FileName: %s", NS_ConvertUTF16toUTF8(optimizedName).get()));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
("Optimizing FileName: %s", optimizedName.get()));
optimizedName.ReplaceSubstring(u".xpi!"_ns, u"!"_ns);
optimizedName.ReplaceSubstring(u"shield.mozilla.org!"_ns, u"s!"_ns);
optimizedName.ReplaceSubstring(u"mozilla.org!"_ns, u"m!"_ns);
optimizedName.ReplaceSubstring(".xpi!"_ns, "!"_ns);
optimizedName.ReplaceSubstring("shield.mozilla.org!"_ns, "s!"_ns);
optimizedName.ReplaceSubstring("mozilla.org!"_ns, "m!"_ns);
if (optimizedName.Length() > 80) {
optimizedName.Truncate(80);
}
MOZ_LOG(
sCSMLog, LogLevel::Verbose,
("Optimized FileName: %s", NS_ConvertUTF16toUTF8(optimizedName).get()));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
("Optimized FileName: %s", optimizedName.get()));
return optimizedName;
}
@ -306,7 +304,7 @@ nsString OptimizeFileName(const nsAString& aFileName) {
/* static */
FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
const nsString& fileName, bool collectAdditionalExtensionData) {
const nsACString& fileName, bool collectAdditionalExtensionData) {
// These are strings because the Telemetry Events API only accepts strings
static constexpr auto kChromeURI = "chromeuri"_ns;
static constexpr auto kResourceURI = "resourceuri"_ns;
@ -337,31 +335,33 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
}
// resource:// and chrome://
if (StringBeginsWith(fileName, u"chrome://"_ns)) {
return FilenameTypeAndDetails(kChromeURI, Some(fileName));
if (StringBeginsWith(fileName, "chrome://"_ns)) {
return FilenameTypeAndDetails(kChromeURI, Some(nsCString(fileName)));
}
if (StringBeginsWith(fileName, u"resource://"_ns)) {
return FilenameTypeAndDetails(kResourceURI, Some(fileName));
if (StringBeginsWith(fileName, "resource://"_ns)) {
return FilenameTypeAndDetails(kResourceURI, Some(nsCString(fileName)));
}
// blob: and data:
if (StringBeginsWith(fileName, u"blob:"_ns)) {
if (StringBeginsWith(fileName, "blob:"_ns)) {
return FilenameTypeAndDetails(kBlobUri, Nothing());
}
if (StringBeginsWith(fileName, u"data:text/css;extension=style;"_ns)) {
if (StringBeginsWith(fileName, "data:text/css;extension=style;"_ns)) {
return FilenameTypeAndDetails(kDataUriWebExtCStyle, Nothing());
}
if (StringBeginsWith(fileName, u"data:"_ns)) {
if (StringBeginsWith(fileName, "data:"_ns)) {
return FilenameTypeAndDetails(kDataUri, Nothing());
}
// Can't do regex matching off-main-thread
if (NS_IsMainThread()) {
NS_ConvertUTF8toUTF16 fileNameA(fileName);
// Extension as loaded via a file://
bool regexMatch;
nsTArray<nsString> regexResults;
nsresult rv = RegexEval(kExtensionRegex, fileName, /* aOnlyMatch = */ false,
regexMatch, &regexResults);
nsresult rv =
RegexEval(kExtensionRegex, fileNameA,
/* aOnlyMatch = */ false, regexMatch, &regexResults);
if (NS_FAILED(rv)) {
return FilenameTypeAndDetails(kRegexFailure, Nothing());
}
@ -376,17 +376,17 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
}
// Single File
rv = RegexEval(kSingleFileRegex, fileName, /* aOnlyMatch = */ true,
rv = RegexEval(kSingleFileRegex, fileNameA, /* aOnlyMatch = */ true,
regexMatch);
if (NS_FAILED(rv)) {
return FilenameTypeAndDetails(kRegexFailure, Nothing());
}
if (regexMatch) {
return FilenameTypeAndDetails(kSingleString, Some(fileName));
return FilenameTypeAndDetails(kSingleString, Some(nsCString(fileName)));
}
// Suspected userChromeJS script
rv = RegexEval(kUCJSRegex, fileName, /* aOnlyMatch = */ true, regexMatch);
rv = RegexEval(kUCJSRegex, fileNameA, /* aOnlyMatch = */ true, regexMatch);
if (NS_FAILED(rv)) {
return FilenameTypeAndDetails(kRegexFailure, Nothing());
}
@ -396,7 +396,7 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
}
// Something loaded via an about:// URI.
if (StringBeginsWith(fileName, u"about:"_ns)) {
if (StringBeginsWith(fileName, "about:"_ns)) {
// Remove any querystrings and such
long int desired_length = fileName.Length();
long int possible_new_length = 0;
@ -413,17 +413,17 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
auto subFileName = Substring(fileName, 0, desired_length);
return FilenameTypeAndDetails(kAboutUri, Some(subFileName));
return FilenameTypeAndDetails(kAboutUri, Some(nsCString(subFileName)));
}
// Something loaded via a moz-extension:// URI.
if (StringBeginsWith(fileName, u"moz-extension://"_ns)) {
if (StringBeginsWith(fileName, "moz-extension://"_ns)) {
if (!collectAdditionalExtensionData) {
return FilenameTypeAndDetails(kExtensionURI, Nothing());
}
nsAutoString sanitizedPathAndScheme;
sanitizedPathAndScheme.Append(u"moz-extension://["_ns);
nsAutoCString sanitizedPathAndScheme;
sanitizedPathAndScheme.Append("moz-extension://["_ns);
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), fileName);
@ -442,36 +442,37 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
nsString addOnId;
policy->GetId(addOnId);
sanitizedPathAndScheme.Append(addOnId);
sanitizedPathAndScheme.Append(u": "_ns);
sanitizedPathAndScheme.Append(policy->Name());
sanitizedPathAndScheme.Append(u"]"_ns);
sanitizedPathAndScheme.Append(NS_ConvertUTF16toUTF8(addOnId));
sanitizedPathAndScheme.Append(": "_ns);
sanitizedPathAndScheme.Append(NS_ConvertUTF16toUTF8(policy->Name()));
sanitizedPathAndScheme.Append("]"_ns);
if (policy->IsPrivileged()) {
sanitizedPathAndScheme.Append(u"P=1"_ns);
sanitizedPathAndScheme.Append("P=1"_ns);
} else {
sanitizedPathAndScheme.Append(u"P=0"_ns);
sanitizedPathAndScheme.Append("P=0"_ns);
}
} else {
sanitizedPathAndScheme.Append(u"failed finding addon by host]"_ns);
sanitizedPathAndScheme.Append("failed finding addon by host]"_ns);
}
} else {
sanitizedPathAndScheme.Append(u"can't get addon off main thread]"_ns);
sanitizedPathAndScheme.Append("can't get addon off main thread]"_ns);
}
AppendUTF8toUTF16(url.FilePath(), sanitizedPathAndScheme);
sanitizedPathAndScheme.Append(url.FilePath());
return FilenameTypeAndDetails(kExtensionURI, Some(sanitizedPathAndScheme));
}
#if defined(XP_WIN)
auto flags = mozilla::widget::WinUtils::PathTransformFlags::Default |
mozilla::widget::WinUtils::PathTransformFlags::RequireFilePath;
nsAutoString strSanitizedPath(fileName);
const NS_ConvertUTF8toUTF16 fileNameA(fileName);
nsAutoString strSanitizedPath(fileNameA);
if (widget::WinUtils::PreparePathForTelemetry(strSanitizedPath, flags)) {
DWORD cchDecodedUrl = INTERNET_MAX_URL_LENGTH;
WCHAR szOut[INTERNET_MAX_URL_LENGTH];
HRESULT hr;
SAFECALL_URLMON_FUNC(CoInternetParseUrl, fileName.get(), PARSE_SCHEMA, 0,
SAFECALL_URLMON_FUNC(CoInternetParseUrl, fileNameA.get(), PARSE_SCHEMA, 0,
szOut, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0);
if (hr == S_OK && cchDecodedUrl) {
nsAutoString sanitizedPathAndScheme;
@ -480,11 +481,12 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType(
sanitizedPathAndScheme.Append(u"://.../"_ns);
sanitizedPathAndScheme.Append(strSanitizedPath);
}
return FilenameTypeAndDetails(kSanitizedWindowsURL,
Some(sanitizedPathAndScheme));
return FilenameTypeAndDetails(
kSanitizedWindowsURL,
Some(NS_ConvertUTF16toUTF8(sanitizedPathAndScheme)));
} else {
return FilenameTypeAndDetails(kSanitizedWindowsPath,
Some(strSanitizedPath));
return FilenameTypeAndDetails(
kSanitizedWindowsPath, Some(NS_ConvertUTF16toUTF8(strSanitizedPath)));
}
}
#endif
@ -562,19 +564,18 @@ void PossiblyCrash(const char* aPrefSuffix, const char* aUnsafeCrashString,
class EvalUsageNotificationRunnable final : public Runnable {
public:
EvalUsageNotificationRunnable(bool aIsSystemPrincipal,
NS_ConvertUTF8toUTF16& aFileNameA,
uint64_t aWindowID, uint32_t aLineNumber,
uint32_t aColumnNumber)
const nsACString& aFileName, uint64_t aWindowID,
uint32_t aLineNumber, uint32_t aColumnNumber)
: mozilla::Runnable("EvalUsageNotificationRunnable"),
mIsSystemPrincipal(aIsSystemPrincipal),
mFileNameA(aFileNameA),
mFileName(aFileName),
mWindowID(aWindowID),
mLineNumber(aLineNumber),
mColumnNumber(aColumnNumber) {}
NS_IMETHOD Run() override {
nsContentSecurityUtils::NotifyEvalUsage(
mIsSystemPrincipal, mFileNameA, mWindowID, mLineNumber, mColumnNumber);
mIsSystemPrincipal, mFileName, mWindowID, mLineNumber, mColumnNumber);
return NS_OK;
}
@ -582,7 +583,7 @@ class EvalUsageNotificationRunnable final : public Runnable {
private:
bool mIsSystemPrincipal;
NS_ConvertUTF8toUTF16 mFileNameA;
nsCString mFileName;
uint64_t mWindowID;
uint32_t mLineNumber;
uint32_t mColumnNumber;
@ -686,14 +687,8 @@ bool nsContentSecurityUtils::IsEvalAllowed(JSContext* cx,
// Check the allowlist for the provided filename. getFilename is a helper
// function
nsAutoCString fileName;
uint32_t lineNumber = 0, columnNumber = 1;
nsJSUtils::GetCallingLocation(cx, fileName, &lineNumber, &columnNumber);
if (fileName.IsEmpty()) {
fileName = "unknown-file"_ns;
}
NS_ConvertUTF8toUTF16 fileNameA(fileName);
auto location = JSCallingLocation::Get(cx);
const nsCString& fileName = location.FileName();
for (const nsLiteralCString& allowlistEntry : evalAllowlist) {
// checking if current filename begins with entry, because JS Engine
// gives us additional stuff for code inside eval or Function ctor
@ -711,11 +706,13 @@ bool nsContentSecurityUtils::IsEvalAllowed(JSContext* cx,
// Send Telemetry and Log to the Console
uint64_t windowID = nsJSUtils::GetCurrentlyRunningCodeInnerWindowID(cx);
if (NS_IsMainThread()) {
nsContentSecurityUtils::NotifyEvalUsage(aIsSystemPrincipal, fileNameA,
windowID, lineNumber, columnNumber);
nsContentSecurityUtils::NotifyEvalUsage(aIsSystemPrincipal, fileName,
windowID, location.mLine,
location.mColumn);
} else {
auto runnable = new EvalUsageNotificationRunnable(
aIsSystemPrincipal, fileNameA, windowID, lineNumber, columnNumber);
aIsSystemPrincipal, fileName, windowID, location.mLine,
location.mColumn);
NS_DispatchToMainThread(runnable);
}
@ -741,7 +738,7 @@ bool nsContentSecurityUtils::IsEvalAllowed(JSContext* cx,
/* static */
void nsContentSecurityUtils::NotifyEvalUsage(bool aIsSystemPrincipal,
NS_ConvertUTF8toUTF16& aFileNameA,
const nsACString& aFileName,
uint64_t aWindowID,
uint32_t aLineNumber,
uint32_t aColumnNumber) {
@ -751,12 +748,11 @@ void nsContentSecurityUtils::NotifyEvalUsage(bool aIsSystemPrincipal,
: Telemetry::EventID::Security_Evalusage_Parentprocess;
FilenameTypeAndDetails fileNameTypeAndDetails =
FilenameToFilenameType(aFileNameA, false);
FilenameToFilenameType(aFileName, false);
mozilla::Maybe<nsTArray<EventExtraEntry>> extra;
if (fileNameTypeAndDetails.second.isSome()) {
extra = Some<nsTArray<EventExtraEntry>>({EventExtraEntry{
"fileinfo"_ns,
NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value())}});
"fileinfo"_ns, fileNameTypeAndDetails.second.value()}});
} else {
extra = Nothing();
}
@ -790,14 +786,15 @@ void nsContentSecurityUtils::NotifyEvalUsage(bool aIsSystemPrincipal,
return;
}
nsAutoString message;
AutoTArray<nsString, 1> formatStrings = {aFileNameA};
NS_ConvertUTF8toUTF16 fileNameA(aFileName);
AutoTArray<nsString, 1> formatStrings = {fileNameA};
nsresult rv = bundle->FormatStringFromName("RestrictBrowserEvalUsage",
formatStrings, message);
if (NS_FAILED(rv)) {
return;
}
rv = error->InitWithWindowID(message, aFileNameA, u""_ns, aLineNumber,
rv = error->InitWithWindowID(message, fileNameA, u""_ns, aLineNumber,
aColumnNumber, nsIScriptError::errorFlag,
"BrowserEvalUsage", aWindowID,
true /* From chrome context */);
@ -1149,7 +1146,7 @@ void EnforceXFrameOptionsCheck(nsIChannel* aChannel,
AutoTArray<nsString, 2> params = {u"x-frame-options"_ns,
u"frame-ancestors"_ns};
CSP_LogLocalizedStr("IgnoringSrcBecauseOfDirective", params,
u""_ns, // no sourcefile
""_ns, // no sourcefile
u""_ns, // no scriptsample
0, // no linenumber
1, // no columnnumber
@ -1457,10 +1454,10 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
// If we have allowed eval (because of a user configuration or more
// likely a test has requested it), and the script is an eval, allow it.
NS_ConvertUTF8toUTF16 filenameU(aFilename);
nsDependentCString filename(aFilename);
if (StaticPrefs::security_allow_eval_with_system_principal() ||
StaticPrefs::security_allow_eval_in_parent_process()) {
if (StringEndsWith(filenameU, u"> eval"_ns)) {
if (StringEndsWith(filename, "> eval"_ns)) {
return true;
}
}
@ -1493,29 +1490,29 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
return true;
}
if (StringBeginsWith(filenameU, u"chrome://"_ns)) {
if (StringBeginsWith(filename, "chrome://"_ns)) {
// If it's a chrome:// url, allow it
return true;
}
if (StringBeginsWith(filenameU, u"resource://"_ns)) {
if (StringBeginsWith(filename, "resource://"_ns)) {
// If it's a resource:// url, allow it
return true;
}
if (StringBeginsWith(filenameU, u"file://"_ns)) {
if (StringBeginsWith(filename, "file://"_ns)) {
// We will temporarily allow all file:// URIs through for now
return true;
}
if (StringBeginsWith(filenameU, u"jar:file://"_ns)) {
if (StringBeginsWith(filename, "jar:file://"_ns)) {
// We will temporarily allow all jar URIs through for now
return true;
}
if (filenameU.Equals(u"about:sync-log"_ns)) {
if (filename.Equals("about:sync-log"_ns)) {
// about:sync-log runs in the parent process and displays a directory
// listing. The listing has inline javascript that executes on load.
return true;
}
if (StringBeginsWith(filenameU, u"moz-extension://"_ns)) {
if (StringBeginsWith(filename, "moz-extension://"_ns)) {
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aFilename);
if (!NS_FAILED(rv) && NS_IsMainThread()) {
@ -1544,11 +1541,11 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
auto kAllowedFilenamesExact = {
// Allow through the injection provided by about:sync addon
u"data:,new function() {\n const { AboutSyncRedirector } = ChromeUtils.import(\"chrome://aboutsync/content/AboutSyncRedirector.js\");\n AboutSyncRedirector.register();\n}"_ns,
"data:,new function() {\n const { AboutSyncRedirector } = ChromeUtils.import(\"chrome://aboutsync/content/AboutSyncRedirector.js\");\n AboutSyncRedirector.register();\n}"_ns,
};
for (auto allowedFilename : kAllowedFilenamesExact) {
if (filenameU == allowedFilename) {
if (filename == allowedFilename) {
return true;
}
}
@ -1556,16 +1553,16 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
auto kAllowedFilenamesPrefix = {
// Until 371900 is fixed, we need to do something about about:downloads
// and this is the most reasonable. See 1727770
u"about:downloads"_ns,
"about:downloads"_ns,
// We think this is the same problem as about:downloads
u"about:preferences"_ns, u"about:settings"_ns,
"about:preferences"_ns, "about:settings"_ns,
// Browser console will give a filename of 'debugger' See 1763943
// Sometimes it's 'debugger eager eval code', other times just 'debugger
// eval code'
u"debugger"_ns};
"debugger"_ns};
for (auto allowedFilenamePrefix : kAllowedFilenamesPrefix) {
if (StringBeginsWith(filenameU, allowedFilenamePrefix)) {
if (StringBeginsWith(filename, allowedFilenamePrefix)) {
return true;
}
}
@ -1576,7 +1573,7 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
// Send Telemetry
FilenameTypeAndDetails fileNameTypeAndDetails =
FilenameToFilenameType(filenameU, true);
FilenameToFilenameType(filename, true);
Telemetry::EventID eventType =
Telemetry::EventID::Security_Javascriptload_Parentprocess;
@ -1584,8 +1581,7 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
mozilla::Maybe<nsTArray<EventExtraEntry>> extra;
if (fileNameTypeAndDetails.second.isSome()) {
extra = Some<nsTArray<EventExtraEntry>>({EventExtraEntry{
"fileinfo"_ns,
NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value())}});
"fileinfo"_ns, fileNameTypeAndDetails.second.value()}});
} else {
extra = Nothing();
}
@ -1601,7 +1597,7 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
auto crashString = nsContentSecurityUtils::SmartFormatCrashString(
aFilename,
fileNameTypeAndDetails.second.isSome()
? NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value()).get()
? fileNameTypeAndDetails.second.value().get()
: "(None)",
"Blocking a script load %s from file %s");
MOZ_CRASH_UNSAFE_PRINTF("%s", crashString.get());
@ -1612,7 +1608,7 @@ bool nsContentSecurityUtils::ValidateScriptFilename(JSContext* cx,
// in Event Telemetry and have received data review.
if (fileNameTypeAndDetails.second.isSome()) {
PossiblyCrash("js_load_1", aFilename,
NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value()));
fileNameTypeAndDetails.second.value());
} else {
PossiblyCrash("js_load_1", aFilename, "(None)"_ns);
}
@ -1659,7 +1655,8 @@ void nsContentSecurityUtils::LogMessageToConsole(nsIHttpChannel* aChannel,
}
nsContentUtils::ReportToConsoleByWindowID(
localizedMsg, nsIScriptError::warningFlag, "Security"_ns, windowID, uri);
localizedMsg, nsIScriptError::warningFlag, "Security"_ns, windowID,
SourceLocation{uri.get()});
}
/* static */

Просмотреть файл

@ -24,7 +24,7 @@ class Document;
class Element;
} // namespace mozilla::dom
using FilenameTypeAndDetails = std::pair<nsCString, mozilla::Maybe<nsString>>;
using FilenameTypeAndDetails = std::pair<nsCString, mozilla::Maybe<nsCString>>;
class nsContentSecurityUtils {
public:
@ -39,9 +39,8 @@ class nsContentSecurityUtils {
static bool IsEvalAllowed(JSContext* cx, bool aIsSystemPrincipal,
const nsAString& aScript);
static void NotifyEvalUsage(bool aIsSystemPrincipal,
NS_ConvertUTF8toUTF16& aFileNameA,
uint64_t aWindowID, uint32_t aLineNumber,
uint32_t aColumnNumber);
const nsACString& aFileName, uint64_t aWindowID,
uint32_t aLineNumber, uint32_t aColumnNumber);
// Helper function for various checks:
// This function detects profiles with userChrome.js or extension signatures
@ -80,7 +79,7 @@ class nsContentSecurityUtils {
// Public only for testing
static FilenameTypeAndDetails FilenameToFilenameType(
const nsString& fileName, bool collectAdditionalExtensionData);
const nsACString& fileName, bool collectAdditionalExtensionData);
static char* SmartFormatCrashString(const char* str);
static char* SmartFormatCrashString(char* str);
static nsCString SmartFormatCrashString(const char* part1, const char* part2,

Просмотреть файл

@ -843,8 +843,8 @@ void nsHTTPSOnlyUtils::LogMessage(const nsAString& aMessage, uint32_t aFlags,
}
if (windowId) {
// Send to content console
nsContentUtils::ReportToConsoleByWindowID(message, aFlags, category,
windowId, aURI);
nsContentUtils::ReportToConsoleByWindowID(
message, aFlags, category, windowId, mozilla::SourceLocation(aURI));
} else {
// Send to browser console
bool isPrivateWin = aLoadInfo->GetOriginAttributes().IsPrivateBrowsing();

Просмотреть файл

@ -115,9 +115,9 @@ static void LogMixedContentMessage(
messageLookupKey.get(), params,
localizedMsg);
nsContentUtils::ReportToConsoleByWindowID(localizedMsg, severityFlag,
messageCategory, aInnerWindowID,
aRequestingLocation);
nsContentUtils::ReportToConsoleByWindowID(
localizedMsg, severityFlag, messageCategory, aInnerWindowID,
SourceLocation(aRequestingLocation));
}
/* nsIChannelEventSink implementation
@ -802,7 +802,7 @@ nsresult nsMixedContentBlocker::ShouldLoad(bool aHadInsecureImageRedirect,
CopyUTF8toUTF16(spec, *params.AppendElement());
CSP_LogLocalizedStr("blockAllMixedContent", params,
u""_ns, // aSourceFile
""_ns, // aSourceFile
u""_ns, // aScriptSample
0, // aLineNumber
1, // aColumnNumber

Просмотреть файл

@ -46,14 +46,14 @@ static constexpr auto kOther = "other"_ns;
TEST(FilenameEvalParser, ResourceChrome)
{
{
constexpr auto str = u"chrome://firegestures/content/browser.js"_ns;
constexpr auto str = "chrome://firegestures/content/browser.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kChromeURI && ret.second.isSome() &&
ret.second.value() == str);
}
{
constexpr auto str = u"resource://firegestures/content/browser.js"_ns;
constexpr auto str = "resource://firegestures/content/browser.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kResourceURI && ret.second.isSome() &&
@ -64,25 +64,25 @@ TEST(FilenameEvalParser, ResourceChrome)
TEST(FilenameEvalParser, BlobData)
{
{
constexpr auto str = u"blob://000-000"_ns;
constexpr auto str = "blob://000-000"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kBlobUri && !ret.second.isSome());
}
{
constexpr auto str = u"blob:000-000"_ns;
constexpr auto str = "blob:000-000"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kBlobUri && !ret.second.isSome());
}
{
constexpr auto str = u"data://blahblahblah"_ns;
constexpr auto str = "data://blahblahblah"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kDataUri && !ret.second.isSome());
}
{
constexpr auto str = u"data:blahblahblah"_ns;
constexpr auto str = "data:blahblahblah"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kDataUri && !ret.second.isSome());
@ -93,20 +93,20 @@ TEST(FilenameEvalParser, MozExtension)
{
{ // Test shield.mozilla.org replacing
constexpr auto str =
u"jar:file:///c:/users/bob/appdata/roaming/mozilla/firefox/profiles/"
u"foo/"
"jar:file:///c:/users/bob/appdata/roaming/mozilla/firefox/profiles/"
"foo/"
"extensions/federated-learning@shield.mozilla.org.xpi!/experiments/"
"study/api.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kMozillaExtensionFile &&
ret.second.value() ==
u"federated-learning@s!/experiments/study/api.js"_ns);
"federated-learning@s!/experiments/study/api.js"_ns);
}
{ // Test mozilla.org replacing
constexpr auto str =
u"jar:file:///c:/users/bob/appdata/roaming/mozilla/firefox/profiles/"
u"foo/"
"jar:file:///c:/users/bob/appdata/roaming/mozilla/firefox/profiles/"
"foo/"
"extensions/federated-learning@shigeld.mozilla.org.xpi!/experiments/"
"study/api.js"_ns;
FilenameTypeAndDetails ret =
@ -114,20 +114,19 @@ TEST(FilenameEvalParser, MozExtension)
ASSERT_TRUE(
ret.first == kMozillaExtensionFile &&
ret.second.value() ==
nsLiteralString(
u"federated-learning@shigeld.m!/experiments/study/api.js"));
"federated-learning@shigeld.m!/experiments/study/api.js"_ns);
}
{ // Test truncating
constexpr auto str =
u"jar:file:///c:/users/bob/appdata/roaming/mozilla/firefox/profiles/"
u"foo/"
"jar:file:///c:/users/bob/appdata/roaming/mozilla/firefox/profiles/"
"foo/"
"extensions/federated-learning@shigeld.mozilla.org.xpi!/experiments/"
"study/apiiiiiiiiiiiiiiiiiiiiiiiiiiiiii.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kMozillaExtensionFile &&
ret.second.value() ==
u"federated-learning@shigeld.m!/experiments/"
"federated-learning@shigeld.m!/experiments/"
"study/apiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"_ns);
}
}
@ -135,26 +134,26 @@ TEST(FilenameEvalParser, MozExtension)
TEST(FilenameEvalParser, UserChromeJS)
{
{
constexpr auto str = u"firegestures/content/browser.uc.js"_ns;
constexpr auto str = "firegestures/content/browser.uc.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kSuspectedUserChromeJS && !ret.second.isSome());
}
{
constexpr auto str = u"firegestures/content/browser.uc.js?"_ns;
constexpr auto str = "firegestures/content/browser.uc.js?"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kSuspectedUserChromeJS && !ret.second.isSome());
}
{
constexpr auto str = u"firegestures/content/browser.uc.js?243244224"_ns;
constexpr auto str = "firegestures/content/browser.uc.js?243244224"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kSuspectedUserChromeJS && !ret.second.isSome());
}
{
constexpr auto str =
u"file:///b:/fxprofiles/mark/chrome/"
"file:///b:/fxprofiles/mark/chrome/"
"addbookmarkherewithmiddleclick.uc.js?1558444389291"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
@ -165,14 +164,14 @@ TEST(FilenameEvalParser, UserChromeJS)
TEST(FilenameEvalParser, SingleFile)
{
{
constexpr auto str = u"browser.uc.js?2456"_ns;
constexpr auto str = "browser.uc.js?2456"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kSingleString && ret.second.isSome() &&
ret.second.value() == str);
}
{
constexpr auto str = u"debugger"_ns;
constexpr auto str = "debugger"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kSingleString && ret.second.isSome() &&
@ -183,13 +182,13 @@ TEST(FilenameEvalParser, SingleFile)
TEST(FilenameEvalParser, Other)
{
{
constexpr auto str = u"firegestures--content"_ns;
constexpr auto str = "firegestures--content"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kOther && !ret.second.isSome());
}
{
constexpr auto str = u"gallop://thing/fire"_ns;
constexpr auto str = "gallop://thing/fire"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -200,7 +199,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"gallop://fire"_ns;
constexpr auto str = "gallop://fire"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -211,7 +210,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"firegestures/content"_ns;
constexpr auto str = "firegestures/content"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -222,7 +221,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"firegestures\\content"_ns;
constexpr auto str = "firegestures\\content"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -233,7 +232,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"/home/tom/files/thing"_ns;
constexpr auto str = "/home/tom/files/thing"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -244,7 +243,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"file://c/uers/tom/file.txt"_ns;
constexpr auto str = "file://c/uers/tom/file.txt"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -255,7 +254,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"c:/uers/tom/file.txt"_ns;
constexpr auto str = "c:/uers/tom/file.txt"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -266,7 +265,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"http://example.com/"_ns;
constexpr auto str = "http://example.com/"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -277,7 +276,7 @@ TEST(FilenameEvalParser, Other)
#endif
}
{
constexpr auto str = u"http://example.com/thing.html"_ns;
constexpr auto str = "http://example.com/thing.html"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
#if defined(XP_WIN)
@ -327,13 +326,13 @@ TEST(FilenameEvalParser, WebExtensionPathParser)
w->SetActive(true, eR);
constexpr auto str =
u"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/file.js"_ns;
"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/file.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, true);
ASSERT_TRUE(ret.first == kExtensionURI &&
ret.second.value() ==
u"moz-extension://[gtesttestextension@mozilla.org: "
"moz-extension://[gtesttestextension@mozilla.org: "
"gtest Test Extension]P=0/path/to/file.js"_ns);
w->SetActive(false, eR);
@ -376,13 +375,13 @@ TEST(FilenameEvalParser, WebExtensionPathParser)
w->SetActive(true, eR);
constexpr auto str =
u"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/file.js"_ns;
"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/file.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, true);
ASSERT_TRUE(ret.first == kExtensionURI &&
ret.second.value() ==
u"moz-extension://[gtesttestextension@mozilla.org: "
"moz-extension://[gtesttestextension@mozilla.org: "
"gtest Test Extension]P=1/path/to/file.js"_ns);
w->SetActive(false, eR);
@ -391,31 +390,30 @@ TEST(FilenameEvalParser, WebExtensionPathParser)
}
{
constexpr auto str =
u"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/file.js"_ns;
"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/file.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kExtensionURI && !ret.second.isSome());
}
{
constexpr auto str =
u"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/file.js"_ns;
"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/file.js"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, true);
ASSERT_TRUE(
ret.first == kExtensionURI &&
ret.second.value() ==
nsLiteralString(
u"moz-extension://[failed finding addon by host]/file.js"));
"moz-extension://[failed finding addon by host]/file.js"_ns);
}
{
constexpr auto str =
u"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/"
"moz-extension://e37c3c08-beac-a04b-8032-c4f699a1a856/path/to/"
"file.js?querystringx=6"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, true);
ASSERT_TRUE(ret.first == kExtensionURI &&
ret.second.value() ==
u"moz-extension://[failed finding addon "
"moz-extension://[failed finding addon "
"by host]/path/to/file.js"_ns);
}
}
@ -423,31 +421,31 @@ TEST(FilenameEvalParser, WebExtensionPathParser)
TEST(FilenameEvalParser, AboutPageParser)
{
{
constexpr auto str = u"about:about"_ns;
constexpr auto str = "about:about"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kAboutUri &&
ret.second.value() == u"about:about"_ns);
ret.second.value() == "about:about"_ns);
}
{
constexpr auto str = u"about:about?hello"_ns;
constexpr auto str = "about:about?hello"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kAboutUri &&
ret.second.value() == u"about:about"_ns);
ret.second.value() == "about:about"_ns);
}
{
constexpr auto str = u"about:about#mom"_ns;
constexpr auto str = "about:about#mom"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kAboutUri &&
ret.second.value() == u"about:about"_ns);
ret.second.value() == "about:about"_ns);
}
{
constexpr auto str = u"about:about?hello=there#mom"_ns;
constexpr auto str = "about:about?hello=there#mom"_ns;
FilenameTypeAndDetails ret =
nsContentSecurityUtils::FilenameToFilenameType(str, false);
ASSERT_TRUE(ret.first == kAboutUri &&
ret.second.value() == u"about:about"_ns);
ret.second.value() == "about:about"_ns);
}
}

Просмотреть файл

@ -15,8 +15,6 @@
#include "mozilla/dom/TrustedTypePolicy.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "jsapi.h"
namespace mozilla::dom {
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(TrustedTypePolicyFactory, mGlobalObject)
@ -31,17 +29,7 @@ constexpr size_t kCreatePolicyCSPViolationMaxSampleLength = 40;
static CSPViolationData CreateCSPViolationData(JSContext* aJSContext,
uint32_t aPolicyIndex,
const nsAString& aPolicyName) {
JS::AutoFilename autoFilename;
nsAutoString fileName;
uint32_t lineNumber{0};
JS::ColumnNumberOneOrigin columnNumber;
if (JS::DescribeScriptedCaller(aJSContext, &autoFilename, &lineNumber,
&columnNumber)) {
if (const char* file = autoFilename.get()) {
CopyUTF8toUTF16(nsDependentCString(file), fileName);
}
}
auto caller = JSCallingLocation::Get(aJSContext);
const nsAString& sample =
Substring(aPolicyName, /* aStartPos */ 0,
/* aLength */ kCreatePolicyCSPViolationMaxSampleLength);
@ -53,9 +41,9 @@ static CSPViolationData CreateCSPViolationData(JSContext* aJSContext,
CSPViolationData::Resource{
CSPViolationData::BlockedContentSource::TrustedTypesPolicy},
nsIContentSecurityPolicy::TRUSTED_TYPES_DIRECTIVE,
fileName,
lineNumber,
columnNumber.oneOriginValue(),
caller.FileName(),
caller.mLine,
caller.mColumn,
/* aElement */ nullptr,
sample};
}

Просмотреть файл

@ -109,10 +109,7 @@ CancelChannelRunnable::Run() {
}
FetchEvent::FetchEvent(EventTarget* aOwner)
: ExtendableEvent(aOwner),
mPreventDefaultLineNumber(0),
mPreventDefaultColumnNumber(1),
mWaitToRespond(false) {}
: ExtendableEvent(aOwner), mWaitToRespond(false) {}
FetchEvent::~FetchEvent() = default;
@ -767,11 +764,7 @@ void FetchEvent::RespondWith(JSContext* aCx, Promise& aArg, ErrorResult& aRv) {
// Record where respondWith() was called in the script so we can include the
// information in any error reporting. We should be guaranteed not to get
// a file:// string here because service workers require http/https.
nsCString spec;
uint32_t line = 0;
uint32_t column = 1;
nsJSUtils::GetCallingLocation(aCx, spec, &line, &column);
auto location = JSCallingLocation::Get(aCx);
SafeRefPtr<InternalRequest> ir = mRequest->GetInternalRequest();
nsAutoCString requestURL;
@ -784,12 +777,14 @@ void FetchEvent::RespondWith(JSContext* aCx, Promise& aArg, ErrorResult& aRv) {
RefPtr<RespondWithHandler> handler = new RespondWithHandler(
mChannel, mRegistration, mRequest->Mode(), ir->IsClientRequest(),
mRequest->Redirect(), mScriptSpec, NS_ConvertUTF8toUTF16(requestURL),
ir->GetFragment(), spec, line, column);
ir->GetFragment(), location.FileName(), location.mLine,
location.mColumn);
aArg.AppendNativeHandler(handler);
// mRespondWithHandler can be nullptr for self-dispatched FetchEvent.
} else if (mRespondWithHandler) {
mRespondWithHandler->RespondWithCalledAt(spec, line, column);
mRespondWithHandler->RespondWithCalledAt(location.FileName(),
location.mLine, location.mColumn);
aArg.AppendNativeHandler(mRespondWithHandler);
mRespondWithHandler = nullptr;
}
@ -804,22 +799,20 @@ void FetchEvent::PreventDefault(JSContext* aCx, CallerType aCallerType) {
MOZ_ASSERT(aCallerType != CallerType::System,
"Since when do we support system-principal service workers?");
if (mPreventDefaultScriptSpec.IsEmpty()) {
if (!mPreventDefaultLocation) {
// Note when the FetchEvent might have been canceled by script, but don't
// actually log the location until we are sure it matters. This is
// determined in ServiceWorkerPrivate.cpp. We only remember the first
// call to preventDefault() as its the most likely to have actually canceled
// the event.
nsJSUtils::GetCallingLocation(aCx, mPreventDefaultScriptSpec,
&mPreventDefaultLineNumber,
&mPreventDefaultColumnNumber);
mPreventDefaultLocation = JSCallingLocation::Get(aCx);
}
Event::PreventDefault(aCx, aCallerType);
}
void FetchEvent::ReportCanceled() {
MOZ_ASSERT(!mPreventDefaultScriptSpec.IsEmpty());
MOZ_ASSERT(mPreventDefaultLocation);
SafeRefPtr<InternalRequest> ir = mRequest->GetInternalRequest();
nsAutoCString url;
@ -832,14 +825,14 @@ void FetchEvent::ReportCanceled() {
// CopyUTF8toUTF16(url, requestURL);
if (mChannel) {
::AsyncLog(mChannel.get(), mPreventDefaultScriptSpec,
mPreventDefaultLineNumber, mPreventDefaultColumnNumber,
::AsyncLog(mChannel.get(), mPreventDefaultLocation.FileName(),
mPreventDefaultLocation.mLine, mPreventDefaultLocation.mColumn,
"InterceptionCanceledWithURL"_ns, requestURL);
// mRespondWithHandler could be nullptr for self-dispatched FetchEvent.
} else if (mRespondWithHandler) {
mRespondWithHandler->ReportCanceled(mPreventDefaultScriptSpec,
mPreventDefaultLineNumber,
mPreventDefaultColumnNumber);
mRespondWithHandler->ReportCanceled(mPreventDefaultLocation.FileName(),
mPreventDefaultLocation.mLine,
mPreventDefaultLocation.mColumn);
mRespondWithHandler = nullptr;
}
}
@ -848,9 +841,7 @@ namespace {
class WaitUntilHandler final : public PromiseNativeHandler {
const nsCString mScope;
nsString mSourceSpec;
uint32_t mLine;
uint32_t mColumn;
JSCallingLocation mLocation;
nsString mRejectValue;
~WaitUntilHandler() = default;
@ -860,13 +851,8 @@ class WaitUntilHandler final : public PromiseNativeHandler {
WaitUntilHandler(WorkerPrivate* aWorkerPrivate, JSContext* aCx)
: mScope(GetCurrentThreadWorkerPrivate()->ServiceWorkerScope()),
mLine(0),
mColumn(1) {
mLocation(JSCallingLocation::Get(aCx)) {
MOZ_ASSERT(GetCurrentThreadWorkerPrivate());
// Save the location of the waitUntil() call itself as a fallback
// in case the rejection value does not contain any location info.
nsJSUtils::GetCallingLocation(aCx, mSourceSpec, &mLine, &mColumn);
}
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValu,
@ -879,7 +865,7 @@ class WaitUntilHandler final : public PromiseNativeHandler {
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(workerPrivate);
nsString spec;
nsCString spec;
uint32_t line = 0;
uint32_t column = 0;
nsContentUtils::ExtractErrorValues(aCx, aValue, spec, &line, &column,
@ -887,9 +873,9 @@ class WaitUntilHandler final : public PromiseNativeHandler {
// only use the extracted location if we found one
if (!spec.IsEmpty()) {
mSourceSpec = spec;
mLine = line;
mColumn = column;
mLocation.mResource = AsVariant(std::move(spec));
mLocation.mLine = line;
mLocation.mColumn = column;
}
MOZ_ALWAYS_SUCCEEDS(workerPrivate->DispatchToMainThread(
@ -920,8 +906,9 @@ class WaitUntilHandler final : public PromiseNativeHandler {
// because there is no documeny yet, and the navigation is no longer
// being intercepted.
swm->ReportToAllClients(mScope, message, mSourceSpec, u""_ns, mLine,
mColumn, nsIScriptError::errorFlag);
swm->ReportToAllClients(mScope, message, mLocation.FileName(), u""_ns,
mLocation.mLine, mLocation.mColumn,
nsIScriptError::errorFlag);
}
};

Просмотреть файл

@ -140,11 +140,9 @@ class FetchEvent final : public ExtendableEvent {
RefPtr<Promise> mHandled;
RefPtr<Promise> mPreloadResponse;
nsCString mScriptSpec;
nsCString mPreventDefaultScriptSpec;
nsString mClientId;
nsString mResultingClientId;
uint32_t mPreventDefaultLineNumber;
uint32_t mPreventDefaultColumnNumber;
JSCallingLocation mPreventDefaultLocation;
bool mWaitToRespond;
protected:

Просмотреть файл

@ -1447,7 +1447,7 @@ already_AddRefed<ServiceWorkerManager> ServiceWorkerManager::GetInstance() {
void ServiceWorkerManager::ReportToAllClients(
const nsCString& aScope, const nsString& aMessage,
const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber,
const nsCString& aFilename, const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags) {
ConsoleUtils::ReportForServiceWorkerScope(
NS_ConvertUTF8toUTF16(aScope), aMessage, aFilename, aLineNumber,
@ -1458,7 +1458,7 @@ void ServiceWorkerManager::ReportToAllClients(
void ServiceWorkerManager::LocalizeAndReportToAllClients(
const nsCString& aScope, const char* aStringKey,
const nsTArray<nsString>& aParamArray, uint32_t aFlags,
const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber,
const nsCString& aFilename, const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber) {
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
if (!swm) {
@ -1479,8 +1479,8 @@ void ServiceWorkerManager::LocalizeAndReportToAllClients(
void ServiceWorkerManager::HandleError(
JSContext* aCx, nsIPrincipal* aPrincipal, const nsCString& aScope,
const nsString& aWorkerURL, const nsString& aMessage,
const nsString& aFilename, const nsString& aLine, uint32_t aLineNumber,
const nsCString& aWorkerURL, const nsString& aMessage,
const nsCString& aFilename, const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags, JSExnType aExnType) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aPrincipal);

Просмотреть файл

@ -180,7 +180,7 @@ class ServiceWorkerManager final : public nsIServiceWorkerManager,
* localizing the error.
*/
void ReportToAllClients(const nsCString& aScope, const nsString& aMessage,
const nsString& aFilename, const nsString& aLine,
const nsCString& aFilename, const nsString& aLine,
uint32_t aLineNumber, uint32_t aColumnNumber,
uint32_t aFlags);
@ -204,14 +204,14 @@ class ServiceWorkerManager final : public nsIServiceWorkerManager,
static void LocalizeAndReportToAllClients(
const nsCString& aScope, const char* aStringKey,
const nsTArray<nsString>& aParamArray, uint32_t aFlags = 0x0,
const nsString& aFilename = u""_ns, const nsString& aLine = u""_ns,
const nsCString& aFilename = ""_ns, const nsString& aLine = u""_ns,
uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0);
// Always consumes the error by reporting to consoles of all controlled
// documents.
void HandleError(JSContext* aCx, nsIPrincipal* aPrincipal,
const nsCString& aScope, const nsString& aWorkerURL,
const nsString& aMessage, const nsString& aFilename,
const nsCString& aScope, const nsCString& aWorkerURL,
const nsString& aMessage, const nsCString& aFilename,
const nsString& aLine, uint32_t aLineNumber,
uint32_t aColumnNumber, uint32_t aFlags, JSExnType aExnType);

Просмотреть файл

@ -1575,8 +1575,8 @@ void ServiceWorkerPrivate::ErrorReceived(const ErrorValue& aError) {
ServiceWorkerInfo* info = mInfo;
swm->HandleError(nullptr, info->Principal(), info->Scope(),
NS_ConvertUTF8toUTF16(info->ScriptSpec()), u""_ns, u""_ns,
u""_ns, 0, 0, nsIScriptError::errorFlag, JSEXN_ERR);
info->ScriptSpec(), u""_ns, ""_ns, u""_ns, 0, 0,
nsIScriptError::errorFlag, JSEXN_ERR);
}
void ServiceWorkerPrivate::Terminated() {

Просмотреть файл

@ -387,7 +387,7 @@ void ServiceWorkerUpdateJob::ComparisonResult(nsresult aStatus,
message, nsContentUtils::eDOM_PROPERTIES,
"ServiceWorkerScopePathMismatch", reportScope, reportMaxPrefix);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to format localized string");
swm->ReportToAllClients(mScope, message, u""_ns, u""_ns, 0, 0,
swm->ReportToAllClients(mScope, message, ""_ns, u""_ns, 0, 0,
nsIScriptError::errorFlag);
FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
return;

Просмотреть файл

@ -6,6 +6,7 @@
#include "mozilla/dom/SVGScriptElement.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/FetchPriority.h"
#include "nsGkAtoms.h"
#include "nsNetUtil.h"
@ -130,6 +131,8 @@ void SVGScriptElement::FreezeExecutionAttrs(const Document* aOwnerDoc) {
mStringAttributes[XLINK_HREF].GetAnimValue(src, this);
}
SourceLocation loc{OwnerDoc()->GetDocumentURI(), GetScriptLineNumber(),
GetScriptColumnNumber().oneOriginValue()};
// Empty src should be treated as invalid URL.
if (!src.IsEmpty()) {
NS_NewURI(getter_AddRefs(mUri), src, nullptr, GetBaseURI());
@ -138,20 +141,17 @@ void SVGScriptElement::FreezeExecutionAttrs(const Document* aOwnerDoc) {
AutoTArray<nsString, 2> params = {
isHref ? u"href"_ns : u"xlink:href"_ns, src};
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "SVG"_ns, OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES, "ScriptSourceInvalidUri", params,
nullptr, u""_ns, GetScriptLineNumber(),
GetScriptColumnNumber().oneOriginValue());
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "SVG"_ns,
OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES,
"ScriptSourceInvalidUri", params, loc);
}
} else {
AutoTArray<nsString, 1> params = {isHref ? u"href"_ns : u"xlink:href"_ns};
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "SVG"_ns, OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES, "ScriptSourceEmpty", params, nullptr,
u""_ns, GetScriptLineNumber(),
GetScriptColumnNumber().oneOriginValue());
nsContentUtils::eDOM_PROPERTIES, "ScriptSourceEmpty", params, loc);
}
// At this point mUri will be null for invalid URLs.

Просмотреть файл

@ -19,7 +19,7 @@ dictionary CSPReportProperties {
SecurityPolicyViolationEventDisposition disposition = "report";
long status-code = 0;
DOMString source-file;
UTF8String source-file;
DOMString script-sample;
long line-number;
long column-number;

Просмотреть файл

@ -20,7 +20,7 @@ interface FeaturePolicy {
Exposed=Window]
interface FeaturePolicyViolationReportBody : ReportBody {
readonly attribute DOMString featureId;
readonly attribute DOMString? sourceFile;
readonly attribute UTF8String? sourceFile;
readonly attribute long? lineNumber;
readonly attribute long? columnNumber;
readonly attribute DOMString disposition;

Просмотреть файл

@ -52,7 +52,7 @@ interface DeprecationReportBody : ReportBody {
// here.
readonly attribute DOMTimeStamp? anticipatedRemoval;
readonly attribute DOMString message;
readonly attribute DOMString? sourceFile;
readonly attribute UTF8String? sourceFile;
readonly attribute unsigned long? lineNumber;
readonly attribute unsigned long? columnNumber;
};
@ -78,7 +78,7 @@ interface CSPViolationReportBody : ReportBody {
readonly attribute USVString? blockedURL;
readonly attribute DOMString effectiveDirective;
readonly attribute DOMString originalPolicy;
readonly attribute USVString? sourceFile;
readonly attribute UTF8String? sourceFile;
readonly attribute DOMString? sample;
readonly attribute SecurityPolicyViolationEventDisposition disposition;
readonly attribute unsigned short statusCode;

Просмотреть файл

@ -40,6 +40,8 @@ dictionary SecurityPolicyViolationEventInit : EventInit
DOMString violatedDirective = "";
DOMString effectiveDirective = "";
DOMString originalPolicy = "";
// TODO: We could avoid some string copies if these were USVStrings or
// UTF8Strings, see https://github.com/w3c/webappsec-csp/issues/674
DOMString sourceFile = "";
DOMString sample = "";
SecurityPolicyViolationEventDisposition disposition = "enforce";

Просмотреть файл

@ -1780,7 +1780,7 @@ nsresult WebSocketImpl::Init(nsIGlobalObject* aWindowGlobal, JSContext* aCx,
params.AppendElement(u"wss"_ns);
CSP_LogLocalizedStr("upgradeInsecureRequest", params,
u""_ns, // aSourceFile
""_ns, // aSourceFile
u""_ns, // aScriptSample
0, // aLineNumber
1, // aColumnNumber

Просмотреть файл

@ -475,14 +475,14 @@ MOZ_CAN_RUN_SCRIPT bool InterruptCallback(JSContext* aCx) {
class LogViolationDetailsRunnable final : public WorkerMainThreadRunnable {
uint16_t mViolationType;
nsString mFileName;
nsCString mFileName;
uint32_t mLineNum;
uint32_t mColumnNum;
nsString mScriptSample;
public:
LogViolationDetailsRunnable(WorkerPrivate* aWorker, uint16_t aViolationType,
const nsString& aFileName, uint32_t aLineNum,
const nsCString& aFileName, uint32_t aLineNum,
uint32_t aColumnNum,
const nsAString& aScriptSample)
: WorkerMainThreadRunnable(aWorker,
@ -531,22 +531,11 @@ bool ContentSecurityPolicyAllows(JSContext* aCx, JS::RuntimeCode aKind,
}
if (reportViolation) {
nsString fileName;
uint32_t lineNum = 0;
JS::ColumnNumberOneOrigin columnNum;
JS::AutoFilename file;
if (JS::DescribeScriptedCaller(aCx, &file, &lineNum, &columnNum) &&
file.get()) {
CopyUTF8toUTF16(MakeStringSpan(file.get()), fileName);
} else {
MOZ_ASSERT(!JS_IsExceptionPending(aCx));
}
auto caller = JSCallingLocation::Get(aCx);
RefPtr<LogViolationDetailsRunnable> runnable =
new LogViolationDetailsRunnable(worker, violationType, fileName,
lineNum, columnNum.oneOriginValue(),
scriptSample);
new LogViolationDetailsRunnable(worker, violationType,
caller.FileName(), caller.mLine,
caller.mColumn, scriptSample);
ErrorResult rv;
runnable->Dispatch(worker, Killing, rv);

Просмотреть файл

@ -170,7 +170,8 @@ bool WorkerScriptTimeoutHandler::Call(const char* aExecutionReason) {
JSContext* cx = aes.cx();
JS::CompileOptions options(cx);
options.setFileAndLine(mFileName.get(), mLineNo).setNoScriptRval(true);
options.setFileAndLine(mCaller.FileName().get(), mCaller.mLine)
.setNoScriptRval(true);
options.setIntroductionType("domTimer");
JS::Rooted<JS::Value> unused(cx);
@ -1156,9 +1157,7 @@ namespace {
class ReportFetchListenerWarningRunnable final : public Runnable {
const nsCString mScope;
nsString mSourceSpec;
uint32_t mLine;
uint32_t mColumn;
mozilla::JSCallingLocation mCaller;
public:
explicit ReportFetchListenerWarningRunnable(const nsString& aScope)
@ -1169,7 +1168,7 @@ class ReportFetchListenerWarningRunnable final : public Runnable {
JSContext* cx = workerPrivate->GetJSContext();
MOZ_ASSERT(cx);
nsJSUtils::GetCallingLocation(cx, mSourceSpec, &mLine, &mColumn);
mCaller = JSCallingLocation::Get(cx);
}
NS_IMETHOD
@ -1178,7 +1177,8 @@ class ReportFetchListenerWarningRunnable final : public Runnable {
ServiceWorkerManager::LocalizeAndReportToAllClients(
mScope, "ServiceWorkerNoFetchHandler", nsTArray<nsString>{},
nsIScriptError::warningFlag, mSourceSpec, u""_ns, mLine, mColumn);
nsIScriptError::warningFlag, mCaller.FileName(), u""_ns, mCaller.mLine,
mCaller.mColumn);
return NS_OK;
}

Просмотреть файл

@ -696,7 +696,7 @@ nsresult XULContentSinkImpl::OpenScript(const char16_t** aAttributes,
u"Versioned JavaScripts are no longer supported. "
"Please remove the version parameter."_ns,
nsIScriptError::errorFlag, "XUL Document"_ns, nullptr,
mDocumentURL, u""_ns, aLineNumber);
SourceLocation(mDocumentURL.get()));
isJavaScript = false;
} else if (rv != NS_ERROR_INVALID_ARG) {
return rv;

Просмотреть файл

@ -11,6 +11,7 @@
#include "js/Wrapper.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/SourceLocation.h"
#include "nsIScriptError.h"
#include "nsPrintfCString.h"
#include "nsPointerHashKeys.h"
@ -198,14 +199,13 @@ already_AddRefed<XPCNativeInterface> XPCNativeInterface::NewInstance(
nsPrintfCString errorMsg("Use of %s in content process is deprecated.",
intfNameChars);
nsAutoString filename;
uint32_t lineno = 0, column = 1;
nsJSUtils::GetCallingLocation(cx, filename, &lineno, &column);
auto location = JSCallingLocation::Get(cx);
nsCOMPtr<nsIScriptError> error(
do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
error->Init(NS_ConvertUTF8toUTF16(errorMsg), filename, u""_ns, lineno,
column, nsIScriptError::warningFlag, "chrome javascript"_ns,
false /* from private window */,
error->Init(NS_ConvertUTF8toUTF16(errorMsg),
NS_ConvertUTF8toUTF16(location.FileName()), u""_ns,
location.mLine, location.mColumn, nsIScriptError::warningFlag,
"chrome javascript"_ns, false /* from private window */,
true /* from chrome context */);
console->LogMessage(error);
}

Просмотреть файл

@ -76,9 +76,9 @@ static void logMessage(nsIContent* aContent, const nsAString& aCoordsSpec,
aFlags, "Layout: ImageMap"_ns, aContent->OwnerDoc(),
nsContentUtils::eLAYOUT_PROPERTIES, aMessageName,
nsTArray<nsString>(), /* params */
nullptr,
PromiseFlatString(u"coords=\""_ns + aCoordsSpec +
u"\""_ns)); /* source line */
SourceLocation(aContent->OwnerDoc()->GetDocumentURI(), 0, 1,
NS_ConvertUTF16toUTF8(u"coords=\""_ns + aCoordsSpec +
u"\""_ns))); /* source line */
}
void Area::ParseCoords(const nsAString& aSpec) {

Просмотреть файл

@ -815,7 +815,8 @@ nsresult SheetLoadData::VerifySheetReadyToParse(
nsCOMPtr<nsIURI> referrer = ReferrerInfo()->GetOriginalReferrer();
nsContentUtils::ReportToConsole(
errorFlag, "CSS Loader"_ns, mLoader->mDocument,
nsContentUtils::eCSS_PROPERTIES, errorMessage, strings, referrer);
nsContentUtils::eCSS_PROPERTIES, errorMessage, strings,
SourceLocation(referrer.get()));
if (errorFlag == nsIScriptError::errorFlag) {
LOG_WARN(

Просмотреть файл

@ -2993,7 +2993,7 @@ static bool ShouldSecureUpgradeNoHSTS(nsIURI* aURI, nsILoadInfo* aLoadInfo) {
AutoTArray<nsString, 2> params = {reportSpec, reportScheme};
uint64_t innerWindowId = aLoadInfo->GetInnerWindowID();
CSP_LogLocalizedStr("upgradeInsecureRequest", params,
u""_ns, // aSourceFile
""_ns, // aSourceFile
u""_ns, // aScriptSample
0, // aLineNumber
1, // aColumnNumber
@ -3027,7 +3027,7 @@ static bool ShouldSecureUpgradeNoHSTS(nsIURI* aURI, nsILoadInfo* aLoadInfo) {
uint64_t innerWindowId = aLoadInfo->GetInnerWindowID();
nsContentUtils::ReportToConsoleByWindowID(
message, nsIScriptError::warningFlag, "Mixed Content Message"_ns,
innerWindowId, aURI);
innerWindowId, SourceLocation(aURI));
// Set this flag so we know we'll upgrade because of
// 'security.mixed_content.upgrade_display_content'.

Просмотреть файл

@ -6639,7 +6639,8 @@ void HttpBaseChannel::LogORBError(
if (contentWindowId) {
nsContentUtils::ReportToConsoleByWindowID(
u"A resource is blocked by OpaqueResponseBlocking, please check browser console for details."_ns,
nsIScriptError::warningFlag, "ORB"_ns, contentWindowId, mURI);
nsIScriptError::warningFlag, "ORB"_ns, contentWindowId,
SourceLocation(mURI.get()));
}
AutoTArray<nsString, 2> params;

Просмотреть файл

@ -803,14 +803,10 @@ Maybe<nsCString> CallingScriptLocationString() {
return Nothing();
}
nsAutoCString fileNameString;
uint32_t line = 0, col = 0;
if (!nsJSUtils::GetCallingLocation(cx, fileNameString, &line, &col)) {
return Nothing();
}
auto location = JSCallingLocation::Get(cx);
nsCString logString = ""_ns;
logString.AppendPrintf("%s:%u:%u", fileNameString.get(), line, col);
logString.AppendPrintf("%s:%u:%u", location.FileName().get(), location.mLine,
location.mColumn);
return Some(logString);
}

Просмотреть файл

@ -2671,9 +2671,10 @@ void nsHtml5StreamParser::ContinueAfterScriptsOrEncodingCommitment(
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "DOM Events"_ns,
mExecutor->GetDocument(), nsContentUtils::eDOM_PROPERTIES,
"SpeculationFailed2", nsTArray<nsString>(), nullptr, u""_ns,
speculation->GetStartLineNumber(),
speculation->GetStartColumnNumber());
"SpeculationFailed2", nsTArray<nsString>(),
SourceLocation(mExecutor->GetDocument()->GetDocumentURI(),
speculation->GetStartLineNumber(),
speculation->GetStartColumnNumber()));
nsHtml5OwningUTF16Buffer* buffer = mFirstBuffer->next;
while (buffer) {

Просмотреть файл

@ -1031,7 +1031,8 @@ void nsHtml5TreeOpExecutor::MaybeComplainAboutCharset(const char* aMsgId,
nsContentUtils::ReportToConsole(
aError ? nsIScriptError::errorFlag : nsIScriptError::warningFlag,
"HTML parser"_ns, mDocument, nsContentUtils::eHTMLPARSER_PROPERTIES,
aMsgId, nsTArray<nsString>(), nullptr, u""_ns, aLineNumber);
aMsgId, nsTArray<nsString>(),
SourceLocation{mDocument->GetDocumentURI(), aLineNumber});
}
void nsHtml5TreeOpExecutor::ComplainAboutBogusProtocolCharset(
@ -1053,7 +1054,8 @@ void nsHtml5TreeOpExecutor::MaybeComplainAboutDeepTree(uint32_t aLineNumber) {
nsContentUtils::ReportToConsole(
nsIScriptError::errorFlag, "HTML parser"_ns, mDocument,
nsContentUtils::eHTMLPARSER_PROPERTIES, "errDeepTree",
nsTArray<nsString>(), nullptr, u""_ns, aLineNumber);
nsTArray<nsString>(),
SourceLocation{mDocument->GetDocumentURI(), aLineNumber});
}
nsHtml5Parser* nsHtml5TreeOpExecutor::GetParser() {

Просмотреть файл

@ -521,9 +521,11 @@ void nsExpatDriver::HandleStartElementForSystemPrincipal(
error.AppendLiteral("> created from entity value.");
nsContentUtils::ReportToConsoleNonLocalized(
error, nsIScriptError::warningFlag, "XML Document"_ns, doc, nullptr,
u""_ns, lineNumber.unverified_safe_because(RLBOX_SAFE_PRINT),
colNumber.unverified_safe_because(RLBOX_SAFE_PRINT));
error, nsIScriptError::warningFlag, "XML Document"_ns, doc,
mozilla::SourceLocation(
doc->GetDocumentURI(),
lineNumber.unverified_safe_because(RLBOX_SAFE_PRINT),
colNumber.unverified_safe_because(RLBOX_SAFE_PRINT)));
}
}

Просмотреть файл

@ -10,6 +10,7 @@
#include "mozilla/EventQueue.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/SourceLocation.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/Document.h"
@ -21,13 +22,11 @@
#include "nsIURI.h"
#include "nsIOService.h"
#include "nsGlobalWindowOuter.h"
#include "nsJSUtils.h"
#include "mozIThirdPartyUtil.h"
using namespace mozilla;
using namespace mozilla::dom;
using mozilla::dom::BrowsingContext;
using mozilla::dom::ContentChild;
using mozilla::dom::Document;
static const uint32_t kMaxConsoleOutputDelayMs = 100;
@ -58,20 +57,16 @@ void ReportUnblockingToConsole(
MOZ_ASSERT(aWindowID);
MOZ_ASSERT(aPrincipal);
nsAutoString sourceLine;
uint32_t lineNumber = 0, columnNumber = 1;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, sourceLine, &lineNumber, &columnNumber);
}
// Grab the calling location now since the runnable will run without a JS
// context on the stack.
auto location = JSCallingLocation::Get();
nsCOMPtr<nsIPrincipal> principal(aPrincipal);
nsAutoString trackingOrigin(aTrackingOrigin);
RefPtr<Runnable> runnable = NS_NewRunnableFunction(
"ReportUnblockingToConsoleDelayed",
[aWindowID, sourceLine, lineNumber, columnNumber, principal,
trackingOrigin, aReason]() {
[aWindowID, loc = std::move(location), principal, trackingOrigin,
aReason]() {
const char* messageWithSameOrigin = nullptr;
switch (aReason) {
@ -105,8 +100,7 @@ void ReportUnblockingToConsole(
nsContentUtils::ReportToConsoleByWindowID(
errorText, nsIScriptError::warningFlag,
ANTITRACKING_CONSOLE_CATEGORY, aWindowID, nullptr, sourceLine,
lineNumber, columnNumber);
ANTITRACKING_CONSOLE_CATEGORY, aWindowID, loc);
});
RunConsoleReportingRunnable(runnable.forget());
@ -148,18 +142,13 @@ void ReportBlockingToConsole(uint64_t aWindowID, nsIURI* aURI,
return;
}
nsAutoString sourceLine;
uint32_t lineNumber = 0, columnNumber = 1;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, sourceLine, &lineNumber, &columnNumber);
}
auto location = JSCallingLocation::Get();
nsCOMPtr<nsIURI> uri(aURI);
RefPtr<Runnable> runnable = NS_NewRunnableFunction(
"ReportBlockingToConsoleDelayed", [aWindowID, sourceLine, lineNumber,
columnNumber, uri, aRejectedReason]() {
"ReportBlockingToConsoleDelayed",
[aWindowID, loc = std::move(location), uri, aRejectedReason]() {
const char* message = nullptr;
nsAutoCString category;
// When changing this list, please make sure to update the corresponding
@ -215,8 +204,7 @@ void ReportBlockingToConsole(uint64_t aWindowID, nsIURI* aURI,
NS_ENSURE_SUCCESS_VOID(rv);
nsContentUtils::ReportToConsoleByWindowID(
errorText, nsIScriptError::warningFlag, category, aWindowID,
nullptr, sourceLine, lineNumber, columnNumber);
errorText, nsIScriptError::warningFlag, category, aWindowID, loc);
});
RunConsoleReportingRunnable(runnable.forget());

Просмотреть файл

@ -1058,7 +1058,7 @@ nsExternalHelperAppService::LoadURI(nsIURI* aURI,
nsContentUtils::ReportToConsoleByWindowID(
localizedMsg, nsIScriptError::errorFlag, "Security"_ns,
windowContext->InnerWindowId(),
windowContext->Canonical()->GetDocumentURI());
SourceLocation(windowContext->Canonical()->GetDocumentURI()));
return NS_OK;
}