Bug 1366511: Part 3 - Add mozilla::ToResult() to convert other result types to equivalent Result. r?nbp,ehsan draft
authorKris Maglione <maglione.k@gmail.com>
Tue, 29 Aug 2017 21:28:31 -0700
changeset 655537 ddfd7a72397055fdf38c1b00755a9cad7a9fea92
parent 655536 bdf69e6d9837c52fbe532cb7e0ac0b054eb94dad
child 728864 4b2dd4ed68f92df6ddd19d73fd4b95795375bbcc
push id76906
push usermaglione.k@gmail.com
push dateWed, 30 Aug 2017 04:49:23 +0000
reviewersnbp, ehsan
bugs1366511
milestone57.0a1
Bug 1366511: Part 3 - Add mozilla::ToResult() to convert other result types to equivalent Result. r?nbp,ehsan Also adds a mozilla/ResultExtensions.h header to define the appropriate conversion functions for nsresult and PRResult. This is in a separate header since those types are not available in Spidermonkey, and this is the pattern other *Extensions.h headers follow. Also removes equivalent NS_TRY macros and WrapNSResult inlines that served the same purpose in existing code, and are no longer necessary. MozReview-Commit-ID: A85PCAeyWhx
js/xpconnect/loader/AutoMemMap.cpp
js/xpconnect/loader/ScriptPreloader-inl.h
js/xpconnect/loader/ScriptPreloader.cpp
mfbt/Result.h
mfbt/ResultExtensions.h
netwerk/protocol/res/ExtensionProtocolHandler.cpp
security/certverifier/tests/gtest/BTSerializationTest.cpp
security/certverifier/tests/gtest/CTSerializationTest.cpp
security/certverifier/tests/gtest/CTTestUtils.cpp
toolkit/components/extensions/WebExtensionPolicy.cpp
toolkit/mozapps/extensions/AddonManagerStartup.cpp
xpcom/base/nscore.h
--- a/js/xpconnect/loader/AutoMemMap.cpp
+++ b/js/xpconnect/loader/AutoMemMap.cpp
@@ -40,17 +40,17 @@ AutoMemMap::cloneFileDescriptor()
     return FileDescriptor();
 }
 
 Result<Ok, nsresult>
 AutoMemMap::init(nsIFile* file, int flags, int mode, PRFileMapProtect prot)
 {
     MOZ_ASSERT(!fd);
 
-    NS_TRY(file->OpenNSPRFileDesc(flags, mode, &fd.rwget()));
+    MOZ_TRY(file->OpenNSPRFileDesc(flags, mode, &fd.rwget()));
 
     return initInternal(prot);
 }
 
 Result<Ok, nsresult>
 AutoMemMap::init(const FileDescriptor& file)
 {
     MOZ_ASSERT(!fd);
@@ -71,17 +71,17 @@ AutoMemMap::init(const FileDescriptor& f
 
 Result<Ok, nsresult>
 AutoMemMap::initInternal(PRFileMapProtect prot)
 {
     MOZ_ASSERT(!fileMap);
     MOZ_ASSERT(!addr);
 
     PRFileInfo64 fileInfo;
-    NS_TRY(PR_GetOpenFileInfo64(fd.get(), &fileInfo));
+    MOZ_TRY(PR_GetOpenFileInfo64(fd.get(), &fileInfo));
 
     if (fileInfo.size > UINT32_MAX)
         return Err(NS_ERROR_INVALID_ARG);
 
     fileMap = PR_CreateFileMap(fd, 0, prot);
     if (!fileMap)
         return Err(NS_ERROR_FAILURE);
 
--- a/js/xpconnect/loader/ScriptPreloader-inl.h
+++ b/js/xpconnect/loader/ScriptPreloader-inl.h
@@ -25,36 +25,16 @@ namespace loader {
 
 using mozilla::dom::AutoJSAPI;
 
 struct MOZ_RAII AutoSafeJSAPI : public AutoJSAPI
 {
     AutoSafeJSAPI() { Init(); }
 };
 
-static inline Result<Ok, nsresult>
-WrapNSResult(PRStatus aRv)
-{
-    if (aRv != PR_SUCCESS) {
-        return Err(NS_ERROR_FAILURE);
-    }
-    return Ok();
-}
-
-static inline Result<Ok, nsresult>
-WrapNSResult(nsresult aRv)
-{
-    if (NS_FAILED(aRv)) {
-        return Err(aRv);
-    }
-    return Ok();
-}
-
-#define NS_TRY(expr) MOZ_TRY(WrapNSResult(expr))
-
 
 class OutputBuffer
 {
 public:
     OutputBuffer()
     {}
 
     uint8_t*
--- a/js/xpconnect/loader/ScriptPreloader.cpp
+++ b/js/xpconnect/loader/ScriptPreloader.cpp
@@ -357,43 +357,43 @@ ScriptPreloader::Observe(nsISupports* su
     return NS_OK;
 }
 
 
 Result<nsCOMPtr<nsIFile>, nsresult>
 ScriptPreloader::GetCacheFile(const nsAString& suffix)
 {
     nsCOMPtr<nsIFile> cacheFile;
-    NS_TRY(mProfD->Clone(getter_AddRefs(cacheFile)));
+    MOZ_TRY(mProfD->Clone(getter_AddRefs(cacheFile)));
 
-    NS_TRY(cacheFile->AppendNative(NS_LITERAL_CSTRING("startupCache")));
+    MOZ_TRY(cacheFile->AppendNative(NS_LITERAL_CSTRING("startupCache")));
     Unused << cacheFile->Create(nsIFile::DIRECTORY_TYPE, 0777);
 
-    NS_TRY(cacheFile->Append(mBaseName + suffix));
+    MOZ_TRY(cacheFile->Append(mBaseName + suffix));
 
     return Move(cacheFile);
 }
 
 static const uint8_t MAGIC[] = "mozXDRcachev001";
 
 Result<Ok, nsresult>
 ScriptPreloader::OpenCache()
 {
-    NS_TRY(NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(mProfD)));
+    MOZ_TRY(NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(mProfD)));
 
     nsCOMPtr<nsIFile> cacheFile;
     MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING(".bin")));
 
     bool exists;
-    NS_TRY(cacheFile->Exists(&exists));
+    MOZ_TRY(cacheFile->Exists(&exists));
     if (exists) {
-        NS_TRY(cacheFile->MoveTo(nullptr, mBaseName + NS_LITERAL_STRING("-current.bin")));
+        MOZ_TRY(cacheFile->MoveTo(nullptr, mBaseName + NS_LITERAL_STRING("-current.bin")));
     } else {
-        NS_TRY(cacheFile->SetLeafName(mBaseName + NS_LITERAL_STRING("-current.bin")));
-        NS_TRY(cacheFile->Exists(&exists));
+        MOZ_TRY(cacheFile->SetLeafName(mBaseName + NS_LITERAL_STRING("-current.bin")));
+        MOZ_TRY(cacheFile->Exists(&exists));
         if (!exists) {
             return Err(NS_ERROR_FILE_NOT_FOUND);
         }
     }
 
     MOZ_TRY(mCacheData.init(cacheFile));
 
     return Ok();
@@ -622,24 +622,24 @@ ScriptPreloader::WriteCache()
         // If we don't have anything we need to save, we're done.
         return Ok();
     }
 
     nsCOMPtr<nsIFile> cacheFile;
     MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING("-new.bin")));
 
     bool exists;
