diff --git a/caps/nsScriptSecurityManager.cpp b/caps/nsScriptSecurityManager.cpp index cb2079a8fd5f..b0dab054e2d3 100644 --- a/caps/nsScriptSecurityManager.cpp +++ b/caps/nsScriptSecurityManager.cpp @@ -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; diff --git a/dom/base/Document.cpp b/dom/base/Document.cpp index 0f2cbcd82468..052395509e88 100644 --- a/dom/base/Document.cpp +++ b/dom/base/Document.cpp @@ -3490,11 +3490,11 @@ static void WarnIfSandboxIneffective(nsIDocShell* aDocShell, nsCOMPtr parentDocument = parentDocShell->GetDocument(); nsCOMPtr iframeUri; parentChannel->GetURI(getter_AddRefs(iframeUri)); - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - "Iframe Sandbox"_ns, parentDocument, - nsContentUtils::eSECURITY_PROPERTIES, - "BothAllowScriptsAndSameOriginPresent", - nsTArray(), iframeUri); + nsContentUtils::ReportToConsole( + nsIScriptError::warningFlag, "Iframe Sandbox"_ns, parentDocument, + nsContentUtils::eSECURITY_PROPERTIES, + "BothAllowScriptsAndSameOriginPresent", nsTArray(), + SourceLocation(iframeUri.get())); } } diff --git a/dom/base/EventSource.cpp b/dom/base/EventSource.cpp index a7afb4b980f6..aa3f675d19fb 100644 --- a/dom/base/EventSource.cpp +++ b/dom/base/EventSource.cpp @@ -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 diff --git a/dom/base/SourceLocation.cpp b/dom/base/SourceLocation.cpp new file mode 100644 index 000000000000..48b6337d64a5 --- /dev/null +++ b/dom/base/SourceLocation.cpp @@ -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&& 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 diff --git a/dom/base/SourceLocation.h b/dom/base/SourceLocation.h new file mode 100644 index 000000000000..e23d417c63a4 --- /dev/null +++ b/dom/base/SourceLocation.h @@ -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> 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&&, uint32_t aLine = 0, + uint32_t aCol = 1, nsCString&& aSourceLine = {}); + + ~SourceLocation(); + + bool IsEmpty() const { + return mResource.is() ? mResource.as().IsEmpty() + : !mResource.as>(); + } + explicit operator bool() const { return !IsEmpty(); } +}; + +struct JSCallingLocation : SourceLocation { + const nsCString& FileName() const { return mResource.as(); } + + static JSCallingLocation Get(); + static JSCallingLocation Get(JSContext*); +}; + +} // namespace mozilla + +#endif diff --git a/dom/base/TimeoutHandler.cpp b/dom/base/TimeoutHandler.cpp index b6f16c902a9c..7429c654022a 100644 --- a/dom/base/TimeoutHandler.cpp +++ b/dom/base/TimeoutHandler.cpp @@ -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(" (%s:%d:%d)", mFileName.get(), - mLineNo, mColumn); + aOutString.AppendPrintf(" (%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( " (%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(" (%s:%d:%d)", - NS_ConvertUTF16toUTF8(mExpr).get(), mFileName.get(), - mLineNo, mColumn); + NS_ConvertUTF16toUTF8(mExpr).get(), + mCaller.FileName().get(), mCaller.mLine, + mCaller.mColumn); } } diff --git a/dom/base/TimeoutHandler.h b/dom/base/TimeoutHandler.h index f8dd350af603..9b724a503d72 100644 --- a/dom/base/TimeoutHandler.h +++ b/dom/base/TimeoutHandler.h @@ -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; diff --git a/dom/base/moz.build b/dom/base/moz.build index 9cc4c9bfdf88..0c3995a617bc 100644 --- a/dom/base/moz.build +++ b/dom/base/moz.build @@ -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", diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp index 6d694feaccd3..b3e4b04d4aaa 100644 --- a/dom/base/nsContentUtils.cpp +++ b/dom/base/nsContentUtils.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& aParams, nsIURI* aURI, - const nsString& aSourceLine, uint32_t aLineNumber, uint32_t aColumnNumber) { + const nsTArray& 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 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>()) { + nsIURI* uri = aLocation.mResource.as>(); + 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()), + sourceLine, aLocation.mLine, aLocation.mColumn, aErrorFlags, aCategory, + aInnerWindowID); } NS_ENSURE_SUCCESS(rv, rv); diff --git a/dom/base/nsContentUtils.h b/dom/base/nsContentUtils.h index e50ef5bae79e..f0e5c36019d9 100644 --- a/dom/base/nsContentUtils.h +++ b/dom/base/nsContentUtils.h @@ -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& aParams = nsTArray(), - 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); diff --git a/dom/base/nsFocusManager.cpp b/dom/base/nsFocusManager.cpp index 54fabd169bc8..c151f8ca4d45 100644 --- a/dom/base/nsFocusManager.cpp +++ b/dom/base/nsFocusManager.cpp @@ -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 diff --git a/dom/base/nsFrameMessageManager.cpp b/dom/base/nsFrameMessageManager.cpp index 13c26ef60aa1..03afb5ca1e7f 100644 --- a/dom/base/nsFrameMessageManager.cpp +++ b/dom/base/nsFrameMessageManager.cpp @@ -455,17 +455,15 @@ bool nsFrameMessageManager::GetParamsForMessage(JSContext* aCx, nsCOMPtr 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 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); } diff --git a/dom/base/nsGlobalWindowInner.cpp b/dom/base/nsGlobalWindowInner.cpp index d8a812271372..b1f836d9f6f0 100644 --- a/dom/base/nsGlobalWindowInner.cpp +++ b/dom/base/nsGlobalWindowInner.cpp @@ -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 global(aes.cx(), mGlobal->GetGlobalJSObject()); diff --git a/dom/base/nsJSUtils.cpp b/dom/base/nsJSUtils.cpp index cf8037cd5800..48df3ae2d30b 100644 --- a/dom/base/nsJSUtils.cpp +++ b/dom/base/nsJSUtils.cpp @@ -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; diff --git a/dom/base/nsJSUtils.h b/dom/base/nsJSUtils.h index cceb725d393d..8b4c1492c648 100644 --- a/dom/base/nsJSUtils.h +++ b/dom/base/nsJSUtils.h @@ -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. * diff --git a/dom/bindings/BindingUtils.cpp b/dom/bindings/BindingUtils.cpp index 017b0bc322d7..e819bf688fa5 100644 --- a/dom/bindings/BindingUtils.cpp +++ b/dom/bindings/BindingUtils.cpp @@ -4048,7 +4048,7 @@ static const char* kDeprecatedOperations[] = { void ReportDeprecation(nsIGlobalObject* aGlobal, nsIURI* aURI, DeprecatedOperations aOperation, - const nsAString& aFileName, + const nsACString& aFileName, const Nullable& aLineNumber, const Nullable& aColumnNumber) { MOZ_ASSERT(aURI); @@ -4156,21 +4156,18 @@ void MaybeReportDeprecation(const GlobalObject& aGlobal, return; } - nsAutoString fileName; + auto location = JSCallingLocation::Get(aGlobal.Context()); Nullable lineNumber; Nullable 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 global = do_QueryInterface(aGlobal.GetAsSupports()); MOZ_ASSERT(global); - ReportDeprecation(global, uri, aOperation, fileName, lineNumber, + ReportDeprecation(global, uri, aOperation, location.FileName(), lineNumber, columnNumber); } diff --git a/dom/chrome-webidl/ConsoleInstance.webidl b/dom/chrome-webidl/ConsoleInstance.webidl index b80a0da0f9a5..d11c7e1ba810 100644 --- a/dom/chrome-webidl/ConsoleInstance.webidl +++ b/dom/chrome-webidl/ConsoleInstance.webidl @@ -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); }; diff --git a/dom/console/Console.cpp b/dom/console/Console.cpp index b58ce08e2368..db0f1eed674c 100644 --- a/dom/console/Console.cpp +++ b/dom/console/Console.cpp @@ -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; } } diff --git a/dom/console/ConsoleInstance.cpp b/dom/console/ConsoleInstance.cpp index a73b83ee4c64..fd037e39c667 100644 --- a/dom/console/ConsoleInstance.cpp +++ b/dom/console/ConsoleInstance.cpp @@ -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) { diff --git a/dom/console/ConsoleInstance.h b/dom/console/ConsoleInstance.h index 3d0e4ddcde9e..329186ae57e2 100644 --- a/dom/console/ConsoleInstance.h +++ b/dom/console/ConsoleInstance.h @@ -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); diff --git a/dom/console/ConsoleReportCollector.cpp b/dom/console/ConsoleReportCollector.cpp index f64d79aa6477..f0284df1efc8 100644 --- a/dom/console/ConsoleReportCollector.cpp +++ b/dom/console/ConsoleReportCollector.cpp @@ -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); } } diff --git a/dom/console/ConsoleUtils.cpp b/dom/console/ConsoleUtils.cpp index 585ff2ec3d6f..9cf03a3c0bd8 100644 --- a/dom/console/ConsoleUtils.cpp +++ b/dom/console/ConsoleUtils.cpp @@ -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()); diff --git a/dom/console/ConsoleUtils.h b/dom/console/ConsoleUtils.h index 6e3d71ea0481..aea9d268ef9b 100644 --- a/dom/console/ConsoleUtils.h +++ b/dom/console/ConsoleUtils.h @@ -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); diff --git a/dom/events/KeyEventHandler.cpp b/dom/events/KeyEventHandler.cpp index 8d6eec63a4c5..3f3ca808e815 100644 --- a/dom/events/KeyEventHandler.cpp +++ b/dom/events/KeyEventHandler.cpp @@ -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( diff --git a/dom/html/HTMLFormElement.cpp b/dom/html/HTMLFormElement.cpp index 5ed8e521cd9f..b5b04db7f985 100644 --- a/dom/html/HTMLFormElement.cpp +++ b/dom/html/HTMLFormElement.cpp @@ -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 diff --git a/dom/html/HTMLScriptElement.cpp b/dom/html/HTMLScriptElement.cpp index 9fbf46699df1..faae5f4a070f 100644 --- a/dom/html/HTMLScriptElement.cpp +++ b/dom/html/HTMLScriptElement.cpp @@ -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 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 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. diff --git a/dom/indexedDB/IDBDatabase.cpp b/dom/indexedDB/IDBDatabase.cpp index 7326289c22dc..2c4a3c8b920f 100644 --- a/dom/indexedDB/IDBDatabase.cpp +++ b/dom/indexedDB/IDBDatabase.cpp @@ -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) diff --git a/dom/indexedDB/IDBDatabase.h b/dom/indexedDB/IDBDatabase.h index 6d96aaa35ddd..91f255178dc0 100644 --- a/dom/indexedDB/IDBDatabase.h +++ b/dom/indexedDB/IDBDatabase.h @@ -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); diff --git a/dom/indexedDB/IDBRequest.cpp b/dom/indexedDB/IDBRequest.cpp index efc3f9a44e01..18e9ca3ffd68 100644 --- a/dom/indexedDB/IDBRequest.cpp +++ b/dom/indexedDB/IDBRequest.cpp @@ -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> IDBRequest::Create( aDatabase->AssertIsOnOwningThread(); RefPtr 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& 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::Create( RefPtr 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(); diff --git a/dom/indexedDB/IDBRequest.h b/dom/indexedDB/IDBRequest.h index 4bbb7eefa76e..88e03c7c5f73 100644 --- a/dom/indexedDB/IDBRequest.h +++ b/dom/indexedDB/IDBRequest.h @@ -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 mResultVal; RefPtr 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 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; } diff --git a/dom/indexedDB/IDBTransaction.cpp b/dom/indexedDB/IDBTransaction.cpp index b35bea6eff10..054f4faf49d4 100644 --- a/dom/indexedDB/IDBTransaction.cpp +++ b/dom/indexedDB/IDBTransaction.cpp @@ -90,8 +90,7 @@ auto IDBTransaction::DoWithTransactionChild(const Func& aFunc) const { IDBTransaction::IDBTransaction(IDBDatabase* const aDatabase, const nsTArray& 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::CreateVersionChange( const nsTArray emptyObjectStoreNames; - nsString filename; - uint32_t lineNo, column; - aOpenRequest->GetCallerLocation(filename, &lineNo, &column); // XXX: What should we have as durability hint here? auto transaction = MakeSafeRefPtr( 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::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( - 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 IDBTransaction::CreateObjectStore( ObjectStoreSpec& aSpec) { AssertIsOnOwningThread(); diff --git a/dom/indexedDB/IDBTransaction.h b/dom/indexedDB/IDBTransaction.h index 9feafb3c68ae..997bbbd2e992 100644 --- a/dom/indexedDB/IDBTransaction.h +++ b/dom/indexedDB/IDBTransaction.h @@ -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 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& aObjectStoreNames, Mode aMode, - Durability aDurability, nsString aFilename, uint32_t aLineNo, - uint32_t aColumn, CreatedFromFactoryFunction aDummy); + Durability aDurability, JSCallingLocation&& aCallerLocation, + CreatedFromFactoryFunction aDummy); private: ~IDBTransaction(); diff --git a/dom/indexedDB/ScriptErrorHelper.cpp b/dom/indexedDB/ScriptErrorHelper.cpp index 0bf33336ba32..f5823f59c0d6 100644 --- a/dom/indexedDB/ScriptErrorHelper.cpp +++ b/dom/indexedDB/ScriptErrorHelper.cpp @@ -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 consoleService = - do_GetService(NS_CONSOLESERVICE_CONTRACTID); - - nsCOMPtr 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 runnable = - new ScriptErrorRunnable(aMessage, aFilename, aLineNumber, aColumnNumber, - aSeverityFlag, aIsChrome, aInnerWindowID); + RefPtr 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 runnable = new ScriptErrorRunnable( - aMessageName, aFilename, aLineNumber, aColumnNumber, aSeverityFlag, - aIsChrome, aInnerWindowID); + aMessageName, aCallingLocation, aSeverityFlag, aIsChrome, aInnerWindowID); MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(runnable.forget())); } } diff --git a/dom/indexedDB/ScriptErrorHelper.h b/dom/indexedDB/ScriptErrorHelper.h index 691411b82fc4..415791c96d84 100644 --- a/dom/indexedDB/ScriptErrorHelper.h +++ b/dom/indexedDB/ScriptErrorHelper.h @@ -10,19 +10,21 @@ #include #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); }; diff --git a/dom/interfaces/security/nsIContentSecurityPolicy.idl b/dom/interfaces/security/nsIContentSecurityPolicy.idl index 128c8198203f..570ae9adeef2 100644 --- a/dom/interfaces/security/nsIContentSecurityPolicy.idl +++ b/dom/interfaces/security/nsIContentSecurityPolicy.idl @@ -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, diff --git a/dom/media/webaudio/WebAudioUtils.cpp b/dom/media/webaudio/WebAudioUtils.cpp index a1338650e0b4..8c17e01e1dc8 100644 --- a/dom/media/webaudio/WebAudioUtils.cpp +++ b/dom/media/webaudio/WebAudioUtils.cpp @@ -73,41 +73,17 @@ void WebAudioUtils::LogToDeveloperConsole(uint64_t aWindowID, return; } - nsCOMPtr 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 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 diff --git a/dom/prototype/PrototypeDocumentContentSink.cpp b/dom/prototype/PrototypeDocumentContentSink.cpp index c19bc3c35310..8ae8e58157b8 100644 --- a/dom/prototype/PrototypeDocumentContentSink.cpp +++ b/dom/prototype/PrototypeDocumentContentSink.cpp @@ -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 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(); diff --git a/dom/push/PushNotifier.cpp b/dom/push/PushNotifier.cpp index 458be9f33126..e36714c932ca 100644 --- a/dom/push/PushNotifier.cpp +++ b/dom/push/PushNotifier.cpp @@ -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 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 diff --git a/dom/reporting/CSPViolationReportBody.cpp b/dom/reporting/CSPViolationReportBody.cpp index 970c017d45d2..e6ad5bdd52bb 100644 --- a/dom/reporting/CSPViolationReportBody.cpp +++ b/dom/reporting/CSPViolationReportBody.cpp @@ -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()) { diff --git a/dom/reporting/CSPViolationReportBody.h b/dom/reporting/CSPViolationReportBody.h index bbfb76bf4d11..94175bfea95f 100644 --- a/dom/reporting/CSPViolationReportBody.h +++ b/dom/reporting/CSPViolationReportBody.h @@ -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; diff --git a/dom/reporting/DeprecationReportBody.cpp b/dom/reporting/DeprecationReportBody.cpp index 115412148444..8d18a4b321da 100644 --- a/dom/reporting/DeprecationReportBody.cpp +++ b/dom/reporting/DeprecationReportBody.cpp @@ -13,7 +13,7 @@ namespace mozilla::dom { DeprecationReportBody::DeprecationReportBody( nsIGlobalObject* aGlobal, const nsAString& aId, const Nullable& aDate, const nsAString& aMessage, - const nsAString& aSourceFile, const Nullable& aLineNumber, + const nsACString& aSourceFile, const Nullable& aLineNumber, const Nullable& 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()) { diff --git a/dom/reporting/DeprecationReportBody.h b/dom/reporting/DeprecationReportBody.h index 9476899b1298..c5441b4be8ad 100644 --- a/dom/reporting/DeprecationReportBody.h +++ b/dom/reporting/DeprecationReportBody.h @@ -17,7 +17,8 @@ class DeprecationReportBody final : public ReportBody { public: DeprecationReportBody(nsIGlobalObject* aGlobal, const nsAString& aId, const Nullable& aDate, - const nsAString& aMessage, const nsAString& aSourceFile, + const nsAString& aMessage, + const nsACString& aSourceFile, const Nullable& aLineNumber, const Nullable& 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 GetLineNumber() const; @@ -45,7 +46,7 @@ class DeprecationReportBody final : public ReportBody { const nsString mId; const Nullable mDate; const nsString mMessage; - const nsString mSourceFile; + const nsCString mSourceFile; const Nullable mLineNumber; const Nullable mColumnNumber; }; diff --git a/dom/reporting/FeaturePolicyViolationReportBody.cpp b/dom/reporting/FeaturePolicyViolationReportBody.cpp index a8c46bf6edba..84fba6b6f698 100644 --- a/dom/reporting/FeaturePolicyViolationReportBody.cpp +++ b/dom/reporting/FeaturePolicyViolationReportBody.cpp @@ -13,7 +13,7 @@ namespace mozilla::dom { FeaturePolicyViolationReportBody::FeaturePolicyViolationReportBody( nsIGlobalObject* aGlobal, const nsAString& aFeatureId, - const nsAString& aSourceFile, const Nullable& aLineNumber, + const nsACString& aSourceFile, const Nullable& aLineNumber, const Nullable& 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()) { diff --git a/dom/reporting/FeaturePolicyViolationReportBody.h b/dom/reporting/FeaturePolicyViolationReportBody.h index bf6f74925605..870b05c2e1f2 100644 --- a/dom/reporting/FeaturePolicyViolationReportBody.h +++ b/dom/reporting/FeaturePolicyViolationReportBody.h @@ -17,7 +17,7 @@ class FeaturePolicyViolationReportBody final : public ReportBody { public: FeaturePolicyViolationReportBody(nsIGlobalObject* aGlobal, const nsAString& aFeatureId, - const nsAString& aSourceFile, + const nsACString& aSourceFile, const Nullable& aLineNumber, const Nullable& 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 GetLineNumber() const; @@ -42,7 +42,7 @@ class FeaturePolicyViolationReportBody final : public ReportBody { ~FeaturePolicyViolationReportBody(); const nsString mFeatureId; - const nsString mSourceFile; + const nsCString mSourceFile; const Nullable mLineNumber; const Nullable mColumnNumber; const nsString mDisposition; diff --git a/dom/reporting/ReportingHeader.cpp b/dom/reporting/ReportingHeader.cpp index 0ba71add9f1b..7616ba475761 100644 --- a/dom/reporting/ReportingHeader.cpp +++ b/dom/reporting/ReportingHeader.cpp @@ -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)); } diff --git a/dom/script/ScriptLoader.cpp b/dom/script/ScriptLoader.cpp index 6e29210986c6..f5d58fce20ab 100644 --- a/dom/script/ScriptLoader.cpp +++ b/dom/script/ScriptLoader.cpp @@ -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) { diff --git a/dom/security/CSPEvalChecker.cpp b/dom/security/CSPEvalChecker.cpp index ba2caf52ebd3..1536b59fca87 100644 --- a/dom/security/CSPEvalChecker.cpp +++ b/dom/security/CSPEvalChecker.cpp @@ -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 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 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())) { diff --git a/dom/security/CSPViolationData.cpp b/dom/security/CSPViolationData.cpp index c50ee67ab0ef..49368a5d892c 100644 --- a/dom/security/CSPViolationData.cpp +++ b/dom/security/CSPViolationData.cpp @@ -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}, diff --git a/dom/security/CSPViolationData.h b/dom/security/CSPViolationData.h index 4ac793271671..4c5af34cbb75 100644 --- a/dom/security/CSPViolationData.h +++ b/dom/security/CSPViolationData.h @@ -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 mElement; diff --git a/dom/security/DOMSecurityMonitor.cpp b/dom/security/DOMSecurityMonitor.cpp index 2ec4998b0b31..b8aaa9c98fe5 100644 --- a/dom/security/DOMSecurityMonitor.cpp +++ b/dom/security/DOMSecurityMonitor.cpp @@ -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); diff --git a/dom/security/ReferrerInfo.cpp b/dom/security/ReferrerInfo.cpp index 8923bb46aada..76bd44b1b12b 100644 --- a/dom/security/ReferrerInfo.cpp +++ b/dom/security/ReferrerInfo.cpp @@ -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)); } diff --git a/dom/security/featurepolicy/FeaturePolicyUtils.cpp b/dom/security/featurepolicy/FeaturePolicyUtils.cpp index 8423a62a6a84..f9b6a224ae5b 100644 --- a/dom/security/featurepolicy/FeaturePolicyUtils.cpp +++ b/dom/security/featurepolicy/FeaturePolicyUtils.cpp @@ -222,14 +222,12 @@ void FeaturePolicyUtils::ReportViolation(Document* aDocument, return; } - nsAutoString fileName; Nullable lineNumber; Nullable columnNumber; - uint32_t line = 0; - uint32_t column = 0; - if (nsJSUtils::GetCallingLocation(cx, fileName, &line, &column)) { - lineNumber.SetValue(static_cast(line)); - columnNumber.SetValue(static_cast(column)); + auto loc = JSCallingLocation::Get(); + if (loc) { + lineNumber.SetValue(static_cast(loc.mLine)); + columnNumber.SetValue(static_cast(loc.mColumn)); } nsPIDOMWindowInner* window = aDocument->GetInnerWindow(); @@ -239,8 +237,8 @@ void FeaturePolicyUtils::ReportViolation(Document* aDocument, RefPtr 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); diff --git a/dom/security/nsCSPContext.cpp b/dom/security/nsCSPContext.cpp index 03bbd9a85716..7fb67544cdaf 100644 --- a/dom/security/nsCSPContext.cpp +++ b/dom/security/nsCSPContext.cpp @@ -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& 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 doc = do_QueryReferent(mLoadingContext); - if (doc) { + if (nsCOMPtr doc = do_QueryReferent(mLoadingContext)) { privateWindow = doc->NodePrincipal()->OriginAttributesRef().IsPrivateBrowsing(); } @@ -1082,11 +1068,12 @@ nsresult nsCSPContext::GatherSecurityPolicyViolationEventData( nsCOMPtr 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 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 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 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 params = {policy}; - logToConsole("ignoringReportOnlyDirective", params, u""_ns, u""_ns, 0, 1, + logToConsole("ignoringReportOnlyDirective", params, ""_ns, u""_ns, 0, 1, nsIScriptError::warningFlag); } } diff --git a/dom/security/nsCSPContext.h b/dom/security/nsCSPContext.h index 695ea4fb0bb6..292a0f96e5dd 100644 --- a/dom/security/nsCSPContext.h +++ b/dom/security/nsCSPContext.h @@ -74,7 +74,7 @@ class nsCSPContext : public nsIContentSecurityPolicy { void flushConsoleMessages(); void logToConsole(const char* aName, const nsTArray& aParams, - const nsAString& aSourceName, const nsAString& aSourceLine, + const nsACString& aSourceName, const nsAString& aSourceLine, uint32_t aLineNumber, uint32_t aColumnNumber, uint32_t aSeverityFlag); diff --git a/dom/security/nsCSPParser.cpp b/dom/security/nsCSPParser.cpp index 037ea13be47d..0e9e85af4fcb 100644 --- a/dom/security/nsCSPParser.cpp +++ b/dom/security/nsCSPParser.cpp @@ -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 diff --git a/dom/security/nsCSPUtils.cpp b/dom/security/nsCSPUtils.cpp index b0f474bbc907..6f087ff67bf0 100644 --- a/dom/security/nsCSPUtils.cpp +++ b/dom/security/nsCSPUtils.cpp @@ -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& 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, diff --git a/dom/security/nsCSPUtils.h b/dom/security/nsCSPUtils.h index a41590eb40d7..eb2b7f3ffbd9 100644 --- a/dom/security/nsCSPUtils.h +++ b/dom/security/nsCSPUtils.h @@ -27,7 +27,7 @@ class Document; /* =============== Logging =================== */ void CSP_LogLocalizedStr(const char* aName, const nsTArray& 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& 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, diff --git a/dom/security/nsContentSecurityManager.cpp b/dom/security/nsContentSecurityManager.cpp index 100852562ea0..9181de826575 100644 --- a/dom/security/nsContentSecurityManager.cpp +++ b/dom/security/nsContentSecurityManager.cpp @@ -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` diff --git a/dom/security/nsContentSecurityUtils.cpp b/dom/security/nsContentSecurityUtils.cpp index f0eccaa0c1c6..3cf9aea7cb3a 100644 --- a/dom/security/nsContentSecurityUtils.cpp +++ b/dom/security/nsContentSecurityUtils.cpp @@ -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 regexResults; - nsresult rv = RegexEval(kExtensionRegex, fileName, /* aOnlyMatch = */ false, - regexMatch, ®exResults); + nsresult rv = + RegexEval(kExtensionRegex, fileNameA, + /* aOnlyMatch = */ false, regexMatch, ®exResults); 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 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> extra; if (fileNameTypeAndDetails.second.isSome()) { extra = Some>({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 formatStrings = {aFileNameA}; + NS_ConvertUTF8toUTF16 fileNameA(aFileName); + AutoTArray 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 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 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> extra; if (fileNameTypeAndDetails.second.isSome()) { extra = Some>({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 */ diff --git a/dom/security/nsContentSecurityUtils.h b/dom/security/nsContentSecurityUtils.h index 807e085797d9..b12d87a168c3 100644 --- a/dom/security/nsContentSecurityUtils.h +++ b/dom/security/nsContentSecurityUtils.h @@ -24,7 +24,7 @@ class Document; class Element; } // namespace mozilla::dom -using FilenameTypeAndDetails = std::pair>; +using FilenameTypeAndDetails = std::pair>; 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, diff --git a/dom/security/nsHTTPSOnlyUtils.cpp b/dom/security/nsHTTPSOnlyUtils.cpp index 60a67aab89f6..efcda38aaa29 100644 --- a/dom/security/nsHTTPSOnlyUtils.cpp +++ b/dom/security/nsHTTPSOnlyUtils.cpp @@ -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(); diff --git a/dom/security/nsMixedContentBlocker.cpp b/dom/security/nsMixedContentBlocker.cpp index d3a780a2b339..9d51f3ab3c05 100644 --- a/dom/security/nsMixedContentBlocker.cpp +++ b/dom/security/nsMixedContentBlocker.cpp @@ -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 diff --git a/dom/security/test/gtest/TestFilenameEvalParser.cpp b/dom/security/test/gtest/TestFilenameEvalParser.cpp index 60683007caa4..3c91e8c8bdcd 100644 --- a/dom/security/test/gtest/TestFilenameEvalParser.cpp +++ b/dom/security/test/gtest/TestFilenameEvalParser.cpp @@ -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); } } diff --git a/dom/security/trusted-types/TrustedTypePolicyFactory.cpp b/dom/security/trusted-types/TrustedTypePolicyFactory.cpp index 8be268388549..2dd8fc8dc575 100644 --- a/dom/security/trusted-types/TrustedTypePolicyFactory.cpp +++ b/dom/security/trusted-types/TrustedTypePolicyFactory.cpp @@ -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}; } diff --git a/dom/serviceworkers/ServiceWorkerEvents.cpp b/dom/serviceworkers/ServiceWorkerEvents.cpp index 99f76f186dcc..4f3250670e60 100644 --- a/dom/serviceworkers/ServiceWorkerEvents.cpp +++ b/dom/serviceworkers/ServiceWorkerEvents.cpp @@ -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 ir = mRequest->GetInternalRequest(); nsAutoCString requestURL; @@ -784,12 +777,14 @@ void FetchEvent::RespondWith(JSContext* aCx, Promise& aArg, ErrorResult& aRv) { RefPtr 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 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 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); } }; diff --git a/dom/serviceworkers/ServiceWorkerEvents.h b/dom/serviceworkers/ServiceWorkerEvents.h index eaa5d57213e3..783b10113cb9 100644 --- a/dom/serviceworkers/ServiceWorkerEvents.h +++ b/dom/serviceworkers/ServiceWorkerEvents.h @@ -140,11 +140,9 @@ class FetchEvent final : public ExtendableEvent { RefPtr mHandled; RefPtr mPreloadResponse; nsCString mScriptSpec; - nsCString mPreventDefaultScriptSpec; nsString mClientId; nsString mResultingClientId; - uint32_t mPreventDefaultLineNumber; - uint32_t mPreventDefaultColumnNumber; + JSCallingLocation mPreventDefaultLocation; bool mWaitToRespond; protected: diff --git a/dom/serviceworkers/ServiceWorkerManager.cpp b/dom/serviceworkers/ServiceWorkerManager.cpp index 05c40520136b..c21461ef33dc 100644 --- a/dom/serviceworkers/ServiceWorkerManager.cpp +++ b/dom/serviceworkers/ServiceWorkerManager.cpp @@ -1447,7 +1447,7 @@ already_AddRefed 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& 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 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); diff --git a/dom/serviceworkers/ServiceWorkerManager.h b/dom/serviceworkers/ServiceWorkerManager.h index 11c8f2f6723e..b0d0d046a6f9 100644 --- a/dom/serviceworkers/ServiceWorkerManager.h +++ b/dom/serviceworkers/ServiceWorkerManager.h @@ -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& 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); diff --git a/dom/serviceworkers/ServiceWorkerPrivate.cpp b/dom/serviceworkers/ServiceWorkerPrivate.cpp index 93679c90e542..97aa9c2a50ea 100644 --- a/dom/serviceworkers/ServiceWorkerPrivate.cpp +++ b/dom/serviceworkers/ServiceWorkerPrivate.cpp @@ -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() { diff --git a/dom/serviceworkers/ServiceWorkerUpdateJob.cpp b/dom/serviceworkers/ServiceWorkerUpdateJob.cpp index 25f86e164d3d..3d3ded7d70b7 100644 --- a/dom/serviceworkers/ServiceWorkerUpdateJob.cpp +++ b/dom/serviceworkers/ServiceWorkerUpdateJob.cpp @@ -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; diff --git a/dom/svg/SVGScriptElement.cpp b/dom/svg/SVGScriptElement.cpp index 22fb23998094..d4ecc0501594 100644 --- a/dom/svg/SVGScriptElement.cpp +++ b/dom/svg/SVGScriptElement.cpp @@ -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 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 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. diff --git a/dom/webidl/CSPReport.webidl b/dom/webidl/CSPReport.webidl index e8141ddfee73..6de19fbfa00d 100644 --- a/dom/webidl/CSPReport.webidl +++ b/dom/webidl/CSPReport.webidl @@ -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; diff --git a/dom/webidl/FeaturePolicy.webidl b/dom/webidl/FeaturePolicy.webidl index 18f683f2022f..fad971be1865 100644 --- a/dom/webidl/FeaturePolicy.webidl +++ b/dom/webidl/FeaturePolicy.webidl @@ -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; diff --git a/dom/webidl/Reporting.webidl b/dom/webidl/Reporting.webidl index 17379fe0d68a..982195794511 100644 --- a/dom/webidl/Reporting.webidl +++ b/dom/webidl/Reporting.webidl @@ -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; diff --git a/dom/webidl/SecurityPolicyViolationEvent.webidl b/dom/webidl/SecurityPolicyViolationEvent.webidl index 4366347e14d6..e0d3f02b8c7c 100644 --- a/dom/webidl/SecurityPolicyViolationEvent.webidl +++ b/dom/webidl/SecurityPolicyViolationEvent.webidl @@ -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"; diff --git a/dom/websocket/WebSocket.cpp b/dom/websocket/WebSocket.cpp index 9c17339ae497..b9577b03c750 100644 --- a/dom/websocket/WebSocket.cpp +++ b/dom/websocket/WebSocket.cpp @@ -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 diff --git a/dom/workers/RuntimeService.cpp b/dom/workers/RuntimeService.cpp index 3a76d2e07126..1ba2051ed316 100644 --- a/dom/workers/RuntimeService.cpp +++ b/dom/workers/RuntimeService.cpp @@ -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 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); diff --git a/dom/workers/WorkerScope.cpp b/dom/workers/WorkerScope.cpp index fe338f70426e..c7ed66563346 100644 --- a/dom/workers/WorkerScope.cpp +++ b/dom/workers/WorkerScope.cpp @@ -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 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{}, - nsIScriptError::warningFlag, mSourceSpec, u""_ns, mLine, mColumn); + nsIScriptError::warningFlag, mCaller.FileName(), u""_ns, mCaller.mLine, + mCaller.mColumn); return NS_OK; } diff --git a/dom/xul/nsXULContentSink.cpp b/dom/xul/nsXULContentSink.cpp index 9a4f2deb2355..7922d3960307 100644 --- a/dom/xul/nsXULContentSink.cpp +++ b/dom/xul/nsXULContentSink.cpp @@ -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; diff --git a/js/xpconnect/src/XPCWrappedNativeInfo.cpp b/js/xpconnect/src/XPCWrappedNativeInfo.cpp index aeb43e062cb4..a832616a657d 100644 --- a/js/xpconnect/src/XPCWrappedNativeInfo.cpp +++ b/js/xpconnect/src/XPCWrappedNativeInfo.cpp @@ -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::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 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); } diff --git a/layout/generic/nsImageMap.cpp b/layout/generic/nsImageMap.cpp index 54b861c093f2..69221d4e97c9 100644 --- a/layout/generic/nsImageMap.cpp +++ b/layout/generic/nsImageMap.cpp @@ -76,9 +76,9 @@ static void logMessage(nsIContent* aContent, const nsAString& aCoordsSpec, aFlags, "Layout: ImageMap"_ns, aContent->OwnerDoc(), nsContentUtils::eLAYOUT_PROPERTIES, aMessageName, nsTArray(), /* 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) { diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp index 49a410986251..bcff1d4aba9b 100644 --- a/layout/style/Loader.cpp +++ b/layout/style/Loader.cpp @@ -815,7 +815,8 @@ nsresult SheetLoadData::VerifySheetReadyToParse( nsCOMPtr 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( diff --git a/netwerk/base/nsNetUtil.cpp b/netwerk/base/nsNetUtil.cpp index 28cb3a21f0ef..3f0af205ee97 100644 --- a/netwerk/base/nsNetUtil.cpp +++ b/netwerk/base/nsNetUtil.cpp @@ -2993,7 +2993,7 @@ static bool ShouldSecureUpgradeNoHSTS(nsIURI* aURI, nsILoadInfo* aLoadInfo) { AutoTArray 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'. diff --git a/netwerk/protocol/http/HttpBaseChannel.cpp b/netwerk/protocol/http/HttpBaseChannel.cpp index da6529a52915..8c568e12f8ba 100644 --- a/netwerk/protocol/http/HttpBaseChannel.cpp +++ b/netwerk/protocol/http/HttpBaseChannel.cpp @@ -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 params; diff --git a/netwerk/protocol/http/nsHttp.cpp b/netwerk/protocol/http/nsHttp.cpp index 9ccaaf6c7ded..bdcc87cf7a52 100644 --- a/netwerk/protocol/http/nsHttp.cpp +++ b/netwerk/protocol/http/nsHttp.cpp @@ -803,14 +803,10 @@ Maybe 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); } diff --git a/parser/html/nsHtml5StreamParser.cpp b/parser/html/nsHtml5StreamParser.cpp index 6286087d2a0e..a4dded4e024b 100644 --- a/parser/html/nsHtml5StreamParser.cpp +++ b/parser/html/nsHtml5StreamParser.cpp @@ -2671,9 +2671,10 @@ void nsHtml5StreamParser::ContinueAfterScriptsOrEncodingCommitment( nsContentUtils::ReportToConsole( nsIScriptError::warningFlag, "DOM Events"_ns, mExecutor->GetDocument(), nsContentUtils::eDOM_PROPERTIES, - "SpeculationFailed2", nsTArray(), nullptr, u""_ns, - speculation->GetStartLineNumber(), - speculation->GetStartColumnNumber()); + "SpeculationFailed2", nsTArray(), + SourceLocation(mExecutor->GetDocument()->GetDocumentURI(), + speculation->GetStartLineNumber(), + speculation->GetStartColumnNumber())); nsHtml5OwningUTF16Buffer* buffer = mFirstBuffer->next; while (buffer) { diff --git a/parser/html/nsHtml5TreeOpExecutor.cpp b/parser/html/nsHtml5TreeOpExecutor.cpp index f25949e6cc90..071ed8da4135 100644 --- a/parser/html/nsHtml5TreeOpExecutor.cpp +++ b/parser/html/nsHtml5TreeOpExecutor.cpp @@ -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(), nullptr, u""_ns, aLineNumber); + aMsgId, nsTArray(), + 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(), nullptr, u""_ns, aLineNumber); + nsTArray(), + SourceLocation{mDocument->GetDocumentURI(), aLineNumber}); } nsHtml5Parser* nsHtml5TreeOpExecutor::GetParser() { diff --git a/parser/htmlparser/nsExpatDriver.cpp b/parser/htmlparser/nsExpatDriver.cpp index d365cec7dee9..7cdaedba942b 100644 --- a/parser/htmlparser/nsExpatDriver.cpp +++ b/parser/htmlparser/nsExpatDriver.cpp @@ -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))); } } diff --git a/toolkit/components/antitracking/ContentBlockingNotifier.cpp b/toolkit/components/antitracking/ContentBlockingNotifier.cpp index 84f58020ef57..0faf20582adf 100644 --- a/toolkit/components/antitracking/ContentBlockingNotifier.cpp +++ b/toolkit/components/antitracking/ContentBlockingNotifier.cpp @@ -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 principal(aPrincipal); nsAutoString trackingOrigin(aTrackingOrigin); RefPtr 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 uri(aURI); RefPtr 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()); diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp index 92a5b8226e4a..486c1ddbd2dd 100644 --- a/uriloader/exthandler/nsExternalHelperAppService.cpp +++ b/uriloader/exthandler/nsExternalHelperAppService.cpp @@ -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; }