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