1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "mozilla/ArrayUtils.h"
8 #include "mozilla/ErrorNames.h"
9 #include "nsString.h"
10 #include "prerror.h"
11 
12 // Get the GetErrorNameInternal method
13 #include "ErrorNamesInternal.h"
14 
15 namespace mozilla {
16 
GetStaticErrorName(nsresult rv)17 const char* GetStaticErrorName(nsresult rv) { return GetErrorNameInternal(rv); }
18 
GetErrorName(nsresult rv,nsACString & name)19 void GetErrorName(nsresult rv, nsACString& name) {
20   if (const char* errorName = GetErrorNameInternal(rv)) {
21     name.AssignASCII(errorName);
22     return;
23   }
24 
25   bool isSecurityError = NS_ERROR_GET_MODULE(rv) == NS_ERROR_MODULE_SECURITY;
26 
27   // NS_ERROR_MODULE_SECURITY is the only module that is "allowed" to
28   // synthesize nsresult error codes that are not listed in ErrorList.h. (The
29   // NS_ERROR_MODULE_SECURITY error codes are synthesized from NSPR error
30   // codes.)
31   MOZ_ASSERT(isSecurityError);
32 
33   if (NS_SUCCEEDED(rv)) {
34     name.AssignLiteral("NS_ERROR_GENERATE_SUCCESS(");
35   } else {
36     name.AssignLiteral("NS_ERROR_GENERATE_FAILURE(");
37   }
38 
39   if (isSecurityError) {
40     name.AppendLiteral("NS_ERROR_MODULE_SECURITY");
41   } else {
42     // This should never happen given the assertion above, so we don't bother
43     // trying to print a symbolic name for the module here.
44     name.AppendInt(NS_ERROR_GET_MODULE(rv));
45   }
46 
47   name.AppendLiteral(", ");
48 
49   const char* nsprName = nullptr;
50   if (isSecurityError) {
51     // Invert the logic from NSSErrorsService::GetXPCOMFromNSSError
52     PRErrorCode nsprCode = -1 * static_cast<PRErrorCode>(NS_ERROR_GET_CODE(rv));
53     nsprName = PR_ErrorToName(nsprCode);
54 
55     // All NSPR error codes defined by NSPR or NSS should have a name mapping.
56     MOZ_ASSERT(nsprName);
57   }
58 
59   if (nsprName) {
60     name.AppendASCII(nsprName);
61   } else {
62     name.AppendInt(NS_ERROR_GET_CODE(rv));
63   }
64 
65   name.AppendLiteral(")");
66 }
67 
68 }  // namespace mozilla
69 
70 extern "C" {
71 
72 // This is an extern "C" binding for the GetErrorName method which is used by
73 // the nsresult rust bindings in xpcom/rust/nserror.
Gecko_GetErrorName(nsresult aRv,nsACString & aName)74 void Gecko_GetErrorName(nsresult aRv, nsACString& aName) {
75   mozilla::GetErrorName(aRv, aName);
76 }
77 }
78