-    NS_TRY(cacheFile->Exists(&exists));
+    MOZ_TRY(cacheFile->Exists(&exists));
     if (exists) {
-        NS_TRY(cacheFile->Remove(false));
+        MOZ_TRY(cacheFile->Remove(false));
     }
 
     {
         AutoFDClose fd;
-        NS_TRY(cacheFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE, 0644, &fd.rwget()));
+        MOZ_TRY(cacheFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE, 0644, &fd.rwget()));
 
         // We also need to hold mMonitor while we're touching scripts in
         // mScripts, or they may be freed before we're done with them.
         mMonitor.AssertNotCurrentThreadOwns();
         MonitorAutoLock mal(mMonitor);
 
         nsTArray<CachedScript*> scripts;
         for (auto& script : IterHash(mScripts, Match<ScriptStatus::Saved>())) {
@@ -670,17 +670,17 @@ ScriptPreloader::WriteCache()
             MOZ_TRY(Write(fd, script->Range().begin().get(), script->mSize));
 
             if (script->mScript) {
                 script->FreeData();
             }
         }
     }
 
-    NS_TRY(cacheFile->MoveTo(nullptr, mBaseName + NS_LITERAL_STRING(".bin")));
+    MOZ_TRY(cacheFile->MoveTo(nullptr, mBaseName + NS_LITERAL_STRING(".bin")));
 
     return Ok();
 }
 
 // Runs in the mSaveThread thread, and writes out the cache file for the next
 // session after a reasonable delay.
 nsresult
 ScriptPreloader::Run()
--- a/mfbt/Result.h
+++ b/mfbt/Result.h
@@ -250,16 +250,24 @@ struct SelectResultImpl
 template <typename T>
 struct IsResult : FalseType { };
 
 template <typename V, typename E>
 struct IsResult<Result<V, E>> : TrueType { };
 
 } // namespace detail
 
+template <typename V, typename E>
+auto
+ToResult(Result<V, E>&& aValue)
+  -> decltype(Forward<Result<V, E>>(aValue))
+{
+  return Forward<Result<V, E>>(aValue);
+}
+
 /**
  * Result<V, E> represents the outcome of an operation that can either succeed
  * or fail. It contains either a success value of type V or an error value of
  * type E.
  *
  * All Result methods are const, so results are basically immutable.
  * This is just like Variant<V, E> but with a slightly different API, and the
  * following cases are optimized so Result can be stored more efficiently:
@@ -432,17 +440,17 @@ Err(E&& aErrorValue)
 /**
  * MOZ_TRY(expr) is the C++ equivalent of Rust's `try!(expr);`. First, it
  * evaluates expr, which must produce a Result value. On success, it
  * discards the result altogether. On error, it immediately returns an error
  * Result from the enclosing function.
  */
 #define MOZ_TRY(expr) \
   do { \
-    auto mozTryTempResult_ = (expr); \
+    auto mozTryTempResult_ = ::mozilla::ToResult(expr); \
     if (mozTryTempResult_.isErr()) { \
       return ::mozilla::Err(mozTryTempResult_.unwrapErr()); \
     } \
   } while (0)
 
 /**
  * MOZ_TRY_VAR(target, expr) is the C++ equivalent of Rust's `target = try!(expr);`.
  * First, it evaluates expr, which must produce a Result value.
--- a/mfbt/ResultExtensions.h
+++ b/mfbt/ResultExtensions.h
@@ -6,16 +6,17 @@
 
 /* Extensions to the Result type to enable simpler handling of XPCOM/NSPR results. */
 
 #ifndef mozilla_ResultExtensions_h
 #define mozilla_ResultExtensions_h
 
 #include "mozilla/Assertions.h"
 #include "nscore.h"
+#include "prtypes.h"
 
 namespace mozilla {
 
 // Allow nsresult errors to automatically convert to nsresult values, so MOZ_TRY
 // can be used in XPCOM methods with Result<T, nserror> results.
 template <>
 class MOZ_MUST_USE_TYPE GenericErrorResult<nsresult>
 {
@@ -27,11 +28,38 @@ public:
   explicit GenericErrorResult(nsresult aErrorValue) : mErrorValue(aErrorValue)
   {
     MOZ_ASSERT(NS_FAILED(aErrorValue));
   }
 
   operator nsresult() { return mErrorValue; }
 };
 
+// Allow MOZ_TRY to handle `PRStatus` values.
+inline Result<Ok, nsresult> ToResult(PRStatus aValue);
+
+} // namespace mozilla
+
+#include "mozilla/Result.h"
+
+namespace mozilla {
+
+inline Result<Ok, nsresult>
+ToResult(nsresult aValue)
+{
+  if (NS_FAILED(aValue)) {
+    return Err(aValue);
+  }
+  return Ok();
+}
+
+inline Result<Ok, nsresult>
+ToResult(PRStatus aValue)
+{
+  if (aValue == PR_SUCCESS) {
+    return Ok();
+  }
+  return Err(NS_ERROR_FAILURE);
+}
+
 } // namespace mozilla
 
 #endif // mozilla_ResultExtensions_h
--- a/netwerk/protocol/res/ExtensionProtocolHandler.cpp
+++ b/netwerk/protocol/res/ExtensionProtocolHandler.cpp
@@ -10,16 +10,17 @@
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/ExtensionPolicyService.h"
 #include "mozilla/FileUtils.h"
 #include "mozilla/ipc/IPCStreamUtils.h"
 #include "mozilla/ipc/URIParams.h"
 #include "mozilla/ipc/URIUtils.h"
 #include "mozilla/net/NeckoChild.h"
 #include "mozilla/RefPtr.h"
+#include "mozilla/ResultExtensions.h"
 
 #include "FileDescriptor.h"
 #include "FileDescriptorFile.h"
 #include "LoadInfo.h"
 #include "nsContentUtils.h"
 #include "nsServiceManagerUtils.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsIFile.h"
