GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_errors.h Lines: 13 16 81.2 %
Date: 2021-10-02 04:13:01 Branches: 0 0 - %

Line Branch Exec Source
1
#ifndef SRC_NODE_ERRORS_H_
2
#define SRC_NODE_ERRORS_H_
3
4
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
6
#include "debug_utils-inl.h"
7
#include "env.h"
8
#include "v8.h"
9
10
// Use ostringstream to print exact-width integer types
11
// because the format specifiers are not available on AIX.
12
#include <sstream>
13
14
namespace node {
15
16
enum ErrorHandlingMode { CONTEXTIFY_ERROR, FATAL_ERROR, MODULE_ERROR };
17
void AppendExceptionLine(Environment* env,
18
                         v8::Local<v8::Value> er,
19
                         v8::Local<v8::Message> message,
20
                         enum ErrorHandlingMode mode);
21
22
[[noreturn]] void FatalError(const char* location, const char* message);
23
void OnFatalError(const char* location, const char* message);
24
25
// Helpers to construct errors similar to the ones provided by
26
// lib/internal/errors.js.
27
// Example: with `V(ERR_INVALID_ARG_TYPE, TypeError)`, there will be
28
// `node::ERR_INVALID_ARG_TYPE(isolate, "message")` returning
29
// a `Local<Value>` containing the TypeError with proper code and message
30
31
#define ERRORS_WITH_CODE(V)                                                    \
32
  V(ERR_BUFFER_CONTEXT_NOT_AVAILABLE, Error)                                   \
33
  V(ERR_BUFFER_OUT_OF_BOUNDS, RangeError)                                      \
34
  V(ERR_BUFFER_TOO_LARGE, Error)                                               \
35
  V(ERR_CLOSED_MESSAGE_PORT, Error)                                            \
36
  V(ERR_CONSTRUCT_CALL_REQUIRED, TypeError)                                    \
37
  V(ERR_CONSTRUCT_CALL_INVALID, TypeError)                                     \
38
  V(ERR_CRYPTO_INITIALIZATION_FAILED, Error)                                   \
39
  V(ERR_CRYPTO_INVALID_AUTH_TAG, TypeError)                                    \
40
  V(ERR_CRYPTO_INVALID_COUNTER, TypeError)                                     \
41
  V(ERR_CRYPTO_INVALID_CURVE, TypeError)                                       \
42
  V(ERR_CRYPTO_INVALID_DIGEST, TypeError)                                      \
43
  V(ERR_CRYPTO_INVALID_IV, TypeError)                                          \
44
  V(ERR_CRYPTO_INVALID_JWK, TypeError)                                         \
45
  V(ERR_CRYPTO_INVALID_KEYLEN, RangeError)                                     \
46
  V(ERR_CRYPTO_INVALID_KEYPAIR, RangeError)                                    \
47
  V(ERR_CRYPTO_INVALID_KEYTYPE, RangeError)                                    \
48
  V(ERR_CRYPTO_INVALID_MESSAGELEN, RangeError)                                 \
49
  V(ERR_CRYPTO_INVALID_SCRYPT_PARAMS, RangeError)                              \
50
  V(ERR_CRYPTO_INVALID_STATE, Error)                                           \
51
  V(ERR_CRYPTO_INVALID_TAG_LENGTH, RangeError)                                 \
52
  V(ERR_CRYPTO_JWK_UNSUPPORTED_CURVE, Error)                                   \
53
  V(ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE, Error)                                \
54
  V(ERR_CRYPTO_OPERATION_FAILED, Error)                                        \
55
  V(ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, RangeError)                           \
56
  V(ERR_CRYPTO_UNKNOWN_CIPHER, Error)                                          \
57
  V(ERR_CRYPTO_UNKNOWN_DH_GROUP, Error)                                        \
58
  V(ERR_CRYPTO_UNSUPPORTED_OPERATION, Error)                                   \
59
  V(ERR_CRYPTO_JOB_INIT_FAILED, Error)                                         \
60
  V(ERR_DLOPEN_DISABLED, Error)                                                \
61
  V(ERR_DLOPEN_FAILED, Error)                                                  \
62
  V(ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE, Error)                            \
63
  V(ERR_INVALID_ADDRESS, Error)                                                \
64
  V(ERR_INVALID_ARG_VALUE, TypeError)                                          \
65
  V(ERR_OSSL_EVP_INVALID_DIGEST, Error)                                        \
66
  V(ERR_INVALID_ARG_TYPE, TypeError)                                           \
67
  V(ERR_INVALID_MODULE, Error)                                                 \
68
  V(ERR_INVALID_THIS, TypeError)                                               \
69
  V(ERR_INVALID_TRANSFER_OBJECT, TypeError)                                    \
70
  V(ERR_MEMORY_ALLOCATION_FAILED, Error)                                       \
71
  V(ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE, Error)                             \
72
  V(ERR_MISSING_ARGS, TypeError)                                               \
73
  V(ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST, TypeError)                      \
74
  V(ERR_MISSING_PASSPHRASE, TypeError)                                         \
75
  V(ERR_MISSING_PLATFORM_FOR_WORKER, Error)                                    \
76
  V(ERR_NON_CONTEXT_AWARE_DISABLED, Error)                                     \
77
  V(ERR_OUT_OF_RANGE, RangeError)                                              \
78
  V(ERR_SCRIPT_EXECUTION_INTERRUPTED, Error)                                   \
79
  V(ERR_SCRIPT_EXECUTION_TIMEOUT, Error)                                       \
80
  V(ERR_STRING_TOO_LONG, Error)                                                \
81
  V(ERR_TLS_INVALID_PROTOCOL_METHOD, TypeError)                                \
82
  V(ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED, Error)                                \
83
  V(ERR_VM_MODULE_CACHED_DATA_REJECTED, Error)                                 \
84
  V(ERR_VM_MODULE_LINK_FAILURE, Error)                                         \
85
  V(ERR_WASI_NOT_STARTED, Error)                                               \
86
  V(ERR_WORKER_INIT_FAILED, Error)                                             \
87
  V(ERR_PROTO_ACCESS, Error)
88
89
#define V(code, type)                                                          \
90
  template <typename... Args>                                                  \
91
  inline v8::Local<v8::Value> code(                                            \
92
      v8::Isolate* isolate, const char* format, Args&&... args) {              \
93
    std::string message = SPrintF(format, std::forward<Args>(args)...);        \
94
    v8::Local<v8::String> js_code = OneByteString(isolate, #code);             \
95
    v8::Local<v8::String> js_msg =                                             \
96
        OneByteString(isolate, message.c_str(), message.length());             \
97
    v8::Local<v8::Object> e = v8::Exception::type(js_msg)                      \
98
                                  ->ToObject(isolate->GetCurrentContext())     \
99
                                  .ToLocalChecked();                           \
100
    e->Set(isolate->GetCurrentContext(),                                       \
101
           OneByteString(isolate, "code"),                                     \
102
           js_code)                                                            \
103
        .Check();                                                              \
104
    return e;                                                                  \
105
  }                                                                            \
106
  template <typename... Args>                                                  \
107
  inline void THROW_##code(                                                    \
108
      v8::Isolate* isolate, const char* format, Args&&... args) {              \
109
    isolate->ThrowException(                                                   \
110
        code(isolate, format, std::forward<Args>(args)...));                   \
111
  }                                                                            \
112
  template <typename... Args>                                                  \
113
  inline void THROW_##code(                                                    \
114
      Environment* env, const char* format, Args&&... args) {                  \
115
    THROW_##code(env->isolate(), format, std::forward<Args>(args)...);         \
116
  }