@@ -57,36 +58,16 @@ namespace net {
 using extensions::URLInfo;
 
 LazyLogModule gExtProtocolLog("ExtProtocol");
 #undef LOG
 #define LOG(...) MOZ_LOG(gExtProtocolLog, LogLevel::Debug, (__VA_ARGS__))
 
 StaticRefPtr<ExtensionProtocolHandler> ExtensionProtocolHandler::sSingleton;
 
-static inline Result<Ok, nsresult>
-WrapNSResult(PRStatus aRv)
-{
-    if (aRv != PR_SUCCESS) {
-        return Err(NS_ERROR_FAILURE);
-    }
-    return Ok();
-}
-
-static inline Result<Ok, nsresult>
-WrapNSResult(nsresult aRv)
-{
-    if (NS_FAILED(aRv)) {
-        return Err(aRv);
-    }
-    return Ok();
-}
-
-#define NS_TRY(expr) MOZ_TRY(WrapNSResult(expr))
-
 /**
  * Helper class used with SimpleChannel to asynchronously obtain an input
  * stream or file descriptor from the parent for a remote moz-extension load
  * from the child.
  */
 class ExtensionStreamGetter : public RefCounted<ExtensionStreamGetter>
 {
   public:
@@ -444,31 +425,31 @@ ExtensionProtocolHandler::ResolveSpecial
 
 // For file or JAR URI's, substitute in a remote channel.
 Result<Ok, nsresult>
 ExtensionProtocolHandler::SubstituteRemoteChannel(nsIURI* aURI,
                                                   nsILoadInfo* aLoadInfo,
                                                   nsIChannel** aRetVal)
 {
   MOZ_ASSERT(IsNeckoChild());
-  NS_TRY(aURI ? NS_OK : NS_ERROR_INVALID_ARG);
-  NS_TRY(aLoadInfo ? NS_OK : NS_ERROR_INVALID_ARG);
+  MOZ_TRY(aURI ? NS_OK : NS_ERROR_INVALID_ARG);
+  MOZ_TRY(aLoadInfo ? NS_OK : NS_ERROR_INVALID_ARG);
 
   nsAutoCString unResolvedSpec;
-  NS_TRY(aURI->GetSpec(unResolvedSpec));
+  MOZ_TRY(aURI->GetSpec(unResolvedSpec));
 
   nsAutoCString resolvedSpec;
-  NS_TRY(ResolveURI(aURI, resolvedSpec));
+  MOZ_TRY(ResolveURI(aURI, resolvedSpec));
 
   // Use the target URI scheme to determine if this is a packed or unpacked
   // extension URI. For unpacked extensions, we'll request an input stream
   // from the parent. For a packed extension, we'll request a file descriptor
   // for the JAR file.
   nsAutoCString scheme;
-  NS_TRY(net_ExtractURLScheme(resolvedSpec, scheme));
+  MOZ_TRY(net_ExtractURLScheme(resolvedSpec, scheme));
 
   if (scheme.EqualsLiteral("file")) {
     // Unpacked extension
     SubstituteRemoteFileChannel(aURI, aLoadInfo, resolvedSpec, aRetVal);
     return Ok();
   }
 
   if (scheme.EqualsLiteral("jar")) {
@@ -506,31 +487,31 @@ ExtensionProtocolHandler::SubstituteChan
 
   bool haveLoadInfo = aLoadInfo;
   nsCOMPtr<nsIChannel> channel = NS_NewSimpleChannel(
     aURI, aLoadInfo, *result,
     [haveLoadInfo] (nsIStreamListener* listener, nsIChannel* channel, nsIChannel* origChannel) -> RequestOrReason {
       nsresult rv;
       nsCOMPtr<nsIStreamConverterService> convService =
         do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID, &rv);
-      NS_TRY(rv);
+      MOZ_TRY(rv);
 
       nsCOMPtr<nsIURI> uri;
-      NS_TRY(channel->GetURI(getter_AddRefs(uri)));
+      MOZ_TRY(channel->GetURI(getter_AddRefs(uri)));
 
       const char* kFromType = "application/vnd.mozilla.webext.unlocalized";
       const char* kToType = "text/css";
 
       nsCOMPtr<nsIStreamListener> converter;
-      NS_TRY(convService->AsyncConvertData(kFromType, kToType, listener,
+      MOZ_TRY(convService->AsyncConvertData(kFromType, kToType, listener,
                                         uri, getter_AddRefs(converter)));
       if (haveLoadInfo) {
-        NS_TRY(origChannel->AsyncOpen2(converter));
+        MOZ_TRY(origChannel->AsyncOpen2(converter));
       } else {
-        NS_TRY(origChannel->AsyncOpen(converter, nullptr));
+        MOZ_TRY(origChannel->AsyncOpen(converter, nullptr));
       }
 
       return RequestOrReason(origChannel);
     });
   NS_ENSURE_TRUE(channel, NS_ERROR_OUT_OF_MEMORY);
 
   if (aLoadInfo) {
     nsCOMPtr<nsILoadInfo> loadInfo =
@@ -591,26 +572,26 @@ ExtensionProtocolHandler::DevRepoContain
   MOZ_ASSERT(mozilla::IsDevelopmentBuild());
   MOZ_ASSERT(!IsNeckoChild());
   MOZ_ASSERT(aResult);
   *aResult = false;
 
   // On the first invocation, set mDevRepo
   if (!mAlreadyCheckedDevRepo) {
     mAlreadyCheckedDevRepo = true;
-    NS_TRY(mozilla::GetRepoDir(getter_AddRefs(mDevRepo)));
+    MOZ_TRY(mozilla::GetRepoDir(getter_AddRefs(mDevRepo)));
     if (MOZ_LOG_TEST(gExtProtocolLog, LogLevel::Debug)) {
       nsAutoCString repoPath;
       Unused << mDevRepo->GetNativePath(repoPath);
       LOG("Repo path: %s", repoPath.get());
     }
   }
 
   if (mDevRepo) {
-    NS_TRY(mDevRepo->Contains(aRequestedFile, aResult));
+    MOZ_TRY(mDevRepo->Contains(aRequestedFile, aResult));
   }
 
   return Ok();
 }
 #endif /* XP_MACOSX */
 
 #if !defined(XP_WIN)
 Result<Ok, nsresult>
@@ -620,26 +601,26 @@ ExtensionProtocolHandler::AppDirContains
   MOZ_ASSERT(mozilla::IsDevelopmentBuild());
   MOZ_ASSERT(!IsNeckoChild());
   MOZ_ASSERT(aResult);
   *aResult = false;
 
   // On the first invocation, set mAppDir
   if (!mAlreadyCheckedAppDir) {
     mAlreadyCheckedAppDir = true;
-    NS_TRY(NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(mAppDir)));
+    MOZ_TRY(NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(mAppDir)));
     if (MOZ_LOG_TEST(gExtProtocolLog, LogLevel::Debug)) {
       nsAutoCString appDirPath;
       Unused << mAppDir->GetNativePath(appDirPath);
       LOG("AppDir path: %s", appDirPath.get());
     }
   }
 
   if (mAppDir) {
-    NS_TRY(mAppDir->Contains(aExtensionDir, aResult));
+    MOZ_TRY(mAppDir->Contains(aExtensionDir, aResult));
   }
 
   return Ok();
 }
 #endif /* !defined(XP_WIN) */
 
 static void
 LogExternalResourceError(nsIFile* aExtensionDir, nsIFile* aRequestedFile)
@@ -655,18 +636,18 @@ LogExternalResourceError(nsIFile* aExten
       "extension directory [%s]", requestedFilePath.get(),
       extensionDirPath.get());
 }
 
 Result<nsCOMPtr<nsIInputStream>, nsresult>
 ExtensionProtocolHandler::NewStream(nsIURI* aChildURI, bool* aTerminateSender)
 {
   MOZ_ASSERT(!IsNeckoChild());
-  NS_TRY(aChildURI ? NS_OK : NS_ERROR_INVALID_ARG);
-  NS_TRY(aTerminateSender ? NS_OK : NS_ERROR_INVALID_ARG);
+  MOZ_TRY(aChildURI ? NS_OK : NS_ERROR_INVALID_ARG);
+  MOZ_TRY(aTerminateSender ? NS_OK : NS_ERROR_INVALID_ARG);
 
   *aTerminateSender = true;
   nsresult rv;
 
   // We should never receive a URI that isn't for a moz-extension because
   // these requests ordinarily come from the child's ExtensionProtocolHandler.
   // Ensure this request is for a moz-extension URI. A rogue child process
   // could send us any URI.
@@ -683,167 +664,167 @@ ExtensionProtocolHandler::NewStream(nsIU
 
   /*
    * Make sure there is a substitution installed for the host found
    * in the child's request URI and make sure the host resolves to
    * a directory.
    */
 
   nsAutoCString host;
-  NS_TRY(aChildURI->GetAsciiHost(host));
+  MOZ_TRY(aChildURI->GetAsciiHost(host));
 
   // Lookup the directory this host string resolves to
   nsCOMPtr<nsIURI> baseURI;
-  NS_TRY(GetSubstitution(host, getter_AddRefs(baseURI)));
+  MOZ_TRY(GetSubstitution(host, getter_AddRefs(baseURI)));
 
   // The result should be a file URL for the extension base dir
   nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(baseURI, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIFile> extensionDir;
-  NS_TRY(fileURL->GetFile(getter_AddRefs(extensionDir)));
+  MOZ_TRY(fileURL->GetFile(getter_AddRefs(extensionDir)));
 
   bool isDirectory = false;
-  NS_TRY(extensionDir->IsDirectory(&isDirectory));
+  MOZ_TRY(extensionDir->IsDirectory(&isDirectory));
   if (!isDirectory) {
     // The host should map to a directory for unpacked extensions
     return Err(NS_ERROR_FILE_NOT_DIRECTORY);
   }
 
   // Make sure the child URI resolves to a file URI then get a file
   // channel for the request. The resultant channel should be a
   // file channel because we only request remote streams for unpacked
   // extension resource loads where the URI resolves to a file.
   nsAutoCString resolvedSpec;
-  NS_TRY(ResolveURI(aChildURI, resolvedSpec));
+  MOZ_TRY(ResolveURI(aChildURI, resolvedSpec));
 
   nsAutoCString resolvedScheme;
-  NS_TRY(net_ExtractURLScheme(resolvedSpec, resolvedScheme));
+  MOZ_TRY(net_ExtractURLScheme(resolvedSpec, resolvedScheme));
   if (!resolvedScheme.EqualsLiteral("file")) {
     return Err(NS_ERROR_UNEXPECTED);
   }
 
   nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIURI> resolvedURI;
-  NS_TRY(ioService->NewURI(resolvedSpec,
-                           nullptr,
-                           nullptr,
-                           getter_AddRefs(resolvedURI)));
+  MOZ_TRY(ioService->NewURI(resolvedSpec,
+                            nullptr,
+                            nullptr,
+                            getter_AddRefs(resolvedURI)));
 
   // We use the system principal to get a file channel for the request,
   // but only after we've checked (above) that the child URI is of
   // moz-extension scheme and that the URI host maps to a directory.
   nsCOMPtr<nsIChannel> channel;
-  NS_TRY(NS_NewChannel(getter_AddRefs(channel),
-                       resolvedURI,
-                       nsContentUtils::GetSystemPrincipal(),
-                       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
-                       nsIContentPolicy::TYPE_OTHER));
+  MOZ_TRY(NS_NewChannel(getter_AddRefs(channel),
+                        resolvedURI,
+                        nsContentUtils::GetSystemPrincipal(),
+                        nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
+                        nsIContentPolicy::TYPE_OTHER));
 
   nsCOMPtr<nsIFileChannel> fileChannel = do_QueryInterface(channel, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIFile> requestedFile;
-  NS_TRY(fileChannel->GetFile(getter_AddRefs(requestedFile)));
+  MOZ_TRY(fileChannel->GetFile(getter_AddRefs(requestedFile)));
 
   /*
    * Make sure the file we resolved to is within the extension directory.
    */
 
   // Normalize paths for sane comparisons. nsIFile::Contains depends on
   // it for reliable subpath checks.
-  NS_TRY(extensionDir->Normalize());
-  NS_TRY(requestedFile->Normalize());
+  MOZ_TRY(extensionDir->Normalize());
+  MOZ_TRY(requestedFile->Normalize());
 #if defined(XP_WIN)
   if (!widget::WinUtils::ResolveJunctionPointsAndSymLinks(extensionDir) ||
       !widget::WinUtils::ResolveJunctionPointsAndSymLinks(requestedFile)) {
     return Err(NS_ERROR_FILE_ACCESS_DENIED);
   }
 #endif
 
   bool isResourceFromExtensionDir = false;
-  NS_TRY(extensionDir->Contains(requestedFile, &isResourceFromExtensionDir));
+  MOZ_TRY(extensionDir->Contains(requestedFile, &isResourceFromExtensionDir));
   if (!isResourceFromExtensionDir) {
     bool isAllowed = false;
     MOZ_TRY(AllowExternalResource(extensionDir, requestedFile, &isAllowed));
     if (!isAllowed) {
       LogExternalResourceError(extensionDir, requestedFile);
       return Err(NS_ERROR_FILE_ACCESS_DENIED);
     }
   }
 
   nsCOMPtr<nsIInputStream> inputStream;
-  NS_TRY(NS_NewLocalFileInputStream(getter_AddRefs(inputStream),
-                                    requestedFile,
-                                    PR_RDONLY,
-                                    -1,
-                                    nsIFileInputStream::DEFER_OPEN));
+  MOZ_TRY(NS_NewLocalFileInputStream(getter_AddRefs(inputStream),
+                                     requestedFile,
+                                     PR_RDONLY,
+                                     -1,
+                                     nsIFileInputStream::DEFER_OPEN));
 
   return inputStream;
 }
 
 Result<Ok, nsresult>
 ExtensionProtocolHandler::NewFD(nsIURI* aChildURI,
                                 bool* aTerminateSender,
                                 NeckoParent::GetExtensionFDResolver& aResolve)
 {
   MOZ_ASSERT(!IsNeckoChild());
-  NS_TRY(aChildURI ? NS_OK : NS_ERROR_INVALID_ARG);
-  NS_TRY(aTerminateSender ? NS_OK : NS_ERROR_INVALID_ARG);
+  MOZ_TRY(aChildURI ? NS_OK : NS_ERROR_INVALID_ARG);
+  MOZ_TRY(aTerminateSender ? NS_OK : NS_ERROR_INVALID_ARG);
 
   *aTerminateSender = true;
   nsresult rv;
 
   // Ensure this is a moz-extension URI
   bool isExtScheme = false;
   if (NS_FAILED(aChildURI->SchemeIs(EXTENSION_SCHEME, &isExtScheme)) ||
       !isExtScheme) {
     return Err(NS_ERROR_UNKNOWN_PROTOCOL);
   }
 
   // For errors after this point, we want to propagate the error to
   // the child, but we don't force the child to be terminated.
   *aTerminateSender = false;
 
   nsAutoCString host;
-  NS_TRY(aChildURI->GetAsciiHost(host));
+  MOZ_TRY(aChildURI->GetAsciiHost(host));
 
   // We expect the host string to map to a JAR file because the URI
   // should refer to a web accessible resource for an enabled extension.
   nsCOMPtr<nsIURI> subURI;
-  NS_TRY(GetSubstitution(host, getter_AddRefs(subURI)));
+  MOZ_TRY(GetSubstitution(host, getter_AddRefs(subURI)));
 
   nsCOMPtr<nsIJARURI> jarURI = do_QueryInterface(subURI, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIURI> innerFileURI;
-  NS_TRY(jarURI->GetJARFile(getter_AddRefs(innerFileURI)));
+  MOZ_TRY(jarURI->GetJARFile(getter_AddRefs(innerFileURI)));
 
   nsCOMPtr<nsIFileURL> innerFileURL = do_QueryInterface(innerFileURI, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIFile> jarFile;
-  NS_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile)));
+  MOZ_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile)));
 
   if (!mFileOpenerThread) {
     mFileOpenerThread =
       new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS,
                          NS_LITERAL_CSTRING("ExtensionProtocolHandler"));
   }
 
   RefPtr<ExtensionJARFileOpener> fileOpener =
     new ExtensionJARFileOpener(jarFile, aResolve);
 
   nsCOMPtr<nsIRunnable> event =
     mozilla::NewRunnableMethod("ExtensionJarFileOpener",
         fileOpener, &ExtensionJARFileOpener::OpenFile);
 