117
10081
ERRORS_WITH_CODE(V)
118
#undef V
119
120
// Errors with predefined static messages
121
122
#define PREDEFINED_ERROR_MESSAGES(V)                                           \
123
  V(ERR_BUFFER_CONTEXT_NOT_AVAILABLE,                                          \
124
    "Buffer is not available for the current Context")                         \
125
  V(ERR_CLOSED_MESSAGE_PORT, "Cannot send data on closed MessagePort")         \
126
  V(ERR_CONSTRUCT_CALL_INVALID, "Constructor cannot be called")                \
127
  V(ERR_CONSTRUCT_CALL_REQUIRED, "Cannot call constructor without `new`")      \
128
  V(ERR_CRYPTO_INITIALIZATION_FAILED, "Initialization failed")                 \
129
  V(ERR_CRYPTO_INVALID_AUTH_TAG, "Invalid authentication tag")                 \
130
  V(ERR_CRYPTO_INVALID_COUNTER, "Invalid counter")                             \
131
  V(ERR_CRYPTO_INVALID_CURVE, "Invalid EC curve name")                         \
132
  V(ERR_CRYPTO_INVALID_DIGEST, "Invalid digest")                               \
133
  V(ERR_CRYPTO_INVALID_IV, "Invalid initialization vector")                    \