-  NS_TRY(mFileOpenerThread->Dispatch(event, nsIEventTarget::DISPATCH_NORMAL));
+  MOZ_TRY(mFileOpenerThread->Dispatch(event, nsIEventTarget::DISPATCH_NORMAL));
 
   return Ok();
 }
 
 static void
 NewSimpleChannel(nsIURI* aURI,
                  nsILoadInfo* aLoadinfo,
                  ExtensionStreamGetter* aStreamGetter,
@@ -887,23 +868,23 @@ ExtensionProtocolHandler::SubstituteRemo
 static Result<Ok, nsresult>
 LogCacheCheck(const nsIJARChannel* aJarChannel,
               nsIJARURI* aJarURI,
               bool aIsCached)
 {
   nsresult rv;
 
   nsCOMPtr<nsIURI> innerFileURI;
-  NS_TRY(aJarURI->GetJARFile(getter_AddRefs(innerFileURI)));
+  MOZ_TRY(aJarURI->GetJARFile(getter_AddRefs(innerFileURI)));
 
   nsCOMPtr<nsIFileURL> innerFileURL = do_QueryInterface(innerFileURI, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIFile> jarFile;
-  NS_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile)));
+  MOZ_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile)));
 
   nsAutoCString uriSpec, jarSpec;
   Unused << aJarURI->GetSpec(uriSpec);
   Unused << innerFileURI->GetSpec(jarSpec);
   LOG("[JARChannel %p] Cache %s: %s (%s)",
       aJarChannel, aIsCached ? "hit" : "miss", uriSpec.get(), jarSpec.get());
 
   return Ok();
@@ -916,50 +897,48 @@ ExtensionProtocolHandler::SubstituteRemo
                                                      nsIChannel** aRetVal)
 {
   MOZ_ASSERT(IsNeckoChild());
   nsresult rv;
 
   // Build a JAR URI for this jar:file:// URI and use it to extract the
   // inner file URI.
   nsCOMPtr<nsIURI> uri;
-  NS_TRY(NS_NewURI(getter_AddRefs(uri), aResolvedSpec));
+  MOZ_TRY(NS_NewURI(getter_AddRefs(uri), aResolvedSpec));
 
   nsCOMPtr<nsIJARURI> jarURI = do_QueryInterface(uri, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<nsIJARChannel> jarChannel = do_QueryInterface(*aRetVal, &rv);
-  NS_TRY(rv);
+  MOZ_TRY(rv);
 
   bool isCached = false;
-  NS_TRY(jarChannel->EnsureCached(&isCached));
+  MOZ_TRY(jarChannel->EnsureCached(&isCached));
   if (MOZ_LOG_TEST(gExtProtocolLog, LogLevel::Debug)) {
     Unused << LogCacheCheck(jarChannel, jarURI, isCached);
   }
 
   RefPtr<ExtensionStreamGetter> streamGetter;
 
   if (isCached) {
     streamGetter = new ExtensionStreamGetter(jarChannel.forget());
   } else {
     nsCOMPtr<nsIURI> innerFileURI;
-    NS_TRY(jarURI->GetJARFile(getter_AddRefs(innerFileURI)));
+    MOZ_TRY(jarURI->GetJARFile(getter_AddRefs(innerFileURI)));
 
     nsCOMPtr<nsIFileURL> innerFileURL = do_QueryInterface(innerFileURI, &rv);
-    NS_TRY(rv);
+    MOZ_TRY(rv);
 
     nsCOMPtr<nsIFile> jarFile;
-    NS_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile)));
+    MOZ_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile)));
 
     streamGetter = new ExtensionStreamGetter(aURI,
                                              aLoadinfo,
                                              jarChannel.forget(),
                                              jarFile);
   }
 
   NewSimpleChannel(aURI, aLoadinfo, streamGetter, aRetVal);
   return Ok();
 }
 