134
  V(ERR_CRYPTO_INVALID_JWK, "Invalid JWK format")                              \
135
  V(ERR_CRYPTO_INVALID_KEYLEN, "Invalid key length")                           \
136
  V(ERR_CRYPTO_INVALID_KEYPAIR, "Invalid key pair")                            \
137
  V(ERR_CRYPTO_INVALID_KEYTYPE, "Invalid key type")                            \
138
  V(ERR_CRYPTO_INVALID_MESSAGELEN, "Invalid message length")                   \
139
  V(ERR_CRYPTO_INVALID_SCRYPT_PARAMS, "Invalid scrypt params")                 \
140
  V(ERR_CRYPTO_INVALID_STATE, "Invalid state")                                 \
141
  V(ERR_CRYPTO_INVALID_TAG_LENGTH, "Invalid taglength")                        \
142
  V(ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE, "Unsupported JWK Key Type.")          \
143
  V(ERR_CRYPTO_OPERATION_FAILED, "Operation failed")                           \
144
  V(ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH,                                       \
145
    "Input buffers must have the same byte length")                            \
146
  V(ERR_CRYPTO_UNKNOWN_CIPHER, "Unknown cipher")                               \
147
  V(ERR_CRYPTO_UNKNOWN_DH_GROUP, "Unknown DH group")                           \
148
  V(ERR_CRYPTO_UNSUPPORTED_OPERATION, "Unsupported crypto operation")          \
149
  V(ERR_CRYPTO_JOB_INIT_FAILED, "Failed to initialize crypto job config")      \
150
  V(ERR_DLOPEN_FAILED, "DLOpen failed")                                        \
151
  V(ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE,                                   \
152
    "Context not associated with Node.js environment")                         \
153
  V(ERR_INVALID_ADDRESS, "Invalid socket address")                             \
154
  V(ERR_INVALID_MODULE, "No such module")                                      \
155
  V(ERR_INVALID_THIS, "Value of \"this\" is the wrong type")                   \
156
  V(ERR_INVALID_TRANSFER_OBJECT, "Found invalid object in transferList")       \
157
  V(ERR_MEMORY_ALLOCATION_FAILED, "Failed to allocate memory")                 \
158
  V(ERR_OSSL_EVP_INVALID_DIGEST, "Invalid digest used")                        \
159
  V(ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE,                                    \
160
    "A message object could not be deserialized successfully in the target "   \
161
    "vm.Context")                                                              \
162
  V(ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST,                                 \
163
    "Object that needs transfer was found in message but not listed "          \
164
    "in transferList")                                                         \
165
  V(ERR_MISSING_PLATFORM_FOR_WORKER,                                           \
166
    "The V8 platform used by this instance of Node does not support "          \
167
    "creating Workers")                                                        \
168
  V(ERR_NON_CONTEXT_AWARE_DISABLED,                                            \
169
    "Loading non context-aware native modules has been disabled")              \
170
  V(ERR_SCRIPT_EXECUTION_INTERRUPTED,                                          \
171
    "Script execution was interrupted by `SIGINT`")                            \
172
  V(ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED, "Failed to set PSK identity hint")    \
173
  V(ERR_WASI_NOT_STARTED, "wasi.start() has not been called")                  \
174
  V(ERR_WORKER_INIT_FAILED, "Worker initialization failure")                   \
175
  V(ERR_PROTO_ACCESS,                                                          \
176
    "Accessing Object.prototype.__proto__ has been "                           \
177
    "disallowed with --disable-proto=throw")