-#undef NS_TRY
-
 } // namespace net
 } // namespace mozilla
--- a/security/certverifier/tests/gtest/BTSerializationTest.cpp
+++ b/security/certverifier/tests/gtest/BTSerializationTest.cpp
@@ -69,92 +69,92 @@ TEST_F(BTSerializationTest, DecodesInclu
 }
 
 TEST_F(BTSerializationTest, FailsDecodingInclusionProofUnexpectedData)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofUnexpectedData);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingInvalidHashSize)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofInvalidHashSize);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingInvalidHash)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofInvalidHash);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingMissingLogId)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofMissingLogId);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingNullPathLength)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofNullPathLength);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingPathLengthTooSmall)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofPathLengthTooSmall);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingPathLengthTooLarge)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofPathLengthTooLarge);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingNullTreeSize)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofNullTreeSize);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingLeafIndexOutOfBounds)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofLeafIndexOutOfBounds);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 
 TEST_F(BTSerializationTest, FailsDecodingExtraData)
 {
   Input encodedProofInput = InputForBuffer(mTestInclusionProofExtraData);
   Reader encodedProofReader(encodedProofInput);
   InclusionProofDataV2 ipr;
 
-  ASSERT_EQ(Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
+  ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr));
 }
 } } // namespace mozilla::ct
--- a/security/certverifier/tests/gtest/CTSerializationTest.cpp
+++ b/security/certverifier/tests/gtest/CTSerializationTest.cpp
@@ -224,24 +224,24 @@ TEST_F(CTSerializationTest, DecodesSigne
 TEST_F(CTSerializationTest, FailsDecodingInvalidSignedCertificateTimestamp)
 {
   SignedCertificateTimestamp sct;
 
   // Invalid version
   const uint8_t INVALID_VERSION_BYTES[] = { 0x02, 0x00 };
   Input invalidVersionSctInput(INVALID_VERSION_BYTES);
   Reader invalidVersionSctReader(invalidVersionSctInput);
-  EXPECT_EQ(Result::ERROR_BAD_DER,
+  EXPECT_EQ(pkix::Result::ERROR_BAD_DER,
     DecodeSignedCertificateTimestamp(invalidVersionSctReader, sct));
 
   // Valid version, invalid length (missing data)
   const uint8_t INVALID_LENGTH_BYTES[] = { 0x00, 0x0a, 0x0b, 0x0c };
   Input invalidLengthSctInput(INVALID_LENGTH_BYTES);
   Reader invalidLengthSctReader(invalidLengthSctInput);
-  EXPECT_EQ(Result::ERROR_BAD_DER,
+  EXPECT_EQ(pkix::Result::ERROR_BAD_DER,
     DecodeSignedCertificateTimestamp(invalidLengthSctReader, sct));
 }
 
 TEST_F(CTSerializationTest, EncodesValidSignedTreeHead)
 {
   SignedTreeHead signedTreeHead;
   GetSampleSignedTreeHead(signedTreeHead);
 
--- a/security/certverifier/tests/gtest/CTTestUtils.cpp
+++ b/security/certverifier/tests/gtest/CTTestUtils.cpp
@@ -749,93 +749,93 @@ void
 ExtractEmbeddedSCTList(const Buffer& cert, Buffer& result)
 {
   ExtractEmbeddedSCTList(InputForBuffer(cert), result);
 }
 
 class OCSPExtensionTrustDomain : public TrustDomain
 {
 public:
-  Result GetCertTrust(EndEntityOrCA, const CertPolicyId&,
-                      Input, TrustLevel&) override
+  pkix::Result GetCertTrust(EndEntityOrCA, const CertPolicyId&,
+                            Input, TrustLevel&) override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result FindIssuer(Input, IssuerChecker&, Time) override
+  pkix::Result FindIssuer(Input, IssuerChecker&, Time) override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result CheckRevocation(EndEntityOrCA, const CertID&, Time, Duration,
-                         const Input*, const Input*) override
+  pkix::Result CheckRevocation(EndEntityOrCA, const CertID&, Time, Duration,
+                               const Input*, const Input*) override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result IsChainValid(const DERArray&, Time, const CertPolicyId&) override
+  pkix::Result IsChainValid(const DERArray&, Time, const CertPolicyId&) override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result DigestBuf(Input item, DigestAlgorithm digestAlg,
-                   /*out*/ uint8_t* digestBuf, size_t digestBufLen) override
+  pkix::Result DigestBuf(Input item, DigestAlgorithm digestAlg,
+                         /*out*/ uint8_t* digestBuf, size_t digestBufLen) override
   {
     return DigestBufNSS(item, digestAlg, digestBuf, digestBufLen);
   }
 
-  Result CheckSignatureDigestAlgorithm(DigestAlgorithm, EndEntityOrCA, Time)
+  pkix::Result CheckSignatureDigestAlgorithm(DigestAlgorithm, EndEntityOrCA, Time)
                                        override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result CheckECDSACurveIsAcceptable(EndEntityOrCA, NamedCurve) override
+  pkix::Result CheckECDSACurveIsAcceptable(EndEntityOrCA, NamedCurve) override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result VerifyECDSASignedDigest(const SignedDigest& signedDigest,
-                                 Input subjectPublicKeyInfo) override
+  pkix::Result VerifyECDSASignedDigest(const SignedDigest& signedDigest,
+                                       Input subjectPublicKeyInfo) override
   {
     return VerifyECDSASignedDigestNSS(signedDigest, subjectPublicKeyInfo,
                                       nullptr);
   }
 
-  Result CheckRSAPublicKeyModulusSizeInBits(EndEntityOrCA, unsigned int)
+  pkix::Result CheckRSAPublicKeyModulusSizeInBits(EndEntityOrCA, unsigned int)
                                             override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result VerifyRSAPKCS1SignedDigest(const SignedDigest& signedDigest,
-                                    Input subjectPublicKeyInfo) override
+  pkix::Result VerifyRSAPKCS1SignedDigest(const SignedDigest& signedDigest,
+                                          Input subjectPublicKeyInfo) override
   {
     return VerifyRSAPKCS1SignedDigestNSS(signedDigest, subjectPublicKeyInfo,
                                          nullptr);
   }
 
-  Result CheckValidityIsAcceptable(Time, Time, EndEntityOrCA, KeyPurposeId)
+  pkix::Result CheckValidityIsAcceptable(Time, Time, EndEntityOrCA, KeyPurposeId)
                                    override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
-  Result NetscapeStepUpMatchesServerAuth(Time, bool&) override
+  pkix::Result NetscapeStepUpMatchesServerAuth(Time, bool&) override
   {
     ADD_FAILURE();
-    return Result::FATAL_ERROR_LIBRARY_FAILURE;
+    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
   }
 
   void NoteAuxiliaryExtension(AuxiliaryExtension extension, Input data) override
   {
     if (extension != AuxiliaryExtension::SCTListFromOCSPResponse) {
       ADD_FAILURE();
       return;
     }
@@ -859,20 +859,20 @@ ExtractSCTListFromOCSPResponse(Input cer
 
   BackCert backCert(cert, EndEntityOrCA::MustBeEndEntity, nullptr);
   ASSERT_EQ(Success, backCert.Init());
 
   CertID certID(backCert.GetIssuer(), issuerSPKI, backCert.GetSerialNumber());
 
   bool expired;
   OCSPExtensionTrustDomain trustDomain;
-  Result rv = VerifyEncodedOCSPResponse(trustDomain, certID,
-                                        time, /*time*/
-                                        1000, /*maxLifetimeInDays*/
-                                        encodedResponse, expired);
+  pkix::Result rv = VerifyEncodedOCSPResponse(trustDomain, certID,
+                                              time, /*time*/
+                                              1000, /*maxLifetimeInDays*/
+                                              encodedResponse, expired);
   ASSERT_EQ(Success, rv);
 
   result = Move(trustDomain.signedCertificateTimestamps);
 }
 
 Buffer
 cloneBuffer(const Buffer& buffer)
 {
--- a/toolkit/components/extensions/WebExtensionPolicy.cpp
+++ b/toolkit/components/extensions/WebExtensionPolicy.cpp
@@ -14,36 +14,16 @@
 #include "nsNetUtil.h"
 #include "nsPrintfCString.h"
 
 namespace mozilla {
 namespace extensions {
 
 using namespace dom;
 
-static inline Result<Ok, nsresult>
-WrapNSResult(PRStatus aRv)
-{
-  if (aRv != PR_SUCCESS) {
-    return Err(NS_ERROR_FAILURE);
-  }
-  return Ok();
-}
-
-static inline Result<Ok, nsresult>
-WrapNSResult(nsresult aRv)
-{
-  if (NS_FAILED(aRv)) {
-    return Err(aRv);
-  }
-  return Ok();
-}
-
-#define NS_TRY(expr) MOZ_TRY(WrapNSResult(expr))
-
 static const char kProto[] = "moz-extension";
 
 static const char kBackgroundPageHTMLStart[] = "<!DOCTYPE html>\n\
 <html>\n\
   <head><meta charset=\"utf-8\"></head>\n\
   <body>";
 
 static const char kBackgroundPageHTMLScript[] = "\n\
@@ -220,19 +200,19 @@ WebExtensionPolicy::GetURL(const nsAStri
 }
 
 Result<nsString, nsresult>
 WebExtensionPolicy::GetURL(const nsAString& aPath) const
 {
   nsPrintfCString spec("%s://%s/", kProto, mHostname.get());
 
   nsCOMPtr<nsIURI> uri;
-  NS_TRY(NS_NewURI(getter_AddRefs(uri), spec));
+  MOZ_TRY(NS_NewURI(getter_AddRefs(uri), spec));
 
-  NS_TRY(uri->Resolve(NS_ConvertUTF16toUTF8(aPath), spec));
+  MOZ_TRY(uri->Resolve(NS_ConvertUTF16toUTF8(aPath), spec));
 
   return NS_ConvertUTF8toUTF16(spec);
 }
 
 /* static */ bool
 WebExtensionPolicy::IsExtensionProcess(GlobalObject& aGlobal)
 {
   return EPS().IsExtensionProcess();
--- a/toolkit/mozapps/extensions/AddonManagerStartup.cpp
+++ b/toolkit/mozapps/extensions/AddonManagerStartup.cpp
@@ -38,37 +38,16 @@
 #include "nsJSUtils.h"
 #include "nsReadableUtils.h"
 #include "nsXULAppAPI.h"
 
 #include <stdlib.h>
 
 namespace mozilla {
 
-static inline Result<Ok, nsresult>
-WrapNSResult(PRStatus aRv)
-{
-    if (aRv != PR_SUCCESS) {
-        return Err(NS_ERROR_FAILURE);
-    }
-    return Ok();
-}
-
-static inline Result<Ok, nsresult>
-WrapNSResult(nsresult aRv)
-{
-    if (NS_FAILED(aRv)) {
-        return Err(aRv);
-    }
-    return Ok();
-}
-
-#define NS_TRY(expr) MOZ_TRY(WrapNSResult(expr))
-
-
 using Compression::LZ4;
 using dom::ipc::StructuredCloneData;
 
 #ifdef XP_WIN
 #  define READ_BINARYMODE "rb"
 #else
 #  define READ_BINARYMODE "r"
 #endif
@@ -126,17 +105,17 @@ IsNormalFile(nsIFile* file)
 }
 
 static Result<nsCString, nsresult>
 ReadFile(nsIFile* file)
 {
   nsCString result;
 
   AutoFDClose fd;
-  NS_TRY(file->OpenNSPRFileDesc(PR_RDONLY, 0, &fd.rwget()));
+  MOZ_TRY(file->OpenNSPRFileDesc(PR_RDONLY, 0, &fd.rwget()));
 
   auto size = PR_Seek64(fd, 0, PR_SEEK_END);
   PR_Seek64(fd, 0, PR_SEEK_SET);
 
   result.SetLength(size);
 
   auto len = PR_Read(fd, result.BeginWriting(), size);
 
@@ -242,51 +221,51 @@ ParseJSON(JSContext* cx, nsACString& jso
 
 static Result<nsCOMPtr<nsIZipReaderCache>, nsresult>
 GetJarCache()
 {
   nsCOMPtr<nsIIOService> ios = services::GetIOService();
   NS_ENSURE_TRUE(ios, Err(NS_ERROR_FAILURE));
 
   nsCOMPtr<nsIProtocolHandler> jarProto;
-  NS_TRY(ios->GetProtocolHandler("jar", getter_AddRefs(jarProto)));
+  MOZ_TRY(ios->GetProtocolHandler("jar", getter_AddRefs(jarProto)));
 
   nsCOMPtr<nsIJARProtocolHandler> jar = do_QueryInterface(jarProto);
   MOZ_ASSERT(jar);
 
   nsCOMPtr<nsIZipReaderCache> zipCache;
-  NS_TRY(jar->GetJARCache(getter_AddRefs(zipCache)));
+  MOZ_TRY(jar->GetJARCache(getter_AddRefs(zipCache)));
 
   return Move(zipCache);
 }
 
 static Result<FileLocation, nsresult>
 GetFileLocation(nsIURI* uri)
 {
   FileLocation location;
 
   nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(uri);
   nsCOMPtr<nsIFile> file;
   if (fileURL) {
-    NS_TRY(fileURL->GetFile(getter_AddRefs(file)));
+    MOZ_TRY(fileURL->GetFile(getter_AddRefs(file)));
     location.Init(file);
   } else {
     nsCOMPtr<nsIJARURI> jarURI = do_QueryInterface(uri);
     NS_ENSURE_TRUE(jarURI, Err(NS_ERROR_INVALID_ARG));
 
     nsCOMPtr<nsIURI> fileURI;
-    NS_TRY(jarURI->GetJARFile(getter_AddRefs(fileURI)));
+    MOZ_TRY(jarURI->GetJARFile(getter_AddRefs(fileURI)));
 
     fileURL = do_QueryInterface(fileURI);
     NS_ENSURE_TRUE(fileURL, Err(NS_ERROR_INVALID_ARG));
 
-    NS_TRY(fileURL->GetFile(getter_AddRefs(file)));
+    MOZ_TRY(fileURL->GetFile(getter_AddRefs(file)));
 
     nsCString entry;
-    NS_TRY(jarURI->GetJAREntry(entry));
+    MOZ_TRY(jarURI->GetJAREntry(entry));
 
     location.Init(file, entry.get());
   }
 
   return Move(location);
 }
 
 
@@ -480,19 +459,19 @@ Addon::FullPath()
 
   // First check for an absolute path, in case we have a proxy file.
   nsCOMPtr<nsIFile> file;
   if (NS_SUCCEEDED(NS_NewLocalFile(path, false, getter_AddRefs(file)))) {
     return Move(file);
   }
 
   // If not an absolute path, fall back to a relative path from the location.
-  NS_TRY(NS_NewLocalFile(mLocation.Path(), false, getter_AddRefs(file)));
+  MOZ_TRY(NS_NewLocalFile(mLocation.Path(), false, getter_AddRefs(file)));
 
-  NS_TRY(file->AppendRelativePath(path));
+  MOZ_TRY(file->AppendRelativePath(path));
   return Move(file);
 }
 
 NSLocationType
 Addon::LocationType()
 {
   nsString type = GetString("type", "extension");
   if (type.LowerCaseEqualsLiteral("theme")) {
@@ -575,17 +554,17 @@ EnableShims(const nsAString& addonId)
 
 Result<Ok, nsresult>
 AddonManagerStartup::AddInstallLocation(Addon& addon)
 {
   nsCOMPtr<nsIFile> file;
   MOZ_TRY_VAR(file, addon.FullPath());
 
   nsString path;
-  NS_TRY(file->GetPath(path));
+  MOZ_TRY(file->GetPath(path));
 
   auto type = addon.LocationType();
 
   if (type == NS_SKIN_LOCATION) {
     mThemePaths.AppendElement(file);
   } else {
     mExtensionPaths.AppendElement(file);
   }
@@ -694,17 +673,17 @@ AddonManagerStartup::EncodeBlob(JS::Hand
     scData.Append(nsDependentCSubstring(iter.Data(), iter.RemainingInSegment()));
     iter.Advance(data, iter.RemainingInSegment());
   }
 
   nsCString lz4;
   MOZ_TRY_VAR(lz4, EncodeLZ4(scData, STRUCTURED_CLONE_MAGIC));
 
   JS::RootedObject obj(cx);
-  NS_TRY(nsContentUtils::CreateArrayBuffer(cx, lz4, &obj.get()));
+  MOZ_TRY(nsContentUtils::CreateArrayBuffer(cx, lz4, &obj.get()));
 
   result.set(JS::ObjectValue(*obj));
   return NS_OK;
 }
 
 nsresult
 AddonManagerStartup::DecodeBlob(JS::HandleValue value, JSContext* cx, JS::MutableHandleValue result)
 {
@@ -744,26 +723,26 @@ AddonManagerStartup::EnumerateZipFile(ns
   NS_ENSURE_ARG_POINTER(file);
   NS_ENSURE_ARG_POINTER(countOut);
   NS_ENSURE_ARG_POINTER(entriesOut);
 
   nsCOMPtr<nsIZipReaderCache> zipCache;
   MOZ_TRY_VAR(zipCache, GetJarCache());
 
   nsCOMPtr<nsIZipReader> zip;
-  NS_TRY(zipCache->GetZip(file, getter_AddRefs(zip)));
+  MOZ_TRY(zipCache->GetZip(file, getter_AddRefs(zip)));
 
   nsCOMPtr<nsIUTF8StringEnumerator> entries;
-  NS_TRY(zip->FindEntries(pattern, getter_AddRefs(entries)));
+  MOZ_TRY(zip->FindEntries(pattern, getter_AddRefs(entries)));
 
   nsTArray<nsString> results;
   bool hasMore;
   while (NS_SUCCEEDED(entries->HasMore(&hasMore)) && hasMore) {
     nsAutoCString name;
-    NS_TRY(entries->GetNext(name));
+    MOZ_TRY(entries->GetNext(name));
 
     results.AppendElement(NS_ConvertUTF8toUTF16(name));
   }
 
   auto strResults = MakeUnique<char16_t*[]>(results.Length());
   for (uint32_t i = 0; i < results.Length(); i++) {
     strResults[i] = ToNewUnicode(results[i]);
   }
--- a/xpcom/base/nscore.h
+++ b/xpcom/base/nscore.h
@@ -210,16 +210,22 @@ template<>
 struct UnusedZero<nsresult>
 {
   static const bool value = true;
 };
 } // namespace detail
 
 template <typename T> class MOZ_MUST_USE_TYPE GenericErrorResult;
 template <> class MOZ_MUST_USE_TYPE GenericErrorResult<nsresult>;
+
+struct Ok;
+template <typename V, typename E> class Result;
+
+// Allow MOZ_TRY to handle `nsresult` values.
+inline Result<Ok, nsresult> ToResult(nsresult aValue);
 } // namespace mozilla
 
 /*
  * Use these macros to do 64bit safe pointer conversions.
  */
 
 #define NS_PTR_TO_INT32(x) ((int32_t)(intptr_t)(x))
 #define NS_PTR_TO_UINT32(x) ((uint32_t)(intptr_t)(x))