178
179
#define V(code, message)                                                     \
180
  inline v8::Local<v8::Value> code(v8::Isolate* isolate) {                   \
181
    return code(isolate, message);                                           \
182
  }                                                                          \
183
  inline void THROW_ ## code(v8::Isolate* isolate) {                         \
184
    isolate->ThrowException(code(isolate, message));                         \
185
  }                                                                          \
186
  inline void THROW_ ## code(Environment* env) {                             \
187
    THROW_ ## code(env->isolate());                                          \
188
  }
189
2821
  PREDEFINED_ERROR_MESSAGES(V)
190
#undef V
191
192
// Errors with predefined non-static messages
193
13
inline void THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(Environment* env,
194
                                               int64_t timeout) {
195
13
  std::ostringstream message;
196
13
  message << "Script execution timed out after ";
197
13
  message << timeout << "ms";
198
13
  THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, message.str().c_str());
199
13
}
200
201
inline v8::Local<v8::Value> ERR_BUFFER_TOO_LARGE(v8::Isolate* isolate) {
202
  char message[128];
203
  snprintf(message, sizeof(message),
204
      "Cannot create a Buffer larger than 0x%zx bytes",
205
      v8::TypedArray::kMaxLength);
206
  return ERR_BUFFER_TOO_LARGE(isolate, message);
207
}
208
209
8
inline v8::Local<v8::Value> ERR_STRING_TOO_LONG(v8::Isolate* isolate) {
210
  char message[128];
211
8
  snprintf(message, sizeof(message),
212
      "Cannot create a string longer than 0x%x characters",
213
      v8::String::kMaxLength);
214
8
  return ERR_STRING_TOO_LONG(isolate, message);
215
}
216
217
#define THROW_AND_RETURN_IF_NOT_BUFFER(env, val, prefix)                     \
218
  do {                                                                       \
219
    if (!Buffer::HasInstance(val))                                           \
220
      return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
221
                                              prefix " must be a buffer");   \
222
  } while (0)
223
224
#define THROW_AND_RETURN_IF_NOT_STRING(env, val, prefix)                     \
225
  do {                                                                       \
226
    if (!val->IsString())                                                    \
227
      return node::THROW_ERR_INVALID_ARG_TYPE(env,                           \
228
                                              prefix " must be a string");   \
229
  } while (0)
230
231
namespace errors {
232
233
class TryCatchScope : public v8::TryCatch {
234
 public:
235
  enum class CatchMode { kNormal, kFatal };
236
237
849125
  explicit TryCatchScope(Environment* env, CatchMode mode = CatchMode::kNormal)
238
849125
      : v8::TryCatch(env->isolate()), env_(env), mode_(mode) {}
239
  ~TryCatchScope();
240
241
  // Since the dtor is not virtual we need to make sure no one creates
242
  // object of it in the free store that might be held by polymorphic pointers.
243
  void* operator new(std::size_t count) = delete;
244
  void* operator new[](std::size_t count) = delete;
245
  TryCatchScope(TryCatchScope&) = delete;
246
  TryCatchScope(TryCatchScope&&) = delete;
247
  TryCatchScope operator=(TryCatchScope&) = delete;
248
  TryCatchScope operator=(TryCatchScope&&) = delete;
249
250
 private:
251
  Environment* env_;
252
  CatchMode mode_;
253
};
254
255
// Trigger the global uncaught exception handler `process._fatalException`
256
// in JS land (which emits the 'uncaughtException' event). If that returns
257
// true, continue program execution, otherwise exit the process.
258
void TriggerUncaughtException(v8::Isolate* isolate,
259
                              const v8::TryCatch& try_catch);
260
void TriggerUncaughtException(v8::Isolate* isolate,
261
                              v8::Local<v8::Value> error,
262
                              v8::Local<v8::Message> message,
263
                              bool from_promise = false);
264
265
const char* errno_string(int errorno);
266
void PerIsolateMessageListener(v8::Local<v8::Message> message,
267
                               v8::Local<v8::Value> error);
268
269
void DecorateErrorStack(Environment* env,
270
                        const errors::TryCatchScope& try_catch);
271
}  // namespace errors
272
273
}  // namespace node
274
275
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
276
277
#endif  // SRC_NODE_ERRORS_H_