diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000000..4aad29c328abd4 --- /dev/null +++ b/.clang-format @@ -0,0 +1,111 @@ +--- +Language: Cpp +# BasedOnStyle: Google +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: true +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^' + Priority: 2 + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: false +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 8 +UseTab: Never diff --git a/.gitignore b/.gitignore index 1d901b3a69906e..255a4c5a4bc62b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ !test/fixtures/**/.* !tools/node_modules/**/.* !tools/doc/node_modules/**/.* +!.clang-format !.editorconfig !.eslintignore !.eslintrc.js diff --git a/Makefile b/Makefile index c3da8e88bff698..434511f28d0f17 100644 --- a/Makefile +++ b/Makefile @@ -1187,6 +1187,33 @@ LINT_CPP_FILES = $(filter-out $(LINT_CPP_EXCLUDE), $(wildcard \ # and the actual filename is generated so it won't match header guards ADDON_DOC_LINT_FLAGS=-whitespace/ending_newline,-build/header_guard +format-cpp-build: + cd tools/clang-format && $(call available-node,$(run-npm-install)) + +format-cpp-clean: + $(RM) -r tools/clang-format/node_modules + +CLANG_FORMAT_START ?= HEAD +.PHONY: format-cpp +# To format staged changes: +# $ make format-cpp +# To format HEAD~1...HEAD (latest commit): +# $ CLANG_FORMAT_START=`git rev-parse HEAD~1` make format-cpp +# To format diff between master and current branch head (master...HEAD): +# $ CLANG_FORMAT_START=master make format-cpp +format-cpp: ## Format C++ diff from $CLANG_FORMAT_START to current changes +ifneq ("","$(wildcard tools/clang-format/node_modules/)") + @echo "Formatting C++ diff from $(CLANG_FORMAT_START).." + @$(PYTHON) tools/clang-format/node_modules/.bin/git-clang-format \ + --binary=tools/clang-format/node_modules/.bin/clang-format \ + --style=file \ + $(CLANG_FORMAT_START) -- \ + $(LINT_CPP_FILES) +else + @echo "clang-format is not installed." + @echo "To install (requires internet access) run: $ make format-cpp-build" +endif + .PHONY: lint-cpp # Lints the C++ code with cpplint.py and check-imports.py. lint-cpp: tools/.cpplintstamp diff --git a/benchmark/napi/function_call/binding.cc b/benchmark/napi/function_call/binding.cc index 289a94ac3ecc88..40688767814f0f 100644 --- a/benchmark/napi/function_call/binding.cc +++ b/benchmark/napi/function_call/binding.cc @@ -1,5 +1,5 @@ -#include #include +#include static int c = 0; diff --git a/src/aliased_buffer.h b/src/aliased_buffer.h index 10659f6d529f02..f21b33b594bc3f 100644 --- a/src/aliased_buffer.h +++ b/src/aliased_buffer.h @@ -2,8 +2,8 @@ #ifndef SRC_ALIASED_BUFFER_H_ #define SRC_ALIASED_BUFFER_H_ -#include "v8.h" #include "util-inl.h" +#include "v8.h" namespace node { @@ -25,10 +25,7 @@ template class AliasedBuffer { public: AliasedBuffer(v8::Isolate* isolate, const size_t count) - : isolate_(isolate), - count_(count), - byte_offset_(0), - free_buffer_(true) { + : isolate_(isolate), count_(count), byte_offset_(0), free_buffer_(true) { CHECK_GT(count, 0); const v8::HandleScope handle_scope(isolate_); @@ -38,8 +35,8 @@ class AliasedBuffer { buffer_ = Calloc(count); // allocate v8 ArrayBuffer - v8::Local ab = v8::ArrayBuffer::New( - isolate_, buffer_, sizeInBytes); + v8::Local ab = + v8::ArrayBuffer::New(isolate_, buffer_, sizeInBytes); // allocate v8 TypedArray v8::Local js_array = V8T::New(ab, byte_offset_, count); @@ -57,8 +54,7 @@ class AliasedBuffer { AliasedBuffer(v8::Isolate* isolate, const size_t byte_offset, const size_t count, - const AliasedBuffer& backing_buffer) + const AliasedBuffer& backing_buffer) : isolate_(isolate), count_(count), byte_offset_(byte_offset), @@ -70,7 +66,7 @@ class AliasedBuffer { // validate that the byte_offset is aligned with sizeof(NativeT) CHECK_EQ(byte_offset & (sizeof(NativeT) - 1), 0); // validate this fits inside the backing buffer - CHECK_LE(sizeof(NativeT) * count, ab->ByteLength() - byte_offset); + CHECK_LE(sizeof(NativeT) * count, ab->ByteLength() - byte_offset); buffer_ = reinterpret_cast( const_cast(backing_buffer.GetNativeBuffer() + byte_offset)); @@ -117,14 +113,10 @@ class AliasedBuffer { class Reference { public: Reference(AliasedBuffer* aliased_buffer, size_t index) - : aliased_buffer_(aliased_buffer), - index_(index) { - } + : aliased_buffer_(aliased_buffer), index_(index) {} Reference(const Reference& that) - : aliased_buffer_(that.aliased_buffer_), - index_(that.index_) { - } + : aliased_buffer_(that.aliased_buffer_), index_(that.index_) {} inline Reference& operator=(const NativeT& val) { aliased_buffer_->SetValue(index_, val); @@ -135,9 +127,7 @@ class AliasedBuffer { return *this = static_cast(val); } - operator NativeT() const { - return aliased_buffer_->GetValue(index_); - } + operator NativeT() const { return aliased_buffer_->GetValue(index_); } inline Reference& operator+=(const NativeT& val) { const NativeT current = aliased_buffer_->GetValue(index_); @@ -163,14 +153,12 @@ class AliasedBuffer { /** * Get the underlying v8 TypedArray overlayed on top of the native buffer */ - v8::Local GetJSArray() const { - return js_array_.Get(isolate_); - } + v8::Local GetJSArray() const { return js_array_.Get(isolate_); } /** - * Get the underlying v8::ArrayBuffer underlying the TypedArray and - * overlaying the native buffer - */ + * Get the underlying v8::ArrayBuffer underlying the TypedArray and + * overlaying the native buffer + */ v8::Local GetArrayBuffer() const { return GetJSArray()->Buffer(); } @@ -179,16 +167,12 @@ class AliasedBuffer { * Get the underlying native buffer. Note that all reads/writes should occur * through the GetValue/SetValue/operator[] methods */ - inline const NativeT* GetNativeBuffer() const { - return buffer_; - } + inline const NativeT* GetNativeBuffer() const { return buffer_; } /** * Synonym for GetBuffer() */ - inline const NativeT* operator * () const { - return GetNativeBuffer(); - } + inline const NativeT* operator*() const { return GetNativeBuffer(); } /** * Set position index to given value. @@ -213,17 +197,11 @@ class AliasedBuffer { /** * Effectively, a synonym for GetValue/SetValue */ - Reference operator[](size_t index) { - return Reference(this, index); - } + Reference operator[](size_t index) { return Reference(this, index); } - NativeT operator[](size_t index) const { - return GetValue(index); - } + NativeT operator[](size_t index) const { return GetValue(index); } - size_t Length() const { - return count_; - } + size_t Length() const { return count_; } private: v8::Isolate* isolate_; diff --git a/src/async_wrap-inl.h b/src/async_wrap-inl.h index 4405bb3a9baa52..100b9351343faa 100644 --- a/src/async_wrap-inl.h +++ b/src/async_wrap-inl.h @@ -34,19 +34,15 @@ inline AsyncWrap::ProviderType AsyncWrap::provider_type() const { return provider_type_; } - inline double AsyncWrap::get_async_id() const { return async_id_; } - inline double AsyncWrap::get_trigger_async_id() const { return trigger_async_id_; } - -inline AsyncWrap::AsyncScope::AsyncScope(AsyncWrap* wrap) - : wrap_(wrap) { +inline AsyncWrap::AsyncScope::AsyncScope(AsyncWrap* wrap) : wrap_(wrap) { Environment* env = wrap->env(); if (env->async_hooks()->fields()[Environment::AsyncHooks::kBefore] == 0) return; @@ -60,27 +56,18 @@ inline AsyncWrap::AsyncScope::~AsyncScope() { EmitAfter(env, wrap_->get_async_id()); } - inline v8::MaybeLocal AsyncWrap::MakeCallback( - const v8::Local symbol, - int argc, - v8::Local* argv) { + const v8::Local symbol, int argc, v8::Local* argv) { return MakeCallback(symbol.As(), argc, argv); } - inline v8::MaybeLocal AsyncWrap::MakeCallback( - const v8::Local symbol, - int argc, - v8::Local* argv) { + const v8::Local symbol, int argc, v8::Local* argv) { return MakeCallback(symbol.As(), argc, argv); } - inline v8::MaybeLocal AsyncWrap::MakeCallback( - const v8::Local symbol, - int argc, - v8::Local* argv) { + const v8::Local symbol, int argc, v8::Local* argv) { v8::Local cb_v; if (!object()->Get(env()->context(), symbol).ToLocal(&cb_v)) return v8::MaybeLocal(); @@ -92,10 +79,9 @@ inline v8::MaybeLocal AsyncWrap::MakeCallback( return MakeCallback(cb_v.As(), argc, argv); } - // Defined here to avoid a circular dependency with env-inl.h. -inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope - ::DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap) +inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope :: + DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap) : DefaultTriggerAsyncIdScope(async_wrap->env(), async_wrap->get_async_id()) {} diff --git a/src/async_wrap.cc b/src/async_wrap.cc index 7ef3dafdf992c5..c9fa754130c447 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -24,8 +24,8 @@ #include "node_internals.h" #include "util-inl.h" -#include "v8.h" #include "v8-profiler.h" +#include "v8.h" using v8::Context; using v8::Function; @@ -52,13 +52,11 @@ using AsyncHooks = node::Environment::AsyncHooks; namespace node { static const char* const provider_names[] = { -#define V(PROVIDER) \ - #PROVIDER, - NODE_ASYNC_PROVIDER_TYPES(V) +#define V(PROVIDER) #PROVIDER, + NODE_ASYNC_PROVIDER_TYPES(V) #undef V }; - struct AsyncWrapObject : public AsyncWrap { static inline void New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -69,15 +67,16 @@ struct AsyncWrapObject : public AsyncWrap { new AsyncWrapObject(env, args.This(), type); } - inline AsyncWrapObject(Environment* env, Local object, - ProviderType type) : AsyncWrap(env, object, type) {} + inline AsyncWrapObject(Environment* env, + Local object, + ProviderType type) + : AsyncWrap(env, object, type) {} void MemoryInfo(MemoryTracker* tracker) const override { tracker->TrackThis(this); } }; - static void DestroyAsyncIdsCallback(Environment* env, void* data) { Local fn = env->async_hooks_destroy_function(); @@ -95,8 +94,7 @@ static void DestroyAsyncIdsCallback(Environment* env, void* data) { MaybeLocal ret = fn->Call( env->context(), Undefined(env->isolate()), 1, &async_id_value); - if (ret.IsEmpty()) - return; + if (ret.IsEmpty()) return; } } while (!env->destroy_async_id_list()->empty()); } @@ -107,13 +105,13 @@ static void DestroyAsyncIdsCallback(void* arg) { DestroyAsyncIdsCallback(env, nullptr); } - -void Emit(Environment* env, double async_id, AsyncHooks::Fields type, +void Emit(Environment* env, + double async_id, + AsyncHooks::Fields type, Local fn) { AsyncHooks* async_hooks = env->async_hooks(); - if (async_hooks->fields()[type] == 0 || !env->can_call_into_js()) - return; + if (async_hooks->fields()[type] == 0 || !env->can_call_into_js()) return; v8::HandleScope handle_scope(env->isolate()); Local async_id_value = Number::New(env->isolate(), async_id); @@ -121,21 +119,21 @@ void Emit(Environment* env, double async_id, AsyncHooks::Fields type, USE(fn->Call(env->context(), Undefined(env->isolate()), 1, &async_id_value)); } - void AsyncWrap::EmitPromiseResolve(Environment* env, double async_id) { - Emit(env, async_id, AsyncHooks::kPromiseResolve, + Emit(env, + async_id, + AsyncHooks::kPromiseResolve, env->async_hooks_promise_resolve_function()); } - void AsyncWrap::EmitTraceEventBefore() { switch (provider_type()) { -#define V(PROVIDER) \ - case PROVIDER_ ## PROVIDER: \ - TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( \ - TRACING_CATEGORY_NODE1(async_hooks), \ - #PROVIDER "_CALLBACK", static_cast(get_async_id())); \ - break; +#define V(PROVIDER) \ + case PROVIDER_##PROVIDER: \ + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(TRACING_CATEGORY_NODE1(async_hooks), \ + #PROVIDER "_CALLBACK", \ + static_cast(get_async_id())); \ + break; NODE_ASYNC_PROVIDER_TYPES(V) #undef V default: @@ -143,21 +141,18 @@ void AsyncWrap::EmitTraceEventBefore() { } } - void AsyncWrap::EmitBefore(Environment* env, double async_id) { - Emit(env, async_id, AsyncHooks::kBefore, - env->async_hooks_before_function()); + Emit(env, async_id, AsyncHooks::kBefore, env->async_hooks_before_function()); } - void AsyncWrap::EmitTraceEventAfter(ProviderType type, double async_id) { switch (type) { -#define V(PROVIDER) \ - case PROVIDER_ ## PROVIDER: \ - TRACE_EVENT_NESTABLE_ASYNC_END0( \ - TRACING_CATEGORY_NODE1(async_hooks), \ - #PROVIDER "_CALLBACK", static_cast(async_id)); \ - break; +#define V(PROVIDER) \ + case PROVIDER_##PROVIDER: \ + TRACE_EVENT_NESTABLE_ASYNC_END0(TRACING_CATEGORY_NODE1(async_hooks), \ + #PROVIDER "_CALLBACK", \ + static_cast(async_id)); \ + break; NODE_ASYNC_PROVIDER_TYPES(V) #undef V default: @@ -165,12 +160,10 @@ void AsyncWrap::EmitTraceEventAfter(ProviderType type, double async_id) { } } - void AsyncWrap::EmitAfter(Environment* env, double async_id) { // If the user's callback failed then the after() hooks will be called at the // end of _fatalException(). - Emit(env, async_id, AsyncHooks::kAfter, - env->async_hooks_after_function()); + Emit(env, async_id, AsyncHooks::kAfter, env->async_hooks_after_function()); } class PromiseWrap : public AsyncWrap { @@ -203,12 +196,12 @@ PromiseWrap* PromiseWrap::New(Environment* env, PromiseWrap* parent_wrap, bool silent) { Local object = env->promise_wrap_template() - ->NewInstance(env->context()).ToLocalChecked(); + ->NewInstance(env->context()) + .ToLocalChecked(); object->SetInternalField(PromiseWrap::kPromiseField, promise); object->SetInternalField(PromiseWrap::kIsChainedPromiseField, - parent_wrap != nullptr ? - v8::True(env->isolate()) : - v8::False(env->isolate())); + parent_wrap != nullptr ? v8::True(env->isolate()) + : v8::False(env->isolate())); CHECK_EQ(promise->GetAlignedPointerFromInternalField(0), nullptr); promise->SetInternalField(0, object); return new PromiseWrap(env, object, silent); @@ -222,7 +215,7 @@ void PromiseWrap::GetPromise(Local property, void PromiseWrap::getIsChainedPromise(Local property, const PropertyCallbackInfo& info) { info.GetReturnValue().Set( - info.Holder()->GetInternalField(kIsChainedPromiseField)); + info.Holder()->GetInternalField(kIsChainedPromiseField)); } static PromiseWrap* extractPromiseWrap(Local promise) { @@ -233,8 +226,10 @@ static PromiseWrap* extractPromiseWrap(Local promise) { return nullptr; } -static void PromiseHook(PromiseHookType type, Local promise, - Local parent, void* arg) { +static void PromiseHook(PromiseHookType type, + Local promise, + Local parent, + void* arg) { Environment* env = static_cast(arg); PromiseWrap* wrap = extractPromiseWrap(promise); if (type == PromiseHookType::kInit || wrap == nullptr) { @@ -260,8 +255,8 @@ static void PromiseHook(PromiseHookType type, Local promise, CHECK_NOT_NULL(wrap); if (type == PromiseHookType::kBefore) { - env->async_hooks()->push_async_ids( - wrap->get_async_id(), wrap->get_trigger_async_id()); + env->async_hooks()->push_async_ids(wrap->get_async_id(), + wrap->get_trigger_async_id()); wrap->EmitTraceEventBefore(); AsyncWrap::EmitBefore(wrap->env(), wrap->get_async_id()); } else if (type == PromiseHookType::kAfter) { @@ -280,7 +275,6 @@ static void PromiseHook(PromiseHookType type, Local promise, } } - static void SetupHooks(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -293,11 +287,12 @@ static void SetupHooks(const FunctionCallbackInfo& args) { Local fn_obj = args[0].As(); -#define SET_HOOK_FN(name) \ - Local name##_v = fn_obj->Get( \ - env->context(), \ - FIXED_ONE_BYTE_STRING(env->isolate(), #name)).ToLocalChecked(); \ - CHECK(name##_v->IsFunction()); \ +#define SET_HOOK_FN(name) \ + Local name##_v = \ + fn_obj \ + ->Get(env->context(), FIXED_ONE_BYTE_STRING(env->isolate(), #name)) \ + .ToLocalChecked(); \ + CHECK(name##_v->IsFunction()); \ env->set_async_hooks_##name##_function(name##_v.As()); SET_HOOK_FN(init); @@ -308,8 +303,7 @@ static void SetupHooks(const FunctionCallbackInfo& args) { #undef SET_HOOK_FN { - Local ctor = - FunctionTemplate::New(env->isolate()); + Local ctor = FunctionTemplate::New(env->isolate()); ctor->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "PromiseWrap")); Local promise_wrap_template = ctor->InstanceTemplate(); promise_wrap_template->SetInternalFieldCount( @@ -324,25 +318,24 @@ static void SetupHooks(const FunctionCallbackInfo& args) { } } - static void EnablePromiseHook(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); env->AddPromiseHook(PromiseHook, static_cast(env)); } - static void DisablePromiseHook(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); // Delay the call to `RemovePromiseHook` because we might currently be // between the `before` and `after` calls of a Promise. - env->isolate()->EnqueueMicrotask([](void* data) { - Environment* env = static_cast(data); - env->RemovePromiseHook(PromiseHook, data); - }, static_cast(env)); + env->isolate()->EnqueueMicrotask( + [](void* data) { + Environment* env = static_cast(data); + env->RemovePromiseHook(PromiseHook, data); + }, + static_cast(env)); } - class DestroyParam { public: double asyncId; @@ -351,7 +344,6 @@ class DestroyParam { Persistent propBag; }; - void AsyncWrap::WeakCallback(const v8::WeakCallbackInfo& info) { HandleScope scope(info.GetIsolate()); @@ -365,7 +357,6 @@ void AsyncWrap::WeakCallback(const v8::WeakCallbackInfo& info) { // unique_ptr goes out of scope here and pointer is deleted. } - static void RegisterDestroyHook(const FunctionCallbackInfo& args) { CHECK(args[0]->IsObject()); CHECK(args[1]->IsNumber()); @@ -378,10 +369,9 @@ static void RegisterDestroyHook(const FunctionCallbackInfo& args) { p->target.Reset(isolate, args[0].As()); p->propBag.Reset(isolate, args[2].As()); p->target.SetWeak( - p, AsyncWrap::WeakCallback, v8::WeakCallbackType::kParameter); + p, AsyncWrap::WeakCallback, v8::WeakCallbackType::kParameter); } - void AsyncWrap::GetAsyncId(const FunctionCallbackInfo& args) { AsyncWrap* wrap; args.GetReturnValue().Set(-1); @@ -389,7 +379,6 @@ void AsyncWrap::GetAsyncId(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(wrap->get_async_id()); } - void AsyncWrap::PushAsyncIds(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); // No need for CHECK(IsNumber()) on args because if FromJust() doesn't fail @@ -399,14 +388,12 @@ void AsyncWrap::PushAsyncIds(const FunctionCallbackInfo& args) { env->async_hooks()->push_async_ids(async_id, trigger_async_id); } - void AsyncWrap::PopAsyncIds(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); double async_id = args[0]->NumberValue(env->context()).FromJust(); args.GetReturnValue().Set(env->async_hooks()->pop_async_id(async_id)); } - void AsyncWrap::AsyncReset(const FunctionCallbackInfo& args) { AsyncWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -414,11 +401,9 @@ void AsyncWrap::AsyncReset(const FunctionCallbackInfo& args) { wrap->AsyncReset(execution_async_id); } - void AsyncWrap::QueueDestroyAsyncId(const FunctionCallbackInfo& args) { CHECK(args[0]->IsNumber()); - AsyncWrap::EmitDestroy( - Environment::GetCurrent(args), args[0]->NumberValue()); + AsyncWrap::EmitDestroy(Environment::GetCurrent(args), args[0]->NumberValue()); } void AsyncWrap::AddWrapMethods(Environment* env, @@ -449,19 +434,20 @@ void AsyncWrap::Initialize(Local target, v8::PropertyAttribute ReadOnlyDontDelete = static_cast(v8::ReadOnly | v8::DontDelete); -#define FORCE_SET_TARGET_FIELD(obj, str, field) \ - (obj)->DefineOwnProperty(context, \ - FIXED_ONE_BYTE_STRING(isolate, str), \ - field, \ - ReadOnlyDontDelete).FromJust() +#define FORCE_SET_TARGET_FIELD(obj, str, field) \ + (obj) \ + ->DefineOwnProperty(context, \ + FIXED_ONE_BYTE_STRING(isolate, str), \ + field, \ + ReadOnlyDontDelete) \ + .FromJust() // Attach the uint32_t[] where each slot contains the count of the number of // callbacks waiting to be called on a particular event. It can then be // incremented/decremented from JS quickly to communicate to C++ if there are // any callbacks waiting to be called. - FORCE_SET_TARGET_FIELD(target, - "async_hook_fields", - env->async_hooks()->fields().GetJSArray()); + FORCE_SET_TARGET_FIELD( + target, "async_hook_fields", env->async_hooks()->fields().GetJSArray()); // The following v8::Float64Array has 5 fields. These fields are shared in // this way to allow JS and C++ to read/write each value as quickly as @@ -477,13 +463,15 @@ void AsyncWrap::Initialize(Local target, "async_id_fields", env->async_hooks()->async_id_fields().GetJSArray()); - target->Set(context, - env->async_ids_stack_string(), - env->async_hooks()->async_ids_stack().GetJSArray()).FromJust(); + target + ->Set(context, + env->async_ids_stack_string(), + env->async_hooks()->async_ids_stack().GetJSArray()) + .FromJust(); Local constants = Object::New(isolate); -#define SET_HOOKS_CONSTANT(name) \ - FORCE_SET_TARGET_FIELD( \ +#define SET_HOOKS_CONSTANT(name) \ + FORCE_SET_TARGET_FIELD( \ constants, #name, Integer::New(isolate, AsyncHooks::name)); SET_HOOKS_CONSTANT(kInit); @@ -502,9 +490,9 @@ void AsyncWrap::Initialize(Local target, FORCE_SET_TARGET_FIELD(target, "constants", constants); Local async_providers = Object::New(isolate); -#define V(p) \ - FORCE_SET_TARGET_FIELD( \ - async_providers, #p, Integer::New(isolate, AsyncWrap::PROVIDER_ ## p)); +#define V(p) \ + FORCE_SET_TARGET_FIELD( \ + async_providers, #p, Integer::New(isolate, AsyncWrap::PROVIDER_##p)); NODE_ASYNC_PROVIDER_TYPES(V) #undef V FORCE_SET_TARGET_FIELD(target, "Providers", async_providers); @@ -532,7 +520,6 @@ void AsyncWrap::Initialize(Local target, } } - AsyncWrap::AsyncWrap(Environment* env, Local object, ProviderType provider, @@ -544,8 +531,7 @@ AsyncWrap::AsyncWrap(Environment* env, ProviderType provider, double execution_async_id, bool silent) - : BaseObject(env, object), - provider_type_(provider) { + : BaseObject(env, object), provider_type_(provider) { CHECK_NE(provider, PROVIDER_NONE); CHECK_GE(object->InternalFieldCount(), 1); @@ -556,7 +542,6 @@ AsyncWrap::AsyncWrap(Environment* env, AsyncReset(execution_async_id, silent); } - AsyncWrap::~AsyncWrap() { EmitTraceEventDestroy(); EmitDestroy(env(), get_async_id()); @@ -564,14 +549,14 @@ AsyncWrap::~AsyncWrap() { void AsyncWrap::EmitTraceEventDestroy() { switch (provider_type()) { - #define V(PROVIDER) \ - case PROVIDER_ ## PROVIDER: \ - TRACE_EVENT_NESTABLE_ASYNC_END0( \ - TRACING_CATEGORY_NODE1(async_hooks), \ - #PROVIDER, static_cast(get_async_id())); \ - break; +#define V(PROVIDER) \ + case PROVIDER_##PROVIDER: \ + TRACE_EVENT_NESTABLE_ASYNC_END0(TRACING_CATEGORY_NODE1(async_hooks), \ + #PROVIDER, \ + static_cast(get_async_id())); \ + break; NODE_ASYNC_PROVIDER_TYPES(V) - #undef V +#undef V default: UNREACHABLE(); } @@ -590,26 +575,26 @@ void AsyncWrap::EmitDestroy(Environment* env, double async_id) { env->destroy_async_id_list()->push_back(async_id); } - // Generalized call for both the constructor and for handles that are pooled // and reused over their lifetime. This way a new uid can be assigned when // the resource is pulled out of the pool and put back into use. void AsyncWrap::AsyncReset(double execution_async_id, bool silent) { async_id_ = - execution_async_id == -1 ? env()->new_async_id() : execution_async_id; + execution_async_id == -1 ? env()->new_async_id() : execution_async_id; trigger_async_id_ = env()->get_default_trigger_async_id(); switch (provider_type()) { -#define V(PROVIDER) \ - case PROVIDER_ ## PROVIDER: \ - TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( \ - TRACING_CATEGORY_NODE1(async_hooks), \ - #PROVIDER, static_cast(get_async_id()), \ - "executionAsyncId", \ - static_cast(env()->execution_async_id()), \ - "triggerAsyncId", \ - static_cast(get_trigger_async_id())); \ - break; +#define V(PROVIDER) \ + case PROVIDER_##PROVIDER: \ + TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( \ + TRACING_CATEGORY_NODE1(async_hooks), \ + #PROVIDER, \ + static_cast(get_async_id()), \ + "executionAsyncId", \ + static_cast(env()->execution_async_id()), \ + "triggerAsyncId", \ + static_cast(get_trigger_async_id())); \ + break; NODE_ASYNC_PROVIDER_TYPES(V) #undef V default: @@ -618,12 +603,13 @@ void AsyncWrap::AsyncReset(double execution_async_id, bool silent) { if (silent) return; - EmitAsyncInit(env(), object(), + EmitAsyncInit(env(), + object(), env()->async_hooks()->provider_string(provider_type()), - async_id_, trigger_async_id_); + async_id_, + trigger_async_id_); } - void AsyncWrap::EmitAsyncInit(Environment* env, Local object, Local type, @@ -642,26 +628,25 @@ void AsyncWrap::EmitAsyncInit(Environment* env, Local init_fn = env->async_hooks_init_function(); Local argv[] = { - Number::New(env->isolate(), async_id), - type, - Number::New(env->isolate(), trigger_async_id), - object, + Number::New(env->isolate(), async_id), + type, + Number::New(env->isolate(), trigger_async_id), + object, }; FatalTryCatch try_catch(env); USE(init_fn->Call(env->context(), object, arraysize(argv), argv)); } - MaybeLocal AsyncWrap::MakeCallback(const Local cb, int argc, Local* argv) { EmitTraceEventBefore(); ProviderType provider = provider_type(); - async_context context { get_async_id(), get_trigger_async_id() }; - MaybeLocal ret = InternalMakeCallback( - env(), object(), cb, argc, argv, context); + async_context context{get_async_id(), get_trigger_async_id()}; + MaybeLocal ret = + InternalMakeCallback(env(), object(), cb, argc, argv, context); // This is a static call with cached values because the `this` object may // no longer be alive at this point. @@ -670,20 +655,16 @@ MaybeLocal AsyncWrap::MakeCallback(const Local cb, return ret; } - /* Public C++ embedder API */ - async_id AsyncHooksGetExecutionAsyncId(Isolate* isolate) { return Environment::GetCurrent(isolate)->execution_async_id(); } - async_id AsyncHooksGetTriggerAsyncId(Isolate* isolate) { return Environment::GetCurrent(isolate)->trigger_async_id(); } - async_context EmitAsyncInit(Isolate* isolate, Local resource, const char* name, @@ -705,20 +686,20 @@ async_context EmitAsyncInit(Isolate* isolate, trigger_async_id = env->get_default_trigger_async_id(); async_context context = { - env->new_async_id(), // async_id_ - trigger_async_id // trigger_async_id_ + env->new_async_id(), // async_id_ + trigger_async_id // trigger_async_id_ }; // Run init hooks - AsyncWrap::EmitAsyncInit(env, resource, name, context.async_id, - context.trigger_async_id); + AsyncWrap::EmitAsyncInit( + env, resource, name, context.async_id, context.trigger_async_id); return context; } void EmitAsyncDestroy(Isolate* isolate, async_context asyncContext) { - AsyncWrap::EmitDestroy( - Environment::GetCurrent(isolate), asyncContext.async_id); + AsyncWrap::EmitDestroy(Environment::GetCurrent(isolate), + asyncContext.async_id); } std::string AsyncWrap::MemoryInfoName() const { @@ -727,7 +708,7 @@ std::string AsyncWrap::MemoryInfoName() const { std::string AsyncWrap::diagnostic_name() const { return MemoryInfoName() + " (" + std::to_string(env()->thread_id()) + ":" + - std::to_string(static_cast(async_id_)) + ")"; + std::to_string(static_cast(async_id_)) + ")"; } } // namespace node diff --git a/src/async_wrap.h b/src/async_wrap.h index fed05ab021b3ca..cb418026429cc6 100644 --- a/src/async_wrap.h +++ b/src/async_wrap.h @@ -33,63 +33,62 @@ namespace node { #define NODE_ASYNC_ID_OFFSET 0xA1C -#define NODE_ASYNC_NON_CRYPTO_PROVIDER_TYPES(V) \ - V(NONE) \ - V(DNSCHANNEL) \ - V(FILEHANDLE) \ - V(FILEHANDLECLOSEREQ) \ - V(FSEVENTWRAP) \ - V(FSREQWRAP) \ - V(FSREQPROMISE) \ - V(GETADDRINFOREQWRAP) \ - V(GETNAMEINFOREQWRAP) \ - V(HTTP2SESSION) \ - V(HTTP2STREAM) \ - V(HTTP2PING) \ - V(HTTP2SETTINGS) \ - V(HTTPPARSER) \ - V(JSSTREAM) \ - V(MESSAGEPORT) \ - V(PIPECONNECTWRAP) \ - V(PIPESERVERWRAP) \ - V(PIPEWRAP) \ - V(PROCESSWRAP) \ - V(PROMISE) \ - V(QUERYWRAP) \ - V(SHUTDOWNWRAP) \ - V(SIGNALWRAP) \ - V(STATWATCHER) \ - V(STREAMPIPE) \ - V(TCPCONNECTWRAP) \ - V(TCPSERVERWRAP) \ - V(TCPWRAP) \ - V(TTYWRAP) \ - V(UDPSENDWRAP) \ - V(UDPWRAP) \ - V(WORKER) \ - V(WRITEWRAP) \ +#define NODE_ASYNC_NON_CRYPTO_PROVIDER_TYPES(V) \ + V(NONE) \ + V(DNSCHANNEL) \ + V(FILEHANDLE) \ + V(FILEHANDLECLOSEREQ) \ + V(FSEVENTWRAP) \ + V(FSREQWRAP) \ + V(FSREQPROMISE) \ + V(GETADDRINFOREQWRAP) \ + V(GETNAMEINFOREQWRAP) \ + V(HTTP2SESSION) \ + V(HTTP2STREAM) \ + V(HTTP2PING) \ + V(HTTP2SETTINGS) \ + V(HTTPPARSER) \ + V(JSSTREAM) \ + V(MESSAGEPORT) \ + V(PIPECONNECTWRAP) \ + V(PIPESERVERWRAP) \ + V(PIPEWRAP) \ + V(PROCESSWRAP) \ + V(PROMISE) \ + V(QUERYWRAP) \ + V(SHUTDOWNWRAP) \ + V(SIGNALWRAP) \ + V(STATWATCHER) \ + V(STREAMPIPE) \ + V(TCPCONNECTWRAP) \ + V(TCPSERVERWRAP) \ + V(TCPWRAP) \ + V(TTYWRAP) \ + V(UDPSENDWRAP) \ + V(UDPWRAP) \ + V(WORKER) \ + V(WRITEWRAP) \ V(ZLIB) #if HAVE_OPENSSL -#define NODE_ASYNC_CRYPTO_PROVIDER_TYPES(V) \ - V(PBKDF2REQUEST) \ - V(RANDOMBYTESREQUEST) \ - V(SCRYPTREQUEST) \ +#define NODE_ASYNC_CRYPTO_PROVIDER_TYPES(V) \ + V(PBKDF2REQUEST) \ + V(RANDOMBYTESREQUEST) \ + V(SCRYPTREQUEST) \ V(TLSWRAP) #else #define NODE_ASYNC_CRYPTO_PROVIDER_TYPES(V) #endif // HAVE_OPENSSL #if HAVE_INSPECTOR -#define NODE_ASYNC_INSPECTOR_PROVIDER_TYPES(V) \ - V(INSPECTORJSBINDING) +#define NODE_ASYNC_INSPECTOR_PROVIDER_TYPES(V) V(INSPECTORJSBINDING) #else #define NODE_ASYNC_INSPECTOR_PROVIDER_TYPES(V) #endif // HAVE_INSPECTOR -#define NODE_ASYNC_PROVIDER_TYPES(V) \ - NODE_ASYNC_NON_CRYPTO_PROVIDER_TYPES(V) \ - NODE_ASYNC_CRYPTO_PROVIDER_TYPES(V) \ +#define NODE_ASYNC_PROVIDER_TYPES(V) \ + NODE_ASYNC_NON_CRYPTO_PROVIDER_TYPES(V) \ + NODE_ASYNC_CRYPTO_PROVIDER_TYPES(V) \ NODE_ASYNC_INSPECTOR_PROVIDER_TYPES(V) class Environment; @@ -98,17 +97,13 @@ class DestroyParam; class AsyncWrap : public BaseObject { public: enum ProviderType { -#define V(PROVIDER) \ - PROVIDER_ ## PROVIDER, +#define V(PROVIDER) PROVIDER_##PROVIDER, NODE_ASYNC_PROVIDER_TYPES(V) #undef V - PROVIDERS_LENGTH, + PROVIDERS_LENGTH, }; - enum Flags { - kFlagNone = 0x0, - kFlagHasReset = 0x1 - }; + enum Flags { kFlagNone = 0x0, kFlagHasReset = 0x1 }; AsyncWrap(Environment* env, v8::Local object, @@ -130,7 +125,7 @@ class AsyncWrap : public BaseObject { static void PopAsyncIds(const v8::FunctionCallbackInfo& args); static void AsyncReset(const v8::FunctionCallbackInfo& args); static void QueueDestroyAsyncId( - const v8::FunctionCallbackInfo& args); + const v8::FunctionCallbackInfo& args); static void EmitAsyncInit(Environment* env, v8::Local object, @@ -147,7 +142,6 @@ class AsyncWrap : public BaseObject { static void EmitTraceEventAfter(ProviderType type, double async_id); void EmitTraceEventDestroy(); - inline ProviderType provider_type() const; inline double get_async_id() const; @@ -161,22 +155,16 @@ class AsyncWrap : public BaseObject { int argc, v8::Local* argv); inline v8::MaybeLocal MakeCallback( - const v8::Local symbol, - int argc, - v8::Local* argv); + const v8::Local symbol, int argc, v8::Local* argv); inline v8::MaybeLocal MakeCallback( - const v8::Local symbol, - int argc, - v8::Local* argv); + const v8::Local symbol, int argc, v8::Local* argv); inline v8::MaybeLocal MakeCallback( - const v8::Local symbol, - int argc, - v8::Local* argv); + const v8::Local symbol, int argc, v8::Local* argv); virtual std::string diagnostic_name() const; virtual std::string MemoryInfoName() const; - static void WeakCallback(const v8::WeakCallbackInfo &info); + static void WeakCallback(const v8::WeakCallbackInfo& info); // This is a simplified version of InternalCallbackScope that only runs // the `before` and `after` hooks. Only use it when not actually calling diff --git a/src/base64.h b/src/base64.h index a19d11f71c65f5..84fee885e52cc3 100644 --- a/src/base64.h +++ b/src/base64.h @@ -12,7 +12,6 @@ namespace node { //// Base 64 //// #define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - // Doesn't check for padding at the end. Can be 1-2 bytes over. static inline size_t base64_decoded_size_fast(size_t size) { size_t remainder = size % 4; @@ -33,46 +32,39 @@ static inline size_t base64_decoded_size_fast(size_t size) { template size_t base64_decoded_size(const TypeName* src, size_t size) { - if (size == 0) - return 0; + if (size == 0) return 0; - if (src[size - 1] == '=') - size--; - if (size > 0 && src[size - 1] == '=') - size--; + if (src[size - 1] == '=') size--; + if (size > 0 && src[size - 1] == '=') size--; return base64_decoded_size_fast(size); } - extern const int8_t unbase64_table[256]; - -#define unbase64(x) \ +#define unbase64(x) \ static_cast(unbase64_table[static_cast(x)]) - template -bool base64_decode_group_slow(char* const dst, const size_t dstlen, - const TypeName* const src, const size_t srclen, - size_t* const i, size_t* const k) { +bool base64_decode_group_slow(char* const dst, + const size_t dstlen, + const TypeName* const src, + const size_t srclen, + size_t* const i, + size_t* const k) { uint8_t hi; uint8_t lo; -#define V(expr) \ - for (;;) { \ - const uint8_t c = src[*i]; \ - lo = unbase64(c); \ - *i += 1; \ - if (lo < 64) \ - break; /* Legal character. */ \ - if (c == '=' || *i >= srclen) \ - return false; /* Stop decoding. */ \ - } \ - expr; \ - if (*i >= srclen) \ - return false; \ - if (*k >= dstlen) \ - return false; \ +#define V(expr) \ + for (;;) { \ + const uint8_t c = src[*i]; \ + lo = unbase64(c); \ + *i += 1; \ + if (lo < 64) break; /* Legal character. */ \ + if (c == '=' || *i >= srclen) return false; /* Stop decoding. */ \ + } \ + expr; \ + if (*i >= srclen) return false; \ + if (*k >= dstlen) return false; \ hi = lo; V(/* Nothing. */); V(dst[(*k)++] = ((hi & 0x3F) << 2) | ((lo & 0x30) >> 4)); @@ -82,10 +74,11 @@ bool base64_decode_group_slow(char* const dst, const size_t dstlen, return true; // Continue decoding. } - template -size_t base64_decode_fast(char* const dst, const size_t dstlen, - const TypeName* const src, const size_t srclen, +size_t base64_decode_fast(char* const dst, + const size_t dstlen, + const TypeName* const src, + const size_t srclen, const size_t decoded_size) { const size_t available = dstlen < decoded_size ? dstlen : decoded_size; const size_t max_k = available / 3 * 3; @@ -93,20 +86,16 @@ size_t base64_decode_fast(char* const dst, const size_t dstlen, size_t i = 0; size_t k = 0; while (i < max_i && k < max_k) { - const uint32_t v = - unbase64(src[i + 0]) << 24 | - unbase64(src[i + 1]) << 16 | - unbase64(src[i + 2]) << 8 | - unbase64(src[i + 3]); + const uint32_t v = unbase64(src[i + 0]) << 24 | unbase64(src[i + 1]) << 16 | + unbase64(src[i + 2]) << 8 | unbase64(src[i + 3]); // If MSB is set, input contains whitespace or is not valid base64. if (v & 0x80808080) { - if (!base64_decode_group_slow(dst, dstlen, src, srclen, &i, &k)) - return k; + if (!base64_decode_group_slow(dst, dstlen, src, srclen, &i, &k)) return k; max_i = i + (srclen - i) / 4 * 4; // Align max_i again. } else { dst[k + 0] = ((v >> 22) & 0xFC) | ((v >> 20) & 0x03); dst[k + 1] = ((v >> 12) & 0xF0) | ((v >> 10) & 0x0F); - dst[k + 2] = ((v >> 2) & 0xC0) | ((v >> 0) & 0x3F); + dst[k + 2] = ((v >> 2) & 0xC0) | ((v >> 0) & 0x3F); i += 4; k += 3; } @@ -117,10 +106,11 @@ size_t base64_decode_fast(char* const dst, const size_t dstlen, return k; } - template -size_t base64_decode(char* const dst, const size_t dstlen, - const TypeName* const src, const size_t srclen) { +size_t base64_decode(char* const dst, + const size_t dstlen, + const TypeName* const src, + const size_t srclen) { const size_t decoded_size = base64_decoded_size(src, srclen); return base64_decode_fast(dst, dstlen, src, srclen, decoded_size); } @@ -189,7 +179,6 @@ static size_t base64_encode(const char* src, } } // namespace node - #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #endif // SRC_BASE64_H_ diff --git a/src/base_object-inl.h b/src/base_object-inl.h index d067a807cb8e14..8252f96f4eebf0 100644 --- a/src/base_object-inl.h +++ b/src/base_object-inl.h @@ -32,15 +32,13 @@ namespace node { BaseObject::BaseObject(Environment* env, v8::Local object) - : persistent_handle_(env->isolate(), object), - env_(env) { + : persistent_handle_(env->isolate(), object), env_(env) { CHECK_EQ(false, object.IsEmpty()); CHECK_GT(object->InternalFieldCount(), 0); object->SetAlignedPointerInInternalField(0, static_cast(this)); env_->AddCleanupHook(DeleteMe, static_cast(this)); } - BaseObject::~BaseObject() { env_->RemoveCleanupHook(DeleteMe, static_cast(this)); @@ -55,12 +53,10 @@ BaseObject::~BaseObject() { } } - Persistent& BaseObject::persistent() { return persistent_handle_; } - v8::Local BaseObject::object() const { return PersistentToLocal(env_->isolate(), persistent_handle_); } @@ -78,41 +74,38 @@ Environment* BaseObject::env() const { return env_; } - BaseObject* BaseObject::FromJSObject(v8::Local obj) { CHECK_GT(obj->InternalFieldCount(), 0); return static_cast(obj->GetAlignedPointerFromInternalField(0)); } - template T* BaseObject::FromJSObject(v8::Local object) { return static_cast(FromJSObject(object)); } - void BaseObject::MakeWeak() { - persistent_handle_.SetWeak( - this, - [](const v8::WeakCallbackInfo& data) { - BaseObject* obj = data.GetParameter(); - // Clear the persistent handle so that ~BaseObject() doesn't attempt - // to mess with internal fields, since the JS object may have - // transitioned into an invalid state. - // Refs: https://github.com/nodejs/node/issues/18897 - obj->persistent_handle_.Reset(); - delete obj; - }, v8::WeakCallbackType::kParameter); + persistent_handle_.SetWeak(this, + [](const v8::WeakCallbackInfo& data) { + BaseObject* obj = data.GetParameter(); + // Clear the persistent handle so that + // ~BaseObject() doesn't attempt to mess with + // internal fields, since the JS object may have + // transitioned into an invalid state. + // Refs: + // https://github.com/nodejs/node/issues/18897 + obj->persistent_handle_.Reset(); + delete obj; + }, + v8::WeakCallbackType::kParameter); } - void BaseObject::ClearWeak() { persistent_handle_.ClearWeak(); } - -v8::Local -BaseObject::MakeLazilyInitializedJSTemplate(Environment* env) { +v8::Local BaseObject::MakeLazilyInitializedJSTemplate( + Environment* env) { auto constructor = [](const v8::FunctionCallbackInfo& args) { #ifdef DEBUG CHECK(args.IsConstructCall()); diff --git a/src/base_object.h b/src/base_object.h index 64a237143386f2..059d41e6c6dbdc 100644 --- a/src/base_object.h +++ b/src/base_object.h @@ -24,19 +24,17 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_persistent.h" +#include // std::remove_reference #include "memory_tracker-inl.h" +#include "node_persistent.h" #include "v8.h" -#include // std::remove_reference namespace node { class Environment; -#define ADD_MEMORY_INFO_NAME(name) \ - std::string MemoryInfoName() const override { \ - return #name; \ - } +#define ADD_MEMORY_INFO_NAME(name) \ + std::string MemoryInfoName() const override { return #name; } class BaseObject : public MemoryRetainer { public: @@ -97,20 +95,17 @@ class BaseObject : public MemoryRetainer { Environment* env_; }; - // Global alias for FromJSObject() to avoid churn. template inline T* Unwrap(v8::Local obj) { return BaseObject::FromJSObject(obj); } - -#define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...) \ - do { \ - *ptr = static_cast::type>( \ - BaseObject::FromJSObject(obj)); \ - if (*ptr == nullptr) \ - return __VA_ARGS__; \ +#define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...) \ + do { \ + *ptr = static_cast::type>( \ + BaseObject::FromJSObject(obj)); \ + if (*ptr == nullptr) return __VA_ARGS__; \ } while (0) } // namespace node diff --git a/src/bootstrapper.cc b/src/bootstrapper.cc index 5f40d62a82fdef..e593f68aa719da 100644 --- a/src/bootstrapper.cc +++ b/src/bootstrapper.cc @@ -1,5 +1,5 @@ -#include "node.h" #include "env-inl.h" +#include "node.h" #include "node_internals.h" #include "v8.h" @@ -38,9 +38,9 @@ void SetupNextTick(const FunctionCallbackInfo& args) { env->set_tick_callback_function(args[0].As()); - Local run_microtasks_fn = - env->NewFunctionTemplate(RunMicrotasks)->GetFunction(context) - .ToLocalChecked(); + Local run_microtasks_fn = env->NewFunctionTemplate(RunMicrotasks) + ->GetFunction(context) + .ToLocalChecked(); run_microtasks_fn->SetName(FIXED_ONE_BYTE_STRING(isolate, "runMicrotasks")); Local ret = Array::New(isolate, 2); @@ -63,8 +63,7 @@ void PromiseRejectCallback(PromiseRejectMessage message) { callback = env->promise_reject_unhandled_function(); value = message.GetValue(); - if (value.IsEmpty()) - value = Undefined(isolate); + if (value.IsEmpty()) value = Undefined(isolate); } else if (event == v8::kPromiseHandlerAddedAfterReject) { callback = env->promise_reject_handled_function(); value = Undefined(isolate); @@ -72,11 +71,9 @@ void PromiseRejectCallback(PromiseRejectMessage message) { return; } - Local args[] = { promise, value }; - MaybeLocal ret = callback->Call(env->context(), - Undefined(isolate), - arraysize(args), - args); + Local args[] = {promise, value}; + MaybeLocal ret = + callback->Call(env->context(), Undefined(isolate), arraysize(args), args); if (!ret.IsEmpty() && ret.ToLocalChecked()->IsTrue()) env->tick_info()->promise_rejections_toggle_on(); @@ -100,8 +97,7 @@ void SetupPromises(const FunctionCallbackInfo& args) { // the bootstrap process of the Node.js environment. A reference to the // bootstrap object must not be kept around after the bootstrap process // completes so that it can be gc'd as soon as possible. -void SetupBootstrapObject(Environment* env, - Local bootstrapper) { +void SetupBootstrapObject(Environment* env, Local bootstrapper) { BOOTSTRAP_METHOD(_setupProcessObject, SetupProcessObject); BOOTSTRAP_METHOD(_setupNextTick, SetupNextTick); BOOTSTRAP_METHOD(_setupPromises, SetupPromises); @@ -126,10 +122,11 @@ void SetupBootstrapObject(Environment* env, Local should_abort_on_uncaught_toggle = FIXED_ONE_BYTE_STRING(env->isolate(), "_shouldAbortOnUncaughtToggle"); - CHECK(bootstrapper->Set(env->context(), - should_abort_on_uncaught_toggle, - env->should_abort_on_uncaught_toggle().GetJSArray()) - .FromJust()); + CHECK(bootstrapper + ->Set(env->context(), + should_abort_on_uncaught_toggle, + env->should_abort_on_uncaught_toggle().GetJSArray()) + .FromJust()); } #undef BOOTSTRAP_METHOD @@ -139,10 +136,10 @@ void Initialize(Local target, Local unused, Local context) { Environment* env = Environment::GetCurrent(context); -#define V(PropertyName, StringValue) \ - target->Set(env->context(), \ - env->PropertyName()->Name(), \ - env->PropertyName()).FromJust(); +#define V(PropertyName, StringValue) \ + target \ + ->Set(env->context(), env->PropertyName()->Name(), env->PropertyName()) \ + .FromJust(); PER_ISOLATE_SYMBOL_PROPERTIES(V) #undef V } diff --git a/src/callback_scope.cc b/src/callback_scope.cc index 7929fd67d7667e..c7de3e21232289 100644 --- a/src/callback_scope.cc +++ b/src/callback_scope.cc @@ -1,6 +1,6 @@ -#include "node.h" #include "async_wrap-inl.h" #include "env-inl.h" +#include "node.h" #include "v8.h" namespace node { @@ -15,33 +15,31 @@ using AsyncHooks = Environment::AsyncHooks; CallbackScope::CallbackScope(Isolate* isolate, Local object, async_context asyncContext) - : private_(new InternalCallbackScope(Environment::GetCurrent(isolate), - object, - asyncContext)), - try_catch_(isolate) { + : private_(new InternalCallbackScope( + Environment::GetCurrent(isolate), object, asyncContext)), + try_catch_(isolate) { try_catch_.SetVerbose(true); } CallbackScope::~CallbackScope() { - if (try_catch_.HasCaught()) - private_->MarkAsFailed(); + if (try_catch_.HasCaught()) private_->MarkAsFailed(); delete private_; } InternalCallbackScope::InternalCallbackScope(AsyncWrap* async_wrap) - : InternalCallbackScope(async_wrap->env(), - async_wrap->object(), - { async_wrap->get_async_id(), - async_wrap->get_trigger_async_id() }) {} + : InternalCallbackScope( + async_wrap->env(), + async_wrap->object(), + {async_wrap->get_async_id(), async_wrap->get_trigger_async_id()}) {} InternalCallbackScope::InternalCallbackScope(Environment* env, Local object, const async_context& asyncContext, ResourceExpectation expect) - : env_(env), - async_context_(asyncContext), - object_(object), - callback_scope_(env) { + : env_(env), + async_context_(asyncContext), + object_(object), + callback_scope_(env) { CHECK_IMPLIES(expect == kRequireResource, !object.IsEmpty()); if (!env->can_call_into_js()) { @@ -60,7 +58,7 @@ InternalCallbackScope::InternalCallbackScope(Environment* env, } env->async_hooks()->push_async_ids(async_context_.async_id, - async_context_.trigger_async_id); + async_context_.trigger_async_id); pushed_ids_ = true; } @@ -78,8 +76,7 @@ void InternalCallbackScope::Close() { env_->async_hooks()->clear_async_id_stack(); } - if (pushed_ids_) - env_->async_hooks()->pop_async_id(async_context_.async_id); + if (pushed_ids_) env_->async_hooks()->pop_async_id(async_context_.async_id); if (failed_) return; diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index 9d3d098734470f..f9d9ab3bd3a937 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -31,25 +31,23 @@ #include #include -#include #include +#include #ifdef __POSIX__ -# include +#include #endif // __POSIX__ -#if defined(__ANDROID__) || \ - defined(__MINGW32__) || \ - defined(__OpenBSD__) || \ +#if defined(__ANDROID__) || defined(__MINGW32__) || defined(__OpenBSD__) || \ defined(_MSC_VER) -# include +#include #else -# include +#include #endif #if defined(__OpenBSD__) -# define AI_V4MAPPED 0 +#define AI_V4MAPPED 0 #endif namespace node { @@ -79,8 +77,7 @@ inline uint16_t cares_get_16bit(const unsigned char* p) { inline uint32_t cares_get_32bit(const unsigned char* p) { return static_cast(p[0] << 24U) | static_cast(p[1] << 16U) | - static_cast(p[2] << 8U) | - static_cast(p[3]); + static_cast(p[2] << 8U) | static_cast(p[3]); } const int ns_t_cname_or_a = -1; @@ -88,7 +85,9 @@ const int ns_t_cname_or_a = -1; #define DNS_ESETSRVPENDING -1000 inline const char* ToErrorCodeString(int status) { switch (status) { -#define V(code) case ARES_##code: return #code; +#define V(code) \ + case ARES_##code: \ + return #code; V(EADDRGETNETWORKPARAMS) V(EBADFAMILY) V(EBADFLAGS) @@ -196,15 +195,14 @@ void node_ares_task::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("channel", channel); } -ChannelWrap::ChannelWrap(Environment* env, - Local object) - : AsyncWrap(env, object, PROVIDER_DNSCHANNEL), - timer_handle_(nullptr), - channel_(nullptr), - query_last_ok_(true), - is_servers_default_(true), - library_inited_(false), - active_query_count_(0) { +ChannelWrap::ChannelWrap(Environment* env, Local object) + : AsyncWrap(env, object, PROVIDER_DNSCHANNEL), + timer_handle_(nullptr), + channel_(nullptr), + query_last_ok_(true), + is_servers_default_(true), + library_inited_(false), + active_query_count_(0) { MakeWeak(); Setup(); @@ -239,10 +237,8 @@ class GetAddrInfoReqWrap : public ReqWrap { GetAddrInfoReqWrap::GetAddrInfoReqWrap(Environment* env, Local req_wrap_obj, bool verbatim) - : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETADDRINFOREQWRAP) - , verbatim_(verbatim) { -} - + : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETADDRINFOREQWRAP), + verbatim_(verbatim) {} class GetNameInfoReqWrap : public ReqWrap { public: @@ -257,9 +253,7 @@ class GetNameInfoReqWrap : public ReqWrap { GetNameInfoReqWrap::GetNameInfoReqWrap(Environment* env, Local req_wrap_obj) - : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETNAMEINFOREQWRAP) { -} - + : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETNAMEINFOREQWRAP) {} /* This is called once per second by loop->timer. It is used to constantly */ /* call back into c-ares for possibly processing timeouts. */ @@ -270,7 +264,6 @@ void ChannelWrap::AresTimeout(uv_timer_t* handle) { ares_process_fd(channel->cares_channel(), ARES_SOCKET_BAD, ARES_SOCKET_BAD); } - void ares_poll_cb(uv_poll_t* watcher, int status, int events) { node_ares_task* task = ContainerOf(&node_ares_task::poll_watcher, watcher); ChannelWrap* channel = task->channel; @@ -291,13 +284,11 @@ void ares_poll_cb(uv_poll_t* watcher, int status, int events) { events & UV_WRITABLE ? task->sock : ARES_SOCKET_BAD); } - void ares_poll_close_cb(uv_poll_t* watcher) { node_ares_task* task = ContainerOf(&node_ares_task::poll_watcher, watcher); delete task; } - /* Allocates and returns a new node_ares_task */ node_ares_task* ares_task_create(ChannelWrap* channel, ares_socket_t sock) { auto task = new node_ares_task(); @@ -310,8 +301,8 @@ node_ares_task* ares_task_create(ChannelWrap* channel, ares_socket_t sock) { task->channel = channel; task->sock = sock; - if (uv_poll_init_socket(channel->env()->event_loop(), - &task->poll_watcher, sock) < 0) { + if (uv_poll_init_socket( + channel->env()->event_loop(), &task->poll_watcher, sock) < 0) { /* This should never happen. */ free(task); return nullptr; @@ -320,12 +311,8 @@ node_ares_task* ares_task_create(ChannelWrap* channel, ares_socket_t sock) { return task; } - /* Callback from ares when socket operation is started */ -void ares_sockstate_cb(void* data, - ares_socket_t sock, - int read, - int write) { +void ares_sockstate_cb(void* data, ares_socket_t sock, int read, int write) { ChannelWrap* channel = static_cast(data); node_ares_task* task; @@ -373,7 +360,6 @@ void ares_sockstate_cb(void* data, } } - Local HostentToNames(Environment* env, struct hostent* host, Local append_to = Local()) { @@ -434,9 +420,7 @@ void cares_wrap_hostent_cpy(struct hostent* dest, struct hostent* src) { /* copy `h_aliases` */ size_t alias_count; size_t cur_alias_length; - for (alias_count = 0; - src->h_aliases[alias_count] != nullptr; - alias_count++) { + for (alias_count = 0; src->h_aliases[alias_count] != nullptr; alias_count++) { } dest->h_aliases = node::Malloc(alias_count + 1); @@ -449,9 +433,7 @@ void cares_wrap_hostent_cpy(struct hostent* dest, struct hostent* src) { /* copy `h_addr_list` */ size_t list_count; - for (list_count = 0; - src->h_addr_list[list_count] != nullptr; - list_count++) { + for (list_count = 0; src->h_addr_list[list_count] != nullptr; list_count++) { } dest->h_addr_list = node::Malloc(list_count + 1); @@ -493,14 +475,12 @@ void ChannelWrap::Setup() { // Multiple calls to ares_library_init() increase a reference counter, // so this is a no-op except for the first call to it. r = ares_library_init(ARES_LIB_INIT_ALL); - if (r != ARES_SUCCESS) - return env()->ThrowError(ToErrorCodeString(r)); + if (r != ARES_SUCCESS) return env()->ThrowError(ToErrorCodeString(r)); } /* We do the call to ares_init_option for caller. */ - r = ares_init_options(&channel_, - &options, - ARES_OPT_FLAGS | ARES_OPT_SOCK_STATE_CB); + r = ares_init_options( + &channel_, &options, ARES_OPT_FLAGS | ARES_OPT_SOCK_STATE_CB); if (r != ARES_SUCCESS) { Mutex::ScopedLock lock(ares_library_mutex); @@ -523,8 +503,7 @@ void ChannelWrap::StartTimer() { } void ChannelWrap::CloseTimer() { - if (timer_handle_ == nullptr) - return; + if (timer_handle_ == nullptr) return; env()->CloseHandle(timer_handle_, [](uv_timer_t* handle) { delete handle; }); timer_handle_ = nullptr; @@ -541,13 +520,11 @@ ChannelWrap::~ChannelWrap() { CloseTimer(); } - void ChannelWrap::ModifyActivityQueryCount(int count) { active_query_count_ += count; if (active_query_count_ < 0) active_query_count_ = 0; } - /** * This function is to check whether current servers are fallback servers * when cares initialized. @@ -576,8 +553,7 @@ void ChannelWrap::EnsureServers() { /* if the only server is not 127.0.0.1, ignore */ if (servers[0].family != AF_INET || servers[0].addr.addr4.s_addr != htonl(INADDR_LOOPBACK) || - servers[0].tcp_port != 0 || - servers[0].udp_port != 0) { + servers[0].tcp_port != 0 || servers[0].udp_port != 0) { ares_free_data(servers); is_servers_default_ = false; return; @@ -593,21 +569,18 @@ void ChannelWrap::EnsureServers() { Setup(); } - class QueryWrap : public AsyncWrap { public: QueryWrap(ChannelWrap* channel, Local req_wrap_obj) : AsyncWrap(channel->env(), req_wrap_obj, AsyncWrap::PROVIDER_QUERYWRAP), channel_(channel) { // Make sure the channel object stays alive during the query lifetime. - req_wrap_obj->Set(env()->context(), - env()->channel_string(), - channel->object()).FromJust(); + req_wrap_obj + ->Set(env()->context(), env()->channel_string(), channel->object()) + .FromJust(); } - ~QueryWrap() override { - CHECK_EQ(false, persistent().IsEmpty()); - } + ~QueryWrap() override { CHECK_EQ(false, persistent().IsEmpty()); } // Subclasses should implement the appropriate Send method. virtual int Send(const char* name) { @@ -621,11 +594,13 @@ class QueryWrap : public AsyncWrap { } protected: - void AresQuery(const char* name, - int dnsclass, - int type) { + void AresQuery(const char* name, int dnsclass, int type) { channel_->EnsureServers(); - ares_query(channel_->cares_channel(), name, dnsclass, type, Callback, + ares_query(channel_->cares_channel(), + name, + dnsclass, + type, + Callback, static_cast(this)); } @@ -657,8 +632,11 @@ class QueryWrap : public AsyncWrap { wrap->env()->CloseHandle(handle, CaresAsyncClose); } - static void Callback(void* arg, int status, int timeouts, - unsigned char* answer_buf, int answer_len) { + static void Callback(void* arg, + int status, + int timeouts, + unsigned char* answer_buf, + int answer_len) { QueryWrap* wrap = static_cast(arg); unsigned char* buf_copy = nullptr; @@ -675,9 +653,9 @@ class QueryWrap : public AsyncWrap { data->len = answer_len; uv_async_t* async_handle = &data->async_handle; - CHECK_EQ(0, uv_async_init(wrap->env()->event_loop(), - async_handle, - CaresAsyncCb)); + CHECK_EQ( + 0, + uv_async_init(wrap->env()->event_loop(), async_handle, CaresAsyncCb)); wrap->channel_->set_query_last_ok(status != ARES_ECONNREFUSED); wrap->channel_->ModifyActivityQueryCount(-1); @@ -685,7 +663,9 @@ class QueryWrap : public AsyncWrap { uv_async_send(async_handle); } - static void Callback(void* arg, int status, int timeouts, + static void Callback(void* arg, + int status, + int timeouts, struct hostent* host) { QueryWrap* wrap = static_cast(arg); @@ -702,9 +682,9 @@ class QueryWrap : public AsyncWrap { data->is_host = true; uv_async_t* async_handle = &data->async_handle; - CHECK_EQ(0, uv_async_init(wrap->env()->event_loop(), - async_handle, - CaresAsyncCb)); + CHECK_EQ( + 0, + uv_async_init(wrap->env()->event_loop(), async_handle, CaresAsyncCb)); wrap->channel_->set_query_last_ok(status != ARES_ECONNREFUSED); async_handle->data = data; @@ -715,11 +695,7 @@ class QueryWrap : public AsyncWrap { Local extra = Local()) { HandleScope handle_scope(env()->isolate()); Context::Scope context_scope(env()->context()); - Local argv[] = { - Integer::New(env()->isolate(), 0), - answer, - extra - }; + Local argv[] = {Integer::New(env()->isolate(), 0), answer, extra}; const int argc = arraysize(argv) - extra.IsEmpty(); MakeCallback(env()->oncomplete_string(), argc, argv); } @@ -734,18 +710,13 @@ class QueryWrap : public AsyncWrap { } // Subclasses should implement the appropriate Parse method. - virtual void Parse(unsigned char* buf, int len) { - UNREACHABLE(); - } + virtual void Parse(unsigned char* buf, int len) { UNREACHABLE(); } - virtual void Parse(struct hostent* host) { - UNREACHABLE(); - } + virtual void Parse(struct hostent* host) { UNREACHABLE(); } ChannelWrap* channel_; }; - template Local AddrTTLToArray(Environment* env, const T* addrttls, @@ -763,7 +734,6 @@ Local AddrTTLToArray(Environment* env, return escapable_handle_scope.Escape(ttls); } - int ParseGeneralReply(Environment* env, const unsigned char* buf, int len, @@ -780,18 +750,12 @@ int ParseGeneralReply(Environment* env, case ns_t_a: case ns_t_cname: case ns_t_cname_or_a: - status = ares_parse_a_reply(buf, - len, - &host, - static_cast(addrttls), - naddrttls); + status = ares_parse_a_reply( + buf, len, &host, static_cast(addrttls), naddrttls); break; case ns_t_aaaa: - status = ares_parse_aaaa_reply(buf, - len, - &host, - static_cast(addrttls), - naddrttls); + status = ares_parse_aaaa_reply( + buf, len, &host, static_cast(addrttls), naddrttls); break; case ns_t_ns: status = ares_parse_ns_reply(buf, len, &host); @@ -804,8 +768,7 @@ int ParseGeneralReply(Environment* env, break; } - if (status != ARES_SUCCESS) - return status; + if (status != ARES_SUCCESS) return status; /* If it's `CNAME`, return the CNAME value; * And if it's `CNAME_OR_A` and it has value in `h_name` and `h_aliases[0]`, @@ -815,15 +778,14 @@ int ParseGeneralReply(Environment* env, // A cname lookup always returns a single record but we follow the // common API here. *type = ns_t_cname; - ret->Set(context, - ret->Length(), - OneByteString(env->isolate(), host->h_name)).FromJust(); + ret->Set( + context, ret->Length(), OneByteString(env->isolate(), host->h_name)) + .FromJust(); ares_free_hostent(host); return ARES_SUCCESS; } - if (*type == ns_t_cname_or_a) - *type = ns_t_a; + if (*type == ns_t_cname_or_a) *type = ns_t_a; if (*type == ns_t_ns) { HostentToNames(env, host, ret); @@ -848,7 +810,6 @@ int ParseGeneralReply(Environment* env, return ARES_SUCCESS; } - int ParseMxReply(Environment* env, const unsigned char* buf, int len, @@ -867,16 +828,19 @@ int ParseMxReply(Environment* env, ares_mx_reply* current = mx_start; for (uint32_t i = 0; current != nullptr; ++i, current = current->next) { Local mx_record = Object::New(env->isolate()); - mx_record->Set(context, - env->exchange_string(), - OneByteString(env->isolate(), current->host)).FromJust(); - mx_record->Set(context, - env->priority_string(), - Integer::New(env->isolate(), current->priority)).FromJust(); + mx_record + ->Set(context, + env->exchange_string(), + OneByteString(env->isolate(), current->host)) + .FromJust(); + mx_record + ->Set(context, + env->priority_string(), + Integer::New(env->isolate(), current->priority)) + .FromJust(); if (need_type) - mx_record->Set(context, - env->type_string(), - env->dns_mx_string()).FromJust(); + mx_record->Set(context, env->type_string(), env->dns_mx_string()) + .FromJust(); ret->Set(context, i + offset, mx_record).FromJust(); } @@ -914,9 +878,8 @@ int ParseTxtReply(Environment* env, if (need_type) { Local elem = Object::New(env->isolate()); elem->Set(context, env->entries_string(), txt_chunk).FromJust(); - elem->Set(context, - env->type_string(), - env->dns_txt_string()).FromJust(); + elem->Set(context, env->type_string(), env->dns_txt_string()) + .FromJust(); ret->Set(context, offset + i++, elem).FromJust(); } else { ret->Set(context, offset + i++, txt_chunk).FromJust(); @@ -935,9 +898,7 @@ int ParseTxtReply(Environment* env, if (need_type) { Local elem = Object::New(env->isolate()); elem->Set(context, env->entries_string(), txt_chunk).FromJust(); - elem->Set(context, - env->type_string(), - env->dns_txt_string()).FromJust(); + elem->Set(context, env->type_string(), env->dns_txt_string()).FromJust(); ret->Set(context, offset + i, elem).FromJust(); } else { ret->Set(context, offset + i, txt_chunk).FromJust(); @@ -948,7 +909,6 @@ int ParseTxtReply(Environment* env, return ARES_SUCCESS; } - int ParseSrvReply(Environment* env, const unsigned char* buf, int len, @@ -967,22 +927,29 @@ int ParseSrvReply(Environment* env, int offset = ret->Length(); for (uint32_t i = 0; current != nullptr; ++i, current = current->next) { Local srv_record = Object::New(env->isolate()); - srv_record->Set(context, - env->name_string(), - OneByteString(env->isolate(), current->host)).FromJust(); - srv_record->Set(context, - env->port_string(), - Integer::New(env->isolate(), current->port)).FromJust(); - srv_record->Set(context, - env->priority_string(), - Integer::New(env->isolate(), current->priority)).FromJust(); - srv_record->Set(context, - env->weight_string(), - Integer::New(env->isolate(), current->weight)).FromJust(); + srv_record + ->Set(context, + env->name_string(), + OneByteString(env->isolate(), current->host)) + .FromJust(); + srv_record + ->Set(context, + env->port_string(), + Integer::New(env->isolate(), current->port)) + .FromJust(); + srv_record + ->Set(context, + env->priority_string(), + Integer::New(env->isolate(), current->priority)) + .FromJust(); + srv_record + ->Set(context, + env->weight_string(), + Integer::New(env->isolate(), current->weight)) + .FromJust(); if (need_type) - srv_record->Set(context, - env->type_string(), - env->dns_srv_string()).FromJust(); + srv_record->Set(context, env->type_string(), env->dns_srv_string()) + .FromJust(); ret->Set(context, i + offset, srv_record).FromJust(); } @@ -991,7 +958,6 @@ int ParseSrvReply(Environment* env, return ARES_SUCCESS; } - int ParseNaptrReply(Environment* env, const unsigned char* buf, int len, @@ -1011,32 +977,39 @@ int ParseNaptrReply(Environment* env, int offset = ret->Length(); for (uint32_t i = 0; current != nullptr; ++i, current = current->next) { Local naptr_record = Object::New(env->isolate()); - naptr_record->Set(context, - env->flags_string(), - OneByteString(env->isolate(), current->flags)).FromJust(); - naptr_record->Set(context, - env->service_string(), - OneByteString(env->isolate(), - current->service)).FromJust(); - naptr_record->Set(context, - env->regexp_string(), - OneByteString(env->isolate(), - current->regexp)).FromJust(); - naptr_record->Set(context, - env->replacement_string(), - OneByteString(env->isolate(), - current->replacement)).FromJust(); - naptr_record->Set(context, - env->order_string(), - Integer::New(env->isolate(), current->order)).FromJust(); - naptr_record->Set(context, - env->preference_string(), - Integer::New(env->isolate(), - current->preference)).FromJust(); + naptr_record + ->Set(context, + env->flags_string(), + OneByteString(env->isolate(), current->flags)) + .FromJust(); + naptr_record + ->Set(context, + env->service_string(), + OneByteString(env->isolate(), current->service)) + .FromJust(); + naptr_record + ->Set(context, + env->regexp_string(), + OneByteString(env->isolate(), current->regexp)) + .FromJust(); + naptr_record + ->Set(context, + env->replacement_string(), + OneByteString(env->isolate(), current->replacement)) + .FromJust(); + naptr_record + ->Set(context, + env->order_string(), + Integer::New(env->isolate(), current->order)) + .FromJust(); + naptr_record + ->Set(context, + env->preference_string(), + Integer::New(env->isolate(), current->preference)) + .FromJust(); if (need_type) - naptr_record->Set(context, - env->type_string(), - env->dns_naptr_string()).FromJust(); + naptr_record->Set(context, env->type_string(), env->dns_naptr_string()) + .FromJust(); ret->Set(context, i + offset, naptr_record).FromJust(); } @@ -1045,7 +1018,6 @@ int ParseNaptrReply(Environment* env, return ARES_SUCCESS; } - int ParseSoaReply(Environment* env, unsigned char* buf, int len, @@ -1075,8 +1047,7 @@ int ParseSoaReply(Environment* env, for (unsigned int i = 0; i < ancount; i++) { status = ares_expand_name(ptr, buf, len, &rr_name, &temp_len); - if (status != ARES_SUCCESS) - break; + if (status != ARES_SUCCESS) break; ptr += temp_len; if (ptr + NS_RRFIXEDSZ > buf + len) { @@ -1123,31 +1094,43 @@ int ParseSoaReply(Environment* env, soa.minttl = cares_get_32bit(ptr + 4 * 4); Local soa_record = Object::New(env->isolate()); - soa_record->Set(context, - env->nsname_string(), - OneByteString(env->isolate(), soa.nsname)).FromJust(); - soa_record->Set(context, - env->hostmaster_string(), - OneByteString(env->isolate(), - soa.hostmaster)).FromJust(); - soa_record->Set(context, - env->serial_string(), - Integer::New(env->isolate(), soa.serial)).FromJust(); - soa_record->Set(context, - env->refresh_string(), - Integer::New(env->isolate(), soa.refresh)).FromJust(); - soa_record->Set(context, - env->retry_string(), - Integer::New(env->isolate(), soa.retry)).FromJust(); - soa_record->Set(context, - env->expire_string(), - Integer::New(env->isolate(), soa.expire)).FromJust(); - soa_record->Set(context, - env->minttl_string(), - Integer::New(env->isolate(), soa.minttl)).FromJust(); - soa_record->Set(context, - env->type_string(), - env->dns_soa_string()).FromJust(); + soa_record + ->Set(context, + env->nsname_string(), + OneByteString(env->isolate(), soa.nsname)) + .FromJust(); + soa_record + ->Set(context, + env->hostmaster_string(), + OneByteString(env->isolate(), soa.hostmaster)) + .FromJust(); + soa_record + ->Set(context, + env->serial_string(), + Integer::New(env->isolate(), soa.serial)) + .FromJust(); + soa_record + ->Set(context, + env->refresh_string(), + Integer::New(env->isolate(), soa.refresh)) + .FromJust(); + soa_record + ->Set(context, + env->retry_string(), + Integer::New(env->isolate(), soa.retry)) + .FromJust(); + soa_record + ->Set(context, + env->expire_string(), + Integer::New(env->isolate(), soa.expire)) + .FromJust(); + soa_record + ->Set(context, + env->minttl_string(), + Integer::New(env->isolate(), soa.minttl)) + .FromJust(); + soa_record->Set(context, env->type_string(), env->dns_soa_string()) + .FromJust(); free(soa.nsname); free(soa.hostmaster); @@ -1169,12 +1152,10 @@ int ParseSoaReply(Environment* env, return ARES_SUCCESS; } - -class QueryAnyWrap: public QueryWrap { +class QueryAnyWrap : public QueryWrap { public: QueryAnyWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_any); @@ -1201,13 +1182,8 @@ class QueryAnyWrap: public QueryWrap { int naddrttls = arraysize(addrttls); type = ns_t_cname_or_a; - status = ParseGeneralReply(env(), - buf, - len, - &type, - ret, - addrttls, - &naddrttls); + status = + ParseGeneralReply(env(), buf, len, &type, ret, addrttls, &naddrttls); int a_count = ret->Length(); if (status != ARES_SUCCESS && status != ARES_ENODATA) { ParseError(status); @@ -1220,13 +1196,14 @@ class QueryAnyWrap: public QueryWrap { Local obj = Object::New(env()->isolate()); obj->Set(context, env()->address_string(), - ret->Get(context, i).ToLocalChecked()).FromJust(); + ret->Get(context, i).ToLocalChecked()) + .FromJust(); obj->Set(context, env()->ttl_string(), - Integer::New(env()->isolate(), addrttls[i].ttl)).FromJust(); - obj->Set(context, - env()->type_string(), - env()->dns_a_string()).FromJust(); + Integer::New(env()->isolate(), addrttls[i].ttl)) + .FromJust(); + obj->Set(context, env()->type_string(), env()->dns_a_string()) + .FromJust(); ret->Set(context, i, obj).FromJust(); } } else { @@ -1234,10 +1211,10 @@ class QueryAnyWrap: public QueryWrap { Local obj = Object::New(env()->isolate()); obj->Set(context, env()->value_string(), - ret->Get(context, i).ToLocalChecked()).FromJust(); - obj->Set(context, - env()->type_string(), - env()->dns_cname_string()).FromJust(); + ret->Get(context, i).ToLocalChecked()) + .FromJust(); + obj->Set(context, env()->type_string(), env()->dns_cname_string()) + .FromJust(); ret->Set(context, i, obj).FromJust(); } } @@ -1247,13 +1224,8 @@ class QueryAnyWrap: public QueryWrap { int naddr6ttls = arraysize(addr6ttls); type = ns_t_aaaa; - status = ParseGeneralReply(env(), - buf, - len, - &type, - ret, - addr6ttls, - &naddr6ttls); + status = + ParseGeneralReply(env(), buf, len, &type, ret, addr6ttls, &naddr6ttls); int aaaa_count = ret->Length() - a_count; if (status != ARES_SUCCESS && status != ARES_ENODATA) { ParseError(status); @@ -1265,13 +1237,14 @@ class QueryAnyWrap: public QueryWrap { Local obj = Object::New(env()->isolate()); obj->Set(context, env()->address_string(), - ret->Get(context, i).ToLocalChecked()).FromJust(); + ret->Get(context, i).ToLocalChecked()) + .FromJust(); obj->Set(context, env()->ttl_string(), - Integer::New(env()->isolate(), addr6ttls[i].ttl)).FromJust(); - obj->Set(context, - env()->type_string(), - env()->dns_aaaa_string()).FromJust(); + Integer::New(env()->isolate(), addr6ttls[i].ttl)) + .FromJust(); + obj->Set(context, env()->type_string(), env()->dns_aaaa_string()) + .FromJust(); ret->Set(context, i, obj).FromJust(); } @@ -1294,10 +1267,10 @@ class QueryAnyWrap: public QueryWrap { Local obj = Object::New(env()->isolate()); obj->Set(context, env()->value_string(), - ret->Get(context, i).ToLocalChecked()).FromJust(); - obj->Set(context, - env()->type_string(), - env()->dns_ns_string()).FromJust(); + ret->Get(context, i).ToLocalChecked()) + .FromJust(); + obj->Set(context, env()->type_string(), env()->dns_ns_string()) + .FromJust(); ret->Set(context, i, obj).FromJust(); } @@ -1322,10 +1295,10 @@ class QueryAnyWrap: public QueryWrap { Local obj = Object::New(env()->isolate()); obj->Set(context, env()->value_string(), - ret->Get(context, i).ToLocalChecked()).FromJust(); - obj->Set(context, - env()->type_string(), - env()->dns_ptr_string()).FromJust(); + ret->Get(context, i).ToLocalChecked()) + .FromJust(); + obj->Set(context, env()->type_string(), env()->dns_ptr_string()) + .FromJust(); ret->Set(context, i, obj).FromJust(); } @@ -1350,12 +1323,10 @@ class QueryAnyWrap: public QueryWrap { } }; - -class QueryAWrap: public QueryWrap { +class QueryAWrap : public QueryWrap { public: QueryAWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_a); @@ -1378,32 +1349,24 @@ class QueryAWrap: public QueryWrap { Local ret = Array::New(env()->isolate()); int type = ns_t_a; - status = ParseGeneralReply(env(), - buf, - len, - &type, - ret, - addrttls, - &naddrttls); + status = + ParseGeneralReply(env(), buf, len, &type, ret, addrttls, &naddrttls); if (status != ARES_SUCCESS) { ParseError(status); return; } - Local ttls = AddrTTLToArray(env(), - addrttls, - naddrttls); + Local ttls = + AddrTTLToArray(env(), addrttls, naddrttls); CallOnComplete(ret, ttls); } }; - -class QueryAaaaWrap: public QueryWrap { +class QueryAaaaWrap : public QueryWrap { public: QueryAaaaWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_aaaa); @@ -1426,32 +1389,24 @@ class QueryAaaaWrap: public QueryWrap { Local ret = Array::New(env()->isolate()); int type = ns_t_aaaa; - status = ParseGeneralReply(env(), - buf, - len, - &type, - ret, - addrttls, - &naddrttls); + status = + ParseGeneralReply(env(), buf, len, &type, ret, addrttls, &naddrttls); if (status != ARES_SUCCESS) { ParseError(status); return; } - Local ttls = AddrTTLToArray(env(), - addrttls, - naddrttls); + Local ttls = + AddrTTLToArray(env(), addrttls, naddrttls); CallOnComplete(ret, ttls); } }; - -class QueryCnameWrap: public QueryWrap { +class QueryCnameWrap : public QueryWrap { public: QueryCnameWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_cname); @@ -1481,12 +1436,10 @@ class QueryCnameWrap: public QueryWrap { } }; - -class QueryMxWrap: public QueryWrap { +class QueryMxWrap : public QueryWrap { public: QueryMxWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_mx); @@ -1516,12 +1469,10 @@ class QueryMxWrap: public QueryWrap { } }; - -class QueryNsWrap: public QueryWrap { +class QueryNsWrap : public QueryWrap { public: QueryNsWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_ns); @@ -1551,12 +1502,10 @@ class QueryNsWrap: public QueryWrap { } }; - -class QueryTxtWrap: public QueryWrap { +class QueryTxtWrap : public QueryWrap { public: QueryTxtWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_txt); @@ -1585,12 +1534,10 @@ class QueryTxtWrap: public QueryWrap { } }; - -class QuerySrvWrap: public QueryWrap { +class QuerySrvWrap : public QueryWrap { public: explicit QuerySrvWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_srv); @@ -1619,11 +1566,10 @@ class QuerySrvWrap: public QueryWrap { } }; -class QueryPtrWrap: public QueryWrap { +class QueryPtrWrap : public QueryWrap { public: explicit QueryPtrWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_ptr); @@ -1654,11 +1600,10 @@ class QueryPtrWrap: public QueryWrap { } }; -class QueryNaptrWrap: public QueryWrap { +class QueryNaptrWrap : public QueryWrap { public: explicit QueryNaptrWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_naptr); @@ -1687,12 +1632,10 @@ class QueryNaptrWrap: public QueryWrap { } }; - -class QuerySoaWrap: public QueryWrap { +class QuerySoaWrap : public QueryWrap { public: QuerySoaWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { AresQuery(name, ns_c_in, ns_t_soa); @@ -1721,30 +1664,41 @@ class QuerySoaWrap: public QueryWrap { Local soa_record = Object::New(env()->isolate()); - soa_record->Set(context, - env()->nsname_string(), - OneByteString(env()->isolate(), - soa_out->nsname)).FromJust(); - soa_record->Set(context, - env()->hostmaster_string(), - OneByteString(env()->isolate(), - soa_out->hostmaster)).FromJust(); - soa_record->Set(context, - env()->serial_string(), - Integer::New(env()->isolate(), soa_out->serial)).FromJust(); - soa_record->Set(context, - env()->refresh_string(), - Integer::New(env()->isolate(), - soa_out->refresh)).FromJust(); - soa_record->Set(context, - env()->retry_string(), - Integer::New(env()->isolate(), soa_out->retry)).FromJust(); - soa_record->Set(context, - env()->expire_string(), - Integer::New(env()->isolate(), soa_out->expire)).FromJust(); - soa_record->Set(context, - env()->minttl_string(), - Integer::New(env()->isolate(), soa_out->minttl)).FromJust(); + soa_record + ->Set(context, + env()->nsname_string(), + OneByteString(env()->isolate(), soa_out->nsname)) + .FromJust(); + soa_record + ->Set(context, + env()->hostmaster_string(), + OneByteString(env()->isolate(), soa_out->hostmaster)) + .FromJust(); + soa_record + ->Set(context, + env()->serial_string(), + Integer::New(env()->isolate(), soa_out->serial)) + .FromJust(); + soa_record + ->Set(context, + env()->refresh_string(), + Integer::New(env()->isolate(), soa_out->refresh)) + .FromJust(); + soa_record + ->Set(context, + env()->retry_string(), + Integer::New(env()->isolate(), soa_out->retry)) + .FromJust(); + soa_record + ->Set(context, + env()->expire_string(), + Integer::New(env()->isolate(), soa_out->expire)) + .FromJust(); + soa_record + ->Set(context, + env()->minttl_string(), + Integer::New(env()->isolate(), soa_out->minttl)) + .FromJust(); ares_free_data(soa_out); @@ -1752,12 +1706,10 @@ class QuerySoaWrap: public QueryWrap { } }; - -class GetHostByAddrWrap: public QueryWrap { +class GetHostByAddrWrap : public QueryWrap { public: explicit GetHostByAddrWrap(ChannelWrap* channel, Local req_wrap_obj) - : QueryWrap(channel, req_wrap_obj) { - } + : QueryWrap(channel, req_wrap_obj) {} int Send(const char* name) override { int length, family; @@ -1796,7 +1748,6 @@ class GetHostByAddrWrap: public QueryWrap { } }; - template static void Query(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1822,7 +1773,6 @@ static void Query(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } - void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { GetAddrInfoReqWrap* req_wrap = static_cast(req->data); Environment* env = req_wrap->env(); @@ -1830,16 +1780,14 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); - Local argv[] = { - Integer::New(env->isolate(), status), - Null(env->isolate()) - }; + Local argv[] = {Integer::New(env->isolate(), status), + Null(env->isolate())}; if (status == 0) { int n = 0; Local results = Array::New(env->isolate()); - auto add = [&] (bool want_ipv4, bool want_ipv6) { + auto add = [&](bool want_ipv4, bool want_ipv6) { for (auto p = res; p != nullptr; p = p->ai_next) { CHECK_EQ(p->ai_socktype, SOCK_STREAM); @@ -1855,8 +1803,7 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { } char ip[INET6_ADDRSTRLEN]; - if (uv_inet_ntop(p->ai_family, addr, ip, sizeof(ip))) - continue; + if (uv_inet_ntop(p->ai_family, addr, ip, sizeof(ip))) continue; Local s = OneByteString(env->isolate(), ip); results->Set(n, s); @@ -1866,8 +1813,7 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { const bool verbatim = req_wrap->verbatim(); add(true, verbatim); - if (verbatim == false) - add(false, true); + if (verbatim == false) add(false, true); // No responses were found to return if (n == 0) { @@ -1885,7 +1831,6 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { delete req_wrap; } - void AfterGetNameInfo(uv_getnameinfo_t* req, int status, const char* hostname, @@ -1896,11 +1841,9 @@ void AfterGetNameInfo(uv_getnameinfo_t* req, HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); - Local argv[] = { - Integer::New(env->isolate(), status), - Null(env->isolate()), - Null(env->isolate()) - }; + Local argv[] = {Integer::New(env->isolate(), status), + Null(env->isolate()), + Null(env->isolate())}; if (status == 0) { // Success @@ -1942,8 +1885,9 @@ void CanonicalizeIP(const FunctionCallbackInfo& args) { char canonical_ip[INET6_ADDRSTRLEN]; const int af = (rc == 4 ? AF_INET : AF_INET6); CHECK_EQ(0, uv_inet_ntop(af, &result, canonical_ip, sizeof(canonical_ip))); - v8::Local val = String::NewFromUtf8(isolate, canonical_ip, - v8::NewStringType::kNormal).ToLocalChecked(); + v8::Local val = + String::NewFromUtf8(isolate, canonical_ip, v8::NewStringType::kNormal) + .ToLocalChecked(); args.GetReturnValue().Set(val); } @@ -1965,17 +1909,17 @@ void GetAddrInfo(const FunctionCallbackInfo& args) { int family; switch (args[2]->Int32Value(env->context()).FromJust()) { - case 0: - family = AF_UNSPEC; - break; - case 4: - family = AF_INET; - break; - case 6: - family = AF_INET6; - break; - default: - CHECK(0 && "bad address family"); + case 0: + family = AF_UNSPEC; + break; + case 4: + family = AF_INET; + break; + case 6: + family = AF_INET6; + break; + default: + CHECK(0 && "bad address family"); } auto req_wrap = new GetAddrInfoReqWrap(env, req_wrap_obj, args[4]->IsTrue()); @@ -1986,18 +1930,13 @@ void GetAddrInfo(const FunctionCallbackInfo& args) { hints.ai_socktype = SOCK_STREAM; hints.ai_flags = flags; - int err = req_wrap->Dispatch(uv_getaddrinfo, - AfterGetAddrInfo, - *hostname, - nullptr, - &hints); - if (err) - delete req_wrap; + int err = req_wrap->Dispatch( + uv_getaddrinfo, AfterGetAddrInfo, *hostname, nullptr, &hints); + if (err) delete req_wrap; args.GetReturnValue().Set(err); } - void GetNameInfo(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -2018,13 +1957,11 @@ void GetNameInfo(const FunctionCallbackInfo& args) { AfterGetNameInfo, reinterpret_cast(&addr), NI_NAMEREQD); - if (err) - delete req_wrap; + if (err) delete req_wrap; args.GetReturnValue().Set(err); } - void GetServers(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); ChannelWrap* channel; @@ -2058,7 +1995,6 @@ void GetServers(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(server_array); } - void SetServers(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); ChannelWrap* channel; @@ -2090,18 +2026,26 @@ void SetServers(const FunctionCallbackInfo& args) { Local elm = Local::Cast(arr->Get(env->context(), i).ToLocalChecked()); - CHECK(elm->Get(env->context(), - 0).ToLocalChecked()->Int32Value(env->context()).FromJust()); + CHECK(elm->Get(env->context(), 0) + .ToLocalChecked() + ->Int32Value(env->context()) + .FromJust()); CHECK(elm->Get(env->context(), 1).ToLocalChecked()->IsString()); - CHECK(elm->Get(env->context(), - 2).ToLocalChecked()->Int32Value(env->context()).FromJust()); + CHECK(elm->Get(env->context(), 2) + .ToLocalChecked() + ->Int32Value(env->context()) + .FromJust()); int fam = elm->Get(env->context(), 0) - .ToLocalChecked()->Int32Value(env->context()).FromJust(); + .ToLocalChecked() + ->Int32Value(env->context()) + .FromJust(); node::Utf8Value ip(env->isolate(), elm->Get(env->context(), 1).ToLocalChecked()); int port = elm->Get(env->context(), 2) - .ToLocalChecked()->Int32Value(env->context()).FromJust(); + .ToLocalChecked() + ->Int32Value(env->context()) + .FromJust(); ares_addr_port_node* cur = &servers[i]; @@ -2119,13 +2063,11 @@ void SetServers(const FunctionCallbackInfo& args) { CHECK(0 && "Bad address family."); } - if (err) - break; + if (err) break; cur->next = nullptr; - if (last != nullptr) - last->next = cur; + if (last != nullptr) last->next = cur; last = cur; } @@ -2135,8 +2077,7 @@ void SetServers(const FunctionCallbackInfo& args) { else err = ARES_EBADSTR; - if (err == ARES_SUCCESS) - channel->set_is_servers_default(false); + if (err == ARES_SUCCESS) channel->set_is_servers_default(false); args.GetReturnValue().Set(err); } @@ -2152,13 +2093,11 @@ const char EMSG_ESETSRVPENDING[] = "There are pending queries."; void StrError(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); int code = args[0]->Int32Value(env->context()).FromJust(); - const char* errmsg = (code == DNS_ESETSRVPENDING) ? - EMSG_ESETSRVPENDING : - ares_strerror(code); + const char* errmsg = + (code == DNS_ESETSRVPENDING) ? EMSG_ESETSRVPENDING : ares_strerror(code); args.GetReturnValue().Set(OneByteString(env->isolate(), errmsg)); } - void Initialize(Local target, Local unused, Local context) { diff --git a/src/connect_wrap.cc b/src/connect_wrap.cc index dacdf72da7c494..9e55fab6106d87 100644 --- a/src/connect_wrap.cc +++ b/src/connect_wrap.cc @@ -9,10 +9,9 @@ namespace node { using v8::Local; using v8::Object; - ConnectWrap::ConnectWrap(Environment* env, - Local req_wrap_obj, - AsyncWrap::ProviderType provider) : ReqWrap(env, req_wrap_obj, provider) { -} + Local req_wrap_obj, + AsyncWrap::ProviderType provider) + : ReqWrap(env, req_wrap_obj, provider) {} } // namespace node diff --git a/src/connect_wrap.h b/src/connect_wrap.h index 2370157eaa2a11..92b982615aab13 100644 --- a/src/connect_wrap.h +++ b/src/connect_wrap.h @@ -3,9 +3,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "async_wrap.h" #include "env.h" #include "req_wrap-inl.h" -#include "async_wrap.h" #include "v8.h" namespace node { diff --git a/src/connection_wrap.cc b/src/connection_wrap.cc index 3021307c065511..61d1882bbcb0e0 100644 --- a/src/connection_wrap.cc +++ b/src/connection_wrap.cc @@ -2,8 +2,8 @@ #include "connect_wrap.h" #include "env-inl.h" -#include "pipe_wrap.h" #include "node_internals.h" +#include "pipe_wrap.h" #include "stream_base-inl.h" #include "stream_wrap.h" #include "tcp_wrap.h" @@ -19,16 +19,12 @@ using v8::Local; using v8::Object; using v8::Value; - template ConnectionWrap::ConnectionWrap(Environment* env, Local object, ProviderType provider) - : LibuvStreamWrap(env, - object, - reinterpret_cast(&handle_), - provider) {} - + : LibuvStreamWrap( + env, object, reinterpret_cast(&handle_), provider) {} template void ConnectionWrap::OnConnection(uv_stream_t* handle, @@ -49,9 +45,8 @@ void ConnectionWrap::OnConnection(uv_stream_t* handle, if (status == 0) { // Instantiate the client javascript object and handle. - Local client_obj = WrapType::Instantiate(env, - wrap_data, - WrapType::SOCKET); + Local client_obj = + WrapType::Instantiate(env, wrap_data, WrapType::SOCKET); // Unwrap the client javascript object. WrapType* wrap; @@ -60,8 +55,7 @@ void ConnectionWrap::OnConnection(uv_stream_t* handle, // uv_accept can fail if the new connection has already been closed, in // which case an EAGAIN (resource temporarily unavailable) will be // returned. - if (uv_accept(handle, client)) - return; + if (uv_accept(handle, client)) return; // Successful accept. Call the onconnection callback in JavaScript land. client_handle = client_obj; @@ -69,11 +63,10 @@ void ConnectionWrap::OnConnection(uv_stream_t* handle, client_handle = Undefined(env->isolate()); } - Local argv[] = { Integer::New(env->isolate(), status), client_handle }; + Local argv[] = {Integer::New(env->isolate(), status), client_handle}; wrap_data->MakeCallback(env->onconnection_string(), arraysize(argv), argv); } - template void ConnectionWrap::AfterConnect(uv_connect_t* req, int status) { @@ -99,13 +92,11 @@ void ConnectionWrap::AfterConnect(uv_connect_t* req, writable = uv_is_writable(req->handle) != 0; } - Local argv[5] = { - Integer::New(env->isolate(), status), - wrap->object(), - req_wrap->object(), - Boolean::New(env->isolate(), readable), - Boolean::New(env->isolate(), writable) - }; + Local argv[5] = {Integer::New(env->isolate(), status), + wrap->object(), + req_wrap->object(), + Boolean::New(env->isolate(), readable), + Boolean::New(env->isolate(), writable)}; req_wrap->MakeCallback(env->oncomplete_string(), arraysize(argv), argv); @@ -113,14 +104,10 @@ void ConnectionWrap::AfterConnect(uv_connect_t* req, } template ConnectionWrap::ConnectionWrap( - Environment* env, - Local object, - ProviderType provider); + Environment* env, Local object, ProviderType provider); template ConnectionWrap::ConnectionWrap( - Environment* env, - Local object, - ProviderType provider); + Environment* env, Local object, ProviderType provider); template void ConnectionWrap::OnConnection( uv_stream_t* handle, int status); @@ -134,5 +121,4 @@ template void ConnectionWrap::AfterConnect( template void ConnectionWrap::AfterConnect( uv_connect_t* handle, int status); - } // namespace node diff --git a/src/connection_wrap.h b/src/connection_wrap.h index 72030a00901daf..ebcd473992d9f9 100644 --- a/src/connection_wrap.h +++ b/src/connection_wrap.h @@ -12,9 +12,7 @@ namespace node { template class ConnectionWrap : public LibuvStreamWrap { public: - UVType* UVHandle() { - return &handle_; - } + UVType* UVHandle() { return &handle_; } static void OnConnection(uv_stream_t* handle, int status); static void AfterConnect(uv_connect_t* req, int status); diff --git a/src/debug_utils.cc b/src/debug_utils.cc index a24c51de39cf2d..9b25df2e1d6b14 100644 --- a/src/debug_utils.cc +++ b/src/debug_utils.cc @@ -6,8 +6,7 @@ #include #endif -#if defined(__linux__) && !defined(__GLIBC__) || \ - defined(__UCLIBC__) || \ +#if defined(__linux__) && !defined(__GLIBC__) || defined(__UCLIBC__) || \ defined(_AIX) #define HAVE_EXECINFO_H 0 #else @@ -18,15 +17,15 @@ #include #include #include -#include -#include #include +#include +#include #endif #else // __POSIX__ -#include #include +#include #endif // __POSIX__ @@ -36,14 +35,13 @@ namespace node { #if HAVE_EXECINFO_H class PosixSymbolDebuggingContext final : public NativeSymbolDebuggingContext { public: - PosixSymbolDebuggingContext() : pagesize_(getpagesize()) { } + PosixSymbolDebuggingContext() : pagesize_(getpagesize()) {} SymbolInfo LookupSymbol(void* address) override { Dl_info info; const bool have_info = dladdr(address, &info); SymbolInfo ret; - if (!have_info) - return ret; + if (!have_info) return ret; if (info.dli_sname != nullptr) { if (char* demangled = abi::__cxa_demangle(info.dli_sname, 0, 0, 0)) { @@ -100,12 +98,11 @@ class Win32SymbolDebuggingContext final : public NativeSymbolDebuggingContext { USE(SymInitialize(current_process_, nullptr, true)); } - ~Win32SymbolDebuggingContext() { - USE(SymCleanup(current_process_)); - } + ~Win32SymbolDebuggingContext() { USE(SymCleanup(current_process_)); } SymbolInfo LookupSymbol(void* address) override { - // Ref: https://msdn.microsoft.com/en-en/library/windows/desktop/ms680578(v=vs.85).aspx + // Ref: + // https://msdn.microsoft.com/en-en/library/windows/desktop/ms680578(v=vs.85).aspx char info_buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; SYMBOL_INFO* info = reinterpret_cast(info_buf); char demangled[MAX_SYM_NAME]; @@ -114,15 +111,11 @@ class Win32SymbolDebuggingContext final : public NativeSymbolDebuggingContext { info->SizeOfStruct = sizeof(SYMBOL_INFO); SymbolInfo ret; - const bool have_info = SymFromAddr(current_process_, - reinterpret_cast(address), - nullptr, - info); + const bool have_info = SymFromAddr( + current_process_, reinterpret_cast(address), nullptr, info); if (have_info && strlen(info->Name) == 0) { - if (UnDecorateSymbolName(info->Name, - demangled, - sizeof(demangled), - UNDNAME_COMPLETE)) { + if (UnDecorateSymbolName( + info->Name, demangled, sizeof(demangled), UNDNAME_COMPLETE)) { ret.name = demangled; } else { ret.name = info->Name; @@ -173,8 +166,11 @@ void DumpBacktrace(FILE* fp) { const int size = sym_ctx->GetStackTrace(frames, arraysize(frames)); for (int i = 1; i < size; i += 1) { void* frame = frames[i]; - fprintf(fp, "%2d: %p %s\n", - i, frame, sym_ctx->LookupSymbol(frame).Display().c_str()); + fprintf(fp, + "%2d: %p %s\n", + i, + frame, + sym_ctx->LookupSymbol(frame).Display().c_str()); } } @@ -185,33 +181,43 @@ void CheckedUvLoopClose(uv_loop_t* loop) { fprintf(stderr, "uv loop at [%p] has active handles\n", loop); - uv_walk(loop, [](uv_handle_t* handle, void* arg) { - auto sym_ctx = static_cast(arg); - - fprintf(stderr, "[%p] %s\n", handle, uv_handle_type_name(handle->type)); - - void* close_cb = reinterpret_cast(handle->close_cb); - fprintf(stderr, "\tClose callback: %p %s\n", - close_cb, sym_ctx->LookupSymbol(close_cb).Display().c_str()); - - fprintf(stderr, "\tData: %p %s\n", - handle->data, sym_ctx->LookupSymbol(handle->data).Display().c_str()); - - // We are also interested in the first field of what `handle->data` - // points to, because for C++ code that is usually the virtual table pointer - // and gives us information about the exact kind of object we're looking at. - void* first_field = nullptr; - // `handle->data` might be any value, including `nullptr`, or something - // cast from a completely different type; therefore, check that it’s - // dereferencable first. - if (sym_ctx->IsMapped(handle->data)) - first_field = *reinterpret_cast(handle->data); - - if (first_field != nullptr) { - fprintf(stderr, "\t(First field): %p %s\n", - first_field, sym_ctx->LookupSymbol(first_field).Display().c_str()); - } - }, sym_ctx.get()); + uv_walk(loop, + [](uv_handle_t* handle, void* arg) { + auto sym_ctx = static_cast(arg); + + fprintf( + stderr, "[%p] %s\n", handle, uv_handle_type_name(handle->type)); + + void* close_cb = reinterpret_cast(handle->close_cb); + fprintf(stderr, + "\tClose callback: %p %s\n", + close_cb, + sym_ctx->LookupSymbol(close_cb).Display().c_str()); + + fprintf(stderr, + "\tData: %p %s\n", + handle->data, + sym_ctx->LookupSymbol(handle->data).Display().c_str()); + + // We are also interested in the first field of what `handle->data` + // points to, because for C++ code that is usually the virtual table + // pointer and gives us information about the exact kind of object + // we're looking at. + void* first_field = nullptr; + // `handle->data` might be any value, including `nullptr`, or + // something cast from a completely different type; therefore, check + // that it’s dereferencable first. + if (sym_ctx->IsMapped(handle->data)) + first_field = *reinterpret_cast(handle->data); + + if (first_field != nullptr) { + fprintf(stderr, + "\t(First field): %p %s\n", + first_field, + sym_ctx->LookupSymbol(first_field).Display().c_str()); + } + }, + sym_ctx.get()); fflush(stderr); // Finally, abort. diff --git a/src/debug_utils.h b/src/debug_utils.h index 2fd9e7dab7f8f4..bb203164dd9906 100644 --- a/src/debug_utils.h +++ b/src/debug_utils.h @@ -3,9 +3,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include #include "async_wrap.h" #include "env.h" -#include // Use FORCE_INLINE on functions that have a debug-category-enabled check first // and then ideally only a single function call following it, to maintain @@ -21,20 +21,16 @@ namespace node { template -inline void FORCE_INLINE Debug(Environment* env, - DebugCategory cat, - const char* format, - Args&&... args) { - if (!UNLIKELY(env->debug_enabled(cat))) - return; +inline void FORCE_INLINE +Debug(Environment* env, DebugCategory cat, const char* format, Args&&... args) { + if (!UNLIKELY(env->debug_enabled(cat))) return; fprintf(stderr, format, std::forward(args)...); } inline void FORCE_INLINE Debug(Environment* env, DebugCategory cat, const char* message) { - if (!UNLIKELY(env->debug_enabled(cat))) - return; + if (!UNLIKELY(env->debug_enabled(cat))) return; fprintf(stderr, "%s", message); } @@ -70,10 +66,8 @@ inline void FORCE_INLINE Debug(AsyncWrap* async_wrap, #ifdef DEBUG CHECK_NOT_NULL(async_wrap); #endif - DebugCategory cat = - static_cast(async_wrap->provider_type()); - if (!UNLIKELY(async_wrap->env()->debug_enabled(cat))) - return; + DebugCategory cat = static_cast(async_wrap->provider_type()); + if (!UNLIKELY(async_wrap->env()->debug_enabled(cat))) return; UnconditionalAsyncWrapDebug(async_wrap, format, std::forward(args)...); } @@ -98,7 +92,7 @@ class NativeSymbolDebuggingContext { }; virtual ~NativeSymbolDebuggingContext() {} - virtual SymbolInfo LookupSymbol(void* address) { return { "", "" }; } + virtual SymbolInfo LookupSymbol(void* address) { return {"", ""}; } virtual bool IsMapped(void* address) { return false; } virtual int GetStackTrace(void** frames, int count) { return 0; } }; diff --git a/src/env-inl.h b/src/env-inl.h index a294066bb5aa0d..33f17541c20c2c 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -27,13 +27,13 @@ #include "aliased_buffer.h" #include "env.h" #include "node.h" +#include "node_context_data.h" +#include "node_perf_common.h" +#include "node_worker.h" +#include "tracing/agent.h" #include "util-inl.h" #include "uv.h" #include "v8.h" -#include "node_perf_common.h" -#include "node_context_data.h" -#include "tracing/agent.h" -#include "node_worker.h" #include #include @@ -82,14 +82,14 @@ inline Environment::AsyncHooks::AsyncHooks() // Create all the provider strings that will be passed to JS. Place them in // an array so the array index matches the PROVIDER id offset. This way the // strings can be retrieved quickly. -#define V(Provider) \ - providers_[AsyncWrap::PROVIDER_ ## Provider].Set( \ - env()->isolate(), \ - v8::String::NewFromOneByte( \ - env()->isolate(), \ - reinterpret_cast(#Provider), \ - v8::NewStringType::kInternalized, \ - sizeof(#Provider) - 1).ToLocalChecked()); +#define V(Provider) \ + providers_[AsyncWrap::PROVIDER_##Provider].Set( \ + env()->isolate(), \ + v8::String::NewFromOneByte(env()->isolate(), \ + reinterpret_cast(#Provider), \ + v8::NewStringType::kInternalized, \ + sizeof(#Provider) - 1) \ + .ToLocalChecked()); NODE_ASYNC_PROVIDER_TYPES(V) #undef V } @@ -132,8 +132,7 @@ inline void Environment::AsyncHooks::push_async_ids(double async_id, } uint32_t offset = fields_[kStackLength]; - if (offset * 2 >= async_ids_stack_.Length()) - grow_async_ids_stack(); + if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack(); async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId]; async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId]; fields_[kStackLength] += 1; @@ -159,8 +158,7 @@ inline bool Environment::AsyncHooks::pop_async_id(double async_id) { async_id); DumpBacktrace(stderr); fflush(stderr); - if (!env()->abort_on_uncaught_exception()) - exit(1); + if (!env()->abort_on_uncaught_exception()) exit(1); fprintf(stderr, "\n"); fflush(stderr); ABORT_NO_BACKTRACE(); @@ -184,8 +182,8 @@ inline void Environment::AsyncHooks::clear_async_id_stack() { // The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in // async_wrap-inl.h to avoid a circular dependency. -inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope - ::DefaultTriggerAsyncIdScope(Environment* env, +inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope :: + DefaultTriggerAsyncIdScope(Environment* env, double default_trigger_async_id) : async_id_fields_ref_(env->async_hooks()->async_id_fields()) { if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) { @@ -193,23 +191,21 @@ inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope } old_default_trigger_async_id_ = - async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId]; + async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId]; async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId] = - default_trigger_async_id; + default_trigger_async_id; } -inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope - ::~DefaultTriggerAsyncIdScope() { +inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope :: + ~DefaultTriggerAsyncIdScope() { async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId] = - old_default_trigger_async_id_; + old_default_trigger_async_id_; } - Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) { return ContainerOf(&Environment::async_hooks_, hooks); } - inline Environment::AsyncCallbackScope::AsyncCallbackScope(Environment* env) : env_(env) { env_->makecallback_cntr_++; @@ -227,7 +223,7 @@ inline Environment::ImmediateInfo::ImmediateInfo(v8::Isolate* isolate) : fields_(isolate, kFieldsCount) {} inline AliasedBuffer& - Environment::ImmediateInfo::fields() { +Environment::ImmediateInfo::fields() { return fields_; } @@ -280,11 +276,11 @@ inline void Environment::TickInfo::promise_rejections_toggle_on() { inline void Environment::AssignToContext(v8::Local context, const ContextInfo& info) { - context->SetAlignedPointerInEmbedderData( - ContextEmbedderIndex::kEnvironment, this); + context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment, + this); // Used by EnvPromiseHook to know that we are on a node context. - context->SetAlignedPointerInEmbedderData( - ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr); + context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag, + Environment::kNodeContextTagPtr); #if HAVE_INSPECTOR inspector_agent()->ContextCreated(context, info); #endif // HAVE_INSPECTOR @@ -295,9 +291,8 @@ inline Environment* Environment::GetCurrent(v8::Isolate* isolate) { } inline Environment* Environment::GetCurrent(v8::Local context) { - return static_cast( - context->GetAlignedPointerFromEmbedderData( - ContextEmbedderIndex::kEnvironment)); + return static_cast(context->GetAlignedPointerFromEmbedderData( + ContextEmbedderIndex::kEnvironment)); } inline Environment* Environment::GetCurrent( @@ -370,9 +365,9 @@ inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) { OnCloseCallback callback; void* original_data; }; - handle->data = new CloseData { this, callback, handle->data }; + handle->data = new CloseData{this, callback, handle->data}; uv_close(reinterpret_cast(handle), [](uv_handle_t* handle) { - std::unique_ptr data { static_cast(handle->data) }; + std::unique_ptr data{static_cast(handle->data)}; data->env->handle_cleanup_waiting_--; handle->data = data->original_data; data->callback(reinterpret_cast(handle)); @@ -473,7 +468,7 @@ inline double Environment::trigger_async_id() { inline double Environment::get_default_trigger_async_id() { double default_trigger_async_id = - async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId]; + async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId]; // If defaultTriggerAsyncId isn't set, use the executionAsyncId if (default_trigger_async_id < 0) default_trigger_async_id = execution_async_id(); @@ -564,13 +559,12 @@ void Environment::CreateImmediate(native_immediate_callback cb, void* data, v8::Local obj, bool ref) { - native_immediate_callbacks_.push_back({ - cb, - data, - std::unique_ptr>(obj.IsEmpty() ? - nullptr : new Persistent(isolate_, obj)), - ref - }); + native_immediate_callbacks_.push_back( + {cb, + data, + std::unique_ptr>( + obj.IsEmpty() ? nullptr : new Persistent(isolate_, obj)), + ref}); immediate_info()->count_inc(1); } @@ -579,8 +573,7 @@ void Environment::SetImmediate(native_immediate_callback cb, v8::Local obj) { CreateImmediate(cb, data, obj, true); - if (immediate_info()->ref_count() == 0) - ToggleImmediateRef(true); + if (immediate_info()->ref_count() == 0) ToggleImmediateRef(true); immediate_info()->ref_count_inc(1); } @@ -637,7 +630,7 @@ inline performance::performance_state* Environment::performance_state() { } inline std::unordered_map* - Environment::performance_marks() { +Environment::performance_marks() { return &performance_marks_; } @@ -658,8 +651,7 @@ inline void Environment::ThrowRangeError(const char* errmsg) { } inline void Environment::ThrowError( - v8::Local (*fun)(v8::Local), - const char* errmsg) { + v8::Local (*fun)(v8::Local), const char* errmsg) { v8::HandleScope handle_scope(isolate()); isolate()->ThrowException(fun(OneByteString(isolate(), errmsg))); } @@ -681,14 +673,14 @@ inline void Environment::ThrowUVException(int errorno, UVException(isolate(), errorno, syscall, message, path, dest)); } -inline v8::Local - Environment::NewFunctionTemplate(v8::FunctionCallback callback, - v8::Local signature, - v8::ConstructorBehavior behavior, - v8::SideEffectType side_effect_type) { +inline v8::Local Environment::NewFunctionTemplate( + v8::FunctionCallback callback, + v8::Local signature, + v8::ConstructorBehavior behavior, + v8::SideEffectType side_effect_type) { v8::Local external = as_external(); - return v8::FunctionTemplate::New(isolate(), callback, external, - signature, 0, behavior, side_effect_type); + return v8::FunctionTemplate::New( + isolate(), callback, external, signature, 0, behavior, side_effect_type); } inline void Environment::SetMethod(v8::Local that, @@ -700,7 +692,8 @@ inline void Environment::SetMethod(v8::Local that, // TODO(TimothyGu): Investigate if SetMethod is ever // used for constructors. v8::ConstructorBehavior::kAllow, - v8::SideEffectType::kHasSideEffect)->GetFunction(); + v8::SideEffectType::kHasSideEffect) + ->GetFunction(); // kInternalized strings are created in the old space. const v8::NewStringType type = v8::NewStringType::kInternalized; v8::Local name_string = @@ -718,7 +711,8 @@ inline void Environment::SetMethodNoSideEffect(v8::Local that, // TODO(TimothyGu): Investigate if SetMethod is ever // used for constructors. v8::ConstructorBehavior::kAllow, - v8::SideEffectType::kHasNoSideEffect)->GetFunction(); + v8::SideEffectType::kHasNoSideEffect) + ->GetFunction(); // kInternalized strings are created in the old space. const v8::NewStringType type = v8::NewStringType::kInternalized; v8::Local name_string = @@ -732,7 +726,9 @@ inline void Environment::SetProtoMethod(v8::Local that, v8::FunctionCallback callback) { v8::Local signature = v8::Signature::New(isolate(), that); v8::Local t = - NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow, + NewFunctionTemplate(callback, + signature, + v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasSideEffect); // kInternalized strings are created in the old space. const v8::NewStringType type = v8::NewStringType::kInternalized; @@ -748,7 +744,9 @@ inline void Environment::SetProtoMethodNoSideEffect( v8::FunctionCallback callback) { v8::Local signature = v8::Signature::New(isolate(), that); v8::Local t = - NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow, + NewFunctionTemplate(callback, + signature, + v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect); // kInternalized strings are created in the old space. const v8::NewStringType type = v8::NewStringType::kInternalized; @@ -762,7 +760,8 @@ inline void Environment::SetTemplateMethod(v8::Local that, const char* name, v8::FunctionCallback callback) { v8::Local t = - NewFunctionTemplate(callback, v8::Local(), + NewFunctionTemplate(callback, + v8::Local(), v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasSideEffect); // kInternalized strings are created in the old space. @@ -778,7 +777,8 @@ inline void Environment::SetTemplateMethodNoSideEffect( const char* name, v8::FunctionCallback callback) { v8::Local t = - NewFunctionTemplate(callback, v8::Local(), + NewFunctionTemplate(callback, + v8::Local(), v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasNoSideEffect); // kInternalized strings are created in the old space. @@ -790,15 +790,14 @@ inline void Environment::SetTemplateMethodNoSideEffect( } void Environment::AddCleanupHook(void (*fn)(void*), void* arg) { - auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback { - fn, arg, cleanup_hook_counter_++ - }); + auto insertion_info = cleanup_hooks_.emplace( + CleanupHookCallback{fn, arg, cleanup_hook_counter_++}); // Make sure there was no existing element with these values. CHECK_EQ(insertion_info.second, true); } void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) { - CleanupHookCallback search { fn, arg, 0 }; + CleanupHookCallback search{fn, arg, 0}; cleanup_hooks_.erase(search); } @@ -823,23 +822,22 @@ template void Environment::ForEachBaseObject(T&& iterator) { for (const auto& hook : cleanup_hooks_) { BaseObject* obj = hook.GetBaseObject(); - if (obj != nullptr) - iterator(obj); + if (obj != nullptr) iterator(obj); } } #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) #define VS(PropertyName, StringValue) V(v8::String, PropertyName) -#define V(TypeName, PropertyName) \ - inline \ - v8::Local IsolateData::PropertyName(v8::Isolate* isolate) const { \ - /* Strings are immutable so casting away const-ness here is okay. */ \ - return const_cast(this)->PropertyName ## _.Get(isolate); \ +#define V(TypeName, PropertyName) \ + inline v8::Local IsolateData::PropertyName(v8::Isolate* isolate) \ + const { \ + /* Strings are immutable so casting away const-ness here is okay. */ \ + return const_cast(this)->PropertyName##_.Get(isolate); \ } - PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) - PER_ISOLATE_SYMBOL_PROPERTIES(VY) - PER_ISOLATE_STRING_PROPERTIES(VS) +PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) +PER_ISOLATE_SYMBOL_PROPERTIES(VY) +PER_ISOLATE_STRING_PROPERTIES(VS) #undef V #undef VS #undef VY @@ -848,26 +846,26 @@ void Environment::ForEachBaseObject(T&& iterator) { #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) #define VS(PropertyName, StringValue) V(v8::String, PropertyName) -#define V(TypeName, PropertyName) \ - inline v8::Local Environment::PropertyName() const { \ - return isolate_data()->PropertyName(isolate()); \ +#define V(TypeName, PropertyName) \ + inline v8::Local Environment::PropertyName() const { \ + return isolate_data()->PropertyName(isolate()); \ } - PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) - PER_ISOLATE_SYMBOL_PROPERTIES(VY) - PER_ISOLATE_STRING_PROPERTIES(VS) +PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) +PER_ISOLATE_SYMBOL_PROPERTIES(VY) +PER_ISOLATE_STRING_PROPERTIES(VS) #undef V #undef VS #undef VY #undef VP -#define V(PropertyName, TypeName) \ - inline v8::Local Environment::PropertyName() const { \ - return StrongPersistentToLocal(PropertyName ## _); \ - } \ - inline void Environment::set_ ## PropertyName(v8::Local value) { \ - PropertyName ## _.Reset(isolate(), value); \ +#define V(PropertyName, TypeName) \ + inline v8::Local Environment::PropertyName() const { \ + return StrongPersistentToLocal(PropertyName##_); \ + } \ + inline void Environment::set_##PropertyName(v8::Local value) { \ + PropertyName##_.Reset(isolate(), value); \ } - ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) +ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) #undef V } // namespace node diff --git a/src/env.cc b/src/env.cc index 769676275b25f0..980459ed56c4c6 100644 --- a/src/env.cc +++ b/src/env.cc @@ -1,12 +1,12 @@ -#include "node_internals.h" #include "async_wrap.h" -#include "v8-profiler.h" #include "node_buffer.h" -#include "node_platform.h" -#include "node_file.h" #include "node_context_data.h" +#include "node_file.h" +#include "node_internals.h" +#include "node_platform.h" #include "node_worker.h" #include "tracing/agent.h" +#include "v8-profiler.h" #include #include @@ -32,73 +32,70 @@ using v8::Value; using worker::Worker; int const Environment::kNodeContextTag = 0x6e6f64; -void* Environment::kNodeContextTagPtr = const_cast( - static_cast(&Environment::kNodeContextTag)); +void* Environment::kNodeContextTagPtr = + const_cast(static_cast(&Environment::kNodeContextTag)); IsolateData::IsolateData(Isolate* isolate, uv_loop_t* event_loop, MultiIsolatePlatform* platform, - uint32_t* zero_fill_field) : - isolate_(isolate), - event_loop_(event_loop), - zero_fill_field_(zero_fill_field), - platform_(platform) { - if (platform_ != nullptr) - platform_->RegisterIsolate(this, event_loop); - - // Create string and private symbol properties as internalized one byte - // strings after the platform is properly initialized. - // - // Internalized because it makes property lookups a little faster and - // because the string is created in the old space straight away. It's going - // to end up in the old space sooner or later anyway but now it doesn't go - // through v8::Eternal's new space handling first. - // - // One byte because our strings are ASCII and we can safely skip V8's UTF-8 - // decoding step. - -#define V(PropertyName, StringValue) \ - PropertyName ## _.Set( \ - isolate, \ - Private::New( \ - isolate, \ - String::NewFromOneByte( \ - isolate, \ - reinterpret_cast(StringValue), \ - v8::NewStringType::kInternalized, \ - sizeof(StringValue) - 1).ToLocalChecked())); + uint32_t* zero_fill_field) + : isolate_(isolate), + event_loop_(event_loop), + zero_fill_field_(zero_fill_field), + platform_(platform) { + if (platform_ != nullptr) platform_->RegisterIsolate(this, event_loop); + + // Create string and private symbol properties as internalized one byte + // strings after the platform is properly initialized. + // + // Internalized because it makes property lookups a little faster and + // because the string is created in the old space straight away. It's going + // to end up in the old space sooner or later anyway but now it doesn't go + // through v8::Eternal's new space handling first. + // + // One byte because our strings are ASCII and we can safely skip V8's UTF-8 + // decoding step. + +#define V(PropertyName, StringValue) \ + PropertyName##_.Set( \ + isolate, \ + Private::New(isolate, \ + String::NewFromOneByte( \ + isolate, \ + reinterpret_cast(StringValue), \ + v8::NewStringType::kInternalized, \ + sizeof(StringValue) - 1) \ + .ToLocalChecked())); PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) #undef V -#define V(PropertyName, StringValue) \ - PropertyName ## _.Set( \ - isolate, \ - Symbol::New( \ - isolate, \ - String::NewFromOneByte( \ - isolate, \ - reinterpret_cast(StringValue), \ - v8::NewStringType::kInternalized, \ - sizeof(StringValue) - 1).ToLocalChecked())); +#define V(PropertyName, StringValue) \ + PropertyName##_.Set( \ + isolate, \ + Symbol::New(isolate, \ + String::NewFromOneByte( \ + isolate, \ + reinterpret_cast(StringValue), \ + v8::NewStringType::kInternalized, \ + sizeof(StringValue) - 1) \ + .ToLocalChecked())); PER_ISOLATE_SYMBOL_PROPERTIES(V) #undef V -#define V(PropertyName, StringValue) \ - PropertyName ## _.Set( \ - isolate, \ - String::NewFromOneByte( \ - isolate, \ - reinterpret_cast(StringValue), \ - v8::NewStringType::kInternalized, \ - sizeof(StringValue) - 1).ToLocalChecked()); +#define V(PropertyName, StringValue) \ + PropertyName##_.Set( \ + isolate, \ + String::NewFromOneByte(isolate, \ + reinterpret_cast(StringValue), \ + v8::NewStringType::kInternalized, \ + sizeof(StringValue) - 1) \ + .ToLocalChecked()); PER_ISOLATE_STRING_PROPERTIES(V) #undef V } IsolateData::~IsolateData() { - if (platform_ != nullptr) - platform_->UnregisterIsolate(this); + if (platform_ != nullptr) platform_->UnregisterIsolate(this); } - void InitThreadLocalOnce() { CHECK_EQ(0, uv_key_create(&Environment::thread_local_env)); } @@ -134,14 +131,11 @@ Environment::Environment(IsolateData* isolate_data, destroy_async_id_list_.reserve(512); performance_state_.reset(new performance::performance_state(isolate())); - performance_state_->Mark( - performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT); - performance_state_->Mark( - performance::NODE_PERFORMANCE_MILESTONE_NODE_START, - performance::performance_node_start); - performance_state_->Mark( - performance::NODE_PERFORMANCE_MILESTONE_V8_START, - performance::performance_v8_start); + performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT); + performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START, + performance::performance_node_start); + performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START, + performance::performance_v8_start); // By default, always abort when --abort-on-uncaught-exception was passed. should_abort_on_uncaught_toggle_[0] = 1; @@ -170,8 +164,8 @@ Environment::~Environment() { inspector_agent_.reset(); #endif - context()->SetAlignedPointerInEmbedderData( - ContextEmbedderIndex::kEnvironment, nullptr); + context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment, + nullptr); delete[] heap_statistics_buffer_; delete[] heap_space_statistics_buffer_; @@ -235,48 +229,41 @@ void Environment::Start(int argc, } void Environment::RegisterHandleCleanups() { - HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle, - void* arg) { - handle->data = env; + HandleCleanupCb close_and_finish = + [](Environment* env, uv_handle_t* handle, void* arg) { + handle->data = env; - env->CloseHandle(handle, [](uv_handle_t* handle) {}); - }; + env->CloseHandle(handle, [](uv_handle_t* handle) {}); + }; - RegisterHandleCleanup( - reinterpret_cast(timer_handle()), - close_and_finish, - nullptr); + RegisterHandleCleanup(reinterpret_cast(timer_handle()), + close_and_finish, + nullptr); RegisterHandleCleanup( reinterpret_cast(immediate_check_handle()), close_and_finish, nullptr); - RegisterHandleCleanup( - reinterpret_cast(immediate_idle_handle()), - close_and_finish, - nullptr); - RegisterHandleCleanup( - reinterpret_cast(&idle_prepare_handle_), - close_and_finish, - nullptr); - RegisterHandleCleanup( - reinterpret_cast(&idle_check_handle_), - close_and_finish, - nullptr); + RegisterHandleCleanup(reinterpret_cast(immediate_idle_handle()), + close_and_finish, + nullptr); + RegisterHandleCleanup(reinterpret_cast(&idle_prepare_handle_), + close_and_finish, + nullptr); + RegisterHandleCleanup(reinterpret_cast(&idle_check_handle_), + close_and_finish, + nullptr); } void Environment::CleanupHandles() { - for (ReqWrap* request : req_wrap_queue_) - request->Cancel(); + for (ReqWrap* request : req_wrap_queue_) request->Cancel(); - for (HandleWrap* handle : handle_wrap_queue_) - handle->Close(); + for (HandleWrap* handle : handle_wrap_queue_) handle->Close(); for (HandleCleanup& hc : handle_cleanup_queue_) hc.cb_(this, hc.handle_, hc.arg_); handle_cleanup_queue_.clear(); - while (handle_cleanup_waiting_ != 0 || - request_waiting_ != 0 || + while (handle_cleanup_waiting_ != 0 || request_waiting_ != 0 || !handle_wrap_queue_.IsEmpty()) { uv_run(event_loop(), UV_RUN_ONCE); } @@ -285,8 +272,7 @@ void Environment::CleanupHandles() { } void Environment::StartProfilerIdleNotifier() { - if (profiler_idle_notifier_started_) - return; + if (profiler_idle_notifier_started_) return; profiler_idle_notifier_started_ = true; @@ -308,15 +294,14 @@ void Environment::StopProfilerIdleNotifier() { } void Environment::PrintSyncTrace() const { - if (!trace_sync_io_) - return; + if (!trace_sync_io_) return; HandleScope handle_scope(isolate()); Local stack = StackTrace::CurrentStackTrace(isolate(), 10, StackTrace::kDetailed); - fprintf(stderr, "(node:%d) WARNING: Detected use of sync API\n", - uv_os_getpid()); + fprintf( + stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid()); for (int i = 0; i < stack->GetFrameCount() - 1; i++) { Local stack_frame = stack->GetFrame(i); @@ -357,17 +342,18 @@ void Environment::RunCleanup() { while (!cleanup_hooks_.empty()) { // Copy into a vector, since we can't sort an unordered_set in-place. - std::vector callbacks( - cleanup_hooks_.begin(), cleanup_hooks_.end()); + std::vector callbacks(cleanup_hooks_.begin(), + cleanup_hooks_.end()); // We can't erase the copied elements from `cleanup_hooks_` yet, because we // need to be able to check whether they were un-scheduled by another hook. - std::sort(callbacks.begin(), callbacks.end(), + std::sort(callbacks.begin(), + callbacks.end(), [](const CleanupHookCallback& a, const CleanupHookCallback& b) { - // Sort in descending order so that the most recently inserted callbacks - // are run first. - return a.insertion_order_counter_ > b.insertion_order_counter_; - }); + // Sort in descending order so that the most recently inserted + // callbacks are run first. + return a.insertion_order_counter_ > b.insertion_order_counter_; + }); for (const CleanupHookCallback& cb : callbacks) { if (cleanup_hooks_.count(cb) == 0) { @@ -406,11 +392,11 @@ void Environment::AtExit(void (*cb)(void* arg), void* arg) { } void Environment::AddPromiseHook(promise_hook_func fn, void* arg) { - auto it = std::find_if( - promise_hooks_.begin(), promise_hooks_.end(), - [&](const PromiseHookCallback& hook) { - return hook.cb_ == fn && hook.arg_ == arg; - }); + auto it = std::find_if(promise_hooks_.begin(), + promise_hooks_.end(), + [&](const PromiseHookCallback& hook) { + return hook.cb_ == fn && hook.arg_ == arg; + }); if (it != promise_hooks_.end()) { it->enable_count_++; return; @@ -423,11 +409,11 @@ void Environment::AddPromiseHook(promise_hook_func fn, void* arg) { } bool Environment::RemovePromiseHook(promise_hook_func fn, void* arg) { - auto it = std::find_if( - promise_hooks_.begin(), promise_hooks_.end(), - [&](const PromiseHookCallback& hook) { - return hook.cb_ == fn && hook.arg_ == arg; - }); + auto it = std::find_if(promise_hooks_.begin(), + promise_hooks_.end(), + [&](const PromiseHookCallback& hook) { + return hook.cb_ == fn && hook.arg_ == arg; + }); if (it == promise_hooks_.end()) return false; @@ -450,8 +436,8 @@ void Environment::EnvPromiseHook(v8::PromiseHookType type, // when reading the magic number. context->SetAlignedPointerInEmbedderData( ContextEmbedderIndex::kContextTagBoundary, nullptr); - int* magicNumberPtr = reinterpret_cast( - context->GetAlignedPointerFromEmbedderData( + int* magicNumberPtr = + reinterpret_cast(context->GetAlignedPointerFromEmbedderData( ContextEmbedderIndex::kContextTag)); if (magicNumberPtr != Environment::kNodeContextTagPtr) { return; @@ -476,11 +462,9 @@ void Environment::RunAndClearNativeImmediates() { v8::SealHandleScope seal_handle_scope(isolate()); #endif it->cb_(this, it->data_); - if (it->refed_) - ref_count++; + if (it->refed_) ref_count++; if (UNLIKELY(try_catch.HasCaught())) { - if (!try_catch.HasTerminated()) - FatalException(isolate(), try_catch); + if (!try_catch.HasTerminated()) FatalException(isolate(), try_catch); // Bail out, remove the already executed callbacks from list // and set up a new TryCatch for the other pending callbacks. @@ -491,7 +475,8 @@ void Environment::RunAndClearNativeImmediates() { } return false; }; - while (drain_list()) {} + while (drain_list()) { + } #ifdef DEBUG CHECK_GE(immediate_info()->count(), count); @@ -501,7 +486,6 @@ void Environment::RunAndClearNativeImmediates() { } } - void Environment::ScheduleTimer(int64_t duration_ms) { uv_timer_start(timer_handle(), RunTimers, duration_ms, 0); } @@ -517,8 +501,7 @@ void Environment::ToggleTimerRef(bool ref) { void Environment::RunTimers(uv_timer_t* handle) { Environment* env = Environment::from_timer_handle(handle); - if (!env->can_call_into_js()) - return; + if (!env->can_call_into_js()) return; HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); @@ -543,8 +526,7 @@ void Environment::RunTimers(uv_timer_t* handle) { // code becomes invalid and needs to be rewritten. Otherwise catastrophic // timers corruption will occurr and all timers behaviour will become // entirely unpredictable. - if (ret.IsEmpty()) - return; + if (ret.IsEmpty()) return; // To allow for less JS-C++ boundary crossing, the value returned from JS // serves a few purposes: @@ -573,20 +555,17 @@ void Environment::RunTimers(uv_timer_t* handle) { } } - void Environment::CheckImmediate(uv_check_t* handle) { Environment* env = Environment::from_immediate_check_handle(handle); - if (env->immediate_info()->count() == 0) - return; + if (env->immediate_info()->count() == 0) return; HandleScope scope(env->isolate()); Context::Scope context_scope(env->context()); env->RunAndClearNativeImmediates(); - if (!env->can_call_into_js()) - return; + if (!env->can_call_into_js()) return; do { MakeCallback(env->isolate(), @@ -594,23 +573,22 @@ void Environment::CheckImmediate(uv_check_t* handle) { env->immediate_callback_function(), 0, nullptr, - {0, 0}).ToLocalChecked(); + {0, 0}) + .ToLocalChecked(); } while (env->immediate_info()->has_outstanding() && env->can_call_into_js()); - if (env->immediate_info()->ref_count() == 0) - env->ToggleImmediateRef(false); + if (env->immediate_info()->ref_count() == 0) env->ToggleImmediateRef(false); } void Environment::ToggleImmediateRef(bool ref) { if (ref) { // Idle handle is needed only to stop the event loop from blocking in poll. - uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ }); + uv_idle_start(immediate_idle_handle(), [](uv_idle_t*) {}); } else { uv_idle_stop(immediate_idle_handle()); } } - Local Environment::GetNow() { uv_update_time(event_loop()); uint64_t now = uv_now(event_loop()); @@ -622,24 +600,22 @@ Local Environment::GetNow() { return Number::New(isolate(), static_cast(now)); } - void Environment::set_debug_categories(const std::string& cats, bool enabled) { std::string debug_categories = cats; while (!debug_categories.empty()) { std::string::size_type comma_pos = debug_categories.find(','); std::string wanted = ToLower(debug_categories.substr(0, comma_pos)); -#define V(name) \ - { \ - static const std::string available_category = ToLower(#name); \ - if (available_category.find(wanted) != std::string::npos) \ - set_debug_enabled(DebugCategory::name, enabled); \ - } +#define V(name) \ + { \ + static const std::string available_category = ToLower(#name); \ + if (available_category.find(wanted) != std::string::npos) \ + set_debug_enabled(DebugCategory::name, enabled); \ + } DEBUG_CATEGORY_NAMES(V) - if (comma_pos == std::string::npos) - break; + if (comma_pos == std::string::npos) break; // Use everything after the `,` as the list for the next iteration. debug_categories = debug_categories.substr(comma_pos + 1); } @@ -655,31 +631,37 @@ void CollectExceptionInfo(Environment* env, const char* dest) { obj->Set(env->errno_string(), v8::Integer::New(env->isolate(), errorno)); - obj->Set(env->context(), env->code_string(), - OneByteString(env->isolate(), err_string)).FromJust(); + obj->Set(env->context(), + env->code_string(), + OneByteString(env->isolate(), err_string)) + .FromJust(); if (message != nullptr) { - obj->Set(env->context(), env->message_string(), - OneByteString(env->isolate(), message)).FromJust(); + obj->Set(env->context(), + env->message_string(), + OneByteString(env->isolate(), message)) + .FromJust(); } v8::Local path_buffer; if (path != nullptr) { path_buffer = - Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked(); + Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked(); obj->Set(env->context(), env->path_string(), path_buffer).FromJust(); } v8::Local dest_buffer; if (dest != nullptr) { dest_buffer = - Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked(); + Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked(); obj->Set(env->context(), env->dest_string(), dest_buffer).FromJust(); } if (syscall != nullptr) { - obj->Set(env->context(), env->syscall_string(), - OneByteString(env->isolate(), syscall)).FromJust(); + obj->Set(env->context(), + env->syscall_string(), + OneByteString(env->isolate(), syscall)) + .FromJust(); } } @@ -688,8 +670,7 @@ void Environment::CollectExceptionInfo(v8::Local object, const char* syscall, const char* message, const char* path) { - if (!object->IsObject() || errorno == 0) - return; + if (!object->IsObject() || errorno == 0) return; v8::Local obj = object.As(); const char* err_string = node::errno_string(errorno); @@ -698,8 +679,8 @@ void Environment::CollectExceptionInfo(v8::Local object, message = strerror(errorno); } - node::CollectExceptionInfo(this, obj, errorno, err_string, - syscall, message, path, nullptr); + node::CollectExceptionInfo( + this, obj, errorno, err_string, syscall, message, path, nullptr); } void Environment::CollectUVExceptionInfo(v8::Local object, @@ -708,8 +689,7 @@ void Environment::CollectUVExceptionInfo(v8::Local object, const char* message, const char* path, const char* dest) { - if (!object->IsObject() || errorno == 0) - return; + if (!object->IsObject() || errorno == 0) return; v8::Local obj = object.As(); const char* err_string = uv_err_name(errorno); @@ -718,25 +698,26 @@ void Environment::CollectUVExceptionInfo(v8::Local object, message = uv_strerror(errorno); } - node::CollectExceptionInfo(this, obj, errorno, err_string, - syscall, message, path, dest); + node::CollectExceptionInfo( + this, obj, errorno, err_string, syscall, message, path, dest); } - void Environment::AsyncHooks::grow_async_ids_stack() { const uint32_t old_capacity = async_ids_stack_.Length() / 2; const uint32_t new_capacity = old_capacity * 1.5; - AliasedBuffer new_buffer( - env()->isolate(), new_capacity * 2); + AliasedBuffer new_buffer(env()->isolate(), + new_capacity * 2); for (uint32_t i = 0; i < old_capacity * 2; ++i) new_buffer[i] = async_ids_stack_[i]; async_ids_stack_ = std::move(new_buffer); - env()->async_hooks_binding()->Set( - env()->context(), - env()->async_ids_stack_string(), - async_ids_stack_.GetJSArray()).FromJust(); + env() + ->async_hooks_binding() + ->Set(env()->context(), + env()->async_ids_stack_string(), + async_ids_stack_.GetJSArray()) + .FromJust(); } uv_key_t Environment::thread_local_env = {}; @@ -761,12 +742,10 @@ void Environment::BuildEmbedderGraph(v8::Isolate* isolate, v8::EmbedderGraph* graph, void* data) { MemoryTracker tracker(isolate, graph); - static_cast(data)->ForEachBaseObject([&](BaseObject* obj) { - tracker.Track(obj); - }); + static_cast(data)->ForEachBaseObject( + [&](BaseObject* obj) { tracker.Track(obj); }); } - // Not really any better place than env.cc at this moment. void BaseObject::DeleteMe(void* data) { BaseObject* self = static_cast(data); diff --git a/src/env.h b/src/env.h index acbdd013285d6c..e309db2ddb3239 100644 --- a/src/env.h +++ b/src/env.h @@ -29,19 +29,19 @@ #include "inspector_agent.h" #endif #include "handle_wrap.h" +#include "node.h" +#include "node_http2_state.h" #include "req_wrap.h" +#include "tracing/agent.h" #include "util.h" #include "uv.h" #include "v8.h" -#include "node.h" -#include "node_http2_state.h" -#include "tracing/agent.h" -#include #include -#include +#include #include #include +#include struct nghttp2_rcbuf; @@ -102,269 +102,270 @@ struct PackageConfig { // Private symbols are per-isolate primitives but Environment proxies them // for the sake of convenience. Strings should be ASCII-only and have a // "node:" prefix to avoid name clashes with third-party code. -#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) \ - V(alpn_buffer_private_symbol, "node:alpnBuffer") \ - V(arrow_message_private_symbol, "node:arrowMessage") \ - V(contextify_context_private_symbol, "node:contextify:context") \ - V(contextify_global_private_symbol, "node:contextify:global") \ - V(decorated_private_symbol, "node:decorated") \ - V(napi_env, "node:napi:env") \ - V(napi_wrapper, "node:napi:wrapper") \ - V(sab_lifetimepartner_symbol, "node:sharedArrayBufferLifetimePartner") \ +#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) \ + V(alpn_buffer_private_symbol, "node:alpnBuffer") \ + V(arrow_message_private_symbol, "node:arrowMessage") \ + V(contextify_context_private_symbol, "node:contextify:context") \ + V(contextify_global_private_symbol, "node:contextify:global") \ + V(decorated_private_symbol, "node:decorated") \ + V(napi_env, "node:napi:env") \ + V(napi_wrapper, "node:napi:wrapper") \ + V(sab_lifetimepartner_symbol, "node:sharedArrayBufferLifetimePartner") // Symbols are per-isolate primitives but Environment proxies them // for the sake of convenience. -#define PER_ISOLATE_SYMBOL_PROPERTIES(V) \ - V(handle_onclose_symbol, "handle_onclose") \ +#define PER_ISOLATE_SYMBOL_PROPERTIES(V) \ + V(handle_onclose_symbol, "handle_onclose") // Strings are per-isolate primitives but Environment proxies them // for the sake of convenience. Strings should be ASCII-only. -#define PER_ISOLATE_STRING_PROPERTIES(V) \ - V(address_string, "address") \ - V(args_string, "args") \ - V(async, "async") \ - V(async_ids_stack_string, "async_ids_stack") \ - V(buffer_string, "buffer") \ - V(bytes_string, "bytes") \ - V(bytes_parsed_string, "bytesParsed") \ - V(bytes_read_string, "bytesRead") \ - V(bytes_written_string, "bytesWritten") \ - V(cached_data_string, "cachedData") \ - V(cached_data_produced_string, "cachedDataProduced") \ - V(cached_data_rejected_string, "cachedDataRejected") \ - V(change_string, "change") \ - V(channel_string, "channel") \ - V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite") \ - V(constants_string, "constants") \ - V(oncertcb_string, "oncertcb") \ - V(code_string, "code") \ - V(cwd_string, "cwd") \ - V(dest_string, "dest") \ - V(destroyed_string, "destroyed") \ - V(detached_string, "detached") \ - V(dns_a_string, "A") \ - V(dns_aaaa_string, "AAAA") \ - V(dns_cname_string, "CNAME") \ - V(dns_mx_string, "MX") \ - V(dns_naptr_string, "NAPTR") \ - V(dns_ns_string, "NS") \ - V(dns_ptr_string, "PTR") \ - V(dns_soa_string, "SOA") \ - V(dns_srv_string, "SRV") \ - V(dns_txt_string, "TXT") \ - V(emit_warning_string, "emitWarning") \ - V(exchange_string, "exchange") \ - V(encoding_string, "encoding") \ - V(enter_string, "enter") \ - V(entries_string, "entries") \ - V(env_pairs_string, "envPairs") \ - V(errno_string, "errno") \ - V(error_string, "error") \ - V(exit_code_string, "exitCode") \ - V(expire_string, "expire") \ - V(exponent_string, "exponent") \ - V(exports_string, "exports") \ - V(ext_key_usage_string, "ext_key_usage") \ - V(external_stream_string, "_externalStream") \ - V(family_string, "family") \ - V(fatal_exception_string, "_fatalException") \ - V(fd_string, "fd") \ - V(file_string, "file") \ - V(fingerprint_string, "fingerprint") \ - V(fingerprint256_string, "fingerprint256") \ - V(flags_string, "flags") \ - V(fragment_string, "fragment") \ - V(get_data_clone_error_string, "_getDataCloneError") \ - V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId") \ - V(gid_string, "gid") \ - V(handle_string, "handle") \ - V(homedir_string, "homedir") \ - V(host_string, "host") \ - V(hostmaster_string, "hostmaster") \ - V(ignore_string, "ignore") \ - V(infoaccess_string, "infoAccess") \ - V(inherit_string, "inherit") \ - V(input_string, "input") \ - V(internal_string, "internal") \ - V(ipv4_string, "IPv4") \ - V(ipv6_string, "IPv6") \ - V(isclosing_string, "isClosing") \ - V(issuer_string, "issuer") \ - V(issuercert_string, "issuerCertificate") \ - V(kill_signal_string, "killSignal") \ - V(mac_string, "mac") \ - V(main_string, "main") \ - V(max_buffer_string, "maxBuffer") \ - V(max_semi_space_size_string, "maxSemiSpaceSize") \ - V(max_old_space_size_string, "maxOldSpaceSize") \ - V(message_string, "message") \ - V(message_port_string, "messagePort") \ - V(message_port_constructor_string, "MessagePort") \ - V(minttl_string, "minttl") \ - V(modulus_string, "modulus") \ - V(name_string, "name") \ - V(netmask_string, "netmask") \ - V(nsname_string, "nsname") \ - V(ocsp_request_string, "OCSPRequest") \ - V(onaltsvc_string, "onaltsvc") \ - V(onchange_string, "onchange") \ - V(onclienthello_string, "onclienthello") \ - V(oncomplete_string, "oncomplete") \ - V(onconnection_string, "onconnection") \ - V(ondone_string, "ondone") \ - V(onerror_string, "onerror") \ - V(onexit_string, "onexit") \ - V(onframeerror_string, "onframeerror") \ - V(ongetpadding_string, "ongetpadding") \ - V(onhandshakedone_string, "onhandshakedone") \ - V(onhandshakestart_string, "onhandshakestart") \ - V(onheaders_string, "onheaders") \ - V(oninit_string, "oninit") \ - V(onmessage_string, "onmessage") \ - V(onnewsession_string, "onnewsession") \ - V(onocspresponse_string, "onocspresponse") \ - V(ongoawaydata_string, "ongoawaydata") \ - V(onpriority_string, "onpriority") \ - V(onread_string, "onread") \ - V(onreadstart_string, "onreadstart") \ - V(onreadstop_string, "onreadstop") \ - V(onsettings_string, "onsettings") \ - V(onshutdown_string, "onshutdown") \ - V(onsignal_string, "onsignal") \ - V(onstop_string, "onstop") \ - V(onstreamclose_string, "onstreamclose") \ - V(ontrailers_string, "ontrailers") \ - V(onunpipe_string, "onunpipe") \ - V(onwrite_string, "onwrite") \ - V(openssl_error_stack, "opensslErrorStack") \ - V(output_string, "output") \ - V(order_string, "order") \ - V(owner_string, "owner") \ - V(parse_error_string, "Parse Error") \ - V(password_string, "password") \ - V(path_string, "path") \ - V(pending_handle_string, "pendingHandle") \ - V(pid_string, "pid") \ - V(pipe_string, "pipe") \ - V(pipe_target_string, "pipeTarget") \ - V(pipe_source_string, "pipeSource") \ - V(port_string, "port") \ - V(port1_string, "port1") \ - V(port2_string, "port2") \ - V(preference_string, "preference") \ - V(priority_string, "priority") \ - V(promise_string, "promise") \ - V(pubkey_string, "pubkey") \ - V(query_string, "query") \ - V(raw_string, "raw") \ - V(read_host_object_string, "_readHostObject") \ - V(readable_string, "readable") \ - V(refresh_string, "refresh") \ - V(regexp_string, "regexp") \ - V(rename_string, "rename") \ - V(replacement_string, "replacement") \ - V(retry_string, "retry") \ - V(scheme_string, "scheme") \ - V(serial_string, "serial") \ - V(scopeid_string, "scopeid") \ - V(serial_number_string, "serialNumber") \ - V(service_string, "service") \ - V(servername_string, "servername") \ - V(session_id_string, "sessionId") \ - V(shell_string, "shell") \ - V(signal_string, "signal") \ - V(sink_string, "sink") \ - V(size_string, "size") \ - V(sni_context_err_string, "Invalid SNI context") \ - V(sni_context_string, "sni_context") \ - V(source_string, "source") \ - V(stack_string, "stack") \ - V(status_string, "status") \ - V(stdio_string, "stdio") \ - V(subject_string, "subject") \ - V(subjectaltname_string, "subjectaltname") \ - V(syscall_string, "syscall") \ - V(thread_id_string, "threadId") \ - V(ticketkeycallback_string, "onticketkeycallback") \ - V(timeout_string, "timeout") \ - V(tls_ticket_string, "tlsTicket") \ - V(ttl_string, "ttl") \ - V(type_string, "type") \ - V(uid_string, "uid") \ - V(unknown_string, "") \ - V(url_string, "url") \ - V(user_string, "user") \ - V(username_string, "username") \ - V(valid_from_string, "valid_from") \ - V(valid_to_string, "valid_to") \ - V(value_string, "value") \ - V(verify_error_string, "verifyError") \ - V(version_string, "version") \ - V(weight_string, "weight") \ - V(windows_hide_string, "windowsHide") \ - V(windows_verbatim_arguments_string, "windowsVerbatimArguments") \ - V(wrap_string, "wrap") \ - V(writable_string, "writable") \ - V(write_host_object_string, "_writeHostObject") \ - V(write_queue_size_string, "writeQueueSize") \ - V(x_forwarded_string, "x-forwarded-for") \ +#define PER_ISOLATE_STRING_PROPERTIES(V) \ + V(address_string, "address") \ + V(args_string, "args") \ + V(async, "async") \ + V(async_ids_stack_string, "async_ids_stack") \ + V(buffer_string, "buffer") \ + V(bytes_string, "bytes") \ + V(bytes_parsed_string, "bytesParsed") \ + V(bytes_read_string, "bytesRead") \ + V(bytes_written_string, "bytesWritten") \ + V(cached_data_string, "cachedData") \ + V(cached_data_produced_string, "cachedDataProduced") \ + V(cached_data_rejected_string, "cachedDataRejected") \ + V(change_string, "change") \ + V(channel_string, "channel") \ + V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite") \ + V(constants_string, "constants") \ + V(oncertcb_string, "oncertcb") \ + V(code_string, "code") \ + V(cwd_string, "cwd") \ + V(dest_string, "dest") \ + V(destroyed_string, "destroyed") \ + V(detached_string, "detached") \ + V(dns_a_string, "A") \ + V(dns_aaaa_string, "AAAA") \ + V(dns_cname_string, "CNAME") \ + V(dns_mx_string, "MX") \ + V(dns_naptr_string, "NAPTR") \ + V(dns_ns_string, "NS") \ + V(dns_ptr_string, "PTR") \ + V(dns_soa_string, "SOA") \ + V(dns_srv_string, "SRV") \ + V(dns_txt_string, "TXT") \ + V(emit_warning_string, "emitWarning") \ + V(exchange_string, "exchange") \ + V(encoding_string, "encoding") \ + V(enter_string, "enter") \ + V(entries_string, "entries") \ + V(env_pairs_string, "envPairs") \ + V(errno_string, "errno") \ + V(error_string, "error") \ + V(exit_code_string, "exitCode") \ + V(expire_string, "expire") \ + V(exponent_string, "exponent") \ + V(exports_string, "exports") \ + V(ext_key_usage_string, "ext_key_usage") \ + V(external_stream_string, "_externalStream") \ + V(family_string, "family") \ + V(fatal_exception_string, "_fatalException") \ + V(fd_string, "fd") \ + V(file_string, "file") \ + V(fingerprint_string, "fingerprint") \ + V(fingerprint256_string, "fingerprint256") \ + V(flags_string, "flags") \ + V(fragment_string, "fragment") \ + V(get_data_clone_error_string, "_getDataCloneError") \ + V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId") \ + V(gid_string, "gid") \ + V(handle_string, "handle") \ + V(homedir_string, "homedir") \ + V(host_string, "host") \ + V(hostmaster_string, "hostmaster") \ + V(ignore_string, "ignore") \ + V(infoaccess_string, "infoAccess") \ + V(inherit_string, "inherit") \ + V(input_string, "input") \ + V(internal_string, "internal") \ + V(ipv4_string, "IPv4") \ + V(ipv6_string, "IPv6") \ + V(isclosing_string, "isClosing") \ + V(issuer_string, "issuer") \ + V(issuercert_string, "issuerCertificate") \ + V(kill_signal_string, "killSignal") \ + V(mac_string, "mac") \ + V(main_string, "main") \ + V(max_buffer_string, "maxBuffer") \ + V(max_semi_space_size_string, "maxSemiSpaceSize") \ + V(max_old_space_size_string, "maxOldSpaceSize") \ + V(message_string, "message") \ + V(message_port_string, "messagePort") \ + V(message_port_constructor_string, "MessagePort") \ + V(minttl_string, "minttl") \ + V(modulus_string, "modulus") \ + V(name_string, "name") \ + V(netmask_string, "netmask") \ + V(nsname_string, "nsname") \ + V(ocsp_request_string, "OCSPRequest") \ + V(onaltsvc_string, "onaltsvc") \ + V(onchange_string, "onchange") \ + V(onclienthello_string, "onclienthello") \ + V(oncomplete_string, "oncomplete") \ + V(onconnection_string, "onconnection") \ + V(ondone_string, "ondone") \ + V(onerror_string, "onerror") \ + V(onexit_string, "onexit") \ + V(onframeerror_string, "onframeerror") \ + V(ongetpadding_string, "ongetpadding") \ + V(onhandshakedone_string, "onhandshakedone") \ + V(onhandshakestart_string, "onhandshakestart") \ + V(onheaders_string, "onheaders") \ + V(oninit_string, "oninit") \ + V(onmessage_string, "onmessage") \ + V(onnewsession_string, "onnewsession") \ + V(onocspresponse_string, "onocspresponse") \ + V(ongoawaydata_string, "ongoawaydata") \ + V(onpriority_string, "onpriority") \ + V(onread_string, "onread") \ + V(onreadstart_string, "onreadstart") \ + V(onreadstop_string, "onreadstop") \ + V(onsettings_string, "onsettings") \ + V(onshutdown_string, "onshutdown") \ + V(onsignal_string, "onsignal") \ + V(onstop_string, "onstop") \ + V(onstreamclose_string, "onstreamclose") \ + V(ontrailers_string, "ontrailers") \ + V(onunpipe_string, "onunpipe") \ + V(onwrite_string, "onwrite") \ + V(openssl_error_stack, "opensslErrorStack") \ + V(output_string, "output") \ + V(order_string, "order") \ + V(owner_string, "owner") \ + V(parse_error_string, "Parse Error") \ + V(password_string, "password") \ + V(path_string, "path") \ + V(pending_handle_string, "pendingHandle") \ + V(pid_string, "pid") \ + V(pipe_string, "pipe") \ + V(pipe_target_string, "pipeTarget") \ + V(pipe_source_string, "pipeSource") \ + V(port_string, "port") \ + V(port1_string, "port1") \ + V(port2_string, "port2") \ + V(preference_string, "preference") \ + V(priority_string, "priority") \ + V(promise_string, "promise") \ + V(pubkey_string, "pubkey") \ + V(query_string, "query") \ + V(raw_string, "raw") \ + V(read_host_object_string, "_readHostObject") \ + V(readable_string, "readable") \ + V(refresh_string, "refresh") \ + V(regexp_string, "regexp") \ + V(rename_string, "rename") \ + V(replacement_string, "replacement") \ + V(retry_string, "retry") \ + V(scheme_string, "scheme") \ + V(serial_string, "serial") \ + V(scopeid_string, "scopeid") \ + V(serial_number_string, "serialNumber") \ + V(service_string, "service") \ + V(servername_string, "servername") \ + V(session_id_string, "sessionId") \ + V(shell_string, "shell") \ + V(signal_string, "signal") \ + V(sink_string, "sink") \ + V(size_string, "size") \ + V(sni_context_err_string, "Invalid SNI context") \ + V(sni_context_string, "sni_context") \ + V(source_string, "source") \ + V(stack_string, "stack") \ + V(status_string, "status") \ + V(stdio_string, "stdio") \ + V(subject_string, "subject") \ + V(subjectaltname_string, "subjectaltname") \ + V(syscall_string, "syscall") \ + V(thread_id_string, "threadId") \ + V(ticketkeycallback_string, "onticketkeycallback") \ + V(timeout_string, "timeout") \ + V(tls_ticket_string, "tlsTicket") \ + V(ttl_string, "ttl") \ + V(type_string, "type") \ + V(uid_string, "uid") \ + V(unknown_string, "") \ + V(url_string, "url") \ + V(user_string, "user") \ + V(username_string, "username") \ + V(valid_from_string, "valid_from") \ + V(valid_to_string, "valid_to") \ + V(value_string, "value") \ + V(verify_error_string, "verifyError") \ + V(version_string, "version") \ + V(weight_string, "weight") \ + V(windows_hide_string, "windowsHide") \ + V(windows_verbatim_arguments_string, "windowsVerbatimArguments") \ + V(wrap_string, "wrap") \ + V(writable_string, "writable") \ + V(write_host_object_string, "_writeHostObject") \ + V(write_queue_size_string, "writeQueueSize") \ + V(x_forwarded_string, "x-forwarded-for") \ V(zero_return_string, "ZERO_RETURN") -#define ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) \ - V(as_external, v8::External) \ - V(async_hooks_after_function, v8::Function) \ - V(async_hooks_before_function, v8::Function) \ - V(async_hooks_binding, v8::Object) \ - V(async_hooks_destroy_function, v8::Function) \ - V(async_hooks_init_function, v8::Function) \ - V(async_hooks_promise_resolve_function, v8::Function) \ - V(async_wrap_constructor_template, v8::FunctionTemplate) \ - V(buffer_prototype_object, v8::Object) \ - V(context, v8::Context) \ - V(domain_callback, v8::Function) \ - V(domexception_function, v8::Function) \ - V(fdclose_constructor_template, v8::ObjectTemplate) \ - V(fd_constructor_template, v8::ObjectTemplate) \ - V(filehandlereadwrap_template, v8::ObjectTemplate) \ - V(fsreqpromise_constructor_template, v8::ObjectTemplate) \ - V(fs_use_promises_symbol, v8::Symbol) \ - V(host_import_module_dynamically_callback, v8::Function) \ - V(host_initialize_import_meta_object_callback, v8::Function) \ - V(http2ping_constructor_template, v8::ObjectTemplate) \ - V(http2settings_constructor_template, v8::ObjectTemplate) \ - V(http2stream_constructor_template, v8::ObjectTemplate) \ - V(immediate_callback_function, v8::Function) \ - V(inspector_console_api_object, v8::Object) \ - V(message_port, v8::Object) \ - V(message_port_constructor_template, v8::FunctionTemplate) \ - V(pipe_constructor_template, v8::FunctionTemplate) \ - V(performance_entry_callback, v8::Function) \ - V(performance_entry_template, v8::Function) \ - V(process_object, v8::Object) \ - V(promise_reject_handled_function, v8::Function) \ - V(promise_reject_unhandled_function, v8::Function) \ - V(promise_wrap_template, v8::ObjectTemplate) \ - V(push_values_to_array_function, v8::Function) \ - V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate) \ - V(script_context_constructor_template, v8::FunctionTemplate) \ - V(script_data_constructor_function, v8::Function) \ - V(secure_context_constructor_template, v8::FunctionTemplate) \ - V(shutdown_wrap_template, v8::ObjectTemplate) \ - V(tcp_constructor_template, v8::FunctionTemplate) \ - V(tick_callback_function, v8::Function) \ - V(timers_callback_function, v8::Function) \ - V(tls_wrap_constructor_function, v8::Function) \ - V(tty_constructor_template, v8::FunctionTemplate) \ - V(udp_constructor_function, v8::Function) \ - V(vm_parsing_context_symbol, v8::Symbol) \ - V(url_constructor_function, v8::Function) \ +#define ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) \ + V(as_external, v8::External) \ + V(async_hooks_after_function, v8::Function) \ + V(async_hooks_before_function, v8::Function) \ + V(async_hooks_binding, v8::Object) \ + V(async_hooks_destroy_function, v8::Function) \ + V(async_hooks_init_function, v8::Function) \ + V(async_hooks_promise_resolve_function, v8::Function) \ + V(async_wrap_constructor_template, v8::FunctionTemplate) \ + V(buffer_prototype_object, v8::Object) \ + V(context, v8::Context) \ + V(domain_callback, v8::Function) \ + V(domexception_function, v8::Function) \ + V(fdclose_constructor_template, v8::ObjectTemplate) \ + V(fd_constructor_template, v8::ObjectTemplate) \ + V(filehandlereadwrap_template, v8::ObjectTemplate) \ + V(fsreqpromise_constructor_template, v8::ObjectTemplate) \ + V(fs_use_promises_symbol, v8::Symbol) \ + V(host_import_module_dynamically_callback, v8::Function) \ + V(host_initialize_import_meta_object_callback, v8::Function) \ + V(http2ping_constructor_template, v8::ObjectTemplate) \ + V(http2settings_constructor_template, v8::ObjectTemplate) \ + V(http2stream_constructor_template, v8::ObjectTemplate) \ + V(immediate_callback_function, v8::Function) \ + V(inspector_console_api_object, v8::Object) \ + V(message_port, v8::Object) \ + V(message_port_constructor_template, v8::FunctionTemplate) \ + V(pipe_constructor_template, v8::FunctionTemplate) \ + V(performance_entry_callback, v8::Function) \ + V(performance_entry_template, v8::Function) \ + V(process_object, v8::Object) \ + V(promise_reject_handled_function, v8::Function) \ + V(promise_reject_unhandled_function, v8::Function) \ + V(promise_wrap_template, v8::ObjectTemplate) \ + V(push_values_to_array_function, v8::Function) \ + V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate) \ + V(script_context_constructor_template, v8::FunctionTemplate) \ + V(script_data_constructor_function, v8::Function) \ + V(secure_context_constructor_template, v8::FunctionTemplate) \ + V(shutdown_wrap_template, v8::ObjectTemplate) \ + V(tcp_constructor_template, v8::FunctionTemplate) \ + V(tick_callback_function, v8::Function) \ + V(timers_callback_function, v8::Function) \ + V(tls_wrap_constructor_function, v8::Function) \ + V(tty_constructor_template, v8::FunctionTemplate) \ + V(udp_constructor_function, v8::Function) \ + V(vm_parsing_context_symbol, v8::Symbol) \ + V(url_constructor_function, v8::Function) \ V(write_wrap_template, v8::ObjectTemplate) class Environment; class IsolateData { public: - IsolateData(v8::Isolate* isolate, uv_loop_t* event_loop, + IsolateData(v8::Isolate* isolate, + uv_loop_t* event_loop, MultiIsolatePlatform* platform = nullptr, uint32_t* zero_fill_field = nullptr); ~IsolateData(); @@ -375,7 +376,7 @@ class IsolateData { #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) #define VS(PropertyName, StringValue) V(v8::String, PropertyName) -#define V(TypeName, PropertyName) \ +#define V(TypeName, PropertyName) \ inline v8::Local PropertyName(v8::Isolate* isolate) const; PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) PER_ISOLATE_SYMBOL_PROPERTIES(VY) @@ -391,8 +392,7 @@ class IsolateData { #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) #define VS(PropertyName, StringValue) V(v8::String, PropertyName) -#define V(TypeName, PropertyName) \ - v8::Eternal PropertyName ## _; +#define V(TypeName, PropertyName) v8::Eternal PropertyName##_; PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) PER_ISOLATE_SYMBOL_PROPERTIES(VY) PER_ISOLATE_STRING_PROPERTIES(VS) @@ -417,15 +417,15 @@ struct ContextInfo { // Listing the AsyncWrap provider types first enables us to cast directly // from a provider type to a debug category. -#define DEBUG_CATEGORY_NAMES(V) \ - NODE_ASYNC_PROVIDER_TYPES(V) \ - V(INSPECTOR_SERVER) +#define DEBUG_CATEGORY_NAMES(V) \ + NODE_ASYNC_PROVIDER_TYPES(V) \ + V(INSPECTOR_SERVER) enum class DebugCategory { #define V(name) name, DEBUG_CATEGORY_NAMES(V) #undef V - CATEGORY_COUNT + CATEGORY_COUNT }; class Environment { @@ -484,7 +484,6 @@ class Environment { DISALLOW_COPY_AND_ASSIGN(DefaultTriggerAsyncIdScope); }; - private: friend class Environment; // So we can call the constructor. inline AsyncHooks(); @@ -535,12 +534,7 @@ class Environment { friend class Environment; // So we can call the constructor. inline explicit ImmediateInfo(v8::Isolate* isolate); - enum Fields { - kCount, - kRefCount, - kHasOutstanding, - kFieldsCount - }; + enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount }; AliasedBuffer fields_; @@ -559,11 +553,7 @@ class Environment { friend class Environment; // So we can call the constructor. inline explicit TickInfo(v8::Isolate* isolate); - enum Fields { - kHasScheduled, - kHasPromiseRejections, - kFieldsCount - }; + enum Fields { kHasScheduled, kHasPromiseRejections, kFieldsCount }; AliasedBuffer fields_; @@ -692,14 +682,14 @@ class Environment { inline AliasedBuffer* fs_stats_field_array(); inline AliasedBuffer* - fs_stats_field_bigint_array(); + fs_stats_field_bigint_array(); // stat fields contains twice the number of entries because `fs.StatWatcher` // needs room to store data for *two* `fs.Stats` instances. static const int kFsStatsFieldsLength = 14; inline std::vector>& - file_handle_read_wrap_freelist(); + file_handle_read_wrap_freelist(); inline performance::performance_state* performance_state(); inline std::unordered_map* performance_marks(); @@ -746,14 +736,11 @@ class Environment { const char* path = nullptr, const char* dest = nullptr); - inline v8::Local - NewFunctionTemplate(v8::FunctionCallback callback, - v8::Local signature = - v8::Local(), - v8::ConstructorBehavior behavior = - v8::ConstructorBehavior::kAllow, - v8::SideEffectType side_effect = - v8::SideEffectType::kHasSideEffect); + inline v8::Local NewFunctionTemplate( + v8::FunctionCallback callback, + v8::Local signature = v8::Local(), + v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow, + v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect); // Convenience methods for NewFunctionTemplate(). inline void SetMethod(v8::Local that, @@ -789,7 +776,7 @@ class Environment { #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) #define VS(PropertyName, StringValue) V(v8::String, PropertyName) -#define V(TypeName, PropertyName) \ +#define V(TypeName, PropertyName) \ inline v8::Local PropertyName() const; PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) PER_ISOLATE_SYMBOL_PROPERTIES(VY) @@ -799,9 +786,9 @@ class Environment { #undef VY #undef VP -#define V(PropertyName, TypeName) \ - inline v8::Local PropertyName() const; \ - inline void set_ ## PropertyName(v8::Local value); +#define V(PropertyName, TypeName) \ + inline v8::Local PropertyName() const; \ + inline void set_##PropertyName(v8::Local value); ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) #undef V @@ -813,7 +800,7 @@ class Environment { typedef ListHead HandleWrapQueue; typedef ListHead, &ReqWrap::req_wrap_queue_> - ReqWrapQueue; + ReqWrapQueue; inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; } inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; } @@ -832,10 +819,10 @@ class Environment { inline void SetImmediate(native_immediate_callback cb, void* data, v8::Local obj = v8::Local()); - inline void SetUnrefImmediate(native_immediate_callback cb, - void* data, - v8::Local obj = - v8::Local()); + inline void SetUnrefImmediate( + native_immediate_callback cb, + void* data, + v8::Local obj = v8::Local()); // This needs to be available for the JS-land setImmediate(). void ToggleImmediateRef(bool ref); @@ -994,7 +981,8 @@ class Environment { // Use an unordered_set, so that we have efficient insertion and removal. std::unordered_set cleanup_hooks_; + CleanupHookCallback::Equal> + cleanup_hooks_; uint64_t cleanup_hook_counter_ = 0; static void EnvPromiseHook(v8::PromiseHookType type, @@ -1004,7 +992,7 @@ class Environment { template void ForEachBaseObject(T&& iterator); -#define V(PropertyName, TypeName) Persistent PropertyName ## _; +#define V(PropertyName, TypeName) Persistent PropertyName##_; ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) #undef V diff --git a/src/exceptions.cc b/src/exceptions.cc index 9cdb5a54b880c3..1733c97fc14715 100644 --- a/src/exceptions.cc +++ b/src/exceptions.cc @@ -1,9 +1,9 @@ +#include "env-inl.h" #include "node.h" #include "node_internals.h" -#include "env-inl.h" #include "util-inl.h" -#include "v8.h" #include "uv.h" +#include "v8.h" #include @@ -39,8 +39,9 @@ Local ErrnoException(Isolate* isolate, Local path_string; if (path != nullptr) { // FIXME(bnoordhuis) It's questionable to interpret the file path as UTF-8. - path_string = String::NewFromUtf8(env->isolate(), path, - v8::NewStringType::kNormal).ToLocalChecked(); + path_string = + String::NewFromUtf8(env->isolate(), path, v8::NewStringType::kNormal) + .ToLocalChecked(); } if (path_string.IsEmpty() == false) { @@ -68,10 +69,10 @@ Local ErrnoException(Isolate* isolate, static Local StringFromPath(Isolate* isolate, const char* path) { #ifdef _WIN32 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) { - return String::Concat(FIXED_ONE_BYTE_STRING(isolate, "\\\\"), - String::NewFromUtf8(isolate, path + 8, - v8::NewStringType::kNormal) - .ToLocalChecked()); + return String::Concat( + FIXED_ONE_BYTE_STRING(isolate, "\\\\"), + String::NewFromUtf8(isolate, path + 8, v8::NewStringType::kNormal) + .ToLocalChecked()); } else if (strncmp(path, "\\\\?\\", 4) == 0) { return String::NewFromUtf8(isolate, path + 4, v8::NewStringType::kNormal) .ToLocalChecked(); @@ -82,7 +83,6 @@ static Local StringFromPath(Isolate* isolate, const char* path) { .ToLocalChecked(); } - Local UVException(Isolate* isolate, int errorno, const char* syscall, @@ -91,7 +91,6 @@ Local UVException(Isolate* isolate, return UVException(isolate, errorno, syscall, msg, path, nullptr); } - Local UVException(Isolate* isolate, int errorno, const char* syscall, @@ -100,8 +99,7 @@ Local UVException(Isolate* isolate, const char* dest) { Environment* env = Environment::GetCurrent(isolate); - if (!msg || !msg[0]) - msg = uv_strerror(errorno); + if (!msg || !msg[0]) msg = uv_strerror(errorno); Local js_code = OneByteString(isolate, uv_err_name(errorno)); Local js_syscall = OneByteString(isolate, syscall); @@ -135,10 +133,8 @@ Local UVException(Isolate* isolate, e->Set(env->errno_string(), Integer::New(isolate, errorno)); e->Set(env->code_string(), js_code); e->Set(env->syscall_string(), js_syscall); - if (!js_path.IsEmpty()) - e->Set(env->path_string(), js_path); - if (!js_dest.IsEmpty()) - e->Set(env->dest_string(), js_dest); + if (!js_path.IsEmpty()) e->Set(env->path_string(), js_path); + if (!js_dest.IsEmpty()) e->Set(env->dest_string(), js_dest); return e; } @@ -150,15 +146,21 @@ static const char* winapi_strerror(const int errorno, bool* must_free) { char* errmsg = nullptr; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorno, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, nullptr); + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + errorno, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR)&errmsg, + 0, + nullptr); if (errmsg) { *must_free = true; // Remove trailing newlines for (int i = strlen(errmsg) - 1; - i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) { + i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); + i--) { errmsg[i] = '\0'; } @@ -170,7 +172,6 @@ static const char* winapi_strerror(const int errorno, bool* must_free) { } } - Local WinapiErrnoException(Isolate* isolate, int errorno, const char* syscall, @@ -187,10 +188,10 @@ Local WinapiErrnoException(Isolate* isolate, if (path) { Local cons1 = String::Concat(message, FIXED_ONE_BYTE_STRING(isolate, " '")); - Local cons2 = - String::Concat(cons1, - String::NewFromUtf8(isolate, path, v8::NewStringType::kNormal) - .ToLocalChecked()); + Local cons2 = String::Concat( + cons1, + String::NewFromUtf8(isolate, path, v8::NewStringType::kNormal) + .ToLocalChecked()); Local cons3 = String::Concat(cons2, FIXED_ONE_BYTE_STRING(isolate, "'")); e = Exception::Error(cons3); @@ -211,8 +212,7 @@ Local WinapiErrnoException(Isolate* isolate, obj->Set(env->syscall_string(), OneByteString(isolate, syscall)); } - if (must_free) - LocalFree((HLOCAL)msg); + if (must_free) LocalFree((HLOCAL)msg); return e; } diff --git a/src/fs_event_wrap.cc b/src/fs_event_wrap.cc index e0cdab4d3e20f1..2a563ba43157fe 100644 --- a/src/fs_event_wrap.cc +++ b/src/fs_event_wrap.cc @@ -21,12 +21,11 @@ #include "async_wrap-inl.h" #include "env-inl.h" -#include "util-inl.h" +#include "handle_wrap.h" #include "node.h" #include "node_internals.h" -#include "handle_wrap.h" #include "string_bytes.h" - +#include "util-inl.h" namespace node { @@ -48,7 +47,7 @@ using v8::Value; namespace { -class FSEventWrap: public HandleWrap { +class FSEventWrap : public HandleWrap { public: static void Initialize(Local target, Local unused, @@ -69,14 +68,15 @@ class FSEventWrap: public HandleWrap { FSEventWrap(Environment* env, Local object); ~FSEventWrap() override; - static void OnEvent(uv_fs_event_t* handle, const char* filename, int events, - int status); + static void OnEvent(uv_fs_event_t* handle, + const char* filename, + int events, + int status); uv_fs_event_t handle_; enum encoding encoding_ = kDefaultEncoding; }; - FSEventWrap::FSEventWrap(Environment* env, Local object) : HandleWrap(env, object, @@ -85,9 +85,7 @@ FSEventWrap::FSEventWrap(Environment* env, Local object) MarkAsUninitialized(); } - -FSEventWrap::~FSEventWrap() { -} +FSEventWrap::~FSEventWrap() {} void FSEventWrap::GetInitialized(const FunctionCallbackInfo& args) { FSEventWrap* wrap = Unwrap(args.This()); @@ -124,7 +122,6 @@ void FSEventWrap::Initialize(Local target, target->Set(fsevent_string, t->GetFunction()); } - void FSEventWrap::New(const FunctionCallbackInfo& args) { CHECK(args.IsConstructCall()); Environment* env = Environment::GetCurrent(args); @@ -146,8 +143,7 @@ void FSEventWrap::Start(const FunctionCallbackInfo& args) { CHECK_NOT_NULL(*path); unsigned int flags = 0; - if (args[2]->IsTrue()) - flags |= UV_FS_EVENT_RECURSIVE; + if (args[2]->IsTrue()) flags |= UV_FS_EVENT_RECURSIVE; wrap->encoding_ = ParseEncoding(env->isolate(), args[3], kDefaultEncoding); @@ -172,9 +168,10 @@ void FSEventWrap::Start(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } - -void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename, - int events, int status) { +void FSEventWrap::OnEvent(uv_fs_event_t* handle, + const char* filename, + int events, + int status) { FSEventWrap* wrap = static_cast(handle->data); Environment* env = wrap->env(); @@ -206,24 +203,17 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename, } Local argv[] = { - Integer::New(env->isolate(), status), - event_string, - Null(env->isolate()) - }; + Integer::New(env->isolate(), status), event_string, Null(env->isolate())}; if (filename != nullptr) { Local error; - MaybeLocal fn = StringBytes::Encode(env->isolate(), - filename, - wrap->encoding_, - &error); + MaybeLocal fn = + StringBytes::Encode(env->isolate(), filename, wrap->encoding_, &error); if (fn.IsEmpty()) { argv[0] = Integer::New(env->isolate(), UV_EINVAL); - argv[2] = StringBytes::Encode(env->isolate(), - filename, - strlen(filename), - BUFFER, - &error).ToLocalChecked(); + argv[2] = StringBytes::Encode( + env->isolate(), filename, strlen(filename), BUFFER, &error) + .ToLocalChecked(); } else { argv[2] = fn.ToLocalChecked(); } diff --git a/src/handle_wrap.cc b/src/handle_wrap.cc index 9281300146c4f3..b349f2799bd7bb 100644 --- a/src/handle_wrap.cc +++ b/src/handle_wrap.cc @@ -22,8 +22,8 @@ #include "handle_wrap.h" #include "async_wrap-inl.h" #include "env-inl.h" -#include "util-inl.h" #include "node.h" +#include "util-inl.h" namespace node { @@ -35,32 +35,26 @@ using v8::Local; using v8::Object; using v8::Value; - void HandleWrap::Ref(const FunctionCallbackInfo& args) { HandleWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); - if (IsAlive(wrap)) - uv_ref(wrap->GetHandle()); + if (IsAlive(wrap)) uv_ref(wrap->GetHandle()); } - void HandleWrap::Unref(const FunctionCallbackInfo& args) { HandleWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); - if (IsAlive(wrap)) - uv_unref(wrap->GetHandle()); + if (IsAlive(wrap)) uv_unref(wrap->GetHandle()); } - void HandleWrap::HasRef(const FunctionCallbackInfo& args) { HandleWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); args.GetReturnValue().Set(HasRef(wrap)); } - void HandleWrap::Close(const FunctionCallbackInfo& args) { HandleWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -69,49 +63,41 @@ void HandleWrap::Close(const FunctionCallbackInfo& args) { } void HandleWrap::Close(Local close_callback) { - if (state_ != kInitialized) - return; + if (state_ != kInitialized) return; CHECK_EQ(false, persistent().IsEmpty()); uv_close(handle_, OnClose); state_ = kClosing; if (!close_callback.IsEmpty() && close_callback->IsFunction()) { - object()->Set(env()->context(), - env()->handle_onclose_symbol(), - close_callback) + object() + ->Set(env()->context(), env()->handle_onclose_symbol(), close_callback) .FromMaybe(false); } } - void HandleWrap::MarkAsInitialized() { env()->handle_wrap_queue()->PushBack(this); state_ = kInitialized; } - void HandleWrap::MarkAsUninitialized() { handle_wrap_queue_.Remove(); state_ = kClosed; } - HandleWrap::HandleWrap(Environment* env, Local object, uv_handle_t* handle, AsyncWrap::ProviderType provider) - : AsyncWrap(env, object, provider), - state_(kInitialized), - handle_(handle) { + : AsyncWrap(env, object, provider), state_(kInitialized), handle_(handle) { handle_->data = this; HandleScope scope(env->isolate()); env->handle_wrap_queue()->PushBack(this); } - void HandleWrap::OnClose(uv_handle_t* handle) { - std::unique_ptr wrap { static_cast(handle->data) }; + std::unique_ptr wrap{static_cast(handle->data)}; Environment* env = wrap->env(); HandleScope scope(env->isolate()); Context::Scope context_scope(env->context()); @@ -124,20 +110,18 @@ void HandleWrap::OnClose(uv_handle_t* handle) { wrap->OnClose(); - if (wrap->object()->Has(env->context(), env->handle_onclose_symbol()) - .FromMaybe(false)) { + if (wrap->object() + ->Has(env->context(), env->handle_onclose_symbol()) + .FromMaybe(false)) { wrap->MakeCallback(env->handle_onclose_symbol(), 0, nullptr); } } - -void HandleWrap::AddWrapMethods(Environment* env, - Local t) { +void HandleWrap::AddWrapMethods(Environment* env, Local t) { env->SetProtoMethod(t, "close", HandleWrap::Close); env->SetProtoMethodNoSideEffect(t, "hasRef", HandleWrap::HasRef); env->SetProtoMethod(t, "ref", HandleWrap::Ref); env->SetProtoMethod(t, "unref", HandleWrap::Unref); } - } // namespace node diff --git a/src/handle_wrap.h b/src/handle_wrap.h index 443d28bf523933..110fea97336709 100644 --- a/src/handle_wrap.h +++ b/src/handle_wrap.h @@ -106,7 +106,6 @@ class HandleWrap : public AsyncWrap { uv_handle_t* const handle_; }; - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/heap_utils.cc b/src/heap_utils.cc index 2d339c580fa076..b9417be9bd41b4 100644 --- a/src/heap_utils.cc +++ b/src/heap_utils.cc @@ -1,5 +1,5 @@ -#include "node_internals.h" #include "env.h" +#include "node_internals.h" using v8::Array; using v8::Boolean; @@ -62,10 +62,9 @@ class JSGraph : public EmbedderGraph { explicit JSGraph(Isolate* isolate) : isolate_(isolate) {} Node* V8Node(const Local& value) override { - std::unique_ptr n { new JSGraphJSNode(isolate_, value) }; + std::unique_ptr n{new JSGraphJSNode(isolate_, value)}; auto it = engine_nodes_.find(n.get()); - if (it != engine_nodes_.end()) - return *it; + if (it != engine_nodes_.end()) return *it; engine_nodes_.insert(n.get()); return AddNode(std::unique_ptr(n.release())); } @@ -76,9 +75,7 @@ class JSGraph : public EmbedderGraph { return n; } - void AddEdge(Node* from, Node* to) override { - edges_[from].insert(to); - } + void AddEdge(Node* from, Node* to) override { edges_[from].insert(to); } MaybeLocal CreateObject() const { EscapableHandleScope handle_scope(isolate_); @@ -102,15 +99,19 @@ class JSGraph : public EmbedderGraph { for (const std::unique_ptr& n : nodes_) { Local obj = info_objects[n.get()]; Local value; - if (!String::NewFromUtf8(isolate_, n->Name(), - v8::NewStringType::kNormal).ToLocal(&value) || + if (!String::NewFromUtf8( + isolate_, n->Name(), v8::NewStringType::kNormal) + .ToLocal(&value) || obj->Set(context, name_string, value).IsNothing() || - obj->Set(context, is_root_string, - Boolean::New(isolate_, n->IsRootNode())).IsNothing() || - obj->Set(context, size_string, - Number::New(isolate_, n->SizeInBytes())).IsNothing() || - obj->Set(context, edges_string, - Array::New(isolate_)).IsNothing()) { + obj->Set(context, + is_root_string, + Boolean::New(isolate_, n->IsRootNode())) + .IsNothing() || + obj->Set(context, + size_string, + Number::New(isolate_, n->SizeInBytes())) + .IsNothing() || + obj->Set(context, edges_string, Array::New(isolate_)).IsNothing()) { return MaybeLocal(); } if (nodes->Set(context, i++, obj).IsNothing()) @@ -142,9 +143,9 @@ class JSGraph : public EmbedderGraph { size_t i = 0; for (Node* target : edge_info.second) { - if (edges.As()->Set(context, - i++, - info_objects[target]).IsNothing()) { + if (edges.As() + ->Set(context, i++, info_objects[target]) + .IsNothing()) { return MaybeLocal(); } } @@ -166,11 +167,9 @@ void BuildEmbedderGraph(const FunctionCallbackInfo& args) { JSGraph graph(env->isolate()); Environment::BuildEmbedderGraph(env->isolate(), &graph, env); Local ret; - if (graph.CreateObject().ToLocal(&ret)) - args.GetReturnValue().Set(ret); + if (graph.CreateObject().ToLocal(&ret)) args.GetReturnValue().Set(ret); } - class BufferOutputStream : public v8::OutputStream { public: BufferOutputStream() : buffer_(new JSString()) {} @@ -183,16 +182,14 @@ class BufferOutputStream : public v8::OutputStream { } Local ToString(Isolate* isolate) { - return String::NewExternalOneByte(isolate, - buffer_.release()).ToLocalChecked(); + return String::NewExternalOneByte(isolate, buffer_.release()) + .ToLocalChecked(); } private: class JSString : public String::ExternalOneByteStringResource { public: - void Append(char* data, size_t count) { - store_.append(data, count); - } + void Append(char* data, size_t count) { store_.append(data, count); } const char* data() const override { return store_.data(); } size_t length() const override { return store_.size(); } @@ -211,8 +208,8 @@ void CreateHeapDump(const FunctionCallbackInfo& args) { snapshot->Serialize(&out, HeapSnapshot::kJSON); const_cast(snapshot)->Delete(); Local ret; - if (JSON::Parse(isolate->GetCurrentContext(), - out.ToString(isolate)).ToLocal(&ret)) { + if (JSON::Parse(isolate->GetCurrentContext(), out.ToString(isolate)) + .ToLocal(&ret)) { args.GetReturnValue().Set(ret); } } diff --git a/src/inspector/main_thread_interface.cc b/src/inspector/main_thread_interface.cc index da43c95bea5fe3..279b8cf1e0639f 100644 --- a/src/inspector/main_thread_interface.cc +++ b/src/inspector/main_thread_interface.cc @@ -9,16 +9,14 @@ namespace node { namespace inspector { namespace { -using v8_inspector::StringView; using v8_inspector::StringBuffer; +using v8_inspector::StringView; template class DeleteRequest : public Request { public: explicit DeleteRequest(T* object) : object_(object) {} - void Call() override { - delete object_; - } + void Call() override { delete object_; } private: T* object_; @@ -30,13 +28,9 @@ class SingleArgumentFunctionCall : public Request { using Fn = void (Target::*)(Arg); SingleArgumentFunctionCall(Target* target, Fn fn, Arg argument) - : target_(target), - fn_(fn), - arg_(std::move(argument)) {} + : target_(target), fn_(fn), arg_(std::move(argument)) {} - void Call() override { - Apply(target_, fn_, std::move(arg_)); - } + void Call() override { Apply(target_, fn_, std::move(arg_)); } private: template @@ -51,14 +45,10 @@ class SingleArgumentFunctionCall : public Request { class PostMessageRequest : public Request { public: - PostMessageRequest(InspectorSessionDelegate* delegate, - StringView message) - : delegate_(delegate), - message_(StringBuffer::create(message)) {} + PostMessageRequest(InspectorSessionDelegate* delegate, StringView message) + : delegate_(delegate), message_(StringBuffer::create(message)) {} - void Call() override { - delegate_->SendMessageToFrontend(message_->string()); - } + void Call() override { delegate_->SendMessageToFrontend(message_->string()); } private: InspectorSessionDelegate* delegate_; @@ -68,11 +58,9 @@ class PostMessageRequest : public Request { class DispatchMessagesTask : public v8::Task { public: explicit DispatchMessagesTask(MainThreadInterface* thread) - : thread_(thread) {} + : thread_(thread) {} - void Run() override { - thread_->DispatchMessages(); - } + void Run() override { thread_->DispatchMessages(); } private: MainThreadInterface* thread_; @@ -92,8 +80,7 @@ class AnotherThreadObjectReference { // proper thread. AnotherThreadObjectReference(std::shared_ptr thread, T* object) - : thread_(thread), object_(object) { - } + : thread_(thread), object_(object) {} AnotherThreadObjectReference(AnotherThreadObjectReference&) = delete; ~AnotherThreadObjectReference() { @@ -109,9 +96,7 @@ class AnotherThreadObjectReference { thread_->Post(std::unique_ptr(new R(object_, fn, std::move(argument)))); } - T* get() const { - return object_; - } + T* get() const { return object_; } private: std::shared_ptr thread_; @@ -120,10 +105,9 @@ class AnotherThreadObjectReference { class MainThreadSessionState { public: - MainThreadSessionState( - std::shared_ptr thread, - bool prevent_shutdown) : thread_(thread), - prevent_shutdown_(prevent_shutdown) {} + MainThreadSessionState(std::shared_ptr thread, + bool prevent_shutdown) + : thread_(thread), prevent_shutdown_(prevent_shutdown) {} void Connect(std::unique_ptr delegate) { Agent* agent = thread_->GetInspectorAgent(); @@ -165,7 +149,7 @@ class ThreadSafeDelegate : public InspectorSessionDelegate { public: ThreadSafeDelegate(std::shared_ptr thread, std::unique_ptr delegate) - : thread_(thread), delegate_(thread, delegate.release()) {} + : thread_(thread), delegate_(thread, delegate.release()) {} void SendMessageToFrontend(const v8_inspector::StringView& message) override { thread_->Post(std::unique_ptr( @@ -178,22 +162,22 @@ class ThreadSafeDelegate : public InspectorSessionDelegate { }; } // namespace - -MainThreadInterface::MainThreadInterface(Agent* agent, uv_loop_t* loop, +MainThreadInterface::MainThreadInterface(Agent* agent, + uv_loop_t* loop, v8::Isolate* isolate, v8::Platform* platform) - : agent_(agent), isolate_(isolate), - platform_(platform) { + : agent_(agent), isolate_(isolate), platform_(platform) { main_thread_request_.reset(new AsyncAndInterface(uv_async_t(), this)); - CHECK_EQ(0, uv_async_init(loop, &main_thread_request_->first, - DispatchMessagesAsyncCallback)); + CHECK_EQ( + 0, + uv_async_init( + loop, &main_thread_request_->first, DispatchMessagesAsyncCallback)); // Inspector uv_async_t should not prevent main loop shutdown. uv_unref(reinterpret_cast(&main_thread_request_->first)); } MainThreadInterface::~MainThreadInterface() { - if (handle_) - handle_->Reset(); + if (handle_) handle_->Reset(); } // static @@ -217,9 +201,11 @@ void MainThreadInterface::Post(std::unique_ptr request) { if (isolate_ != nullptr && platform_ != nullptr) { platform_->CallOnForegroundThread(isolate_, new DispatchMessagesTask(this)); - isolate_->RequestInterrupt([](v8::Isolate* isolate, void* thread) { - static_cast(thread)->DispatchMessages(); - }, this); + isolate_->RequestInterrupt( + [](v8::Isolate* isolate, void* thread) { + static_cast(thread)->DispatchMessages(); + }, + this); } } incoming_message_cond_.Broadcast(scoped_lock); @@ -238,8 +224,7 @@ bool MainThreadInterface::WaitForFrontendEvent() { } void MainThreadInterface::DispatchMessages() { - if (dispatching_messages_) - return; + if (dispatching_messages_) return; dispatching_messages_ = true; bool had_messages = false; do { @@ -259,8 +244,7 @@ void MainThreadInterface::DispatchMessages() { } std::shared_ptr MainThreadInterface::GetHandle() { - if (handle_ == nullptr) - handle_ = std::make_shared(this); + if (handle_ == nullptr) handle_ = std::make_shared(this); return handle_; } @@ -273,8 +257,7 @@ std::unique_ptr Utf8ToStringView(const std::string& message) { } std::unique_ptr MainThreadHandle::Connect( - std::unique_ptr delegate, - bool prevent_shutdown) { + std::unique_ptr delegate, bool prevent_shutdown) { return std::unique_ptr( new CrossThreadInspectorSession(++next_session_id_, shared_from_this(), @@ -284,8 +267,7 @@ std::unique_ptr MainThreadHandle::Connect( bool MainThreadHandle::Post(std::unique_ptr request) { Mutex::ScopedLock scoped_lock(block_lock_); - if (!main_thread_) - return false; + if (!main_thread_) return false; main_thread_->Post(std::move(request)); return true; } @@ -297,8 +279,7 @@ void MainThreadHandle::Reset() { Agent* MainThreadHandle::GetInspectorAgent() { Mutex::ScopedLock scoped_lock(block_lock_); - if (main_thread_ == nullptr) - return nullptr; + if (main_thread_ == nullptr) return nullptr; return main_thread_->inspector_agent(); } diff --git a/src/inspector/main_thread_interface.h b/src/inspector/main_thread_interface.h index 75df5ffe809048..e2ff0895cdf00e 100644 --- a/src/inspector/main_thread_interface.h +++ b/src/inspector/main_thread_interface.h @@ -36,7 +36,7 @@ class MainThreadInterface; class MainThreadHandle : public std::enable_shared_from_this { public: explicit MainThreadHandle(MainThreadInterface* main_thread) - : main_thread_(main_thread) {} + : main_thread_(main_thread) {} ~MainThreadHandle() { CHECK_NULL(main_thread_); // main_thread_ should have called Reset } @@ -61,7 +61,9 @@ class MainThreadHandle : public std::enable_shared_from_this { class MainThreadInterface { public: - MainThreadInterface(Agent* agent, uv_loop_t*, v8::Isolate* isolate, + MainThreadInterface(Agent* agent, + uv_loop_t*, + v8::Isolate* isolate, v8::Platform* platform); ~MainThreadInterface(); @@ -69,9 +71,7 @@ class MainThreadInterface { void Post(std::unique_ptr request); bool WaitForFrontendEvent(); std::shared_ptr GetHandle(); - Agent* inspector_agent() { - return agent_; - } + Agent* inspector_agent() { return agent_; } private: using AsyncAndInterface = std::pair; @@ -80,7 +80,7 @@ class MainThreadInterface { static void CloseAsync(AsyncAndInterface*); MessageQueue requests_; - Mutex requests_lock_; // requests_ live across threads + Mutex requests_lock_; // requests_ live across threads // This queue is to maintain the order of the messages for the cases // when we reenter the DispatchMessages function. MessageQueue dispatching_message_queue_; diff --git a/src/inspector/node_string.cc b/src/inspector/node_string.cc index cb9e90c20e807a..05a376cfc3a9d9 100644 --- a/src/inspector/node_string.cc +++ b/src/inspector/node_string.cc @@ -17,34 +17,31 @@ void builderAppendQuotedString(StringBuilder& builder, const String& string) { icu::UnicodeString utf16 = icu::UnicodeString::fromUTF8( icu::StringPiece(string.data(), string.length())); escapeWideStringForJSON( - reinterpret_cast(utf16.getBuffer()), utf16.length(), + reinterpret_cast(utf16.getBuffer()), + utf16.length(), &builder); } builder.put('"'); } std::unique_ptr parseJSON(const String& string) { - if (string.empty()) - return nullptr; + if (string.empty()) return nullptr; - icu::UnicodeString utf16 = - icu::UnicodeString::fromUTF8(icu::StringPiece(string.data(), - string.length())); + icu::UnicodeString utf16 = icu::UnicodeString::fromUTF8( + icu::StringPiece(string.data(), string.length())); return parseJSONCharacters( reinterpret_cast(utf16.getBuffer()), utf16.length()); } std::unique_ptr parseJSON(v8_inspector::StringView string) { - if (string.length() == 0) - return nullptr; + if (string.length() == 0) return nullptr; if (string.is8Bit()) return parseJSONCharacters(string.characters8(), string.length()); return parseJSONCharacters(string.characters16(), string.length()); } String StringViewToUtf8(v8_inspector::StringView view) { - if (view.length() == 0) - return ""; + if (view.length() == 0) return ""; if (view.is8Bit()) { return std::string(reinterpret_cast(view.characters8()), view.length()); @@ -89,4 +86,3 @@ double toDouble(const char* buffer, size_t length, bool* ok) { } // namespace protocol } // namespace inspector } // namespace node - diff --git a/src/inspector/node_string.h b/src/inspector/node_string.h index 468aec96b56e79..36040a78a8202d 100644 --- a/src/inspector/node_string.h +++ b/src/inspector/node_string.h @@ -26,7 +26,8 @@ inline void builderAppend(StringBuilder& builder, char c) { } // NOLINTNEXTLINE(runtime/references) -inline void builderAppend(StringBuilder& builder, const char* value, +inline void builderAppend(StringBuilder& builder, + const char* value, size_t length) { builder.write(value, length); } diff --git a/src/inspector/tracing_agent.cc b/src/inspector/tracing_agent.cc index c0425aab29d4a0..6dde072942a7d0 100644 --- a/src/inspector/tracing_agent.cc +++ b/src/inspector/tracing_agent.cc @@ -16,7 +16,7 @@ using v8::platform::tracing::TraceWriter; class InspectorTraceWriter : public node::tracing::AsyncTraceWriter { public: explicit InspectorTraceWriter(NodeTracing::Frontend* frontend) - : frontend_(frontend) {} + : frontend_(frontend) {} void AppendTraceEvent( v8::platform::tracing::TraceObject* trace_event) override { @@ -26,8 +26,7 @@ class InspectorTraceWriter : public node::tracing::AsyncTraceWriter { } void Flush(bool) override { - if (!json_writer_) - return; + if (!json_writer_) return; json_writer_.reset(); std::ostringstream result( "{\"method\":\"NodeTracing.dataCollected\",\"data\":", @@ -46,10 +45,7 @@ class InspectorTraceWriter : public node::tracing::AsyncTraceWriter { } // namespace TracingAgent::TracingAgent(Environment* env) - : env_(env), - trace_writer_( - tracing::Agent::EmptyClientHandle()) { -} + : env_(env), trace_writer_(tracing::Agent::EmptyClientHandle()) {} TracingAgent::~TracingAgent() { trace_writer_.reset(); diff --git a/src/inspector/tracing_agent.h b/src/inspector/tracing_agent.h index 478107c5acdd64..fa794b3b275a32 100644 --- a/src/inspector/tracing_agent.h +++ b/src/inspector/tracing_agent.h @@ -4,7 +4,6 @@ #include "node/inspector/protocol/NodeTracing.h" #include "v8.h" - namespace node { class Environment; @@ -33,11 +32,11 @@ class TracingAgent : public NodeTracing::Backend { Environment* env_; std::unique_ptr, - void (*)(std::pair*)> trace_writer_; + void (*)(std::pair*)> + trace_writer_; std::unique_ptr frontend_; }; - } // namespace protocol } // namespace inspector } // namespace node diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index ebb8d8a161606d..bc146782dd31b9 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -1,9 +1,9 @@ #include "inspector_agent.h" -#include "inspector_io.h" #include "inspector/main_thread_interface.h" #include "inspector/node_string.h" #include "inspector/tracing_agent.h" +#include "inspector_io.h" #include "node/inspector/protocol/Protocol.h" #include "node_internals.h" #include "v8-inspector.h" @@ -49,9 +49,7 @@ class StartIoTask : public v8::Task { public: explicit StartIoTask(Agent* agent) : agent(agent) {} - void Run() override { - agent->StartIoThread(); - } + void Run() override { agent->StartIoThread(); } private: Agent* agent; @@ -72,7 +70,6 @@ void StartIoInterrupt(Isolate* isolate, void* agent) { static_cast(agent)->StartIoThread(); } - #ifdef __POSIX__ static void StartIoThreadWakeup(int signo) { uv_sem_post(&start_io_thread_semaphore); @@ -82,8 +79,7 @@ inline void* StartIoThreadMain(void* unused) { for (;;) { uv_sem_wait(&start_io_thread_semaphore); Agent* agent = static_cast(start_io_thread_async.data); - if (agent != nullptr) - agent->RequestIoThreadStart(); + if (agent != nullptr) agent->RequestIoThreadStart(); } return nullptr; } @@ -107,14 +103,15 @@ static int StartDebugSignalHandler() { sigfillset(&sigmask); CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, &sigmask)); pthread_t thread; - const int err = pthread_create(&thread, &attr, - StartIoThreadMain, nullptr); + const int err = pthread_create(&thread, &attr, StartIoThreadMain, nullptr); // Restore original mask CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr)); CHECK_EQ(0, pthread_attr_destroy(&attr)); if (err != 0) { - fprintf(stderr, "node[%u]: pthread_create: %s\n", - uv_os_getpid(), strerror(err)); + fprintf(stderr, + "node[%u]: pthread_create: %s\n", + uv_os_getpid(), + strerror(err)); fflush(stderr); // Leave SIGUSR1 blocked. We don't install a signal handler, // receiving the signal would terminate the process. @@ -129,16 +126,15 @@ static int StartDebugSignalHandler() { } #endif // __POSIX__ - #ifdef _WIN32 DWORD WINAPI StartIoThreadProc(void* arg) { Agent* agent = static_cast(start_io_thread_async.data); - if (agent != nullptr) - agent->RequestIoThreadStart(); + if (agent != nullptr) agent->RequestIoThreadStart(); return 0; } -static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf, +static int GetDebugSignalHandlerMappingName(DWORD pid, + wchar_t* buf, size_t buf_len) { return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid); } @@ -151,9 +147,8 @@ static int StartDebugSignalHandler() { pid = uv_os_getpid(); - if (GetDebugSignalHandlerMappingName(pid, - mapping_name, - arraysize(mapping_name)) < 0) { + if (GetDebugSignalHandlerMappingName( + pid, mapping_name, arraysize(mapping_name)) < 0) { return -1; } @@ -167,12 +162,8 @@ static int StartDebugSignalHandler() { return -1; } - handler = reinterpret_cast( - MapViewOfFile(mapping_handle, - FILE_MAP_ALL_ACCESS, - 0, - 0, - sizeof *handler)); + handler = reinterpret_cast(MapViewOfFile( + mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof *handler)); if (handler == nullptr) { CloseHandle(mapping_handle); return -1; @@ -186,7 +177,6 @@ static int StartDebugSignalHandler() { } #endif // _WIN32 - // Used in NodeInspectorClient::currentTimeMS() below. const int NANOS_PER_MSEC = 1000000; const int CONTEXT_GROUP_ID = 1; @@ -198,8 +188,7 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel, const std::unique_ptr& inspector, std::unique_ptr delegate, bool prevent_shutdown) - : delegate_(std::move(delegate)), - prevent_shutdown_(prevent_shutdown) { + : delegate_(std::move(delegate)), prevent_shutdown_(prevent_shutdown) { session_ = inspector->connect(1, this, StringView()); node_dispatcher_.reset(new protocol::UberDispatcher(this)); tracing_agent_.reset(new protocol::TracingAgent(env)); @@ -230,9 +219,7 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel, session_->schedulePauseOnNextStatement(buffer->string(), buffer->string()); } - bool preventShutdown() { - return prevent_shutdown_; - } + bool preventShutdown() { return prevent_shutdown_; } private: void sendResponse( @@ -246,7 +233,7 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel, sendMessageToFrontend(message->string()); } - void flushProtocolNotifications() override { } + void flushProtocolNotifications() override {} void sendMessageToFrontend(const StringView& message) { delegate_->SendMessageToFrontend(message); @@ -279,9 +266,8 @@ class InspectorTimer { InspectorTimer(uv_loop_t* loop, double interval_s, V8InspectorClient::TimerCallback callback, - void* data) : timer_(), - callback_(callback), - data_(data) { + void* data) + : timer_(), callback_(callback), data_(data) { uv_timer_init(loop, &timer_); int64_t interval_ms = 1000 * interval_s; uv_timer_start(&timer_, OnTimer, interval_ms, interval_ms); @@ -301,9 +287,8 @@ class InspectorTimer { } static void TimerClosedCb(uv_handle_t* uvtimer) { - std::unique_ptr timer( - node::ContainerOf(&InspectorTimer::timer_, - reinterpret_cast(uvtimer))); + std::unique_ptr timer(node::ContainerOf( + &InspectorTimer::timer_, reinterpret_cast(uvtimer))); // Unique_ptr goes out of scope here and pointer is deleted. } @@ -318,8 +303,10 @@ class InspectorTimer { class InspectorTimerHandle { public: - InspectorTimerHandle(uv_loop_t* loop, double interval_s, - V8InspectorClient::TimerCallback callback, void* data) { + InspectorTimerHandle(uv_loop_t* loop, + double interval_s, + V8InspectorClient::TimerCallback callback, + void* data) { timer_ = new InspectorTimer(loop, interval_s, callback, data); } @@ -330,14 +317,15 @@ class InspectorTimerHandle { timer_->Stop(); timer_ = nullptr; } + private: InspectorTimer* timer_; }; class SameThreadInspectorSession : public InspectorSession { public: - SameThreadInspectorSession( - int session_id, std::shared_ptr client) + SameThreadInspectorSession(int session_id, + std::shared_ptr client) : session_id_(session_id), client_(client) {} ~SameThreadInspectorSession() override; void Dispatch(const v8_inspector::StringView& message) override; @@ -358,18 +346,22 @@ void NotifyClusterWorkersDebugEnabled(Environment* env) { process_object->Get(context, FIXED_ONE_BYTE_STRING(isolate, "emit")) .ToLocalChecked(); // In case the thread started early during the startup - if (!emit_fn->IsFunction()) - return; + if (!emit_fn->IsFunction()) return; Local message = Object::New(isolate); - message->Set(context, FIXED_ONE_BYTE_STRING(isolate, "cmd"), - FIXED_ONE_BYTE_STRING(isolate, "NODE_DEBUG_ENABLED")).FromJust(); - Local argv[] = { - FIXED_ONE_BYTE_STRING(isolate, "internalMessage"), - message - }; - MakeCallback(env->isolate(), process_object, emit_fn.As(), - arraysize(argv), argv, {0, 0}); + message + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "cmd"), + FIXED_ONE_BYTE_STRING(isolate, "NODE_DEBUG_ENABLED")) + .FromJust(); + Local argv[] = {FIXED_ONE_BYTE_STRING(isolate, "internalMessage"), + message}; + MakeCallback(env->isolate(), + process_object, + emit_fn.As(), + arraysize(argv), + argv, + {0, 0}); } } // namespace @@ -431,9 +423,7 @@ class NodeInspectorClient : public V8InspectorClient { client_->contextDestroyed(context); } - void quitMessageLoopOnPause() override { - waiting_for_resume_ = false; - } + void quitMessageLoopOnPause() override { waiting_for_resume_ = false; } int connectFrontend(std::unique_ptr delegate, bool prevent_shutdown) { @@ -471,9 +461,8 @@ class NodeInspectorClient : public V8InspectorClient { console_api->GetOwnPropertyNames(context).ToLocalChecked(); for (uint32_t i = 0; i < properties->Length(); ++i) { Local key = properties->Get(context, i).ToLocalChecked(); - target->Set(context, - key, - console_api->Get(context, key).ToLocalChecked()).FromJust(); + target->Set(context, key, console_api->Get(context, key).ToLocalChecked()) + .FromJust(); } } @@ -484,8 +473,7 @@ class NodeInspectorClient : public V8InspectorClient { Local stack_trace = message->GetStackTrace(); - if (!stack_trace.IsEmpty() && - stack_trace->GetFrameCount() > 0 && + if (!stack_trace.IsEmpty() && stack_trace->GetFrameCount() > 0 && script_id == stack_trace->GetFrame(0)->GetScriptId()) { script_id = 0; } @@ -509,36 +497,28 @@ class NodeInspectorClient : public V8InspectorClient { void startRepeatingTimer(double interval_s, TimerCallback callback, void* data) override { - timers_.emplace(std::piecewise_construct, std::make_tuple(data), - std::make_tuple(env_->event_loop(), interval_s, callback, - data)); + timers_.emplace( + std::piecewise_construct, + std::make_tuple(data), + std::make_tuple(env_->event_loop(), interval_s, callback, data)); } - void cancelTimer(void* data) override { - timers_.erase(data); - } + void cancelTimer(void* data) override { timers_.erase(data); } // Async stack traces instrumentation. - void AsyncTaskScheduled(const StringView& task_name, void* task, + void AsyncTaskScheduled(const StringView& task_name, + void* task, bool recurring) { client_->asyncTaskScheduled(task_name, task, recurring); } - void AsyncTaskCanceled(void* task) { - client_->asyncTaskCanceled(task); - } + void AsyncTaskCanceled(void* task) { client_->asyncTaskCanceled(task); } - void AsyncTaskStarted(void* task) { - client_->asyncTaskStarted(task); - } + void AsyncTaskStarted(void* task) { client_->asyncTaskStarted(task); } - void AsyncTaskFinished(void* task) { - client_->asyncTaskFinished(task); - } + void AsyncTaskFinished(void* task) { client_->asyncTaskFinished(task); } - void AllAsyncTasksCanceled() { - client_->allAsyncTasksCanceled(); - } + void AllAsyncTasksCanceled() { client_->allAsyncTasksCanceled(); } void schedulePauseOnNextStatement(const std::string& reason) { for (const auto& id_channel : channels_) { @@ -549,37 +529,34 @@ class NodeInspectorClient : public V8InspectorClient { bool hasConnectedSessions() { for (const auto& id_channel : channels_) { // Other sessions are "invisible" more most purposes - if (id_channel.second->preventShutdown()) - return true; + if (id_channel.second->preventShutdown()) return true; } return false; } std::shared_ptr getThreadHandle() { if (interface_ == nullptr) { - interface_.reset(new MainThreadInterface( - env_->inspector_agent(), env_->event_loop(), env_->isolate(), - env_->isolate_data()->platform())); + interface_.reset( + new MainThreadInterface(env_->inspector_agent(), + env_->event_loop(), + env_->isolate(), + env_->isolate_data()->platform())); } return interface_->GetHandle(); } - bool IsActive() { - return !channels_.empty(); - } + bool IsActive() { return !channels_.empty(); } private: bool shouldRunMessageLoop() { - if (waiting_for_frontend_) - return true; + if (waiting_for_frontend_) return true; if (waiting_for_io_shutdown_ || waiting_for_resume_) return hasConnectedSessions(); return false; } void runMessageLoop() { - if (running_nested_loop_) - return; + if (running_nested_loop_) return; running_nested_loop_ = true; @@ -587,14 +564,13 @@ class NodeInspectorClient : public V8InspectorClient { while (shouldRunMessageLoop()) { if (interface_ && hasConnectedSessions()) interface_->WaitForFrontendEvent(); - while (platform->FlushForegroundTasks(env_->isolate())) {} + while (platform->FlushForegroundTasks(env_->isolate())) { + } } running_nested_loop_ = false; } - double currentTimeMS() override { - return uv_hrtime() * 1.0 / NANOS_PER_MSEC; - } + double currentTimeMS() override { return uv_hrtime() * 1.0 / NANOS_PER_MSEC; } node::Environment* env_; bool running_nested_loop_ = false; @@ -619,9 +595,10 @@ bool Agent::Start(const std::string& path, const DebugOptions& options) { debug_options_ = options; client_ = std::make_shared(parent_env_); if (parent_env_->is_main_thread()) { - CHECK_EQ(0, uv_async_init(parent_env_->event_loop(), - &start_io_thread_async, - StartIoThreadAsyncCallback)); + CHECK_EQ(0, + uv_async_init(parent_env_->event_loop(), + &start_io_thread_async, + StartIoThreadAsyncCallback)); uv_unref(reinterpret_cast(&start_io_thread_async)); start_io_thread_async.data = this; // Ignore failure, SIGUSR1 won't work, but that should not block node start. @@ -634,11 +611,12 @@ bool Agent::Start(const std::string& path, const DebugOptions& options) { } if (wait_for_connect) { HandleScope scope(parent_env_->isolate()); - parent_env_->process_object()->DefineOwnProperty( - parent_env_->context(), - FIXED_ONE_BYTE_STRING(parent_env_->isolate(), "_breakFirstLine"), - True(parent_env_->isolate()), - static_cast(v8::ReadOnly | v8::DontEnum)) + parent_env_->process_object() + ->DefineOwnProperty( + parent_env_->context(), + FIXED_ONE_BYTE_STRING(parent_env_->isolate(), "_breakFirstLine"), + True(parent_env_->isolate()), + static_cast(v8::ReadOnly | v8::DontEnum)) .FromJust(); client_->waitForFrontend(); } @@ -646,13 +624,11 @@ bool Agent::Start(const std::string& path, const DebugOptions& options) { } bool Agent::StartIoThread() { - if (io_ != nullptr) - return true; + if (io_ != nullptr) return true; CHECK_NOT_NULL(client_); - io_ = InspectorIo::Start( - client_->getThreadHandle(), path_, debug_options_); + io_ = InspectorIo::Start(client_->getThreadHandle(), path_, debug_options_); if (io_ == nullptr) { return false; } @@ -665,11 +641,10 @@ void Agent::Stop() { } std::unique_ptr Agent::Connect( - std::unique_ptr delegate, - bool prevent_shutdown) { + std::unique_ptr delegate, bool prevent_shutdown) { CHECK_NOT_NULL(client_); - int session_id = client_->connectFrontend(std::move(delegate), - prevent_shutdown); + int session_id = + client_->connectFrontend(std::move(delegate), prevent_shutdown); return std::unique_ptr( new SameThreadInspectorSession(session_id, client_)); } @@ -690,8 +665,7 @@ void Agent::WaitForDisconnect() { } void Agent::FatalException(Local error, Local message) { - if (!IsListening()) - return; + if (!IsListening()) return; client_->FatalException(error, message); WaitForDisconnect(); } @@ -745,13 +719,13 @@ void Agent::ToggleAsyncHook(Isolate* isolate, auto context = parent_env_->context(); auto result = fn.Get(isolate)->Call(context, Undefined(isolate), 0, nullptr); if (result.IsEmpty()) { - FatalError( - "node::inspector::Agent::ToggleAsyncHook", - "Cannot toggle Inspector's AsyncHook, please report this."); + FatalError("node::inspector::Agent::ToggleAsyncHook", + "Cannot toggle Inspector's AsyncHook, please report this."); } } -void Agent::AsyncTaskScheduled(const StringView& task_name, void* task, +void Agent::AsyncTaskScheduled(const StringView& task_name, + void* task, bool recurring) { client_->AsyncTaskScheduled(task_name, task, recurring); } @@ -795,8 +769,7 @@ bool Agent::WillWaitForConnect() { } bool Agent::IsActive() { - if (client_ == nullptr) - return false; + if (client_ == nullptr) return false; return io_ != nullptr || client_->IsActive(); } @@ -807,18 +780,14 @@ void Agent::WaitForConnect() { SameThreadInspectorSession::~SameThreadInspectorSession() { auto client = client_.lock(); - if (client) - client->disconnectFrontend(session_id_); + if (client) client->disconnectFrontend(session_id_); } void SameThreadInspectorSession::Dispatch( const v8_inspector::StringView& message) { auto client = client_.lock(); - if (client) - client->dispatchMessageFromFrontend(session_id_, message); + if (client) client->dispatchMessageFromFrontend(session_id_, message); } - - } // namespace inspector } // namespace node diff --git a/src/inspector_agent.h b/src/inspector_agent.h index dcd6e13aba275f..e17fc774fbb61b 100644 --- a/src/inspector_agent.h +++ b/src/inspector_agent.h @@ -35,8 +35,8 @@ class InspectorSession { class InspectorSessionDelegate { public: virtual ~InspectorSessionDelegate() = default; - virtual void SendMessageToFrontend(const v8_inspector::StringView& message) - = 0; + virtual void SendMessageToFrontend( + const v8_inspector::StringView& message) = 0; }; class Agent { @@ -65,7 +65,8 @@ class Agent { v8::Local message); // Async stack traces instrumentation. - void AsyncTaskScheduled(const v8_inspector::StringView& taskName, void* task, + void AsyncTaskScheduled(const v8_inspector::StringView& taskName, + void* task, bool recurring); void AsyncTaskCanceled(void* task); void AsyncTaskStarted(void* task); @@ -73,8 +74,8 @@ class Agent { void AllAsyncTasksCanceled(); void RegisterAsyncHook(v8::Isolate* isolate, - v8::Local enable_function, - v8::Local disable_function); + v8::Local enable_function, + v8::Local disable_function); void EnableAsyncHook(); void DisableAsyncHook(); @@ -86,9 +87,7 @@ class Agent { void PauseOnNextJavascriptStatement(const std::string& reason); - InspectorIo* io() { - return io_.get(); - } + InspectorIo* io() { return io_.get(); } // Can only be called from the main thread. bool StartIoThread(); diff --git a/src/inspector_io.cc b/src/inspector_io.cc index 41fea546a83265..8da3dc1db95a92 100644 --- a/src/inspector_io.cc +++ b/src/inspector_io.cc @@ -1,19 +1,19 @@ #include "inspector_io.h" -#include "inspector_socket_server.h" +#include "debug_utils.h" +#include "env-inl.h" #include "inspector/main_thread_interface.h" #include "inspector/node_string.h" -#include "env-inl.h" -#include "debug_utils.h" +#include "inspector_socket_server.h" #include "node.h" #include "node_crypto.h" #include "node_mutex.h" -#include "v8-inspector.h" #include "util.h" +#include "v8-inspector.h" #include "zlib.h" -#include #include +#include #include namespace node { @@ -46,13 +46,15 @@ std::string GenerateID() { sizeof(buffer))); char uuid[256]; - snprintf(uuid, sizeof(uuid), "%04x%04x-%04x-%04x-%04x-%04x%04x%04x", - buffer[0], // time_low - buffer[1], // time_mid - buffer[2], // time_low + snprintf(uuid, + sizeof(uuid), + "%04x%04x-%04x-%04x-%04x-%04x%04x%04x", + buffer[0], // time_low + buffer[1], // time_mid + buffer[2], // time_low (buffer[3] & 0x0fff) | 0x4000, // time_hi_and_version (buffer[4] & 0x3fff) | 0x8000, // clk_seq_hi clk_seq_low - buffer[5], // node + buffer[5], // node buffer[6], buffer[7]); return uuid; @@ -63,9 +65,9 @@ class RequestToServer { RequestToServer(TransportAction action, int session_id, std::unique_ptr message) - : action_(action), - session_id_(session_id), - message_(std::move(message)) {} + : action_(action), + session_id_(session_id), + message_(std::move(message)) {} void Dispatch(InspectorSocketServer* server) const { switch (action_) { @@ -94,7 +96,7 @@ class RequestQueueData { using MessageQueue = std::deque; explicit RequestQueueData(uv_loop_t* loop) - : handle_(std::make_shared(this)) { + : handle_(std::make_shared(this)) { int err = uv_async_init(loop, &async_, [](uv_async_t* async) { RequestQueueData* wrapper = node::ContainerOf(&RequestQueueData::async_, async); @@ -124,13 +126,9 @@ class RequestQueueData { } } - void SetServer(InspectorSocketServer* server) { - server_ = server; - } + void SetServer(InspectorSocketServer* server) { server_ = server; } - std::shared_ptr handle() { - return handle_; - } + std::shared_ptr handle() { return handle_; } private: ~RequestQueueData() = default; @@ -143,8 +141,7 @@ class RequestQueueData { } void DoDispatch() { - if (server_ == nullptr) - return; + if (server_ == nullptr) return; for (const auto& request : GetMessages()) { request.Dispatch(server_); } @@ -172,14 +169,12 @@ class RequestQueue { TransportAction action, std::unique_ptr message) { Mutex::ScopedLock scoped_lock(lock_); - if (data_ != nullptr) - data_->Post(session_id, action, std::move(message)); + if (data_ != nullptr) data_->Post(session_id, action, std::move(message)); } void SetServer(InspectorSocketServer* server) { Mutex::ScopedLock scoped_lock(lock_); - if (data_ != nullptr) - data_->SetServer(server); + if (data_ != nullptr) data_->SetServer(server); } bool Expired() { @@ -195,10 +190,10 @@ class RequestQueue { class IoSessionDelegate : public InspectorSessionDelegate { public: explicit IoSessionDelegate(std::shared_ptr queue, int id) - : request_queue_(queue), id_(id) { } + : request_queue_(queue), id_(id) {} void SendMessageToFrontend(const v8_inspector::StringView& message) override { - request_queue_->Post(id_, TransportAction::kSendMessage, - StringBuffer::create(message)); + request_queue_->Post( + id_, TransportAction::kSendMessage, StringBuffer::create(message)); } private: @@ -208,15 +203,14 @@ class IoSessionDelegate : public InspectorSessionDelegate { // Passed to InspectorSocketServer to handle WS inspector protocol events, // mostly session start, message received, and session end. -class InspectorIoDelegate: public node::inspector::SocketServerDelegate { +class InspectorIoDelegate : public node::inspector::SocketServerDelegate { public: InspectorIoDelegate(std::shared_ptr queue, std::shared_ptr main_threade, const std::string& target_id, const std::string& script_path, const std::string& script_name); - ~InspectorIoDelegate() { - } + ~InspectorIoDelegate() {} void StartSession(int session_id, const std::string& target_id) override; void MessageReceived(int session_id, const std::string& message) override; @@ -243,8 +237,8 @@ std::unique_ptr InspectorIo::Start( std::shared_ptr main_thread, const std::string& path, const DebugOptions& options) { - auto io = std::unique_ptr( - new InspectorIo(main_thread, path, options)); + auto io = + std::unique_ptr(new InspectorIo(main_thread, path, options)); if (io->request_queue_->Expired()) { // Thread is not running return nullptr; } @@ -254,8 +248,11 @@ std::unique_ptr InspectorIo::Start( InspectorIo::InspectorIo(std::shared_ptr main_thread, const std::string& path, const DebugOptions& options) - : main_thread_(main_thread), options_(options), - thread_(), script_name_(path), id_(GenerateID()) { + : main_thread_(main_thread), + options_(options), + thread_(), + script_name_(path), + id_(GenerateID()) { Mutex::ScopedLock scoped_lock(thread_start_lock_); CHECK_EQ(uv_thread_create(&thread_, InspectorIo::ThreadMain, this), 0); thread_start_condition_.Wait(scoped_lock); @@ -284,11 +281,10 @@ void InspectorIo::ThreadMain() { std::shared_ptr queue(new RequestQueueData(&loop), RequestQueueData::CloseAndFree); std::string script_path = ScriptPath(&loop, script_name_); - std::unique_ptr delegate( - new InspectorIoDelegate(queue, main_thread_, id_, - script_path, script_name_)); - InspectorSocketServer server(std::move(delegate), &loop, - options_.host_name(), options_.port()); + std::unique_ptr delegate(new InspectorIoDelegate( + queue, main_thread_, id_, script_path, script_name_)); + InspectorSocketServer server( + std::move(delegate), &loop, options_.host_name(), options_.port()); request_queue_ = queue->handle(); // Its lifetime is now that of the server delegate queue.reset(); @@ -304,7 +300,7 @@ void InspectorIo::ThreadMain() { } std::vector InspectorIo::GetTargetIds() const { - return { id_ }; + return {id_}; } InspectorIoDelegate::InspectorIoDelegate( @@ -313,15 +309,18 @@ InspectorIoDelegate::InspectorIoDelegate( const std::string& target_id, const std::string& script_path, const std::string& script_name) - : request_queue_(queue), main_thread_(main_thread), - script_name_(script_name), script_path_(script_path), + : request_queue_(queue), + main_thread_(main_thread), + script_name_(script_name), + script_path_(script_path), target_id_(target_id) {} void InspectorIoDelegate::StartSession(int session_id, const std::string& target_id) { auto session = main_thread_->Connect( std::unique_ptr( - new IoSessionDelegate(request_queue_->handle(), session_id)), true); + new IoSessionDelegate(request_queue_->handle(), session_id)), + true); if (session) { sessions_[session_id] = std::move(session); fprintf(stderr, "Debugger attached.\n"); @@ -340,7 +339,7 @@ void InspectorIoDelegate::EndSession(int session_id) { } std::vector InspectorIoDelegate::GetTargetIds() { - return { target_id_ }; + return {target_id_}; } std::string InspectorIoDelegate::GetTargetTitle(const std::string& id) { @@ -357,11 +356,11 @@ void RequestQueueData::CloseAndFree(RequestQueueData* queue) { queue->handle_.reset(); uv_close(reinterpret_cast(&queue->async_), [](uv_handle_t* handle) { - uv_async_t* async = reinterpret_cast(handle); - RequestQueueData* wrapper = - node::ContainerOf(&RequestQueueData::async_, async); - delete wrapper; - }); + uv_async_t* async = reinterpret_cast(handle); + RequestQueueData* wrapper = + node::ContainerOf(&RequestQueueData::async_, async); + delete wrapper; + }); } } // namespace inspector } // namespace node diff --git a/src/inspector_io.h b/src/inspector_io.h index 7c43d212f0422e..a1e53cc89f7d88 100644 --- a/src/inspector_io.h +++ b/src/inspector_io.h @@ -6,14 +6,13 @@ #include "node_mutex.h" #include "uv.h" -#include #include +#include #if !HAVE_INSPECTOR #error("This header can only be used when inspector is enabled") #endif - namespace v8_inspector { class StringBuffer; class StringView; @@ -24,7 +23,8 @@ namespace node { class Environment; namespace inspector { -std::string FormatWsAddress(const std::string& host, int port, +std::string FormatWsAddress(const std::string& host, + int port, const std::string& target_id, bool include_protocol); @@ -33,11 +33,7 @@ class MainThreadHandle; class RequestQueue; // kKill closes connections and stops the server, kStop only stops the server -enum class TransportAction { - kKill, - kSendMessage, - kStop -}; +enum class TransportAction { kKill, kSendMessage, kStop }; class InspectorIo { public: @@ -45,7 +41,8 @@ class InspectorIo { // bool Start(); // Returns empty pointer if thread was not started static std::unique_ptr Start( - std::shared_ptr main_thread, const std::string& path, + std::shared_ptr main_thread, + const std::string& path, const DebugOptions& options); // Will block till the transport thread shuts down @@ -58,7 +55,8 @@ class InspectorIo { private: InspectorIo(std::shared_ptr handle, - const std::string& path, const DebugOptions& options); + const std::string& path, + const DebugOptions& options); // Wrapper for agent->ThreadMain() static void ThreadMain(void* agent); diff --git a/src/inspector_js_api.cc b/src/inspector_js_api.cc index 4e95598d3a0580..6a38f415360119 100644 --- a/src/inspector_js_api.cc +++ b/src/inspector_js_api.cc @@ -2,8 +2,8 @@ #include "inspector_agent.h" #include "inspector_io.h" #include "node_internals.h" -#include "v8.h" #include "v8-inspector.h" +#include "v8.h" namespace node { namespace inspector { @@ -38,18 +38,18 @@ class JSBindingsConnection : public AsyncWrap { public: JSBindingsSessionDelegate(Environment* env, JSBindingsConnection* connection) - : env_(env), - connection_(connection) { - } + : env_(env), connection_(connection) {} - void SendMessageToFrontend(const v8_inspector::StringView& message) - override { + void SendMessageToFrontend( + const v8_inspector::StringView& message) override { Isolate* isolate = env_->isolate(); HandleScope handle_scope(isolate); Context::Scope context_scope(env_->context()); MaybeLocal v8string = - String::NewFromTwoByte(isolate, message.characters16(), - NewStringType::kNormal, message.length()); + String::NewFromTwoByte(isolate, + message.characters16(), + NewStringType::kNormal, + message.length()); Local argument = v8string.ToLocalChecked().As(); connection_->OnMessage(argument); } @@ -62,11 +62,12 @@ class JSBindingsConnection : public AsyncWrap { JSBindingsConnection(Environment* env, Local wrap, Local callback) - : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING), - callback_(env->isolate(), callback) { + : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING), + callback_(env->isolate(), callback) { Agent* inspector = env->inspector_agent(); session_ = inspector->Connect(std::unique_ptr( - new JSBindingsSessionDelegate(env, this)), false); + new JSBindingsSessionDelegate(env, this)), + false); } void OnMessage(Local value) { @@ -139,9 +140,8 @@ void CallAndPauseOnStart(const FunctionCallbackInfo& args) { CHECK(args[0]->IsFunction()); SlicedArguments call_args(args, /* start */ 2); env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start"); - v8::MaybeLocal retval = - args[0].As()->Call(env->context(), args[1], - call_args.size(), call_args.data()); + v8::MaybeLocal retval = args[0].As()->Call( + env->context(), args[1], call_args.size(), call_args.data()); if (!retval.IsEmpty()) { args.GetReturnValue().Set(retval.ToLocalChecked()); } @@ -162,23 +162,21 @@ void InspectorConsoleCall(const FunctionCallbackInfo& info) { Local config_object = config_value.As(); Local in_call_key = FIXED_ONE_BYTE_STRING(isolate, "in_call"); if (!config_object->Has(context, in_call_key).FromMaybe(false)) { - CHECK(config_object->Set(context, - in_call_key, - v8::True(isolate)).FromJust()); - CHECK(!inspector_method.As()->Call(context, - info.Holder(), - call_args.size(), - call_args.data()).IsEmpty()); + CHECK(config_object->Set(context, in_call_key, v8::True(isolate)) + .FromJust()); + CHECK(!inspector_method.As() + ->Call( + context, info.Holder(), call_args.size(), call_args.data()) + .IsEmpty()); } CHECK(config_object->Delete(context, in_call_key).FromJust()); } Local node_method = info[1]; CHECK(node_method->IsFunction()); - node_method.As()->Call(context, - info.Holder(), - call_args.size(), - call_args.data()).FromMaybe(Local()); + node_method.As() + ->Call(context, info.Holder(), call_args.size(), call_args.data()) + .FromMaybe(Local()); } static void* GetAsyncTask(int64_t asyncId) { @@ -226,8 +224,8 @@ static void RegisterAsyncHookWrapper(const FunctionCallbackInfo& args) { v8::Local enable_function = args[0].As(); CHECK(args[1]->IsFunction()); v8::Local disable_function = args[1].As(); - env->inspector_agent()->RegisterAsyncHook(env->isolate(), - enable_function, disable_function); + env->inspector_agent()->RegisterAsyncHook( + env->isolate(), enable_function, disable_function); } void IsEnabled(const FunctionCallbackInfo& args) { @@ -254,8 +252,7 @@ void Open(const FunctionCallbackInfo& args) { wait_for_connect = args[2]->BooleanValue(env->context()).FromJust(); } agent->StartIoThread(); - if (wait_for_connect) - agent->WaitForConnect(); + if (wait_for_connect) agent->WaitForConnect(); } void Url(const FunctionCallbackInfo& args) { @@ -273,8 +270,10 @@ void Url(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(OneByteString(env->isolate(), url.c_str())); } -void Initialize(Local target, Local unused, - Local context, void* priv) { +void Initialize(Local target, + Local unused, + Local context, + void* priv) { Environment* env = Environment::GetCurrent(context); { auto obj = Object::New(env->isolate()); @@ -292,12 +291,15 @@ void Initialize(Local target, Local unused, env->SetMethodNoSideEffect(target, "url", Url); env->SetMethod(target, "asyncTaskScheduled", AsyncTaskScheduledWrapper); - env->SetMethod(target, "asyncTaskCanceled", - InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>); - env->SetMethod(target, "asyncTaskStarted", - InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>); - env->SetMethod(target, "asyncTaskFinished", - InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>); + env->SetMethod(target, + "asyncTaskCanceled", + InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>); + env->SetMethod(target, + "asyncTaskStarted", + InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>); + env->SetMethod(target, + "asyncTaskFinished", + InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>); env->SetMethod(target, "registerAsyncHook", RegisterAsyncHookWrapper); env->SetMethodNoSideEffect(target, "isEnabled", IsEnabled); @@ -317,5 +319,4 @@ void Initialize(Local target, Local unused, } // namespace inspector } // namespace node -NODE_BUILTIN_MODULE_CONTEXT_AWARE(inspector, - node::inspector::Initialize); +NODE_BUILTIN_MODULE_CONTEXT_AWARE(inspector, node::inspector::Initialize); diff --git a/src/inspector_socket.cc b/src/inspector_socket.cc index dc36359b5c927c..ede3070b63e98a 100644 --- a/src/inspector_socket.cc +++ b/src/inspector_socket.cc @@ -8,8 +8,8 @@ #include "openssl/sha.h" // Sha-1 hash -#include #include +#include #define ACCEPT_KEY_LENGTH base64_encoded_size(20) #define BUFFER_GROWTH_CHUNK_SIZE 1024 @@ -29,9 +29,7 @@ class TcpHolder { InspectorSocket::DelegatePointer delegate); void SetHandler(ProtocolHandler* handler); int WriteRaw(const std::vector& buffer, uv_write_cb write_cb); - uv_tcp_t* tcp() { - return &tcp_; - } + uv_tcp_t* tcp() { return &tcp_; } InspectorSocket::Delegate* delegate(); private: @@ -40,7 +38,8 @@ class TcpHolder { reinterpret_cast(handle)); } static void OnClosed(uv_handle_t* handle); - static void OnDataReceivedCb(uv_stream_t* stream, ssize_t nread, + static void OnDataReceivedCb(uv_stream_t* stream, + ssize_t nread, const uv_buf_t* buf); explicit TcpHolder(InspectorSocket::DelegatePointer delegate); ~TcpHolder() = default; @@ -52,7 +51,6 @@ class TcpHolder { std::vector buffer; }; - class ProtocolHandler { public: ProtocolHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp); @@ -65,9 +63,7 @@ class ProtocolHandler { std::string GetHost() const; - InspectorSocket* inspector() { - return inspector_; - } + InspectorSocket* inspector() { return inspector_; } virtual void Shutdown() = 0; protected: @@ -110,10 +106,10 @@ static void dump_hex(const char* buf, size_t len) { class WriteRequest { public: WriteRequest(ProtocolHandler* handler, const std::vector& buffer) - : handler(handler) - , storage(buffer) - , req(uv_write_t()) - , buf(uv_buf_init(storage.data(), storage.size())) {} + : handler(handler), + storage(buffer), + req(uv_write_t()), + buf(uv_buf_init(storage.data(), storage.size())) {} static WriteRequest* from_write_req(uv_write_t* req) { return node::ContainerOf(&WriteRequest::req, req); @@ -139,9 +135,7 @@ static void remove_from_beginning(std::vector* buffer, size_t count) { static const char CLOSE_FRAME[] = {'\x88', '\x00'}; -enum ws_decode_result { - FRAME_OK, FRAME_INCOMPLETE, FRAME_CLOSE, FRAME_ERROR -}; +enum ws_decode_result { FRAME_OK, FRAME_INCOMPLETE, FRAME_CLOSE, FRAME_ERROR }; static void generate_accept_string(const std::string& client_key, char (*buffer)[ACCEPT_KEY_LENGTH]) { @@ -149,15 +143,15 @@ static void generate_accept_string(const std::string& client_key, static const char ws_magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string input(client_key + ws_magic); char hash[SHA_DIGEST_LENGTH]; - SHA1(reinterpret_cast(&input[0]), input.size(), + SHA1(reinterpret_cast(&input[0]), + input.size(), reinterpret_cast(hash)); node::base64_encode(hash, sizeof(hash), *buffer, sizeof(*buffer)); } static std::string TrimPort(const std::string& host) { size_t last_colon_pos = host.rfind(":"); - if (last_colon_pos == std::string::npos) - return host; + if (last_colon_pos == std::string::npos) return host; size_t bracket = host.rfind("]"); if (bracket == std::string::npos || last_colon_pos > bracket) return host.substr(0, last_colon_pos); @@ -221,8 +215,8 @@ static std::vector encode_frame_hybi17(const std::vector& message) { extended_payload_length[7 - i] = remaining & 0xFF; remaining >>= 8; } - frame.insert(frame.end(), extended_payload_length, - extended_payload_length + 8); + frame.insert( + frame.end(), extended_payload_length, extended_payload_length + 8); CHECK_EQ(0, remaining); } frame.insert(frame.end(), message.begin(), message.end()); @@ -235,8 +229,7 @@ static ws_decode_result decode_frame_hybi17(const std::vector& buffer, std::vector* output, bool* compressed) { *bytes_consumed = 0; - if (buffer.size() < 2) - return FRAME_INCOMPLETE; + if (buffer.size() < 2) return FRAME_INCOMPLETE; auto it = buffer.begin(); @@ -319,18 +312,17 @@ static ws_decode_result decode_frame_hybi17(const std::vector& buffer, class WsHandler : public ProtocolHandler { public: WsHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp) - : ProtocolHandler(inspector, std::move(tcp)), - OnCloseSent(&WsHandler::WaitForCloseReply), - OnCloseRecieved(&WsHandler::CloseFrameReceived), - dispose_(false) { } + : ProtocolHandler(inspector, std::move(tcp)), + OnCloseSent(&WsHandler::WaitForCloseReply), + OnCloseRecieved(&WsHandler::CloseFrameReceived), + dispose_(false) {} - void AcceptUpgrade(const std::string& accept_key) override { } + void AcceptUpgrade(const std::string& accept_key) override {} void CancelHandshake() override {} void OnEof() override { tcp_.reset(); - if (dispose_) - delete this; + if (dispose_) delete this; } void OnData(std::vector* data) override { @@ -371,9 +363,7 @@ class WsHandler : public ProtocolHandler { (handler->*cb)(); } - void WaitForCloseReply() { - OnCloseRecieved = &WsHandler::OnEof; - } + void WaitForCloseReply() { OnCloseRecieved = &WsHandler::OnEof; } void SendClose() { WriteRaw(std::vector(CLOSE_FRAME, CLOSE_FRAME + sizeof(CLOSE_FRAME)), @@ -390,10 +380,8 @@ class WsHandler : public ProtocolHandler { std::vector output; bool compressed = false; - ws_decode_result r = decode_frame_hybi17(buffer, - true /* client_frame */, - &bytes_consumed, &output, - &compressed); + ws_decode_result r = decode_frame_hybi17( + buffer, true /* client_frame */, &bytes_consumed, &output, &compressed); // Compressed frame means client is ignoring the headers and misbehaves if (compressed || r == FRAME_ERROR) { OnEof(); @@ -407,7 +395,6 @@ class WsHandler : public ProtocolHandler { return bytes_consumed; } - Callback OnCloseSent; Callback OnCloseRecieved; bool dispose_; @@ -416,10 +403,16 @@ class WsHandler : public ProtocolHandler { // HTTP protocol class HttpEvent { public: - HttpEvent(const std::string& path, bool upgrade, bool isGET, - const std::string& ws_key, const std::string& host) - : path(path), upgrade(upgrade), isGET(isGET), ws_key(ws_key), - host(host) { } + HttpEvent(const std::string& path, + bool upgrade, + bool isGET, + const std::string& ws_key, + const std::string& host) + : path(path), + upgrade(upgrade), + isGET(isGET), + ws_key(ws_key), + host(host) {} std::string path; bool upgrade; @@ -431,8 +424,7 @@ class HttpEvent { class HttpHandler : public ProtocolHandler { public: explicit HttpHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp) - : ProtocolHandler(inspector, std::move(tcp)), - parsing_value_(false) { + : ProtocolHandler(inspector, std::move(tcp)), parsing_value_(false) { http_parser_init(&parser_, HTTP_REQUEST); http_parser_settings_init(&parser_settings); parser_settings.on_header_field = OnHeaderField; @@ -451,9 +443,10 @@ class HttpHandler : public ProtocolHandler { const char accept_ws_suffix[] = "\r\n\r\n"; std::vector reply(accept_ws_prefix, accept_ws_prefix + sizeof(accept_ws_prefix) - 1); - reply.insert(reply.end(), accept_string, - accept_string + sizeof(accept_string)); - reply.insert(reply.end(), accept_ws_suffix, + reply.insert( + reply.end(), accept_string, accept_string + sizeof(accept_string)); + reply.insert(reply.end(), + accept_ws_suffix, accept_ws_suffix + sizeof(accept_ws_suffix) - 1); if (WriteRaw(reply, WriteRequest::Cleanup) >= 0) { inspector_->SwitchProtocol(new WsHandler(inspector_, std::move(tcp_))); @@ -468,14 +461,12 @@ class HttpHandler : public ProtocolHandler { "Content-Type: text/html; charset=UTF-8\r\n\r\n" "WebSockets request was expected\r\n"; WriteRaw(std::vector(HANDSHAKE_FAILED_RESPONSE, - HANDSHAKE_FAILED_RESPONSE + sizeof(HANDSHAKE_FAILED_RESPONSE) - 1), + HANDSHAKE_FAILED_RESPONSE + + sizeof(HANDSHAKE_FAILED_RESPONSE) - 1), ThenCloseAndReportFailure); } - - void OnEof() override { - tcp_.reset(); - } + void OnEof() override { tcp_.reset(); } void OnData(std::vector* data) override { http_parser_execute(&parser_, &parser_settings, data->data(), data->size()); @@ -506,9 +497,7 @@ class HttpHandler : public ProtocolHandler { } protected: - void Shutdown() override { - delete this; - } + void Shutdown() override { delete this; } private: static void ThenCloseAndReportFailure(uv_write_t* req, int status) { @@ -548,7 +537,9 @@ class HttpHandler : public ProtocolHandler { // Event needs to be fired after the parser is done. HttpHandler* handler = From(parser); handler->events_.push_back( - HttpEvent(handler->path_, parser->upgrade, parser->method == HTTP_GET, + HttpEvent(handler->path_, + parser->upgrade, + parser->method == HTTP_GET, handler->HeaderValue("Sec-WebSocket-Key"), handler->HeaderValue("Host"))); handler->path_ = ""; @@ -562,10 +553,9 @@ class HttpHandler : public ProtocolHandler { bool header_found = false; std::string value; for (const auto& header_value : headers_) { - if (node::StringEqualNoCaseN(header_value.first.data(), header.data(), - header.length())) { - if (header_found) - return ""; + if (node::StringEqualNoCaseN( + header_value.first.data(), header.data(), header.length())) { + if (header_found) return ""; value = header_value.second; header_found = true; } @@ -575,9 +565,9 @@ class HttpHandler : public ProtocolHandler { bool IsAllowedHost(const std::string& host_with_port) const { std::string host = TrimPort(host_with_port); - return host.empty() || IsIPAddress(host) - || node::StringEqualNoCase(host.data(), "localhost") - || node::StringEqualNoCase(host.data(), "localhost6"); + return host.empty() || IsIPAddress(host) || + node::StringEqualNoCase(host.data(), "localhost") || + node::StringEqualNoCase(host.data(), "localhost6"); } bool parsing_value_; @@ -594,7 +584,7 @@ class HttpHandler : public ProtocolHandler { // Any protocol ProtocolHandler::ProtocolHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp) - : inspector_(inspector), tcp_(std::move(tcp)) { + : inspector_(inspector), tcp_(std::move(tcp)) { CHECK_NOT_NULL(tcp_); tcp_->SetHandler(this); } @@ -612,11 +602,9 @@ std::string ProtocolHandler::GetHost() const { char ip[INET6_ADDRSTRLEN]; sockaddr_storage addr; int len = sizeof(addr); - int err = uv_tcp_getsockname(tcp_->tcp(), - reinterpret_cast(&addr), - &len); - if (err != 0) - return ""; + int err = uv_tcp_getsockname( + tcp_->tcp(), reinterpret_cast(&addr), &len); + if (err != 0) return ""; if (addr.ss_family == AF_INET6) { const sockaddr_in6* v6 = reinterpret_cast(&addr); err = uv_ip6_name(v6, ip, sizeof(ip)); @@ -624,21 +612,17 @@ std::string ProtocolHandler::GetHost() const { const sockaddr_in* v4 = reinterpret_cast(&addr); err = uv_ip4_name(v4, ip, sizeof(ip)); } - if (err != 0) - return ""; + if (err != 0) return ""; return ip; } // RAII uv_tcp_t wrapper TcpHolder::TcpHolder(InspectorSocket::DelegatePointer delegate) - : tcp_(), - delegate_(std::move(delegate)), - handler_(nullptr) { } + : tcp_(), delegate_(std::move(delegate)), handler_(nullptr) {} // static TcpHolder::Pointer TcpHolder::Accept( - uv_stream_t* server, - InspectorSocket::DelegatePointer delegate) { + uv_stream_t* server, InspectorSocket::DelegatePointer delegate) { TcpHolder* result = new TcpHolder(std::move(delegate)); uv_stream_t* tcp = reinterpret_cast(&result->tcp_); int err = uv_tcp_init(server->loop, &result->tcp_); @@ -671,8 +655,7 @@ int TcpHolder::WriteRaw(const std::vector& buffer, uv_write_cb write_cb) { WriteRequest* wr = new WriteRequest(handler_, buffer); uv_stream_t* stream = reinterpret_cast(&tcp_); int err = uv_write(&wr->req, stream, &wr->buf, 1, write_cb); - if (err < 0) - delete wr; + if (err < 0) delete wr; return err < 0; } @@ -685,7 +668,8 @@ void TcpHolder::OnClosed(uv_handle_t* handle) { delete From(handle); } -void TcpHolder::OnDataReceivedCb(uv_stream_t* tcp, ssize_t nread, +void TcpHolder::OnDataReceivedCb(uv_stream_t* tcp, + ssize_t nread, const uv_buf_t* buf) { #if DUMP_READS if (nread >= 0) { diff --git a/src/inspector_socket.h b/src/inspector_socket.h index ae49d78ff3452a..715ae1dcebc48e 100644 --- a/src/inspector_socket.h +++ b/src/inspector_socket.h @@ -48,9 +48,7 @@ class InspectorSocket { DISALLOW_COPY_AND_ASSIGN(InspectorSocket); }; - } // namespace inspector } // namespace node - #endif // SRC_INSPECTOR_SOCKET_H_ diff --git a/src/inspector_socket_server.cc b/src/inspector_socket_server.cc index 1621b408b43274..287c27df955099 100644 --- a/src/inspector_socket_server.cc +++ b/src/inspector_socket_server.cc @@ -14,13 +14,14 @@ namespace inspector { // Function is declared in inspector_io.h so the rest of the node does not // depend on inspector_socket_server.h -std::string FormatWsAddress(const std::string& host, int port, +std::string FormatWsAddress(const std::string& host, + int port, const std::string& target_id, bool include_protocol); namespace { static const uint8_t PROTOCOL_JSON[] = { - #include "v8_inspector_protocol_json.h" // NOLINT(build/include_order) +#include "v8_inspector_protocol_json.h" // NOLINT(build/include_order) }; void Escape(std::string* string) { @@ -48,8 +49,7 @@ std::string FormatAddress(const std::string& host, const std::string& target_id, bool include_protocol) { std::ostringstream url; - if (include_protocol) - url << "ws://"; + if (include_protocol) url << "ws://"; url << host << '/' << target_id; return url.str(); } @@ -59,8 +59,7 @@ std::string MapToString(const std::map& object) { std::ostringstream json; json << "{\n"; for (const auto& name_value : object) { - if (!first) - json << ",\n"; + if (!first) json << ",\n"; first = false; json << " \"" << name_value.first << "\": \""; json << name_value.second << "\""; @@ -75,8 +74,7 @@ std::string MapsToString( std::ostringstream json; json << "[ "; for (const auto& object : array) { - if (!first) - json << ", "; + if (!first) json << ", "; first = false; json << MapToString(object); } @@ -101,11 +99,11 @@ void PrintDebuggerReadyMessage(const std::string& host, return; } for (const std::string& id : ids) { - fprintf(out, "Debugger listening on %s\n", + fprintf(out, + "Debugger listening on %s\n", FormatWsAddress(host, port, id, true).c_str()); } - fprintf(out, "For help, see: %s\n", - "https://nodejs.org/en/docs/inspector"); + fprintf(out, "For help, see: %s\n", "https://nodejs.org/en/docs/inspector"); fflush(out); } @@ -134,10 +132,9 @@ void SendProtocolJson(InspectorSocket* socket) { strm.zfree = Z_NULL; strm.opaque = Z_NULL; CHECK_EQ(Z_OK, inflateInit(&strm)); - static const size_t kDecompressedSize = - PROTOCOL_JSON[0] * 0x10000u + - PROTOCOL_JSON[1] * 0x100u + - PROTOCOL_JSON[2]; + static const size_t kDecompressedSize = PROTOCOL_JSON[0] * 0x10000u + + PROTOCOL_JSON[1] * 0x100u + + PROTOCOL_JSON[2]; strm.next_in = const_cast(PROTOCOL_JSON + 3); strm.avail_in = sizeof(PROTOCOL_JSON) - 3; std::string data(kDecompressedSize, '\0'); @@ -150,7 +147,8 @@ void SendProtocolJson(InspectorSocket* socket) { } } // namespace -std::string FormatWsAddress(const std::string& host, int port, +std::string FormatWsAddress(const std::string& host, + int port, const std::string& target_id, bool include_protocol) { return FormatAddress(FormatHostPort(host, port), target_id, include_protocol); @@ -159,43 +157,30 @@ std::string FormatWsAddress(const std::string& host, int port, class SocketSession { public: SocketSession(InspectorSocketServer* server, int id, int server_port); - void Close() { - ws_socket_.reset(); - } + void Close() { ws_socket_.reset(); } void Send(const std::string& message); void Own(InspectorSocket::Pointer ws_socket) { ws_socket_ = std::move(ws_socket); } int id() const { return id_; } - int server_port() { - return server_port_; - } - InspectorSocket* ws_socket() { - return ws_socket_.get(); - } - void Accept(const std::string& ws_key) { - ws_socket_->AcceptUpgrade(ws_key); - } - void Decline() { - ws_socket_->CancelHandshake(); - } + int server_port() { return server_port_; } + InspectorSocket* ws_socket() { return ws_socket_.get(); } + void Accept(const std::string& ws_key) { ws_socket_->AcceptUpgrade(ws_key); } + void Decline() { ws_socket_->CancelHandshake(); } class Delegate : public InspectorSocket::Delegate { public: Delegate(InspectorSocketServer* server, int session_id) - : server_(server), session_id_(session_id) { } - ~Delegate() { - server_->SessionTerminated(session_id_); - } + : server_(server), session_id_(session_id) {} + ~Delegate() { server_->SessionTerminated(session_id_); } void OnHttpGet(const std::string& host, const std::string& path) override; - void OnSocketUpgrade(const std::string& host, const std::string& path, + void OnSocketUpgrade(const std::string& host, + const std::string& path, const std::string& ws_key) override; void OnWsFrame(const std::vector& data) override; private: - SocketSession* Session() { - return server_->Session(session_id_); - } + SocketSession* Session() { return server_->Session(session_id_); } InspectorSocketServer* server_; int session_id_; @@ -210,7 +195,7 @@ class SocketSession { class ServerSocket { public: explicit ServerSocket(InspectorSocketServer* server) - : tcp_socket_(uv_tcp_t()), server_(server) {} + : tcp_socket_(uv_tcp_t()), server_(server) {} int Listen(sockaddr* addr, uv_loop_t* loop); void Close() { uv_close(reinterpret_cast(&tcp_socket_), FreeOnCloseCallback); @@ -236,10 +221,17 @@ class ServerSocket { }; InspectorSocketServer::InspectorSocketServer( - std::unique_ptr delegate, uv_loop_t* loop, - const std::string& host, int port, FILE* out) - : loop_(loop), delegate_(std::move(delegate)), host_(host), port_(port), - next_session_id_(0), out_(out) { + std::unique_ptr delegate, + uv_loop_t* loop, + const std::string& host, + int port, + FILE* out) + : loop_(loop), + delegate_(std::move(delegate)), + host_(host), + port_(port), + next_session_id_(0), + out_(out) { delegate_->AssignServer(this); state_ = ServerState::kNew; } @@ -274,10 +266,10 @@ void InspectorSocketServer::SessionTerminated(int session_id) { } connected_sessions_.erase(session_id); if (connected_sessions_.empty()) { - if (was_attached && state_ == ServerState::kRunning - && !server_sockets_.empty()) { - PrintDebuggerReadyMessage(host_, server_sockets_[0]->port(), - delegate_->GetTargetIds(), out_); + if (was_attached && state_ == ServerState::kRunning && + !server_sockets_.empty()) { + PrintDebuggerReadyMessage( + host_, server_sockets_[0]->port(), delegate_->GetTargetIds(), out_); } if (state_ == ServerState::kStopped) { delegate_.reset(); @@ -291,8 +283,7 @@ bool InspectorSocketServer::HandleGetRequest(int session_id, SocketSession* session = Session(session_id); InspectorSocket* socket = session->ws_socket(); const char* command = MatchPathSegment(path.c_str(), "/json"); - if (command == nullptr) - return false; + if (command == nullptr) return false; if (MatchPathSegment(command, "list") || command[0] == '\0') { SendListResponse(socket, host, session); @@ -327,22 +318,21 @@ void InspectorSocketServer::SendListResponse(InspectorSocket* socket, std::string detected_host = host; if (detected_host.empty()) { - detected_host = FormatHostPort(socket->GetHost(), - session->server_port()); + detected_host = FormatHostPort(socket->GetHost(), session->server_port()); } std::string formatted_address = FormatAddress(detected_host, id, false); - target_map["devtoolsFrontendUrl"] = GetFrontendURL(false, - formatted_address); + target_map["devtoolsFrontendUrl"] = + GetFrontendURL(false, formatted_address); // The compat URL is for Chrome browsers older than 66.0.3345.0 - target_map["devtoolsFrontendUrlCompat"] = GetFrontendURL(true, - formatted_address); + target_map["devtoolsFrontendUrlCompat"] = + GetFrontendURL(true, formatted_address); target_map["webSocketDebuggerUrl"] = FormatAddress(detected_host, id, true); } SendHttpResponse(socket, MapsToString(response)); } -std::string InspectorSocketServer::GetFrontendURL(bool is_compat, - const std::string &formatted_address) { +std::string InspectorSocketServer::GetFrontendURL( + bool is_compat, const std::string& formatted_address) { std::ostringstream frontend_url; frontend_url << "chrome-devtools://devtools/bundled/"; frontend_url << (is_compat ? "inspector" : "js_app"); @@ -363,11 +353,13 @@ bool InspectorSocketServer::Start() { hints.ai_socktype = SOCK_STREAM; uv_getaddrinfo_t req; const std::string port_string = std::to_string(port_); - int err = uv_getaddrinfo(loop_, &req, nullptr, host_.c_str(), - port_string.c_str(), &hints); + int err = uv_getaddrinfo( + loop_, &req, nullptr, host_.c_str(), port_string.c_str(), &hints); if (err < 0) { if (out_ != nullptr) { - fprintf(out_, "Unable to resolve \"%s\": %s\n", host_.c_str(), + fprintf(out_, + "Unable to resolve \"%s\": %s\n", + host_.c_str(), uv_strerror(err)); } return false; @@ -376,8 +368,7 @@ bool InspectorSocketServer::Start() { address = address->ai_next) { auto server_socket = ServerSocketPtr(new ServerSocket(this)); err = server_socket->Listen(address->ai_addr, loop_); - if (err == 0) - server_sockets_.push_back(std::move(server_socket)); + if (err == 0) server_sockets_.push_back(std::move(server_socket)); } uv_freeaddrinfo(req.addrinfo); @@ -385,8 +376,11 @@ bool InspectorSocketServer::Start() { // show one error, for the last address. if (server_sockets_.empty()) { if (out_ != nullptr) { - fprintf(out_, "Starting inspector on %s:%d failed: %s\n", - host_.c_str(), port_, uv_strerror(err)); + fprintf(out_, + "Starting inspector on %s:%d failed: %s\n", + host_.c_str(), + port_, + uv_strerror(err)); fflush(out_); } return false; @@ -394,19 +388,17 @@ bool InspectorSocketServer::Start() { delegate_.swap(delegate_holder); state_ = ServerState::kRunning; // getaddrinfo sorts the addresses, so the first port is most relevant. - PrintDebuggerReadyMessage(host_, server_sockets_[0]->port(), - delegate_->GetTargetIds(), out_); + PrintDebuggerReadyMessage( + host_, server_sockets_[0]->port(), delegate_->GetTargetIds(), out_); return true; } void InspectorSocketServer::Stop() { - if (state_ == ServerState::kStopped) - return; + if (state_ == ServerState::kStopped) return; CHECK_EQ(state_, ServerState::kRunning); state_ = ServerState::kStopped; server_sockets_.clear(); - if (done()) - delegate_.reset(); + if (done()) delegate_.reset(); } void InspectorSocketServer::TerminateConnections() { @@ -432,9 +424,8 @@ void InspectorSocketServer::Accept(int server_port, std::unique_ptr session( new SocketSession(this, next_session_id_++, server_port)); - InspectorSocket::DelegatePointer delegate = - InspectorSocket::DelegatePointer( - new SocketSession::Delegate(this, session->id())); + InspectorSocket::DelegatePointer delegate = InspectorSocket::DelegatePointer( + new SocketSession::Delegate(this, session->id())); InspectorSocket::Pointer inspector = InspectorSocket::Accept(server_socket, std::move(delegate)); @@ -456,7 +447,8 @@ void InspectorSocketServer::CloseServerSocket(ServerSocket* server) { } // InspectorSession tracking -SocketSession::SocketSession(InspectorSocketServer* server, int id, +SocketSession::SocketSession(InspectorSocketServer* server, + int id, int server_port) : id_(id), server_port_(server_port) {} @@ -478,18 +470,16 @@ void SocketSession::Delegate::OnSocketUpgrade(const std::string& host, } void SocketSession::Delegate::OnWsFrame(const std::vector& data) { - server_->MessageReceived(session_id_, - std::string(data.data(), data.size())); + server_->MessageReceived(session_id_, std::string(data.data(), data.size())); } // ServerSocket implementation int ServerSocket::DetectPort() { sockaddr_storage addr; int len = sizeof(addr); - int err = uv_tcp_getsockname(&tcp_socket_, - reinterpret_cast(&addr), &len); - if (err != 0) - return err; + int err = uv_tcp_getsockname( + &tcp_socket_, reinterpret_cast(&addr), &len); + if (err != 0) return err; int port; if (addr.ss_family == AF_INET6) port = reinterpret_cast(&addr)->sin6_port; @@ -505,7 +495,8 @@ int ServerSocket::Listen(sockaddr* addr, uv_loop_t* loop) { int err = uv_tcp_bind(server, addr, 0); if (err == 0) { // 511 is the value used by a 'net' module by default - err = uv_listen(reinterpret_cast(server), 511, + err = uv_listen(reinterpret_cast(server), + 511, ServerSocket::SocketConnectedCallback); } if (err == 0) { diff --git a/src/inspector_socket_server.h b/src/inspector_socket_server.h index 271be6ec555bf1..25ee94937b8619 100644 --- a/src/inspector_socket_server.h +++ b/src/inspector_socket_server.h @@ -58,9 +58,11 @@ class InspectorSocketServer { // Session connection lifecycle void Accept(int server_port, uv_stream_t* server_socket); - bool HandleGetRequest(int session_id, const std::string& host, + bool HandleGetRequest(int session_id, + const std::string& host, const std::string& path); - void SessionStarted(int session_id, const std::string& target_id, + void SessionStarted(int session_id, + const std::string& target_id, const std::string& ws_id); void SessionTerminated(int session_id); void MessageReceived(int session_id, const std::string& message) { @@ -75,13 +77,14 @@ class InspectorSocketServer { static void CloseServerSocket(ServerSocket*); using ServerSocketPtr = DeleteFnPtr; - void SendListResponse(InspectorSocket* socket, const std::string& host, + void SendListResponse(InspectorSocket* socket, + const std::string& host, SocketSession* session); std::string GetFrontendURL(bool is_compat, - const std::string &formatted_address); + const std::string& formatted_address); bool TargetExists(const std::string& id); - enum class ServerState {kNew, kRunning, kStopping, kStopped}; + enum class ServerState { kNew, kRunning, kStopping, kStopped }; uv_loop_t* loop_; std::unique_ptr delegate_; const std::string host_; diff --git a/src/js_stream.cc b/src/js_stream.cc index 902aff7abee43e..f5216656cf7f57 100644 --- a/src/js_stream.cc +++ b/src/js_stream.cc @@ -20,38 +20,31 @@ using v8::String; using v8::TryCatch; using v8::Value; - JSStream::JSStream(Environment* env, Local obj) - : AsyncWrap(env, obj, AsyncWrap::PROVIDER_JSSTREAM), - StreamBase(env) { + : AsyncWrap(env, obj, AsyncWrap::PROVIDER_JSSTREAM), StreamBase(env) { MakeWeak(); } - AsyncWrap* JSStream::GetAsyncWrap() { return static_cast(this); } - bool JSStream::IsAlive() { return true; } - bool JSStream::IsClosing() { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); TryCatch try_catch(env()->isolate()); Local value; if (!MakeCallback(env()->isclosing_string(), 0, nullptr).ToLocal(&value)) { - if (!try_catch.HasTerminated()) - FatalException(env()->isolate(), try_catch); + if (!try_catch.HasTerminated()) FatalException(env()->isolate(), try_catch); return true; } return value->IsTrue(); } - int JSStream::ReadStart() { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); @@ -60,13 +53,11 @@ int JSStream::ReadStart() { int value_int = UV_EPROTO; if (!MakeCallback(env()->onreadstart_string(), 0, nullptr).ToLocal(&value) || !value->Int32Value(env()->context()).To(&value_int)) { - if (!try_catch.HasTerminated()) - FatalException(env()->isolate(), try_catch); + if (!try_catch.HasTerminated()) FatalException(env()->isolate(), try_catch); } return value_int; } - int JSStream::ReadStop() { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); @@ -75,35 +66,28 @@ int JSStream::ReadStop() { int value_int = UV_EPROTO; if (!MakeCallback(env()->onreadstop_string(), 0, nullptr).ToLocal(&value) || !value->Int32Value(env()->context()).To(&value_int)) { - if (!try_catch.HasTerminated()) - FatalException(env()->isolate(), try_catch); + if (!try_catch.HasTerminated()) FatalException(env()->isolate(), try_catch); } return value_int; } - int JSStream::DoShutdown(ShutdownWrap* req_wrap) { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); - Local argv[] = { - req_wrap->object() - }; + Local argv[] = {req_wrap->object()}; TryCatch try_catch(env()->isolate()); Local value; int value_int = UV_EPROTO; - if (!MakeCallback(env()->onshutdown_string(), - arraysize(argv), - argv).ToLocal(&value) || + if (!MakeCallback(env()->onshutdown_string(), arraysize(argv), argv) + .ToLocal(&value) || !value->Int32Value(env()->context()).To(&value_int)) { - if (!try_catch.HasTerminated()) - FatalException(env()->isolate(), try_catch); + if (!try_catch.HasTerminated()) FatalException(env()->isolate(), try_catch); } return value_int; } - int JSStream::DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count, @@ -120,25 +104,19 @@ int JSStream::DoWrite(WriteWrap* w, bufs_arr->Set(i, buf); } - Local argv[] = { - w->object(), - bufs_arr - }; + Local argv[] = {w->object(), bufs_arr}; TryCatch try_catch(env()->isolate()); Local value; int value_int = UV_EPROTO; - if (!MakeCallback(env()->onwrite_string(), - arraysize(argv), - argv).ToLocal(&value) || + if (!MakeCallback(env()->onwrite_string(), arraysize(argv), argv) + .ToLocal(&value) || !value->Int32Value(env()->context()).To(&value_int)) { - if (!try_catch.HasTerminated()) - FatalException(env()->isolate(), try_catch); + if (!try_catch.HasTerminated()) FatalException(env()->isolate(), try_catch); } return value_int; } - void JSStream::New(const FunctionCallbackInfo& args) { // This constructor should not be exposed to public javascript. // Therefore we assert that we are not trying to call this as a @@ -148,7 +126,6 @@ void JSStream::New(const FunctionCallbackInfo& args) { new JSStream(env, args.This()); } - template void JSStream::Finish(const FunctionCallbackInfo& args) { CHECK(args[0]->IsObject()); @@ -157,7 +134,6 @@ void JSStream::Finish(const FunctionCallbackInfo& args) { w->Done(args[1]->Int32Value()); } - void JSStream::ReadBuffer(const FunctionCallbackInfo& args) { JSStream* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -171,8 +147,7 @@ void JSStream::ReadBuffer(const FunctionCallbackInfo& args) { while (len != 0) { uv_buf_t buf = wrap->EmitAlloc(len); ssize_t avail = len; - if (static_cast(buf.len) < avail) - avail = buf.len; + if (static_cast(buf.len) < avail) avail = buf.len; memcpy(buf.base, data, avail); data += avail; @@ -181,7 +156,6 @@ void JSStream::ReadBuffer(const FunctionCallbackInfo& args) { } } - void JSStream::EmitEOF(const FunctionCallbackInfo& args) { JSStream* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -189,7 +163,6 @@ void JSStream::EmitEOF(const FunctionCallbackInfo& args) { wrap->EmitRead(UV_EOF); } - void JSStream::Initialize(Local target, Local unused, Local context) { diff --git a/src/memory_tracker-inl.h b/src/memory_tracker-inl.h index 568a4364f9c64d..c2ef26f1fe6d52 100644 --- a/src/memory_tracker-inl.h +++ b/src/memory_tracker-inl.h @@ -12,12 +12,11 @@ class MemoryRetainerNode : public v8::EmbedderGraph::Node { explicit inline MemoryRetainerNode(MemoryTracker* tracker, const MemoryRetainer* retainer, const char* name) - : retainer_(retainer) { + : retainer_(retainer) { if (retainer_ != nullptr) { v8::HandleScope handle_scope(tracker->isolate()); v8::Local obj = retainer_->WrappedObject(); - if (!obj.IsEmpty()) - wrapper_node_ = tracker->graph()->V8Node(obj); + if (!obj.IsEmpty()) wrapper_node_ = tracker->graph()->V8Node(obj); name_ = retainer_->MemoryInfoName(); } @@ -53,8 +52,7 @@ void MemoryTracker::TrackThis(const T* obj) { } void MemoryTracker::TrackFieldWithSize(const char* name, size_t size) { - if (size > 0) - AddNode(name)->size_ = size; + if (size > 0) AddNode(name)->size_ = size; } void MemoryTracker::TrackField(const char* name, const MemoryRetainer& value) { @@ -128,8 +126,7 @@ void MemoryTracker::TrackField(const char* name, template void MemoryTracker::TrackField(const char* name, const v8::Local& value) { - if (!value.IsEmpty()) - graph_->AddEdge(CurrentNode(), graph_->V8Node(value)); + if (!value.IsEmpty()) graph_->AddEdge(CurrentNode(), graph_->V8Node(value)); } template @@ -144,7 +141,7 @@ void MemoryTracker::TrackField(const char* name, const uv_buf_t& value) { template void MemoryTracker::TrackField(const char* name, - const AliasedBuffer& value) { + const AliasedBuffer& value) { TrackField(name, value.GetJSArray()); } @@ -162,15 +159,13 @@ MemoryRetainerNode* MemoryTracker::CurrentNode() const { return node_stack_.top(); } -MemoryRetainerNode* MemoryTracker::AddNode( - const char* name, const MemoryRetainer* retainer) { +MemoryRetainerNode* MemoryTracker::AddNode(const char* name, + const MemoryRetainer* retainer) { MemoryRetainerNode* n = new MemoryRetainerNode(this, retainer, name); graph_->AddNode(std::unique_ptr(n)); - if (retainer != nullptr) - seen_[retainer] = n; + if (retainer != nullptr) seen_[retainer] = n; - if (CurrentNode() != nullptr) - graph_->AddEdge(CurrentNode(), n); + if (CurrentNode() != nullptr) graph_->AddEdge(CurrentNode(), n); if (n->JSWrapperNode() != nullptr) { graph_->AddEdge(n, n->JSWrapperNode()); @@ -180,8 +175,8 @@ MemoryRetainerNode* MemoryTracker::AddNode( return n; } -MemoryRetainerNode* MemoryTracker::PushNode( - const char* name, const MemoryRetainer* retainer) { +MemoryRetainerNode* MemoryTracker::PushNode(const char* name, + const MemoryRetainer* retainer) { MemoryRetainerNode* n = AddNode(name, retainer); node_stack_.push(n); return n; diff --git a/src/memory_tracker.h b/src/memory_tracker.h index d0f9e0dcad8f1e..93b152a4da7c1d 100644 --- a/src/memory_tracker.h +++ b/src/memory_tracker.h @@ -3,12 +3,12 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include +#include +#include #include #include #include -#include -#include +#include #include "aliased_buffer.h" #include "v8-profiler.h" @@ -54,10 +54,10 @@ class MemoryTracker { inline void TrackField(const char* name, const std::queue& value); template inline void TrackField(const char* name, const std::basic_string& value); - template ::is_specialized, bool>::type, - typename dummy = bool> + template ::is_specialized, bool>::type, + typename dummy = bool> inline void TrackField(const char* name, const T& value); template inline void TrackField(const char* name, const std::pair& value); @@ -79,9 +79,8 @@ class MemoryTracker { inline v8::EmbedderGraph* graph() { return graph_; } inline v8::Isolate* isolate() { return isolate_; } - inline explicit MemoryTracker(v8::Isolate* isolate, - v8::EmbedderGraph* graph) - : isolate_(isolate), graph_(graph) {} + inline explicit MemoryTracker(v8::Isolate* isolate, v8::EmbedderGraph* graph) + : isolate_(isolate), graph_(graph) {} private: typedef std::unordered_map diff --git a/src/module_wrap.cc b/src/module_wrap.cc index ab1950311ad631..ecd8260dd67df6 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -1,15 +1,15 @@ -#include -#include // PATH_MAX -#include // S_IFDIR #include "module_wrap.h" +#include // PATH_MAX +#include // S_IFDIR +#include #include "env.h" +#include "node_contextify.h" #include "node_errors.h" -#include "node_url.h" -#include "util-inl.h" #include "node_internals.h" -#include "node_contextify.h" +#include "node_url.h" #include "node_watchdog.h" +#include "util-inl.h" namespace node { namespace loader { @@ -47,7 +47,8 @@ static const char* const EXTENSIONS[] = {".mjs", ".js", ".json", ".node"}; ModuleWrap::ModuleWrap(Environment* env, Local object, Local module, - Local url) : BaseObject(env, object) { + Local url) + : BaseObject(env, object) { module_.Reset(env->isolate(), module); url_.Reset(env->isolate(), url); } @@ -64,8 +65,7 @@ ModuleWrap::~ModuleWrap() { } } -ModuleWrap* ModuleWrap::GetFromModule(Environment* env, - Local module) { +ModuleWrap* ModuleWrap::GetFromModule(Environment* env, Local module) { ModuleWrap* ret = nullptr; auto range = env->module_map.equal_range(module->GetIdentityHash()); for (auto it = range.first; it != range.second; ++it) { @@ -129,21 +129,23 @@ void ModuleWrap::New(const FunctionCallbackInfo& args) { // compile { ScriptOrigin origin(url, - line_offset, // line offset - column_offset, // column offset - False(isolate), // is cross origin - Local(), // script id - Local(), // source map URL - False(isolate), // is opaque (?) - False(isolate), // is WASM - True(isolate)); // is ES6 module + line_offset, // line offset + column_offset, // column offset + False(isolate), // is cross origin + Local(), // script id + Local(), // source map URL + False(isolate), // is opaque (?) + False(isolate), // is WASM + True(isolate)); // is ES6 module Context::Scope context_scope(context); ScriptCompiler::Source source(source_text, origin); if (!ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) { CHECK(try_catch.HasCaught()); CHECK(!try_catch.Message().IsEmpty()); CHECK(!try_catch.Exception().IsEmpty()); - AppendExceptionLine(env, try_catch.Exception(), try_catch.Message(), + AppendExceptionLine(env, + try_catch.Exception(), + try_catch.Message(), ErrorHandlingMode::MODULE_ERROR); try_catch.ReThrow(); return; @@ -175,8 +177,7 @@ void ModuleWrap::Link(const FunctionCallbackInfo& args) { ModuleWrap* obj; ASSIGN_OR_RETURN_UNWRAP(&obj, that); - if (obj->linked_) - return; + if (obj->linked_) return; obj->linked_ = true; Local resolver_arg = args[0].As(); @@ -184,8 +185,8 @@ void ModuleWrap::Link(const FunctionCallbackInfo& args) { Local mod_context = obj->context_.Get(isolate); Local module = obj->module_.Get(isolate); - Local promises = Array::New(isolate, - module->GetModuleRequestsLength()); + Local promises = + Array::New(isolate, module->GetModuleRequestsLength()); // call the dependency resolve callbacks for (int i = 0; i < module->GetModuleRequestsLength(); i++) { @@ -193,9 +194,7 @@ void ModuleWrap::Link(const FunctionCallbackInfo& args) { Utf8Value specifier_utf8(env->isolate(), specifier); std::string specifier_std(*specifier_utf8, specifier_utf8.length()); - Local argv[] = { - specifier - }; + Local argv[] = {specifier}; MaybeLocal maybe_resolve_return_value = resolver_arg->Call(mod_context, that, 1, argv); @@ -233,7 +232,9 @@ void ModuleWrap::Instantiate(const FunctionCallbackInfo& args) { CHECK(try_catch.HasCaught()); CHECK(!try_catch.Message().IsEmpty()); CHECK(!try_catch.Exception().IsEmpty()); - AppendExceptionLine(env, try_catch.Exception(), try_catch.Message(), + AppendExceptionLine(env, + try_catch.Exception(), + try_catch.Message(), ErrorHandlingMode::MODULE_ERROR); try_catch.ReThrow(); return; @@ -412,16 +413,13 @@ namespace { inline bool ShouldBeTreatedAsRelativeOrAbsolutePath( const std::string& specifier) { size_t len = specifier.length(); - if (len == 0) - return false; + if (len == 0) return false; if (specifier[0] == '/') { return true; } else if (specifier[0] == '.') { - if (len == 1 || specifier[1] == '/') - return true; + if (len == 1 || specifier[1] == '/') return true; if (specifier[1] == '.') { - if (len == 2 || specifier[2] == '/') - return true; + if (len == 2 || specifier[2] == '/') return true; } } return false; @@ -444,17 +442,13 @@ std::string ReadFile(uv_file file) { nullptr); uv_fs_req_cleanup(&req); - if (r <= 0) - break; + if (r <= 0) break; contents.append(buf.base, r); } while (true); return contents; } -enum CheckFileOptions { - LEAVE_OPEN_AFTER_CHECK, - CLOSE_AFTER_CHECK -}; +enum CheckFileOptions { LEAVE_OPEN_AFTER_CHECK, CLOSE_AFTER_CHECK }; Maybe CheckFile(const std::string& path, CheckFileOptions opt = CLOSE_AFTER_CHECK) { @@ -489,15 +483,15 @@ Maybe CheckFile(const std::string& path, } const PackageConfig& GetPackageConfig(Environment* env, - const std::string path) { + const std::string path) { auto existing = env->package_json_cache.find(path); if (existing != env->package_json_cache.end()) { return existing->second; } Maybe check = CheckFile(path, LEAVE_OPEN_AFTER_CHECK); if (check.IsNothing()) { - auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "" }); + auto entry = env->package_json_cache.emplace( + path, PackageConfig{Exists::No, IsValid::Yes, HasMain::No, ""}); return entry.first->second; } @@ -513,9 +507,10 @@ const PackageConfig& GetPackageConfig(Environment* env, if (!String::NewFromUtf8(isolate, pkg_src.c_str(), v8::NewStringType::kNormal, - pkg_src.length()).ToLocal(&src)) { - auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "" }); + pkg_src.length()) + .ToLocal(&src)) { + auto entry = env->package_json_cache.emplace( + path, PackageConfig{Exists::No, IsValid::Yes, HasMain::No, ""}); return entry.first->second; } @@ -524,8 +519,8 @@ const PackageConfig& GetPackageConfig(Environment* env, if (!JSON::Parse(env->context(), src).ToLocal(&pkg_json_v) || !pkg_json_v->ToObject(env->context()).ToLocal(&pkg_json)) { - auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::Yes, IsValid::No, HasMain::No, "" }); + auto entry = env->package_json_cache.emplace( + path, PackageConfig{Exists::Yes, IsValid::No, HasMain::No, ""}); return entry.first->second; } @@ -538,15 +533,12 @@ const PackageConfig& GetPackageConfig(Environment* env, main_std.assign(std::string(*main_utf8, main_utf8.length())); } - auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::Yes, IsValid::Yes, has_main, main_std }); + auto entry = env->package_json_cache.emplace( + path, PackageConfig{Exists::Yes, IsValid::Yes, has_main, main_std}); return entry.first->second; } -enum ResolveExtensionsOptions { - TRY_EXACT_NAME, - ONLY_VIA_EXTENSIONS -}; +enum ResolveExtensionsOptions { TRY_EXACT_NAME, ONLY_VIA_EXTENSIONS }; template Maybe ResolveExtensions(const URL& search) { @@ -576,12 +568,10 @@ inline Maybe ResolveIndex(const URL& search) { Maybe ResolveMain(Environment* env, const URL& search) { URL pkg("package.json", &search); - const PackageConfig& pjson = - GetPackageConfig(env, pkg.ToFilePath()); + const PackageConfig& pjson = GetPackageConfig(env, pkg.ToFilePath()); // Note invalid package.json should throw in resolver // currently we silently ignore which is incorrect - if (pjson.exists == Exists::No || - pjson.is_valid == IsValid::No || + if (pjson.exists == Exists::No || pjson.is_valid == IsValid::No || pjson.has_main == HasMain::No) { return Nothing(); } @@ -603,8 +593,7 @@ Maybe ResolveModule(Environment* env, if (!check.IsNothing()) { const size_t limit = specifier.find('/'); const size_t spec_len = - limit == std::string::npos ? specifier.length() : - limit + 1; + limit == std::string::npos ? specifier.length() : limit + 1; std::string chroot = dir.path() + "node_modules/" + specifier.substr(0, spec_len); if (check.FromJust().path().substr(0, chroot.length()) != chroot) { @@ -624,8 +613,7 @@ Maybe ResolveDirectory(Environment* env, PackageMainCheck check_pjson_main) { if (check_pjson_main) { Maybe main = ResolveMain(env, search); - if (!main.IsNothing()) - return main; + if (!main.IsNothing()) return main; } return ResolveIndex(search); } @@ -651,8 +639,7 @@ Maybe Resolve(Environment* env, if (ShouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { URL resolved(specifier, base); Maybe file = ResolveExtensions(resolved); - if (!file.IsNothing()) - return file; + if (!file.IsNothing()) return file; if (specifier.back() != '/') { resolved = URL(specifier + "/", base); } @@ -704,7 +691,7 @@ static MaybeLocal ImportModuleDynamically( if (maybe_resolver.ToLocal(&resolver)) { // TODO(jkrems): Turn into proper error object w/ code Local error = v8::Exception::Error( - OneByteString(iso, "import() called outside of main context")); + OneByteString(iso, "import() called outside of main context")); if (resolver->Reject(context, error).IsJust()) { return handle_scope.Escape(resolver.As()); } @@ -713,15 +700,11 @@ static MaybeLocal ImportModuleDynamically( } Local import_callback = - env->host_import_module_dynamically_callback(); - Local import_args[] = { - referrer->GetResourceName(), - Local(specifier) - }; - MaybeLocal maybe_result = import_callback->Call(context, - v8::Undefined(iso), - 2, - import_args); + env->host_import_module_dynamically_callback(); + Local import_args[] = {referrer->GetResourceName(), + Local(specifier)}; + MaybeLocal maybe_result = + import_callback->Call(context, v8::Undefined(iso), 2, import_args); Local result; if (maybe_result.ToLocal(&result)) { @@ -744,8 +727,9 @@ void ModuleWrap::SetImportModuleDynamicallyCallback( iso->SetHostImportModuleDynamicallyCallback(ImportModuleDynamically); } -void ModuleWrap::HostInitializeImportMetaObjectCallback( - Local context, Local module, Local meta) { +void ModuleWrap::HostInitializeImportMetaObjectCallback(Local context, + Local module, + Local meta) { Isolate* isolate = context->GetIsolate(); Environment* env = Environment::GetCurrent(context); ModuleWrap* module_wrap = GetFromModule(env, module); @@ -755,9 +739,8 @@ void ModuleWrap::HostInitializeImportMetaObjectCallback( } Local wrap = module_wrap->object(); - Local callback = - env->host_initialize_import_meta_object_callback(); - Local args[] = { wrap, meta }; + Local callback = env->host_initialize_import_meta_object_callback(); + Local args[] = {wrap, meta}; callback->Call(context, Undefined(isolate), arraysize(args), args) .ToLocalChecked(); } @@ -792,8 +775,8 @@ void ModuleWrap::Initialize(Local target, env->SetProtoMethodNoSideEffect(tpl, "namespace", Namespace); env->SetProtoMethodNoSideEffect(tpl, "getStatus", GetStatus); env->SetProtoMethodNoSideEffect(tpl, "getError", GetError); - env->SetProtoMethodNoSideEffect(tpl, "getStaticDependencySpecifiers", - GetStaticDependencySpecifiers); + env->SetProtoMethodNoSideEffect( + tpl, "getStaticDependencySpecifiers", GetStaticDependencySpecifiers); target->Set(FIXED_ONE_BYTE_STRING(isolate, "ModuleWrap"), tpl->GetFunction()); env->SetMethod(target, "resolve", Resolve); @@ -805,16 +788,17 @@ void ModuleWrap::Initialize(Local target, SetInitializeImportMetaObjectCallback); #define V(name) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ - Integer::New(env->isolate(), Module::Status::name)) \ - .FromJust() - V(kUninstantiated); - V(kInstantiating); - V(kInstantiated); - V(kEvaluating); - V(kEvaluated); - V(kErrored); + target \ + ->Set(context, \ + FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ + Integer::New(env->isolate(), Module::Status::name)) \ + .FromJust() + V(kUninstantiated); + V(kInstantiating); + V(kInstantiated); + V(kEvaluating); + V(kEvaluated); + V(kErrored); #undef V } diff --git a/src/module_wrap.h b/src/module_wrap.h index 3e19b6c9eb3ebe..0c8203921a4d13 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h @@ -3,19 +3,16 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include #include +#include #include -#include "node_url.h" #include "base_object-inl.h" +#include "node_url.h" namespace node { namespace loader { -enum PackageMainCheck : bool { - CheckMain = true, - IgnoreMain = false -}; +enum PackageMainCheck : bool { CheckMain = true, IgnoreMain = false }; v8::Maybe Resolve(Environment* env, const std::string& specifier, @@ -69,7 +66,6 @@ class ModuleWrap : public BaseObject { v8::Local referrer); static ModuleWrap* GetFromModule(node::Environment*, v8::Local); - Persistent module_; Persistent url_; bool linked_ = false; diff --git a/src/node.cc b/src/node.cc index c4fc05f75fe2b1..0a71035bde495d 100644 --- a/src/node.cc +++ b/src/node.cc @@ -20,16 +20,16 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_buffer.h" +#include "node_code_cache.h" #include "node_constants.h" +#include "node_context_data.h" +#include "node_debug_options.h" +#include "node_internals.h" #include "node_javascript.h" -#include "node_code_cache.h" +#include "node_perf.h" #include "node_platform.h" -#include "node_version.h" -#include "node_internals.h" #include "node_revert.h" -#include "node_debug_options.h" -#include "node_perf.h" -#include "node_context_data.h" +#include "node_version.h" #include "tracing/traced_value.h" #if defined HAVE_PERFCTR @@ -74,7 +74,7 @@ #endif #include -#include // _O_RDWR +#include // _O_RDWR #include // PATH_MAX #include #include @@ -102,12 +102,12 @@ typedef int mode_t; #else #include #include // getrlimit, setrlimit -#include // setuid, getuid +#include // setuid, getuid #endif #if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__) -#include // getpwnam() #include // getgrnam() +#include // getpwnam() #endif #if defined(__POSIX__) @@ -118,7 +118,7 @@ typedef int mode_t; #include #define environ (*_NSGetEnviron()) #elif !defined(_MSC_VER) -extern char **environ; +extern char** environ; #endif // This is used to load built-in modules. Instead of using @@ -128,7 +128,7 @@ extern char **environ; // The definitions are in each module's implementation when calling // the NODE_BUILTIN_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); - NODE_BUILTIN_MODULES(V) +NODE_BUILTIN_MODULES(V) #undef V namespace node { @@ -192,8 +192,8 @@ static node_module* modlist_internal; static node_module* modlist_linked; static node_module* modlist_addon; static std::string trace_enabled_categories; // NOLINT(runtime/string) -static std::string trace_file_pattern = // NOLINT(runtime/string) - "node_trace.${rotation}.log"; +static std::string trace_file_pattern = // NOLINT(runtime/string) + "node_trace.${rotation}.log"; static bool abort_on_uncaught_exception = false; // Bit flag used to track security reverts (see node_revert.h) @@ -211,18 +211,18 @@ bool no_deprecation = false; // use OpenSSL's cert store instead of bundled certs bool ssl_openssl_cert_store = #if defined(NODE_OPENSSL_CERT_STORE) - true; + true; #else - false; + false; #endif -# if NODE_FIPS_MODE +#if NODE_FIPS_MODE // used by crypto module bool enable_fips_crypto = false; bool force_fips_crypto = false; -# endif // NODE_FIPS_MODE +#endif // NODE_FIPS_MODE std::string openssl_config; // NOLINT(runtime/string) -#endif // HAVE_OPENSSL +#endif // HAVE_OPENSSL // true if process warnings should be suppressed bool no_process_warnings = false; @@ -292,31 +292,32 @@ DebugOptions debug_options; // Ensures that __metadata trace events are only emitted // when tracing is enabled. -class NodeTraceStateObserver : - public v8::TracingController::TraceStateObserver { +class NodeTraceStateObserver + : public v8::TracingController::TraceStateObserver { public: void OnTraceEnabled() override { char name_buffer[512]; if (uv_get_process_title(name_buffer, sizeof(name_buffer)) == 0) { // Only emit the metadata event if the title can be retrieved // successfully. Ignore it otherwise. - TRACE_EVENT_METADATA1("__metadata", "process_name", - "name", TRACE_STR_COPY(name_buffer)); + TRACE_EVENT_METADATA1( + "__metadata", "process_name", "name", TRACE_STR_COPY(name_buffer)); } - TRACE_EVENT_METADATA1("__metadata", "version", - "node", NODE_VERSION_STRING); - TRACE_EVENT_METADATA1("__metadata", "thread_name", - "name", "JavaScriptMainThread"); + TRACE_EVENT_METADATA1("__metadata", "version", "node", NODE_VERSION_STRING); + TRACE_EVENT_METADATA1( + "__metadata", "thread_name", "name", "JavaScriptMainThread"); auto trace_process = tracing::TracedValue::Create(); trace_process->BeginDictionary("versions"); + // clang-format off const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "." NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR) "." NODE_STRINGIFY(HTTP_PARSER_VERSION_PATCH); + // clang-format on const char node_napi_version[] = NODE_STRINGIFY(NAPI_VERSION); const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION); @@ -341,14 +342,13 @@ class NodeTraceStateObserver : if ('0' <= c && c <= '9') { for (j = i + 1; j < k; ++j) { c = OPENSSL_VERSION_TEXT[j]; - if (c == ' ') - break; + if (c == ' ') break; } break; } } trace_process->SetString("openssl", - std::string(&OPENSSL_VERSION_TEXT[i], j - i)); + std::string(&OPENSSL_VERSION_TEXT[i], j - i)); } #endif trace_process->EndDictionary(); @@ -362,8 +362,8 @@ class NodeTraceStateObserver : trace_process->SetString("lts", NODE_VERSION_LTS_CODENAME); #endif trace_process->EndDictionary(); - TRACE_EVENT_METADATA1("__metadata", "node", - "process", std::move(trace_process)); + TRACE_EVENT_METADATA1( + "__metadata", "node", "process", std::move(trace_process)); // This only runs the first time tracing is enabled controller_->RemoveTraceStateObserver(this); @@ -376,8 +376,8 @@ class NodeTraceStateObserver : UNREACHABLE(); } - explicit NodeTraceStateObserver(v8::TracingController* controller) : - controller_(controller) {} + explicit NodeTraceStateObserver(v8::TracingController* controller) + : controller_(controller) {} ~NodeTraceStateObserver() override {} private: @@ -403,16 +403,15 @@ static struct { tracing_agent_.reset(nullptr); } - void DrainVMTasks(Isolate* isolate) { - platform_->DrainTasks(isolate); - } + void DrainVMTasks(Isolate* isolate) { platform_->DrainTasks(isolate); } void CancelVMTasks(Isolate* isolate) { platform_->CancelPendingDelayedTasks(isolate); } #if HAVE_INSPECTOR - bool StartInspector(Environment* env, const char* script_path, + bool StartInspector(Environment* env, + const char* script_path, const DebugOptions& options) { // Inspector agent can't fail to start, but if it was configured to listen // right away on the websocket port and fails to bind/etc, this will return @@ -426,31 +425,25 @@ static struct { } #endif // HAVE_INSPECTOR - void StartTracingAgent() { - tracing_agent_->Enable(trace_enabled_categories); - } + void StartTracingAgent() { tracing_agent_->Enable(trace_enabled_categories); } void StopTracingAgent() { - if (tracing_agent_) - tracing_agent_->Stop(); + if (tracing_agent_) tracing_agent_->Stop(); } - tracing::Agent* GetTracingAgent() const { - return tracing_agent_.get(); - } + tracing::Agent* GetTracingAgent() const { return tracing_agent_.get(); } - NodePlatform* Platform() { - return platform_; - } + NodePlatform* Platform() { return platform_; } std::unique_ptr tracing_agent_; NodePlatform* platform_; -#else // !NODE_USE_V8_PLATFORM +#else // !NODE_USE_V8_PLATFORM void Initialize(int thread_pool_size) {} void Dispose() {} void DrainVMTasks(Isolate* isolate) {} void CancelVMTasks(Isolate* isolate) {} - bool StartInspector(Environment* env, const char* script_path, + bool StartInspector(Environment* env, + const char* script_path, const DebugOptions& options) { env->ThrowError("Node compiled with NODE_USE_V8_PLATFORM=0"); return true; @@ -458,23 +451,20 @@ static struct { void StartTracingAgent() { if (!trace_enabled_categories.empty()) { - fprintf(stderr, "Node compiled with NODE_USE_V8_PLATFORM=0, " - "so event tracing is not available.\n"); + fprintf(stderr, + "Node compiled with NODE_USE_V8_PLATFORM=0, " + "so event tracing is not available.\n"); } } void StopTracingAgent() {} tracing::Agent* GetTracingAgent() const { return nullptr; } - NodePlatform* Platform() { - return nullptr; - } + NodePlatform* Platform() { return nullptr; } #endif // !NODE_USE_V8_PLATFORM #if !NODE_USE_V8_PLATFORM || !HAVE_INSPECTOR - bool InspectorStarted(Environment* env) { - return false; - } + bool InspectorStarted(Environment* env) { return false; } #endif // !NODE_USE_V8_PLATFORM || !HAVE_INSPECTOR } v8_platform; @@ -489,8 +479,7 @@ void PrintErrorString(const char* format, ...) { HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); // Check if stderr is something other than a tty/console - if (stderr_handle == INVALID_HANDLE_VALUE || - stderr_handle == nullptr || + if (stderr_handle == INVALID_HANDLE_VALUE || stderr_handle == nullptr || uv_guess_handle(_fileno(stderr)) != UV_TTY) { vfprintf(stderr, format, ap); va_end(ap); @@ -518,162 +507,164 @@ void PrintErrorString(const char* format, ...) { } const char* signo_string(int signo) { -#define SIGNO_CASE(e) case e: return #e; +#define SIGNO_CASE(e) \ + case e: \ + return #e; switch (signo) { #ifdef SIGHUP - SIGNO_CASE(SIGHUP); + SIGNO_CASE(SIGHUP); #endif #ifdef SIGINT - SIGNO_CASE(SIGINT); + SIGNO_CASE(SIGINT); #endif #ifdef SIGQUIT - SIGNO_CASE(SIGQUIT); + SIGNO_CASE(SIGQUIT); #endif #ifdef SIGILL - SIGNO_CASE(SIGILL); + SIGNO_CASE(SIGILL); #endif #ifdef SIGTRAP - SIGNO_CASE(SIGTRAP); + SIGNO_CASE(SIGTRAP); #endif #ifdef SIGABRT - SIGNO_CASE(SIGABRT); + SIGNO_CASE(SIGABRT); #endif #ifdef SIGIOT -# if SIGABRT != SIGIOT - SIGNO_CASE(SIGIOT); -# endif +#if SIGABRT != SIGIOT + SIGNO_CASE(SIGIOT); +#endif #endif #ifdef SIGBUS - SIGNO_CASE(SIGBUS); + SIGNO_CASE(SIGBUS); #endif #ifdef SIGFPE - SIGNO_CASE(SIGFPE); + SIGNO_CASE(SIGFPE); #endif #ifdef SIGKILL - SIGNO_CASE(SIGKILL); + SIGNO_CASE(SIGKILL); #endif #ifdef SIGUSR1 - SIGNO_CASE(SIGUSR1); + SIGNO_CASE(SIGUSR1); #endif #ifdef SIGSEGV - SIGNO_CASE(SIGSEGV); + SIGNO_CASE(SIGSEGV); #endif #ifdef SIGUSR2 - SIGNO_CASE(SIGUSR2); + SIGNO_CASE(SIGUSR2); #endif #ifdef SIGPIPE - SIGNO_CASE(SIGPIPE); + SIGNO_CASE(SIGPIPE); #endif #ifdef SIGALRM - SIGNO_CASE(SIGALRM); + SIGNO_CASE(SIGALRM); #endif - SIGNO_CASE(SIGTERM); + SIGNO_CASE(SIGTERM); #ifdef SIGCHLD - SIGNO_CASE(SIGCHLD); + SIGNO_CASE(SIGCHLD); #endif #ifdef SIGSTKFLT - SIGNO_CASE(SIGSTKFLT); + SIGNO_CASE(SIGSTKFLT); #endif - #ifdef SIGCONT - SIGNO_CASE(SIGCONT); + SIGNO_CASE(SIGCONT); #endif #ifdef SIGSTOP - SIGNO_CASE(SIGSTOP); + SIGNO_CASE(SIGSTOP); #endif #ifdef SIGTSTP - SIGNO_CASE(SIGTSTP); + SIGNO_CASE(SIGTSTP); #endif #ifdef SIGBREAK - SIGNO_CASE(SIGBREAK); + SIGNO_CASE(SIGBREAK); #endif #ifdef SIGTTIN - SIGNO_CASE(SIGTTIN); + SIGNO_CASE(SIGTTIN); #endif #ifdef SIGTTOU - SIGNO_CASE(SIGTTOU); + SIGNO_CASE(SIGTTOU); #endif #ifdef SIGURG - SIGNO_CASE(SIGURG); + SIGNO_CASE(SIGURG); #endif #ifdef SIGXCPU - SIGNO_CASE(SIGXCPU); + SIGNO_CASE(SIGXCPU); #endif #ifdef SIGXFSZ - SIGNO_CASE(SIGXFSZ); + SIGNO_CASE(SIGXFSZ); #endif #ifdef SIGVTALRM - SIGNO_CASE(SIGVTALRM); + SIGNO_CASE(SIGVTALRM); #endif #ifdef SIGPROF - SIGNO_CASE(SIGPROF); + SIGNO_CASE(SIGPROF); #endif #ifdef SIGWINCH - SIGNO_CASE(SIGWINCH); + SIGNO_CASE(SIGWINCH); #endif #ifdef SIGIO - SIGNO_CASE(SIGIO); + SIGNO_CASE(SIGIO); #endif #ifdef SIGPOLL -# if SIGPOLL != SIGIO - SIGNO_CASE(SIGPOLL); -# endif +#if SIGPOLL != SIGIO + SIGNO_CASE(SIGPOLL); +#endif #endif #ifdef SIGLOST -# if SIGLOST != SIGABRT - SIGNO_CASE(SIGLOST); -# endif +#if SIGLOST != SIGABRT + SIGNO_CASE(SIGLOST); +#endif #endif #ifdef SIGPWR -# if SIGPWR != SIGLOST - SIGNO_CASE(SIGPWR); -# endif +#if SIGPWR != SIGLOST + SIGNO_CASE(SIGPWR); +#endif #endif #ifdef SIGINFO -# if !defined(SIGPWR) || SIGINFO != SIGPWR - SIGNO_CASE(SIGINFO); -# endif +#if !defined(SIGPWR) || SIGINFO != SIGPWR + SIGNO_CASE(SIGINFO); +#endif #endif #ifdef SIGSYS - SIGNO_CASE(SIGSYS); + SIGNO_CASE(SIGSYS); #endif - default: return ""; + default: + return ""; } } @@ -697,7 +688,6 @@ bool SafeGetenv(const char* key, std::string* text) { return false; } - void* ArrayBufferAllocator::Allocate(size_t size) { if (zero_fill_field_ || zero_fill_all_buffers) return UncheckedCalloc(size); @@ -716,7 +706,6 @@ bool ShouldAbortOnUncaughtException(Isolate* isolate) { } // anonymous namespace - void AddPromiseHook(v8::Isolate* isolate, promise_hook_func fn, void* arg) { Environment* env = Environment::GetCurrent(isolate); env->AddPromiseHook(fn, arg); @@ -729,7 +718,6 @@ void AddEnvironmentCleanupHook(v8::Isolate* isolate, env->AddCleanupHook(fun, arg); } - void RemoveEnvironmentCleanupHook(v8::Isolate* isolate, void (*fun)(void* arg), void* arg) { @@ -775,10 +763,8 @@ MaybeLocal InternalMakeCallback(Environment* env, return ret; } - // Public MakeCallback()s - MaybeLocal MakeCallback(Isolate* isolate, Local recv, const char* method, @@ -791,7 +777,6 @@ MaybeLocal MakeCallback(Isolate* isolate, return MakeCallback(isolate, recv, method_string, argc, argv, asyncContext); } - MaybeLocal MakeCallback(Isolate* isolate, Local recv, Local symbol, @@ -805,7 +790,6 @@ MaybeLocal MakeCallback(Isolate* isolate, return MakeCallback(isolate, recv, callback, argc, argv, asyncContext); } - MaybeLocal MakeCallback(Isolate* isolate, Local recv, Local callback, @@ -821,11 +805,9 @@ MaybeLocal MakeCallback(Isolate* isolate, // the two contexts need not be the same. Environment* env = Environment::GetCurrent(callback->CreationContext()); Context::Scope context_scope(env->context()); - return InternalMakeCallback(env, recv, callback, - argc, argv, asyncContext); + return InternalMakeCallback(env, recv, callback, argc, argv, asyncContext); } - // Legacy MakeCallback()s Local MakeCallback(Isolate* isolate, @@ -839,24 +821,22 @@ Local MakeCallback(Isolate* isolate, .FromMaybe(Local())); } - Local MakeCallback(Isolate* isolate, - Local recv, - Local symbol, - int argc, - Local* argv) { + Local recv, + Local symbol, + int argc, + Local* argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( MakeCallback(isolate, recv, symbol, argc, argv, {0, 0}) .FromMaybe(Local())); } - Local MakeCallback(Isolate* isolate, - Local recv, - Local callback, - int argc, - Local* argv) { + Local recv, + Local callback, + int argc, + Local* argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( MakeCallback(isolate, recv, callback, argc, argv, {0, 0}) @@ -878,8 +858,7 @@ void AppendExceptionLine(Environment* env, Local er, Local message, enum ErrorHandlingMode mode) { - if (message.IsEmpty()) - return; + if (message.IsEmpty()) return; HandleScope scope(env->isolate()); Local err_obj; @@ -921,9 +900,9 @@ void AppendExceptionLine(Environment* env, // sourceline to 78 characters, and we end up not providing very much // useful debugging info to the user if we remove 62 characters. - int script_start = - (linenum - origin.ResourceLineOffset()->Value()) == 1 ? - origin.ResourceColumnOffset()->Value() : 0; + int script_start = (linenum - origin.ResourceLineOffset()->Value()) == 1 + ? origin.ResourceColumnOffset()->Value() + : 0; int start = message->GetStartColumn(env->context()).FromMaybe(0); int end = message->GetEndColumn(env->context()).FromMaybe(0); if (start >= script_start) { @@ -965,8 +944,9 @@ void AppendExceptionLine(Environment* env, arrow[off] = '\n'; arrow[off + 1] = '\0'; - Local arrow_str = String::NewFromUtf8(env->isolate(), arrow, - v8::NewStringType::kNormal).ToLocalChecked(); + Local arrow_str = + String::NewFromUtf8(env->isolate(), arrow, v8::NewStringType::kNormal) + .ToLocalChecked(); const bool can_set_arrow = !arrow_str.IsEmpty() && !err_obj.IsEmpty(); // If allocating arrow_str failed, print it out. There's not much else to do. @@ -975,8 +955,7 @@ void AppendExceptionLine(Environment* env, // Otherwise, the arrow property will be attached to the object and handled // by the caller. if (!can_set_arrow || (mode == FATAL_ERROR && !err_obj->IsNativeError())) { - if (env->printed_error()) - return; + if (env->printed_error()) return; Mutex::ScopedLock lock(process_mutex); env->set_printed_error(true); @@ -985,21 +964,19 @@ void AppendExceptionLine(Environment* env, return; } - CHECK(err_obj->SetPrivate( - env->context(), - env->arrow_message_private_symbol(), - arrow_str).FromMaybe(false)); + CHECK(err_obj + ->SetPrivate( + env->context(), env->arrow_message_private_symbol(), arrow_str) + .FromMaybe(false)); } - void ReportException(Environment* env, Local er, Local message) { CHECK(!er.IsEmpty()); HandleScope scope(env->isolate()); - if (message.IsEmpty()) - message = Exception::CreateMessage(env->isolate(), er); + if (message.IsEmpty()) message = Exception::CreateMessage(env->isolate(), er); AppendExceptionLine(env, er, message, FATAL_ERROR); @@ -1014,9 +991,8 @@ void ReportException(Environment* env, trace_value = err_obj->Get(env->stack_string()); arrow = - err_obj->GetPrivate( - env->context(), - env->arrow_message_private_symbol()).ToLocalChecked(); + err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol()) + .ToLocalChecked(); } node::Utf8Value trace(env->isolate(), trace_value); @@ -1042,15 +1018,13 @@ void ReportException(Environment* env, name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name")); } - if (message.IsEmpty() || - message->IsUndefined() || - name.IsEmpty() || + if (message.IsEmpty() || message->IsUndefined() || name.IsEmpty() || name->IsUndefined()) { // Not an error object. Just print as-is. String::Utf8Value message(env->isolate(), er); - PrintErrorString("%s\n", *message ? *message : - ""); + PrintErrorString("%s\n", + *message ? *message : ""); } else { node::Utf8Value name_string(env->isolate(), name); node::Utf8Value message_string(env->isolate(), message); @@ -1059,10 +1033,8 @@ void ReportException(Environment* env, PrintErrorString("%s: %s\n", *name_string, *message_string); } else { node::Utf8Value arrow_string(env->isolate(), arrow); - PrintErrorString("%s\n%s: %s\n", - *arrow_string, - *name_string, - *message_string); + PrintErrorString( + "%s\n%s: %s\n", *arrow_string, *name_string, *message_string); } } } @@ -1074,12 +1046,10 @@ void ReportException(Environment* env, #endif } - static void ReportException(Environment* env, const TryCatch& try_catch) { ReportException(env, try_catch.Exception(), try_catch.Message()); } - // Executes a str within the current v8 context. static MaybeLocal ExecuteString(Environment* env, Local source, @@ -1114,7 +1084,6 @@ static MaybeLocal ExecuteString(Environment* env, return scope.Escape(result.ToLocalChecked()); } - static void GetActiveRequests(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1125,8 +1094,7 @@ static void GetActiveRequests(const FunctionCallbackInfo& args) { size_t idx = 0; for (auto w : *env->req_wrap_queue()) { - if (w->persistent().IsEmpty()) - continue; + if (w->persistent().IsEmpty()) continue; argv[idx] = w->object(); if (++idx >= arraysize(argv)) { fn->Call(ctx, ary, idx, argv).ToLocalChecked(); @@ -1141,7 +1109,6 @@ static void GetActiveRequests(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ary); } - // Non-static, friend of HandleWrap. Could have been a HandleWrap method but // implemented here for consistency with GetActiveRequests(). void GetActiveHandles(const FunctionCallbackInfo& args) { @@ -1156,12 +1123,10 @@ void GetActiveHandles(const FunctionCallbackInfo& args) { Local owner_sym = env->owner_string(); for (auto w : *env->handle_wrap_queue()) { - if (w->persistent().IsEmpty() || !HandleWrap::HasRef(w)) - continue; + if (w->persistent().IsEmpty() || !HandleWrap::HasRef(w)) continue; Local object = w->object(); Local owner = object->Get(owner_sym); - if (owner->IsUndefined()) - owner = object; + if (owner->IsUndefined()) owner = object; argv[idx] = owner; if (++idx >= arraysize(argv)) { fn->Call(ctx, ary, idx, argv).ToLocalChecked(); @@ -1175,14 +1140,12 @@ void GetActiveHandles(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ary); } - NO_RETURN void Abort() { DumpBacktrace(stderr); fflush(stderr); ABORT_NO_BACKTRACE(); } - NO_RETURN void Assert(const char* const (*args)[4]) { auto filename = (*args)[0]; auto linenum = (*args)[1]; @@ -1192,14 +1155,19 @@ NO_RETURN void Assert(const char* const (*args)[4]) { char name[1024]; GetHumanReadableProcessName(&name); - fprintf(stderr, "%s: %s:%s:%s%s Assertion `%s' failed.\n", - name, filename, linenum, function, *function ? ":" : "", message); + fprintf(stderr, + "%s: %s:%s:%s%s Assertion `%s' failed.\n", + name, + filename, + linenum, + function, + *function ? ":" : "", + message); fflush(stderr); Abort(); } - static void WaitForInspectorDisconnect(Environment* env) { #if HAVE_INSPECTOR if (env->inspector_agent()->IsActive()) { @@ -1209,8 +1177,7 @@ static void WaitForInspectorDisconnect(Environment* env) { struct sigaction act; memset(&act, 0, sizeof(act)); for (unsigned nr = 1; nr < kMaxSignal; nr += 1) { - if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF) - continue; + if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF) continue; act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL; CHECK_EQ(0, sigaction(nr, &act, nullptr)); } @@ -1220,7 +1187,6 @@ static void WaitForInspectorDisconnect(Environment* env) { #endif } - static void Exit(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); WaitForInspectorDisconnect(env); @@ -1254,8 +1220,7 @@ inline struct node_module* FindModule(struct node_module* list, struct node_module* mp; for (mp = list; mp != nullptr; mp = mp->nm_link) { - if (strcmp(mp->nm_modname, name) == 0) - break; + if (strcmp(mp->nm_modname, name) == 0) break; } CHECK(mp == nullptr || (mp->nm_flags & flag) != 0); @@ -1298,12 +1263,10 @@ class DLib { DISALLOW_COPY_AND_ASSIGN(DLib); }; - #ifdef __POSIX__ bool DLib::Open() { handle_ = dlopen(filename_.c_str(), flags_); - if (handle_ != nullptr) - return true; + if (handle_ != nullptr) return true; errmsg_ = dlerror(); return false; } @@ -1317,7 +1280,7 @@ void DLib::Close() { void* DLib::GetSymbolAddress(const char* name) { return dlsym(handle_, name); } -#else // !__POSIX__ +#else // !__POSIX__ bool DLib::Open() { int ret = uv_dlopen(filename_.c_str(), &lib_); if (ret == 0) { @@ -1354,8 +1317,8 @@ inline InitializerCallback GetInitializerCallback(DLib* dlib) { inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) { const char* name = STRINGIFY(NAPI_MODULE_INITIALIZER_BASE) STRINGIFY(NAPI_MODULE_VERSION); - return - reinterpret_cast(dlib->GetSymbolAddress(name)); + return reinterpret_cast( + dlib->GetSymbolAddress(name)); } // DLOpen is process.dlopen(module, filename, flags). @@ -1404,8 +1367,8 @@ static void DLOpen(const FunctionCallbackInfo& args) { dlib.Close(); #ifdef _WIN32 // Windows needs to add the filename into the error message - errmsg = String::Concat(errmsg, - args[1]->ToString(context).ToLocalChecked()); + errmsg = + String::Concat(errmsg, args[1]->ToString(context).ToLocalChecked()); #endif // _WIN32 env->isolate()->ThrowException(Exception::Error(errmsg)); return; @@ -1441,7 +1404,9 @@ static void DLOpen(const FunctionCallbackInfo& args) { "\nNODE_MODULE_VERSION %d. Please try re-compiling or " "re-installing\nthe module (for instance, using `npm rebuild` " "or `npm install`).", - *filename, mp->nm_version, NODE_MODULE_VERSION); + *filename, + mp->nm_version, + NODE_MODULE_VERSION); // NOTE: `mp` is allocated inside of the shared library's memory, calling // `dlclose` will deallocate it @@ -1473,7 +1438,6 @@ static void DLOpen(const FunctionCallbackInfo& args) { // coverity[leaked_storage] } - static void OnFatalError(const char* location, const char* message) { if (location) { PrintErrorString("FATAL ERROR: %s %s\n", location, message); @@ -1484,14 +1448,12 @@ static void OnFatalError(const char* location, const char* message) { ABORT(); } - NO_RETURN void FatalError(const char* location, const char* message) { OnFatalError(location, message); // to suppress compiler warning ABORT(); } - FatalTryCatch::~FatalTryCatch() { if (HasCaught()) { HandleScope scope(env_->isolate()); @@ -1500,7 +1462,6 @@ FatalTryCatch::~FatalTryCatch() { } } - void FatalException(Isolate* isolate, Local error, Local message) { @@ -1527,8 +1488,7 @@ void FatalException(Isolate* isolate, Local caught = fatal_exception_function->Call(process_object, 1, &error); - if (fatal_try_catch.HasTerminated()) - return; + if (fatal_try_catch.HasTerminated()) return; if (fatal_try_catch.HasCaught()) { // The fatal exception function threw, so we must exit @@ -1550,7 +1510,6 @@ void FatalException(Isolate* isolate, } } - void FatalException(Isolate* isolate, const TryCatch& try_catch) { // If we try to print out a termination exception, we'd just get 'null', // so just crashing here with that information seems like a better idea, @@ -1564,7 +1523,6 @@ void FatalException(Isolate* isolate, const TryCatch& try_catch) { } } - static void OnMessage(Local message, Local error) { // The current version of V8 sends messages for errors only // (thus `error` is always set). @@ -1580,8 +1538,8 @@ static Maybe ProcessEmitWarningGeneric(Environment* env, Local process = env->process_object(); Local emit_warning; - if (!process->Get(env->context(), - env->emit_warning_string()).ToLocal(&emit_warning)) { + if (!process->Get(env->context(), env->emit_warning_string()) + .ToLocal(&emit_warning)) { return Nothing(); } @@ -1592,39 +1550,36 @@ static Maybe ProcessEmitWarningGeneric(Environment* env, // The caller has to be able to handle a failure anyway, so we might as well // do proper error checking for string creation. - if (!String::NewFromUtf8(env->isolate(), - warning, - v8::NewStringType::kNormal).ToLocal(&args[argc++])) { + if (!String::NewFromUtf8(env->isolate(), warning, v8::NewStringType::kNormal) + .ToLocal(&args[argc++])) { return Nothing(); } if (type != nullptr) { if (!String::NewFromOneByte(env->isolate(), reinterpret_cast(type), v8::NewStringType::kNormal) - .ToLocal(&args[argc++])) { + .ToLocal(&args[argc++])) { return Nothing(); } if (code != nullptr && !String::NewFromOneByte(env->isolate(), reinterpret_cast(code), v8::NewStringType::kNormal) - .ToLocal(&args[argc++])) { + .ToLocal(&args[argc++])) { return Nothing(); } } // MakeCallback() unneeded because emitWarning is internal code, it calls // process.emit('warning', ...), but does so on the nextTick. - if (emit_warning.As()->Call(env->context(), - process, - argc, - args).IsEmpty()) { + if (emit_warning.As() + ->Call(env->context(), process, argc, args) + .IsEmpty()) { return Nothing(); } return Just(true); } - // Call process.emitWarning(str), fmt is a snprintf() format string Maybe ProcessEmitWarning(Environment* env, const char* fmt, ...) { char warning[1024]; @@ -1637,38 +1592,28 @@ Maybe ProcessEmitWarning(Environment* env, const char* fmt, ...) { return ProcessEmitWarningGeneric(env, warning); } - Maybe ProcessEmitDeprecationWarning(Environment* env, const char* warning, const char* deprecation_code) { - return ProcessEmitWarningGeneric(env, - warning, - "DeprecationWarning", - deprecation_code); + return ProcessEmitWarningGeneric( + env, warning, "DeprecationWarning", deprecation_code); } - static Local InitModule(Environment* env, - node_module* mod, - Local module) { + node_module* mod, + Local module) { Local exports = Object::New(env->isolate()); // Internal bindings don't have a "module" object, only exports. CHECK_NULL(mod->nm_register_func); CHECK_NOT_NULL(mod->nm_context_register_func); Local unused = Undefined(env->isolate()); - mod->nm_context_register_func(exports, - unused, - env->context(), - mod->nm_priv); + mod->nm_context_register_func(exports, unused, env->context(), mod->nm_priv); return exports; } static void ThrowIfNoSuchModule(Environment* env, const char* module_v) { char errmsg[1024]; - snprintf(errmsg, - sizeof(errmsg), - "No such module: %s", - module_v); + snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_v); env->ThrowError(errmsg); } @@ -1686,8 +1631,8 @@ static void GetBinding(const FunctionCallbackInfo& args) { exports = InitModule(env, mod, module); } else if (!strcmp(*module_v, "constants")) { exports = Object::New(env->isolate()); - CHECK(exports->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK( + exports->SetPrototype(env->context(), Null(env->isolate())).FromJust()); DefineConstants(env->isolate(), exports); } else if (!strcmp(*module_v, "natives")) { exports = Object::New(env->isolate()); @@ -1743,15 +1688,14 @@ static void GetLinkedBinding(const FunctionCallbackInfo& args) { Local module = Object::New(env->isolate()); Local exports = Object::New(env->isolate()); - Local exports_prop = String::NewFromUtf8(env->isolate(), "exports", - v8::NewStringType::kNormal).ToLocalChecked(); + Local exports_prop = + String::NewFromUtf8(env->isolate(), "exports", v8::NewStringType::kNormal) + .ToLocalChecked(); module->Set(exports_prop, exports); if (mod->nm_context_register_func != nullptr) { - mod->nm_context_register_func(exports, - module, - env->context(), - mod->nm_priv); + mod->nm_context_register_func( + exports, module, env->context(), mod->nm_priv); } else if (mod->nm_register_func != nullptr) { mod->nm_register_func(exports, module, mod->nm_priv); } else { @@ -1767,21 +1711,20 @@ static void ProcessTitleGetter(Local property, const PropertyCallbackInfo& info) { char buffer[512]; uv_get_process_title(buffer, sizeof(buffer)); - info.GetReturnValue().Set(String::NewFromUtf8(info.GetIsolate(), buffer, - v8::NewStringType::kNormal).ToLocalChecked()); + info.GetReturnValue().Set( + String::NewFromUtf8(info.GetIsolate(), buffer, v8::NewStringType::kNormal) + .ToLocalChecked()); } - static void ProcessTitleSetter(Local property, Local value, const PropertyCallbackInfo& info) { node::Utf8Value title(info.GetIsolate(), value); - TRACE_EVENT_METADATA1("__metadata", "process_name", "name", - TRACE_STR_COPY(*title)); + TRACE_EVENT_METADATA1( + "__metadata", "process_name", "name", TRACE_STR_COPY(*title)); uv_set_process_title(*title); } - static void EnvGetter(Local property, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); @@ -1793,16 +1736,16 @@ static void EnvGetter(Local property, node::Utf8Value key(isolate, property); const char* val = getenv(*key); if (val) { - return info.GetReturnValue().Set(String::NewFromUtf8(isolate, val, - v8::NewStringType::kNormal).ToLocalChecked()); + return info.GetReturnValue().Set( + String::NewFromUtf8(isolate, val, v8::NewStringType::kNormal) + .ToLocalChecked()); } #else // _WIN32 node::TwoByteValue key(isolate, property); WCHAR buffer[32767]; // The maximum size allowed for environment variables. SetLastError(ERROR_SUCCESS); - DWORD result = GetEnvironmentVariableW(reinterpret_cast(*key), - buffer, - arraysize(buffer)); + DWORD result = GetEnvironmentVariableW( + reinterpret_cast(*key), buffer, arraysize(buffer)); // If result >= sizeof buffer the buffer was too small. That should never // happen. If result == 0 and result != ERROR_SUCCESS the variable was not // found. @@ -1815,7 +1758,6 @@ static void EnvGetter(Local property, #endif } - static void EnvSetter(Local property, Local value, const PropertyCallbackInfo& info) { @@ -1823,11 +1765,13 @@ static void EnvSetter(Local property, if (config_pending_deprecation && env->EmitProcessEnvWarning() && !value->IsString() && !value->IsNumber() && !value->IsBoolean()) { if (ProcessEmitDeprecationWarning( - env, - "Assigning any value other than a string, number, or boolean to a " - "process.env property is deprecated. Please make sure to convert the " - "value to a string before setting process.env with it.", - "DEP0104").IsNothing()) + env, + "Assigning any value other than a string, number, or boolean to a " + "process.env property is deprecated. Please make sure to convert " + "the " + "value to a string before setting process.env with it.", + "DEP0104") + .IsNothing()) return; } @@ -1849,7 +1793,6 @@ static void EnvSetter(Local property, info.GetReturnValue().Set(value); } - static void EnvQuery(Local property, const PropertyCallbackInfo& info) { Mutex::ScopedLock lock(environ_mutex); @@ -1857,8 +1800,7 @@ static void EnvQuery(Local property, if (property->IsString()) { #ifdef __POSIX__ node::Utf8Value key(info.GetIsolate(), property); - if (getenv(*key)) - rc = 0; + if (getenv(*key)) rc = 0; #else // _WIN32 node::TwoByteValue key(info.GetIsolate(), property); WCHAR* key_ptr = reinterpret_cast(*key); @@ -1875,11 +1817,9 @@ static void EnvQuery(Local property, } #endif } - if (rc != -1) - info.GetReturnValue().Set(rc); + if (rc != -1) info.GetReturnValue().Set(rc); } - static void EnvDeleter(Local property, const PropertyCallbackInfo& info) { Mutex::ScopedLock lock(environ_mutex); @@ -1899,7 +1839,6 @@ static void EnvDeleter(Local property, info.GetReturnValue().Set(true); } - static void EnvEnumerator(const PropertyCallbackInfo& info) { Environment* env = Environment::GetCurrent(info); Isolate* isolate = env->isolate(); @@ -1911,8 +1850,7 @@ static void EnvEnumerator(const PropertyCallbackInfo& info) { Mutex::ScopedLock lock(environ_mutex); #ifdef __POSIX__ int size = 0; - while (environ[size]) - size++; + while (environ[size]) size++; Local envarr = Array::New(isolate); @@ -1920,10 +1858,9 @@ static void EnvEnumerator(const PropertyCallbackInfo& info) { const char* var = environ[i]; const char* s = strchr(var, '='); const int length = s ? s - var : strlen(var); - argv[idx] = String::NewFromUtf8(isolate, - var, - v8::NewStringType::kNormal, - length).ToLocalChecked(); + argv[idx] = + String::NewFromUtf8(isolate, var, v8::NewStringType::kNormal, length) + .ToLocalChecked(); if (++idx >= arraysize(argv)) { fn->Call(ctx, envarr, idx, argv).ToLocalChecked(); idx = 0; @@ -1934,8 +1871,7 @@ static void EnvEnumerator(const PropertyCallbackInfo& info) { } #else // _WIN32 WCHAR* environment = GetEnvironmentStringsW(); - if (environment == nullptr) - return; // This should not happen. + if (environment == nullptr) return; // This should not happen. Local envarr = Array::New(isolate); WCHAR* p = environment; while (*p) { @@ -1952,10 +1888,8 @@ static void EnvEnumerator(const PropertyCallbackInfo& info) { } const uint16_t* two_byte_buffer = reinterpret_cast(p); const size_t two_byte_buffer_len = s - p; - argv[idx] = String::NewFromTwoByte(isolate, - two_byte_buffer, - String::kNormalString, - two_byte_buffer_len); + argv[idx] = String::NewFromTwoByte( + isolate, two_byte_buffer, String::kNormalString, two_byte_buffer_len); if (++idx >= arraysize(argv)) { fn->Call(ctx, envarr, idx, argv).ToLocalChecked(); idx = 0; @@ -1971,13 +1905,11 @@ static void EnvEnumerator(const PropertyCallbackInfo& info) { info.GetReturnValue().Set(envarr); } - static void GetParentProcessId(Local property, const PropertyCallbackInfo& info) { info.GetReturnValue().Set(Integer::New(info.GetIsolate(), uv_os_getppid())); } - static Local GetFeatures(Environment* env) { EscapableHandleScope scope(env->isolate()); @@ -2007,7 +1939,6 @@ static Local GetFeatures(Environment* env) { return scope.Escape(obj); } - static void DebugPortGetter(Local property, const PropertyCallbackInfo& info) { Mutex::ScopedLock lock(process_mutex); @@ -2015,14 +1946,12 @@ static void DebugPortGetter(Local property, #if HAVE_INSPECTOR if (port == 0) { Environment* env = Environment::GetCurrent(info); - if (auto io = env->inspector_agent()->io()) - port = io->port(); + if (auto io = env->inspector_agent()->io()) port = io->port(); } #endif // HAVE_INSPECTOR info.GetReturnValue().Set(port); } - static void DebugPortSetter(Local property, Local value, const PropertyCallbackInfo& info) { @@ -2030,28 +1959,28 @@ static void DebugPortSetter(Local property, debug_options.set_port(value->Int32Value()); } - static void DebugProcess(const FunctionCallbackInfo& args); static void DebugEnd(const FunctionCallbackInfo& args); namespace { -#define READONLY_PROPERTY(obj, str, var) \ - do { \ - obj->DefineOwnProperty(env->context(), \ - OneByteString(env->isolate(), str), \ - var, \ - v8::ReadOnly).FromJust(); \ +#define READONLY_PROPERTY(obj, str, var) \ + do { \ + obj->DefineOwnProperty(env->context(), \ + OneByteString(env->isolate(), str), \ + var, \ + v8::ReadOnly) \ + .FromJust(); \ } while (0) -#define READONLY_DONT_ENUM_PROPERTY(obj, str, var) \ - do { \ - obj->DefineOwnProperty(env->context(), \ - OneByteString(env->isolate(), str), \ - var, \ - static_cast(v8::ReadOnly | \ - v8::DontEnum)) \ - .FromJust(); \ +#define READONLY_DONT_ENUM_PROPERTY(obj, str, var) \ + do { \ + obj->DefineOwnProperty( \ + env->context(), \ + OneByteString(env->isolate(), str), \ + var, \ + static_cast(v8::ReadOnly | v8::DontEnum)) \ + .FromJust(); \ } while (0) } // anonymous namespace @@ -2066,46 +1995,44 @@ void SetupProcessObject(Environment* env, Local process = env->process_object(); auto title_string = FIXED_ONE_BYTE_STRING(env->isolate(), "title"); - CHECK(process->SetAccessor( - env->context(), - title_string, - ProcessTitleGetter, - env->is_main_thread() ? ProcessTitleSetter : nullptr, - env->as_external(), - v8::DEFAULT, - v8::None, - SideEffectType::kHasNoSideEffect).FromJust()); + CHECK(process + ->SetAccessor(env->context(), + title_string, + ProcessTitleGetter, + env->is_main_thread() ? ProcessTitleSetter : nullptr, + env->as_external(), + v8::DEFAULT, + v8::None, + SideEffectType::kHasNoSideEffect) + .FromJust()); // process.version - READONLY_PROPERTY(process, - "version", - FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION)); + READONLY_PROPERTY( + process, "version", FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION)); // process.versions Local versions = Object::New(env->isolate()); READONLY_PROPERTY(process, "versions", versions); - - const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) - "." - NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR) - "." - NODE_STRINGIFY(HTTP_PARSER_VERSION_PATCH); + // clang-format off + const char http_parser_version[] = + NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) + "." + NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR) + "." + NODE_STRINGIFY(HTTP_PARSER_VERSION_PATCH); + // clang-format on READONLY_PROPERTY(versions, "http_parser", FIXED_ONE_BYTE_STRING(env->isolate(), http_parser_version)); // +1 to get rid of the leading 'v' - READONLY_PROPERTY(versions, - "node", - OneByteString(env->isolate(), NODE_VERSION + 1)); - READONLY_PROPERTY(versions, - "v8", - OneByteString(env->isolate(), V8::GetVersion())); - READONLY_PROPERTY(versions, - "uv", - OneByteString(env->isolate(), uv_version_string())); - READONLY_PROPERTY(versions, - "zlib", - FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION)); + READONLY_PROPERTY( + versions, "node", OneByteString(env->isolate(), NODE_VERSION + 1)); + READONLY_PROPERTY( + versions, "v8", OneByteString(env->isolate(), V8::GetVersion())); + READONLY_PROPERTY( + versions, "uv", OneByteString(env->isolate(), uv_version_string())); + READONLY_PROPERTY( + versions, "zlib", FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION)); READONLY_PROPERTY(versions, "ares", FIXED_ONE_BYTE_STRING(env->isolate(), ARES_VERSION_STR)); @@ -2119,10 +2046,9 @@ void SetupProcessObject(Environment* env, "nghttp2", FIXED_ONE_BYTE_STRING(env->isolate(), NGHTTP2_VERSION)); const char node_napi_version[] = NODE_STRINGIFY(NAPI_VERSION); - READONLY_PROPERTY( - versions, - "napi", - FIXED_ONE_BYTE_STRING(env->isolate(), node_napi_version)); + READONLY_PROPERTY(versions, + "napi", + FIXED_ONE_BYTE_STRING(env->isolate(), node_napi_version)); #if HAVE_OPENSSL // Stupid code to slice out the version string. @@ -2134,8 +2060,7 @@ void SetupProcessObject(Environment* env, if ('0' <= c && c <= '9') { for (j = i + 1; j < k; ++j) { c = OPENSSL_VERSION_TEXT[j]; - if (c == ' ') - break; + if (c == ' ') break; } break; } @@ -2151,65 +2076,69 @@ void SetupProcessObject(Environment* env, READONLY_PROPERTY(process, "arch", OneByteString(env->isolate(), NODE_ARCH)); // process.platform - READONLY_PROPERTY(process, - "platform", - OneByteString(env->isolate(), NODE_PLATFORM)); + READONLY_PROPERTY( + process, "platform", OneByteString(env->isolate(), NODE_PLATFORM)); // process.release Local release = Object::New(env->isolate()); READONLY_PROPERTY(process, "release", release); - READONLY_PROPERTY(release, "name", - OneByteString(env->isolate(), NODE_RELEASE)); + READONLY_PROPERTY( + release, "name", OneByteString(env->isolate(), NODE_RELEASE)); #if NODE_VERSION_IS_LTS - READONLY_PROPERTY(release, "lts", - OneByteString(env->isolate(), NODE_VERSION_LTS_CODENAME)); + READONLY_PROPERTY( + release, "lts", OneByteString(env->isolate(), NODE_VERSION_LTS_CODENAME)); #endif // if this is a release build and no explicit base has been set // substitute the standard release download URL #ifndef NODE_RELEASE_URLBASE -# if NODE_VERSION_IS_RELEASE -# define NODE_RELEASE_URLBASE "https://nodejs.org/download/release/" -# endif +#if NODE_VERSION_IS_RELEASE +#define NODE_RELEASE_URLBASE "https://nodejs.org/download/release/" +#endif #endif #if defined(NODE_RELEASE_URLBASE) -# define NODE_RELEASE_URLPFX NODE_RELEASE_URLBASE "v" NODE_VERSION_STRING "/" -# define NODE_RELEASE_URLFPFX NODE_RELEASE_URLPFX "node-v" NODE_VERSION_STRING - - READONLY_PROPERTY(release, - "sourceUrl", - OneByteString(env->isolate(), - NODE_RELEASE_URLFPFX ".tar.gz")); - READONLY_PROPERTY(release, - "headersUrl", - OneByteString(env->isolate(), - NODE_RELEASE_URLFPFX "-headers.tar.gz")); -# ifdef _WIN32 - READONLY_PROPERTY(release, - "libUrl", - OneByteString(env->isolate(), - strcmp(NODE_ARCH, "ia32") ? NODE_RELEASE_URLPFX "win-" - NODE_ARCH "/node.lib" - : NODE_RELEASE_URLPFX - "win-x86/node.lib")); -# endif +#define NODE_RELEASE_URLPFX NODE_RELEASE_URLBASE "v" NODE_VERSION_STRING "/" +#define NODE_RELEASE_URLFPFX NODE_RELEASE_URLPFX "node-v" NODE_VERSION_STRING + + READONLY_PROPERTY( + release, + "sourceUrl", + OneByteString(env->isolate(), NODE_RELEASE_URLFPFX ".tar.gz")); + READONLY_PROPERTY( + release, + "headersUrl", + OneByteString(env->isolate(), NODE_RELEASE_URLFPFX "-headers.tar.gz")); +#ifdef _WIN32 + READONLY_PROPERTY( + release, + "libUrl", + OneByteString(env->isolate(), + strcmp(NODE_ARCH, "ia32") + ? NODE_RELEASE_URLPFX "win-" NODE_ARCH "/node.lib" + : NODE_RELEASE_URLPFX "win-x86/node.lib")); +#endif #endif // process.argv Local arguments = Array::New(env->isolate(), argc); for (int i = 0; i < argc; ++i) { - arguments->Set(i, String::NewFromUtf8(env->isolate(), argv[i], - v8::NewStringType::kNormal).ToLocalChecked()); + arguments->Set( + i, + String::NewFromUtf8(env->isolate(), argv[i], v8::NewStringType::kNormal) + .ToLocalChecked()); } process->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "argv"), arguments); // process.execArgv Local exec_arguments = Array::New(env->isolate(), exec_argc); for (int i = 0; i < exec_argc; ++i) { - exec_arguments->Set(i, String::NewFromUtf8(env->isolate(), exec_argv[i], - v8::NewStringType::kNormal).ToLocalChecked()); + exec_arguments->Set( + i, + String::NewFromUtf8( + env->isolate(), exec_argv[i], v8::NewStringType::kNormal) + .ToLocalChecked()); } process->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "execArgv"), exec_arguments); @@ -2217,32 +2146,36 @@ void SetupProcessObject(Environment* env, // create process.env Local process_env_template = ObjectTemplate::New(env->isolate()); - process_env_template->SetHandler(NamedPropertyHandlerConfiguration( - EnvGetter, - EnvSetter, - EnvQuery, - EnvDeleter, - EnvEnumerator, - env->as_external())); + process_env_template->SetHandler( + NamedPropertyHandlerConfiguration(EnvGetter, + EnvSetter, + EnvQuery, + EnvDeleter, + EnvEnumerator, + env->as_external())); Local process_env = process_env_template->NewInstance(env->context()).ToLocalChecked(); process->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "env"), process_env); - READONLY_PROPERTY(process, "pid", - Integer::New(env->isolate(), uv_os_getpid())); + READONLY_PROPERTY( + process, "pid", Integer::New(env->isolate(), uv_os_getpid())); READONLY_PROPERTY(process, "features", GetFeatures(env)); - CHECK(process->SetAccessor(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "ppid"), - GetParentProcessId).FromJust()); + CHECK(process + ->SetAccessor(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "ppid"), + GetParentProcessId) + .FromJust()); // -e, --eval if (eval_string) { - READONLY_PROPERTY(process, - "_eval", - String::NewFromUtf8(env->isolate(), eval_string, - v8::NewStringType::kNormal).ToLocalChecked()); + READONLY_PROPERTY( + process, + "_eval", + String::NewFromUtf8( + env->isolate(), eval_string, v8::NewStringType::kNormal) + .ToLocalChecked()); } // -p, --print @@ -2270,9 +2203,7 @@ void SetupProcessObject(Environment* env, .ToLocalChecked(); array->Set(i, module); } - READONLY_PROPERTY(process, - "_preload_modules", - array); + READONLY_PROPERTY(process, "_preload_modules", array); preload_modules.clear(); } @@ -2315,33 +2246,32 @@ void SetupProcessObject(Environment* env, // TODO(refack): move the following 3 to `node_config` // --inspect-brk if (debug_options.wait_for_connect()) { - READONLY_DONT_ENUM_PROPERTY(process, - "_breakFirstLine", True(env->isolate())); + READONLY_DONT_ENUM_PROPERTY( + process, "_breakFirstLine", True(env->isolate())); } if (debug_options.break_node_first_line()) { - READONLY_DONT_ENUM_PROPERTY(process, - "_breakNodeFirstLine", True(env->isolate())); + READONLY_DONT_ENUM_PROPERTY( + process, "_breakNodeFirstLine", True(env->isolate())); } // --inspect --debug-brk if (debug_options.deprecated_invocation()) { - READONLY_DONT_ENUM_PROPERTY(process, - "_deprecatedDebugBrk", True(env->isolate())); + READONLY_DONT_ENUM_PROPERTY( + process, "_deprecatedDebugBrk", True(env->isolate())); } // --debug or, --debug-brk without --inspect if (debug_options.invalid_invocation()) { - READONLY_DONT_ENUM_PROPERTY(process, - "_invalidDebug", True(env->isolate())); + READONLY_DONT_ENUM_PROPERTY(process, "_invalidDebug", True(env->isolate())); } // --security-revert flags -#define V(code, _, __) \ - do { \ - if (IsReverted(SECURITY_REVERT_ ## code)) { \ - READONLY_PROPERTY(process, "REVERT_" #code, True(env->isolate())); \ - } \ +#define V(code, _, __) \ + do { \ + if (IsReverted(SECURITY_REVERT_##code)) { \ + READONLY_PROPERTY(process, "REVERT_" #code, True(env->isolate())); \ + } \ } while (0); SECURITY_REVERSIONS(V) #undef V @@ -2353,32 +2283,35 @@ void SetupProcessObject(Environment* env, exec_path_value = String::NewFromUtf8(env->isolate(), exec_path, v8::NewStringType::kInternalized, - exec_path_len).ToLocalChecked(); + exec_path_len) + .ToLocalChecked(); } else { - exec_path_value = String::NewFromUtf8(env->isolate(), argv[0], - v8::NewStringType::kInternalized).ToLocalChecked(); + exec_path_value = + String::NewFromUtf8( + env->isolate(), argv[0], v8::NewStringType::kInternalized) + .ToLocalChecked(); } process->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "execPath"), exec_path_value); delete[] exec_path; auto debug_port_string = FIXED_ONE_BYTE_STRING(env->isolate(), "debugPort"); - CHECK(process->SetAccessor(env->context(), - debug_port_string, - DebugPortGetter, - env->is_main_thread() ? DebugPortSetter : nullptr, - env->as_external()).FromJust()); + CHECK(process + ->SetAccessor(env->context(), + debug_port_string, + DebugPortGetter, + env->is_main_thread() ? DebugPortSetter : nullptr, + env->as_external()) + .FromJust()); // define various internal methods if (env->is_main_thread()) { env->SetMethod(process, "_debugProcess", DebugProcess); env->SetMethod(process, "_debugEnd", DebugEnd); - env->SetMethod(process, - "_startProfilerIdleNotifier", - StartProfilerIdleNotifier); - env->SetMethod(process, - "_stopProfilerIdleNotifier", - StopProfilerIdleNotifier); + env->SetMethod( + process, "_startProfilerIdleNotifier", StartProfilerIdleNotifier); + env->SetMethod( + process, "_stopProfilerIdleNotifier", StopProfilerIdleNotifier); env->SetMethod(process, "abort", Abort); env->SetMethod(process, "chdir", Chdir); env->SetMethod(process, "umask", Umask); @@ -2401,10 +2334,8 @@ void SetupProcessObject(Environment* env, #endif // __POSIX__ && !defined(__ANDROID__) && !defined(__CloudABI__) } - #undef READONLY_PROPERTY - void SignalExit(int signo) { uv_tty_reset_mode(); v8_platform.StopTracingAgent(); @@ -2418,11 +2349,9 @@ void SignalExit(int signo) { raise(signo); } - -static MaybeLocal GetBootstrapper( - Environment* env, - Local source, - Local script_name) { +static MaybeLocal GetBootstrapper(Environment* env, + Local source, + Local script_name) { EscapableHandleScope scope(env->isolate()); TryCatch try_catch(env->isolate()); @@ -2437,7 +2366,7 @@ static MaybeLocal GetBootstrapper( if (bootstrapper_v.IsEmpty()) // This happens when execution was interrupted. return MaybeLocal(); - if (try_catch.HasCaught()) { + if (try_catch.HasCaught()) { ReportException(env, try_catch); exit(10); } @@ -2446,11 +2375,14 @@ static MaybeLocal GetBootstrapper( return scope.Escape(bootstrapper_v.ToLocalChecked().As()); } -static bool ExecuteBootstrapper(Environment* env, Local bootstrapper, - int argc, Local argv[], +static bool ExecuteBootstrapper(Environment* env, + Local bootstrapper, + int argc, + Local argv[], Local* out) { - bool ret = bootstrapper->Call( - env->context(), Null(env->isolate()), argc, argv).ToLocal(out); + bool ret = + bootstrapper->Call(env->context(), Null(env->isolate()), argc, argv) + .ToLocal(out); // If there was an error during bootstrap then it was either handled by the // FatalException handler or it's unrecoverable (e.g. max call stack @@ -2466,7 +2398,6 @@ static bool ExecuteBootstrapper(Environment* env, Local bootstrapper, return ret; } - void LoadEnvironment(Environment* env) { HandleScope handle_scope(env->isolate()); @@ -2520,29 +2451,31 @@ void LoadEnvironment(Environment* env) { global->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "global"), global); // Create binding loaders - v8::Local get_binding_fn = - env->NewFunctionTemplate(GetBinding)->GetFunction(env->context()) - .ToLocalChecked(); + v8::Local get_binding_fn = env->NewFunctionTemplate(GetBinding) + ->GetFunction(env->context()) + .ToLocalChecked(); v8::Local get_linked_binding_fn = - env->NewFunctionTemplate(GetLinkedBinding)->GetFunction(env->context()) + env->NewFunctionTemplate(GetLinkedBinding) + ->GetFunction(env->context()) .ToLocalChecked(); v8::Local get_internal_binding_fn = - env->NewFunctionTemplate(GetInternalBinding)->GetFunction(env->context()) + env->NewFunctionTemplate(GetInternalBinding) + ->GetFunction(env->context()) .ToLocalChecked(); Local loaders_bootstrapper_args[] = { - env->process_object(), - get_binding_fn, - get_linked_binding_fn, - get_internal_binding_fn, - Boolean::New(env->isolate(), debug_options.break_node_first_line()) - }; + env->process_object(), + get_binding_fn, + get_linked_binding_fn, + get_internal_binding_fn, + Boolean::New(env->isolate(), debug_options.break_node_first_line())}; // Bootstrap internal loaders Local bootstrapped_loaders; - if (!ExecuteBootstrapper(env, loaders_bootstrapper.ToLocalChecked(), + if (!ExecuteBootstrapper(env, + loaders_bootstrapper.ToLocalChecked(), arraysize(loaders_bootstrapper_args), loaders_bootstrapper_args, &bootstrapped_loaders)) { @@ -2554,11 +2487,9 @@ void LoadEnvironment(Environment* env) { SetupBootstrapObject(env, bootstrapper); Local bootstrapped_node; Local node_bootstrapper_args[] = { - env->process_object(), - bootstrapper, - bootstrapped_loaders - }; - if (!ExecuteBootstrapper(env, node_bootstrapper.ToLocalChecked(), + env->process_object(), bootstrapper, bootstrapped_loaders}; + if (!ExecuteBootstrapper(env, + node_bootstrapper.ToLocalChecked(), arraysize(node_bootstrapper_args), node_bootstrapper_args, &bootstrapped_node)) { @@ -2722,92 +2653,83 @@ static void PrintHelp() { "Documentation can be found at https://nodejs.org/\n"); } - static bool ArgIsAllowed(const char* arg, const char* allowed) { for (; *arg && *allowed; arg++, allowed++) { // Like normal strcmp(), except that a '_' in `allowed` matches either a '-' // or '_' in `arg`. if (*allowed == '_') { - if (!(*arg == '_' || *arg == '-')) - return false; + if (!(*arg == '_' || *arg == '-')) return false; } else { - if (*arg != *allowed) - return false; + if (*arg != *allowed) return false; } } // "--some-arg=val" is allowed for "--some-arg" - if (*arg == '=') - return true; + if (*arg == '=') return true; // Both must be null, or one string is just a prefix of the other, not a // match. return !*arg && !*allowed; } - -static void CheckIfAllowedInEnv(const char* exe, bool is_env, - const char* arg) { - if (!is_env) - return; +static void CheckIfAllowedInEnv(const char* exe, bool is_env, const char* arg) { + if (!is_env) return; static const char* whitelist[] = { - // Node options, sorted in `node --help` order for ease of comparison. - // Please, update NODE_OPTIONS section in cli.md if changed. - "--enable-fips", - "--experimental-modules", - "--experimental-repl-await", - "--experimental-vm-modules", - "--experimental-worker", - "--force-fips", - "--icu-data-dir", - "--inspect", - "--inspect-brk", - "--inspect-port", - "--loader", - "--napi-modules", - "--no-deprecation", - "--no-force-async-hooks-checks", - "--no-warnings", - "--openssl-config", - "--pending-deprecation", - "--redirect-warnings", - "--require", - "--throw-deprecation", - "--title", - "--tls-cipher-list", - "--trace-deprecation", - "--trace-event-categories", - "--trace-event-file-pattern", - "--trace-events-enabled", - "--trace-sync-io", - "--trace-warnings", - "--track-heap-objects", - "--use-bundled-ca", - "--use-openssl-ca", - "--v8-pool-size", - "--zero-fill-buffers", - "-r", - - // V8 options (define with '_', which allows '-' or '_') - "--abort_on_uncaught_exception", - "--max_old_space_size", - "--perf_basic_prof", - "--perf_prof", - "--stack_trace_limit", + // Node options, sorted in `node --help` order for ease of comparison. + // Please, update NODE_OPTIONS section in cli.md if changed. + "--enable-fips", + "--experimental-modules", + "--experimental-repl-await", + "--experimental-vm-modules", + "--experimental-worker", + "--force-fips", + "--icu-data-dir", + "--inspect", + "--inspect-brk", + "--inspect-port", + "--loader", + "--napi-modules", + "--no-deprecation", + "--no-force-async-hooks-checks", + "--no-warnings", + "--openssl-config", + "--pending-deprecation", + "--redirect-warnings", + "--require", + "--throw-deprecation", + "--title", + "--tls-cipher-list", + "--trace-deprecation", + "--trace-event-categories", + "--trace-event-file-pattern", + "--trace-events-enabled", + "--trace-sync-io", + "--trace-warnings", + "--track-heap-objects", + "--use-bundled-ca", + "--use-openssl-ca", + "--v8-pool-size", + "--zero-fill-buffers", + "-r", + + // V8 options (define with '_', which allows '-' or '_') + "--abort_on_uncaught_exception", + "--max_old_space_size", + "--perf_basic_prof", + "--perf_prof", + "--stack_trace_limit", }; for (unsigned i = 0; i < arraysize(whitelist); i++) { const char* allowed = whitelist[i]; - if (ArgIsAllowed(arg, allowed)) - return; + if (ArgIsAllowed(arg, allowed)) return; } fprintf(stderr, "%s: %s is not allowed in NODE_OPTIONS\n", exe, arg); exit(9); } - // Parse command line arguments. // // argv is modified in place. exec_argv and v8_argv are out arguments that @@ -2864,10 +2786,8 @@ static void ParseArgs(int* argc, } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) { PrintHelp(); exit(0); - } else if (strcmp(arg, "--eval") == 0 || - strcmp(arg, "-e") == 0 || - strcmp(arg, "--print") == 0 || - strcmp(arg, "-pe") == 0 || + } else if (strcmp(arg, "--eval") == 0 || strcmp(arg, "-e") == 0 || + strcmp(arg, "--print") == 0 || strcmp(arg, "-pe") == 0 || strcmp(arg, "-p") == 0) { bool is_eval = strchr(arg, 'e') != nullptr; bool is_print = strchr(arg, 'p') != nullptr; @@ -2880,8 +2800,7 @@ static void ParseArgs(int* argc, fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg); exit(9); } - } else if ((index + 1 < nargs) && - argv[index + 1] != nullptr && + } else if ((index + 1 < nargs) && argv[index + 1] != nullptr && argv[index + 1][0] != '-') { args_consumed += 1; eval_string = argv[index + 1]; @@ -2890,8 +2809,7 @@ static void ParseArgs(int* argc, eval_string += 1; } } - } else if (strcmp(arg, "--require") == 0 || - strcmp(arg, "-r") == 0) { + } else if (strcmp(arg, "--require") == 0 || strcmp(arg, "-r") == 0) { const char* module = argv[index + 1]; if (module == nullptr) { fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg); @@ -2963,11 +2881,13 @@ static void ParseArgs(int* argc, config_experimental_worker = true; } else if (strcmp(arg, "--experimental-repl-await") == 0) { config_experimental_repl_await = true; - } else if (strcmp(arg, "--loader") == 0) { + } else if (strcmp(arg, "--loader") == 0) { const char* module = argv[index + 1]; if (!config_experimental_modules) { - fprintf(stderr, "%s: %s requires --experimental-modules be enabled\n", - argv[0], arg); + fprintf(stderr, + "%s: %s requires --experimental-modules be enabled\n", + argv[0], + arg); exit(9); } if (module == nullptr) { @@ -3050,7 +2970,8 @@ static void ParseArgs(int* argc, if (eval_string != nullptr && syntax_check_only) { fprintf(stderr, - "%s: either --check or --eval can be used, not both\n", argv[0]); + "%s: either --check or --eval can be used, not both\n", + argv[0]); exit(9); } @@ -3058,8 +2979,10 @@ static void ParseArgs(int* argc, const unsigned int args_left = nargs - index; if (is_env && args_left) { - fprintf(stderr, "%s: %s is not supported in NODE_OPTIONS\n", - argv[0], argv[index]); + fprintf(stderr, + "%s: %s is not supported in NODE_OPTIONS\n", + argv[0], + argv[index]); exit(9); } @@ -3077,8 +3000,8 @@ static void ParseArgs(int* argc, *argc = static_cast(new_argc); } - -static void StartInspector(Environment* env, const char* path, +static void StartInspector(Environment* env, + const char* path, DebugOptions debug_options) { #if HAVE_INSPECTOR CHECK(!env->inspector_agent()->IsListening()); @@ -3086,7 +3009,6 @@ static void StartInspector(Environment* env, const char* path, #endif // HAVE_INSPECTOR } - #ifdef __POSIX__ void RegisterSignalHandler(int signal, void (*handler)(int signal), @@ -3104,7 +3026,6 @@ void RegisterSignalHandler(int signal, CHECK_EQ(sigaction(signal, &sa, nullptr), 0); } - void DebugProcess(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3123,14 +3044,13 @@ void DebugProcess(const FunctionCallbackInfo& args) { } #endif // __POSIX__ - #ifdef _WIN32 -static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf, - size_t buf_len) { +static int GetDebugSignalHandlerMappingName(DWORD pid, + wchar_t* buf, + size_t buf_len) { return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid); } - static void DebugProcess(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = args.GetIsolate(); @@ -3146,81 +3066,63 @@ static void DebugProcess(const FunctionCallbackInfo& args) { goto out; } - pid = (DWORD) args[0]->IntegerValue(); + pid = (DWORD)args[0]->IntegerValue(); - process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | - PROCESS_VM_OPERATION | PROCESS_VM_WRITE | - PROCESS_VM_READ, - FALSE, - pid); + process = + OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | + PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, + FALSE, + pid); if (process == nullptr) { isolate->ThrowException( WinapiErrnoException(isolate, GetLastError(), "OpenProcess")); goto out; } - if (GetDebugSignalHandlerMappingName(pid, - mapping_name, - arraysize(mapping_name)) < 0) { + if (GetDebugSignalHandlerMappingName( + pid, mapping_name, arraysize(mapping_name)) < 0) { env->ThrowErrnoException(errno, "sprintf"); goto out; } mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name); if (mapping == nullptr) { - isolate->ThrowException(WinapiErrnoException(isolate, - GetLastError(), - "OpenFileMappingW")); + isolate->ThrowException( + WinapiErrnoException(isolate, GetLastError(), "OpenFileMappingW")); goto out; } handler = reinterpret_cast( - MapViewOfFile(mapping, - FILE_MAP_READ, - 0, - 0, - sizeof *handler)); + MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, sizeof *handler)); if (handler == nullptr || *handler == nullptr) { isolate->ThrowException( WinapiErrnoException(isolate, GetLastError(), "MapViewOfFile")); goto out; } - thread = CreateRemoteThread(process, - nullptr, - 0, - *handler, - nullptr, - 0, - nullptr); + thread = + CreateRemoteThread(process, nullptr, 0, *handler, nullptr, 0, nullptr); if (thread == nullptr) { - isolate->ThrowException(WinapiErrnoException(isolate, - GetLastError(), - "CreateRemoteThread")); + isolate->ThrowException( + WinapiErrnoException(isolate, GetLastError(), "CreateRemoteThread")); goto out; } // Wait for the thread to terminate if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) { - isolate->ThrowException(WinapiErrnoException(isolate, - GetLastError(), - "WaitForSingleObject")); + isolate->ThrowException( + WinapiErrnoException(isolate, GetLastError(), "WaitForSingleObject")); goto out; } - out: - if (process != nullptr) - CloseHandle(process); - if (thread != nullptr) - CloseHandle(thread); - if (handler != nullptr) - UnmapViewOfFile(handler); - if (mapping != nullptr) - CloseHandle(mapping); +out: + if (process != nullptr) CloseHandle(process); + if (thread != nullptr) CloseHandle(thread); + if (handler != nullptr) UnmapViewOfFile(handler); + if (mapping != nullptr) CloseHandle(mapping); } #endif // _WIN32 - static void DebugEnd(const FunctionCallbackInfo& args) { #if HAVE_INSPECTOR Environment* env = Environment::GetCurrent(args); @@ -3230,7 +3132,6 @@ static void DebugEnd(const FunctionCallbackInfo& args) { #endif } - inline void PlatformInit() { #ifdef __POSIX__ #if HAVE_INSPECTOR @@ -3243,14 +3144,11 @@ inline void PlatformInit() { // Make sure file descriptors 0-2 are valid before we start logging anything. for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd += 1) { struct stat ignored; - if (fstat(fd, &ignored) == 0) - continue; + if (fstat(fd, &ignored) == 0) continue; // Anything but EBADF means something is seriously wrong. We don't // have to special-case EINTR, fstat() is not interruptible. - if (errno != EBADF) - ABORT(); - if (fd != open("/dev/null", O_RDWR)) - ABORT(); + if (errno != EBADF) ABORT(); + if (fd != open("/dev/null", O_RDWR)) ABORT(); } #if HAVE_INSPECTOR @@ -3266,8 +3164,7 @@ inline void PlatformInit() { // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled. // Counting up to SIGRTMIN doesn't work for the same reason. for (unsigned nr = 1; nr < kMaxSignal; nr += 1) { - if (nr == SIGKILL || nr == SIGSTOP) - continue; + if (nr == SIGKILL || nr == SIGSTOP) continue; act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL; CHECK_EQ(0, sigaction(nr, &act, nullptr)); } @@ -3305,14 +3202,12 @@ inline void PlatformInit() { // Ignore _close result. If it fails or not depends on used Windows // version. We will just check _open result. _close(fd); - if (fd != _open("nul", _O_RDWR)) - ABORT(); + if (fd != _open("nul", _O_RDWR)) ABORT(); } } #endif // _WIN32 } - void ProcessArgv(int* argc, const char** argv, int* exec_argc, @@ -3360,7 +3255,6 @@ void ProcessArgv(int* argc, } } - void Init(int* argc, const char** argv, int* exec_argc, @@ -3404,8 +3298,7 @@ void Init(int* argc, SafeGetenv("NODE_REDIRECT_WARNINGS", &config_warning_file); #if HAVE_OPENSSL - if (openssl_config.empty()) - SafeGetenv("OPENSSL_CONF", &openssl_config); + if (openssl_config.empty()) SafeGetenv("OPENSSL_CONF", &openssl_config); #endif #if !defined(NODE_WITHOUT_NODE_OPTIONS) @@ -3444,8 +3337,7 @@ void Init(int* argc, #if defined(NODE_HAVE_I18N_SUPPORT) // If the parameter isn't given, use the env variable. - if (icu_data_dir.empty()) - SafeGetenv("NODE_ICU_DATA", &icu_data_dir); + if (icu_data_dir.empty()) SafeGetenv("NODE_ICU_DATA", &icu_data_dir); // Initialize ICU. // If icu_data_dir is empty here, it will load the 'minimal' data. if (!i18n::InitializeICUDirectory(icu_data_dir)) { @@ -3463,57 +3355,48 @@ void Init(int* argc, node_is_initialized = true; } - void RunAtExit(Environment* env) { env->RunAtExitCallbacks(); } - uv_loop_t* GetCurrentEventLoop(v8::Isolate* isolate) { HandleScope handle_scope(isolate); auto context = isolate->GetCurrentContext(); - if (context.IsEmpty()) - return nullptr; + if (context.IsEmpty()) return nullptr; return Environment::GetCurrent(context)->event_loop(); } - void AtExit(void (*cb)(void* arg), void* arg) { auto env = Environment::GetThreadLocalEnv(); AtExit(env, cb, arg); } - void AtExit(Environment* env, void (*cb)(void* arg), void* arg) { CHECK_NOT_NULL(env); env->AtExit(cb, arg); } - void RunBeforeExit(Environment* env) { env->RunBeforeExitCallbacks(); - if (!uv_loop_alive(env->event_loop())) - EmitBeforeExit(env); + if (!uv_loop_alive(env->event_loop())) EmitBeforeExit(env); } - void EmitBeforeExit(Environment* env) { HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); Local process_object = env->process_object(); Local exit_code = env->exit_code_string(); - Local args[] = { - FIXED_ONE_BYTE_STRING(env->isolate(), "beforeExit"), - process_object->Get(env->context(), exit_code).ToLocalChecked() - ->ToInteger(env->context()).ToLocalChecked() - }; - MakeCallback(env->isolate(), - process_object, "emit", arraysize(args), args, - {0, 0}).ToLocalChecked(); + Local args[] = {FIXED_ONE_BYTE_STRING(env->isolate(), "beforeExit"), + process_object->Get(env->context(), exit_code) + .ToLocalChecked() + ->ToInteger(env->context()) + .ToLocalChecked()}; + MakeCallback( + env->isolate(), process_object, "emit", arraysize(args), args, {0, 0}) + .ToLocalChecked(); } - int EmitExit(Environment* env) { // process.emit('exit') HandleScope handle_scope(env->isolate()); @@ -3523,61 +3406,54 @@ int EmitExit(Environment* env) { True(env->isolate())); Local exit_code = env->exit_code_string(); - int code = process_object->Get(env->context(), exit_code).ToLocalChecked() - ->Int32Value(env->context()).ToChecked(); + int code = process_object->Get(env->context(), exit_code) + .ToLocalChecked() + ->Int32Value(env->context()) + .ToChecked(); - Local args[] = { - FIXED_ONE_BYTE_STRING(env->isolate(), "exit"), - Integer::New(env->isolate(), code) - }; + Local args[] = {FIXED_ONE_BYTE_STRING(env->isolate(), "exit"), + Integer::New(env->isolate(), code)}; - MakeCallback(env->isolate(), - process_object, "emit", arraysize(args), args, - {0, 0}).ToLocalChecked(); + MakeCallback( + env->isolate(), process_object, "emit", arraysize(args), args, {0, 0}) + .ToLocalChecked(); // Reload exit code, it may be changed by `emit('exit')` - return process_object->Get(env->context(), exit_code).ToLocalChecked() - ->Int32Value(env->context()).ToChecked(); + return process_object->Get(env->context(), exit_code) + .ToLocalChecked() + ->Int32Value(env->context()) + .ToChecked(); } - ArrayBufferAllocator* CreateArrayBufferAllocator() { return new ArrayBufferAllocator(); } - void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator) { delete allocator; } - IsolateData* CreateIsolateData(Isolate* isolate, uv_loop_t* loop) { return new IsolateData(isolate, loop, nullptr); } - -IsolateData* CreateIsolateData( - Isolate* isolate, - uv_loop_t* loop, - MultiIsolatePlatform* platform) { +IsolateData* CreateIsolateData(Isolate* isolate, + uv_loop_t* loop, + MultiIsolatePlatform* platform) { return new IsolateData(isolate, loop, platform); } - -IsolateData* CreateIsolateData( - Isolate* isolate, - uv_loop_t* loop, - MultiIsolatePlatform* platform, - ArrayBufferAllocator* allocator) { +IsolateData* CreateIsolateData(Isolate* isolate, + uv_loop_t* loop, + MultiIsolatePlatform* platform, + ArrayBufferAllocator* allocator) { return new IsolateData(isolate, loop, platform, allocator->zero_fill_field()); } - void FreeIsolateData(IsolateData* isolate_data) { delete isolate_data; } - Environment* CreateEnvironment(IsolateData* isolate_data, Local context, int argc, @@ -3587,63 +3463,58 @@ Environment* CreateEnvironment(IsolateData* isolate_data, Isolate* isolate = context->GetIsolate(); HandleScope handle_scope(isolate); Context::Scope context_scope(context); - auto env = new Environment(isolate_data, context, - v8_platform.GetTracingAgent()); + auto env = + new Environment(isolate_data, context, v8_platform.GetTracingAgent()); env->Start(argc, argv, exec_argc, exec_argv, v8_is_profiling); return env; } - void FreeEnvironment(Environment* env) { env->RunCleanup(); delete env; } - MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform() { return v8_platform.Platform(); } - MultiIsolatePlatform* CreatePlatform( - int thread_pool_size, - v8::TracingController* tracing_controller) { + int thread_pool_size, v8::TracingController* tracing_controller) { return new NodePlatform(thread_pool_size, tracing_controller); } - void FreePlatform(MultiIsolatePlatform* platform) { delete platform; } - Local NewContext(Isolate* isolate, Local object_template) { auto context = Context::New(isolate, nullptr, object_template); if (context.IsEmpty()) return context; HandleScope handle_scope(isolate); - context->SetEmbedderData( - ContextEmbedderIndex::kAllowWasmCodeGeneration, True(isolate)); + context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration, + True(isolate)); { // Run lib/internal/per_context.js Context::Scope context_scope(context); Local per_context = NodePerContextSource(isolate); v8::ScriptCompiler::Source per_context_src(per_context, nullptr); - Local s = v8::ScriptCompiler::Compile( - context, - &per_context_src).ToLocalChecked(); + Local s = + v8::ScriptCompiler::Compile(context, &per_context_src).ToLocalChecked(); s->Run(context).ToLocalChecked(); } return context; } - -inline int Start(Isolate* isolate, IsolateData* isolate_data, - int argc, const char* const* argv, - int exec_argc, const char* const* exec_argv) { +inline int Start(Isolate* isolate, + IsolateData* isolate_data, + int argc, + const char* const* argv, + int exec_argc, + const char* const* exec_argv) { HandleScope handle_scope(isolate); Local context = NewContext(isolate); Context::Scope context_scope(context); @@ -3682,8 +3553,7 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data, v8_platform.DrainVMTasks(isolate); more = uv_loop_alive(env.event_loop()); - if (more) - continue; + if (more) continue; RunBeforeExit(&env); @@ -3716,10 +3586,9 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data, return exit_code; } -bool AllowWasmCodeGenerationCallback( - Local context, Local) { +bool AllowWasmCodeGenerationCallback(Local context, Local) { Local wasm_code_gen = - context->GetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration); + context->GetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration); return wasm_code_gen->IsUndefined() || wasm_code_gen->IsTrue(); } @@ -3731,8 +3600,7 @@ Isolate* NewIsolate(ArrayBufferAllocator* allocator) { #endif Isolate* isolate = Isolate::New(params); - if (isolate == nullptr) - return nullptr; + if (isolate == nullptr) return nullptr; isolate->AddMessageListener(OnMessage); isolate->SetAbortOnUncaughtExceptionCallback(ShouldAbortOnUncaughtException); @@ -3744,13 +3612,14 @@ Isolate* NewIsolate(ArrayBufferAllocator* allocator) { } inline int Start(uv_loop_t* event_loop, - int argc, const char* const* argv, - int exec_argc, const char* const* exec_argv) { + int argc, + const char* const* argv, + int exec_argc, + const char* const* exec_argv) { std::unique_ptr allocator(CreateArrayBufferAllocator(), &FreeArrayBufferAllocator); Isolate* const isolate = NewIsolate(allocator.get()); - if (isolate == nullptr) - return 12; // Signal internal error. + if (isolate == nullptr) return 12; // Signal internal error. { Mutex::ScopedLock scoped_lock(node_isolate_mutex); @@ -3765,10 +3634,7 @@ inline int Start(uv_loop_t* event_loop, HandleScope handle_scope(isolate); std::unique_ptr isolate_data( CreateIsolateData( - isolate, - event_loop, - v8_platform.Platform(), - allocator.get()), + isolate, event_loop, v8_platform.Platform(), allocator.get()), &FreeIsolateData); if (track_heap_objects) { isolate->GetHeapProfiler()->StartTrackingHeapObjects(true); @@ -3789,7 +3655,7 @@ inline int Start(uv_loop_t* event_loop, } int Start(int argc, char** argv) { - atexit([] () { uv_tty_reset_mode(); }); + atexit([]() { uv_tty_reset_mode(); }); PlatformInit(); performance::performance_node_start = PERFORMANCE_NOW(); diff --git a/src/node.h b/src/node.h index a94612eb0b9de8..34946a7cae7600 100644 --- a/src/node.h +++ b/src/node.h @@ -23,31 +23,31 @@ #define SRC_NODE_H_ #ifdef _WIN32 -# ifndef BUILDING_NODE_EXTENSION -# define NODE_EXTERN __declspec(dllexport) -# else -# define NODE_EXTERN __declspec(dllimport) -# endif +#ifndef BUILDING_NODE_EXTENSION +#define NODE_EXTERN __declspec(dllexport) #else -# define NODE_EXTERN /* nothing */ +#define NODE_EXTERN __declspec(dllimport) +#endif +#else +#define NODE_EXTERN /* nothing */ #endif #ifdef BUILDING_NODE_EXTENSION -# undef BUILDING_V8_SHARED -# undef BUILDING_UV_SHARED -# define USING_V8_SHARED 1 -# define USING_UV_SHARED 1 +#undef BUILDING_V8_SHARED +#undef BUILDING_UV_SHARED +#define USING_V8_SHARED 1 +#define USING_UV_SHARED 1 #endif // This should be defined in make system. // See issue https://github.com/nodejs/node-v0.x-archive/issues/1236 #if defined(__MINGW32__) || defined(_MSC_VER) #ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0600 // Windows Server 2008 +#define _WIN32_WINNT 0x0600 // Windows Server 2008 #endif #ifndef NOMINMAX -# define NOMINMAX +#define NOMINMAX #endif #endif @@ -57,41 +57,39 @@ #endif #ifdef _WIN32 -# define SIGKILL 9 +#define SIGKILL 9 #endif -#include "v8.h" // NOLINT(build/include_order) -#include "v8-platform.h" // NOLINT(build/include_order) #include "node_version.h" // NODE_MODULE_VERSION +#include "v8-platform.h" // NOLINT(build/include_order) +#include "v8.h" // NOLINT(build/include_order) -#define NODE_MAKE_VERSION(major, minor, patch) \ - ((major) * 0x1000 + (minor) * 0x100 + (patch)) +#define NODE_MAKE_VERSION(major, minor, patch) \ + ((major)*0x1000 + (minor)*0x100 + (patch)) #ifdef __clang__ -# define NODE_CLANG_AT_LEAST(major, minor, patch) \ - (NODE_MAKE_VERSION(major, minor, patch) <= \ - NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)) +#define NODE_CLANG_AT_LEAST(major, minor, patch) \ + (NODE_MAKE_VERSION(major, minor, patch) <= \ + NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)) #else -# define NODE_CLANG_AT_LEAST(major, minor, patch) (0) +#define NODE_CLANG_AT_LEAST(major, minor, patch) (0) #endif #ifdef __GNUC__ -# define NODE_GNUC_AT_LEAST(major, minor, patch) \ - (NODE_MAKE_VERSION(major, minor, patch) <= \ - NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)) +#define NODE_GNUC_AT_LEAST(major, minor, patch) \ + (NODE_MAKE_VERSION(major, minor, patch) <= \ + NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)) #else -# define NODE_GNUC_AT_LEAST(major, minor, patch) (0) +#define NODE_GNUC_AT_LEAST(major, minor, patch) (0) #endif #if NODE_CLANG_AT_LEAST(2, 9, 0) || NODE_GNUC_AT_LEAST(4, 5, 0) -# define NODE_DEPRECATED(message, declarator) \ - __attribute__((deprecated(message))) declarator +#define NODE_DEPRECATED(message, declarator) \ + __attribute__((deprecated(message))) declarator #elif defined(_MSC_VER) -# define NODE_DEPRECATED(message, declarator) \ - __declspec(deprecated) declarator +#define NODE_DEPRECATED(message, declarator) __declspec(deprecated) declarator #else -# define NODE_DEPRECATED(message, declarator) \ - declarator +#define NODE_DEPRECATED(message, declarator) declarator #endif // Forward-declare libuv loop @@ -123,28 +121,22 @@ NODE_EXTERN v8::Local UVException(v8::Isolate* isolate, const char* path, const char* dest); -NODE_DEPRECATED("Use ErrnoException(isolate, ...)", - inline v8::Local ErrnoException( - int errorno, - const char* syscall = nullptr, - const char* message = nullptr, - const char* path = nullptr) { - return ErrnoException(v8::Isolate::GetCurrent(), - errorno, - syscall, - message, - path); -}) +NODE_DEPRECATED( + "Use ErrnoException(isolate, ...)", + inline v8::Local ErrnoException(int errorno, + const char* syscall = nullptr, + const char* message = nullptr, + const char* path = nullptr) { + return ErrnoException( + v8::Isolate::GetCurrent(), errorno, syscall, message, path); + }) inline v8::Local UVException(int errorno, const char* syscall = nullptr, const char* message = nullptr, const char* path = nullptr) { - return UVException(v8::Isolate::GetCurrent(), - errorno, - syscall, - message, - path); + return UVException( + v8::Isolate::GetCurrent(), errorno, syscall, message, path); } /* @@ -154,20 +146,20 @@ inline v8::Local UVException(int errorno, * `async_context` arguments. */ -NODE_DEPRECATED("Use MakeCallback(..., async_context)", - NODE_EXTERN v8::Local MakeCallback( - v8::Isolate* isolate, - v8::Local recv, - const char* method, - int argc, - v8::Local* argv)); -NODE_DEPRECATED("Use MakeCallback(..., async_context)", - NODE_EXTERN v8::Local MakeCallback( - v8::Isolate* isolate, - v8::Local recv, - v8::Local symbol, - int argc, - v8::Local* argv)); +NODE_DEPRECATED( + "Use MakeCallback(..., async_context)", + NODE_EXTERN v8::Local MakeCallback(v8::Isolate* isolate, + v8::Local recv, + const char* method, + int argc, + v8::Local* argv)); +NODE_DEPRECATED( + "Use MakeCallback(..., async_context)", + NODE_EXTERN v8::Local MakeCallback(v8::Isolate* isolate, + v8::Local recv, + v8::Local symbol, + int argc, + v8::Local* argv)); NODE_DEPRECATED("Use MakeCallback(..., async_context)", NODE_EXTERN v8::Local MakeCallback( v8::Isolate* isolate, @@ -189,23 +181,22 @@ NODE_DEPRECATED("Use MakeCallback(..., async_context)", #ifdef _WIN32 #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) typedef intptr_t ssize_t; -# define _SSIZE_T_ -# define _SSIZE_T_DEFINED +#define _SSIZE_T_ +#define _SSIZE_T_DEFINED #endif -#else // !_WIN32 -# include // size_t, ssize_t -#endif // _WIN32 - +#else // !_WIN32 +#include // size_t, ssize_t +#endif // _WIN32 namespace node { NODE_EXTERN extern bool no_deprecation; #if HAVE_OPENSSL NODE_EXTERN extern bool ssl_openssl_cert_store; -# if NODE_FIPS_MODE +#if NODE_FIPS_MODE NODE_EXTERN extern bool enable_fips_crypto; NODE_EXTERN extern bool force_fips_crypto; -# endif +#endif #endif NODE_EXTERN int Start(int argc, char* argv[]); @@ -224,7 +215,7 @@ class Environment; class MultiIsolatePlatform : public v8::Platform { public: - virtual ~MultiIsolatePlatform() { } + virtual ~MultiIsolatePlatform() {} // Returns true if work was dispatched or executed. New tasks that are // posted during flushing of the queue are postponed until the next // flushing. @@ -251,18 +242,15 @@ NODE_EXTERN v8::Local NewContext( // It can be `nullptr`, in which case creating new Workers inside of // Environments that use this `IsolateData` will not work. // TODO(helloshuangzi): switch to default parameters. -NODE_EXTERN IsolateData* CreateIsolateData( - v8::Isolate* isolate, - struct uv_loop_s* loop); -NODE_EXTERN IsolateData* CreateIsolateData( - v8::Isolate* isolate, - struct uv_loop_s* loop, - MultiIsolatePlatform* platform); -NODE_EXTERN IsolateData* CreateIsolateData( - v8::Isolate* isolate, - struct uv_loop_s* loop, - MultiIsolatePlatform* platform, - ArrayBufferAllocator* allocator); +NODE_EXTERN IsolateData* CreateIsolateData(v8::Isolate* isolate, + struct uv_loop_s* loop); +NODE_EXTERN IsolateData* CreateIsolateData(v8::Isolate* isolate, + struct uv_loop_s* loop, + MultiIsolatePlatform* platform); +NODE_EXTERN IsolateData* CreateIsolateData(v8::Isolate* isolate, + struct uv_loop_s* loop, + MultiIsolatePlatform* platform, + ArrayBufferAllocator* allocator); NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data); NODE_EXTERN Environment* CreateEnvironment(IsolateData* isolate_data, @@ -281,8 +269,7 @@ NODE_EXTERN void FreeEnvironment(Environment* env); NODE_EXTERN MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform(); NODE_EXTERN MultiIsolatePlatform* CreatePlatform( - int thread_pool_size, - v8::TracingController* tracing_controller); + int thread_pool_size, v8::TracingController* tracing_controller); NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform); NODE_EXTERN void EmitBeforeExit(Environment* env); @@ -294,48 +281,46 @@ NODE_EXTERN void RunAtExit(Environment* env); NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate); /* Converts a unixtime to V8 Date */ -#define NODE_UNIXTIME_V8(t) v8::Date::New(v8::Isolate::GetCurrent(), \ - 1000 * static_cast(t)) -#define NODE_V8_UNIXTIME(v) (static_cast((v)->NumberValue())/1000.0); - -#define NODE_DEFINE_CONSTANT(target, constant) \ - do { \ - v8::Isolate* isolate = target->GetIsolate(); \ - v8::Local context = isolate->GetCurrentContext(); \ - v8::Local constant_name = \ - v8::String::NewFromUtf8(isolate, #constant, \ - v8::NewStringType::kInternalized).ToLocalChecked(); \ - v8::Local constant_value = \ - v8::Number::New(isolate, static_cast(constant)); \ - v8::PropertyAttribute constant_attributes = \ - static_cast(v8::ReadOnly | v8::DontDelete); \ - (target)->DefineOwnProperty(context, \ - constant_name, \ - constant_value, \ - constant_attributes).FromJust(); \ - } \ - while (0) - -#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant) \ - do { \ - v8::Isolate* isolate = target->GetIsolate(); \ - v8::Local context = isolate->GetCurrentContext(); \ - v8::Local constant_name = \ - v8::String::NewFromUtf8(isolate, #constant, \ - v8::NewStringType::kInternalized) \ - .ToLocalChecked(); \ - v8::Local constant_value = \ - v8::Number::New(isolate, static_cast(constant)); \ - v8::PropertyAttribute constant_attributes = \ - static_cast(v8::ReadOnly | \ - v8::DontDelete | \ - v8::DontEnum); \ - (target)->DefineOwnProperty(context, \ - constant_name, \ - constant_value, \ - constant_attributes).FromJust(); \ - } \ - while (0) +#define NODE_UNIXTIME_V8(t) \ + v8::Date::New(v8::Isolate::GetCurrent(), 1000 * static_cast(t)) +#define NODE_V8_UNIXTIME(v) (static_cast((v)->NumberValue()) / 1000.0); + +#define NODE_DEFINE_CONSTANT(target, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local context = isolate->GetCurrentContext(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8( \ + isolate, #constant, v8::NewStringType::kInternalized) \ + .ToLocalChecked(); \ + v8::Local constant_value = \ + v8::Number::New(isolate, static_cast(constant)); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | v8::DontDelete); \ + (target) \ + ->DefineOwnProperty( \ + context, constant_name, constant_value, constant_attributes) \ + .FromJust(); \ + } while (0) + +#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local context = isolate->GetCurrentContext(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8( \ + isolate, #constant, v8::NewStringType::kInternalized) \ + .ToLocalChecked(); \ + v8::Local constant_value = \ + v8::Number::New(isolate, static_cast(constant)); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | v8::DontDelete | \ + v8::DontEnum); \ + (target) \ + ->DefineOwnProperty( \ + context, constant_name, constant_value, constant_attributes) \ + .FromJust(); \ + } while (0) // Used to be a macro, hence the uppercase name. inline void NODE_SET_METHOD(v8::Local recv, @@ -343,10 +328,11 @@ inline void NODE_SET_METHOD(v8::Local recv, v8::FunctionCallback callback) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); - v8::Local t = v8::FunctionTemplate::New(isolate, - callback); - v8::Local fn_name = v8::String::NewFromUtf8(isolate, name, - v8::NewStringType::kInternalized).ToLocalChecked(); + v8::Local t = + v8::FunctionTemplate::New(isolate, callback); + v8::Local fn_name = + v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kInternalized) + .ToLocalChecked(); t->SetClassName(fn_name); recv->Set(fn_name, t); } @@ -357,11 +343,12 @@ inline void NODE_SET_METHOD(v8::Local recv, v8::FunctionCallback callback) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); - v8::Local t = v8::FunctionTemplate::New(isolate, - callback); + v8::Local t = + v8::FunctionTemplate::New(isolate, callback); v8::Local fn = t->GetFunction(); - v8::Local fn_name = v8::String::NewFromUtf8(isolate, name, - v8::NewStringType::kInternalized).ToLocalChecked(); + v8::Local fn_name = + v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kInternalized) + .ToLocalChecked(); fn->SetName(fn_name); recv->Set(fn_name, fn); } @@ -377,15 +364,25 @@ inline void NODE_SET_PROTOTYPE_METHOD(v8::Local recv, v8::Local s = v8::Signature::New(isolate, recv); v8::Local t = v8::FunctionTemplate::New(isolate, callback, v8::Local(), s); - v8::Local fn_name = v8::String::NewFromUtf8(isolate, name, - v8::NewStringType::kInternalized).ToLocalChecked(); + v8::Local fn_name = + v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kInternalized) + .ToLocalChecked(); t->SetClassName(fn_name); recv->PrototypeTemplate()->Set(fn_name, t); } #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD // BINARY is a deprecated alias of LATIN1. -enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER, LATIN1 = BINARY}; +enum encoding { + ASCII, + UTF8, + BASE64, + UCS2, + BINARY, + HEX, + BUFFER, + LATIN1 = BINARY +}; NODE_EXTERN enum encoding ParseEncoding( v8::Isolate* isolate, @@ -393,18 +390,19 @@ NODE_EXTERN enum encoding ParseEncoding( enum encoding default_encoding = LATIN1); NODE_DEPRECATED("Use ParseEncoding(isolate, ...)", inline enum encoding ParseEncoding( - v8::Local encoding_v, - enum encoding default_encoding = LATIN1) { - return ParseEncoding(v8::Isolate::GetCurrent(), encoding_v, default_encoding); -}) + v8::Local encoding_v, + enum encoding default_encoding = LATIN1) { + return ParseEncoding( + v8::Isolate::GetCurrent(), encoding_v, default_encoding); + }) NODE_EXTERN void FatalException(v8::Isolate* isolate, const v8::TryCatch& try_catch); NODE_DEPRECATED("Use FatalException(isolate, ...)", inline void FatalException(const v8::TryCatch& try_catch) { - return FatalException(v8::Isolate::GetCurrent(), try_catch); -}) + return FatalException(v8::Isolate::GetCurrent(), try_catch); + }) // Don't call with encoding=UCS2. NODE_EXTERN v8::Local Encode(v8::Isolate* isolate, @@ -417,31 +415,30 @@ NODE_EXTERN v8::Local Encode(v8::Isolate* isolate, const uint16_t* buf, size_t len); -NODE_DEPRECATED("Use Encode(isolate, ...)", - inline v8::Local Encode( - const void* buf, - size_t len, - enum encoding encoding = LATIN1) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - if (encoding == UCS2) { - assert(reinterpret_cast(buf) % sizeof(uint16_t) == 0 && - "UCS2 buffer must be aligned on two-byte boundary."); - const uint16_t* that = static_cast(buf); - return Encode(isolate, that, len / sizeof(*that)); - } - return Encode(isolate, static_cast(buf), len, encoding); -}) +NODE_DEPRECATED( + "Use Encode(isolate, ...)", + inline v8::Local Encode(const void* buf, + size_t len, + enum encoding encoding = LATIN1) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + if (encoding == UCS2) { + assert(reinterpret_cast(buf) % sizeof(uint16_t) == 0 && + "UCS2 buffer must be aligned on two-byte boundary."); + const uint16_t* that = static_cast(buf); + return Encode(isolate, that, len / sizeof(*that)); + } + return Encode(isolate, static_cast(buf), len, encoding); + }) // Returns -1 if the handle was not valid for decoding NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate, v8::Local, enum encoding encoding = LATIN1); NODE_DEPRECATED("Use DecodeBytes(isolate, ...)", - inline ssize_t DecodeBytes( - v8::Local val, - enum encoding encoding = LATIN1) { - return DecodeBytes(v8::Isolate::GetCurrent(), val, encoding); -}) + inline ssize_t DecodeBytes(v8::Local val, + enum encoding encoding = LATIN1) { + return DecodeBytes(v8::Isolate::GetCurrent(), val, encoding); + }) // returns bytes written. NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate, @@ -454,8 +451,9 @@ NODE_DEPRECATED("Use DecodeWrite(isolate, ...)", size_t buflen, v8::Local val, enum encoding encoding = LATIN1) { - return DecodeWrite(v8::Isolate::GetCurrent(), buf, buflen, val, encoding); -}) + return DecodeWrite( + v8::Isolate::GetCurrent(), buf, buflen, val, encoding); + }) #ifdef _WIN32 NODE_EXTERN v8::Local WinapiErrnoException( @@ -466,30 +464,26 @@ NODE_EXTERN v8::Local WinapiErrnoException( const char* path = nullptr); NODE_DEPRECATED("Use WinapiErrnoException(isolate, ...)", - inline v8::Local WinapiErrnoException(int errorno, - const char* syscall = nullptr, const char* msg = "", - const char* path = nullptr) { - return WinapiErrnoException(v8::Isolate::GetCurrent(), - errorno, - syscall, - msg, - path); -}) + inline v8::Local WinapiErrnoException( + int errorno, + const char* syscall = nullptr, + const char* msg = "", + const char* path = nullptr) { + return WinapiErrnoException( + v8::Isolate::GetCurrent(), errorno, syscall, msg, path); + }) #endif const char* signo_string(int errorno); +typedef void (*addon_register_func)(v8::Local exports, + v8::Local module, + void* priv); -typedef void (*addon_register_func)( - v8::Local exports, - v8::Local module, - void* priv); - -typedef void (*addon_context_register_func)( - v8::Local exports, - v8::Local module, - v8::Local context, - void* priv); +typedef void (*addon_context_register_func)(v8::Local exports, + v8::Local module, + v8::Local context, + void* priv); struct node_module { int nm_version; @@ -506,76 +500,70 @@ struct node_module { extern "C" NODE_EXTERN void node_module_register(void* mod); #ifdef _WIN32 -# define NODE_MODULE_EXPORT __declspec(dllexport) +#define NODE_MODULE_EXPORT __declspec(dllexport) #else -# define NODE_MODULE_EXPORT __attribute__((visibility("default"))) +#define NODE_MODULE_EXPORT __attribute__((visibility("default"))) #endif #ifdef NODE_SHARED_MODE -# define NODE_CTOR_PREFIX +#define NODE_CTOR_PREFIX #else -# define NODE_CTOR_PREFIX static +#define NODE_CTOR_PREFIX static #endif #if defined(_MSC_VER) #pragma section(".CRT$XCU", read) -#define NODE_C_CTOR(fn) \ - NODE_CTOR_PREFIX void __cdecl fn(void); \ - __declspec(dllexport, allocate(".CRT$XCU")) \ - void (__cdecl*fn ## _)(void) = fn; \ +#define NODE_C_CTOR(fn) \ + NODE_CTOR_PREFIX void __cdecl fn(void); \ + __declspec(dllexport, allocate(".CRT$XCU")) void(__cdecl * fn##_)(void) = \ + fn; \ NODE_CTOR_PREFIX void __cdecl fn(void) #else -#define NODE_C_CTOR(fn) \ - NODE_CTOR_PREFIX void fn(void) __attribute__((constructor)); \ +#define NODE_C_CTOR(fn) \ + NODE_CTOR_PREFIX void fn(void) __attribute__((constructor)); \ NODE_CTOR_PREFIX void fn(void) #endif -#define NODE_MODULE_X(modname, regfunc, priv, flags) \ - extern "C" { \ - static node::node_module _module = \ - { \ - NODE_MODULE_VERSION, \ - flags, \ - NULL, /* NOLINT (readability/null_usage) */ \ - __FILE__, \ - (node::addon_register_func) (regfunc), \ - NULL, /* NOLINT (readability/null_usage) */ \ - NODE_STRINGIFY(modname), \ - priv, \ - NULL /* NOLINT (readability/null_usage) */ \ - }; \ - NODE_C_CTOR(_register_ ## modname) { \ - node_module_register(&_module); \ - } \ +#define NODE_MODULE_X(modname, regfunc, priv, flags) \ + extern "C" { \ + static node::node_module _module = { \ + NODE_MODULE_VERSION, \ + flags, \ + NULL, /* NOLINT (readability/null_usage) */ \ + __FILE__, \ + (node::addon_register_func)(regfunc), \ + NULL, /* NOLINT (readability/null_usage) */ \ + NODE_STRINGIFY(modname), \ + priv, \ + NULL /* NOLINT (readability/null_usage) */ \ + }; \ + NODE_C_CTOR(_register_##modname) { node_module_register(&_module); } \ } -#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags) \ - extern "C" { \ - static node::node_module _module = \ - { \ - NODE_MODULE_VERSION, \ - flags, \ - NULL, /* NOLINT (readability/null_usage) */ \ - __FILE__, \ - NULL, /* NOLINT (readability/null_usage) */ \ - (node::addon_context_register_func) (regfunc), \ - NODE_STRINGIFY(modname), \ - priv, \ - NULL /* NOLINT (readability/null_usage) */ \ - }; \ - NODE_C_CTOR(_register_ ## modname) { \ - node_module_register(&_module); \ - } \ +#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags) \ + extern "C" { \ + static node::node_module _module = { \ + NODE_MODULE_VERSION, \ + flags, \ + NULL, /* NOLINT (readability/null_usage) */ \ + __FILE__, \ + NULL, /* NOLINT (readability/null_usage) */ \ + (node::addon_context_register_func)(regfunc), \ + NODE_STRINGIFY(modname), \ + priv, \ + NULL /* NOLINT (readability/null_usage) */ \ + }; \ + NODE_C_CTOR(_register_##modname) { node_module_register(&_module); } \ } // Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)` // If no NODE_MODULE is declared, Node.js looks for the well-known // symbol `node_register_module_v${NODE_MODULE_VERSION}`. -#define NODE_MODULE(modname, regfunc) \ +#define NODE_MODULE(modname, regfunc) \ NODE_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) -#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc) \ - /* NOLINTNEXTLINE (readability/null_usage) */ \ +#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc) \ + /* NOLINTNEXTLINE (readability/null_usage) */ \ NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0) /* @@ -585,24 +573,22 @@ extern "C" NODE_EXTERN void node_module_register(void* mod); #define NODE_MODULE_INITIALIZER_BASE node_register_module_v -#define NODE_MODULE_INITIALIZER_X(base, version) \ - NODE_MODULE_INITIALIZER_X_HELPER(base, version) +#define NODE_MODULE_INITIALIZER_X(base, version) \ + NODE_MODULE_INITIALIZER_X_HELPER(base, version) #define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version -#define NODE_MODULE_INITIALIZER \ - NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE, \ - NODE_MODULE_VERSION) - -#define NODE_MODULE_INIT() \ - extern "C" NODE_MODULE_EXPORT void \ - NODE_MODULE_INITIALIZER(v8::Local exports, \ - v8::Local module, \ - v8::Local context); \ - NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, \ - NODE_MODULE_INITIALIZER) \ - void NODE_MODULE_INITIALIZER(v8::Local exports, \ - v8::Local module, \ +#define NODE_MODULE_INITIALIZER \ + NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE, NODE_MODULE_VERSION) + +#define NODE_MODULE_INIT() \ + extern "C" NODE_MODULE_EXPORT void NODE_MODULE_INITIALIZER( \ + v8::Local exports, \ + v8::Local module, \ + v8::Local context); \ + NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, NODE_MODULE_INITIALIZER) \ + void NODE_MODULE_INITIALIZER(v8::Local exports, \ + v8::Local module, \ v8::Local context) /* Called after the event loop exits but before the VM is disposed. @@ -616,10 +602,10 @@ NODE_EXTERN void AtExit(void (*cb)(void* arg), void* arg = 0); */ NODE_EXTERN void AtExit(Environment* env, void (*cb)(void* arg), void* arg = 0); -typedef void (*promise_hook_func) (v8::PromiseHookType type, - v8::Local promise, - v8::Local parent, - void* arg); +typedef void (*promise_hook_func)(v8::PromiseHookType type, + v8::Local promise, + v8::Local parent, + void* arg); typedef double async_id; struct async_context { @@ -745,84 +731,70 @@ v8::MaybeLocal MakeCallback(v8::Isolate* isolate, * `AsyncResource::MakeCallback()` is used, then all four callbacks will be * called automatically. */ class AsyncResource { - public: - AsyncResource(v8::Isolate* isolate, - v8::Local resource, - const char* name, - async_id trigger_async_id = -1) - : isolate_(isolate), - resource_(isolate, resource) { - async_context_ = EmitAsyncInit(isolate, resource, name, - trigger_async_id); - } - - AsyncResource(v8::Isolate* isolate, - v8::Local resource, - v8::Local name, - async_id trigger_async_id = -1) - : isolate_(isolate), - resource_(isolate, resource) { - async_context_ = EmitAsyncInit(isolate, resource, name, - trigger_async_id); - } - - virtual ~AsyncResource() { - EmitAsyncDestroy(isolate_, async_context_); - resource_.Reset(); - } - - v8::MaybeLocal MakeCallback( - v8::Local callback, - int argc, - v8::Local* argv) { - return node::MakeCallback(isolate_, get_resource(), - callback, argc, argv, - async_context_); - } - - v8::MaybeLocal MakeCallback( - const char* method, - int argc, - v8::Local* argv) { - return node::MakeCallback(isolate_, get_resource(), - method, argc, argv, - async_context_); - } - - v8::MaybeLocal MakeCallback( - v8::Local symbol, - int argc, - v8::Local* argv) { - return node::MakeCallback(isolate_, get_resource(), - symbol, argc, argv, - async_context_); - } - - v8::Local get_resource() { - return resource_.Get(isolate_); - } - - async_id get_async_id() const { - return async_context_.async_id; - } - - async_id get_trigger_async_id() const { - return async_context_.trigger_async_id; - } - - protected: - class CallbackScope : public node::CallbackScope { - public: - explicit CallbackScope(AsyncResource* res) + public: + AsyncResource(v8::Isolate* isolate, + v8::Local resource, + const char* name, + async_id trigger_async_id = -1) + : isolate_(isolate), resource_(isolate, resource) { + async_context_ = EmitAsyncInit(isolate, resource, name, trigger_async_id); + } + + AsyncResource(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1) + : isolate_(isolate), resource_(isolate, resource) { + async_context_ = EmitAsyncInit(isolate, resource, name, trigger_async_id); + } + + virtual ~AsyncResource() { + EmitAsyncDestroy(isolate_, async_context_); + resource_.Reset(); + } + + v8::MaybeLocal MakeCallback(v8::Local callback, + int argc, + v8::Local* argv) { + return node::MakeCallback( + isolate_, get_resource(), callback, argc, argv, async_context_); + } + + v8::MaybeLocal MakeCallback(const char* method, + int argc, + v8::Local* argv) { + return node::MakeCallback( + isolate_, get_resource(), method, argc, argv, async_context_); + } + + v8::MaybeLocal MakeCallback(v8::Local symbol, + int argc, + v8::Local* argv) { + return node::MakeCallback( + isolate_, get_resource(), symbol, argc, argv, async_context_); + } + + v8::Local get_resource() { return resource_.Get(isolate_); } + + async_id get_async_id() const { return async_context_.async_id; } + + async_id get_trigger_async_id() const { + return async_context_.trigger_async_id; + } + + protected: + class CallbackScope : public node::CallbackScope { + public: + explicit CallbackScope(AsyncResource* res) : node::CallbackScope(res->isolate_, res->resource_.Get(res->isolate_), res->async_context_) {} - }; + }; - private: - v8::Isolate* isolate_; - v8::Persistent resource_; - async_context async_context_; + private: + v8::Isolate* isolate_; + v8::Persistent resource_; + async_context async_context_; }; } // namespace node diff --git a/src/node_api.cc b/src/node_api.cc index 40ebc02798b4fe..00961c27007b36 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -1,27 +1,24 @@ +#include // INT_MAX #include #include -#include // INT_MAX #include #include #include #include #define NAPI_EXPERIMENTAL +#include "env.h" #include "node_api.h" #include "node_internals.h" -#include "env.h" -static -napi_status napi_set_last_error(napi_env env, napi_status error_code, - uint32_t engine_error_code = 0, - void* engine_reserved = nullptr); -static -napi_status napi_clear_last_error(napi_env env); +static napi_status napi_set_last_error(napi_env env, + napi_status error_code, + uint32_t engine_error_code = 0, + void* engine_reserved = nullptr); +static napi_status napi_clear_last_error(napi_env env); struct napi_env__ { explicit napi_env__(v8::Isolate* _isolate, uv_loop_t* _loop) - : isolate(_isolate), - last_error(), - loop(_loop) {} + : isolate(_isolate), last_error(), loop(_loop) {} v8::Isolate* isolate; node::Persistent last_exception; napi_extended_error_info last_error; @@ -30,100 +27,101 @@ struct napi_env__ { uv_loop_t* loop = nullptr; }; -#define NAPI_PRIVATE_KEY(context, suffix) \ - (node::Environment::GetCurrent((context))->napi_ ## suffix()) +#define NAPI_PRIVATE_KEY(context, suffix) \ + (node::Environment::GetCurrent((context))->napi_##suffix()) -#define RETURN_STATUS_IF_FALSE(env, condition, status) \ - do { \ - if (!(condition)) { \ - return napi_set_last_error((env), (status)); \ - } \ +#define RETURN_STATUS_IF_FALSE(env, condition, status) \ + do { \ + if (!(condition)) { \ + return napi_set_last_error((env), (status)); \ + } \ } while (0) -#define CHECK_ENV(env) \ - do { \ - if ((env) == nullptr) { \ - return napi_invalid_arg; \ - } \ +#define CHECK_ENV(env) \ + do { \ + if ((env) == nullptr) { \ + return napi_invalid_arg; \ + } \ } while (0) -#define CHECK_ARG(env, arg) \ +#define CHECK_ARG(env, arg) \ RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), napi_invalid_arg) -#define CHECK_MAYBE_EMPTY(env, maybe, status) \ +#define CHECK_MAYBE_EMPTY(env, maybe, status) \ RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status)) -#define CHECK_MAYBE_NOTHING(env, maybe, status) \ +#define CHECK_MAYBE_NOTHING(env, maybe, status) \ RETURN_STATUS_IF_FALSE((env), !((maybe).IsNothing()), (status)) // NAPI_PREAMBLE is not wrapped in do..while: try_catch must have function scope -#define NAPI_PREAMBLE(env) \ - CHECK_ENV((env)); \ - RETURN_STATUS_IF_FALSE((env), (env)->last_exception.IsEmpty(), \ - napi_pending_exception); \ - napi_clear_last_error((env)); \ +#define NAPI_PREAMBLE(env) \ + CHECK_ENV((env)); \ + RETURN_STATUS_IF_FALSE( \ + (env), (env)->last_exception.IsEmpty(), napi_pending_exception); \ + napi_clear_last_error((env)); \ v8impl::TryCatch try_catch((env)) -#define CHECK_TO_TYPE(env, type, context, result, src, status) \ - do { \ - CHECK_ARG((env), (src)); \ - auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ - CHECK_MAYBE_EMPTY((env), maybe, (status)); \ - (result) = maybe.ToLocalChecked(); \ +#define CHECK_TO_TYPE(env, type, context, result, src, status) \ + do { \ + CHECK_ARG((env), (src)); \ + auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ + CHECK_MAYBE_EMPTY((env), maybe, (status)); \ + (result) = maybe.ToLocalChecked(); \ } while (0) -#define CHECK_TO_FUNCTION(env, result, src) \ - do { \ - CHECK_ARG((env), (src)); \ - v8::Local v8value = v8impl::V8LocalValueFromJsValue((src)); \ - RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), napi_invalid_arg); \ - (result) = v8value.As(); \ +#define CHECK_TO_FUNCTION(env, result, src) \ + do { \ + CHECK_ARG((env), (src)); \ + v8::Local v8value = v8impl::V8LocalValueFromJsValue((src)); \ + RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), napi_invalid_arg); \ + (result) = v8value.As(); \ } while (0) -#define CHECK_TO_OBJECT(env, context, result, src) \ +#define CHECK_TO_OBJECT(env, context, result, src) \ CHECK_TO_TYPE((env), Object, (context), (result), (src), napi_object_expected) -#define CHECK_TO_STRING(env, context, result, src) \ +#define CHECK_TO_STRING(env, context, result, src) \ CHECK_TO_TYPE((env), String, (context), (result), (src), napi_string_expected) -#define CHECK_TO_NUMBER(env, context, result, src) \ +#define CHECK_TO_NUMBER(env, context, result, src) \ CHECK_TO_TYPE((env), Number, (context), (result), (src), napi_number_expected) -#define CHECK_TO_BOOL(env, context, result, src) \ - CHECK_TO_TYPE((env), Boolean, (context), (result), (src), \ - napi_boolean_expected) +#define CHECK_TO_BOOL(env, context, result, src) \ + CHECK_TO_TYPE( \ + (env), Boolean, (context), (result), (src), napi_boolean_expected) // n-api defines NAPI_AUTO_LENGHTH as the indicator that a string // is null terminated. For V8 the equivalent is -1. The assert // validates that our cast of NAPI_AUTO_LENGTH results in -1 as // needed by V8. -#define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \ - do { \ - static_assert(static_cast(NAPI_AUTO_LENGTH) == -1, \ - "Casting NAPI_AUTO_LENGTH to int must result in -1"); \ - RETURN_STATUS_IF_FALSE((env), \ - (len == NAPI_AUTO_LENGTH) || len <= INT_MAX, \ - napi_invalid_arg); \ - auto str_maybe = v8::String::NewFromUtf8( \ - (env)->isolate, (str), v8::NewStringType::kInternalized, \ - static_cast(len)); \ - CHECK_MAYBE_EMPTY((env), str_maybe, napi_generic_failure); \ - (result) = str_maybe.ToLocalChecked(); \ +#define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \ + do { \ + static_assert(static_cast(NAPI_AUTO_LENGTH) == -1, \ + "Casting NAPI_AUTO_LENGTH to int must result in -1"); \ + RETURN_STATUS_IF_FALSE( \ + (env), (len == NAPI_AUTO_LENGTH) || len <= INT_MAX, napi_invalid_arg); \ + auto str_maybe = v8::String::NewFromUtf8((env)->isolate, \ + (str), \ + v8::NewStringType::kInternalized, \ + static_cast(len)); \ + CHECK_MAYBE_EMPTY((env), str_maybe, napi_generic_failure); \ + (result) = str_maybe.ToLocalChecked(); \ } while (0) -#define CHECK_NEW_FROM_UTF8(env, result, str) \ +#define CHECK_NEW_FROM_UTF8(env, result, str) \ CHECK_NEW_FROM_UTF8_LEN((env), (result), (str), NAPI_AUTO_LENGTH) -#define GET_RETURN_STATUS(env) \ - (!try_catch.HasCaught() ? napi_ok \ - : napi_set_last_error((env), napi_pending_exception)) +#define GET_RETURN_STATUS(env) \ + (!try_catch.HasCaught() \ + ? napi_ok \ + : napi_set_last_error((env), napi_pending_exception)) -#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ - do { \ - if (!(condition)) { \ - napi_throw_range_error((env), (error), (message)); \ - return napi_set_last_error((env), napi_generic_failure); \ - } \ +#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ + do { \ + if (!(condition)) { \ + napi_throw_range_error((env), (error), (message)); \ + return napi_set_last_error((env), napi_generic_failure); \ + } \ } while (0) #define CREATE_TYPED_ARRAY( \ @@ -131,33 +129,36 @@ struct napi_env__ { do { \ if ((size_of_element) > 1) { \ THROW_RANGE_ERROR_IF_FALSE( \ - (env), (byte_offset) % (size_of_element) == 0, \ + (env), \ + (byte_offset) % (size_of_element) == 0, \ "ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", \ - "start offset of "#type" should be a multiple of "#size_of_element); \ + "start offset of " #type \ + " should be a multiple of " #size_of_element); \ } \ - THROW_RANGE_ERROR_IF_FALSE((env), (length) * (size_of_element) + \ - (byte_offset) <= buffer->ByteLength(), \ + THROW_RANGE_ERROR_IF_FALSE( \ + (env), \ + (length) * (size_of_element) + (byte_offset) <= buffer->ByteLength(), \ "ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", \ "Invalid typed array length"); \ (out) = v8::type::New((buffer), (byte_offset), (length)); \ } while (0) -#define NAPI_CALL_INTO_MODULE(env, call, handle_exception) \ - do { \ - int open_handle_scopes = (env)->open_handle_scopes; \ - int open_callback_scopes = (env)->open_callback_scopes; \ - napi_clear_last_error((env)); \ - call; \ - CHECK_EQ((env)->open_handle_scopes, open_handle_scopes); \ - CHECK_EQ((env)->open_callback_scopes, open_callback_scopes); \ - if (!(env)->last_exception.IsEmpty()) { \ - handle_exception( \ - v8::Local::New((env)->isolate, (env)->last_exception)); \ - (env)->last_exception.Reset(); \ - } \ +#define NAPI_CALL_INTO_MODULE(env, call, handle_exception) \ + do { \ + int open_handle_scopes = (env)->open_handle_scopes; \ + int open_callback_scopes = (env)->open_callback_scopes; \ + napi_clear_last_error((env)); \ + call; \ + CHECK_EQ((env)->open_handle_scopes, open_handle_scopes); \ + CHECK_EQ((env)->open_callback_scopes, open_callback_scopes); \ + if (!(env)->last_exception.IsEmpty()) { \ + handle_exception( \ + v8::Local::New((env)->isolate, (env)->last_exception)); \ + (env)->last_exception.Reset(); \ + } \ } while (0) -#define NAPI_CALL_INTO_MODULE_THROW(env, call) \ +#define NAPI_CALL_INTO_MODULE_THROW(env, call) \ NAPI_CALL_INTO_MODULE((env), call, (env)->isolate->ThrowException) namespace { @@ -171,8 +172,9 @@ static inline v8::PropertyAttribute V8PropertyAttributesFromDescriptor( if (descriptor->getter != nullptr || descriptor->setter != nullptr) { // The napi_writable attribute is ignored for accessor descriptors, but // V8 requires the ReadOnly attribute to match nonexistence of a setter. - attribute_flags |= (descriptor->setter == nullptr ? - v8::PropertyAttribute::ReadOnly : v8::PropertyAttribute::None); + attribute_flags |= + (descriptor->setter == nullptr ? v8::PropertyAttribute::ReadOnly + : v8::PropertyAttribute::None); } else if ((descriptor->attributes & napi_writable) == 0) { attribute_flags |= v8::PropertyAttribute::ReadOnly; } @@ -204,9 +206,7 @@ class EscapableHandleScopeWrapper { public: explicit EscapableHandleScopeWrapper(v8::Isolate* isolate) : scope(isolate), escape_called_(false) {} - bool escape_called() const { - return escape_called_; - } + bool escape_called() const { return escape_called_; } template v8::Local Escape(v8::Local handle) { escape_called_ = true; @@ -218,37 +218,32 @@ class EscapableHandleScopeWrapper { bool escape_called_; }; -static -napi_handle_scope JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) { +static napi_handle_scope JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) { return reinterpret_cast(s); } -static -HandleScopeWrapper* V8HandleScopeFromJsHandleScope(napi_handle_scope s) { +static HandleScopeWrapper* V8HandleScopeFromJsHandleScope(napi_handle_scope s) { return reinterpret_cast(s); } -static -napi_escapable_handle_scope JsEscapableHandleScopeFromV8EscapableHandleScope( +static napi_escapable_handle_scope +JsEscapableHandleScopeFromV8EscapableHandleScope( EscapableHandleScopeWrapper* s) { return reinterpret_cast(s); } -static -EscapableHandleScopeWrapper* +static EscapableHandleScopeWrapper* V8EscapableHandleScopeFromJsEscapableHandleScope( napi_escapable_handle_scope s) { return reinterpret_cast(s); } -static -napi_callback_scope JsCallbackScopeFromV8CallbackScope( +static napi_callback_scope JsCallbackScopeFromV8CallbackScope( node::CallbackScope* s) { return reinterpret_cast(s); } -static -node::CallbackScope* V8CallbackScopeFromJsCallbackScope( +static node::CallbackScope* V8CallbackScopeFromJsCallbackScope( napi_callback_scope s) { return reinterpret_cast(s); } @@ -258,45 +253,44 @@ node::CallbackScope* V8CallbackScopeFromJsCallbackScope( // This asserts v8::Local<> will always be implemented with a single // pointer field so that we can pass it around as a void*. static_assert(sizeof(v8::Local) == sizeof(napi_value), - "Cannot convert between v8::Local and napi_value"); + "Cannot convert between v8::Local and napi_value"); -static -napi_deferred JsDeferredFromNodePersistent(node::Persistent* local) { +static napi_deferred JsDeferredFromNodePersistent( + node::Persistent* local) { return reinterpret_cast(local); } -static -node::Persistent* NodePersistentFromJsDeferred(napi_deferred local) { +static node::Persistent* NodePersistentFromJsDeferred( + napi_deferred local) { return reinterpret_cast*>(local); } -static -napi_value JsValueFromV8LocalValue(v8::Local local) { +static napi_value JsValueFromV8LocalValue(v8::Local local) { return reinterpret_cast(*local); } -static -v8::Local V8LocalValueFromJsValue(napi_value v) { +static v8::Local V8LocalValueFromJsValue(napi_value v) { v8::Local local; memcpy(&local, &v, sizeof(v)); return local; } -static inline void trigger_fatal_exception( - napi_env env, v8::Local local_err) { +static inline void trigger_fatal_exception(napi_env env, + v8::Local local_err) { v8::Local local_msg = - v8::Exception::CreateMessage(env->isolate, local_err); + v8::Exception::CreateMessage(env->isolate, local_err); node::FatalException(env->isolate, local_err, local_msg); } -static inline napi_status V8NameFromPropertyDescriptor(napi_env env, - const napi_property_descriptor* p, - v8::Local* result) { +static inline napi_status V8NameFromPropertyDescriptor( + napi_env env, + const napi_property_descriptor* p, + v8::Local* result) { if (p->utf8name != nullptr) { CHECK_NEW_FROM_UTF8(env, *result, p->utf8name); } else { v8::Local property_value = - v8impl::V8LocalValueFromJsValue(p->name); + v8impl::V8LocalValueFromJsValue(p->name); RETURN_STATUS_IF_FALSE(env, property_value->IsName(), napi_name_expected); *result = property_value.As(); @@ -309,40 +303,34 @@ static inline napi_status V8NameFromPropertyDescriptor(napi_env env, class Finalizer { protected: Finalizer(napi_env env, - napi_finalize finalize_callback, - void* finalize_data, - void* finalize_hint) - : _env(env), - _finalize_callback(finalize_callback), - _finalize_data(finalize_data), - _finalize_hint(finalize_hint) { - } + napi_finalize finalize_callback, + void* finalize_data, + void* finalize_hint) + : _env(env), + _finalize_callback(finalize_callback), + _finalize_data(finalize_data), + _finalize_hint(finalize_hint) {} - ~Finalizer() { - } + ~Finalizer() {} public: static Finalizer* New(napi_env env, napi_finalize finalize_callback = nullptr, void* finalize_data = nullptr, void* finalize_hint = nullptr) { - return new Finalizer( - env, finalize_callback, finalize_data, finalize_hint); + return new Finalizer(env, finalize_callback, finalize_data, finalize_hint); } - static void Delete(Finalizer* finalizer) { - delete finalizer; - } + static void Delete(Finalizer* finalizer) { delete finalizer; } // node::Buffer::FreeCallback static void FinalizeBufferCallback(char* data, void* hint) { Finalizer* finalizer = static_cast(hint); if (finalizer->_finalize_callback != nullptr) { - NAPI_CALL_INTO_MODULE_THROW(finalizer->_env, - finalizer->_finalize_callback( + NAPI_CALL_INTO_MODULE_THROW( finalizer->_env, - data, - finalizer->_finalize_hint)); + finalizer->_finalize_callback( + finalizer->_env, data, finalizer->_finalize_hint)); } Delete(finalizer); @@ -365,7 +353,7 @@ class Reference : private Finalizer { napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) - : Finalizer(env, finalize_callback, finalize_data, finalize_hint), + : Finalizer(env, finalize_callback, finalize_data, finalize_hint), _persistent(env->isolate, value), _refcount(initial_refcount), _delete_self(delete_self) { @@ -376,9 +364,7 @@ class Reference : private Finalizer { } public: - void* Data() { - return _finalize_data; - } + void* Data() { return _finalize_data; } static Reference* New(napi_env env, v8::Local value, @@ -388,17 +374,15 @@ class Reference : private Finalizer { void* finalize_data = nullptr, void* finalize_hint = nullptr) { return new Reference(env, - value, - initial_refcount, - delete_self, - finalize_callback, - finalize_data, - finalize_hint); + value, + initial_refcount, + delete_self, + finalize_callback, + finalize_data, + finalize_hint); } - static void Delete(Reference* reference) { - delete reference; - } + static void Delete(Reference* reference) { delete reference; } uint32_t Ref() { if (++_refcount == 1) { @@ -410,7 +394,7 @@ class Reference : private Finalizer { uint32_t Unref() { if (_refcount == 0) { - return 0; + return 0; } if (--_refcount == 0) { _persistent.SetWeak( @@ -420,9 +404,7 @@ class Reference : private Finalizer { return _refcount; } - uint32_t RefCount() { - return _refcount; - } + uint32_t RefCount() { return _refcount; } v8::Local Get() { if (_persistent.IsEmpty()) { @@ -443,11 +425,11 @@ class Reference : private Finalizer { napi_env env = reference->_env; if (reference->_finalize_callback != nullptr) { - NAPI_CALL_INTO_MODULE_THROW(env, - reference->_finalize_callback( - reference->_env, - reference->_finalize_data, - reference->_finalize_hint)); + NAPI_CALL_INTO_MODULE_THROW( + env, + reference->_finalize_callback(reference->_env, + reference->_finalize_data, + reference->_finalize_hint)); } if (delete_self) { @@ -462,8 +444,7 @@ class Reference : private Finalizer { class TryCatch : public v8::TryCatch { public: - explicit TryCatch(napi_env env) - : v8::TryCatch(env->isolate), _env(env) {} + explicit TryCatch(napi_env env) : v8::TryCatch(env->isolate), _env(env) {} ~TryCatch() { if (HasCaught()) { @@ -491,10 +472,10 @@ struct CallbackBundle { handle.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); } - napi_env env; // Necessary to invoke C++ NAPI callback - void* cb_data; // The user provided callback data - napi_callback function_or_getter; - napi_callback setter; + napi_env env; // Necessary to invoke C++ NAPI callback + void* cb_data; // The user provided callback data + napi_callback function_or_getter; + napi_callback setter; node::Persistent handle; // Die with this JavaScript object private: @@ -536,9 +517,8 @@ template class CallbackWrapperBase : public CallbackWrapper { public: CallbackWrapperBase(const Info& cbinfo, const size_t args_length) - : CallbackWrapper(JsValueFromV8LocalValue(cbinfo.This()), - args_length, - nullptr), + : CallbackWrapper( + JsValueFromV8LocalValue(cbinfo.This()), args_length, nullptr), _cbinfo(cbinfo) { _bundle = reinterpret_cast( v8::Local::Cast(cbinfo.Data())->Value()); @@ -687,10 +667,9 @@ class SetterCallbackWrapper // Creates an object to be made available to the static function callback // wrapper, used to retrieve the native callback function and data pointer. -static -v8::Local CreateFunctionCallbackData(napi_env env, - napi_callback cb, - void* data) { +static v8::Local CreateFunctionCallbackData(napi_env env, + napi_callback cb, + void* data) { CallbackBundle* bundle = new CallbackBundle(); bundle->function_or_getter = cb; bundle->cb_data = data; @@ -704,11 +683,10 @@ v8::Local CreateFunctionCallbackData(napi_env env, // Creates an object to be made available to the static getter/setter // callback wrapper, used to retrieve the native getter/setter callback // function and data pointer. -static -v8::Local CreateAccessorCallbackData(napi_env env, - napi_callback getter, - napi_callback setter, - void* data) { +static v8::Local CreateAccessorCallbackData(napi_env env, + napi_callback getter, + napi_callback setter, + void* data) { CallbackBundle* bundle = new CallbackBundle(); bundle->function_or_getter = getter; bundle->setter = setter; @@ -724,8 +702,7 @@ static void DeleteEnv(napi_env env, void* data, void* hint) { delete env; } -static -napi_env GetEnv(v8::Local context) { +static napi_env GetEnv(v8::Local context) { napi_env result; auto isolate = context->GetIsolate(); @@ -737,7 +714,7 @@ napi_env GetEnv(v8::Local context) { // // Re https://github.com/nodejs/node/pull/14217#discussion_r128775149 auto value = global->GetPrivate(context, NAPI_PRIVATE_KEY(context, env)) - .ToLocalChecked(); + .ToLocalChecked(); if (value->IsExternal()) { result = static_cast(value.As()->Value()); @@ -748,7 +725,7 @@ napi_env GetEnv(v8::Local context) { // We must also stop hard if the result of assigning the env to the global // is either nothing or false. CHECK(global->SetPrivate(context, NAPI_PRIVATE_KEY(context, env), external) - .FromJust()); + .FromJust()); // Create a self-destructing reference to external that will get rid of the // napi_env when external goes out of scope. @@ -758,16 +735,12 @@ napi_env GetEnv(v8::Local context) { return result; } -enum UnwrapAction { - KeepWrap, - RemoveWrap -}; +enum UnwrapAction { KeepWrap, RemoveWrap }; -static -napi_status Unwrap(napi_env env, - napi_value js_object, - void** result, - UnwrapAction action) { +static napi_status Unwrap(napi_env env, + napi_value js_object, + void** result, + UnwrapAction action) { NAPI_PREAMBLE(env); CHECK_ARG(env, js_object); if (action == KeepWrap) { @@ -782,7 +755,7 @@ napi_status Unwrap(napi_env env, v8::Local obj = value.As(); auto val = obj->GetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) - .ToLocalChecked(); + .ToLocalChecked(); RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg); Reference* reference = static_cast(val.As()->Value()); @@ -793,18 +766,17 @@ napi_status Unwrap(napi_env env, if (action == RemoveWrap) { CHECK(obj->DeletePrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) - .FromJust()); + .FromJust()); Reference::Delete(reference); } return GET_RETURN_STATUS(env); } -static -napi_status ConcludeDeferred(napi_env env, - napi_deferred deferred, - napi_value result, - bool is_resolved) { +static napi_status ConcludeDeferred(napi_env env, + napi_deferred deferred, + napi_value result, + bool is_resolved) { NAPI_PREAMBLE(env); CHECK_ARG(env, result); @@ -816,9 +788,11 @@ napi_status ConcludeDeferred(napi_env env, auto v8_resolver = v8::Local::Cast(v8_deferred); - v8::Maybe success = is_resolved ? - v8_resolver->Resolve(context, v8impl::V8LocalValueFromJsValue(result)) : - v8_resolver->Reject(context, v8impl::V8LocalValueFromJsValue(result)); + v8::Maybe success = + is_resolved ? v8_resolver->Resolve( + context, v8impl::V8LocalValueFromJsValue(result)) + : v8_resolver->Reject( + context, v8impl::V8LocalValueFromJsValue(result)); delete deferred_ref; @@ -836,7 +810,10 @@ void napi_module_register_cb(v8::Local exports, v8::Local module, v8::Local context, void* priv) { - napi_module_register_by_symbol(exports, module, context, + napi_module_register_by_symbol( + exports, + module, + context, static_cast(priv)->nm_register_func); } @@ -857,8 +834,8 @@ void napi_module_register_by_symbol(v8::Local exports, napi_env env = v8impl::GetEnv(context); napi_value _exports; - NAPI_CALL_INTO_MODULE_THROW(env, - _exports = init(env, v8impl::JsValueFromV8LocalValue(exports))); + NAPI_CALL_INTO_MODULE_THROW( + env, _exports = init(env, v8impl::JsValueFromV8LocalValue(exports))); // If register function returned a non-null exports object different from // the exports object we passed it, set that as the "exports" property of @@ -872,16 +849,16 @@ void napi_module_register_by_symbol(v8::Local exports, // Registers a NAPI module. void napi_module_register(napi_module* mod) { - node::node_module* nm = new node::node_module { - -1, - mod->nm_flags, - nullptr, - mod->nm_filename, - nullptr, - napi_module_register_cb, - mod->nm_modname, - mod, // priv - nullptr, + node::node_module* nm = new node::node_module{ + -1, + mod->nm_flags, + nullptr, + mod->nm_filename, + nullptr, + napi_module_register_cb, + mod->nm_modname, + mod, // priv + nullptr, }; node::node_module_register(nm); } @@ -909,25 +886,25 @@ napi_status napi_remove_env_cleanup_hook(napi_env env, } // Warning: Keep in-sync with napi_status enum -static -const char* error_messages[] = {nullptr, - "Invalid argument", - "An object was expected", - "A string was expected", - "A string or symbol was expected", - "A function was expected", - "A number was expected", - "A boolean was expected", - "An array was expected", - "Unknown failure", - "An exception is pending", - "The async work item was cancelled", - "napi_escape_handle already called on scope", - "Invalid handle scope usage", - "Invalid callback scope usage", - "Thread-safe function queue is full", - "Thread-safe function handle is closing", - "A bigint was expected", +static const char* error_messages[] = { + nullptr, + "Invalid argument", + "An object was expected", + "A string was expected", + "A string or symbol was expected", + "A function was expected", + "A number was expected", + "A boolean was expected", + "An array was expected", + "Unknown failure", + "An exception is pending", + "The async work item was cancelled", + "napi_escape_handle already called on scope", + "Invalid handle scope usage", + "Invalid callback scope usage", + "Thread-safe function queue is full", + "Thread-safe function handle is closing", + "A bigint was expected", }; static inline napi_status napi_clear_last_error(napi_env env) { @@ -939,10 +916,10 @@ static inline napi_status napi_clear_last_error(napi_env env) { return napi_ok; } -static inline -napi_status napi_set_last_error(napi_env env, napi_status error_code, - uint32_t engine_error_code, - void* engine_reserved) { +static inline napi_status napi_set_last_error(napi_env env, + napi_status error_code, + uint32_t engine_error_code, + void* engine_reserved) { env->last_error.error_code = error_code; env->last_error.engine_error_code = engine_error_code; env->last_error.engine_reserved = engine_reserved; @@ -958,15 +935,13 @@ napi_status napi_get_last_error_info(napi_env env, // in the napi_status enum each time a new error message is added. // We don't have a napi_status_last as this would result in an ABI // change each time a message was added. - static_assert( - node::arraysize(error_messages) == napi_bigint_expected + 1, - "Count of error messages must match count of error values"); + static_assert(node::arraysize(error_messages) == napi_bigint_expected + 1, + "Count of error messages must match count of error values"); CHECK_LE(env->last_error.error_code, napi_callback_scope_mismatch); // Wait until someone requests the last error information to fetch the error // message string - env->last_error.error_message = - error_messages[env->last_error.error_code]; + env->last_error.error_message = error_messages[env->last_error.error_code]; *result = &(env->last_error); return napi_ok; @@ -990,19 +965,15 @@ NAPI_NO_RETURN void napi_fatal_error(const char* location, std::string message_string; if (location_len != NAPI_AUTO_LENGTH) { - location_string.assign( - const_cast(location), location_len); + location_string.assign(const_cast(location), location_len); } else { - location_string.assign( - const_cast(location), strlen(location)); + location_string.assign(const_cast(location), strlen(location)); } if (message_len != NAPI_AUTO_LENGTH) { - message_string.assign( - const_cast(message), message_len); + message_string.assign(const_cast(message), message_len); } else { - message_string.assign( - const_cast(message), strlen(message)); + message_string.assign(const_cast(message), strlen(message)); } node::FatalError(location_string.c_str(), message_string.c_str()); @@ -1027,10 +998,8 @@ napi_status napi_create_function(napi_env env, RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); v8::Local context = isolate->GetCurrentContext(); - v8::MaybeLocal maybe_function = - v8::Function::New(context, - v8impl::FunctionCallbackWrapper::Invoke, - cbdata); + v8::MaybeLocal maybe_function = v8::Function::New( + context, v8impl::FunctionCallbackWrapper::Invoke, cbdata); CHECK_MAYBE_EMPTY(env, maybe_function, napi_generic_failure); return_value = scope.Escape(maybe_function.ToLocalChecked()); @@ -1098,15 +1067,15 @@ napi_status napi_define_class(napi_env env, // difference is it applies to a template instead of an object. if (p->getter != nullptr || p->setter != nullptr) { v8::Local cbdata = v8impl::CreateAccessorCallbackData( - env, p->getter, p->setter, p->data); + env, p->getter, p->setter, p->data); tpl->PrototypeTemplate()->SetAccessor( - property_name, - p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, - p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, - cbdata, - v8::AccessControl::DEFAULT, - attributes); + property_name, + p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, + p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, + cbdata, + v8::AccessControl::DEFAULT, + attributes); } else if (p->method != nullptr) { v8::Local cbdata = v8impl::CreateFunctionCallbackData(env, p->method, p->data); @@ -1114,10 +1083,10 @@ napi_status napi_define_class(napi_env env, RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); v8::Local t = - v8::FunctionTemplate::New(isolate, - v8impl::FunctionCallbackWrapper::Invoke, - cbdata, - v8::Signature::New(isolate, tpl)); + v8::FunctionTemplate::New(isolate, + v8impl::FunctionCallbackWrapper::Invoke, + cbdata, + v8::Signature::New(isolate, tpl)); tpl->PrototypeTemplate()->Set(property_name, t, attributes); } else { @@ -1139,11 +1108,8 @@ napi_status napi_define_class(napi_env env, } } - napi_status status = - napi_define_properties(env, - *result, - static_descriptors.size(), - static_descriptors.data()); + napi_status status = napi_define_properties( + env, *result, static_descriptors.size(), static_descriptors.data()); if (status != napi_ok) return status; } @@ -1165,8 +1131,8 @@ napi_status napi_get_property_names(napi_env env, CHECK_MAYBE_EMPTY(env, maybe_propertynames, napi_generic_failure); - *result = v8impl::JsValueFromV8LocalValue( - maybe_propertynames.ToLocalChecked()); + *result = + v8impl::JsValueFromV8LocalValue(maybe_propertynames.ToLocalChecked()); return GET_RETURN_STATUS(env); } @@ -1256,8 +1222,7 @@ napi_status napi_delete_property(napi_env env, v8::Maybe delete_maybe = obj->Delete(context, k); CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure); - if (result != nullptr) - *result = delete_maybe.FromMaybe(false); + if (result != nullptr) *result = delete_maybe.FromMaybe(false); return GET_RETURN_STATUS(env); } @@ -1434,8 +1399,7 @@ napi_status napi_delete_element(napi_env env, v8::Maybe delete_maybe = obj->Delete(context, index); CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure); - if (result != nullptr) - *result = delete_maybe.FromMaybe(false); + if (result != nullptr) *result = delete_maybe.FromMaybe(false); return GET_RETURN_STATUS(env); } @@ -1471,19 +1435,16 @@ napi_status napi_define_properties(napi_env env, if (p->getter != nullptr || p->setter != nullptr) { v8::Local cbdata = v8impl::CreateAccessorCallbackData( - env, - p->getter, - p->setter, - p->data); + env, p->getter, p->setter, p->data); auto set_maybe = obj->SetAccessor( - context, - property_name, - p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, - p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, - cbdata, - v8::AccessControl::DEFAULT, - attributes); + context, + property_name, + p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, + p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, + cbdata, + v8::AccessControl::DEFAULT, + attributes); if (!set_maybe.FromMaybe(false)) { return napi_set_last_error(env, napi_invalid_arg); @@ -1494,15 +1455,13 @@ napi_status napi_define_properties(napi_env env, CHECK_MAYBE_EMPTY(env, cbdata, napi_generic_failure); - v8::MaybeLocal maybe_fn = - v8::Function::New(context, - v8impl::FunctionCallbackWrapper::Invoke, - cbdata); + v8::MaybeLocal maybe_fn = v8::Function::New( + context, v8impl::FunctionCallbackWrapper::Invoke, cbdata); CHECK_MAYBE_EMPTY(env, maybe_fn, napi_generic_failure); auto define_maybe = obj->DefineOwnProperty( - context, property_name, maybe_fn.ToLocalChecked(), attributes); + context, property_name, maybe_fn.ToLocalChecked(), attributes); if (!define_maybe.FromMaybe(false)) { return napi_set_last_error(env, napi_generic_failure); @@ -1586,8 +1545,7 @@ napi_status napi_create_object(napi_env env, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Object::New(env->isolate)); + *result = v8impl::JsValueFromV8LocalValue(v8::Object::New(env->isolate)); return napi_clear_last_error(env); } @@ -1596,8 +1554,7 @@ napi_status napi_create_array(napi_env env, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Array::New(env->isolate)); + *result = v8impl::JsValueFromV8LocalValue(v8::Array::New(env->isolate)); return napi_clear_last_error(env); } @@ -1608,8 +1565,8 @@ napi_status napi_create_array_with_length(napi_env env, CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Array::New(env->isolate, length)); + *result = + v8impl::JsValueFromV8LocalValue(v8::Array::New(env->isolate, length)); return napi_clear_last_error(env); } @@ -1666,26 +1623,22 @@ napi_status napi_create_string_utf16(napi_env env, return napi_clear_last_error(env); } -napi_status napi_create_double(napi_env env, - double value, - napi_value* result) { +napi_status napi_create_double(napi_env env, double value, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Number::New(env->isolate, value)); + *result = + v8impl::JsValueFromV8LocalValue(v8::Number::New(env->isolate, value)); return napi_clear_last_error(env); } -napi_status napi_create_int32(napi_env env, - int32_t value, - napi_value* result) { +napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Integer::New(env->isolate, value)); + *result = + v8impl::JsValueFromV8LocalValue(v8::Integer::New(env->isolate, value)); return napi_clear_last_error(env); } @@ -1702,9 +1655,7 @@ napi_status napi_create_uint32(napi_env env, return napi_clear_last_error(env); } -napi_status napi_create_int64(napi_env env, - int64_t value, - napi_value* result) { +napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); @@ -1720,8 +1671,8 @@ napi_status napi_create_bigint_int64(napi_env env, CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::BigInt::New(env->isolate, value)); + *result = + v8impl::JsValueFromV8LocalValue(v8::BigInt::New(env->isolate, value)); return napi_clear_last_error(env); } @@ -1754,8 +1705,8 @@ napi_status napi_create_bigint_words(napi_env env, return napi_set_last_error(env, napi_pending_exception); } - v8::MaybeLocal b = v8::BigInt::NewFromWords( - context, sign_bit, word_count, words); + v8::MaybeLocal b = + v8::BigInt::NewFromWords(context, sign_bit, word_count, words); if (try_catch.HasCaught()) { return napi_set_last_error(env, napi_pending_exception); @@ -1796,7 +1747,7 @@ napi_status napi_create_symbol(napi_env env, RETURN_STATUS_IF_FALSE(env, desc->IsString(), napi_string_expected); *result = v8impl::JsValueFromV8LocalValue( - v8::Symbol::New(isolate, desc.As())); + v8::Symbol::New(isolate, desc.As())); } return napi_clear_last_error(env); @@ -1823,9 +1774,8 @@ static napi_status set_error_code(napi_env env, CHECK_NEW_FROM_UTF8(env, code_key, "code"); v8::Maybe set_maybe = err_object->Set(context, code_key, code_value); - RETURN_STATUS_IF_FALSE(env, - set_maybe.FromMaybe(false), - napi_generic_failure); + RETURN_STATUS_IF_FALSE( + env, set_maybe.FromMaybe(false), napi_generic_failure); // now update the name to be "name [code]" where name is the // original name and code is the code associated with the Error @@ -1841,16 +1791,15 @@ static napi_status set_error_code(napi_env env, name_string = v8::String::Concat(name_string, name.As()); } } - name_string = v8::String::Concat(name_string, - FIXED_ONE_BYTE_STRING(isolate, " [")); + name_string = + v8::String::Concat(name_string, FIXED_ONE_BYTE_STRING(isolate, " [")); name_string = v8::String::Concat(name_string, code_value.As()); - name_string = v8::String::Concat(name_string, - FIXED_ONE_BYTE_STRING(isolate, "]")); + name_string = + v8::String::Concat(name_string, FIXED_ONE_BYTE_STRING(isolate, "]")); set_maybe = err_object->Set(context, name_key, name_string); - RETURN_STATUS_IF_FALSE(env, - set_maybe.FromMaybe(false), - napi_generic_failure); + RETURN_STATUS_IF_FALSE( + env, set_maybe.FromMaybe(false), napi_generic_failure); } return napi_ok; } @@ -1965,8 +1914,7 @@ napi_status napi_get_undefined(napi_env env, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Undefined(env->isolate)); + *result = v8impl::JsValueFromV8LocalValue(v8::Undefined(env->isolate)); return napi_clear_last_error(env); } @@ -1975,8 +1923,7 @@ napi_status napi_get_null(napi_env env, napi_value* result) { CHECK_ENV(env); CHECK_ARG(env, result); - *result = v8impl::JsValueFromV8LocalValue( - v8::Null(env->isolate)); + *result = v8impl::JsValueFromV8LocalValue(v8::Null(env->isolate)); return napi_clear_last_error(env); } @@ -2047,8 +1994,11 @@ napi_status napi_call_function(napi_env env, v8::Local v8func; CHECK_TO_FUNCTION(env, v8func, func); - auto maybe = v8func->Call(context, v8recv, argc, - reinterpret_cast*>(const_cast(argv))); + auto maybe = v8func->Call( + context, + v8recv, + argc, + reinterpret_cast*>(const_cast(argv))); if (try_catch.HasCaught()) { return napi_set_last_error(env, napi_pending_exception); @@ -2087,9 +2037,7 @@ napi_status napi_throw(napi_env env, napi_value error) { return napi_clear_last_error(env); } -napi_status napi_throw_error(napi_env env, - const char* code, - const char* msg) { +napi_status napi_throw_error(napi_env env, const char* code, const char* msg) { NAPI_PREAMBLE(env); v8::Isolate* isolate = env->isolate; @@ -2345,11 +2293,8 @@ napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) { // If buf is NULL, this method returns the length of the string (in bytes) // via the result parameter. // The result argument is optional unless buf is NULL. -napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) { +napi_status napi_get_value_string_latin1( + napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) { CHECK_ENV(env); CHECK_ARG(env, value); @@ -2360,9 +2305,11 @@ napi_status napi_get_value_string_latin1(napi_env env, CHECK_ARG(env, result); *result = val.As()->Length(); } else { - int copied = val.As()->WriteOneByte( - reinterpret_cast(buf), 0, bufsize - 1, - v8::String::NO_NULL_TERMINATION); + int copied = + val.As()->WriteOneByte(reinterpret_cast(buf), + 0, + bufsize - 1, + v8::String::NO_NULL_TERMINATION); buf[copied] = '\0'; if (result != nullptr) { @@ -2381,11 +2328,8 @@ napi_status napi_get_value_string_latin1(napi_env env, // If buf is NULL, this method returns the length of the string (in bytes) // via the result parameter. // The result argument is optional unless buf is NULL. -napi_status napi_get_value_string_utf8(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) { +napi_status napi_get_value_string_utf8( + napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) { CHECK_ENV(env); CHECK_ARG(env, value); @@ -2397,8 +2341,10 @@ napi_status napi_get_value_string_utf8(napi_env env, *result = val.As()->Utf8Length(); } else { int copied = val.As()->WriteUtf8( - buf, bufsize - 1, nullptr, v8::String::REPLACE_INVALID_UTF8 | - v8::String::NO_NULL_TERMINATION); + buf, + bufsize - 1, + nullptr, + v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION); buf[copied] = '\0'; if (result != nullptr) { @@ -2433,9 +2379,10 @@ napi_status napi_get_value_string_utf16(napi_env env, // V8 assumes UTF-16 length is the same as the number of characters. *result = val.As()->Length(); } else { - int copied = val.As()->Write( - reinterpret_cast(buf), 0, bufsize - 1, - v8::String::NO_NULL_TERMINATION); + int copied = val.As()->Write(reinterpret_cast(buf), + 0, + bufsize - 1, + v8::String::NO_NULL_TERMINATION); buf[copied] = '\0'; if (result != nullptr) { @@ -2530,7 +2477,8 @@ napi_status napi_wrap(napi_env env, v8::Local obj = value.As(); // If we've already wrapped this object, we error out. - RETURN_STATUS_IF_FALSE(env, + RETURN_STATUS_IF_FALSE( + env, !obj->HasPrivate(context, NAPI_PRIVATE_KEY(context, wrapper)).FromJust(), napi_invalid_arg); @@ -2546,12 +2494,20 @@ napi_status napi_wrap(napi_env env, *result = reinterpret_cast(reference); } else { // Create a self-deleting reference. - reference = v8impl::Reference::New(env, obj, 0, true, finalize_cb, - native_object, finalize_cb == nullptr ? nullptr : finalize_hint); + reference = v8impl::Reference::New( + env, + obj, + 0, + true, + finalize_cb, + native_object, + finalize_cb == nullptr ? nullptr : finalize_hint); } - CHECK(obj->SetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper), - v8::External::New(isolate, reference)).FromJust()); + CHECK(obj->SetPrivate(context, + NAPI_PRIVATE_KEY(context, wrapper), + v8::External::New(isolate, reference)) + .FromJust()); return GET_RETURN_STATUS(env); } @@ -2578,13 +2534,8 @@ napi_status napi_create_external(napi_env env, // The Reference object will delete itself after invoking the finalizer // callback. - v8impl::Reference::New(env, - external_value, - 0, - true, - finalize_cb, - data, - finalize_hint); + v8impl::Reference::New( + env, external_value, 0, true, finalize_cb, data, finalize_hint); *result = v8impl::JsValueFromV8LocalValue(external_value); @@ -2735,8 +2686,7 @@ napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) { } napi_status napi_open_escapable_handle_scope( - napi_env env, - napi_escapable_handle_scope* result) { + napi_env env, napi_escapable_handle_scope* result) { // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw // JS exceptions. CHECK_ENV(env); @@ -2749,8 +2699,7 @@ napi_status napi_open_escapable_handle_scope( } napi_status napi_close_escapable_handle_scope( - napi_env env, - napi_escapable_handle_scope scope) { + napi_env env, napi_escapable_handle_scope scope) { // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw // JS exceptions. CHECK_ENV(env); @@ -2803,9 +2752,7 @@ napi_status napi_open_callback_scope(napi_env env, CHECK_TO_OBJECT(env, context, resource, resource_object); *result = v8impl::JsCallbackScopeFromV8CallbackScope( - new node::CallbackScope(env->isolate, - resource, - *node_async_context)); + new node::CallbackScope(env->isolate, resource, *node_async_context)); env->open_callback_scopes++; return napi_clear_last_error(env); @@ -2843,8 +2790,10 @@ napi_status napi_new_instance(napi_env env, v8::Local ctor; CHECK_TO_FUNCTION(env, ctor, constructor); - auto maybe = ctor->NewInstance(context, argc, - reinterpret_cast*>(const_cast(argv))); + auto maybe = ctor->NewInstance( + context, + argc, + reinterpret_cast*>(const_cast(argv))); CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); @@ -2869,9 +2818,8 @@ napi_status napi_instanceof(napi_env env, CHECK_TO_OBJECT(env, context, ctor, constructor); if (!ctor->IsFunction()) { - napi_throw_type_error(env, - "ERR_NAPI_CONS_FUNCTION", - "Constructor must be a function"); + napi_throw_type_error( + env, "ERR_NAPI_CONS_FUNCTION", "Constructor must be a function"); return napi_set_last_error(env, napi_function_expected); } @@ -2916,8 +2864,7 @@ napi_status napi_async_init(napi_env env, return napi_clear_last_error(env); } -napi_status napi_async_destroy(napi_env env, - napi_async_context async_context) { +napi_status napi_async_destroy(napi_env env, napi_async_context async_context) { CHECK_ENV(env); CHECK_ARG(env, async_context); @@ -2954,14 +2901,17 @@ napi_status napi_make_callback(napi_env env, CHECK_TO_FUNCTION(env, v8func, func); node::async_context* node_async_context = - reinterpret_cast(async_context); + reinterpret_cast(async_context); if (node_async_context == nullptr) { - static node::async_context empty_context = { 0, 0 }; + static node::async_context empty_context = {0, 0}; node_async_context = &empty_context; } v8::MaybeLocal callback_result = node::MakeCallback( - isolate, v8recv, v8func, argc, + isolate, + v8recv, + v8func, + argc, reinterpret_cast*>(const_cast(argv)), *node_async_context); @@ -2970,8 +2920,8 @@ napi_status napi_make_callback(napi_env env, } else { CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure); if (result != nullptr) { - *result = v8impl::JsValueFromV8LocalValue( - callback_result.ToLocalChecked()); + *result = + v8impl::JsValueFromV8LocalValue(callback_result.ToLocalChecked()); } } @@ -3000,7 +2950,7 @@ napi_status napi_get_and_clear_last_exception(napi_env env, return napi_get_undefined(env, result); } else { *result = v8impl::JsValueFromV8LocalValue( - v8::Local::New(env->isolate, env->last_exception)); + v8::Local::New(env->isolate, env->last_exception)); env->last_exception.Reset(); } @@ -3041,8 +2991,8 @@ napi_status napi_create_external_buffer(napi_env env, v8::Isolate* isolate = env->isolate; // The finalizer object will delete itself after invoking the callback. - v8impl::Finalizer* finalizer = v8impl::Finalizer::New( - env, finalize_cb, nullptr, finalize_hint); + v8impl::Finalizer* finalizer = + v8impl::Finalizer::New(env, finalize_cb, nullptr, finalize_hint); auto maybe = node::Buffer::New(isolate, static_cast(data), @@ -3068,8 +3018,8 @@ napi_status napi_create_buffer_copy(napi_env env, NAPI_PREAMBLE(env); CHECK_ARG(env, result); - auto maybe = node::Buffer::Copy(env->isolate, - static_cast(data), length); + auto maybe = + node::Buffer::Copy(env->isolate, static_cast(data), length); CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); @@ -3159,13 +3109,8 @@ napi_status napi_create_external_arraybuffer(napi_env env, if (finalize_cb != nullptr) { // Create a self-deleting weak reference that invokes the finalizer // callback. - v8impl::Reference::New(env, - buffer, - 0, - true, - finalize_cb, - external_data, - finalize_hint); + v8impl::Reference::New( + env, buffer, 0, true, finalize_cb, external_data, finalize_hint); } *result = v8impl::JsValueFromV8LocalValue(buffer); @@ -3352,15 +3297,14 @@ napi_status napi_create_dataview(napi_env env, v8::Local buffer = value.As(); if (byte_length + byte_offset > buffer->ByteLength()) { - napi_throw_range_error( - env, - "ERR_NAPI_INVALID_DATAVIEW_ARGS", - "byte_offset + byte_length should be less than or " - "equal to the size in bytes of the array passed in"); + napi_throw_range_error(env, + "ERR_NAPI_INVALID_DATAVIEW_ARGS", + "byte_offset + byte_length should be less than or " + "equal to the size in bytes of the array passed in"); return napi_set_last_error(env, napi_pending_exception); } - v8::Local DataView = v8::DataView::New(buffer, byte_offset, - byte_length); + v8::Local DataView = + v8::DataView::New(buffer, byte_offset, byte_length); *result = v8impl::JsValueFromV8LocalValue(DataView); return GET_RETURN_STATUS(env); @@ -3424,11 +3368,7 @@ napi_status napi_get_node_version(napi_env env, CHECK_ENV(env); CHECK_ARG(env, result); static const napi_node_version version = { - NODE_MAJOR_VERSION, - NODE_MINOR_VERSION, - NODE_PATCH_VERSION, - NODE_RELEASE - }; + NODE_MAJOR_VERSION, NODE_MINOR_VERSION, NODE_PATCH_VERSION, NODE_RELEASE}; *result = &version; return napi_clear_last_error(env); } @@ -3439,8 +3379,8 @@ napi_status napi_adjust_external_memory(napi_env env, CHECK_ENV(env); CHECK_ARG(env, adjusted_value); - *adjusted_value = env->isolate->AdjustAmountOfExternalAllocatedMemory( - change_in_bytes); + *adjusted_value = + env->isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes); return napi_clear_last_error(env); } @@ -3450,12 +3390,12 @@ namespace uvimpl { static napi_status ConvertUVErrorCode(int code) { switch (code) { - case 0: - return napi_ok; - case UV_EINVAL: - return napi_invalid_arg; - case UV_ECANCELED: - return napi_cancelled; + case 0: + return napi_ok; + case UV_EINVAL: + return napi_invalid_arg; + case UV_ECANCELED: + return napi_cancelled; } return napi_generic_failure; @@ -3470,17 +3410,17 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork { napi_async_execute_callback execute, napi_async_complete_callback complete = nullptr, void* data = nullptr) - : AsyncResource(env->isolate, - async_resource, - *v8::String::Utf8Value(env->isolate, async_resource_name)), - ThreadPoolWork(node::Environment::GetCurrent(env->isolate)), - _env(env), - _data(data), - _execute(execute), - _complete(complete) { - } - - virtual ~Work() { } + : AsyncResource( + env->isolate, + async_resource, + *v8::String::Utf8Value(env->isolate, async_resource_name)), + ThreadPoolWork(node::Environment::GetCurrent(env->isolate)), + _env(env), + _data(data), + _execute(execute), + _complete(complete) {} + + virtual ~Work() {} public: static Work* New(napi_env env, @@ -3489,21 +3429,16 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork { napi_async_execute_callback execute, napi_async_complete_callback complete, void* data) { - return new Work(env, async_resource, async_resource_name, - execute, complete, data); + return new Work( + env, async_resource, async_resource_name, execute, complete, data); } - static void Delete(Work* work) { - delete work; - } + static void Delete(Work* work) { delete work; } - void DoThreadPoolWork() override { - _execute(_env, _data); - } + void DoThreadPoolWork() override { _execute(_env, _data); } void AfterThreadPoolWork(int status) override { - if (_complete == nullptr) - return; + if (_complete == nullptr) return; // Establish a handle scope here so that every callback doesn't have to. // Also it is needed for the exception-handling below. @@ -3518,13 +3453,14 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork { napi_env env = _env; NAPI_CALL_INTO_MODULE(env, - _complete(_env, ConvertUVErrorCode(status), _data), - [env] (v8::Local local_err) { - // If there was an unhandled exception in the complete callback, - // report it as a fatal exception. (There is no JavaScript on the - // callstack that can possibly handle it.) - v8impl::trigger_fatal_exception(env, local_err); - }); + _complete(_env, ConvertUVErrorCode(status), _data), + [env](v8::Local local_err) { + // If there was an unhandled exception in the + // complete callback, report it as a fatal + // exception. (There is no JavaScript on the + // callstack that can possibly handle it.) + v8impl::trigger_fatal_exception(env, local_err); + }); // Note: Don't access `work` after this point because it was // likely deleted by the complete callback. @@ -3540,13 +3476,13 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork { } // end of namespace uvimpl } // end of anonymous namespace -#define CALL_UV(env, condition) \ - do { \ - int result = (condition); \ - napi_status status = uvimpl::ConvertUVErrorCode(result); \ - if (status != napi_ok) { \ - return napi_set_last_error(env, status, result); \ - } \ +#define CALL_UV(env, condition) \ + do { \ + int result = (condition); \ + napi_status status = uvimpl::ConvertUVErrorCode(result); \ + if (status != napi_ok) { \ + return napi_set_last_error(env, status, result); \ + } \ } while (0) napi_status napi_create_async_work(napi_env env, @@ -3573,8 +3509,7 @@ napi_status napi_create_async_work(napi_env env, CHECK_TO_STRING(env, context, resource_name, async_resource_name); uvimpl::Work* work = - uvimpl::Work::New(env, resource, resource_name, - execute, complete, data); + uvimpl::Work::New(env, resource, resource_name, execute, complete, data); *result = reinterpret_cast(work); @@ -3604,8 +3539,7 @@ napi_status napi_queue_async_work(napi_env env, napi_async_work work) { napi_status status; uv_loop_t* event_loop = nullptr; status = napi_get_uv_event_loop(env, &event_loop); - if (status != napi_ok) - return napi_set_last_error(env, status); + if (status != napi_ok) return napi_set_last_error(env, status); uvimpl::Work* w = reinterpret_cast(work); @@ -3683,19 +3617,18 @@ napi_status napi_run_script(napi_env env, v8::Local context = env->isolate->GetCurrentContext(); - auto maybe_script = v8::Script::Compile(context, - v8::Local::Cast(v8_script)); + auto maybe_script = + v8::Script::Compile(context, v8::Local::Cast(v8_script)); CHECK_MAYBE_EMPTY(env, maybe_script, napi_generic_failure); - auto script_result = - maybe_script.ToLocalChecked()->Run(context); + auto script_result = maybe_script.ToLocalChecked()->Run(context); CHECK_MAYBE_EMPTY(env, script_result, napi_generic_failure); *result = v8impl::JsValueFromV8LocalValue(script_result.ToLocalChecked()); return GET_RETURN_STATUS(env); } -class TsFn: public node::AsyncResource { +class TsFn : public node::AsyncResource { public: TsFn(v8::Local func, v8::Local resource, @@ -3706,36 +3639,33 @@ class TsFn: public node::AsyncResource { napi_env env_, void* finalize_data_, napi_finalize finalize_cb_, - napi_threadsafe_function_call_js call_js_cb_): - AsyncResource(env_->isolate, - resource, - *v8::String::Utf8Value(env_->isolate, name)), - thread_count(thread_count_), - is_closing(false), - context(context_), - max_queue_size(max_queue_size_), - env(env_), - finalize_data(finalize_data_), - finalize_cb(finalize_cb_), - idle_running(false), - call_js_cb(call_js_cb_ == nullptr ? CallJs : call_js_cb_), - handles_closing(false) { + napi_threadsafe_function_call_js call_js_cb_) + : AsyncResource(env_->isolate, + resource, + *v8::String::Utf8Value(env_->isolate, name)), + thread_count(thread_count_), + is_closing(false), + context(context_), + max_queue_size(max_queue_size_), + env(env_), + finalize_data(finalize_data_), + finalize_cb(finalize_cb_), + idle_running(false), + call_js_cb(call_js_cb_ == nullptr ? CallJs : call_js_cb_), + handles_closing(false) { ref.Reset(env->isolate, func); node::AddEnvironmentCleanupHook(env->isolate, Cleanup, this); } - ~TsFn() { - node::RemoveEnvironmentCleanupHook(env->isolate, Cleanup, this); - } + ~TsFn() { node::RemoveEnvironmentCleanupHook(env->isolate, Cleanup, this); } // These methods can be called from any thread. napi_status Push(void* data, napi_threadsafe_function_call_mode mode) { node::Mutex::ScopedLock lock(this->mutex); - while (queue.size() >= max_queue_size && - max_queue_size > 0 && - !is_closing) { + while (queue.size() >= max_queue_size && max_queue_size > 0 && + !is_closing) { if (mode == napi_tsfn_nonblocking) { return napi_queue_full; } @@ -3795,7 +3725,7 @@ class TsFn: public node::AsyncResource { } void EmptyQueueAndDelete() { - for (; !queue.empty() ; queue.pop()) { + for (; !queue.empty(); queue.pop()) { call_js_cb(nullptr, nullptr, context, queue.front()); } delete this; @@ -3815,14 +3745,14 @@ class TsFn: public node::AsyncResource { return napi_ok; } - node::Environment::GetCurrent(env->isolate)->CloseHandle( - reinterpret_cast(&async), - [] (uv_handle_t* handle) -> void { - TsFn* ts_fn = - node::ContainerOf(&TsFn::async, - reinterpret_cast(handle)); - delete ts_fn; - }); + node::Environment::GetCurrent(env->isolate) + ->CloseHandle(reinterpret_cast(&async), + [](uv_handle_t* handle) -> void { + TsFn* ts_fn = node::ContainerOf( + &TsFn::async, + reinterpret_cast(handle)); + delete ts_fn; + }); // Prevent the thread-safe function from being deleted here, because // the callback above will delete it. @@ -3898,10 +3828,7 @@ class TsFn: public node::AsyncResource { } else { v8::Local js_cb = v8::Local::New(env->isolate, ref); - call_js_cb(env, - v8impl::JsValueFromV8LocalValue(js_cb), - context, - data); + call_js_cb(env, v8impl::JsValueFromV8LocalValue(js_cb), context, data); } } } @@ -3933,9 +3860,7 @@ class TsFn: public node::AsyncResource { EmptyQueueAndDelete(); } - inline void* Context() { - return context; - } + inline void* Context() { return context; } void CloseHandlesAndMaybeDelete(bool set_closing = false) { if (set_closing) { @@ -3951,14 +3876,14 @@ class TsFn: public node::AsyncResource { handles_closing = true; NodeEnv()->CloseHandle( reinterpret_cast(&async), - [] (uv_handle_t* handle) -> void { - TsFn* ts_fn = node::ContainerOf(&TsFn::async, - reinterpret_cast(handle)); + [](uv_handle_t* handle) -> void { + TsFn* ts_fn = node::ContainerOf( + &TsFn::async, reinterpret_cast(handle)); ts_fn->NodeEnv()->CloseHandle( reinterpret_cast(&ts_fn->idle), - [] (uv_handle_t* handle) -> void { - TsFn* ts_fn = node::ContainerOf(&TsFn::idle, - reinterpret_cast(handle)); + [](uv_handle_t* handle) -> void { + TsFn* ts_fn = node::ContainerOf( + &TsFn::idle, reinterpret_cast(handle)); ts_fn->Finalize(); }); }); @@ -3973,29 +3898,28 @@ class TsFn: public node::AsyncResource { status = napi_get_undefined(env, &recv); if (status != napi_ok) { - napi_throw_error(env, "ERR_NAPI_TSFN_GET_UNDEFINED", - "Failed to retrieve undefined value"); + napi_throw_error(env, + "ERR_NAPI_TSFN_GET_UNDEFINED", + "Failed to retrieve undefined value"); return; } status = napi_call_function(env, recv, cb, 0, nullptr, nullptr); if (status != napi_ok && status != napi_pending_exception) { - napi_throw_error(env, "ERR_NAPI_TSFN_CALL_JS", - "Failed to call JS callback"); + napi_throw_error( + env, "ERR_NAPI_TSFN_CALL_JS", "Failed to call JS callback"); return; } } } static void IdleCb(uv_idle_t* idle) { - TsFn* ts_fn = - node::ContainerOf(&TsFn::idle, idle); + TsFn* ts_fn = node::ContainerOf(&TsFn::idle, idle); ts_fn->DispatchOne(); } static void AsyncCb(uv_async_t* async) { - TsFn* ts_fn = - node::ContainerOf(&TsFn::async, async); + TsFn* ts_fn = node::ContainerOf(&TsFn::async, async); ts_fn->MaybeStartIdle(); } @@ -4087,9 +4011,8 @@ napi_create_threadsafe_function(napi_env env, return napi_set_last_error(env, status); } -NAPI_EXTERN napi_status -napi_get_threadsafe_function_context(napi_threadsafe_function func, - void** result) { +NAPI_EXTERN napi_status napi_get_threadsafe_function_context( + napi_threadsafe_function func, void** result) { CHECK(func != nullptr); CHECK(result != nullptr); @@ -4111,9 +4034,8 @@ napi_acquire_threadsafe_function(napi_threadsafe_function func) { return reinterpret_cast(func)->Acquire(); } -NAPI_EXTERN napi_status -napi_release_threadsafe_function(napi_threadsafe_function func, - napi_threadsafe_function_release_mode mode) { +NAPI_EXTERN napi_status napi_release_threadsafe_function( + napi_threadsafe_function func, napi_threadsafe_function_release_mode mode) { CHECK(func != nullptr); return reinterpret_cast(func)->Release(mode); } diff --git a/src/node_api.h b/src/node_api.h index 1b2a392a0a0b1c..06a792fa1a44a9 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -1,8 +1,8 @@ #ifndef SRC_NODE_API_H_ #define SRC_NODE_API_H_ -#include #include +#include #include "node_api_types.h" struct uv_loop_s; // Forward declaration. @@ -18,26 +18,27 @@ struct uv_loop_s; // Forward declaration. #endif #ifdef _WIN32 - #ifdef BUILDING_NODE_EXTENSION - #ifdef EXTERNAL_NAPI - // Building external N-API, or native module against external N-API - #define NAPI_EXTERN /* nothing */ - #else - // Building native module against node with built-in N-API - #define NAPI_EXTERN __declspec(dllimport) - #endif - #else - // Building node with built-in N-API - #define NAPI_EXTERN __declspec(dllexport) - #endif +#ifdef BUILDING_NODE_EXTENSION +#ifdef EXTERNAL_NAPI + // Building external N-API, or native module against external + // N-API +#define NAPI_EXTERN /* nothing */ +#else + // Building native module against node with built-in N-API +#define NAPI_EXTERN __declspec(dllimport) +#endif #else - #define NAPI_EXTERN /* nothing */ + // Building node with built-in N-API +#define NAPI_EXTERN __declspec(dllexport) +#endif +#else +#define NAPI_EXTERN /* nothing */ #endif #ifdef _WIN32 -# define NAPI_MODULE_EXPORT __declspec(dllexport) +#define NAPI_MODULE_EXPORT __declspec(dllexport) #else -# define NAPI_MODULE_EXPORT __attribute__((visibility("default"))) +#define NAPI_MODULE_EXPORT __attribute__((visibility("default"))) #endif #ifdef __GNUC__ @@ -46,7 +47,6 @@ struct uv_loop_s; // Forward declaration. #define NAPI_NO_RETURN #endif - typedef napi_value (*napi_addon_register_func)(napi_env env, napi_value exports); @@ -60,18 +60,18 @@ typedef struct { void* reserved[4]; } napi_module; -#define NAPI_MODULE_VERSION 1 +#define NAPI_MODULE_VERSION 1 #if defined(_MSC_VER) #pragma section(".CRT$XCU", read) -#define NAPI_C_CTOR(fn) \ - static void __cdecl fn(void); \ - __declspec(dllexport, allocate(".CRT$XCU")) void(__cdecl * fn##_)(void) = \ - fn; \ +#define NAPI_C_CTOR(fn) \ + static void __cdecl fn(void); \ + __declspec(dllexport, allocate(".CRT$XCU")) void(__cdecl * fn##_)(void) = \ + fn; \ static void __cdecl fn(void) #else -#define NAPI_C_CTOR(fn) \ - static void fn(void) __attribute__((constructor)); \ +#define NAPI_C_CTOR(fn) \ + static void fn(void) __attribute__((constructor)); \ static void fn(void) #endif @@ -83,44 +83,39 @@ typedef struct { #define EXTERN_C_END #endif -#define NAPI_MODULE_X(modname, regfunc, priv, flags) \ - EXTERN_C_START \ - static napi_module _module = \ - { \ - NAPI_MODULE_VERSION, \ - flags, \ - __FILE__, \ - regfunc, \ - #modname, \ - priv, \ - {0}, \ - }; \ - NAPI_C_CTOR(_register_ ## modname) { \ - napi_module_register(&_module); \ - } \ +#define NAPI_MODULE_X(modname, regfunc, priv, flags) \ + EXTERN_C_START \ + static napi_module _module = { \ + NAPI_MODULE_VERSION, \ + flags, \ + __FILE__, \ + regfunc, \ + #modname, \ + priv, \ + {0}, \ + }; \ + NAPI_C_CTOR(_register_##modname) { napi_module_register(&_module); } \ EXTERN_C_END -#define NAPI_MODULE(modname, regfunc) \ +#define NAPI_MODULE(modname, regfunc) \ NAPI_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) #define NAPI_MODULE_INITIALIZER_BASE napi_register_module_v -#define NAPI_MODULE_INITIALIZER_X(base, version) \ - NAPI_MODULE_INITIALIZER_X_HELPER(base, version) +#define NAPI_MODULE_INITIALIZER_X(base, version) \ + NAPI_MODULE_INITIALIZER_X_HELPER(base, version) #define NAPI_MODULE_INITIALIZER_X_HELPER(base, version) base##version -#define NAPI_MODULE_INITIALIZER \ - NAPI_MODULE_INITIALIZER_X(NAPI_MODULE_INITIALIZER_BASE, \ - NAPI_MODULE_VERSION) +#define NAPI_MODULE_INITIALIZER \ + NAPI_MODULE_INITIALIZER_X(NAPI_MODULE_INITIALIZER_BASE, NAPI_MODULE_VERSION) -#define NAPI_MODULE_INIT() \ - EXTERN_C_START \ - NAPI_MODULE_EXPORT napi_value \ - NAPI_MODULE_INITIALIZER(napi_env env, napi_value exports); \ - EXTERN_C_END \ - NAPI_MODULE(NODE_GYP_MODULE_NAME, NAPI_MODULE_INITIALIZER) \ - napi_value NAPI_MODULE_INITIALIZER(napi_env env, \ - napi_value exports) +#define NAPI_MODULE_INIT() \ + EXTERN_C_START \ + NAPI_MODULE_EXPORT napi_value NAPI_MODULE_INITIALIZER(napi_env env, \ + napi_value exports); \ + EXTERN_C_END \ + NAPI_MODULE(NODE_GYP_MODULE_NAME, NAPI_MODULE_INITIALIZER) \ + napi_value NAPI_MODULE_INITIALIZER(napi_env env, napi_value exports) #define NAPI_AUTO_LENGTH SIZE_MAX @@ -129,8 +124,7 @@ EXTERN_C_START NAPI_EXTERN void napi_module_register(napi_module* mod); NAPI_EXTERN napi_status -napi_get_last_error_info(napi_env env, - const napi_extended_error_info** result); +napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, size_t location_len, @@ -218,18 +212,12 @@ NAPI_EXTERN napi_status napi_get_value_bool(napi_env env, bool* result); // Copies LATIN-1 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result); +NAPI_EXTERN napi_status napi_get_value_string_latin1( + napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result); // Copies UTF-8 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_utf8(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result); +NAPI_EXTERN napi_status napi_get_value_string_utf8( + napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result); // Copies UTF-16 encoded bytes from a string into a buffer. NAPI_EXTERN napi_status napi_get_value_string_utf16(napi_env env, @@ -281,17 +269,17 @@ NAPI_EXTERN napi_status napi_has_own_property(napi_env env, napi_value key, bool* result); NAPI_EXTERN napi_status napi_set_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value value); + napi_value object, + const char* utf8name, + napi_value value); NAPI_EXTERN napi_status napi_has_named_property(napi_env env, - napi_value object, - const char* utf8name, - bool* result); + napi_value object, + const char* utf8name, + bool* result); NAPI_EXTERN napi_status napi_get_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value* result); + napi_value object, + const char* utf8name, + napi_value* result); NAPI_EXTERN napi_status napi_set_element(napi_env env, napi_value object, uint32_t index, @@ -432,12 +420,10 @@ NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result); NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope); -NAPI_EXTERN napi_status -napi_open_escapable_handle_scope(napi_env env, - napi_escapable_handle_scope* result); -NAPI_EXTERN napi_status -napi_close_escapable_handle_scope(napi_env env, - napi_escapable_handle_scope scope); +NAPI_EXTERN napi_status napi_open_escapable_handle_scope( + napi_env env, napi_escapable_handle_scope* result); +NAPI_EXTERN napi_status napi_close_escapable_handle_scope( + napi_env env, napi_escapable_handle_scope scope); NAPI_EXTERN napi_status napi_escape_handle(napi_env env, napi_escapable_handle_scope scope, @@ -450,11 +436,11 @@ NAPI_EXTERN napi_status napi_throw_error(napi_env env, const char* code, const char* msg); NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, - const char* code, - const char* msg); + const char* code, + const char* msg); NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, - const char* code, - const char* msg); + const char* code, + const char* msg); NAPI_EXTERN napi_status napi_is_error(napi_env env, napi_value value, bool* result); @@ -649,9 +635,8 @@ napi_create_threadsafe_function(napi_env env, napi_threadsafe_function_call_js call_js_cb, napi_threadsafe_function* result); -NAPI_EXTERN napi_status -napi_get_threadsafe_function_context(napi_threadsafe_function func, - void** result); +NAPI_EXTERN napi_status napi_get_threadsafe_function_context( + napi_threadsafe_function func, void** result); NAPI_EXTERN napi_status napi_call_threadsafe_function(napi_threadsafe_function func, @@ -661,9 +646,8 @@ napi_call_threadsafe_function(napi_threadsafe_function func, NAPI_EXTERN napi_status napi_acquire_threadsafe_function(napi_threadsafe_function func); -NAPI_EXTERN napi_status -napi_release_threadsafe_function(napi_threadsafe_function func, - napi_threadsafe_function_release_mode mode); +NAPI_EXTERN napi_status napi_release_threadsafe_function( + napi_threadsafe_function func, napi_threadsafe_function_release_mode mode); NAPI_EXTERN napi_status napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func); diff --git a/src/node_api_types.h b/src/node_api_types.h index 10215d9aa3a0ff..3064abfd365f66 100644 --- a/src/node_api_types.h +++ b/src/node_api_types.h @@ -5,7 +5,7 @@ #include #if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) - typedef uint16_t char16_t; +typedef uint16_t char16_t; #endif // JSVM API types are all opaque pointers for ABI stability @@ -96,13 +96,11 @@ typedef enum { } napi_threadsafe_function_call_mode; #endif // NAPI_EXPERIMENTAL -typedef napi_value (*napi_callback)(napi_env env, - napi_callback_info info); +typedef napi_value (*napi_callback)(napi_env env, napi_callback_info info); typedef void (*napi_finalize)(napi_env env, void* finalize_data, void* finalize_hint); -typedef void (*napi_async_execute_callback)(napi_env env, - void* data); +typedef void (*napi_async_execute_callback)(napi_env env, void* data); typedef void (*napi_async_complete_callback)(napi_env env, napi_status status, void* data); diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 858852e748fe03..7f418ac57a356d 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -19,8 +19,8 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node.h" #include "node_buffer.h" +#include "node.h" #include "node_errors.h" #include "env-inl.h" @@ -30,28 +30,28 @@ #include "v8-profiler.h" #include "v8.h" -#include #include +#include #define BUFFER_ID 0xB0E4 #define MIN(a, b) ((a) < (b) ? (a) : (b)) -#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj) \ +#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj) \ THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument") -#define THROW_AND_RETURN_IF_OOB(r) \ - do { \ - if (!(r)) return node::THROW_ERR_INDEX_OUT_OF_RANGE(env); \ +#define THROW_AND_RETURN_IF_OOB(r) \ + do { \ + if (!(r)) return node::THROW_ERR_INDEX_OUT_OF_RANGE(env); \ } while (0) -#define SLICE_START_END(start_arg, end_arg, end_max) \ - size_t start; \ - size_t end; \ - THROW_AND_RETURN_IF_OOB(ParseArrayIndex(start_arg, 0, &start)); \ - THROW_AND_RETURN_IF_OOB(ParseArrayIndex(end_arg, end_max, &end)); \ - if (end < start) end = start; \ - THROW_AND_RETURN_IF_OOB(end <= end_max); \ +#define SLICE_START_END(start_arg, end_arg, end_max) \ + size_t start; \ + size_t end; \ + THROW_AND_RETURN_IF_OOB(ParseArrayIndex(start_arg, 0, &start)); \ + THROW_AND_RETURN_IF_OOB(ParseArrayIndex(end_arg, end_max, &end)); \ + if (end < start) end = start; \ + THROW_AND_RETURN_IF_OOB(end <= end_max); \ size_t length = end - start; namespace node { @@ -62,8 +62,8 @@ bool zero_fill_all_buffers = false; namespace { inline void* BufferMalloc(size_t length) { - return zero_fill_all_buffers ? node::UncheckedCalloc(length) : - node::UncheckedMalloc(length); + return zero_fill_all_buffers ? node::UncheckedCalloc(length) + : node::UncheckedMalloc(length); } } // namespace @@ -98,6 +98,7 @@ class CallbackInfo { FreeCallback callback, char* data, void* hint = 0); + private: static void WeakCallback(const WeakCallbackInfo&); inline void WeakCallback(Isolate* isolate); @@ -113,12 +114,10 @@ class CallbackInfo { DISALLOW_COPY_AND_ASSIGN(CallbackInfo); }; - void CallbackInfo::Free(char* data, void*) { ::free(data); } - CallbackInfo* CallbackInfo::New(Isolate* isolate, Local object, FreeCallback callback, @@ -127,7 +126,6 @@ CallbackInfo* CallbackInfo::New(Isolate* isolate, return new CallbackInfo(isolate, object, callback, data, hint); } - CallbackInfo::CallbackInfo(Isolate* isolate, Local object, FreeCallback callback, @@ -139,30 +137,25 @@ CallbackInfo::CallbackInfo(Isolate* isolate, hint_(hint) { ArrayBuffer::Contents obj_c = object->GetContents(); CHECK_EQ(data_, static_cast(obj_c.Data())); - if (object->ByteLength() != 0) - CHECK_NOT_NULL(data_); + if (object->ByteLength() != 0) CHECK_NOT_NULL(data_); persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); persistent_.SetWrapperClassId(BUFFER_ID); isolate->AdjustAmountOfExternalAllocatedMemory(sizeof(*this)); } - -void CallbackInfo::WeakCallback( - const WeakCallbackInfo& data) { +void CallbackInfo::WeakCallback(const WeakCallbackInfo& data) { CallbackInfo* self = data.GetParameter(); self->WeakCallback(data.GetIsolate()); delete self; } - void CallbackInfo::WeakCallback(Isolate* isolate) { callback_(data_, hint_); int64_t change_in_bytes = -static_cast(sizeof(*this)); isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes); } - // Parse index for external array data. inline MUST_USE_RESULT bool ParseArrayIndex(Local arg, size_t def, @@ -174,14 +167,12 @@ inline MUST_USE_RESULT bool ParseArrayIndex(Local arg, int64_t tmp_i = arg->IntegerValue(); - if (tmp_i < 0) - return false; + if (tmp_i < 0) return false; // Check that the result fits in a size_t. const uint64_t kSizeMax = static_cast(static_cast(-1)); // coverity[pointless_expression] - if (static_cast(tmp_i) > kSizeMax) - return false; + if (static_cast(tmp_i) > kSizeMax) return false; *ret = static_cast(tmp_i); return true; @@ -195,12 +186,10 @@ bool HasInstance(Local val) { return val->IsArrayBufferView(); } - bool HasInstance(Local obj) { return obj->IsArrayBufferView(); } - char* Data(Local val) { CHECK(val->IsArrayBufferView()); Local ui = val.As(); @@ -208,7 +197,6 @@ char* Data(Local val) { return static_cast(ab_c.Data()) + ui->ByteOffset(); } - char* Data(Local obj) { CHECK(obj->IsArrayBufferView()); Local ui = obj.As(); @@ -216,21 +204,18 @@ char* Data(Local obj) { return static_cast(ab_c.Data()) + ui->ByteOffset(); } - size_t Length(Local val) { CHECK(val->IsArrayBufferView()); Local ui = val.As(); return ui->ByteLength(); } - size_t Length(Local obj) { CHECK(obj->IsArrayBufferView()); Local ui = obj.As(); return ui->ByteLength(); } - MaybeLocal New(Isolate* isolate, Local string, enum encoding enc) { @@ -243,8 +228,7 @@ MaybeLocal New(Isolate* isolate, if (length > 0) { data = static_cast(BufferMalloc(length)); - if (data == nullptr) - return Local(); + if (data == nullptr) return Local(); actual = StringBytes::Write(isolate, data, length, string, enc); CHECK(actual <= length); @@ -258,15 +242,13 @@ MaybeLocal New(Isolate* isolate, } Local buf; - if (New(isolate, data, actual).ToLocal(&buf)) - return scope.Escape(buf); + if (New(isolate, data, actual).ToLocal(&buf)) return scope.Escape(buf); // Object failed to be created. Clean up resources. free(data); return Local(); } - MaybeLocal New(Isolate* isolate, size_t length) { EscapableHandleScope handle_scope(isolate); Local obj; @@ -275,7 +257,6 @@ MaybeLocal New(Isolate* isolate, size_t length) { return Local(); } - MaybeLocal New(Environment* env, size_t length) { EscapableHandleScope scope(env->isolate()); @@ -287,17 +268,13 @@ MaybeLocal New(Environment* env, size_t length) { void* data; if (length > 0) { data = BufferMalloc(length); - if (data == nullptr) - return Local(); + if (data == nullptr) return Local(); } else { data = nullptr; } - Local ab = - ArrayBuffer::New(env->isolate(), - data, - length, - ArrayBufferCreationMode::kInternalized); + Local ab = ArrayBuffer::New( + env->isolate(), data, length, ArrayBufferCreationMode::kInternalized); MaybeLocal ui = Buffer::New(env, ab, 0, length); if (ui.IsEmpty()) { @@ -308,7 +285,6 @@ MaybeLocal New(Environment* env, size_t length) { return scope.Escape(ui.FromMaybe(Local())); } - MaybeLocal Copy(Isolate* isolate, const char* data, size_t length) { EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); @@ -318,7 +294,6 @@ MaybeLocal Copy(Isolate* isolate, const char* data, size_t length) { return Local(); } - MaybeLocal Copy(Environment* env, const char* data, size_t length) { EscapableHandleScope scope(env->isolate()); @@ -331,18 +306,14 @@ MaybeLocal Copy(Environment* env, const char* data, size_t length) { if (length > 0) { CHECK_NOT_NULL(data); new_data = node::UncheckedMalloc(length); - if (new_data == nullptr) - return Local(); + if (new_data == nullptr) return Local(); memcpy(new_data, data, length); } else { new_data = nullptr; } - Local ab = - ArrayBuffer::New(env->isolate(), - new_data, - length, - ArrayBufferCreationMode::kInternalized); + Local ab = ArrayBuffer::New( + env->isolate(), new_data, length, ArrayBufferCreationMode::kInternalized); MaybeLocal ui = Buffer::New(env, ab, 0, length); if (ui.IsEmpty()) { @@ -353,7 +324,6 @@ MaybeLocal Copy(Environment* env, const char* data, size_t length) { return scope.Escape(ui.FromMaybe(Local())); } - MaybeLocal New(Isolate* isolate, char* data, size_t length, @@ -367,7 +337,6 @@ MaybeLocal New(Isolate* isolate, return Local(); } - MaybeLocal New(Environment* env, char* data, size_t length, @@ -383,8 +352,7 @@ MaybeLocal New(Environment* env, // `Neuter()`ing is required here to prevent materialization of the backing // store in v8. `nullptr` buffers are not writable, so this is semantically // correct. - if (data == nullptr) - ab->Neuter(); + if (data == nullptr) ab->Neuter(); MaybeLocal ui = Buffer::New(env, ab, 0, length); if (ui.IsEmpty()) { @@ -395,7 +363,6 @@ MaybeLocal New(Environment* env, return scope.Escape(ui.ToLocalChecked()); } - MaybeLocal New(Isolate* isolate, char* data, size_t length) { EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); @@ -405,18 +372,14 @@ MaybeLocal New(Isolate* isolate, char* data, size_t length) { return Local(); } - MaybeLocal New(Environment* env, char* data, size_t length) { if (length > 0) { CHECK_NOT_NULL(data); CHECK(length <= kMaxLength); } - Local ab = - ArrayBuffer::New(env->isolate(), - data, - length, - ArrayBufferCreationMode::kInternalized); + Local ab = ArrayBuffer::New( + env->isolate(), data, length, ArrayBufferCreationMode::kInternalized); return Buffer::New(env, ab, 0, length).FromMaybe(Local()); } @@ -426,15 +389,13 @@ void CreateFromString(const FunctionCallbackInfo& args) { CHECK(args[0]->IsString()); CHECK(args[1]->IsString()); - enum encoding enc = ParseEncoding(args.GetIsolate(), - args[1].As(), - UTF8); + enum encoding enc = + ParseEncoding(args.GetIsolate(), args[1].As(), UTF8); Local buf; if (New(args.GetIsolate(), args[0].As(), enc).ToLocal(&buf)) args.GetReturnValue().Set(buf); } - template void StringSlice(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -443,18 +404,13 @@ void StringSlice(const FunctionCallbackInfo& args) { THROW_AND_RETURN_UNLESS_BUFFER(env, args.This()); SPREAD_BUFFER_ARG(args.This(), ts_obj); - if (ts_obj_length == 0) - return args.GetReturnValue().SetEmptyString(); + if (ts_obj_length == 0) return args.GetReturnValue().SetEmptyString(); SLICE_START_END(args[0], args[1], ts_obj_length) Local error; - MaybeLocal ret = - StringBytes::Encode(isolate, - ts_obj_data + start, - length, - encoding, - &error); + MaybeLocal ret = StringBytes::Encode( + isolate, ts_obj_data + start, length, encoding, &error); if (ret.IsEmpty()) { CHECK(!error.IsEmpty()); isolate->ThrowException(error); @@ -463,7 +419,6 @@ void StringSlice(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ret.ToLocalChecked()); } - template <> void StringSlice(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); @@ -472,8 +427,7 @@ void StringSlice(const FunctionCallbackInfo& args) { THROW_AND_RETURN_UNLESS_BUFFER(env, args.This()); SPREAD_BUFFER_ARG(args.This(), ts_obj); - if (ts_obj_length == 0) - return args.GetReturnValue().SetEmptyString(); + if (ts_obj_length == 0) return args.GetReturnValue().SetEmptyString(); SLICE_START_END(args[0], args[1], ts_obj_length) length /= 2; @@ -505,14 +459,9 @@ void StringSlice(const FunctionCallbackInfo& args) { } Local error; - MaybeLocal ret = - StringBytes::Encode(isolate, - buf, - length, - &error); + MaybeLocal ret = StringBytes::Encode(isolate, buf, length, &error); - if (release) - delete[] buf; + if (release) delete[] buf; if (ret.IsEmpty()) { CHECK(!error.IsEmpty()); @@ -522,9 +471,8 @@ void StringSlice(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ret.ToLocalChecked()); } - // bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd]) -void Copy(const FunctionCallbackInfo &args) { +void Copy(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); @@ -552,15 +500,14 @@ void Copy(const FunctionCallbackInfo &args) { if (source_end - source_start > target_length - target_start) source_end = source_start + target_length - target_start; - uint32_t to_copy = MIN(MIN(source_end - source_start, - target_length - target_start), - ts_obj_length - source_start); + uint32_t to_copy = + MIN(MIN(source_end - source_start, target_length - target_start), + ts_obj_length - source_start); memmove(target_data + target_start, ts_obj_data + source_start, to_copy); args.GetReturnValue().Set(to_copy); } - void Fill(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -623,18 +570,16 @@ void Fill(const FunctionCallbackInfo& args) { nullptr); } - start_fill: +start_fill: - if (str_length >= fill_length) - return; + if (str_length >= fill_length) return; // If str_length is zero, then either an empty buffer was provided, or Write() // indicated that no bytes could be written. If no bytes could be written, // then return -1 because the fill value is invalid. This will trigger a throw // in JavaScript. Silently failing should be avoided because it can lead to // buffers with unexpected contents. - if (str_length == 0) - return args.GetReturnValue().Set(-1); + if (str_length == 0) return args.GetReturnValue().Set(-1); size_t in_there = str_length; char* ptr = ts_obj_data + start + str_length; @@ -650,7 +595,6 @@ void Fill(const FunctionCallbackInfo& args) { } } - template void StringWrite(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -671,24 +615,19 @@ void StringWrite(const FunctionCallbackInfo& args) { env, "\"offset\" is outside of buffer bounds"); } - THROW_AND_RETURN_IF_OOB(ParseArrayIndex(args[2], ts_obj_length - offset, - &max_length)); + THROW_AND_RETURN_IF_OOB( + ParseArrayIndex(args[2], ts_obj_length - offset, &max_length)); max_length = MIN(ts_obj_length - offset, max_length); - if (max_length == 0) - return args.GetReturnValue().Set(0); + if (max_length == 0) return args.GetReturnValue().Set(0); - uint32_t written = StringBytes::Write(env->isolate(), - ts_obj_data + offset, - max_length, - str, - encoding, - nullptr); + uint32_t written = StringBytes::Write( + env->isolate(), ts_obj_data + offset, max_length, str, encoding, nullptr); args.GetReturnValue().Set(written); } -void ByteLengthUtf8(const FunctionCallbackInfo &args) { +void ByteLengthUtf8(const FunctionCallbackInfo& args) { CHECK(args[0]->IsString()); // Fast case: avoid StringBytes on UTF8 string. Jump to v8. @@ -712,7 +651,7 @@ static int normalizeCompareVal(int val, size_t a_length, size_t b_length) { return val; } -void CompareOffset(const FunctionCallbackInfo &args) { +void CompareOffset(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); @@ -738,21 +677,20 @@ void CompareOffset(const FunctionCallbackInfo &args) { CHECK_LE(source_start, source_end); CHECK_LE(target_start, target_end); - size_t to_cmp = MIN(MIN(source_end - source_start, - target_end - target_start), + size_t to_cmp = MIN(MIN(source_end - source_start, target_end - target_start), ts_obj_length - source_start); - int val = normalizeCompareVal(to_cmp > 0 ? - memcmp(ts_obj_data + source_start, - target_data + target_start, - to_cmp) : 0, + int val = normalizeCompareVal(to_cmp > 0 ? memcmp(ts_obj_data + source_start, + target_data + target_start, + to_cmp) + : 0, source_end - source_start, target_end - target_start); args.GetReturnValue().Set(val); } -void Compare(const FunctionCallbackInfo &args) { +void Compare(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); @@ -762,13 +700,13 @@ void Compare(const FunctionCallbackInfo &args) { size_t cmp_length = MIN(obj_a_length, obj_b_length); - int val = normalizeCompareVal(cmp_length > 0 ? - memcmp(obj_a_data, obj_b_data, cmp_length) : 0, - obj_a_length, obj_b_length); + int val = normalizeCompareVal( + cmp_length > 0 ? memcmp(obj_a_data, obj_b_data, cmp_length) : 0, + obj_a_length, + obj_b_length); args.GetReturnValue().Set(val); } - // Computes the offset for starting an indexOf or lastIndexOf search. // Returns either a valid offset in [0...], ie inside the Buffer, // or -1 to signal that there is no possible match. @@ -810,9 +748,7 @@ void IndexOfString(const FunctionCallbackInfo& args) { CHECK(args[2]->IsNumber()); CHECK(args[4]->IsBoolean()); - enum encoding enc = ParseEncoding(args.GetIsolate(), - args[3], - UTF8); + enum encoding enc = ParseEncoding(args.GetIsolate(), args[3], UTF8); THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]); SPREAD_BUFFER_ARG(args[0], ts_obj); @@ -823,16 +759,15 @@ void IndexOfString(const FunctionCallbackInfo& args) { const char* haystack = ts_obj_data; // Round down to the nearest multiple of 2 in case of UCS2. - const size_t haystack_length = (enc == UCS2) ? - ts_obj_length &~ 1 : ts_obj_length; // NOLINT(whitespace/operators) + const size_t haystack_length = + (enc == UCS2) ? ts_obj_length & ~1 + : ts_obj_length; // NOLINT(whitespace/operators) const size_t needle_length = StringBytes::Size(args.GetIsolate(), needle, enc); - int64_t opt_offset = IndexOfOffset(haystack_length, - offset_i64, - needle_length, - is_forward); + int64_t opt_offset = + IndexOfOffset(haystack_length, offset_i64, needle_length, is_forward); if (needle_length == 0) { // Match String#indexOf() and String#lastIndexOf() behavior. @@ -858,8 +793,7 @@ void IndexOfString(const FunctionCallbackInfo& args) { if (enc == UCS2) { String::Value needle_value(args.GetIsolate(), needle); - if (*needle_value == nullptr) - return args.GetReturnValue().Set(-1); + if (*needle_value == nullptr) return args.GetReturnValue().Set(-1); if (haystack_length < 2 || needle_value.length() < 1) { return args.GetReturnValue().Set(-1); @@ -871,8 +805,7 @@ void IndexOfString(const FunctionCallbackInfo& args) { const uint16_t* decoded_string = reinterpret_cast(decoder.out()); - if (decoded_string == nullptr) - return args.GetReturnValue().Set(-1); + if (decoded_string == nullptr) return args.GetReturnValue().Set(-1); result = SearchString(reinterpret_cast(haystack), haystack_length / 2, @@ -891,8 +824,7 @@ void IndexOfString(const FunctionCallbackInfo& args) { result *= 2; } else if (enc == UTF8) { String::Utf8Value needle_value(args.GetIsolate(), needle); - if (*needle_value == nullptr) - return args.GetReturnValue().Set(-1); + if (*needle_value == nullptr) return args.GetReturnValue().Set(-1); result = SearchString(reinterpret_cast(haystack), haystack_length, @@ -926,9 +858,7 @@ void IndexOfBuffer(const FunctionCallbackInfo& args) { CHECK(args[2]->IsNumber()); CHECK(args[4]->IsBoolean()); - enum encoding enc = ParseEncoding(args.GetIsolate(), - args[3], - UTF8); + enum encoding enc = ParseEncoding(args.GetIsolate(), args[3], UTF8); THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]); THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]); @@ -942,10 +872,8 @@ void IndexOfBuffer(const FunctionCallbackInfo& args) { const char* needle = buf_data; const size_t needle_length = buf_length; - int64_t opt_offset = IndexOfOffset(haystack_length, - offset_i64, - needle_length, - is_forward); + int64_t opt_offset = + IndexOfOffset(haystack_length, offset_i64, needle_length, is_forward); if (needle_length == 0) { // Match String#indexOf() and String#lastIndexOf() behavior. @@ -973,22 +901,20 @@ void IndexOfBuffer(const FunctionCallbackInfo& args) { if (haystack_length < 2 || needle_length < 2) { return args.GetReturnValue().Set(-1); } - result = SearchString( - reinterpret_cast(haystack), - haystack_length / 2, - reinterpret_cast(needle), - needle_length / 2, - offset / 2, - is_forward); + result = SearchString(reinterpret_cast(haystack), + haystack_length / 2, + reinterpret_cast(needle), + needle_length / 2, + offset / 2, + is_forward); result *= 2; } else { - result = SearchString( - reinterpret_cast(haystack), - haystack_length, - reinterpret_cast(needle), - needle_length, - offset, - is_forward); + result = SearchString(reinterpret_cast(haystack), + haystack_length, + reinterpret_cast(needle), + needle_length, + offset, + is_forward); } args.GetReturnValue().Set( @@ -1025,7 +951,6 @@ void IndexOfNumber(const FunctionCallbackInfo& args) { : -1); } - void Swap16(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); @@ -1034,7 +959,6 @@ void Swap16(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(args[0]); } - void Swap32(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); @@ -1043,7 +967,6 @@ void Swap32(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(args[0]); } - void Swap64(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); @@ -1052,7 +975,6 @@ void Swap64(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(args[0]); } - // Encode a single string to a UTF-8 Uint8Array (not Buffer). // Used in TextEncoder.prototype.encode. static void EncodeUtf8String(const FunctionCallbackInfo& args) { @@ -1064,16 +986,15 @@ static void EncodeUtf8String(const FunctionCallbackInfo& args) { size_t length = str->Utf8Length(); char* data = node::UncheckedMalloc(length); str->WriteUtf8(data, - -1, // We are certain that `data` is sufficiently large + -1, // We are certain that `data` is sufficiently large nullptr, String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8); - auto array_buf = ArrayBuffer::New(env->isolate(), data, length, - ArrayBufferCreationMode::kInternalized); + auto array_buf = ArrayBuffer::New( + env->isolate(), data, length, ArrayBufferCreationMode::kInternalized); auto array = Uint8Array::New(array_buf, 0, length); args.GetReturnValue().Set(array); } - // pass Buffer object to load prototype methods void SetupBufferJS(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1099,16 +1020,14 @@ void SetupBufferJS(const FunctionCallbackInfo& args) { if (auto zero_fill_field = env->isolate_data()->zero_fill_field()) { CHECK(args[1]->IsObject()); auto binding_object = args[1].As(); - auto array_buffer = ArrayBuffer::New(env->isolate(), - zero_fill_field, - sizeof(*zero_fill_field)); + auto array_buffer = ArrayBuffer::New( + env->isolate(), zero_fill_field, sizeof(*zero_fill_field)); auto name = FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"); auto value = Uint32Array::New(array_buffer, 0, 1); CHECK(binding_object->Set(env->context(), name, value).FromJust()); } } - void Initialize(Local target, Local unused, Local context) { @@ -1132,13 +1051,17 @@ void Initialize(Local target, env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"), - Integer::NewFromUnsigned(env->isolate(), kMaxLength)).FromJust(); - - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"), - Integer::New(env->isolate(), String::kMaxLength)).FromJust(); + target + ->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"), + Integer::NewFromUnsigned(env->isolate(), kMaxLength)) + .FromJust(); + + target + ->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"), + Integer::New(env->isolate(), String::kMaxLength)) + .FromJust(); } } // anonymous namespace diff --git a/src/node_buffer.h b/src/node_buffer.h index b4aa12cbcfadc6..7741ede96aca09 100644 --- a/src/node_buffer.h +++ b/src/node_buffer.h @@ -71,12 +71,10 @@ NODE_EXTERN v8::MaybeLocal New(v8::Isolate* isolate, static inline bool IsWithinBounds(size_t off, size_t len, size_t max) { // Asking to seek too far into the buffer // check to avoid wrapping in subsequent subtraction - if (off > max) - return false; + if (off > max) return false; // Asking for more than is left over in the buffer - if (max - off < len) - return false; + if (max - off < len) return false; // Otherwise we're in bounds return true; diff --git a/src/node_config.cc b/src/node_config.cc index dd5ee666486874..cfea1d4072c0ac 100644 --- a/src/node_config.cc +++ b/src/node_config.cc @@ -1,8 +1,8 @@ +#include "env-inl.h" #include "node.h" +#include "node_debug_options.h" #include "node_i18n.h" -#include "env-inl.h" #include "util-inl.h" -#include "node_debug_options.h" namespace node { @@ -22,18 +22,23 @@ using v8::Value; // alternative to dropping additional properties onto the process object as // has been the practice previously in node.cc. -#define READONLY_BOOLEAN_PROPERTY(str) \ - do { \ - target->DefineOwnProperty(context, \ - FIXED_ONE_BYTE_STRING(isolate, str), \ - True(isolate), ReadOnly).FromJust(); \ +#define READONLY_BOOLEAN_PROPERTY(str) \ + do { \ + target \ + ->DefineOwnProperty(context, \ + FIXED_ONE_BYTE_STRING(isolate, str), \ + True(isolate), \ + ReadOnly) \ + .FromJust(); \ } while (0) -#define READONLY_PROPERTY(obj, name, value) \ - do { \ - obj->DefineOwnProperty(env->context(), \ - FIXED_ONE_BYTE_STRING(isolate, name), \ - value, ReadOnly).FromJust(); \ +#define READONLY_PROPERTY(obj, name, value) \ + do { \ + obj->DefineOwnProperty(env->context(), \ + FIXED_ONE_BYTE_STRING(isolate, name), \ + value, \ + ReadOnly) \ + .FromJust(); \ } while (0) static void Initialize(Local target, @@ -44,8 +49,7 @@ static void Initialize(Local target, #ifdef NODE_FIPS_MODE READONLY_BOOLEAN_PROPERTY("fipsMode"); - if (force_fips_crypto) - READONLY_BOOLEAN_PROPERTY("fipsForced"); + if (force_fips_crypto) READONLY_BOOLEAN_PROPERTY("fipsForced"); #endif #ifdef NODE_HAVE_I18N_SUPPORT @@ -60,31 +64,34 @@ static void Initialize(Local target, READONLY_BOOLEAN_PROPERTY("hasTracing"); #endif - target->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "icuDataDir"), - String::NewFromUtf8(isolate, - icu_data_dir.data(), - v8::NewStringType::kNormal).ToLocalChecked(), - ReadOnly).FromJust(); + target + ->DefineOwnProperty( + context, + FIXED_ONE_BYTE_STRING(isolate, "icuDataDir"), + String::NewFromUtf8( + isolate, icu_data_dir.data(), v8::NewStringType::kNormal) + .ToLocalChecked(), + ReadOnly) + .FromJust(); #endif // NODE_HAVE_I18N_SUPPORT - if (config_preserve_symlinks) - READONLY_BOOLEAN_PROPERTY("preserveSymlinks"); + if (config_preserve_symlinks) READONLY_BOOLEAN_PROPERTY("preserveSymlinks"); if (config_preserve_symlinks_main) READONLY_BOOLEAN_PROPERTY("preserveSymlinksMain"); if (config_experimental_modules) { READONLY_BOOLEAN_PROPERTY("experimentalModules"); if (!config_userland_loader.empty()) { - target->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "userLoader"), - String::NewFromUtf8(isolate, - config_userland_loader.data(), - v8::NewStringType::kNormal).ToLocalChecked(), - ReadOnly).FromJust(); + target + ->DefineOwnProperty(context, + FIXED_ONE_BYTE_STRING(isolate, "userLoader"), + String::NewFromUtf8(isolate, + config_userland_loader.data(), + v8::NewStringType::kNormal) + .ToLocalChecked(), + ReadOnly) + .FromJust(); } } @@ -100,52 +107,59 @@ static void Initialize(Local target, if (config_pending_deprecation) READONLY_BOOLEAN_PROPERTY("pendingDeprecation"); - if (config_expose_internals) - READONLY_BOOLEAN_PROPERTY("exposeInternals"); + if (config_expose_internals) READONLY_BOOLEAN_PROPERTY("exposeInternals"); if (env->abort_on_uncaught_exception()) READONLY_BOOLEAN_PROPERTY("shouldAbortOnUncaughtException"); - READONLY_PROPERTY(target, - "bits", - Number::New(env->isolate(), 8 * sizeof(intptr_t))); + READONLY_PROPERTY( + target, "bits", Number::New(env->isolate(), 8 * sizeof(intptr_t))); if (!config_warning_file.empty()) { - target->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "warningFile"), - String::NewFromUtf8(isolate, - config_warning_file.data(), - v8::NewStringType::kNormal).ToLocalChecked(), - ReadOnly).FromJust(); + target + ->DefineOwnProperty( + context, + FIXED_ONE_BYTE_STRING(isolate, "warningFile"), + String::NewFromUtf8( + isolate, config_warning_file.data(), v8::NewStringType::kNormal) + .ToLocalChecked(), + ReadOnly) + .FromJust(); } Local debugOptions = Object::New(isolate); - target->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "debugOptions"), - debugOptions, ReadOnly).FromJust(); - - debugOptions->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "host"), - String::NewFromUtf8(isolate, - debug_options.host_name().c_str(), - v8::NewStringType::kNormal).ToLocalChecked(), - ReadOnly).FromJust(); - - debugOptions->DefineOwnProperty( - context, - env->port_string(), - Integer::New(isolate, debug_options.port()), - ReadOnly).FromJust(); - - debugOptions->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "inspectorEnabled"), - Boolean::New(isolate, debug_options.inspector_enabled()), ReadOnly) - .FromJust(); + target + ->DefineOwnProperty(context, + FIXED_ONE_BYTE_STRING(isolate, "debugOptions"), + debugOptions, + ReadOnly) + .FromJust(); + + debugOptions + ->DefineOwnProperty(context, + FIXED_ONE_BYTE_STRING(isolate, "host"), + String::NewFromUtf8(isolate, + debug_options.host_name().c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked(), + ReadOnly) + .FromJust(); + + debugOptions + ->DefineOwnProperty(context, + env->port_string(), + Integer::New(isolate, debug_options.port()), + ReadOnly) + .FromJust(); + + debugOptions + ->DefineOwnProperty( + context, + FIXED_ONE_BYTE_STRING(isolate, "inspectorEnabled"), + Boolean::New(isolate, debug_options.inspector_enabled()), + ReadOnly) + .FromJust(); } // InitConfig } // namespace node diff --git a/src/node_constants.cc b/src/node_constants.cc index 61aa42a8efb6b2..1b60a6e7263a95 100644 --- a/src/node_constants.cc +++ b/src/node_constants.cc @@ -30,16 +30,16 @@ #endif #include #include -#include #include +#include #include #if HAVE_OPENSSL -# include -# include -# ifndef OPENSSL_NO_ENGINE -# include -# endif // !OPENSSL_NO_ENGINE +#include +#include +#ifndef OPENSSL_NO_ENGINE +#include +#endif // !OPENSSL_NO_ENGINE #endif #if defined(__POSIX__) @@ -680,7 +680,6 @@ void DefineSignalConstants(Local target) { NODE_DEFINE_CONSTANT(target, SIGSTKFLT); #endif - #ifdef SIGCONT NODE_DEFINE_CONSTANT(target, SIGCONT); #endif @@ -760,248 +759,248 @@ void DefineSignalConstants(Local target) { void DefineOpenSSLConstants(Local target) { #ifdef OPENSSL_VERSION_NUMBER - NODE_DEFINE_CONSTANT(target, OPENSSL_VERSION_NUMBER); + NODE_DEFINE_CONSTANT(target, OPENSSL_VERSION_NUMBER); #endif #ifdef SSL_OP_ALL - NODE_DEFINE_CONSTANT(target, SSL_OP_ALL); + NODE_DEFINE_CONSTANT(target, SSL_OP_ALL); #endif #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION - NODE_DEFINE_CONSTANT(target, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); + NODE_DEFINE_CONSTANT(target, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); #endif #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE - NODE_DEFINE_CONSTANT(target, SSL_OP_CIPHER_SERVER_PREFERENCE); + NODE_DEFINE_CONSTANT(target, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif #ifdef SSL_OP_CISCO_ANYCONNECT - NODE_DEFINE_CONSTANT(target, SSL_OP_CISCO_ANYCONNECT); + NODE_DEFINE_CONSTANT(target, SSL_OP_CISCO_ANYCONNECT); #endif #ifdef SSL_OP_COOKIE_EXCHANGE - NODE_DEFINE_CONSTANT(target, SSL_OP_COOKIE_EXCHANGE); + NODE_DEFINE_CONSTANT(target, SSL_OP_COOKIE_EXCHANGE); #endif #ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_CRYPTOPRO_TLSEXT_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_CRYPTOPRO_TLSEXT_BUG); #endif #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS - NODE_DEFINE_CONSTANT(target, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); + NODE_DEFINE_CONSTANT(target, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); #endif #ifdef SSL_OP_EPHEMERAL_RSA - NODE_DEFINE_CONSTANT(target, SSL_OP_EPHEMERAL_RSA); + NODE_DEFINE_CONSTANT(target, SSL_OP_EPHEMERAL_RSA); #endif #ifdef SSL_OP_LEGACY_SERVER_CONNECT - NODE_DEFINE_CONSTANT(target, SSL_OP_LEGACY_SERVER_CONNECT); + NODE_DEFINE_CONSTANT(target, SSL_OP_LEGACY_SERVER_CONNECT); #endif #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER - NODE_DEFINE_CONSTANT(target, SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER); + NODE_DEFINE_CONSTANT(target, SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER); #endif #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_MICROSOFT_SESS_ID_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_MICROSOFT_SESS_ID_BUG); #endif #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING - NODE_DEFINE_CONSTANT(target, SSL_OP_MSIE_SSLV2_RSA_PADDING); + NODE_DEFINE_CONSTANT(target, SSL_OP_MSIE_SSLV2_RSA_PADDING); #endif #ifdef SSL_OP_NETSCAPE_CA_DN_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_CA_DN_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_CA_DN_BUG); #endif #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_CHALLENGE_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_CHALLENGE_BUG); #endif #ifdef SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG); #endif #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG); #endif #ifdef SSL_OP_NO_COMPRESSION - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_COMPRESSION); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_COMPRESSION); #endif #ifdef SSL_OP_NO_QUERY_MTU - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_QUERY_MTU); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_QUERY_MTU); #endif #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); #endif #ifdef SSL_OP_NO_SSLv2 - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SSLv2); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SSLv2); #endif #ifdef SSL_OP_NO_SSLv3 - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SSLv3); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SSLv3); #endif #ifdef SSL_OP_NO_TICKET - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TICKET); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TICKET); #endif #ifdef SSL_OP_NO_TLSv1 - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1); #endif #ifdef SSL_OP_NO_TLSv1_1 - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1_1); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1_1); #endif #ifdef SSL_OP_NO_TLSv1_2 - NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1_2); + NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1_2); #endif #ifdef SSL_OP_PKCS1_CHECK_1 - NODE_DEFINE_CONSTANT(target, SSL_OP_PKCS1_CHECK_1); + NODE_DEFINE_CONSTANT(target, SSL_OP_PKCS1_CHECK_1); #endif #ifdef SSL_OP_PKCS1_CHECK_2 - NODE_DEFINE_CONSTANT(target, SSL_OP_PKCS1_CHECK_2); + NODE_DEFINE_CONSTANT(target, SSL_OP_PKCS1_CHECK_2); #endif #ifdef SSL_OP_SINGLE_DH_USE - NODE_DEFINE_CONSTANT(target, SSL_OP_SINGLE_DH_USE); + NODE_DEFINE_CONSTANT(target, SSL_OP_SINGLE_DH_USE); #endif #ifdef SSL_OP_SINGLE_ECDH_USE - NODE_DEFINE_CONSTANT(target, SSL_OP_SINGLE_ECDH_USE); + NODE_DEFINE_CONSTANT(target, SSL_OP_SINGLE_ECDH_USE); #endif #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_SSLEAY_080_CLIENT_DH_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_SSLEAY_080_CLIENT_DH_BUG); #endif #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG); #endif #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_BLOCK_PADDING_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_BLOCK_PADDING_BUG); #endif #ifdef SSL_OP_TLS_D5_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_D5_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_D5_BUG); #endif #ifdef SSL_OP_TLS_ROLLBACK_BUG - NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_ROLLBACK_BUG); + NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_ROLLBACK_BUG); #endif -# ifndef OPENSSL_NO_ENGINE +#ifndef OPENSSL_NO_ENGINE -# ifdef ENGINE_METHOD_RSA - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_RSA); -# endif +#ifdef ENGINE_METHOD_RSA + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_RSA); +#endif -# ifdef ENGINE_METHOD_DSA - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DSA); -# endif +#ifdef ENGINE_METHOD_DSA + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DSA); +#endif -# ifdef ENGINE_METHOD_DH - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DH); -# endif +#ifdef ENGINE_METHOD_DH + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DH); +#endif -# ifdef ENGINE_METHOD_RAND - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_RAND); -# endif +#ifdef ENGINE_METHOD_RAND + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_RAND); +#endif -# ifdef ENGINE_METHOD_EC - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_EC); -# endif +#ifdef ENGINE_METHOD_EC + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_EC); +#endif -# ifdef ENGINE_METHOD_CIPHERS - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_CIPHERS); -# endif +#ifdef ENGINE_METHOD_CIPHERS + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_CIPHERS); +#endif -# ifdef ENGINE_METHOD_DIGESTS - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DIGESTS); -# endif +#ifdef ENGINE_METHOD_DIGESTS + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DIGESTS); +#endif -# ifdef ENGINE_METHOD_PKEY_METHS - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_PKEY_METHS); -# endif +#ifdef ENGINE_METHOD_PKEY_METHS + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_PKEY_METHS); +#endif -# ifdef ENGINE_METHOD_PKEY_ASN1_METHS - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_PKEY_ASN1_METHS); -# endif +#ifdef ENGINE_METHOD_PKEY_ASN1_METHS + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_PKEY_ASN1_METHS); +#endif -# ifdef ENGINE_METHOD_ALL - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_ALL); -# endif +#ifdef ENGINE_METHOD_ALL + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_ALL); +#endif -# ifdef ENGINE_METHOD_NONE - NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_NONE); -# endif +#ifdef ENGINE_METHOD_NONE + NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_NONE); +#endif -# endif // !OPENSSL_NO_ENGINE +#endif // !OPENSSL_NO_ENGINE #ifdef DH_CHECK_P_NOT_SAFE_PRIME - NODE_DEFINE_CONSTANT(target, DH_CHECK_P_NOT_SAFE_PRIME); + NODE_DEFINE_CONSTANT(target, DH_CHECK_P_NOT_SAFE_PRIME); #endif #ifdef DH_CHECK_P_NOT_PRIME - NODE_DEFINE_CONSTANT(target, DH_CHECK_P_NOT_PRIME); + NODE_DEFINE_CONSTANT(target, DH_CHECK_P_NOT_PRIME); #endif #ifdef DH_UNABLE_TO_CHECK_GENERATOR - NODE_DEFINE_CONSTANT(target, DH_UNABLE_TO_CHECK_GENERATOR); + NODE_DEFINE_CONSTANT(target, DH_UNABLE_TO_CHECK_GENERATOR); #endif #ifdef DH_NOT_SUITABLE_GENERATOR - NODE_DEFINE_CONSTANT(target, DH_NOT_SUITABLE_GENERATOR); + NODE_DEFINE_CONSTANT(target, DH_NOT_SUITABLE_GENERATOR); #endif #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation #define ALPN_ENABLED 1 - NODE_DEFINE_CONSTANT(target, ALPN_ENABLED); + NODE_DEFINE_CONSTANT(target, ALPN_ENABLED); #endif #ifdef RSA_PKCS1_PADDING - NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PADDING); + NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PADDING); #endif #ifdef RSA_SSLV23_PADDING - NODE_DEFINE_CONSTANT(target, RSA_SSLV23_PADDING); + NODE_DEFINE_CONSTANT(target, RSA_SSLV23_PADDING); #endif #ifdef RSA_NO_PADDING - NODE_DEFINE_CONSTANT(target, RSA_NO_PADDING); + NODE_DEFINE_CONSTANT(target, RSA_NO_PADDING); #endif #ifdef RSA_PKCS1_OAEP_PADDING - NODE_DEFINE_CONSTANT(target, RSA_PKCS1_OAEP_PADDING); + NODE_DEFINE_CONSTANT(target, RSA_PKCS1_OAEP_PADDING); #endif #ifdef RSA_X931_PADDING - NODE_DEFINE_CONSTANT(target, RSA_X931_PADDING); + NODE_DEFINE_CONSTANT(target, RSA_X931_PADDING); #endif #ifdef RSA_PKCS1_PSS_PADDING - NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PSS_PADDING); + NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PSS_PADDING); #endif #ifdef RSA_PSS_SALTLEN_DIGEST - NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_DIGEST); + NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_DIGEST); #endif #ifdef RSA_PSS_SALTLEN_MAX_SIGN - NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_MAX_SIGN); + NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_MAX_SIGN); #endif #ifdef RSA_PSS_SALTLEN_AUTO - NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_AUTO); + NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_AUTO); #endif #if HAVE_OPENSSL @@ -1086,7 +1085,6 @@ void DefineSystemConstants(Local target) { NODE_DEFINE_CONSTANT(target, O_DSYNC); #endif - #ifdef O_SYMLINK NODE_DEFINE_CONSTANT(target, O_SYMLINK); #endif @@ -1164,35 +1162,32 @@ void DefineSystemConstants(Local target) { #endif #ifdef UV_FS_COPYFILE_EXCL -# define COPYFILE_EXCL UV_FS_COPYFILE_EXCL +#define COPYFILE_EXCL UV_FS_COPYFILE_EXCL NODE_DEFINE_CONSTANT(target, UV_FS_COPYFILE_EXCL); NODE_DEFINE_CONSTANT(target, COPYFILE_EXCL); -# undef COPYFILE_EXCL +#undef COPYFILE_EXCL #endif #ifdef UV_FS_COPYFILE_FICLONE -# define COPYFILE_FICLONE UV_FS_COPYFILE_FICLONE +#define COPYFILE_FICLONE UV_FS_COPYFILE_FICLONE NODE_DEFINE_CONSTANT(target, UV_FS_COPYFILE_FICLONE); NODE_DEFINE_CONSTANT(target, COPYFILE_FICLONE); -# undef COPYFILE_FICLONE +#undef COPYFILE_FICLONE #endif #ifdef UV_FS_COPYFILE_FICLONE_FORCE -# define COPYFILE_FICLONE_FORCE UV_FS_COPYFILE_FICLONE_FORCE +#define COPYFILE_FICLONE_FORCE UV_FS_COPYFILE_FICLONE_FORCE NODE_DEFINE_CONSTANT(target, UV_FS_COPYFILE_FICLONE_FORCE); NODE_DEFINE_CONSTANT(target, COPYFILE_FICLONE_FORCE); -# undef COPYFILE_FICLONE_FORCE +#undef COPYFILE_FICLONE_FORCE #endif } void DefineCryptoConstants(Local target) { #if HAVE_OPENSSL - NODE_DEFINE_STRING_CONSTANT(target, - "defaultCoreCipherList", - DEFAULT_CIPHER_LIST_CORE); - NODE_DEFINE_STRING_CONSTANT(target, - "defaultCipherList", - default_cipher_list); + NODE_DEFINE_STRING_CONSTANT( + target, "defaultCoreCipherList", DEFAULT_CIPHER_LIST_CORE); + NODE_DEFINE_STRING_CONSTANT(target, "defaultCipherList", default_cipher_list); #endif NODE_DEFINE_CONSTANT(target, INT_MAX); } @@ -1317,36 +1312,36 @@ void DefineConstants(v8::Isolate* isolate, Local target) { Environment* env = Environment::GetCurrent(isolate); Local os_constants = Object::New(isolate); - CHECK(os_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(os_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local err_constants = Object::New(isolate); - CHECK(err_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(err_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local sig_constants = Object::New(isolate); - CHECK(sig_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(sig_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local fs_constants = Object::New(isolate); - CHECK(fs_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(fs_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local crypto_constants = Object::New(isolate); - CHECK(crypto_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(crypto_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local zlib_constants = Object::New(isolate); - CHECK(zlib_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(zlib_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local dlopen_constants = Object::New(isolate); - CHECK(dlopen_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(dlopen_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); Local trace_constants = Object::New(isolate); - CHECK(trace_constants->SetPrototype(env->context(), - Null(env->isolate())).FromJust()); + CHECK(trace_constants->SetPrototype(env->context(), Null(env->isolate())) + .FromJust()); DefineErrnoConstants(err_constants); DefineWindowsErrorConstants(err_constants); diff --git a/src/node_constants.h b/src/node_constants.h index 1de420e2def571..9df5dad84a4a8f 100644 --- a/src/node_constants.h +++ b/src/node_constants.h @@ -41,27 +41,28 @@ #define RSA_PSS_SALTLEN_AUTO -2 #endif -#define DEFAULT_CIPHER_LIST_CORE "ECDHE-RSA-AES128-GCM-SHA256:" \ - "ECDHE-ECDSA-AES128-GCM-SHA256:" \ - "ECDHE-RSA-AES256-GCM-SHA384:" \ - "ECDHE-ECDSA-AES256-GCM-SHA384:" \ - "DHE-RSA-AES128-GCM-SHA256:" \ - "ECDHE-RSA-AES128-SHA256:" \ - "DHE-RSA-AES128-SHA256:" \ - "ECDHE-RSA-AES256-SHA384:" \ - "DHE-RSA-AES256-SHA384:" \ - "ECDHE-RSA-AES256-SHA256:" \ - "DHE-RSA-AES256-SHA256:" \ - "HIGH:" \ - "!aNULL:" \ - "!eNULL:" \ - "!EXPORT:" \ - "!DES:" \ - "!RC4:" \ - "!MD5:" \ - "!PSK:" \ - "!SRP:" \ - "!CAMELLIA" +#define DEFAULT_CIPHER_LIST_CORE \ + "ECDHE-RSA-AES128-GCM-SHA256:" \ + "ECDHE-ECDSA-AES128-GCM-SHA256:" \ + "ECDHE-RSA-AES256-GCM-SHA384:" \ + "ECDHE-ECDSA-AES256-GCM-SHA384:" \ + "DHE-RSA-AES128-GCM-SHA256:" \ + "ECDHE-RSA-AES128-SHA256:" \ + "DHE-RSA-AES128-SHA256:" \ + "ECDHE-RSA-AES256-SHA384:" \ + "DHE-RSA-AES256-SHA384:" \ + "ECDHE-RSA-AES256-SHA256:" \ + "DHE-RSA-AES256-SHA256:" \ + "HIGH:" \ + "!aNULL:" \ + "!eNULL:" \ + "!EXPORT:" \ + "!DES:" \ + "!RC4:" \ + "!MD5:" \ + "!PSK:" \ + "!SRP:" \ + "!CAMELLIA" #endif namespace node { diff --git a/src/node_contextify.cc b/src/node_contextify.cc index 74b7c594d5f179..2e2b6998949561 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -19,13 +19,12 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node_errors.h" -#include "node_internals.h" -#include "node_watchdog.h" -#include "base_object-inl.h" #include "node_contextify.h" +#include "base_object-inl.h" #include "node_context_data.h" #include "node_errors.h" +#include "node_internals.h" +#include "node_watchdog.h" namespace node { namespace contextify { @@ -91,25 +90,25 @@ namespace { // Convert an int to a V8 Name (String or Symbol). Local Uint32ToName(Local context, uint32_t index) { - return Uint32::New(context->GetIsolate(), index)->ToString(context) + return Uint32::New(context->GetIsolate(), index) + ->ToString(context) .ToLocalChecked(); } } // anonymous namespace -ContextifyContext::ContextifyContext( - Environment* env, - Local sandbox_obj, const ContextOptions& options) : env_(env) { +ContextifyContext::ContextifyContext(Environment* env, + Local sandbox_obj, + const ContextOptions& options) + : env_(env) { Local v8_context = CreateV8Context(env, sandbox_obj, options); context_.Reset(env->isolate(), v8_context); // Allocation failure or maximum call stack size reached - if (context_.IsEmpty()) - return; + if (context_.IsEmpty()) return; context_.SetWeak(this, WeakCallback, WeakCallbackType::kParameter); } - // This is an object that just keeps an internal pointer to this // ContextifyContext. It's passed to the NamedPropertyHandler. If we // pass the main JavaScript context object we're embedded in, then the @@ -117,9 +116,9 @@ ContextifyContext::ContextifyContext( // from getting gc'd. Local ContextifyContext::CreateDataWrapper(Environment* env) { EscapableHandleScope scope(env->isolate()); - Local wrapper = - env->script_data_constructor_function() - ->NewInstance(env->context()).FromMaybe(Local()); + Local wrapper = env->script_data_constructor_function() + ->NewInstance(env->context()) + .FromMaybe(Local()); if (wrapper.IsEmpty()) return scope.Escape(Local::New(env->isolate(), Local())); @@ -127,7 +126,6 @@ Local ContextifyContext::CreateDataWrapper(Environment* env) { return scope.Escape(wrapper); } - Local ContextifyContext::CreateV8Context( Environment* env, Local sandbox_obj, @@ -138,8 +136,7 @@ Local ContextifyContext::CreateV8Context( function_template->SetClassName(sandbox_obj->GetConstructorName()); - Local object_template = - function_template->InstanceTemplate(); + Local object_template = function_template->InstanceTemplate(); NamedPropertyHandlerConfiguration config(PropertyGetterCallback, PropertySetterCallback, @@ -177,9 +174,8 @@ Local ContextifyContext::CreateV8Context( // directly in an Object, we instead hold onto the new context's global // object instead (which then has a reference to the context). ctx->SetEmbedderData(ContextEmbedderIndex::kSandboxObject, sandbox_obj); - sandbox_obj->SetPrivate(env->context(), - env->contextify_global_private_symbol(), - ctx->Global()); + sandbox_obj->SetPrivate( + env->context(), env->contextify_global_private_symbol(), ctx->Global()); Utf8Value name_val(env->isolate(), options.name); ctx->AllowCodeGenerationFromStrings(options.allow_code_gen_strings->IsTrue()); @@ -198,7 +194,6 @@ Local ContextifyContext::CreateV8Context( return scope.Escape(ctx); } - void ContextifyContext::Init(Environment* env, Local target) { Local function_template = FunctionTemplate::New(env->isolate()); @@ -209,7 +204,6 @@ void ContextifyContext::Init(Environment* env, Local target) { env->SetMethod(target, "isContext", IsContext); } - // makeContext(sandbox, name, origin, strings, wasm); void ContextifyContext::MakeContext(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -219,10 +213,10 @@ void ContextifyContext::MakeContext(const FunctionCallbackInfo& args) { Local sandbox = args[0].As(); // Don't allow contextifying a sandbox multiple times. - CHECK( - !sandbox->HasPrivate( - env->context(), - env->contextify_context_private_symbol()).FromJust()); + CHECK(!sandbox + ->HasPrivate(env->context(), + env->contextify_context_private_symbol()) + .FromJust()); ContextOptions options; @@ -248,29 +242,24 @@ void ContextifyContext::MakeContext(const FunctionCallbackInfo& args) { return; } - if (context->context().IsEmpty()) - return; + if (context->context().IsEmpty()) return; - sandbox->SetPrivate( - env->context(), - env->contextify_context_private_symbol(), - External::New(env->isolate(), context)); + sandbox->SetPrivate(env->context(), + env->contextify_context_private_symbol(), + External::New(env->isolate(), context)); } - void ContextifyContext::IsContext(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsObject()); Local sandbox = args[0].As(); - Maybe result = - sandbox->HasPrivate(env->context(), - env->contextify_context_private_symbol()); + Maybe result = sandbox->HasPrivate( + env->context(), env->contextify_context_private_symbol()); args.GetReturnValue().Set(result.FromJust()); } - void ContextifyContext::WeakCallback( const WeakCallbackInfo& data) { ContextifyContext* context = data.GetParameter(); @@ -279,11 +268,9 @@ void ContextifyContext::WeakCallback( // static ContextifyContext* ContextifyContext::ContextFromContextifiedSandbox( - Environment* env, - const Local& sandbox) { - MaybeLocal maybe_value = - sandbox->GetPrivate(env->context(), - env->contextify_context_private_symbol()); + Environment* env, const Local& sandbox) { + MaybeLocal maybe_value = sandbox->GetPrivate( + env->context(), env->contextify_context_private_symbol()); Local context_external_v; if (maybe_value.ToLocal(&context_external_v) && context_external_v->IsExternal()) { @@ -303,27 +290,22 @@ ContextifyContext* ContextifyContext::Get(const PropertyCallbackInfo& args) { // static void ContextifyContext::PropertyGetterCallback( - Local property, - const PropertyCallbackInfo& args) { + Local property, const PropertyCallbackInfo& args) { ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; Local context = ctx->context(); Local sandbox = ctx->sandbox(); - MaybeLocal maybe_rv = - sandbox->GetRealNamedProperty(context, property); + MaybeLocal maybe_rv = sandbox->GetRealNamedProperty(context, property); if (maybe_rv.IsEmpty()) { - maybe_rv = - ctx->global_proxy()->GetRealNamedProperty(context, property); + maybe_rv = ctx->global_proxy()->GetRealNamedProperty(context, property); } Local rv; if (maybe_rv.ToLocal(&rv)) { - if (rv == sandbox) - rv = ctx->global_proxy(); + if (rv == sandbox) rv = ctx->global_proxy(); args.GetReturnValue().Set(rv); } @@ -337,26 +319,24 @@ void ContextifyContext::PropertySetterCallback( ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; auto attributes = PropertyAttribute::None; - bool is_declared_on_global_proxy = ctx->global_proxy() - ->GetRealNamedPropertyAttributes(ctx->context(), property) - .To(&attributes); - bool read_only = - static_cast(attributes) & - static_cast(PropertyAttribute::ReadOnly); - - bool is_declared_on_sandbox = ctx->sandbox() - ->GetRealNamedPropertyAttributes(ctx->context(), property) - .To(&attributes); - read_only = read_only || - (static_cast(attributes) & - static_cast(PropertyAttribute::ReadOnly)); - - if (read_only) - return; + bool is_declared_on_global_proxy = + ctx->global_proxy() + ->GetRealNamedPropertyAttributes(ctx->context(), property) + .To(&attributes); + bool read_only = static_cast(attributes) & + static_cast(PropertyAttribute::ReadOnly); + + bool is_declared_on_sandbox = + ctx->sandbox() + ->GetRealNamedPropertyAttributes(ctx->context(), property) + .To(&attributes); + read_only = read_only || (static_cast(attributes) & + static_cast(PropertyAttribute::ReadOnly)); + + if (read_only) return; // true for x = 5 // false for this.x = 5 @@ -378,7 +358,7 @@ void ContextifyContext::PropertySetterCallback( !is_function) return; - if (!is_declared_on_global_proxy && is_declared_on_sandbox && + if (!is_declared_on_global_proxy && is_declared_on_sandbox && args.ShouldThrowOnError() && is_contextual_store && !is_function) { // The property exists on the sandbox but not on the global // proxy. Setting it would throw because we are in strict mode. @@ -392,13 +372,11 @@ void ContextifyContext::PropertySetterCallback( // static void ContextifyContext::PropertyDescriptorCallback( - Local property, - const PropertyCallbackInfo& args) { + Local property, const PropertyCallbackInfo& args) { ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; Local context = ctx->context(); @@ -406,8 +384,7 @@ void ContextifyContext::PropertyDescriptorCallback( if (sandbox->HasOwnProperty(context, property).FromMaybe(false)) { args.GetReturnValue().Set( - sandbox->GetOwnPropertyDescriptor(context, property) - .ToLocalChecked()); + sandbox->GetOwnPropertyDescriptor(context, property).ToLocalChecked()); } } @@ -419,40 +396,35 @@ void ContextifyContext::PropertyDefinerCallback( ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; Local context = ctx->context(); Isolate* isolate = context->GetIsolate(); auto attributes = PropertyAttribute::None; bool is_declared = - ctx->global_proxy()->GetRealNamedPropertyAttributes(ctx->context(), - property) + ctx->global_proxy() + ->GetRealNamedPropertyAttributes(ctx->context(), property) .To(&attributes); - bool read_only = - static_cast(attributes) & - static_cast(PropertyAttribute::ReadOnly); + bool read_only = static_cast(attributes) & + static_cast(PropertyAttribute::ReadOnly); // If the property is set on the global as read_only, don't change it on // the global or sandbox. - if (is_declared && read_only) - return; + if (is_declared && read_only) return; Local sandbox = ctx->sandbox(); - auto define_prop_on_sandbox = - [&] (PropertyDescriptor* desc_for_sandbox) { - if (desc.has_enumerable()) { - desc_for_sandbox->set_enumerable(desc.enumerable()); - } - if (desc.has_configurable()) { - desc_for_sandbox->set_configurable(desc.configurable()); - } - // Set the property on the sandbox. - sandbox->DefineProperty(context, property, *desc_for_sandbox) - .FromJust(); - }; + auto define_prop_on_sandbox = [&](PropertyDescriptor* desc_for_sandbox) { + if (desc.has_enumerable()) { + desc_for_sandbox->set_enumerable(desc.enumerable()); + } + if (desc.has_configurable()) { + desc_for_sandbox->set_configurable(desc.configurable()); + } + // Set the property on the sandbox. + sandbox->DefineProperty(context, property, *desc_for_sandbox).FromJust(); + }; if (desc.has_get() || desc.has_set()) { PropertyDescriptor desc_for_sandbox( @@ -476,18 +448,15 @@ void ContextifyContext::PropertyDefinerCallback( // static void ContextifyContext::PropertyDeleterCallback( - Local property, - const PropertyCallbackInfo& args) { + Local property, const PropertyCallbackInfo& args) { ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; Maybe success = ctx->sandbox()->Delete(ctx->context(), property); - if (success.FromMaybe(false)) - return; + if (success.FromMaybe(false)) return; // Delete failed on the sandbox, intercept and do not delete on // the global object. @@ -500,27 +469,23 @@ void ContextifyContext::PropertyEnumeratorCallback( ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; args.GetReturnValue().Set(ctx->sandbox()->GetPropertyNames()); } // static void ContextifyContext::IndexedPropertyGetterCallback( - uint32_t index, - const PropertyCallbackInfo& args) { + uint32_t index, const PropertyCallbackInfo& args) { ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; - ContextifyContext::PropertyGetterCallback( - Uint32ToName(ctx->context(), index), args); + ContextifyContext::PropertyGetterCallback(Uint32ToName(ctx->context(), index), + args); } - void ContextifyContext::IndexedPropertySetterCallback( uint32_t index, Local value, @@ -528,8 +493,7 @@ void ContextifyContext::IndexedPropertySetterCallback( ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; ContextifyContext::PropertySetterCallback( Uint32ToName(ctx->context(), index), value, args); @@ -537,19 +501,16 @@ void ContextifyContext::IndexedPropertySetterCallback( // static void ContextifyContext::IndexedPropertyDescriptorCallback( - uint32_t index, - const PropertyCallbackInfo& args) { + uint32_t index, const PropertyCallbackInfo& args) { ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; ContextifyContext::PropertyDescriptorCallback( Uint32ToName(ctx->context(), index), args); } - void ContextifyContext::IndexedPropertyDefinerCallback( uint32_t index, const PropertyDescriptor& desc, @@ -557,8 +518,7 @@ void ContextifyContext::IndexedPropertyDefinerCallback( ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; ContextifyContext::PropertyDefinerCallback( Uint32ToName(ctx->context(), index), desc, args); @@ -566,18 +526,15 @@ void ContextifyContext::IndexedPropertyDefinerCallback( // static void ContextifyContext::IndexedPropertyDeleterCallback( - uint32_t index, - const PropertyCallbackInfo& args) { + uint32_t index, const PropertyCallbackInfo& args) { ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing - if (ctx->context_.IsEmpty()) - return; + if (ctx->context_.IsEmpty()) return; Maybe success = ctx->sandbox()->Delete(ctx->context(), index); - if (success.FromMaybe(false)) - return; + if (success.FromMaybe(false)) return; // Delete failed on the sandbox, intercept and do not delete on // the global object. @@ -610,18 +567,17 @@ class ContextifyScript : public BaseObject { target->Set(class_name, script_tmpl->GetFunction()); env->set_script_context_constructor_template(script_tmpl); - Local parsing_context_symbol = - Symbol::New(env->isolate(), - FIXED_ONE_BYTE_STRING(env->isolate(), - "script parsing context")); + Local parsing_context_symbol = Symbol::New( + env->isolate(), + FIXED_ONE_BYTE_STRING(env->isolate(), "script parsing context")); env->set_vm_parsing_context_symbol(parsing_context_symbol); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kParsingContext"), - parsing_context_symbol) + target + ->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "kParsingContext"), + parsing_context_symbol) .FromJust(); } - static void New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); @@ -677,11 +633,11 @@ class ContextifyScript : public BaseObject { if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( TRACING_CATEGORY_NODE2(vm, script)) != 0) { Utf8Value fn(isolate, filename); - TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( - TRACING_CATEGORY_NODE2(vm, script), - "ContextifyScript::New", - contextify_script, - "filename", TRACE_STR_COPY(*fn)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE2(vm, script), + "ContextifyScript::New", + contextify_script, + "filename", + TRACE_STR_COPY(*fn)); } ScriptCompiler::CachedData* cached_data = nullptr; @@ -704,55 +660,47 @@ class ContextifyScript : public BaseObject { Environment::ShouldNotAbortOnUncaughtScope no_abort_scope(env); Context::Scope scope(parsing_context); - MaybeLocal v8_script = ScriptCompiler::CompileUnboundScript( - isolate, - &source, - compile_options); + MaybeLocal v8_script = + ScriptCompiler::CompileUnboundScript(isolate, &source, compile_options); if (v8_script.IsEmpty()) { DecorateErrorStack(env, try_catch); no_abort_scope.Close(); try_catch.ReThrow(); - TRACE_EVENT_NESTABLE_ASYNC_END0( - TRACING_CATEGORY_NODE2(vm, script), - "ContextifyScript::New", - contextify_script); + TRACE_EVENT_NESTABLE_ASYNC_END0(TRACING_CATEGORY_NODE2(vm, script), + "ContextifyScript::New", + contextify_script); return; } contextify_script->script_.Reset(isolate, v8_script.ToLocalChecked()); if (compile_options == ScriptCompiler::kConsumeCodeCache) { - args.This()->Set( - env->cached_data_rejected_string(), - Boolean::New(isolate, source.GetCachedData()->rejected)); + args.This()->Set(env->cached_data_rejected_string(), + Boolean::New(isolate, source.GetCachedData()->rejected)); } else if (produce_cached_data) { const ScriptCompiler::CachedData* cached_data = - ScriptCompiler::CreateCodeCache(v8_script.ToLocalChecked()); + ScriptCompiler::CreateCodeCache(v8_script.ToLocalChecked()); bool cached_data_produced = cached_data != nullptr; if (cached_data_produced) { - MaybeLocal buf = Buffer::Copy( - env, - reinterpret_cast(cached_data->data), - cached_data->length); + MaybeLocal buf = + Buffer::Copy(env, + reinterpret_cast(cached_data->data), + cached_data->length); args.This()->Set(env->cached_data_string(), buf.ToLocalChecked()); } - args.This()->Set( - env->cached_data_produced_string(), - Boolean::New(isolate, cached_data_produced)); + args.This()->Set(env->cached_data_produced_string(), + Boolean::New(isolate, cached_data_produced)); } - TRACE_EVENT_NESTABLE_ASYNC_END0( - TRACING_CATEGORY_NODE2(vm, script), - "ContextifyScript::New", - contextify_script); + TRACE_EVENT_NESTABLE_ASYNC_END0(TRACING_CATEGORY_NODE2(vm, script), + "ContextifyScript::New", + contextify_script); } - static bool InstanceOf(Environment* env, const Local& value) { return !value.IsEmpty() && env->script_context_constructor_template()->HasInstance(value); } - static void CreateCachedData(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); ContextifyScript* wrapped_script; @@ -764,15 +712,14 @@ class ContextifyScript : public BaseObject { if (!cached_data) { args.GetReturnValue().Set(Buffer::New(env, 0).ToLocalChecked()); } else { - MaybeLocal buf = Buffer::Copy( - env, - reinterpret_cast(cached_data->data), - cached_data->length); + MaybeLocal buf = + Buffer::Copy(env, + reinterpret_cast(cached_data->data), + cached_data->length); args.GetReturnValue().Set(buf.ToLocalChecked()); } } - static void RunInThisContext(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -815,8 +762,7 @@ class ContextifyScript : public BaseObject { ContextifyContext::ContextFromContextifiedSandbox(env, sandbox); CHECK_NOT_NULL(contextify_context); - if (contextify_context->context().IsEmpty()) - return; + if (contextify_context->context().IsEmpty()) return; TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( TRACING_CATEGORY_NODE2(vm, script), "RunInContext", wrapped_script); @@ -845,20 +791,16 @@ class ContextifyScript : public BaseObject { static void DecorateErrorStack(Environment* env, const TryCatch& try_catch) { Local exception = try_catch.Exception(); - if (!exception->IsObject()) - return; + if (!exception->IsObject()) return; Local err_obj = exception.As(); - if (IsExceptionDecorated(env, err_obj)) - return; + if (IsExceptionDecorated(env, err_obj)) return; AppendExceptionLine(env, exception, try_catch.Message(), CONTEXTIFY_ERROR); Local stack = err_obj->Get(env->stack_string()); - MaybeLocal maybe_value = - err_obj->GetPrivate( - env->context(), - env->arrow_message_private_symbol()); + MaybeLocal maybe_value = err_obj->GetPrivate( + env->context(), env->arrow_message_private_symbol()); Local arrow; if (!(maybe_value.ToLocal(&arrow) && arrow->IsString())) { @@ -871,13 +813,11 @@ class ContextifyScript : public BaseObject { Local decorated_stack = String::Concat( String::Concat(arrow.As(), - FIXED_ONE_BYTE_STRING(env->isolate(), "\n")), + FIXED_ONE_BYTE_STRING(env->isolate(), "\n")), stack.As()); err_obj->Set(env->stack_string(), decorated_stack); err_obj->SetPrivate( - env->context(), - env->decorated_private_symbol(), - True(env->isolate())); + env->context(), env->decorated_private_symbol(), True(env->isolate())); } static bool EvalMachine(Environment* env, @@ -885,8 +825,7 @@ class ContextifyScript : public BaseObject { const bool display_errors, const bool break_on_sigint, const FunctionCallbackInfo& args) { - if (!env->can_call_into_js()) - return false; + if (!env->can_call_into_js()) return false; if (!ContextifyScript::InstanceOf(env, args.Holder())) { env->ThrowTypeError( "Script methods can only be called on script instances."); @@ -949,14 +888,12 @@ class ContextifyScript : public BaseObject { return true; } - ContextifyScript(Environment* env, Local object) : BaseObject(env, object) { MakeWeak(); } }; - void Initialize(Local target, Local unused, Local context) { diff --git a/src/node_contextify.h b/src/node_contextify.h index 3d94fbc5c47947..e805588240e581 100644 --- a/src/node_contextify.h +++ b/src/node_contextify.h @@ -1,8 +1,8 @@ #ifndef SRC_NODE_CONTEXTIFY_H_ #define SRC_NODE_CONTEXTIFY_H_ -#include "node_internals.h" #include "node_context_data.h" +#include "node_internals.h" namespace node { namespace contextify { @@ -22,19 +22,17 @@ class ContextifyContext { v8::Local CreateDataWrapper(Environment* env); v8::Local CreateV8Context(Environment* env, - v8::Local sandbox_obj, const ContextOptions& options); + v8::Local sandbox_obj, + const ContextOptions& options); static void Init(Environment* env, v8::Local target); - static bool AllowWasmCodeGeneration( - v8::Local context, v8::Local); + static bool AllowWasmCodeGeneration(v8::Local context, + v8::Local); static ContextifyContext* ContextFromContextifiedSandbox( - Environment* env, - const v8::Local& sandbox); + Environment* env, const v8::Local& sandbox); - inline Environment* env() const { - return env_; - } + inline Environment* env() const { return env_; } inline v8::Local context() const { return PersistentToLocal(env()->isolate(), context_); @@ -49,15 +47,13 @@ class ContextifyContext { context()->GetEmbedderData(ContextEmbedderIndex::kSandboxObject)); } - template static ContextifyContext* Get(const v8::PropertyCallbackInfo& args); private: static void MakeContext(const v8::FunctionCallbackInfo& args); static void IsContext(const v8::FunctionCallbackInfo& args); - static void WeakCallback( - const v8::WeakCallbackInfo& data); + static void WeakCallback(const v8::WeakCallbackInfo& data); static void PropertyGetterCallback( v8::Local property, const v8::PropertyCallbackInfo& args); @@ -78,22 +74,19 @@ class ContextifyContext { static void PropertyEnumeratorCallback( const v8::PropertyCallbackInfo& args); static void IndexedPropertyGetterCallback( - uint32_t index, - const v8::PropertyCallbackInfo& args); + uint32_t index, const v8::PropertyCallbackInfo& args); static void IndexedPropertySetterCallback( uint32_t index, v8::Local value, const v8::PropertyCallbackInfo& args); static void IndexedPropertyDescriptorCallback( - uint32_t index, - const v8::PropertyCallbackInfo& args); + uint32_t index, const v8::PropertyCallbackInfo& args); static void IndexedPropertyDefinerCallback( uint32_t index, const v8::PropertyDescriptor& desc, const v8::PropertyCallbackInfo& args); static void IndexedPropertyDeleterCallback( - uint32_t index, - const v8::PropertyCallbackInfo& args); + uint32_t index, const v8::PropertyCallbackInfo& args); Environment* const env_; Persistent context_; }; diff --git a/src/node_counters.cc b/src/node_counters.cc index 99b3b8fd8ba1ac..36d1557da0d95c 100644 --- a/src/node_counters.cc +++ b/src/node_counters.cc @@ -20,13 +20,12 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_counters.h" +#include "env-inl.h" #include "node_internals.h" #include "uv.h" -#include "env-inl.h" #include - namespace node { using v8::FunctionCallbackInfo; @@ -43,44 +42,36 @@ using v8::Value; static uint64_t counter_gc_start_time; static uint64_t counter_gc_end_time; - void COUNTER_NET_SERVER_CONNECTION(const FunctionCallbackInfo&) { NODE_COUNT_SERVER_CONN_OPEN(); } - void COUNTER_NET_SERVER_CONNECTION_CLOSE(const FunctionCallbackInfo&) { NODE_COUNT_SERVER_CONN_CLOSE(); } - void COUNTER_HTTP_SERVER_REQUEST(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_SERVER_REQUEST(); } - void COUNTER_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_SERVER_RESPONSE(); } - void COUNTER_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_CLIENT_REQUEST(); } - void COUNTER_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_CLIENT_RESPONSE(); } - static void counter_gc_start(Isolate* isolate, GCType type, GCCallbackFlags flags) { counter_gc_start_time = NODE_COUNT_GET_GC_RAWTIME(); } - static void counter_gc_done(Isolate* isolate, GCType type, GCCallbackFlags flags) { @@ -90,8 +81,8 @@ static void counter_gc_done(Isolate* isolate, uint64_t gcperiod = endgc - counter_gc_start_time; if (totalperiod > 0) { - unsigned int percent = static_cast( - (gcperiod * 100) / totalperiod); + unsigned int percent = + static_cast((gcperiod * 100) / totalperiod); NODE_COUNT_GC_PERCENTTIME(percent); counter_gc_end_time = endgc; @@ -99,7 +90,6 @@ static void counter_gc_done(Isolate* isolate, } } - void InitPerfCounters(Environment* env, Local target) { HandleScope scope(env->isolate()); @@ -108,12 +98,12 @@ void InitPerfCounters(Environment* env, Local target) { void (*func)(const FunctionCallbackInfo&); } tab[] = { #define NODE_PROBE(name) #name, name - { NODE_PROBE(COUNTER_NET_SERVER_CONNECTION) }, - { NODE_PROBE(COUNTER_NET_SERVER_CONNECTION_CLOSE) }, - { NODE_PROBE(COUNTER_HTTP_SERVER_REQUEST) }, - { NODE_PROBE(COUNTER_HTTP_SERVER_RESPONSE) }, - { NODE_PROBE(COUNTER_HTTP_CLIENT_REQUEST) }, - { NODE_PROBE(COUNTER_HTTP_CLIENT_RESPONSE) } + {NODE_PROBE(COUNTER_NET_SERVER_CONNECTION)}, + {NODE_PROBE(COUNTER_NET_SERVER_CONNECTION_CLOSE)}, + {NODE_PROBE(COUNTER_HTTP_SERVER_REQUEST)}, + {NODE_PROBE(COUNTER_HTTP_SERVER_RESPONSE)}, + {NODE_PROBE(COUNTER_HTTP_CLIENT_REQUEST)}, + {NODE_PROBE(COUNTER_HTTP_CLIENT_RESPONSE)} #undef NODE_PROBE }; @@ -135,7 +125,6 @@ void InitPerfCounters(Environment* env, Local target) { env->isolate()->AddGCEpilogueCallback(counter_gc_done); } - void TermPerfCounters(Local target) { // Only Windows performance counters supported // To enable other OS, use conditional compilation here diff --git a/src/node_counters.h b/src/node_counters.h index c8a1a88f0b25e0..339989b5588d64 100644 --- a/src/node_counters.h +++ b/src/node_counters.h @@ -30,22 +30,46 @@ #include "node_win32_perfctr_provider.h" #else #define NODE_COUNTER_ENABLED() (false) -#define NODE_COUNT_GC_PERCENTTIME(percent) do { } while (false) -#define NODE_COUNT_GET_GC_RAWTIME() do { } while (false) -#define NODE_COUNT_HTTP_CLIENT_REQUEST() do { } while (false) -#define NODE_COUNT_HTTP_CLIENT_RESPONSE() do { } while (false) -#define NODE_COUNT_HTTP_SERVER_REQUEST() do { } while (false) -#define NODE_COUNT_HTTP_SERVER_RESPONSE() do { } while (false) -#define NODE_COUNT_NET_BYTES_RECV(bytes) do { } while (false) -#define NODE_COUNT_NET_BYTES_SENT(bytes) do { } while (false) -#define NODE_COUNT_PIPE_BYTES_RECV(bytes) do { } while (false) -#define NODE_COUNT_PIPE_BYTES_SENT(bytes) do { } while (false) -#define NODE_COUNT_SERVER_CONN_CLOSE() do { } while (false) -#define NODE_COUNT_SERVER_CONN_OPEN() do { } while (false) +#define NODE_COUNT_GC_PERCENTTIME(percent) \ + do { \ + } while (false) +#define NODE_COUNT_GET_GC_RAWTIME() \ + do { \ + } while (false) +#define NODE_COUNT_HTTP_CLIENT_REQUEST() \ + do { \ + } while (false) +#define NODE_COUNT_HTTP_CLIENT_RESPONSE() \ + do { \ + } while (false) +#define NODE_COUNT_HTTP_SERVER_REQUEST() \ + do { \ + } while (false) +#define NODE_COUNT_HTTP_SERVER_RESPONSE() \ + do { \ + } while (false) +#define NODE_COUNT_NET_BYTES_RECV(bytes) \ + do { \ + } while (false) +#define NODE_COUNT_NET_BYTES_SENT(bytes) \ + do { \ + } while (false) +#define NODE_COUNT_PIPE_BYTES_RECV(bytes) \ + do { \ + } while (false) +#define NODE_COUNT_PIPE_BYTES_SENT(bytes) \ + do { \ + } while (false) +#define NODE_COUNT_SERVER_CONN_CLOSE() \ + do { \ + } while (false) +#define NODE_COUNT_SERVER_CONN_OPEN() \ + do { \ + } while (false) #endif -#include "v8.h" #include "env.h" +#include "v8.h" namespace node { diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 1237157da3f775..f2ead01c88ad12 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -19,16 +19,16 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +#include "node_crypto.h" #include "node.h" #include "node_buffer.h" -#include "node_errors.h" #include "node_constants.h" -#include "node_crypto.h" #include "node_crypto_bio.h" -#include "node_crypto_groups.h" #include "node_crypto_clienthello-inl.h" -#include "node_mutex.h" +#include "node_crypto_groups.h" +#include "node_errors.h" #include "node_internals.h" +#include "node_mutex.h" #include "tls_wrap.h" // TLSWrap #include "async_wrap-inl.h" @@ -45,17 +45,16 @@ #include #include -static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----"; +static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----"; static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1; -static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----"; +static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----"; static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1; -static const char CERTIFICATE_PFX[] = "-----BEGIN CERTIFICATE-----"; +static const char CERTIFICATE_PFX[] = "-----BEGIN CERTIFICATE-----"; static const int CERTIFICATE_PFX_LEN = sizeof(CERTIFICATE_PFX) - 1; -static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL - | ASN1_STRFLGS_UTF8_CONVERT - | XN_FLAG_SEP_MULTILINE - | XN_FLAG_FN_SN; +static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL | + ASN1_STRFLGS_UTF8_CONVERT | + XN_FLAG_SEP_MULTILINE | XN_FLAG_FN_SN; namespace node { namespace crypto { @@ -90,14 +89,13 @@ using v8::String; using v8::Uint32; using v8::Value; - struct StackOfX509Deleter { - void operator()(STACK_OF(X509)* p) const { sk_X509_pop_free(p, X509_free); } + void operator()(STACK_OF(X509) * p) const { sk_X509_pop_free(p, X509_free); } }; using StackOfX509 = std::unique_ptr; struct StackOfXASN1Deleter { - void operator()(STACK_OF(ASN1_OBJECT)* p) const { + void operator()(STACK_OF(ASN1_OBJECT) * p) const { sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free); } }; @@ -126,27 +124,20 @@ template void SSLWrap::ConfigureSecureContext(SecureContext* sc); template void SSLWrap::SetSNIContext(SecureContext* sc); template int SSLWrap::SetCACerts(SecureContext* sc); template SSL_SESSION* SSLWrap::GetSessionCallback( - SSL* s, - const unsigned char* key, - int len, - int* copy); -template int SSLWrap::NewSessionCallback(SSL* s, - SSL_SESSION* sess); + SSL* s, const unsigned char* key, int len, int* copy); +template int SSLWrap::NewSessionCallback(SSL* s, SSL_SESSION* sess); template void SSLWrap::OnClientHello( - void* arg, - const ClientHelloParser::ClientHello& hello); + void* arg, const ClientHelloParser::ClientHello& hello); template int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg); template void SSLWrap::DestroySSL(); template int SSLWrap::SSLCertCallback(SSL* s, void* arg); template void SSLWrap::WaitForCertCb(CertCb cb, void* arg); -template int SSLWrap::SelectALPNCallback( - SSL* s, - const unsigned char** out, - unsigned char* outlen, - const unsigned char* in, - unsigned int inlen, - void* arg); - +template int SSLWrap::SelectALPNCallback(SSL* s, + const unsigned char** out, + unsigned char* outlen, + const unsigned char* in, + unsigned int inlen, + void* arg); static int PasswordCallback(char* buf, int size, int rwflag, void* u) { if (u) { @@ -187,8 +178,8 @@ static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) { if (err != 0) { ERR_error_string_n(err, *errmsg, sizeof(*errmsg)); } else { - snprintf(*errmsg, sizeof(*errmsg), - "Engine \"%s\" was not found", engine_id); + snprintf( + *errmsg, sizeof(*errmsg), "Engine \"%s\" was not found", engine_id); } } @@ -205,7 +196,6 @@ static int NoPasswordCallback(char* buf, int size, int rwflag, void* u) { return 0; } - struct CryptoErrorVector : public std::vector { inline void Capture() { clear(); @@ -225,10 +215,11 @@ struct CryptoErrorVector : public std::vector { if (copy.empty()) copy.push_back("no error"); // But possibly a bug... // Use last element as the error message, everything else goes // into the .opensslErrorStack property on the exception object. - auto exception_string = - String::NewFromUtf8(env->isolate(), copy.back().data(), - NewStringType::kNormal, copy.back().size()) - .ToLocalChecked(); + auto exception_string = String::NewFromUtf8(env->isolate(), + copy.back().data(), + NewStringType::kNormal, + copy.back().size()) + .ToLocalChecked(); copy.pop_back(); return copy.ToException(env, exception_string); } @@ -242,24 +233,24 @@ struct CryptoErrorVector : public std::vector { for (const std::string& string : *this) { const size_t index = &string - &front(); - Local value = - String::NewFromUtf8(env->isolate(), string.data(), - NewStringType::kNormal, string.size()) - .ToLocalChecked(); + Local value = String::NewFromUtf8(env->isolate(), + string.data(), + NewStringType::kNormal, + string.size()) + .ToLocalChecked(); array->Set(env->context(), index, value).FromJust(); } CHECK(exception_v->IsObject()); Local exception = exception_v.As(); - exception->Set(env->context(), - env->openssl_error_stack(), array).FromJust(); + exception->Set(env->context(), env->openssl_error_stack(), array) + .FromJust(); } return exception_v; } }; - void ThrowCryptoError(Environment* env, unsigned long err, // NOLINT(runtime/int) const char* message = nullptr) { @@ -271,14 +262,13 @@ void ThrowCryptoError(Environment* env, HandleScope scope(env->isolate()); auto exception_string = String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal) - .ToLocalChecked(); + .ToLocalChecked(); CryptoErrorVector errors; errors.Capture(); auto exception = errors.ToException(env, exception_string); env->isolate()->ThrowException(exception); } - // Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG. // The entropy pool starts out empty and needs to fill up before the PRNG // can be used securely. Once the pool is filled, it never dries up again; @@ -303,16 +293,13 @@ inline void CheckEntropy() { for (;;) { int status = RAND_status(); CHECK_GE(status, 0); // Cannot fail. - if (status != 0) - break; + if (status != 0) break; // Give up, RAND_poll() not supported. - if (RAND_poll() == 0) - break; + if (RAND_poll() == 0) break; } } - bool EntropySource(unsigned char* buffer, size_t length) { // Ensure that OpenSSL's PRNG is properly seeded. CheckEntropy(); @@ -322,7 +309,6 @@ bool EntropySource(unsigned char* buffer, size_t length) { return RAND_bytes(buffer, length) != -1; } - void SecureContext::Initialize(Environment* env, Local target) { Local t = env->NewFunctionTemplate(New); t->InstanceTemplate()->SetInternalFieldCount(1); @@ -369,13 +355,11 @@ void SecureContext::Initialize(Environment* env, Local target) { env->set_secure_context_constructor_template(t); } - void SecureContext::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); new SecureContext(env, args.This()); } - void SecureContext::Init(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); @@ -464,8 +448,8 @@ void SecureContext::Init(const FunctionCallbackInfo& args) { // SSL session cache configuration SSL_CTX_set_session_cache_mode(sc->ctx_.get(), SSL_SESS_CACHE_SERVER | - SSL_SESS_CACHE_NO_INTERNAL | - SSL_SESS_CACHE_NO_AUTO_CLEAR); + SSL_SESS_CACHE_NO_INTERNAL | + SSL_SESS_CACHE_NO_AUTO_CLEAR); SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version); SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version); @@ -480,7 +464,6 @@ void SecureContext::Init(const FunctionCallbackInfo& args) { SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback); } - // Takes a string or buffer and loads it into a BIO. // Caller responsible for BIO_free_all-ing the returned object. static BIO* LoadBIO(Environment* env, Local v) { @@ -498,7 +481,6 @@ static BIO* LoadBIO(Environment* env, Local v) { return nullptr; } - void SecureContext::SetKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -522,16 +504,12 @@ void SecureContext::SetKey(const FunctionCallbackInfo& args) { } BIOPointer bio(LoadBIO(env, args[0])); - if (!bio) - return; + if (!bio) return; node::Utf8Value passphrase(env->isolate(), args[1]); - EVPKeyPointer key( - PEM_read_bio_PrivateKey(bio.get(), - nullptr, - PasswordCallback, - len == 1 ? nullptr : *passphrase)); + EVPKeyPointer key(PEM_read_bio_PrivateKey( + bio.get(), nullptr, PasswordCallback, len == 1 ? nullptr : *passphrase)); if (!key) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) @@ -545,13 +523,11 @@ void SecureContext::SetKey(const FunctionCallbackInfo& args) { if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) - return env->ThrowError("SSL_CTX_use_PrivateKey"); + if (!err) return env->ThrowError("SSL_CTX_use_PrivateKey"); return ThrowCryptoError(env, err); } } - int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) { X509_STORE* store = SSL_CTX_get_cert_store(ctx); DeleteFnPtr store_ctx( @@ -561,10 +537,9 @@ int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) { X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1; } - int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, X509Pointer&& x, - STACK_OF(X509)* extra_certs, + STACK_OF(X509) * extra_certs, X509Pointer* cert, X509Pointer* issuer_) { CHECK(!*issuer_); @@ -621,18 +596,16 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, } } - end: +end: issuer_->reset(issuer); if (ret && x != nullptr) { cert->reset(X509_dup(x.get())); - if (!*cert) - ret = 0; + if (!*cert) ret = 0; } return ret; } - // Read a file that contains our certificate in "PEM" format, // possibly followed by a sequence of CA certificates that should be // sent to the peer in the Certificate message. @@ -649,8 +622,7 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, X509Pointer x( PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr)); - if (!x) - return 0; + if (!x) return 0; // TODO(addaleax): Turn this into smart pointer as well. X509* extra = nullptr; @@ -658,15 +630,11 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, unsigned long err = 0; // NOLINT(runtime/int) StackOfX509 extra_certs(sk_X509_new_null()); - if (!extra_certs) - goto done; + if (!extra_certs) goto done; - while ((extra = PEM_read_bio_X509(in.get(), - nullptr, - NoPasswordCallback, - nullptr))) { - if (sk_X509_push(extra_certs.get(), extra)) - continue; + while ((extra = PEM_read_bio_X509( + in.get(), nullptr, NoPasswordCallback, nullptr))) { + if (sk_X509_push(extra_certs.get(), extra)) continue; // Failure, free all certs goto done; @@ -678,27 +646,21 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) { ERR_clear_error(); - } else { + } else { // some real error goto done; } - ret = SSL_CTX_use_certificate_chain(ctx, - std::move(x), - extra_certs.get(), - cert, - issuer); - if (!ret) - goto done; + ret = SSL_CTX_use_certificate_chain( + ctx, std::move(x), extra_certs.get(), cert, issuer); + if (!ret) goto done; - done: - if (extra != nullptr) - X509_free(extra); +done: + if (extra != nullptr) X509_free(extra); return ret; } - void SecureContext::SetCert(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -710,16 +672,13 @@ void SecureContext::SetCert(const FunctionCallbackInfo& args) { } BIOPointer bio(LoadBIO(env, args[0])); - if (!bio) - return; + if (!bio) return; sc->cert_.reset(); sc->issuer_.reset(); - int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(), - std::move(bio), - &sc->cert_, - &sc->issuer_); + int rv = SSL_CTX_use_certificate_chain( + sc->ctx_.get(), std::move(bio), &sc->cert_, &sc->issuer_); if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) @@ -730,7 +689,6 @@ void SecureContext::SetCert(const FunctionCallbackInfo& args) { } } - static X509_STORE* NewRootCertStore() { static std::vector root_certs_vector; static Mutex root_certs_vector_mutex; @@ -765,7 +723,6 @@ static X509_STORE* NewRootCertStore() { return store; } - void SecureContext::AddCACert(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -778,12 +735,11 @@ void SecureContext::AddCACert(const FunctionCallbackInfo& args) { } BIOPointer bio(LoadBIO(env, args[0])); - if (!bio) - return; + if (!bio) return; X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get()); while (X509* x509 = PEM_read_bio_X509( - bio.get(), nullptr, NoPasswordCallback, nullptr)) { + bio.get(), nullptr, NoPasswordCallback, nullptr)) { if (cert_store == root_cert_store) { cert_store = NewRootCertStore(); SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store); @@ -794,7 +750,6 @@ void SecureContext::AddCACert(const FunctionCallbackInfo& args) { } } - void SecureContext::AddCRL(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -808,14 +763,12 @@ void SecureContext::AddCRL(const FunctionCallbackInfo& args) { ClearErrorOnReturn clear_error_on_return; BIOPointer bio(LoadBIO(env, args[0])); - if (!bio) - return; + if (!bio) return; DeleteFnPtr crl( PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr)); - if (!crl) - return env->ThrowError("Failed to parse CRL"); + if (!crl) return env->ThrowError("Failed to parse CRL"); X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get()); if (cert_store == root_cert_store) { @@ -828,12 +781,10 @@ void SecureContext::AddCRL(const FunctionCallbackInfo& args) { X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); } - void UseExtraCaCerts(const std::string& file) { extra_root_certs_file = file; } - static unsigned long AddCertsFromFile( // NOLINT(runtime/int) X509_STORE* store, const char* file) { @@ -841,11 +792,10 @@ static unsigned long AddCertsFromFile( // NOLINT(runtime/int) MarkPopErrorOnReturn mark_pop_error_on_return; BIOPointer bio(BIO_new_file(file, "r")); - if (!bio) - return ERR_get_error(); + if (!bio) return ERR_get_error(); - while (X509* x509 = - PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) { + while (X509* x509 = PEM_read_bio_X509( + bio.get(), nullptr, NoPasswordCallback, nullptr)) { X509_STORE_add_cert(store, x509); X509_free(x509); } @@ -870,8 +820,8 @@ void SecureContext::AddRootCerts(const FunctionCallbackInfo& args) { if (!extra_root_certs_file.empty()) { unsigned long err = AddCertsFromFile( // NOLINT(runtime/int) - root_cert_store, - extra_root_certs_file.c_str()); + root_cert_store, + extra_root_certs_file.c_str()); if (err) { // We do not call back into JS after this line anyway, so ignoring // the return value of ProcessEmitWarning does not affect how a @@ -890,7 +840,6 @@ void SecureContext::AddRootCerts(const FunctionCallbackInfo& args) { SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store); } - void SecureContext::SetCiphers(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); @@ -913,7 +862,6 @@ void SecureContext::SetCiphers(const FunctionCallbackInfo& args) { } } - void SecureContext::SetECDHCurve(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); @@ -926,14 +874,12 @@ void SecureContext::SetECDHCurve(const FunctionCallbackInfo& args) { node::Utf8Value curve(env->isolate(), args[0]); - if (strcmp(*curve, "auto") == 0) - return; + if (strcmp(*curve, "auto") == 0) return; if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve)) return env->ThrowError("Failed to set ECDH curve"); } - void SecureContext::SetDHParam(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.This()); @@ -948,22 +894,20 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo& args) { DHPointer dh; { BIOPointer bio(LoadBIO(env, args[0])); - if (!bio) - return; + if (!bio) return; dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr)); } // Invalid dhparam is silently discarded and DHE is no longer used. - if (!dh) - return; + if (!dh) return; const BIGNUM* p; DH_get0_pqg(dh.get(), &p, nullptr, nullptr); const int size = BN_num_bits(p); if (size < 1024) { - return THROW_ERR_INVALID_ARG_VALUE( - env, "DH parameter is less than 1024 bits"); + return THROW_ERR_INVALID_ARG_VALUE(env, + "DH parameter is less than 1024 bits"); } else if (size < 2048) { args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING( env->isolate(), "DH parameter is less than 2048 bits")); @@ -972,18 +916,16 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo& args) { SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE); int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get()); - if (!r) - return env->ThrowTypeError("Error setting temp DH parameter"); + if (!r) return env->ThrowTypeError("Error setting temp DH parameter"); } - void SecureContext::SetOptions(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); if (args.Length() != 1 || !args[0]->IntegerValue()) { - return THROW_ERR_INVALID_ARG_TYPE( - sc->env(), "Options must be an integer value"); + return THROW_ERR_INVALID_ARG_TYPE(sc->env(), + "Options must be an integer value"); } SSL_CTX_set_options( @@ -991,7 +933,6 @@ void SecureContext::SetOptions(const FunctionCallbackInfo& args) { static_cast(args[0]->IntegerValue())); // NOLINT(runtime/int) } - void SecureContext::SetSessionIdContext( const FunctionCallbackInfo& args) { SecureContext* sc; @@ -999,8 +940,8 @@ void SecureContext::SetSessionIdContext( Environment* env = sc->env(); if (args.Length() != 1) { - return THROW_ERR_MISSING_ARGS( - env, "Session ID context argument is mandatory"); + return THROW_ERR_MISSING_ARGS(env, + "Session ID context argument is mandatory"); } THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context"); @@ -1011,8 +952,7 @@ void SecureContext::SetSessionIdContext( unsigned int sid_ctx_len = sessionIdContext.length(); int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len); - if (r == 1) - return; + if (r == 1) return; BUF_MEM* mem; Local message; @@ -1030,7 +970,6 @@ void SecureContext::SetSessionIdContext( args.GetIsolate()->ThrowException(Exception::TypeError(message)); } - void SecureContext::SetSessionTimeout(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); @@ -1044,14 +983,12 @@ void SecureContext::SetSessionTimeout(const FunctionCallbackInfo& args) { SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout); } - void SecureContext::Close(const FunctionCallbackInfo& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); sc->Reset(); } - // Takes .pfx or .p12 and password in string or buffer format void SecureContext::LoadPKCS12(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1068,8 +1005,7 @@ void SecureContext::LoadPKCS12(const FunctionCallbackInfo& args) { } BIOPointer in(LoadBIO(env, args[0])); - if (!in) - return env->ThrowError("Unable to load BIO"); + if (!in) return env->ThrowError("Unable to load BIO"); if (args.Length() >= 2) { THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase"); @@ -1096,12 +1032,12 @@ void SecureContext::LoadPKCS12(const FunctionCallbackInfo& args) { STACK_OF(X509)* extra_certs_ptr = nullptr; if (d2i_PKCS12_bio(in.get(), &p12_ptr) && (p12.reset(p12_ptr), true) && // Move ownership to the smart pointer. - PKCS12_parse(p12.get(), pass.data(), - &pkey_ptr, - &cert_ptr, - &extra_certs_ptr) && - (pkey.reset(pkey_ptr), cert.reset(cert_ptr), - extra_certs.reset(extra_certs_ptr), true) && // Move ownership. + PKCS12_parse( + p12.get(), pass.data(), &pkey_ptr, &cert_ptr, &extra_certs_ptr) && + (pkey.reset(pkey_ptr), + cert.reset(cert_ptr), + extra_certs.reset(extra_certs_ptr), + true) && // Move ownership. SSL_CTX_use_certificate_chain(sc->ctx_.get(), std::move(cert), extra_certs.get(), @@ -1129,10 +1065,11 @@ void SecureContext::LoadPKCS12(const FunctionCallbackInfo& args) { } } - #ifndef OPENSSL_NO_ENGINE // Helper for the smart pointer. -void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); } +void ENGINE_free_fn(ENGINE* engine) { + ENGINE_free(engine); +} void SecureContext::SetClientCertEngine( const FunctionCallbackInfo& args) { @@ -1160,18 +1097,15 @@ void SecureContext::SetClientCertEngine( DeleteFnPtr engine( LoadEngineById(*engine_id, &errmsg)); - if (!engine) - return env->ThrowError(errmsg); + if (!engine) return env->ThrowError(errmsg); // Note that this takes another reference to `engine`. int r = SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get()); - if (r == 0) - return ThrowCryptoError(env, ERR_get_error()); + if (r == 0) return ThrowCryptoError(env, ERR_get_error()); sc->client_cert_engine_provided_ = true; } #endif // !OPENSSL_NO_ENGINE - void SecureContext::GetTicketKeys(const FunctionCallbackInfo& args) { #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys) @@ -1187,7 +1121,6 @@ void SecureContext::GetTicketKeys(const FunctionCallbackInfo& args) { #endif // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys) } - void SecureContext::SetTicketKeys(const FunctionCallbackInfo& args) { #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys) SecureContext* wrap; @@ -1201,8 +1134,8 @@ void SecureContext::SetTicketKeys(const FunctionCallbackInfo& args) { THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Ticket keys"); if (Buffer::Length(args[0]) != 48) { - return THROW_ERR_INVALID_ARG_VALUE( - env, "Ticket keys length must be 48 bytes"); + return THROW_ERR_INVALID_ARG_VALUE(env, + "Ticket keys length must be 48 bytes"); } memcpy(wrap->ticket_key_name_, Buffer::Data(args[0]), 16); @@ -1213,11 +1146,9 @@ void SecureContext::SetTicketKeys(const FunctionCallbackInfo& args) { #endif // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys) } - void SecureContext::SetFreeListLength(const FunctionCallbackInfo& args) { } - // Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for // the regression test in test/parallel/test-https-resume-after-renew.js. void SecureContext::EnableTicketKeyCallback( @@ -1228,7 +1159,6 @@ void SecureContext::EnableTicketKeyCallback( SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback); } - int SecureContext::TicketKeyCallback(SSL* ssl, unsigned char* name, unsigned char* iv, @@ -1237,39 +1167,35 @@ int SecureContext::TicketKeyCallback(SSL* ssl, int enc) { static const int kTicketPartSize = 16; - SecureContext* sc = static_cast( - SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); + SecureContext* sc = + static_cast(SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); Environment* env = sc->env(); HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); Local argv[] = { - Buffer::Copy(env, - reinterpret_cast(name), - kTicketPartSize).ToLocalChecked(), - Buffer::Copy(env, - reinterpret_cast(iv), - kTicketPartSize).ToLocalChecked(), - Boolean::New(env->isolate(), enc != 0) - }; + Buffer::Copy(env, reinterpret_cast(name), kTicketPartSize) + .ToLocalChecked(), + Buffer::Copy(env, reinterpret_cast(iv), kTicketPartSize) + .ToLocalChecked(), + Boolean::New(env->isolate(), enc != 0)}; Local ret = node::MakeCallback(env->isolate(), sc->object(), env->ticketkeycallback_string(), arraysize(argv), argv, - {0, 0}).ToLocalChecked(); + {0, 0}) + .ToLocalChecked(); Local arr = ret.As(); int r = arr->Get(kTicketKeyReturnIndex)->Int32Value(); - if (r < 0) - return r; + if (r < 0) return r; Local hmac = arr->Get(kTicketKeyHMACIndex); Local aes = arr->Get(kTicketKeyAESIndex); - if (Buffer::Length(aes) != kTicketPartSize) - return -1; + if (Buffer::Length(aes) != kTicketPartSize) return -1; if (enc) { Local name_val = arr->Get(kTicketKeyNameIndex); @@ -1284,48 +1210,39 @@ int SecureContext::TicketKeyCallback(SSL* ssl, memcpy(iv, Buffer::Data(iv_val), kTicketPartSize); } - HMAC_Init_ex(hctx, - Buffer::Data(hmac), - Buffer::Length(hmac), - EVP_sha256(), - nullptr); + HMAC_Init_ex( + hctx, Buffer::Data(hmac), Buffer::Length(hmac), EVP_sha256(), nullptr); const unsigned char* aes_key = reinterpret_cast(Buffer::Data(aes)); if (enc) { - EVP_EncryptInit_ex(ectx, - EVP_aes_128_cbc(), - nullptr, - aes_key, - iv); + EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, aes_key, iv); } else { - EVP_DecryptInit_ex(ectx, - EVP_aes_128_cbc(), - nullptr, - aes_key, - iv); + EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, aes_key, iv); } return r; } - int SecureContext::TicketCompatibilityCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, HMAC_CTX* hctx, int enc) { - SecureContext* sc = static_cast( - SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); + SecureContext* sc = + static_cast(SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); if (enc) { memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)); if (RAND_bytes(iv, 16) <= 0 || - EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, - sc->ticket_key_aes_, iv) <= 0 || - HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_), - EVP_sha256(), nullptr) <= 0) { + EVP_EncryptInit_ex( + ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_, iv) <= 0 || + HMAC_Init_ex(hctx, + sc->ticket_key_hmac_, + sizeof(sc->ticket_key_hmac_), + EVP_sha256(), + nullptr) <= 0) { return -1; } return 1; @@ -1336,16 +1253,18 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl, return 0; } - if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_, - iv) <= 0 || - HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_), - EVP_sha256(), nullptr) <= 0) { + if (EVP_DecryptInit_ex( + ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_, iv) <= 0 || + HMAC_Init_ex(hctx, + sc->ticket_key_hmac_, + sizeof(sc->ticket_key_hmac_), + EVP_sha256(), + nullptr) <= 0) { return -1; } return 1; } - template void SecureContext::GetCertificate(const FunctionCallbackInfo& args) { SecureContext* wrap; @@ -1357,19 +1276,17 @@ void SecureContext::GetCertificate(const FunctionCallbackInfo& args) { cert = wrap->cert_.get(); else cert = wrap->issuer_.get(); - if (cert == nullptr) - return args.GetReturnValue().SetNull(); + if (cert == nullptr) return args.GetReturnValue().SetNull(); int size = i2d_X509(cert, nullptr); Local buff = Buffer::New(env, size).ToLocalChecked(); - unsigned char* serialized = reinterpret_cast( - Buffer::Data(buff)); + unsigned char* serialized = + reinterpret_cast(Buffer::Data(buff)); i2d_X509(cert, &serialized); args.GetReturnValue().Set(buff); } - template void SSLWrap::AddMethods(Environment* env, Local t) { HandleScope scope(env->isolate()); @@ -1392,20 +1309,19 @@ void SSLWrap::AddMethods(Environment* env, Local t) { env->SetProtoMethod(t, "newSessionDone", NewSessionDone); env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse); env->SetProtoMethod(t, "requestOCSP", RequestOCSP); - env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo", - GetEphemeralKeyInfo); + env->SetProtoMethodNoSideEffect( + t, "getEphemeralKeyInfo", GetEphemeralKeyInfo); env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol); #ifdef SSL_set_max_send_fragment env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment); #endif // SSL_set_max_send_fragment - env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol", - GetALPNNegotiatedProto); + env->SetProtoMethodNoSideEffect( + t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto); env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols); } - template void SSLWrap::ConfigureSecureContext(SecureContext* sc) { // OCSP stapling @@ -1413,7 +1329,6 @@ void SSLWrap::ConfigureSecureContext(SecureContext* sc) { SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr); } - template SSL_SESSION* SSLWrap::GetSessionCallback(SSL* s, const unsigned char* key, @@ -1425,7 +1340,6 @@ SSL_SESSION* SSLWrap::GetSessionCallback(SSL* s, return w->next_sess_.release(); } - template int SSLWrap::NewSessionCallback(SSL* s, SSL_SESSION* sess) { Base* w = static_cast(SSL_get_app_data(s)); @@ -1433,36 +1347,33 @@ int SSLWrap::NewSessionCallback(SSL* s, SSL_SESSION* sess) { HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); - if (!w->session_callbacks_) - return 0; + if (!w->session_callbacks_) return 0; // Check if session is small enough to be stored int size = i2d_SSL_SESSION(sess, nullptr); - if (size > SecureContext::kMaxSessionSize) - return 0; + if (size > SecureContext::kMaxSessionSize) return 0; // Serialize session Local buff = Buffer::New(env, size).ToLocalChecked(); - unsigned char* serialized = reinterpret_cast( - Buffer::Data(buff)); + unsigned char* serialized = + reinterpret_cast(Buffer::Data(buff)); memset(serialized, 0, size); i2d_SSL_SESSION(sess, &serialized); unsigned int session_id_length; - const unsigned char* session_id = SSL_SESSION_get_id(sess, - &session_id_length); - Local session = Buffer::Copy( - env, - reinterpret_cast(session_id), - session_id_length).ToLocalChecked(); - Local argv[] = { session, buff }; + const unsigned char* session_id = + SSL_SESSION_get_id(sess, &session_id_length); + Local session = + Buffer::Copy( + env, reinterpret_cast(session_id), session_id_length) + .ToLocalChecked(); + Local argv[] = {session, buff}; w->new_session_wait_ = true; w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv); return 0; } - template void SSLWrap::OnClientHello(void* arg, const ClientHelloParser::ClientHello& hello) { @@ -1473,48 +1384,48 @@ void SSLWrap::OnClientHello(void* arg, Context::Scope context_scope(context); Local hello_obj = Object::New(env->isolate()); - Local buff = Buffer::Copy( - env, - reinterpret_cast(hello.session_id()), - hello.session_size()).ToLocalChecked(); + Local buff = + Buffer::Copy(env, + reinterpret_cast(hello.session_id()), + hello.session_size()) + .ToLocalChecked(); hello_obj->Set(context, env->session_id_string(), buff).FromJust(); if (hello.servername() == nullptr) { - hello_obj->Set(context, - env->servername_string(), - String::Empty(env->isolate())).FromJust(); + hello_obj + ->Set(context, env->servername_string(), String::Empty(env->isolate())) + .FromJust(); } else { - Local servername = OneByteString(env->isolate(), - hello.servername(), - hello.servername_size()); + Local servername = OneByteString( + env->isolate(), hello.servername(), hello.servername_size()); hello_obj->Set(context, env->servername_string(), servername).FromJust(); } - hello_obj->Set(context, - env->tls_ticket_string(), - Boolean::New(env->isolate(), hello.has_ticket())).FromJust(); - hello_obj->Set(context, - env->ocsp_request_string(), - Boolean::New(env->isolate(), hello.ocsp_request())).FromJust(); - - Local argv[] = { hello_obj }; + hello_obj + ->Set(context, + env->tls_ticket_string(), + Boolean::New(env->isolate(), hello.has_ticket())) + .FromJust(); + hello_obj + ->Set(context, + env->ocsp_request_string(), + Boolean::New(env->isolate(), hello.ocsp_request())) + .FromJust(); + + Local argv[] = {hello_obj}; w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv); } - static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) { const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext); - if (method != X509V3_EXT_get_nid(NID_subject_alt_name)) - return false; + if (method != X509V3_EXT_get_nid(NID_subject_alt_name)) return false; GENERAL_NAMES* names = static_cast(X509V3_EXT_d2i(ext)); - if (names == nullptr) - return false; + if (names == nullptr) return false; for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) { GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i); - if (i != 0) - BIO_write(out, ", ", 2); + if (i != 0) BIO_write(out, ", ", 2); if (gen->type == GEN_DNS) { ASN1_IA5STRING* name = gen->d.dNSName; @@ -1524,8 +1435,7 @@ static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) { } else { STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME( const_cast(method), gen, nullptr); - if (nval == nullptr) - return false; + if (nval == nullptr) return false; X509V3_EXT_val_prn(out, nval, 0, 0); sk_CONF_VALUE_pop_free(nval, X509V3_conf_free); } @@ -1535,7 +1445,6 @@ static bool SafeX509ExtPrint(BIO* out, X509_EXTENSION* ext) { return true; } - static void AddFingerprintDigest(const unsigned char* md, unsigned int md_size, char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) { @@ -1543,13 +1452,13 @@ static void AddFingerprintDigest(const unsigned char* md, const char hex[] = "0123456789ABCDEF"; for (i = 0; i < md_size; i++) { - (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4]; - (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)]; - (*fingerprint)[(3*i)+2] = ':'; + (*fingerprint)[3 * i] = hex[(md[i] & 0xf0) >> 4]; + (*fingerprint)[(3 * i) + 1] = hex[(md[i] & 0x0f)]; + (*fingerprint)[(3 * i) + 2] = ':'; } if (md_size > 0) { - (*fingerprint)[(3*(md_size-1))+2] = '\0'; + (*fingerprint)[(3 * (md_size - 1)) + 2] = '\0'; } else { (*fingerprint)[0] = '\0'; } @@ -1562,36 +1471,39 @@ static Local X509ToObject(Environment* env, X509* cert) { BIOPointer bio(BIO_new(BIO_s_mem())); BUF_MEM* mem; - if (X509_NAME_print_ex(bio.get(), - X509_get_subject_name(cert), - 0, - X509_NAME_FLAGS) > 0) { + if (X509_NAME_print_ex( + bio.get(), X509_get_subject_name(cert), 0, X509_NAME_FLAGS) > 0) { BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, env->subject_string(), - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set( + context, + env->subject_string(), + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); } USE(BIO_reset(bio.get())); X509_NAME* issuer_name = X509_get_issuer_name(cert); if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) > 0) { BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, env->issuer_string(), - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set( + context, + env->issuer_string(), + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); } USE(BIO_reset(bio.get())); - int nids[] = { NID_subject_alt_name, NID_info_access }; - Local keys[] = { env->subjectaltname_string(), - env->infoaccess_string() }; + int nids[] = {NID_subject_alt_name, NID_info_access}; + Local keys[] = {env->subjectaltname_string(), + env->infoaccess_string()}; CHECK_EQ(arraysize(nids), arraysize(keys)); for (size_t i = 0; i < arraysize(nids); i++) { int index = X509_get_ext_by_NID(cert, nids[i], -1); - if (index < 0) - continue; + if (index < 0) continue; X509_EXTENSION* ext; int rv; @@ -1605,18 +1517,20 @@ static Local X509ToObject(Environment* env, X509* cert) { } BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, keys[i], - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set( + context, + keys[i], + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); USE(BIO_reset(bio.get())); } EVPKeyPointer pkey(X509_get_pubkey(cert)); RSAPointer rsa; - if (pkey) - rsa.reset(EVP_PKEY_get1_RSA(pkey.get())); + if (pkey) rsa.reset(EVP_PKEY_get1_RSA(pkey.get())); if (rsa) { const BIGNUM* n; @@ -1624,10 +1538,13 @@ static Local X509ToObject(Environment* env, X509* cert) { RSA_get0_key(rsa.get(), &n, &e, nullptr); BN_print(bio.get(), n); BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, env->modulus_string(), - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set( + context, + env->modulus_string(), + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); USE(BIO_reset(bio.get())); uint64_t exponent_word = static_cast(BN_get_word(e)); @@ -1639,10 +1556,13 @@ static Local X509ToObject(Environment* env, X509* cert) { BIO_printf(bio.get(), "0x%x%08x", hi, lo); } BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, env->exponent_string(), - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set( + context, + env->exponent_string(), + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); USE(BIO_reset(bio.get())); int size = i2d_RSA_PUBKEY(rsa.get(), nullptr); @@ -1659,32 +1579,40 @@ static Local X509ToObject(Environment* env, X509* cert) { ASN1_TIME_print(bio.get(), X509_get_notBefore(cert)); BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, env->valid_from_string(), - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set(context, + env->valid_from_string(), + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); USE(BIO_reset(bio.get())); ASN1_TIME_print(bio.get(), X509_get_notAfter(cert)); BIO_get_mem_ptr(bio.get(), &mem); - info->Set(context, env->valid_to_string(), - String::NewFromUtf8(env->isolate(), mem->data, - NewStringType::kNormal, - mem->length).ToLocalChecked()).FromJust(); + info->Set(context, + env->valid_to_string(), + String::NewFromUtf8( + env->isolate(), mem->data, NewStringType::kNormal, mem->length) + .ToLocalChecked()) + .FromJust(); bio.reset(); unsigned char md[EVP_MAX_MD_SIZE]; unsigned int md_size; char fingerprint[EVP_MAX_MD_SIZE * 3 + 1]; if (X509_digest(cert, EVP_sha1(), md, &md_size)) { - AddFingerprintDigest(md, md_size, &fingerprint); - info->Set(context, env->fingerprint_string(), - OneByteString(env->isolate(), fingerprint)).FromJust(); + AddFingerprintDigest(md, md_size, &fingerprint); + info->Set(context, + env->fingerprint_string(), + OneByteString(env->isolate(), fingerprint)) + .FromJust(); } if (X509_digest(cert, EVP_sha256(), md, &md_size)) { - AddFingerprintDigest(md, md_size, &fingerprint); - info->Set(context, env->fingerprint256_string(), - OneByteString(env->isolate(), fingerprint)).FromJust(); + AddFingerprintDigest(md, md_size, &fingerprint); + info->Set(context, + env->fingerprint256_string(), + OneByteString(env->isolate(), fingerprint)) + .FromJust(); } StackOfASN1 eku(static_cast( @@ -1695,12 +1623,10 @@ static Local X509ToObject(Environment* env, X509* cert) { int j = 0; for (int i = 0; i < sk_ASN1_OBJECT_num(eku.get()); i++) { - if (OBJ_obj2txt(buf, - sizeof(buf), - sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) { - ext_key_usage->Set(context, - j++, - OneByteString(env->isolate(), buf)).FromJust(); + if (OBJ_obj2txt( + buf, sizeof(buf), sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) { + ext_key_usage->Set(context, j++, OneByteString(env->isolate(), buf)) + .FromJust(); } } @@ -1713,8 +1639,10 @@ static Local X509ToObject(Environment* env, X509* cert) { if (bn) { OpenSSLBuffer buf(BN_bn2hex(bn.get())); if (buf) { - info->Set(context, env->serial_number_string(), - OneByteString(env->isolate(), buf.get())).FromJust(); + info->Set(context, + env->serial_number_string(), + OneByteString(env->isolate(), buf.get())) + .FromJust(); } } } @@ -1722,15 +1650,14 @@ static Local X509ToObject(Environment* env, X509* cert) { // Raw DER certificate int size = i2d_X509(cert, nullptr); Local buff = Buffer::New(env, size).ToLocalChecked(); - unsigned char* serialized = reinterpret_cast( - Buffer::Data(buff)); + unsigned char* serialized = + reinterpret_cast(Buffer::Data(buff)); i2d_X509(cert, &serialized); info->Set(context, env->raw_string(), buff).FromJust(); return scope.Escape(info); } - static Local AddIssuerChainToObject(X509Pointer* cert, Local object, StackOfX509&& peer_certs, @@ -1741,8 +1668,7 @@ static Local AddIssuerChainToObject(X509Pointer* cert, int i; for (i = 0; i < sk_X509_num(peer_certs.get()); i++) { X509* ca = sk_X509_value(peer_certs.get(), i); - if (X509_check_issued(ca, cert->get()) != X509_V_OK) - continue; + if (X509_check_issued(ca, cert->get()) != X509_V_OK) continue; Local ca_info = X509ToObject(env, ca); object->Set(context, env->issuercert_string(), ca_info).FromJust(); @@ -1755,18 +1681,15 @@ static Local AddIssuerChainToObject(X509Pointer* cert, } // Issuer not found, break out of the loop. - if (i == sk_X509_num(peer_certs.get())) - break; + if (i == sk_X509_num(peer_certs.get())) break; } return object; } - static StackOfX509 CloneSSLCerts(X509Pointer&& cert, - const STACK_OF(X509)* const ssl_certs) { + const STACK_OF(X509) * const ssl_certs) { StackOfX509 peer_certs(sk_X509_new(nullptr)); - if (cert) - sk_X509_push(peer_certs.get(), cert.release()); + if (cert) sk_X509_push(peer_certs.get(), cert.release()); for (int i = 0; i < sk_X509_num(ssl_certs); i++) { X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i))); if (!cert || !sk_X509_push(peer_certs.get(), cert.get())) @@ -1777,7 +1700,6 @@ static StackOfX509 CloneSSLCerts(X509Pointer&& cert, return peer_certs; } - static Local GetLastIssuedCert(X509Pointer* cert, const SSLPointer& ssl, Local issuer_chain, @@ -1798,7 +1720,6 @@ static Local GetLastIssuedCert(X509Pointer* cert, return issuer_chain; } - template void SSLWrap::GetPeerCertificate( const FunctionCallbackInfo& args) { @@ -1814,11 +1735,10 @@ void SSLWrap::GetPeerCertificate( // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain` // contains the `peer_certificate`, but on server it doesn't. - X509Pointer cert( - w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) : nullptr); + X509Pointer cert(w->is_server() ? SSL_get_peer_certificate(w->ssl_.get()) + : nullptr); STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(w->ssl_.get()); - if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0)) - goto done; + if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0)) goto done; // Short result requested. if (args.Length() < 1 || !args[0]->IsTrue()) { @@ -1837,18 +1757,15 @@ void SSLWrap::GetPeerCertificate( issuer_chain = GetLastIssuedCert(&cert, w->ssl_, issuer_chain, env); // Last certificate should be self-signed. if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK) - issuer_chain->Set(env->context(), - env->issuercert_string(), - issuer_chain).FromJust(); + issuer_chain->Set(env->context(), env->issuercert_string(), issuer_chain) + .FromJust(); } - done: - if (result.IsEmpty()) - result = Object::New(env->isolate()); +done: + if (result.IsEmpty()) result = Object::New(env->isolate()); args.GetReturnValue().Set(result); } - template void SSLWrap::GetFinished(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1863,15 +1780,13 @@ void SSLWrap::GetFinished(const FunctionCallbackInfo& args) { // Thus, we use a dummy byte. char dummy[1]; size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy); - if (len == 0) - return; + if (len == 0) return; char* buf = Malloc(len); CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf, len)); args.GetReturnValue().Set(Buffer::New(env, buf, len).ToLocalChecked()); } - template void SSLWrap::GetPeerFinished(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1886,15 +1801,13 @@ void SSLWrap::GetPeerFinished(const FunctionCallbackInfo& args) { // Thus, we use a dummy byte. char dummy[1]; size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy); - if (len == 0) - return; + if (len == 0) return; char* buf = Malloc(len); CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf, len)); args.GetReturnValue().Set(Buffer::New(env, buf, len).ToLocalChecked()); } - template void SSLWrap::GetSession(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1903,8 +1816,7 @@ void SSLWrap::GetSession(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); SSL_SESSION* sess = SSL_get_session(w->ssl_.get()); - if (sess == nullptr) - return; + if (sess == nullptr) return; int slen = i2d_SSL_SESSION(sess, nullptr); CHECK_GT(slen, 0); @@ -1915,7 +1827,6 @@ void SSLWrap::GetSession(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(Buffer::New(env, sbuf, slen).ToLocalChecked()); } - template void SSLWrap::SetSession(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1930,22 +1841,18 @@ void SSLWrap::SetSession(const FunctionCallbackInfo& args) { THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session"); size_t slen = Buffer::Length(args[0]); std::vector sbuf(slen); - if (char* p = Buffer::Data(args[0])) - sbuf.assign(p, p + slen); + if (char* p = Buffer::Data(args[0])) sbuf.assign(p, p + slen); const unsigned char* p = reinterpret_cast(sbuf.data()); SSLSessionPointer sess(d2i_SSL_SESSION(nullptr, &p, slen)); - if (sess == nullptr) - return; + if (sess == nullptr) return; int r = SSL_set_session(w->ssl_.get(), sess.get()); - if (!r) - return env->ThrowError("SSL_set_session error"); + if (!r) return env->ThrowError("SSL_set_session error"); } - template void SSLWrap::LoadSession(const FunctionCallbackInfo& args) { Base* w; @@ -1963,7 +1870,6 @@ void SSLWrap::LoadSession(const FunctionCallbackInfo& args) { } } - template void SSLWrap::IsSessionReused(const FunctionCallbackInfo& args) { Base* w; @@ -1972,7 +1878,6 @@ void SSLWrap::IsSessionReused(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(yes); } - template void SSLWrap::EndParser(const FunctionCallbackInfo& args) { Base* w; @@ -1980,7 +1885,6 @@ void SSLWrap::EndParser(const FunctionCallbackInfo& args) { w->hello_parser_.End(); } - template void SSLWrap::Renegotiate(const FunctionCallbackInfo& args) { Base* w; @@ -1992,7 +1896,6 @@ void SSLWrap::Renegotiate(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(yes); } - template void SSLWrap::Shutdown(const FunctionCallbackInfo& args) { Base* w; @@ -2002,7 +1905,6 @@ void SSLWrap::Shutdown(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(rv); } - template void SSLWrap::GetTLSTicket(const FunctionCallbackInfo& args) { Base* w; @@ -2010,23 +1912,21 @@ void SSLWrap::GetTLSTicket(const FunctionCallbackInfo& args) { Environment* env = w->ssl_env(); SSL_SESSION* sess = SSL_get_session(w->ssl_.get()); - if (sess == nullptr) - return; + if (sess == nullptr) return; const unsigned char* ticket; size_t length; SSL_SESSION_get0_ticket(sess, &ticket, &length); - if (ticket == nullptr) - return; + if (ticket == nullptr) return; - Local buff = Buffer::Copy( - env, reinterpret_cast(ticket), length).ToLocalChecked(); + Local buff = + Buffer::Copy(env, reinterpret_cast(ticket), length) + .ToLocalChecked(); args.GetReturnValue().Set(buff); } - template void SSLWrap::NewSessionDone(const FunctionCallbackInfo& args) { Base* w; @@ -2035,7 +1935,6 @@ void SSLWrap::NewSessionDone(const FunctionCallbackInfo& args) { w->NewSessionDoneCb(); } - template void SSLWrap::SetOCSPResponse(const FunctionCallbackInfo& args) { Base* w; @@ -2050,7 +1949,6 @@ void SSLWrap::SetOCSPResponse(const FunctionCallbackInfo& args) { w->ocsp_response_.Reset(args.GetIsolate(), args[0].As()); } - template void SSLWrap::RequestOCSP(const FunctionCallbackInfo& args) { Base* w; @@ -2059,7 +1957,6 @@ void SSLWrap::RequestOCSP(const FunctionCallbackInfo& args) { SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp); } - template void SSLWrap::GetEphemeralKeyInfo( const FunctionCallbackInfo& args) { @@ -2071,8 +1968,7 @@ void SSLWrap::GetEphemeralKeyInfo( CHECK(w->ssl_); // tmp key is available on only client - if (w->is_server()) - return args.GetReturnValue().SetNull(); + if (w->is_server()) return args.GetReturnValue().SetNull(); Local info = Object::New(env->isolate()); @@ -2082,35 +1978,41 @@ void SSLWrap::GetEphemeralKeyInfo( int kid = EVP_PKEY_id(key); switch (kid) { case EVP_PKEY_DH: - info->Set(context, env->type_string(), - FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).FromJust(); - info->Set(context, env->size_string(), - Integer::New(env->isolate(), EVP_PKEY_bits(key))).FromJust(); + info->Set(context, + env->type_string(), + FIXED_ONE_BYTE_STRING(env->isolate(), "DH")) + .FromJust(); + info->Set(context, + env->size_string(), + Integer::New(env->isolate(), EVP_PKEY_bits(key))) + .FromJust(); break; case EVP_PKEY_EC: // TODO(shigeki) Change this to EVP_PKEY_X25519 and add EVP_PKEY_X448 // after upgrading to 1.1.1. - case NID_X25519: - { - const char* curve_name; - if (kid == EVP_PKEY_EC) { - EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key); - int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)); - curve_name = OBJ_nid2sn(nid); - EC_KEY_free(ec); - } else { - curve_name = OBJ_nid2sn(kid); - } - info->Set(context, env->type_string(), - FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).FromJust(); - info->Set(context, env->name_string(), - OneByteString(args.GetIsolate(), - curve_name)).FromJust(); - info->Set(context, env->size_string(), - Integer::New(env->isolate(), - EVP_PKEY_bits(key))).FromJust(); + case NID_X25519: { + const char* curve_name; + if (kid == EVP_PKEY_EC) { + EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key); + int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)); + curve_name = OBJ_nid2sn(nid); + EC_KEY_free(ec); + } else { + curve_name = OBJ_nid2sn(kid); } - break; + info->Set(context, + env->type_string(), + FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")) + .FromJust(); + info->Set(context, + env->name_string(), + OneByteString(args.GetIsolate(), curve_name)) + .FromJust(); + info->Set(context, + env->size_string(), + Integer::New(env->isolate(), EVP_PKEY_bits(key))) + .FromJust(); + } break; } EVP_PKEY_free(key); } @@ -2118,7 +2020,6 @@ void SSLWrap::GetEphemeralKeyInfo( return args.GetReturnValue().Set(info); } - #ifdef SSL_set_max_send_fragment template void SSLWrap::SetMaxSendFragment( @@ -2129,13 +2030,11 @@ void SSLWrap::SetMaxSendFragment( ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); int rv = SSL_set_max_send_fragment( - w->ssl_.get(), - args[0]->Int32Value(w->ssl_env()->context()).FromJust()); + w->ssl_.get(), args[0]->Int32Value(w->ssl_env()->context()).FromJust()); args.GetReturnValue().Set(rv); } #endif // SSL_set_max_send_fragment - template void SSLWrap::IsInitFinished(const FunctionCallbackInfo& args) { Base* w; @@ -2144,7 +2043,6 @@ void SSLWrap::IsInitFinished(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(yes); } - template void SSLWrap::VerifyError(const FunctionCallbackInfo& args) { Base* w; @@ -2160,12 +2058,14 @@ void SSLWrap::VerifyError(const FunctionCallbackInfo& args) { x509_verify_error = SSL_get_verify_result(w->ssl_.get()); } - if (x509_verify_error == X509_V_OK) - return args.GetReturnValue().SetNull(); + if (x509_verify_error == X509_V_OK) return args.GetReturnValue().SetNull(); const char* reason = X509_verify_cert_error_string(x509_verify_error); const char* code = reason; -#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break; +#define CASE_X509_ERR(CODE) \ + case X509_V_ERR_##CODE: \ + code = #CODE; \ + break; switch (x509_verify_error) { CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT) CASE_X509_ERR(UNABLE_TO_GET_CRL) @@ -2201,12 +2101,14 @@ void SSLWrap::VerifyError(const FunctionCallbackInfo& args) { Local reason_string = OneByteString(isolate, reason); Local exception_value = Exception::Error(reason_string); Local exception_object = exception_value->ToObject(isolate); - exception_object->Set(w->env()->context(), w->env()->code_string(), - OneByteString(isolate, code)).FromJust(); + exception_object + ->Set(w->env()->context(), + w->env()->code_string(), + OneByteString(isolate, code)) + .FromJust(); args.GetReturnValue().Set(exception_object); } - template void SSLWrap::GetCurrentCipher(const FunctionCallbackInfo& args) { Base* w; @@ -2215,19 +2117,21 @@ void SSLWrap::GetCurrentCipher(const FunctionCallbackInfo& args) { Local context = env->context(); const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get()); - if (c == nullptr) - return; + if (c == nullptr) return; Local info = Object::New(env->isolate()); const char* cipher_name = SSL_CIPHER_get_name(c); - info->Set(context, env->name_string(), - OneByteString(args.GetIsolate(), cipher_name)).FromJust(); - info->Set(context, env->version_string(), - OneByteString(args.GetIsolate(), "TLSv1/SSLv3")).FromJust(); + info->Set(context, + env->name_string(), + OneByteString(args.GetIsolate(), cipher_name)) + .FromJust(); + info->Set(context, + env->version_string(), + OneByteString(args.GetIsolate(), "TLSv1/SSLv3")) + .FromJust(); args.GetReturnValue().Set(info); } - template void SSLWrap::GetProtocol(const FunctionCallbackInfo& args) { Base* w; @@ -2237,7 +2141,6 @@ void SSLWrap::GetProtocol(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version)); } - template int SSLWrap::SelectALPNCallback(SSL* s, const unsigned char** out, @@ -2251,15 +2154,19 @@ int SSLWrap::SelectALPNCallback(SSL* s, Context::Scope context_scope(env->context()); Local alpn_buffer = - w->object()->GetPrivate( - env->context(), - env->alpn_buffer_private_symbol()).ToLocalChecked(); + w->object() + ->GetPrivate(env->context(), env->alpn_buffer_private_symbol()) + .ToLocalChecked(); CHECK(Buffer::HasInstance(alpn_buffer)); const unsigned char* alpn_protos = reinterpret_cast(Buffer::Data(alpn_buffer)); unsigned alpn_protos_len = Buffer::Length(alpn_buffer); - int status = SSL_select_next_proto(const_cast(out), outlen, - alpn_protos, alpn_protos_len, in, inlen); + int status = SSL_select_next_proto(const_cast(out), + outlen, + alpn_protos, + alpn_protos_len, + in, + inlen); // According to 3.2. Protocol Selection of RFC7301, fatal // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not // support it yet. See @@ -2268,7 +2175,6 @@ int SSLWrap::SelectALPNCallback(SSL* s, : SSL_TLSEXT_ERR_NOACK; } - template void SSLWrap::GetALPNNegotiatedProto( const FunctionCallbackInfo& args) { @@ -2280,14 +2186,12 @@ void SSLWrap::GetALPNNegotiatedProto( SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len); - if (!alpn_proto) - return args.GetReturnValue().Set(false); + if (!alpn_proto) return args.GetReturnValue().Set(false); args.GetReturnValue().Set( OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len)); } - template void SSLWrap::SetALPNProtocols(const FunctionCallbackInfo& args) { Base* w; @@ -2303,19 +2207,16 @@ void SSLWrap::SetALPNProtocols(const FunctionCallbackInfo& args) { int r = SSL_set_alpn_protos(w->ssl_.get(), alpn_protos, alpn_protos_len); CHECK_EQ(r, 0); } else { - CHECK( - w->object()->SetPrivate( - env->context(), - env->alpn_buffer_private_symbol(), - args[0]).FromJust()); + CHECK(w->object() + ->SetPrivate( + env->context(), env->alpn_buffer_private_symbol(), args[0]) + .FromJust()); // Server should select ALPN protocol from list of advertised by client - SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()), - SelectALPNCallback, - nullptr); + SSL_CTX_set_alpn_select_cb( + SSL_get_SSL_CTX(w->ssl_.get()), SelectALPNCallback, nullptr); } } - template int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg) { Base* w = static_cast(SSL_get_app_data(s)); @@ -2330,9 +2231,8 @@ int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg) { if (resp == nullptr) { arg = Null(env->isolate()); } else { - arg = - Buffer::Copy(env, reinterpret_cast(resp), len) - .ToLocalChecked(); + arg = Buffer::Copy(env, reinterpret_cast(resp), len) + .ToLocalChecked(); } w->MakeCallback(env->onocspresponse_string(), 1, &arg); @@ -2341,8 +2241,7 @@ int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg) { return 1; } else { // Outgoing response - if (w->ocsp_response_.IsEmpty()) - return SSL_TLSEXT_ERR_NOACK; + if (w->ocsp_response_.IsEmpty()) return SSL_TLSEXT_ERR_NOACK; Local obj = PersistentToLocal(env->isolate(), w->ocsp_response_); char* resp = Buffer::Data(obj); @@ -2352,34 +2251,28 @@ int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg) { char* data = node::Malloc(len); memcpy(data, resp, len); - if (!SSL_set_tlsext_status_ocsp_resp(s, data, len)) - free(data); + if (!SSL_set_tlsext_status_ocsp_resp(s, data, len)) free(data); w->ocsp_response_.Reset(); return SSL_TLSEXT_ERR_OK; } } - template void SSLWrap::WaitForCertCb(CertCb cb, void* arg) { cert_cb_ = cb; cert_cb_arg_ = arg; } - template int SSLWrap::SSLCertCallback(SSL* s, void* arg) { Base* w = static_cast(SSL_get_app_data(s)); - if (!w->is_server()) - return 1; + if (!w->is_server()) return 1; - if (!w->is_waiting_cert_cb()) - return 1; + if (!w->is_waiting_cert_cb()) return 1; - if (w->cert_cb_running_) - return -1; + if (w->cert_cb_running_) return -1; Environment* env = w->env(); Local context = env->context(); @@ -2391,30 +2284,29 @@ int SSLWrap::SSLCertCallback(SSL* s, void* arg) { const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (servername == nullptr) { - info->Set(context, - env->servername_string(), - String::Empty(env->isolate())).FromJust(); + info->Set(context, env->servername_string(), String::Empty(env->isolate())) + .FromJust(); } else { - Local str = OneByteString(env->isolate(), servername, - strlen(servername)); + Local str = + OneByteString(env->isolate(), servername, strlen(servername)); info->Set(context, env->servername_string(), str).FromJust(); } const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp); - info->Set(context, env->ocsp_request_string(), - Boolean::New(env->isolate(), ocsp)).FromJust(); + info->Set(context, + env->ocsp_request_string(), + Boolean::New(env->isolate(), ocsp)) + .FromJust(); - Local argv[] = { info }; + Local argv[] = {info}; w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv); - if (!w->cert_cb_running_) - return 1; + if (!w->cert_cb_running_) return 1; // Performing async action, wait... return -1; } - template void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { Base* w; @@ -2428,8 +2320,7 @@ void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { Local cons = env->secure_context_constructor_template(); // Not an object, probably undefined or null - if (!ctx->IsObject()) - goto fire_cb; + if (!ctx->IsObject()) goto fire_cb; if (cons->HasInstance(ctx)) { SecureContext* sc; @@ -2441,21 +2332,16 @@ void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { // NOTE: reference count is not increased by this API methods X509* x509 = SSL_CTX_get0_certificate(sc->ctx_.get()); EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_.get()); - STACK_OF(X509)* chain; + STACK_OF(X509) * chain; rv = SSL_CTX_get0_chain_certs(sc->ctx_.get(), &chain); - if (rv) - rv = SSL_use_certificate(w->ssl_.get(), x509); - if (rv) - rv = SSL_use_PrivateKey(w->ssl_.get(), pkey); - if (rv && chain != nullptr) - rv = SSL_set1_chain(w->ssl_.get(), chain); - if (rv) - rv = w->SetCACerts(sc); + if (rv) rv = SSL_use_certificate(w->ssl_.get(), x509); + if (rv) rv = SSL_use_PrivateKey(w->ssl_.get(), pkey); + if (rv && chain != nullptr) rv = SSL_set1_chain(w->ssl_.get(), chain); + if (rv) rv = w->SetCACerts(sc); if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) - return env->ThrowError("CertCbDone"); + if (!err) return env->ThrowError("CertCbDone"); return ThrowCryptoError(env, err); } } else { @@ -2465,7 +2351,7 @@ void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { return; } - fire_cb: +fire_cb: CertCb cb; void* arg; @@ -2479,17 +2365,14 @@ void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { cb(arg); } - template void SSLWrap::DestroySSL() { - if (!ssl_) - return; + if (!ssl_) return; env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize); ssl_.reset(); } - template void SSLWrap::SetSNIContext(SecureContext* sc) { ConfigureSecureContext(sc); @@ -2498,16 +2381,14 @@ void SSLWrap::SetSNIContext(SecureContext* sc) { SetCACerts(sc); } - template int SSLWrap::SetCACerts(SecureContext* sc) { int err = SSL_set1_verify_cert_store(ssl_.get(), SSL_CTX_get_cert_store(sc->ctx_.get())); - if (err != 1) - return err; + if (err != 1) return err; - STACK_OF(X509_NAME)* list = SSL_dup_CA_list( - SSL_CTX_get_client_CA_list(sc->ctx_.get())); + STACK_OF(X509_NAME)* list = + SSL_dup_CA_list(SSL_CTX_get_client_CA_list(sc->ctx_.get())); // NOTE: `SSL_set_client_CA_list` takes the ownership of `list` SSL_set_client_CA_list(ssl_.get(), list); @@ -2577,7 +2458,6 @@ void CipherBase::Initialize(Environment* env, Local target) { t->GetFunction()); } - void CipherBase::New(const FunctionCallbackInfo& args) { CHECK(args.IsConstructCall()); CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher; @@ -2585,7 +2465,6 @@ void CipherBase::New(const FunctionCallbackInfo& args) { new CipherBase(env, args.This(), kind); } - void CipherBase::Init(const char* cipher_type, const char* key_buf, int key_buf_len, @@ -2602,8 +2481,7 @@ void CipherBase::Init(const char* cipher_type, CHECK(!ctx_); const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type); - if (cipher == nullptr) - return env()->ThrowError("Unknown cipher"); + if (cipher == nullptr) return env()->ThrowError("Unknown cipher"); unsigned char key[EVP_MAX_KEY_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH]; @@ -2625,24 +2503,23 @@ void CipherBase::Init(const char* cipher_type, EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); const bool encrypt = (kind_ == kCipher); - if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr, - nullptr, nullptr, encrypt)) { - return ThrowCryptoError(env(), ERR_get_error(), - "Failed to initialize cipher"); + if (1 != EVP_CipherInit_ex( + ctx_.get(), cipher, nullptr, nullptr, nullptr, encrypt)) { + return ThrowCryptoError( + env(), ERR_get_error(), "Failed to initialize cipher"); } if (encrypt && (mode == EVP_CIPH_CTR_MODE || mode == EVP_CIPH_GCM_MODE || - mode == EVP_CIPH_CCM_MODE)) { + mode == EVP_CIPH_CCM_MODE)) { // Ignore the return value (i.e. possible exception) because we are // not calling back into JS anyway. - ProcessEmitWarning(env(), - "Use Cipheriv for counter mode of %s", - cipher_type); + ProcessEmitWarning( + env(), "Use Cipheriv for counter mode of %s", cipher_type); } if (IsAuthenticatedMode()) { - if (!InitAuthenticated(cipher_type, EVP_CIPHER_iv_length(cipher), - auth_tag_len)) + if (!InitAuthenticated( + cipher_type, EVP_CIPHER_iv_length(cipher), auth_tag_len)) return; } @@ -2654,12 +2531,11 @@ void CipherBase::Init(const char* cipher_type, reinterpret_cast(key), reinterpret_cast(iv), encrypt)) { - return ThrowCryptoError(env(), ERR_get_error(), - "Failed to initialize cipher"); + return ThrowCryptoError( + env(), ERR_get_error(), "Failed to initialize cipher"); } } - void CipherBase::Init(const FunctionCallbackInfo& args) { CipherBase* cipher; ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder()); @@ -2684,8 +2560,7 @@ void CipherBase::Init(const FunctionCallbackInfo& args) { } static bool IsSupportedAuthenticatedMode(int mode) { - return mode == EVP_CIPH_CCM_MODE || - mode == EVP_CIPH_GCM_MODE || + return mode == EVP_CIPH_CCM_MODE || mode == EVP_CIPH_GCM_MODE || mode == EVP_CIPH_OCB_MODE; } @@ -2726,16 +2601,15 @@ void CipherBase::InitIv(const char* cipher_type, EVP_CIPHER_CTX_set_flags(ctx_.get(), EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); const bool encrypt = (kind_ == kCipher); - if (1 != EVP_CipherInit_ex(ctx_.get(), cipher, nullptr, - nullptr, nullptr, encrypt)) { - return ThrowCryptoError(env(), ERR_get_error(), - "Failed to initialize cipher"); + if (1 != EVP_CipherInit_ex( + ctx_.get(), cipher, nullptr, nullptr, nullptr, encrypt)) { + return ThrowCryptoError( + env(), ERR_get_error(), "Failed to initialize cipher"); } if (is_authenticated_mode) { CHECK(has_iv); - if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len)) - return; + if (!InitAuthenticated(cipher_type, iv_len, auth_tag_len)) return; } if (!EVP_CIPHER_CTX_set_key_length(ctx_.get(), key_len)) { @@ -2749,12 +2623,11 @@ void CipherBase::InitIv(const char* cipher_type, reinterpret_cast(key), reinterpret_cast(iv), encrypt)) { - return ThrowCryptoError(env(), ERR_get_error(), - "Failed to initialize cipher"); + return ThrowCryptoError( + env(), ERR_get_error(), "Failed to initialize cipher"); } } - void CipherBase::InitIv(const FunctionCallbackInfo& args) { CipherBase* cipher; ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder()); @@ -2788,20 +2661,18 @@ void CipherBase::InitIv(const FunctionCallbackInfo& args) { cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len, auth_tag_len); } - static bool IsValidGCMTagLength(unsigned int tag_len) { return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16); } -bool CipherBase::InitAuthenticated(const char* cipher_type, int iv_len, +bool CipherBase::InitAuthenticated(const char* cipher_type, + int iv_len, unsigned int auth_tag_len) { CHECK(IsAuthenticatedMode()); MarkPopErrorOnReturn mark_pop_error_on_return; - if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), - EVP_CTRL_AEAD_SET_IVLEN, - iv_len, - nullptr)) { + if (!EVP_CIPHER_CTX_ctrl( + ctx_.get(), EVP_CTRL_AEAD_SET_IVLEN, iv_len, nullptr)) { env()->ThrowError("Invalid IV length"); return false; } @@ -2824,8 +2695,8 @@ bool CipherBase::InitAuthenticated(const char* cipher_type, int iv_len, #endif // Tell OpenSSL about the desired length. - if (!EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len, - nullptr)) { + if (!EVP_CIPHER_CTX_ctrl( + ctx_.get(), EVP_CTRL_AEAD_SET_TAG, auth_tag_len, nullptr)) { env()->ThrowError("Invalid authentication tag length"); return false; } @@ -2846,8 +2717,10 @@ bool CipherBase::InitAuthenticated(const char* cipher_type, int iv_len, if (auth_tag_len != kNoAuthTagLength) { if (!IsValidGCMTagLength(auth_tag_len)) { char msg[50]; - snprintf(msg, sizeof(msg), - "Invalid authentication tag length: %u", auth_tag_len); + snprintf(msg, + sizeof(msg), + "Invalid authentication tag length: %u", + auth_tag_len); env()->ThrowError(msg); return false; } @@ -2860,7 +2733,6 @@ bool CipherBase::InitAuthenticated(const char* cipher_type, int iv_len, return true; } - bool CipherBase::CheckCCMMessageLength(int message_len) { CHECK(ctx_); CHECK(EVP_CIPHER_CTX_mode(ctx_.get()) == EVP_CIPH_CCM_MODE); @@ -2873,7 +2745,6 @@ bool CipherBase::CheckCCMMessageLength(int message_len) { return true; } - bool CipherBase::IsAuthenticatedMode() const { // Check if this cipher operates in an AEAD mode that we support. CHECK(ctx_); @@ -2881,32 +2752,28 @@ bool CipherBase::IsAuthenticatedMode() const { return IsSupportedAuthenticatedMode(mode); } - void CipherBase::GetAuthTag(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CipherBase* cipher; ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder()); // Only callable after Final and if encrypting. - if (cipher->ctx_ || - cipher->kind_ != kCipher || + if (cipher->ctx_ || cipher->kind_ != kCipher || cipher->auth_tag_len_ == kNoAuthTagLength) { return args.GetReturnValue().SetUndefined(); } Local buf = Buffer::Copy(env, cipher->auth_tag_, cipher->auth_tag_len_) - .ToLocalChecked(); + .ToLocalChecked(); args.GetReturnValue().Set(buf); } - void CipherBase::SetAuthTag(const FunctionCallbackInfo& args) { CipherBase* cipher; ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder()); - if (!cipher->ctx_ || - !cipher->IsAuthenticatedMode() || + if (!cipher->ctx_ || !cipher->IsAuthenticatedMode() || cipher->kind_ != kDecipher) { return args.GetReturnValue().Set(false); } @@ -2929,8 +2796,8 @@ void CipherBase::SetAuthTag(const FunctionCallbackInfo& args) { if (!is_valid) { char msg[50]; - snprintf(msg, sizeof(msg), - "Invalid authentication tag length: %u", tag_len); + snprintf( + msg, sizeof(msg), "Invalid authentication tag length: %u", tag_len); return cipher->env()->ThrowError(msg); } @@ -2941,10 +2808,8 @@ void CipherBase::SetAuthTag(const FunctionCallbackInfo& args) { memcpy(cipher->auth_tag_, Buffer::Data(args[0]), cipher->auth_tag_len_); } - bool CipherBase::SetAAD(const char* data, unsigned int len, int plaintext_len) { - if (!ctx_ || !IsAuthenticatedMode()) - return false; + if (!ctx_ || !IsAuthenticatedMode()) return false; MarkPopErrorOnReturn mark_pop_error_on_return; int outlen; @@ -2958,8 +2823,7 @@ bool CipherBase::SetAAD(const char* data, unsigned int len, int plaintext_len) { return false; } - if (!CheckCCMMessageLength(plaintext_len)) - return false; + if (!CheckCCMMessageLength(plaintext_len)) return false; if (kind_ == kDecipher && !auth_tag_set_ && auth_tag_len_ > 0 && auth_tag_len_ != kNoAuthTagLength) { @@ -2984,7 +2848,6 @@ bool CipherBase::SetAAD(const char* data, unsigned int len, int plaintext_len) { len); } - void CipherBase::SetAAD(const FunctionCallbackInfo& args) { CipherBase* cipher; ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder()); @@ -2993,25 +2856,22 @@ void CipherBase::SetAAD(const FunctionCallbackInfo& args) { CHECK(args[1]->IsInt32()); int plaintext_len = args[1].As()->Value(); - if (!cipher->SetAAD(Buffer::Data(args[0]), Buffer::Length(args[0]), - plaintext_len)) + if (!cipher->SetAAD( + Buffer::Data(args[0]), Buffer::Length(args[0]), plaintext_len)) args.GetReturnValue().Set(false); // Report invalid state failure } - CipherBase::UpdateResult CipherBase::Update(const char* data, int len, unsigned char** out, int* out_len) { - if (!ctx_) - return kErrorState; + if (!ctx_) return kErrorState; MarkPopErrorOnReturn mark_pop_error_on_return; const int mode = EVP_CIPHER_CTX_mode(ctx_.get()); if (mode == EVP_CIPH_CCM_MODE) { - if (!CheckCCMMessageLength(len)) - return kErrorMessageSize; + if (!CheckCCMMessageLength(len)) return kErrorMessageSize; } // on first update: @@ -3055,7 +2915,6 @@ CipherBase::UpdateResult CipherBase::Update(const char* data, return r == 1 ? kSuccess : kErrorState; } - void CipherBase::Update(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3069,8 +2928,7 @@ void CipherBase::Update(const FunctionCallbackInfo& args) { // Only copy the data if we have to, because it's a string if (args[0]->IsString()) { StringBytes::InlineDecoder decoder; - if (!decoder.Decode(env, args[0].As(), args[1], UTF8)) - return; + if (!decoder.Decode(env, args[0].As(), args[1], UTF8)) return; r = cipher->Update(decoder.out(), decoder.size(), &out, &out_len); } else { char* buf = Buffer::Data(args[0]); @@ -3081,8 +2939,8 @@ void CipherBase::Update(const FunctionCallbackInfo& args) { if (r != kSuccess) { free(out); if (r == kErrorState) { - ThrowCryptoError(env, ERR_get_error(), - "Trying to add data in unsupported state"); + ThrowCryptoError( + env, ERR_get_error(), "Trying to add data in unsupported state"); } return; } @@ -3094,15 +2952,12 @@ void CipherBase::Update(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(buf); } - bool CipherBase::SetAutoPadding(bool auto_padding) { - if (!ctx_) - return false; + if (!ctx_) return false; MarkPopErrorOnReturn mark_pop_error_on_return; return EVP_CIPHER_CTX_set_padding(ctx_.get(), auto_padding); } - void CipherBase::SetAutoPadding(const FunctionCallbackInfo& args) { CipherBase* cipher; ASSIGN_OR_RETURN_UNWRAP(&cipher, args.Holder()); @@ -3111,10 +2966,8 @@ void CipherBase::SetAutoPadding(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(false); // Report invalid state failure } - bool CipherBase::Final(unsigned char** out, int* out_len) { - if (!ctx_) - return false; + if (!ctx_) return false; const int mode = EVP_CIPHER_CTX_mode(ctx_.get()); @@ -3137,9 +2990,12 @@ bool CipherBase::Final(unsigned char** out, int* out_len) { CHECK(mode == EVP_CIPH_GCM_MODE); auth_tag_len_ = sizeof(auth_tag_); } - CHECK_EQ(1, EVP_CIPHER_CTX_ctrl(ctx_.get(), EVP_CTRL_AEAD_GET_TAG, - auth_tag_len_, - reinterpret_cast(auth_tag_))); + CHECK_EQ( + 1, + EVP_CIPHER_CTX_ctrl(ctx_.get(), + EVP_CTRL_AEAD_GET_TAG, + auth_tag_len_, + reinterpret_cast(auth_tag_))); } } @@ -3148,7 +3004,6 @@ bool CipherBase::Final(unsigned char** out, int* out_len) { return ok; } - void CipherBase::Final(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3168,24 +3023,20 @@ void CipherBase::Final(const FunctionCallbackInfo& args) { out_value = nullptr; out_len = 0; if (!r) { - const char* msg = is_auth_mode ? - "Unsupported state or unable to authenticate data" : - "Unsupported state"; + const char* msg = is_auth_mode + ? "Unsupported state or unable to authenticate data" + : "Unsupported state"; - return ThrowCryptoError(env, - ERR_get_error(), - msg); + return ThrowCryptoError(env, ERR_get_error(), msg); } } - Local buf = Buffer::New( - env, - reinterpret_cast(out_value), - out_len).ToLocalChecked(); + Local buf = + Buffer::New(env, reinterpret_cast(out_value), out_len) + .ToLocalChecked(); args.GetReturnValue().Set(buf); } - void Hmac::Initialize(Environment* env, v8::Local target) { Local t = env->NewFunctionTemplate(New); @@ -3198,13 +3049,11 @@ void Hmac::Initialize(Environment* env, v8::Local target) { target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hmac"), t->GetFunction()); } - void Hmac::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); new Hmac(env, args.This()); } - void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) { HandleScope scope(env()->isolate()); @@ -3222,7 +3071,6 @@ void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) { } } - void Hmac::HmacInit(const FunctionCallbackInfo& args) { Hmac* hmac; ASSIGN_OR_RETURN_UNWRAP(&hmac, args.Holder()); @@ -3234,17 +3082,13 @@ void Hmac::HmacInit(const FunctionCallbackInfo& args) { hmac->HmacInit(*hash_type, buffer_data, buffer_length); } - bool Hmac::HmacUpdate(const char* data, int len) { - if (!ctx_) - return false; - int r = HMAC_Update(ctx_.get(), - reinterpret_cast(data), - len); + if (!ctx_) return false; + int r = HMAC_Update( + ctx_.get(), reinterpret_cast(data), len); return r == 1; } - void Hmac::HmacUpdate(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3269,7 +3113,6 @@ void Hmac::HmacUpdate(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(r); } - void Hmac::HmacDigest(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3305,7 +3148,6 @@ void Hmac::HmacDigest(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(rc.ToLocalChecked()); } - void Hash::Initialize(Environment* env, v8::Local target) { Local t = env->NewFunctionTemplate(New); @@ -3317,7 +3159,6 @@ void Hash::Initialize(Environment* env, v8::Local target) { target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hash"), t->GetFunction()); } - void Hash::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3325,16 +3166,14 @@ void Hash::New(const FunctionCallbackInfo& args) { Hash* hash = new Hash(env, args.This()); if (!hash->HashInit(*hash_type)) { - return ThrowCryptoError(env, ERR_get_error(), - "Digest method not supported"); + return ThrowCryptoError( + env, ERR_get_error(), "Digest method not supported"); } } - bool Hash::HashInit(const char* hash_type) { const EVP_MD* md = EVP_get_digestbyname(hash_type); - if (md == nullptr) - return false; + if (md == nullptr) return false; mdctx_.reset(EVP_MD_CTX_new()); if (!mdctx_ || EVP_DigestInit_ex(mdctx_.get(), md, nullptr) <= 0) { mdctx_.reset(); @@ -3344,15 +3183,12 @@ bool Hash::HashInit(const char* hash_type) { return true; } - bool Hash::HashUpdate(const char* data, int len) { - if (!mdctx_) - return false; + if (!mdctx_) return false; EVP_DigestUpdate(mdctx_.get(), data, len); return true; } - void Hash::HashUpdate(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3377,7 +3213,6 @@ void Hash::HashUpdate(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(r); } - void Hash::HashDigest(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3410,18 +3245,15 @@ void Hash::HashDigest(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(rc.ToLocalChecked()); } - SignBase::Error SignBase::Init(const char* sign_type) { CHECK_NULL(mdctx_); // Historically, "dss1" and "DSS1" were DSA aliases for SHA-1 // exposed through the public API. - if (strcmp(sign_type, "dss1") == 0 || - strcmp(sign_type, "DSS1") == 0) { + if (strcmp(sign_type, "dss1") == 0 || strcmp(sign_type, "DSS1") == 0) { sign_type = "SHA1"; } const EVP_MD* md = EVP_get_digestbyname(sign_type); - if (md == nullptr) - return kSignUnknownDigest; + if (md == nullptr) return kSignUnknownDigest; mdctx_.reset(EVP_MD_CTX_new()); if (!mdctx_ || !EVP_DigestInit_ex(mdctx_.get(), md, nullptr)) { @@ -3432,16 +3264,12 @@ SignBase::Error SignBase::Init(const char* sign_type) { return kSignOk; } - SignBase::Error SignBase::Update(const char* data, int len) { - if (mdctx_ == nullptr) - return kSignNotInitialised; - if (!EVP_DigestUpdate(mdctx_.get(), data, len)) - return kSignUpdate; + if (mdctx_ == nullptr) return kSignNotInitialised; + if (!EVP_DigestUpdate(mdctx_.get(), data, len)) return kSignUpdate; return kSignOk; } - void SignBase::CheckThrow(SignBase::Error error) { HandleScope scope(env()->isolate()); @@ -3455,24 +3283,22 @@ void SignBase::CheckThrow(SignBase::Error error) { case kSignInit: case kSignUpdate: case kSignPrivateKey: - case kSignPublicKey: - { - unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (err) - return ThrowCryptoError(env(), err); - switch (error) { - case kSignInit: - return env()->ThrowError("EVP_SignInit_ex failed"); - case kSignUpdate: - return env()->ThrowError("EVP_SignUpdate failed"); - case kSignPrivateKey: - return env()->ThrowError("PEM_read_bio_PrivateKey failed"); - case kSignPublicKey: - return env()->ThrowError("PEM_read_bio_PUBKEY failed"); - default: - ABORT(); - } + case kSignPublicKey: { + unsigned long err = ERR_get_error(); // NOLINT(runtime/int) + if (err) return ThrowCryptoError(env(), err); + switch (error) { + case kSignInit: + return env()->ThrowError("EVP_SignInit_ex failed"); + case kSignUpdate: + return env()->ThrowError("EVP_SignUpdate failed"); + case kSignPrivateKey: + return env()->ThrowError("PEM_read_bio_PrivateKey failed"); + case kSignPublicKey: + return env()->ThrowError("PEM_read_bio_PUBKEY failed"); + default: + ABORT(); } + } case kSignOk: return; @@ -3485,19 +3311,15 @@ static bool ApplyRSAOptions(const EVPKeyPointer& pkey, int salt_len) { if (EVP_PKEY_id(pkey.get()) == EVP_PKEY_RSA || EVP_PKEY_id(pkey.get()) == EVP_PKEY_RSA2) { - if (EVP_PKEY_CTX_set_rsa_padding(pkctx, padding) <= 0) - return false; + if (EVP_PKEY_CTX_set_rsa_padding(pkctx, padding) <= 0) return false; if (padding == RSA_PKCS1_PSS_PADDING) { - if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, salt_len) <= 0) - return false; + if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, salt_len) <= 0) return false; } } return true; } - - void Sign::Initialize(Environment* env, v8::Local target) { Local t = env->NewFunctionTemplate(New); @@ -3510,13 +3332,11 @@ void Sign::Initialize(Environment* env, v8::Local target) { target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Sign"), t->GetFunction()); } - void Sign::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); new Sign(env, args.This()); } - void Sign::SignInit(const FunctionCallbackInfo& args) { Sign* sign; ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder()); @@ -3525,7 +3345,6 @@ void Sign::SignInit(const FunctionCallbackInfo& args) { sign->CheckThrow(sign->Init(*sign_type)); } - void Sign::SignUpdate(const FunctionCallbackInfo& args) { Sign* sign; ASSIGN_OR_RETURN_UNWRAP(&sign, args.Holder()); @@ -3538,24 +3357,24 @@ void Sign::SignUpdate(const FunctionCallbackInfo& args) { sign->CheckThrow(err); } -static int Node_SignFinal(EVPMDPointer&& mdctx, unsigned char* md, +static int Node_SignFinal(EVPMDPointer&& mdctx, + unsigned char* md, unsigned int* sig_len, - const EVPKeyPointer& pkey, int padding, + const EVPKeyPointer& pkey, + int padding, int pss_salt_len) { unsigned char m[EVP_MAX_MD_SIZE]; unsigned int m_len; *sig_len = 0; - if (!EVP_DigestFinal_ex(mdctx.get(), m, &m_len)) - return 0; + if (!EVP_DigestFinal_ex(mdctx.get(), m, &m_len)) return 0; size_t sltmp = static_cast(EVP_PKEY_size(pkey.get())); EVPKeyCtxPointer pkctx(EVP_PKEY_CTX_new(pkey.get(), nullptr)); - if (pkctx && - EVP_PKEY_sign_init(pkctx.get()) > 0 && + if (pkctx && EVP_PKEY_sign_init(pkctx.get()) > 0 && ApplyRSAOptions(pkey, pkctx.get(), padding, pss_salt_len) && - EVP_PKEY_CTX_set_signature_md(pkctx.get(), - EVP_MD_CTX_md(mdctx.get())) > 0 && + EVP_PKEY_CTX_set_signature_md(pkctx.get(), EVP_MD_CTX_md(mdctx.get())) > + 0 && EVP_PKEY_sign(pkctx.get(), md, &sltmp, m, m_len) > 0) { *sig_len = sltmp; return 1; @@ -3570,25 +3389,20 @@ SignBase::Error Sign::SignFinal(const char* key_pem, unsigned int* sig_len, int padding, int salt_len) { - if (!mdctx_) - return kSignNotInitialised; + if (!mdctx_) return kSignNotInitialised; EVPMDPointer mdctx = std::move(mdctx_); BIOPointer bp(BIO_new_mem_buf(const_cast(key_pem), key_pem_len)); - if (!bp) - return kSignPrivateKey; + if (!bp) return kSignPrivateKey; - EVPKeyPointer pkey(PEM_read_bio_PrivateKey(bp.get(), - nullptr, - PasswordCallback, - const_cast(passphrase))); + EVPKeyPointer pkey(PEM_read_bio_PrivateKey( + bp.get(), nullptr, PasswordCallback, const_cast(passphrase))); // Errors might be injected into OpenSSL's error stack // without `pkey` being set to nullptr; // cf. the test of `test_bad_rsa_privkey.pem` for an example. - if (!pkey || 0 != ERR_peek_error()) - return kSignPrivateKey; + if (!pkey || 0 != ERR_peek_error()) return kSignPrivateKey; #ifdef NODE_FIPS_MODE /* Validate DSA2 parameters from FIPS 186-4 */ @@ -3618,7 +3432,6 @@ SignBase::Error Sign::SignFinal(const char* key_pem, return kSignPrivateKey; } - void Sign::SignFinal(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3646,24 +3459,22 @@ void Sign::SignFinal(const FunctionCallbackInfo& args) { unsigned char md_value[8192]; unsigned int md_len = sizeof(md_value); - Error err = sign->SignFinal( - buf, - buf_len, - len >= 2 && !args[1]->IsNull() ? *passphrase : nullptr, - md_value, - &md_len, - padding, - salt_len); - if (err != kSignOk) - return sign->CheckThrow(err); + Error err = + sign->SignFinal(buf, + buf_len, + len >= 2 && !args[1]->IsNull() ? *passphrase : nullptr, + md_value, + &md_len, + padding, + salt_len); + if (err != kSignOk) return sign->CheckThrow(err); Local rc = Buffer::Copy(env, reinterpret_cast(md_value), md_len) - .ToLocalChecked(); + .ToLocalChecked(); args.GetReturnValue().Set(rc); } - void Verify::Initialize(Environment* env, v8::Local target) { Local t = env->NewFunctionTemplate(New); @@ -3677,13 +3488,11 @@ void Verify::Initialize(Environment* env, v8::Local target) { t->GetFunction()); } - void Verify::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); new Verify(env, args.This()); } - void Verify::VerifyInit(const FunctionCallbackInfo& args) { Verify* verify; ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder()); @@ -3692,7 +3501,6 @@ void Verify::VerifyInit(const FunctionCallbackInfo& args) { verify->CheckThrow(verify->Init(*verify_type)); } - void Verify::VerifyUpdate(const FunctionCallbackInfo& args) { Verify* verify; ASSIGN_OR_RETURN_UNWRAP(&verify, args.Holder()); @@ -3705,7 +3513,6 @@ void Verify::VerifyUpdate(const FunctionCallbackInfo& args) { verify->CheckThrow(err); } - SignBase::Error Verify::VerifyFinal(const char* key_pem, int key_pem_len, const char* sig, @@ -3713,8 +3520,7 @@ SignBase::Error Verify::VerifyFinal(const char* key_pem, int padding, int saltlen, bool* verify_result) { - if (!mdctx_) - return kSignNotInitialised; + if (!mdctx_) return kSignNotInitialised; EVPKeyPointer pkey; unsigned char m[EVP_MAX_MD_SIZE]; @@ -3724,8 +3530,7 @@ SignBase::Error Verify::VerifyFinal(const char* key_pem, EVPMDPointer mdctx = std::move(mdctx_); BIOPointer bp(BIO_new_mem_buf(const_cast(key_pem), key_pem_len)); - if (!bp) - return kSignPublicKey; + if (!bp) return kSignPublicKey; // Check if this is a PKCS#8 or RSA public key before trying as X.509. // Split this out into a separate function once we have more than one @@ -3738,30 +3543,25 @@ SignBase::Error Verify::VerifyFinal(const char* key_pem, bp.get(), nullptr, PasswordCallback, nullptr)); if (rsa) { pkey.reset(EVP_PKEY_new()); - if (pkey) - EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); + if (pkey) EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); } } else { // X.509 fallback - X509Pointer x509(PEM_read_bio_X509( - bp.get(), nullptr, NoPasswordCallback, nullptr)); - if (!x509) - return kSignPublicKey; + X509Pointer x509( + PEM_read_bio_X509(bp.get(), nullptr, NoPasswordCallback, nullptr)); + if (!x509) return kSignPublicKey; pkey.reset(X509_get_pubkey(x509.get())); } - if (!pkey) - return kSignPublicKey; + if (!pkey) return kSignPublicKey; - if (!EVP_DigestFinal_ex(mdctx.get(), m, &m_len)) - return kSignPublicKey; + if (!EVP_DigestFinal_ex(mdctx.get(), m, &m_len)) return kSignPublicKey; EVPKeyCtxPointer pkctx(EVP_PKEY_CTX_new(pkey.get(), nullptr)); - if (pkctx && - EVP_PKEY_verify_init(pkctx.get()) > 0 && + if (pkctx && EVP_PKEY_verify_init(pkctx.get()) > 0 && ApplyRSAOptions(pkey, pkctx.get(), padding, saltlen) && - EVP_PKEY_CTX_set_signature_md(pkctx.get(), - EVP_MD_CTX_md(mdctx.get())) > 0) { + EVP_PKEY_CTX_set_signature_md(pkctx.get(), EVP_MD_CTX_md(mdctx.get())) > + 0) { r = EVP_PKEY_verify(pkctx.get(), reinterpret_cast(sig), siglen, @@ -3773,7 +3573,6 @@ SignBase::Error Verify::VerifyFinal(const char* key_pem, return kSignOk; } - void Verify::VerifyFinal(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -3799,14 +3598,12 @@ void Verify::VerifyFinal(const FunctionCallbackInfo& args) { int salt_len = maybe_salt_len.ToChecked(); bool verify_result; - Error err = verify->VerifyFinal(kbuf, klen, hbuf, hlen, padding, salt_len, - &verify_result); - if (err != kSignOk) - return verify->CheckThrow(err); + Error err = verify->VerifyFinal( + kbuf, klen, hbuf, hlen, padding, salt_len, &verify_result); + if (err != kSignOk) return verify->CheckThrow(err); args.GetReturnValue().Set(verify_result); } - template @@ -3821,8 +3618,7 @@ bool PublicKeyCipher::Cipher(const char* key_pem, EVPKeyPointer pkey; BIOPointer bp(BIO_new_mem_buf(const_cast(key_pem), key_pem_len)); - if (!bp) - return false; + if (!bp) return false; // Check if this is a PKCS#8 or RSA public key before trying as X.509 and // private key. @@ -3835,46 +3631,36 @@ bool PublicKeyCipher::Cipher(const char* key_pem, PEM_read_bio_RSAPublicKey(bp.get(), nullptr, nullptr, nullptr)); if (rsa) { pkey.reset(EVP_PKEY_new()); - if (pkey) - EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); + if (pkey) EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); } } else if (operation == kPublic && strncmp(key_pem, CERTIFICATE_PFX, CERTIFICATE_PFX_LEN) == 0) { X509Pointer x509( PEM_read_bio_X509(bp.get(), nullptr, NoPasswordCallback, nullptr)); - if (!x509) - return false; + if (!x509) return false; pkey.reset(X509_get_pubkey(x509.get())); } else { - pkey.reset(PEM_read_bio_PrivateKey(bp.get(), - nullptr, - PasswordCallback, - const_cast(passphrase))); + pkey.reset(PEM_read_bio_PrivateKey( + bp.get(), nullptr, PasswordCallback, const_cast(passphrase))); } - if (!pkey) - return false; + if (!pkey) return false; EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(pkey.get(), nullptr)); - if (!ctx) - return false; - if (EVP_PKEY_cipher_init(ctx.get()) <= 0) - return false; - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0) - return false; + if (!ctx) return false; + if (EVP_PKEY_cipher_init(ctx.get()) <= 0) return false; + if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0) return false; if (EVP_PKEY_cipher(ctx.get(), nullptr, out_len, data, len) <= 0) return false; *out = Malloc(*out_len); - if (EVP_PKEY_cipher(ctx.get(), *out, out_len, data, len) <= 0) - return false; + if (EVP_PKEY_cipher(ctx.get(), *out, out_len, data, len) <= 0) return false; return true; } - template @@ -3913,18 +3699,16 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo& args) { out_value = nullptr; out_len = 0; if (!r) { - return ThrowCryptoError(env, - ERR_get_error()); + return ThrowCryptoError(env, ERR_get_error()); } } Local vbuf = Buffer::New(env, reinterpret_cast(out_value), out_len) - .ToLocalChecked(); + .ToLocalChecked(); args.GetReturnValue().Set(vbuf); } - void DiffieHellman::Initialize(Environment* env, Local target) { Local t = env->NewFunctionTemplate(New); @@ -3952,11 +3736,10 @@ void DiffieHellman::Initialize(Environment* env, Local target) { ConstructorBehavior::kAllow, SideEffectType::kHasNoSideEffect); - t->InstanceTemplate()->SetAccessorProperty( - env->verify_error_string(), - verify_error_getter_templ, - Local(), - attributes); + t->InstanceTemplate()->SetAccessorProperty(env->verify_error_string(), + verify_error_getter_templ, + Local(), + attributes); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellman"), t->GetFunction()); @@ -3981,48 +3764,40 @@ void DiffieHellman::Initialize(Environment* env, Local target) { ConstructorBehavior::kAllow, SideEffectType::kHasNoSideEffect); - t2->InstanceTemplate()->SetAccessorProperty( - env->verify_error_string(), - verify_error_getter_templ2, - Local(), - attributes); + t2->InstanceTemplate()->SetAccessorProperty(env->verify_error_string(), + verify_error_getter_templ2, + Local(), + attributes); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"), t2->GetFunction()); } - bool DiffieHellman::Init(int primeLength, int g) { dh_.reset(DH_new()); - if (!DH_generate_parameters_ex(dh_.get(), primeLength, g, 0)) - return false; + if (!DH_generate_parameters_ex(dh_.get(), primeLength, g, 0)) return false; bool result = VerifyContext(); - if (!result) - return false; + if (!result) return false; initialised_ = true; return true; } - bool DiffieHellman::Init(const char* p, int p_len, int g) { dh_.reset(DH_new()); BIGNUM* bn_p = BN_bin2bn(reinterpret_cast(p), p_len, nullptr); BIGNUM* bn_g = BN_new(); - if (!BN_set_word(bn_g, g) || - !DH_set0_pqg(dh_.get(), bn_p, nullptr, bn_g)) { + if (!BN_set_word(bn_g, g) || !DH_set0_pqg(dh_.get(), bn_p, nullptr, bn_g)) { BN_free(bn_p); BN_free(bn_g); return false; } bool result = VerifyContext(); - if (!result) - return false; + if (!result) return false; initialised_ = true; return true; } - bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) { dh_.reset(DH_new()); BIGNUM* bn_p = BN_bin2bn(reinterpret_cast(p), p_len, 0); @@ -4033,13 +3808,11 @@ bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) { return false; } bool result = VerifyContext(); - if (!result) - return false; + if (!result) return false; initialised_ = true; return true; } - void DiffieHellman::DiffieHellmanGroup( const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4057,33 +3830,27 @@ void DiffieHellman::DiffieHellmanGroup( for (size_t i = 0; i < arraysize(modp_groups); ++i) { const modp_group* it = modp_groups + i; - if (!StringEqualNoCase(*group_name, it->name)) - continue; + if (!StringEqualNoCase(*group_name, it->name)) continue; - initialized = diffieHellman->Init(it->prime, - it->prime_size, - it->gen, - it->gen_size); - if (!initialized) - env->ThrowError("Initialization failed"); + initialized = + diffieHellman->Init(it->prime, it->prime_size, it->gen, it->gen_size); + if (!initialized) env->ThrowError("Initialization failed"); return; } env->ThrowError("Unknown group"); } - void DiffieHellman::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - DiffieHellman* diffieHellman = - new DiffieHellman(env, args.This()); + DiffieHellman* diffieHellman = new DiffieHellman(env, args.This()); bool initialized = false; if (args.Length() == 2) { if (args[0]->IsInt32()) { if (args[1]->IsInt32()) { - initialized = diffieHellman->Init(args[0]->Int32Value(), - args[1]->Int32Value()); + initialized = + diffieHellman->Init(args[0]->Int32Value(), args[1]->Int32Value()); } } else { if (args[1]->IsInt32()) { @@ -4104,7 +3871,6 @@ void DiffieHellman::New(const FunctionCallbackInfo& args) { } } - void DiffieHellman::GenerateKeys(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4127,7 +3893,6 @@ void DiffieHellman::GenerateKeys(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked()); } - void DiffieHellman::GetField(const FunctionCallbackInfo& args, const BIGNUM* (*get_field)(const DH*), const char* err_if_null) { @@ -4147,41 +3912,45 @@ void DiffieHellman::GetField(const FunctionCallbackInfo& args, } void DiffieHellman::GetPrime(const FunctionCallbackInfo& args) { - GetField(args, [](const DH* dh) -> const BIGNUM* { - const BIGNUM* p; - DH_get0_pqg(dh, &p, nullptr, nullptr); - return p; - }, "p is null"); + GetField(args, + [](const DH* dh) -> const BIGNUM* { + const BIGNUM* p; + DH_get0_pqg(dh, &p, nullptr, nullptr); + return p; + }, + "p is null"); } - void DiffieHellman::GetGenerator(const FunctionCallbackInfo& args) { - GetField(args, [](const DH* dh) -> const BIGNUM* { - const BIGNUM* g; - DH_get0_pqg(dh, nullptr, nullptr, &g); - return g; - }, "g is null"); + GetField(args, + [](const DH* dh) -> const BIGNUM* { + const BIGNUM* g; + DH_get0_pqg(dh, nullptr, nullptr, &g); + return g; + }, + "g is null"); } - void DiffieHellman::GetPublicKey(const FunctionCallbackInfo& args) { - GetField(args, [](const DH* dh) -> const BIGNUM* { - const BIGNUM* pub_key; - DH_get0_key(dh, &pub_key, nullptr); - return pub_key; - }, "No public key - did you forget to generate one?"); + GetField(args, + [](const DH* dh) -> const BIGNUM* { + const BIGNUM* pub_key; + DH_get0_key(dh, &pub_key, nullptr); + return pub_key; + }, + "No public key - did you forget to generate one?"); } - void DiffieHellman::GetPrivateKey(const FunctionCallbackInfo& args) { - GetField(args, [](const DH* dh) -> const BIGNUM* { - const BIGNUM* priv_key; - DH_get0_key(dh, nullptr, &priv_key); - return priv_key; - }, "No private key - did you forget to generate one?"); + GetField(args, + [](const DH* dh) -> const BIGNUM* { + const BIGNUM* priv_key; + DH_get0_key(dh, nullptr, &priv_key); + return priv_key; + }, + "No private key - did you forget to generate one?"); } - void DiffieHellman::ComputeSecret(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4200,10 +3969,10 @@ void DiffieHellman::ComputeSecret(const FunctionCallbackInfo& args) { } THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Other party's public key"); - BignumPointer key(BN_bin2bn( - reinterpret_cast(Buffer::Data(args[0])), - Buffer::Length(args[0]), - 0)); + BignumPointer key( + BN_bin2bn(reinterpret_cast(Buffer::Data(args[0])), + Buffer::Length(args[0]), + 0)); MallocedBuffer data(DH_size(diffieHellman->dh_.get())); @@ -4215,9 +3984,8 @@ void DiffieHellman::ComputeSecret(const FunctionCallbackInfo& args) { int checkResult; int checked; - checked = DH_check_pub_key(diffieHellman->dh_.get(), - key.get(), - &checkResult); + checked = + DH_check_pub_key(diffieHellman->dh_.get(), key.get(), &checkResult); if (!checked) { return ThrowCryptoError(env, ERR_get_error(), "Invalid Key"); @@ -4253,7 +4021,8 @@ void DiffieHellman::ComputeSecret(const FunctionCallbackInfo& args) { } void DiffieHellman::SetKey(const v8::FunctionCallbackInfo& args, - int (*set_field)(DH*, BIGNUM*), const char* what) { + int (*set_field)(DH*, BIGNUM*), + const char* what) { Environment* env = Environment::GetCurrent(args); DiffieHellman* dh; @@ -4274,12 +4043,12 @@ void DiffieHellman::SetKey(const v8::FunctionCallbackInfo& args, BIGNUM* num = BN_bin2bn(reinterpret_cast(Buffer::Data(args[0])), - Buffer::Length(args[0]), nullptr); + Buffer::Length(args[0]), + nullptr); CHECK_NOT_NULL(num); CHECK_EQ(1, set_field(dh->dh_.get(), num)); } - void DiffieHellman::SetPublicKey(const FunctionCallbackInfo& args) { SetKey(args, [](DH* dh, BIGNUM* num) { return DH_set0_key(dh, num, nullptr); }, @@ -4287,7 +4056,7 @@ void DiffieHellman::SetPublicKey(const FunctionCallbackInfo& args) { } void DiffieHellman::SetPrivateKey(const FunctionCallbackInfo& args) { -#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ OPENSSL_VERSION_NUMBER < 0x10100070L // Older versions of OpenSSL 1.1.0 have a DH_set0_key which does not work for // Node. See https://github.com/openssl/openssl/pull/4384. @@ -4298,7 +4067,6 @@ void DiffieHellman::SetPrivateKey(const FunctionCallbackInfo& args) { "Private key"); } - void DiffieHellman::VerifyErrorGetter(const FunctionCallbackInfo& args) { HandleScope scope(args.GetIsolate()); @@ -4306,22 +4074,19 @@ void DiffieHellman::VerifyErrorGetter(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&diffieHellman, args.Holder()); if (!diffieHellman->initialised_) - return ThrowCryptoError(diffieHellman->env(), ERR_get_error(), - "Not initialized"); + return ThrowCryptoError( + diffieHellman->env(), ERR_get_error(), "Not initialized"); args.GetReturnValue().Set(diffieHellman->verifyError_); } - bool DiffieHellman::VerifyContext() { int codes; - if (!DH_check(dh_.get(), &codes)) - return false; + if (!DH_check(dh_.get(), &codes)) return false; verifyError_ = codes; return true; } - void ECDH::Initialize(Environment* env, Local target) { HandleScope scope(env->isolate()); @@ -4336,11 +4101,9 @@ void ECDH::Initialize(Environment* env, Local target) { env->SetProtoMethod(t, "setPublicKey", SetPublicKey); env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey); - target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"), - t->GetFunction()); + target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH"), t->GetFunction()); } - void ECDH::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4352,17 +4115,15 @@ void ECDH::New(const FunctionCallbackInfo& args) { int nid = OBJ_sn2nid(*curve); if (nid == NID_undef) - return THROW_ERR_INVALID_ARG_VALUE(env, - "First argument should be a valid curve name"); + return THROW_ERR_INVALID_ARG_VALUE( + env, "First argument should be a valid curve name"); ECKeyPointer key(EC_KEY_new_by_curve_name(nid)); - if (!key) - return env->ThrowError("Failed to create EC_KEY using curve name"); + if (!key) return env->ThrowError("Failed to create EC_KEY using curve name"); new ECDH(env, args.This(), std::move(key)); } - void ECDH::GenerateKeys(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4373,7 +4134,6 @@ void ECDH::GenerateKeys(const FunctionCallbackInfo& args) { return env->ThrowError("Failed to generate EC_KEY"); } - ECPointPointer ECDH::BufferToPoint(Environment* env, const EC_GROUP* group, char* data, @@ -4387,18 +4147,12 @@ ECPointPointer ECDH::BufferToPoint(Environment* env, } r = EC_POINT_oct2point( - group, - pub.get(), - reinterpret_cast(data), - len, - nullptr); - if (!r) - return ECPointPointer(); + group, pub.get(), reinterpret_cast(data), len, nullptr); + if (!r) return ECPointPointer(); return pub; } - void ECDH::ComputeSecret(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4409,18 +4163,13 @@ void ECDH::ComputeSecret(const FunctionCallbackInfo& args) { MarkPopErrorOnReturn mark_pop_error_on_return; - if (!ecdh->IsKeyPairValid()) - return env->ThrowError("Invalid key pair"); + if (!ecdh->IsKeyPairValid()) return env->ThrowError("Invalid key pair"); - ECPointPointer pub( - ECDH::BufferToPoint(env, - ecdh->group_, - Buffer::Data(args[0]), - Buffer::Length(args[0]))); + ECPointPointer pub(ECDH::BufferToPoint( + env, ecdh->group_, Buffer::Data(args[0]), Buffer::Length(args[0]))); if (!pub) { - args.GetReturnValue().Set( - FIXED_ONE_BYTE_STRING(env->isolate(), - "ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY")); + args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING( + env->isolate(), "ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY")); return; } @@ -4439,7 +4188,6 @@ void ECDH::ComputeSecret(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(buf); } - void ECDH::GetPublicKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4450,16 +4198,14 @@ void ECDH::GetPublicKey(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder()); const EC_POINT* pub = EC_KEY_get0_public_key(ecdh->key_.get()); - if (pub == nullptr) - return env->ThrowError("Failed to get ECDH public key"); + if (pub == nullptr) return env->ThrowError("Failed to get ECDH public key"); int size; point_conversion_form_t form = static_cast(args[0]->Uint32Value()); size = EC_POINT_point2oct(ecdh->group_, pub, form, nullptr, 0, nullptr); - if (size == 0) - return env->ThrowError("Failed to get public key length"); + if (size == 0) return env->ThrowError("Failed to get public key length"); unsigned char* out = node::Malloc(size); @@ -4474,7 +4220,6 @@ void ECDH::GetPublicKey(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(buf); } - void ECDH::GetPrivateKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4482,8 +4227,7 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&ecdh, args.Holder()); const BIGNUM* b = EC_KEY_get0_private_key(ecdh->key_.get()); - if (b == nullptr) - return env->ThrowError("Failed to get ECDH private key"); + if (b == nullptr) return env->ThrowError("Failed to get ECDH private key"); int size = BN_num_bytes(b); unsigned char* out = node::Malloc(size); @@ -4498,7 +4242,6 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(buf); } - void ECDH::SetPrivateKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4511,8 +4254,7 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo& args) { reinterpret_cast(Buffer::Data(args[0].As())), Buffer::Length(args[0].As()), nullptr)); - if (!priv) - return env->ThrowError("Failed to convert Buffer to BN"); + if (!priv) return env->ThrowError("Failed to convert Buffer to BN"); if (!ecdh->IsKeyValidForCurve(priv)) { return env->ThrowError("Private key is not valid for specified curve."); @@ -4538,8 +4280,8 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo& args) { ECPointPointer pub(EC_POINT_new(ecdh->group_)); CHECK(pub); - if (!EC_POINT_mul(ecdh->group_, pub.get(), priv_key, - nullptr, nullptr, nullptr)) { + if (!EC_POINT_mul( + ecdh->group_, pub.get(), priv_key, nullptr, nullptr, nullptr)) { return env->ThrowError("Failed to generate ECDH public key"); } @@ -4547,7 +4289,6 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo& args) { return env->ThrowError("Failed to set generated public key"); } - void ECDH::SetPublicKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4558,20 +4299,16 @@ void ECDH::SetPublicKey(const FunctionCallbackInfo& args) { MarkPopErrorOnReturn mark_pop_error_on_return; - ECPointPointer pub( - ECDH::BufferToPoint(env, - ecdh->group_, - Buffer::Data(args[0].As()), - Buffer::Length(args[0].As()))); - if (!pub) - return env->ThrowError("Failed to convert Buffer to EC_POINT"); + ECPointPointer pub(ECDH::BufferToPoint(env, + ecdh->group_, + Buffer::Data(args[0].As()), + Buffer::Length(args[0].As()))); + if (!pub) return env->ThrowError("Failed to convert Buffer to EC_POINT"); int r = EC_KEY_set_public_key(ecdh->key_.get(), pub.get()); - if (!r) - return env->ThrowError("Failed to set EC_POINT as the public key"); + if (!r) return env->ThrowError("Failed to set EC_POINT as the public key"); } - bool ECDH::IsKeyValidForCurve(const BignumPointer& private_key) { CHECK(group_); CHECK(private_key); @@ -4586,14 +4323,12 @@ bool ECDH::IsKeyValidForCurve(const BignumPointer& private_key) { BN_cmp(private_key.get(), order.get()) < 0; } - bool ECDH::IsKeyPairValid() { MarkPopErrorOnReturn mark_pop_error_on_return; USE(&mark_pop_error_on_return); return 1 == EC_KEY_check_key(key_.get()); } - // TODO(addaleax): If there is an `AsyncWrap`, it currently has no access to // this object. This makes proper reporting of memory usage impossible. struct CryptoJob : public ThreadPoolWork { @@ -4605,7 +4340,6 @@ struct CryptoJob : public ThreadPoolWork { static inline void Run(std::unique_ptr job, Local wrap); }; - void CryptoJob::AfterThreadPoolWork(int status) { CHECK(status == 0 || status == UV_ECANCELED); std::unique_ptr job(this); @@ -4616,7 +4350,6 @@ void CryptoJob::AfterThreadPoolWork(int status) { AfterThreadPoolWork(); } - void CryptoJob::Run(std::unique_ptr job, Local wrap) { CHECK(wrap->IsObject()); CHECK_EQ(nullptr, job->async_wrap); @@ -4626,13 +4359,11 @@ void CryptoJob::Run(std::unique_ptr job, Local wrap) { job.release(); // Run free, little job! } - inline void CopyBuffer(Local buf, std::vector* vec) { vec->clear(); if (auto p = Buffer::Data(buf)) vec->assign(p, p + Buffer::Length(buf)); } - struct RandomBytesJob : public CryptoJob { unsigned char* data; size_t size; @@ -4659,15 +4390,14 @@ struct RandomBytesJob : public CryptoJob { } }; - void RandomBytes(const FunctionCallbackInfo& args) { CHECK(args[0]->IsArrayBufferView()); // buffer; wrap object retains ref. - CHECK(args[1]->IsUint32()); // offset - CHECK(args[2]->IsUint32()); // size + CHECK(args[1]->IsUint32()); // offset + CHECK(args[2]->IsUint32()); // size CHECK(args[3]->IsObject() || args[3]->IsUndefined()); // wrap object const uint32_t offset = args[1].As()->Value(); const uint32_t size = args[2].As()->Value(); - CHECK_GE(offset + size, offset); // Overflow check. + CHECK_GE(offset + size, offset); // Overflow check. CHECK_LE(offset + size, Buffer::Length(args[0])); // Bounds check. Environment* env = Environment::GetCurrent(args); std::unique_ptr job(new RandomBytesJob(env)); @@ -4679,7 +4409,6 @@ void RandomBytes(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(job->ToResult()); } - struct PBKDF2Job : public CryptoJob { unsigned char* keybuf_data; size_t keybuf_size; @@ -4692,15 +4421,18 @@ struct PBKDF2Job : public CryptoJob { inline explicit PBKDF2Job(Environment* env) : CryptoJob(env), success(Nothing()) {} - inline ~PBKDF2Job() override { - Cleanse(); - } + inline ~PBKDF2Job() override { Cleanse(); } inline void DoThreadPoolWork() override { auto salt_data = reinterpret_cast(salt.data()); - const bool ok = - PKCS5_PBKDF2_HMAC(pass.data(), pass.size(), salt_data, salt.size(), - iteration_count, digest, keybuf_size, keybuf_data); + const bool ok = PKCS5_PBKDF2_HMAC(pass.data(), + pass.size(), + salt_data, + salt.size(), + iteration_count, + digest, + keybuf_size, + keybuf_data); success = Just(ok); Cleanse(); } @@ -4722,15 +4454,14 @@ struct PBKDF2Job : public CryptoJob { } }; - inline void PBKDF2(const FunctionCallbackInfo& args) { auto rv = args.GetReturnValue(); Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsArrayBufferView()); // keybuf; wrap object retains ref. CHECK(args[1]->IsArrayBufferView()); // pass CHECK(args[2]->IsArrayBufferView()); // salt - CHECK(args[3]->IsUint32()); // iteration_count - CHECK(args[4]->IsString()); // digest_name + CHECK(args[3]->IsUint32()); // iteration_count + CHECK(args[4]->IsString()); // digest_name CHECK(args[5]->IsObject() || args[5]->IsUndefined()); // wrap object std::unique_ptr job(new PBKDF2Job(env)); job->keybuf_data = reinterpret_cast(Buffer::Data(args[0])); @@ -4747,7 +4478,6 @@ inline void PBKDF2(const FunctionCallbackInfo& args) { rv.Set(job->ToResult()); } - #ifndef OPENSSL_NO_SCRYPT struct ScryptJob : public CryptoJob { unsigned char* keybuf_data; @@ -4762,13 +4492,11 @@ struct ScryptJob : public CryptoJob { inline explicit ScryptJob(Environment* env) : CryptoJob(env) {} - inline ~ScryptJob() override { - Cleanse(); - } + inline ~ScryptJob() override { Cleanse(); } inline bool Validate() { - if (1 == EVP_PBE_scrypt(nullptr, 0, nullptr, 0, N, r, p, maxmem, - nullptr, 0)) { + if (1 == + EVP_PBE_scrypt(nullptr, 0, nullptr, 0, N, r, p, maxmem, nullptr, 0)) { return true; } else { // Note: EVP_PBE_scrypt() does not always put errors on the error stack. @@ -4779,8 +4507,16 @@ struct ScryptJob : public CryptoJob { inline void DoThreadPoolWork() override { auto salt_data = reinterpret_cast(salt.data()); - if (1 != EVP_PBE_scrypt(pass.data(), pass.size(), salt_data, salt.size(), - N, r, p, maxmem, keybuf_data, keybuf_size)) { + if (1 != EVP_PBE_scrypt(pass.data(), + pass.size(), + salt_data, + salt.size(), + N, + r, + p, + maxmem, + keybuf_data, + keybuf_size)) { errors.Capture(); } } @@ -4803,16 +4539,15 @@ struct ScryptJob : public CryptoJob { } }; - void Scrypt(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsArrayBufferView()); // keybuf; wrap object retains ref. CHECK(args[1]->IsArrayBufferView()); // pass CHECK(args[2]->IsArrayBufferView()); // salt - CHECK(args[3]->IsUint32()); // N - CHECK(args[4]->IsUint32()); // r - CHECK(args[5]->IsUint32()); // p - CHECK(args[6]->IsUint32()); // maxmem + CHECK(args[3]->IsUint32()); // N + CHECK(args[4]->IsUint32()); // r + CHECK(args[5]->IsUint32()); // p + CHECK(args[6]->IsUint32()); // maxmem CHECK(args[7]->IsObject() || args[7]->IsUndefined()); // wrap object std::unique_ptr job(new ScryptJob(env)); job->keybuf_data = reinterpret_cast(Buffer::Data(args[0])); @@ -4839,7 +4574,6 @@ void Scrypt(const FunctionCallbackInfo& args) { } #endif // OPENSSL_NO_SCRYPT - void GetSSLCiphers(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -4856,20 +4590,17 @@ void GetSSLCiphers(const FunctionCallbackInfo& args) { const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i); arr->Set(env->context(), i, - OneByteString(args.GetIsolate(), - SSL_CIPHER_get_name(cipher))).FromJust(); + OneByteString(args.GetIsolate(), SSL_CIPHER_get_name(cipher))) + .FromJust(); } args.GetReturnValue().Set(arr); } - class CipherPushContext { public: explicit CipherPushContext(Environment* env) - : arr(Array::New(env->isolate())), - env_(env) { - } + : arr(Array::New(env->isolate())), env_(env) {} inline Environment* env() const { return env_; } @@ -4879,7 +4610,6 @@ class CipherPushContext { Environment* env_; }; - template static void array_push_back(const TypeName* md, const char* from, @@ -4889,7 +4619,6 @@ static void array_push_back(const TypeName* md, ctx->arr->Set(ctx->arr->Length(), OneByteString(ctx->env()->isolate(), from)); } - void GetCiphers(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CipherPushContext ctx(env); @@ -4897,7 +4626,6 @@ void GetCiphers(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ctx.arr); } - void GetHashes(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CipherPushContext ctx(env); @@ -4905,7 +4633,6 @@ void GetHashes(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ctx.arr); } - void GetCurves(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); const size_t num_curves = EC_get_builtin_curves(nullptr, 0); @@ -4918,8 +4645,8 @@ void GetCurves(const FunctionCallbackInfo& args) { for (size_t i = 0; i < num_curves; i++) { arr->Set(env->context(), i, - OneByteString(env->isolate(), - OBJ_nid2sn(curves[i].nid))).FromJust(); + OneByteString(env->isolate(), OBJ_nid2sn(curves[i].nid))) + .FromJust(); } } } @@ -4927,26 +4654,21 @@ void GetCurves(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(arr); } - bool VerifySpkac(const char* data, unsigned int len) { NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(data, len)); - if (!spki) - return false; + if (!spki) return false; EVPKeyPointer pkey(X509_PUBKEY_get(spki->spkac->pubkey)); - if (!pkey) - return false; + if (!pkey) return false; return NETSCAPE_SPKI_verify(spki.get(), pkey.get()) > 0; } - void VerifySpkac(const FunctionCallbackInfo& args) { bool verify_result = false; size_t length = Buffer::Length(args[0]); - if (length == 0) - return args.GetReturnValue().Set(verify_result); + if (length == 0) return args.GetReturnValue().Set(verify_result); char* data = Buffer::Data(args[0]); CHECK_NOT_NULL(data); @@ -4956,24 +4678,19 @@ void VerifySpkac(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(verify_result); } - char* ExportPublicKey(const char* data, int len, size_t* size) { char* buf = nullptr; BIOPointer bio(BIO_new(BIO_s_mem())); - if (!bio) - return nullptr; + if (!bio) return nullptr; NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(data, len)); - if (!spki) - return nullptr; + if (!spki) return nullptr; EVPKeyPointer pkey(NETSCAPE_SPKI_get_pubkey(spki.get())); - if (!pkey) - return nullptr; + if (!pkey) return nullptr; - if (PEM_write_bio_PUBKEY(bio.get(), pkey.get()) <= 0) - return nullptr; + if (PEM_write_bio_PUBKEY(bio.get(), pkey.get()) <= 0) return nullptr; BUF_MEM* ptr; BIO_get_mem_ptr(bio.get(), &ptr); @@ -4985,31 +4702,26 @@ char* ExportPublicKey(const char* data, int len, size_t* size) { return buf; } - void ExportPublicKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); size_t length = Buffer::Length(args[0]); - if (length == 0) - return args.GetReturnValue().SetEmptyString(); + if (length == 0) return args.GetReturnValue().SetEmptyString(); char* data = Buffer::Data(args[0]); CHECK_NOT_NULL(data); size_t pkey_size; char* pkey = ExportPublicKey(data, length, &pkey_size); - if (pkey == nullptr) - return args.GetReturnValue().SetEmptyString(); + if (pkey == nullptr) return args.GetReturnValue().SetEmptyString(); Local out = Buffer::New(env, pkey, pkey_size).ToLocalChecked(); args.GetReturnValue().Set(out); } - OpenSSLBuffer ExportChallenge(const char* data, int len) { NetscapeSPKIPointer sp(NETSCAPE_SPKI_b64_decode(data, len)); - if (!sp) - return nullptr; + if (!sp) return nullptr; unsigned char* buf = nullptr; ASN1_STRING_to_UTF8(&buf, sp->spkac->challenge); @@ -5017,20 +4729,17 @@ OpenSSLBuffer ExportChallenge(const char* data, int len) { return OpenSSLBuffer(reinterpret_cast(buf)); } - void ExportChallenge(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); size_t len = Buffer::Length(args[0]); - if (len == 0) - return args.GetReturnValue().SetEmptyString(); + if (len == 0) return args.GetReturnValue().SetEmptyString(); char* data = Buffer::Data(args[0]); CHECK_NOT_NULL(data); OpenSSLBuffer cert = ExportChallenge(data, len); - if (!cert) - return args.GetReturnValue().SetEmptyString(); + if (!cert) return args.GetReturnValue().SetEmptyString(); Local outString = Encode(env->isolate(), cert.get(), strlen(cert.get()), BUFFER); @@ -5038,7 +4747,6 @@ void ExportChallenge(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(outString); } - // Convert the input public key to compressed, uncompressed, or hybrid formats. void ConvertKey(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -5046,25 +4754,18 @@ void ConvertKey(const FunctionCallbackInfo& args) { CHECK_EQ(args.Length(), 3); size_t len = Buffer::Length(args[0]); - if (len == 0) - return args.GetReturnValue().SetEmptyString(); + if (len == 0) return args.GetReturnValue().SetEmptyString(); node::Utf8Value curve(env->isolate(), args[1]); int nid = OBJ_sn2nid(*curve); - if (nid == NID_undef) - return env->ThrowTypeError("Invalid ECDH curve name"); + if (nid == NID_undef) return env->ThrowTypeError("Invalid ECDH curve name"); - ECGroupPointer group( - EC_GROUP_new_by_curve_name(nid)); - if (group == nullptr) - return env->ThrowError("Failed to get EC_GROUP"); + ECGroupPointer group(EC_GROUP_new_by_curve_name(nid)); + if (group == nullptr) return env->ThrowError("Failed to get EC_GROUP"); ECPointPointer pub( - ECDH::BufferToPoint(env, - group.get(), - Buffer::Data(args[0]), - len)); + ECDH::BufferToPoint(env, group.get(), Buffer::Data(args[0]), len)); if (pub == nullptr) return env->ThrowError("Failed to convert Buffer to EC_POINT"); @@ -5072,11 +4773,10 @@ void ConvertKey(const FunctionCallbackInfo& args) { point_conversion_form_t form = static_cast(args[2]->Uint32Value()); - int size = EC_POINT_point2oct( - group.get(), pub.get(), form, nullptr, 0, nullptr); + int size = + EC_POINT_point2oct(group.get(), pub.get(), form, nullptr, 0, nullptr); - if (size == 0) - return env->ThrowError("Failed to get public key length"); + if (size == 0) return env->ThrowError("Failed to get public key length"); unsigned char* out = node::Malloc(size); @@ -5091,7 +4791,6 @@ void ConvertKey(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(buf); } - void TimingSafeEqual(const FunctionCallbackInfo& args) { CHECK(Buffer::HasInstance(args[0])); CHECK(Buffer::HasInstance(args[1])); @@ -5117,9 +4816,7 @@ void InitCryptoOnce() { #endif ERR_clear_error(); CONF_modules_load_file( - openssl_config.c_str(), - nullptr, - CONF_MFLAGS_DEFAULT_SECTION); + openssl_config.c_str(), nullptr, CONF_MFLAGS_DEFAULT_SECTION); int err = ERR_get_error(); if (0 != err) { fprintf(stderr, @@ -5141,14 +4838,12 @@ void InitCryptoOnce() { } } if (0 != err) { - fprintf(stderr, - "openssl fips failed: %s\n", - ERR_error_string(err, nullptr)); + fprintf( + stderr, "openssl fips failed: %s\n", ERR_error_string(err, nullptr)); UNREACHABLE(); } #endif // NODE_FIPS_MODE - // Turn off compression. Saves memory and protects against CRIME attacks. // No-op with OPENSSL_NO_COMP builds of OpenSSL. sk_SSL_COMP_zero(SSL_COMP_get_compression_methods()); @@ -5159,7 +4854,6 @@ void InitCryptoOnce() { #endif // !OPENSSL_NO_ENGINE } - #ifndef OPENSSL_NO_ENGINE void SetEngine(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -5175,15 +4869,13 @@ void SetEngine(const FunctionCallbackInfo& args) { if (engine == nullptr) { int err = ERR_get_error(); - if (err == 0) - return args.GetReturnValue().Set(false); + if (err == 0) return args.GetReturnValue().Set(false); return ThrowCryptoError(env, err); } int r = ENGINE_set_default(engine, flags); ENGINE_free(engine); - if (r == 0) - return ThrowCryptoError(env, ERR_get_error()); + if (r == 0) return ThrowCryptoError(env, ERR_get_error()); args.GetReturnValue().Set(true); } @@ -5199,8 +4891,7 @@ void SetFipsCrypto(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); const bool enabled = FIPS_mode(); const bool enable = args[0]->BooleanValue(); - if (enable == enabled) - return; // No action needed. + if (enable == enabled) return; // No action needed. if (!FIPS_mode_set(enable)) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) return ThrowCryptoError(env, err); @@ -5246,19 +4937,23 @@ void Initialize(Local target, env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers); env->SetMethodNoSideEffect(target, "getHashes", GetHashes); env->SetMethodNoSideEffect(target, "getCurves", GetCurves); - env->SetMethod(target, "publicEncrypt", + env->SetMethod(target, + "publicEncrypt", PublicKeyCipher::Cipher); - env->SetMethod(target, "privateDecrypt", + env->SetMethod(target, + "privateDecrypt", PublicKeyCipher::Cipher); - env->SetMethod(target, "privateEncrypt", + env->SetMethod(target, + "privateEncrypt", PublicKeyCipher::Cipher); - env->SetMethod(target, "publicDecrypt", + env->SetMethod(target, + "publicDecrypt", PublicKeyCipher::Cipher); diff --git a/src/node_crypto.h b/src/node_crypto.h index ee069c9cf799b2..ff220ed00009bb 100644 --- a/src/node_crypto.h +++ b/src/node_crypto.h @@ -30,28 +30,28 @@ #include "node_buffer.h" -#include "env.h" #include "async_wrap-inl.h" #include "base_object-inl.h" +#include "env.h" #include "v8.h" -#include #include #include +#include #ifndef OPENSSL_NO_ENGINE -# include +#include #endif // !OPENSSL_NO_ENGINE #include #include // TODO(shigeki) Remove this after upgrading to 1.1.1 +#include #include #include +#include +#include #include #include -#include -#include -#include namespace node { namespace crypto { @@ -88,10 +88,7 @@ using ECPointPointer = DeleteFnPtr; using ECKeyPointer = DeleteFnPtr; using DHPointer = DeleteFnPtr; -enum CheckResult { - CHECK_CERT_REVOKED = 0, - CHECK_OK = 1 -}; +enum CheckResult { CHECK_CERT_REVOKED = 0, CHECK_OK = 1 }; extern int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx); @@ -99,9 +96,7 @@ extern void UseExtraCaCerts(const std::string& file); class SecureContext : public BaseObject { public: - ~SecureContext() override { - Reset(); - } + ~SecureContext() override { Reset(); } static void Initialize(Environment* env, v8::Local target); @@ -208,10 +203,7 @@ class SecureContext : public BaseObject { template class SSLWrap { public: - enum Kind { - kClient, - kServer - }; + enum Kind { kClient, kServer }; SSLWrap(Environment* env, SecureContext* sc, Kind kind) : env_(env), @@ -227,9 +219,7 @@ class SSLWrap { env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize); } - virtual ~SSLWrap() { - DestroySSL(); - } + virtual ~SSLWrap() { DestroySSL(); } inline void enable_session_callbacks() { session_callbacks_ = true; } inline bool is_server() const { return kind_ == kServer; } @@ -315,9 +305,7 @@ class SSLWrap { void SetSNIContext(SecureContext* sc); int SetCACerts(SecureContext* sc); - inline Environment* ssl_env() const { - return env_; - } + inline Environment* ssl_env() const { return env_; } Environment* const env_; Kind kind_; @@ -350,15 +338,8 @@ class CipherBase : public BaseObject { ADD_MEMORY_INFO_NAME(CipherBase) protected: - enum CipherKind { - kCipher, - kDecipher - }; - enum UpdateResult { - kSuccess, - kErrorMessageSize, - kErrorState - }; + enum CipherKind { kCipher, kDecipher }; + enum UpdateResult { kSuccess, kErrorMessageSize, kErrorState }; static const unsigned kNoAuthTagLength = static_cast(-1); void Init(const char* cipher_type, @@ -371,10 +352,13 @@ class CipherBase : public BaseObject { const char* iv, int iv_len, unsigned int auth_tag_len); - bool InitAuthenticated(const char* cipher_type, int iv_len, + bool InitAuthenticated(const char* cipher_type, + int iv_len, unsigned int auth_tag_len); bool CheckCCMMessageLength(int message_len); - UpdateResult Update(const char* data, int len, unsigned char** out, + UpdateResult Update(const char* data, + int len, + unsigned char** out, int* out_len); bool Final(unsigned char** out, int* out_len); bool SetAutoPadding(bool auto_padding); @@ -393,9 +377,7 @@ class CipherBase : public BaseObject { static void SetAuthTag(const v8::FunctionCallbackInfo& args); static void SetAAD(const v8::FunctionCallbackInfo& args); - CipherBase(Environment* env, - v8::Local wrap, - CipherKind kind) + CipherBase(Environment* env, v8::Local wrap, CipherKind kind) : BaseObject(env, wrap), ctx_(nullptr), kind_(kind), @@ -435,8 +417,7 @@ class Hmac : public BaseObject { static void HmacDigest(const v8::FunctionCallbackInfo& args); Hmac(Environment* env, v8::Local wrap) - : BaseObject(env, wrap), - ctx_(nullptr) { + : BaseObject(env, wrap), ctx_(nullptr) { MakeWeak(); } @@ -463,9 +444,7 @@ class Hash : public BaseObject { static void HashDigest(const v8::FunctionCallbackInfo& args); Hash(Environment* env, v8::Local wrap) - : BaseObject(env, wrap), - mdctx_(nullptr), - finalized_(false) { + : BaseObject(env, wrap), mdctx_(nullptr), finalized_(false) { MakeWeak(); } @@ -487,8 +466,7 @@ class SignBase : public BaseObject { } Error; SignBase(Environment* env, v8::Local wrap) - : BaseObject(env, wrap) { - } + : BaseObject(env, wrap) {} Error Init(const char* sign_type); Error Update(const char* data, int len); @@ -555,13 +533,12 @@ class PublicKeyCipher { public: typedef int (*EVP_PKEY_cipher_init_t)(EVP_PKEY_CTX* ctx); typedef int (*EVP_PKEY_cipher_t)(EVP_PKEY_CTX* ctx, - unsigned char* out, size_t* outlen, - const unsigned char* in, size_t inlen); + unsigned char* out, + size_t* outlen, + const unsigned char* in, + size_t inlen); - enum Operation { - kPublic, - kPrivate - }; + enum Operation { kPublic, kPrivate }; template & args); DiffieHellman(Environment* env, v8::Local wrap) - : BaseObject(env, wrap), - initialised_(false), - verifyError_(0) { + : BaseObject(env, wrap), initialised_(false), verifyError_(0) { MakeWeak(); } @@ -622,7 +597,8 @@ class DiffieHellman : public BaseObject { const BIGNUM* (*get_field)(const DH*), const char* err_if_null); static void SetKey(const v8::FunctionCallbackInfo& args, - int (*set_field)(DH*, BIGNUM*), const char* what); + int (*set_field)(DH*, BIGNUM*), + const char* what); bool VerifyContext(); bool initialised_; @@ -632,9 +608,7 @@ class DiffieHellman : public BaseObject { class ECDH : public BaseObject { public: - ~ECDH() override { - group_ = nullptr; - } + ~ECDH() override { group_ = nullptr; } static void Initialize(Environment* env, v8::Local target); static ECPointPointer BufferToPoint(Environment* env, diff --git a/src/node_crypto_bio.cc b/src/node_crypto_bio.cc index 094bb9cc1f8822..d9e9c4428da8ff 100644 --- a/src/node_crypto_bio.cc +++ b/src/node_crypto_bio.cc @@ -20,10 +20,10 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_crypto_bio.h" -#include "openssl/bio.h" -#include "util-inl.h" #include #include +#include "openssl/bio.h" +#include "util-inl.h" namespace node { namespace crypto { @@ -37,19 +37,16 @@ namespace crypto { #define BIO_get_init(bio) bio->init #endif - BIO* NodeBIO::New() { // The const_cast doesn't violate const correctness. OpenSSL's usage of // BIO_METHOD is effectively const but BIO_new() takes a non-const argument. return BIO_new(const_cast(GetMethod())); } - BIO* NodeBIO::NewFixed(const char* data, size_t len) { BIO* bio = New(); - if (bio == nullptr || - len > INT_MAX || + if (bio == nullptr || len > INT_MAX || BIO_write(bio, data, len) != static_cast(len) || BIO_set_mem_eof_return(bio, 0) != 1) { BIO_free(bio); @@ -59,12 +56,10 @@ BIO* NodeBIO::NewFixed(const char* data, size_t len) { return bio; } - void NodeBIO::AssignEnvironment(Environment* env) { env_ = env; } - int NodeBIO::New(BIO* bio) { BIO_set_data(bio, new NodeBIO()); @@ -73,10 +68,8 @@ int NodeBIO::New(BIO* bio) { return 1; } - int NodeBIO::Free(BIO* bio) { - if (bio == nullptr) - return 0; + if (bio == nullptr) return 0; if (BIO_get_shutdown(bio)) { if (BIO_get_init(bio) && BIO_get_data(bio) != nullptr) { @@ -88,7 +81,6 @@ int NodeBIO::Free(BIO* bio) { return 1; } - int NodeBIO::Read(BIO* bio, char* out, int len) { BIO_clear_retry_flags(bio); @@ -105,13 +97,11 @@ int NodeBIO::Read(BIO* bio, char* out, int len) { return bytes; } - char* NodeBIO::Peek(size_t* size) { *size = read_head_->write_pos_ - read_head_->read_pos_; return read_head_->data_ + read_head_->read_pos_; } - size_t NodeBIO::PeekMultiple(char** out, size_t* size, size_t* count) { Buffer* pos = read_head_; size_t max = *count; @@ -138,7 +128,6 @@ size_t NodeBIO::PeekMultiple(char** out, size_t* size, size_t* count) { return total; } - int NodeBIO::Write(BIO* bio, const char* data, int len) { BIO_clear_retry_flags(bio); @@ -147,27 +136,22 @@ int NodeBIO::Write(BIO* bio, const char* data, int len) { return len; } - int NodeBIO::Puts(BIO* bio, const char* str) { return Write(bio, str, strlen(str)); } - int NodeBIO::Gets(BIO* bio, char* out, int size) { NodeBIO* nbio = FromBIO(bio); - if (nbio->Length() == 0) - return 0; + if (nbio->Length() == 0) return 0; int i = nbio->IndexOf('\n', size); // Include '\n', if it's there. If not, don't read off the end. - if (i < size && i >= 0 && static_cast(i) < nbio->Length()) - i++; + if (i < size && i >= 0 && static_cast(i) < nbio->Length()) i++; // Shift `i` a bit to nullptr-terminate string later - if (size == i) - i--; + if (size == i) i--; // Flush read data nbio->Read(out, i); @@ -177,8 +161,9 @@ int NodeBIO::Gets(BIO* bio, char* out, int size) { return i; } - -long NodeBIO::Ctrl(BIO* bio, int cmd, long num, // NOLINT(runtime/int) +long NodeBIO::Ctrl(BIO* bio, // NOLINT(runtime/int) + int cmd, + long num, // NOLINT(runtime/int) void* ptr) { NodeBIO* nbio; long ret; // NOLINT(runtime/int) @@ -198,8 +183,7 @@ long NodeBIO::Ctrl(BIO* bio, int cmd, long num, // NOLINT(runtime/int) break; case BIO_CTRL_INFO: ret = nbio->Length(); - if (ptr != nullptr) - *reinterpret_cast(ptr) = nullptr; + if (ptr != nullptr) *reinterpret_cast(ptr) = nullptr; break; case BIO_C_SET_BUF_MEM: CHECK(0 && "Can't use SET_BUF_MEM_PTR with NodeBIO"); @@ -233,21 +217,18 @@ long NodeBIO::Ctrl(BIO* bio, int cmd, long num, // NOLINT(runtime/int) return ret; } - const BIO_METHOD* NodeBIO::GetMethod() { #if OPENSSL_VERSION_NUMBER < 0x10100000L - static const BIO_METHOD method = { - BIO_TYPE_MEM, - "node.js SSL buffer", - Write, - Read, - Puts, - Gets, - Ctrl, - New, - Free, - nullptr - }; + static const BIO_METHOD method = {BIO_TYPE_MEM, + "node.js SSL buffer", + Write, + Read, + Puts, + Gets, + Ctrl, + New, + Free, + nullptr}; return &method; #else @@ -268,7 +249,6 @@ const BIO_METHOD* NodeBIO::GetMethod() { #endif } - void NodeBIO::TryMoveReadHead() { // `read_pos_` and `write_pos_` means the position of the reader and writer // inside the buffer, respectively. When they're equal - its safe to reset @@ -282,12 +262,10 @@ void NodeBIO::TryMoveReadHead() { // Move read_head_ forward, just in case if there're still some data to // read in the next buffer. - if (read_head_ != write_head_) - read_head_ = read_head_->next_; + if (read_head_ != write_head_) read_head_ = read_head_->next_; } } - size_t NodeBIO::Read(char* out, size_t size) { size_t bytes_read = 0; size_t expected = Length() > size ? size : Length(); @@ -297,8 +275,7 @@ size_t NodeBIO::Read(char* out, size_t size) { while (bytes_read < expected) { CHECK_LE(read_head_->read_pos_, read_head_->write_pos_); size_t avail = read_head_->write_pos_ - read_head_->read_pos_; - if (avail > left) - avail = left; + if (avail > left) avail = left; // Copy data if (out != nullptr) @@ -321,16 +298,12 @@ size_t NodeBIO::Read(char* out, size_t size) { return bytes_read; } - void NodeBIO::FreeEmpty() { - if (write_head_ == nullptr) - return; + if (write_head_ == nullptr) return; Buffer* child = write_head_->next_; - if (child == write_head_ || child == read_head_) - return; + if (child == write_head_ || child == read_head_) return; Buffer* cur = child->next_; - if (cur == write_head_ || cur == read_head_) - return; + if (cur == write_head_ || cur == read_head_) return; Buffer* prev = child; while (cur != read_head_) { @@ -344,7 +317,6 @@ void NodeBIO::FreeEmpty() { prev->next_ = cur; } - size_t NodeBIO::IndexOf(char delim, size_t limit) { size_t bytes_read = 0; size_t max = Length() > limit ? limit : Length(); @@ -354,8 +326,7 @@ size_t NodeBIO::IndexOf(char delim, size_t limit) { while (bytes_read < max) { CHECK_LE(current->read_pos_, current->write_pos_); size_t avail = current->write_pos_ - current->read_pos_; - if (avail > left) - avail = left; + if (avail > left) avail = left; // Walk through data char* tmp = current->data_ + current->read_pos_; @@ -384,7 +355,6 @@ size_t NodeBIO::IndexOf(char delim, size_t limit) { return max; } - void NodeBIO::Write(const char* data, size_t size) { size_t offset = 0; size_t left = size; @@ -397,13 +367,11 @@ void NodeBIO::Write(const char* data, size_t size) { CHECK_LE(write_head_->write_pos_, write_head_->len_); size_t avail = write_head_->len_ - write_head_->write_pos_; - if (to_write > avail) - to_write = avail; + if (to_write > avail) to_write = avail; // Copy data - memcpy(write_head_->data_ + write_head_->write_pos_, - data + offset, - to_write); + memcpy( + write_head_->data_ + write_head_->write_pos_, data + offset, to_write); // Move pointers left -= to_write; @@ -426,7 +394,6 @@ void NodeBIO::Write(const char* data, size_t size) { CHECK_EQ(left, 0); } - char* NodeBIO::PeekWritable(size_t* size) { TryAllocateForWrite(*size); @@ -439,7 +406,6 @@ char* NodeBIO::PeekWritable(size_t* size) { return write_head_->data_ + write_head_->write_pos_; } - void NodeBIO::Commit(size_t size) { write_head_->write_pos_ += size; length_ += size; @@ -457,18 +423,14 @@ void NodeBIO::Commit(size_t size) { } } - void NodeBIO::TryAllocateForWrite(size_t hint) { Buffer* w = write_head_; Buffer* r = read_head_; // If write head is full, next buffer is either read head or not empty. - if (w == nullptr || - (w->write_pos_ == w->len_ && - (w->next_ == r || w->next_->write_pos_ != 0))) { - size_t len = w == nullptr ? initial_ : - kThroughputBufferLength; - if (len < hint) - len = hint; + if (w == nullptr || (w->write_pos_ == w->len_ && + (w->next_ == r || w->next_->write_pos_ != 0))) { + size_t len = w == nullptr ? initial_ : kThroughputBufferLength; + if (len < hint) len = hint; Buffer* next = new Buffer(env_, len); if (w == nullptr) { @@ -482,10 +444,8 @@ void NodeBIO::TryAllocateForWrite(size_t hint) { } } - void NodeBIO::Reset() { - if (read_head_ == nullptr) - return; + if (read_head_ == nullptr) return; while (read_head_->read_pos_ != read_head_->write_pos_) { CHECK(read_head_->write_pos_ > read_head_->read_pos_); @@ -500,10 +460,8 @@ void NodeBIO::Reset() { CHECK_EQ(length_, 0); } - NodeBIO::~NodeBIO() { - if (read_head_ == nullptr) - return; + if (read_head_ == nullptr) return; Buffer* current = read_head_; do { @@ -516,12 +474,10 @@ NodeBIO::~NodeBIO() { write_head_ = nullptr; } - NodeBIO* NodeBIO::FromBIO(BIO* bio) { CHECK_NOT_NULL(BIO_get_data(bio)); return static_cast(BIO_get_data(bio)); } - } // namespace crypto } // namespace node diff --git a/src/node_crypto_bio.h b/src/node_crypto_bio.h index b4aa85f8fa36fa..30c082f746bfdc 100644 --- a/src/node_crypto_bio.h +++ b/src/node_crypto_bio.h @@ -24,8 +24,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "openssl/bio.h" #include "env-inl.h" +#include "openssl/bio.h" #include "util-inl.h" #include "v8.h" @@ -34,13 +34,13 @@ namespace crypto { class NodeBIO : public MemoryRetainer { public: - NodeBIO() : env_(nullptr), - initial_(kInitialBufferLength), - length_(0), - eof_return_(-1), - read_head_(nullptr), - write_head_(nullptr) { - } + NodeBIO() + : env_(nullptr), + initial_(kInitialBufferLength), + length_(0), + eof_return_(-1), + read_head_(nullptr), + write_head_(nullptr) {} ~NodeBIO(); @@ -90,23 +90,14 @@ class NodeBIO : public MemoryRetainer { // Commit reserved data void Commit(size_t size); - // Return size of buffer in bytes - inline size_t Length() const { - return length_; - } + inline size_t Length() const { return length_; } - inline void set_eof_return(int num) { - eof_return_ = num; - } + inline void set_eof_return(int num) { eof_return_ = num; } - inline int eof_return() { - return eof_return_; - } + inline int eof_return() { return eof_return_; } - inline void set_initial(size_t initial) { - initial_ = initial; - } + inline void set_initial(size_t initial) { initial_ = initial; } static NodeBIO* FromBIO(BIO* bio); @@ -124,7 +115,9 @@ class NodeBIO : public MemoryRetainer { static int Write(BIO* bio, const char* data, int len); static int Puts(BIO* bio, const char* str); static int Gets(BIO* bio, char* out, int size); - static long Ctrl(BIO* bio, int cmd, long num, // NOLINT(runtime/int) + static long Ctrl(BIO* bio, // NOLINT(runtime/int) + int cmd, + long num, // NOLINT(runtime/int) void* ptr); static const BIO_METHOD* GetMethod(); @@ -135,11 +128,8 @@ class NodeBIO : public MemoryRetainer { class Buffer { public: - Buffer(Environment* env, size_t len) : env_(env), - read_pos_(0), - write_pos_(0), - len_(len), - next_(nullptr) { + Buffer(Environment* env, size_t len) + : env_(env), read_pos_(0), write_pos_(0), len_(len), next_(nullptr) { data_ = new char[len]; if (env_ != nullptr) env_->isolate()->AdjustAmountOfExternalAllocatedMemory(len); diff --git a/src/node_crypto_clienthello-inl.h b/src/node_crypto_clienthello-inl.h index c5c595c7606cf9..a25d89c8a9ab25 100644 --- a/src/node_crypto_clienthello-inl.h +++ b/src/node_crypto_clienthello-inl.h @@ -61,8 +61,7 @@ inline void ClientHelloParser::Reset() { inline void ClientHelloParser::Start(ClientHelloParser::OnHelloCb onhello_cb, ClientHelloParser::OnEndCb onend_cb, void* onend_arg) { - if (!IsEnded()) - return; + if (!IsEnded()) return; Reset(); CHECK_NOT_NULL(onhello_cb); @@ -74,8 +73,7 @@ inline void ClientHelloParser::Start(ClientHelloParser::OnHelloCb onhello_cb, } inline void ClientHelloParser::End() { - if (state_ == kEnded) - return; + if (state_ == kEnded) return; state_ = kEnded; if (onend_cb_ != nullptr) { onend_cb_(cb_arg_); diff --git a/src/node_crypto_clienthello.cc b/src/node_crypto_clienthello.cc index d4d222f838c5ac..7b845959f4c711 100644 --- a/src/node_crypto_clienthello.cc +++ b/src/node_crypto_clienthello.cc @@ -27,8 +27,7 @@ namespace crypto { void ClientHelloParser::Parse(const uint8_t* data, size_t avail) { switch (state_) { case kWaiting: - if (!ParseRecordHeader(data, avail)) - break; + if (!ParseRecordHeader(data, avail)) break; // Fall through case kTLSHeader: ParseHeader(data, avail); @@ -43,16 +42,12 @@ void ClientHelloParser::Parse(const uint8_t* data, size_t avail) { } } - bool ClientHelloParser::ParseRecordHeader(const uint8_t* data, size_t avail) { // >= 5 bytes for header parsing - if (avail < 5) - return false; + if (avail < 5) return false; - if (data[0] == kChangeCipherSpec || - data[0] == kAlert || - data[0] == kHandshake || - data[0] == kApplicationData) { + if (data[0] == kChangeCipherSpec || data[0] == kAlert || + data[0] == kHandshake || data[0] == kApplicationData) { frame_len_ = (data[3] << 8) + data[4]; state_ = kTLSHeader; body_offset_ = 5; @@ -71,13 +66,11 @@ bool ClientHelloParser::ParseRecordHeader(const uint8_t* data, size_t avail) { return true; } - void ClientHelloParser::ParseHeader(const uint8_t* data, size_t avail) { ClientHello hello; // >= 5 + frame size bytes for frame parsing - if (body_offset_ + frame_len_ > avail) - return; + if (body_offset_ + frame_len_ > avail) return; // Check hello protocol version. Protocol tuples that we know about: // @@ -85,24 +78,21 @@ void ClientHelloParser::ParseHeader(const uint8_t* data, size_t avail) { // (3,2) TLS v1.1 // (3,3) TLS v1.2 // - if (data[body_offset_ + 4] != 0x03 || - data[body_offset_ + 5] < 0x01 || + if (data[body_offset_ + 4] != 0x03 || data[body_offset_ + 5] < 0x01 || data[body_offset_ + 5] > 0x03) { goto fail; } if (data[body_offset_] == kClientHello) { if (state_ == kTLSHeader) { - if (!ParseTLSClientHello(data, avail)) - goto fail; + if (!ParseTLSClientHello(data, avail)) goto fail; } else { // We couldn't get here, but whatever goto fail; } // Check if we overflowed (do not reply with any private data) - if (session_id_ == nullptr || - session_size_ > 32 || + if (session_id_ == nullptr || session_size_ > 32 || session_id_ + session_size_ > data + avail) { goto fail; } @@ -118,11 +108,10 @@ void ClientHelloParser::ParseHeader(const uint8_t* data, size_t avail) { onhello_cb_(cb_arg_, hello); return; - fail: +fail: End(); } - void ClientHelloParser::ParseExtension(const uint16_t type, const uint8_t* data, size_t len) { @@ -130,37 +119,28 @@ void ClientHelloParser::ParseExtension(const uint16_t type, // That's because we're heavily relying on OpenSSL to solve any problem with // incoming data. switch (type) { - case kServerName: - { - if (len < 2) - return; - uint32_t server_names_len = (data[0] << 8) + data[1]; - if (server_names_len + 2 > len) - return; - for (size_t offset = 2; offset < 2 + server_names_len; ) { - if (offset + 3 > len) - return; - uint8_t name_type = data[offset]; - if (name_type != kServernameHostname) - return; - uint16_t name_len = (data[offset + 1] << 8) + data[offset + 2]; - offset += 3; - if (offset + name_len > len) - return; - servername_ = data + offset; - servername_size_ = name_len; - offset += name_len; - } + case kServerName: { + if (len < 2) return; + uint32_t server_names_len = (data[0] << 8) + data[1]; + if (server_names_len + 2 > len) return; + for (size_t offset = 2; offset < 2 + server_names_len;) { + if (offset + 3 > len) return; + uint8_t name_type = data[offset]; + if (name_type != kServernameHostname) return; + uint16_t name_len = (data[offset + 1] << 8) + data[offset + 2]; + offset += 3; + if (offset + name_len > len) return; + servername_ = data + offset; + servername_size_ = name_len; + offset += name_len; } - break; + } break; case kStatusRequest: // We are ignoring any data, just indicating the presence of extension - if (len < kMinStatusRequestSize) - return; + if (len < kMinStatusRequestSize) return; // Unknown type, ignore it - if (data[0] != kStatusRequestOCSP) - break; + if (data[0] != kStatusRequestOCSP) break; // Ignore extensions, they won't work with caching on backend anyway ocsp_request_ = 1; @@ -175,15 +155,13 @@ void ClientHelloParser::ParseExtension(const uint16_t type, } } - bool ClientHelloParser::ParseTLSClientHello(const uint8_t* data, size_t avail) { const uint8_t* body; // Skip frame header, hello header, protocol version and random data size_t session_offset = body_offset_ + 4 + 2 + 32; - if (session_offset + 1 >= avail) - return false; + if (session_offset + 1 >= avail) return false; body = data + session_offset; session_size_ = *body; @@ -192,54 +170,44 @@ bool ClientHelloParser::ParseTLSClientHello(const uint8_t* data, size_t avail) { size_t cipher_offset = session_offset + 1 + session_size_; // Session OOB failure - if (cipher_offset + 1 >= avail) - return false; + if (cipher_offset + 1 >= avail) return false; - uint16_t cipher_len = - (data[cipher_offset] << 8) + data[cipher_offset + 1]; + uint16_t cipher_len = (data[cipher_offset] << 8) + data[cipher_offset + 1]; size_t comp_offset = cipher_offset + 2 + cipher_len; // Cipher OOB failure - if (comp_offset >= avail) - return false; + if (comp_offset >= avail) return false; uint8_t comp_len = data[comp_offset]; size_t extension_offset = comp_offset + 1 + comp_len; // Compression OOB failure - if (extension_offset > avail) - return false; + if (extension_offset > avail) return false; // No extensions present - if (extension_offset == avail) - return true; + if (extension_offset == avail) return true; size_t ext_off = extension_offset + 2; // Parse known extensions while (ext_off < avail) { // Extension OOB - if (ext_off + 4 > avail) - return false; + if (ext_off + 4 > avail) return false; uint16_t ext_type = (data[ext_off] << 8) + data[ext_off + 1]; uint16_t ext_len = (data[ext_off + 2] << 8) + data[ext_off + 3]; ext_off += 4; // Extension OOB - if (ext_off + ext_len > avail) - return false; + if (ext_off + ext_len > avail) return false; - ParseExtension(ext_type, - data + ext_off, - ext_len); + ParseExtension(ext_type, data + ext_off, ext_len); ext_off += ext_len; } // Extensions OOB failure - if (ext_off > avail) - return false; + if (ext_off > avail) return false; return true; } diff --git a/src/node_crypto_clienthello.h b/src/node_crypto_clienthello.h index fd8756254ffc24..c3561a8ca415fc 100644 --- a/src/node_crypto_clienthello.h +++ b/src/node_crypto_clienthello.h @@ -72,12 +72,7 @@ class ClientHelloParser { static const uint8_t kStatusRequestOCSP = 1; static const size_t kMinStatusRequestSize = 5; - enum ParseState { - kWaiting, - kTLSHeader, - kPaused, - kEnded - }; + enum ParseState { kWaiting, kTLSHeader, kPaused, kEnded }; enum FrameType { kChangeCipherSpec = 20, @@ -87,9 +82,7 @@ class ClientHelloParser { kOther = 255 }; - enum HandshakeType { - kClientHello = 1 - }; + enum HandshakeType { kClientHello = 1 }; enum ExtensionType { kServerName = 0, @@ -99,9 +92,7 @@ class ClientHelloParser { bool ParseRecordHeader(const uint8_t* data, size_t avail); void ParseHeader(const uint8_t* data, size_t avail); - void ParseExtension(const uint16_t type, - const uint8_t* data, - size_t len); + void ParseExtension(const uint16_t type, const uint8_t* data, size_t len); bool ParseTLSClientHello(const uint8_t* data, size_t avail); ParseState state_; diff --git a/src/node_crypto_groups.h b/src/node_crypto_groups.h index d22fdc7f966f9a..5b07575185c9ac 100644 --- a/src/node_crypto_groups.h +++ b/src/node_crypto_groups.h @@ -31,364 +31,305 @@ They all use 2 as a generator. */ - -static const unsigned char two_generator[] = { 2 }; +static const unsigned char two_generator[] = {2}; static const unsigned char group_modp1[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp2[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp5[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, - 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, - 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, - 0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, - 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, - 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, - 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, - 0xca, 0x23, 0x73, 0x27, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, + 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36, + 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, + 0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, + 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, + 0xca, 0x23, 0x73, 0x27, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp14[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, - 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, - 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, - 0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, - 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, - 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, - 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, - 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, - 0xce, 0x3b, 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, - 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, - 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, - 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, - 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, - 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xac, 0xaa, 0x68, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, + 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36, + 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, + 0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, + 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, + 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, + 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, + 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, + 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xac, 0xaa, 0x68, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp15[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, - 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, - 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, - 0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, - 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, - 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, - 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, - 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, - 0xce, 0x3b, 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, - 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, - 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, - 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, - 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, - 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, - 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, - 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, - 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, - 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, 0xab, 0xf5, - 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, - 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, - 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, - 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, - 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, 0xbb, 0xe1, 0x17, 0x57, - 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, - 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, - 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, - 0xd1, 0x20, 0xa9, 0x3a, 0xd2, 0xca, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, + 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36, + 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, + 0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, + 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, + 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, + 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, + 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, + 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, + 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, + 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, + 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, + 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, + 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, 0xd8, 0x76, 0x02, 0x73, + 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, + 0xba, 0xd9, 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, + 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, 0xd1, 0x20, + 0xa9, 0x3a, 0xd2, 0xca, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp16[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, - 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, - 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, - 0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, - 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, - 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, - 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, - 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, - 0xce, 0x3b, 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, - 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, - 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, - 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, - 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, - 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, - 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, - 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, - 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, - 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, 0xab, 0xf5, - 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, - 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, - 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, - 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, - 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, 0xbb, 0xe1, 0x17, 0x57, - 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, - 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, - 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, - 0xd1, 0x20, 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, - 0xa7, 0x87, 0xe6, 0xd7, 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, - 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, 0x6a, 0xf4, 0xe2, 0x3c, - 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, 0x25, 0x83, - 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, 0xdb, 0xbb, 0xc2, 0xdb, - 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, - 0xca, 0xa6, 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, - 0x99, 0xb2, 0x96, 0x4f, 0xa0, 0x90, 0xc3, 0xa2, 0x23, 0x3b, - 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, 0x1f, 0x61, 0x29, 0x70, - 0xce, 0xe2, 0xd7, 0xaf, 0xb8, 0x1b, 0xdd, 0x76, 0x21, 0x70, - 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, - 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, - 0xb7, 0xdc, 0x90, 0xa6, 0xc0, 0x8f, 0x4d, 0xf4, 0x35, 0xc9, - 0x34, 0x06, 0x31, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, + 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36, + 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, + 0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, + 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, + 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, + 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, + 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, + 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, + 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, + 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, + 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, + 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, + 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, 0xd8, 0x76, 0x02, 0x73, + 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, + 0xba, 0xd9, 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, + 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, 0xd1, 0x20, + 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, 0xa7, 0x87, 0xe6, 0xd7, + 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, + 0x6a, 0xf4, 0xe2, 0x3c, 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, + 0x25, 0x83, 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, 0xdb, 0xbb, 0xc2, 0xdb, + 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, 0xca, 0xa6, + 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, 0x99, 0xb2, 0x96, 0x4f, + 0xa0, 0x90, 0xc3, 0xa2, 0x23, 0x3b, 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, + 0x1f, 0x61, 0x29, 0x70, 0xce, 0xe2, 0xd7, 0xaf, 0xb8, 0x1b, 0xdd, 0x76, + 0x21, 0x70, 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, + 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, 0xb7, 0xdc, + 0x90, 0xa6, 0xc0, 0x8f, 0x4d, 0xf4, 0x35, 0xc9, 0x34, 0x06, 0x31, 0x99, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp17[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, - 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, - 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, - 0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, - 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, - 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, - 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, - 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, - 0xce, 0x3b, 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, - 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, - 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, - 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, - 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, - 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, - 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, - 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, - 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, - 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, 0xab, 0xf5, - 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, - 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, - 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, - 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, - 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, 0xbb, 0xe1, 0x17, 0x57, - 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, - 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, - 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, - 0xd1, 0x20, 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, - 0xa7, 0x87, 0xe6, 0xd7, 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, - 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, 0x6a, 0xf4, 0xe2, 0x3c, - 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, 0x25, 0x83, - 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, 0xdb, 0xbb, 0xc2, 0xdb, - 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, - 0xca, 0xa6, 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, - 0x99, 0xb2, 0x96, 0x4f, 0xa0, 0x90, 0xc3, 0xa2, 0x23, 0x3b, - 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, 0x1f, 0x61, 0x29, 0x70, - 0xce, 0xe2, 0xd7, 0xaf, 0xb8, 0x1b, 0xdd, 0x76, 0x21, 0x70, - 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, - 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, - 0xb7, 0xdc, 0x90, 0xa6, 0xc0, 0x8f, 0x4d, 0xf4, 0x35, 0xc9, - 0x34, 0x02, 0x84, 0x92, 0x36, 0xc3, 0xfa, 0xb4, 0xd2, 0x7c, - 0x70, 0x26, 0xc1, 0xd4, 0xdc, 0xb2, 0x60, 0x26, 0x46, 0xde, - 0xc9, 0x75, 0x1e, 0x76, 0x3d, 0xba, 0x37, 0xbd, 0xf8, 0xff, - 0x94, 0x06, 0xad, 0x9e, 0x53, 0x0e, 0xe5, 0xdb, 0x38, 0x2f, - 0x41, 0x30, 0x01, 0xae, 0xb0, 0x6a, 0x53, 0xed, 0x90, 0x27, - 0xd8, 0x31, 0x17, 0x97, 0x27, 0xb0, 0x86, 0x5a, 0x89, 0x18, - 0xda, 0x3e, 0xdb, 0xeb, 0xcf, 0x9b, 0x14, 0xed, 0x44, 0xce, - 0x6c, 0xba, 0xce, 0xd4, 0xbb, 0x1b, 0xdb, 0x7f, 0x14, 0x47, - 0xe6, 0xcc, 0x25, 0x4b, 0x33, 0x20, 0x51, 0x51, 0x2b, 0xd7, - 0xaf, 0x42, 0x6f, 0xb8, 0xf4, 0x01, 0x37, 0x8c, 0xd2, 0xbf, - 0x59, 0x83, 0xca, 0x01, 0xc6, 0x4b, 0x92, 0xec, 0xf0, 0x32, - 0xea, 0x15, 0xd1, 0x72, 0x1d, 0x03, 0xf4, 0x82, 0xd7, 0xce, - 0x6e, 0x74, 0xfe, 0xf6, 0xd5, 0x5e, 0x70, 0x2f, 0x46, 0x98, - 0x0c, 0x82, 0xb5, 0xa8, 0x40, 0x31, 0x90, 0x0b, 0x1c, 0x9e, - 0x59, 0xe7, 0xc9, 0x7f, 0xbe, 0xc7, 0xe8, 0xf3, 0x23, 0xa9, - 0x7a, 0x7e, 0x36, 0xcc, 0x88, 0xbe, 0x0f, 0x1d, 0x45, 0xb7, - 0xff, 0x58, 0x5a, 0xc5, 0x4b, 0xd4, 0x07, 0xb2, 0x2b, 0x41, - 0x54, 0xaa, 0xcc, 0x8f, 0x6d, 0x7e, 0xbf, 0x48, 0xe1, 0xd8, - 0x14, 0xcc, 0x5e, 0xd2, 0x0f, 0x80, 0x37, 0xe0, 0xa7, 0x97, - 0x15, 0xee, 0xf2, 0x9b, 0xe3, 0x28, 0x06, 0xa1, 0xd5, 0x8b, - 0xb7, 0xc5, 0xda, 0x76, 0xf5, 0x50, 0xaa, 0x3d, 0x8a, 0x1f, - 0xbf, 0xf0, 0xeb, 0x19, 0xcc, 0xb1, 0xa3, 0x13, 0xd5, 0x5c, - 0xda, 0x56, 0xc9, 0xec, 0x2e, 0xf2, 0x96, 0x32, 0x38, 0x7f, - 0xe8, 0xd7, 0x6e, 0x3c, 0x04, 0x68, 0x04, 0x3e, 0x8f, 0x66, - 0x3f, 0x48, 0x60, 0xee, 0x12, 0xbf, 0x2d, 0x5b, 0x0b, 0x74, - 0x74, 0xd6, 0xe6, 0x94, 0xf9, 0x1e, 0x6d, 0xcc, 0x40, 0x24, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, + 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36, + 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, + 0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, + 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, + 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, + 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, + 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, + 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, + 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, + 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, + 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, + 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, + 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, 0xd8, 0x76, 0x02, 0x73, + 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, + 0xba, 0xd9, 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, + 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, 0xd1, 0x20, + 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, 0xa7, 0x87, 0xe6, 0xd7, + 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, + 0x6a, 0xf4, 0xe2, 0x3c, 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, + 0x25, 0x83, 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, 0xdb, 0xbb, 0xc2, 0xdb, + 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, 0xca, 0xa6, + 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, 0x99, 0xb2, 0x96, 0x4f, + 0xa0, 0x90, 0xc3, 0xa2, 0x23, 0x3b, 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, + 0x1f, 0x61, 0x29, 0x70, 0xce, 0xe2, 0xd7, 0xaf, 0xb8, 0x1b, 0xdd, 0x76, + 0x21, 0x70, 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, + 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, 0xb7, 0xdc, + 0x90, 0xa6, 0xc0, 0x8f, 0x4d, 0xf4, 0x35, 0xc9, 0x34, 0x02, 0x84, 0x92, + 0x36, 0xc3, 0xfa, 0xb4, 0xd2, 0x7c, 0x70, 0x26, 0xc1, 0xd4, 0xdc, 0xb2, + 0x60, 0x26, 0x46, 0xde, 0xc9, 0x75, 0x1e, 0x76, 0x3d, 0xba, 0x37, 0xbd, + 0xf8, 0xff, 0x94, 0x06, 0xad, 0x9e, 0x53, 0x0e, 0xe5, 0xdb, 0x38, 0x2f, + 0x41, 0x30, 0x01, 0xae, 0xb0, 0x6a, 0x53, 0xed, 0x90, 0x27, 0xd8, 0x31, + 0x17, 0x97, 0x27, 0xb0, 0x86, 0x5a, 0x89, 0x18, 0xda, 0x3e, 0xdb, 0xeb, + 0xcf, 0x9b, 0x14, 0xed, 0x44, 0xce, 0x6c, 0xba, 0xce, 0xd4, 0xbb, 0x1b, + 0xdb, 0x7f, 0x14, 0x47, 0xe6, 0xcc, 0x25, 0x4b, 0x33, 0x20, 0x51, 0x51, + 0x2b, 0xd7, 0xaf, 0x42, 0x6f, 0xb8, 0xf4, 0x01, 0x37, 0x8c, 0xd2, 0xbf, + 0x59, 0x83, 0xca, 0x01, 0xc6, 0x4b, 0x92, 0xec, 0xf0, 0x32, 0xea, 0x15, + 0xd1, 0x72, 0x1d, 0x03, 0xf4, 0x82, 0xd7, 0xce, 0x6e, 0x74, 0xfe, 0xf6, + 0xd5, 0x5e, 0x70, 0x2f, 0x46, 0x98, 0x0c, 0x82, 0xb5, 0xa8, 0x40, 0x31, + 0x90, 0x0b, 0x1c, 0x9e, 0x59, 0xe7, 0xc9, 0x7f, 0xbe, 0xc7, 0xe8, 0xf3, + 0x23, 0xa9, 0x7a, 0x7e, 0x36, 0xcc, 0x88, 0xbe, 0x0f, 0x1d, 0x45, 0xb7, + 0xff, 0x58, 0x5a, 0xc5, 0x4b, 0xd4, 0x07, 0xb2, 0x2b, 0x41, 0x54, 0xaa, + 0xcc, 0x8f, 0x6d, 0x7e, 0xbf, 0x48, 0xe1, 0xd8, 0x14, 0xcc, 0x5e, 0xd2, + 0x0f, 0x80, 0x37, 0xe0, 0xa7, 0x97, 0x15, 0xee, 0xf2, 0x9b, 0xe3, 0x28, + 0x06, 0xa1, 0xd5, 0x8b, 0xb7, 0xc5, 0xda, 0x76, 0xf5, 0x50, 0xaa, 0x3d, + 0x8a, 0x1f, 0xbf, 0xf0, 0xeb, 0x19, 0xcc, 0xb1, 0xa3, 0x13, 0xd5, 0x5c, + 0xda, 0x56, 0xc9, 0xec, 0x2e, 0xf2, 0x96, 0x32, 0x38, 0x7f, 0xe8, 0xd7, + 0x6e, 0x3c, 0x04, 0x68, 0x04, 0x3e, 0x8f, 0x66, 0x3f, 0x48, 0x60, 0xee, + 0x12, 0xbf, 0x2d, 0x5b, 0x0b, 0x74, 0x74, 0xd6, 0xe6, 0x94, 0xf9, 0x1e, + 0x6d, 0xcc, 0x40, 0x24, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const unsigned char group_modp18[] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, - 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, - 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, - 0xfd, 0x24, 0xcf, 0x5f, 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, - 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, - 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, - 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, - 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, - 0xce, 0x3b, 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, - 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, - 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, - 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, - 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, - 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, - 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, - 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, - 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, - 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, 0xab, 0xf5, - 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, - 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, - 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, - 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, - 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, 0xbb, 0xe1, 0x17, 0x57, - 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, - 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, - 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, - 0xd1, 0x20, 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, - 0xa7, 0x87, 0xe6, 0xd7, 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, - 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, 0x6a, 0xf4, 0xe2, 0x3c, - 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, 0x25, 0x83, - 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, 0xdb, 0xbb, 0xc2, 0xdb, - 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, - 0xca, 0xa6, 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, - 0x99, 0xb2, 0x96, 0x4f, 0xa0, 0x90, 0xc3, 0xa2, 0x23, 0x3b, - 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, 0x1f, 0x61, 0x29, 0x70, - 0xce, 0xe2, 0xd7, 0xaf, 0xb8, 0x1b, 0xdd, 0x76, 0x21, 0x70, - 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, - 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, - 0xb7, 0xdc, 0x90, 0xa6, 0xc0, 0x8f, 0x4d, 0xf4, 0x35, 0xc9, - 0x34, 0x02, 0x84, 0x92, 0x36, 0xc3, 0xfa, 0xb4, 0xd2, 0x7c, - 0x70, 0x26, 0xc1, 0xd4, 0xdc, 0xb2, 0x60, 0x26, 0x46, 0xde, - 0xc9, 0x75, 0x1e, 0x76, 0x3d, 0xba, 0x37, 0xbd, 0xf8, 0xff, - 0x94, 0x06, 0xad, 0x9e, 0x53, 0x0e, 0xe5, 0xdb, 0x38, 0x2f, - 0x41, 0x30, 0x01, 0xae, 0xb0, 0x6a, 0x53, 0xed, 0x90, 0x27, - 0xd8, 0x31, 0x17, 0x97, 0x27, 0xb0, 0x86, 0x5a, 0x89, 0x18, - 0xda, 0x3e, 0xdb, 0xeb, 0xcf, 0x9b, 0x14, 0xed, 0x44, 0xce, - 0x6c, 0xba, 0xce, 0xd4, 0xbb, 0x1b, 0xdb, 0x7f, 0x14, 0x47, - 0xe6, 0xcc, 0x25, 0x4b, 0x33, 0x20, 0x51, 0x51, 0x2b, 0xd7, - 0xaf, 0x42, 0x6f, 0xb8, 0xf4, 0x01, 0x37, 0x8c, 0xd2, 0xbf, - 0x59, 0x83, 0xca, 0x01, 0xc6, 0x4b, 0x92, 0xec, 0xf0, 0x32, - 0xea, 0x15, 0xd1, 0x72, 0x1d, 0x03, 0xf4, 0x82, 0xd7, 0xce, - 0x6e, 0x74, 0xfe, 0xf6, 0xd5, 0x5e, 0x70, 0x2f, 0x46, 0x98, - 0x0c, 0x82, 0xb5, 0xa8, 0x40, 0x31, 0x90, 0x0b, 0x1c, 0x9e, - 0x59, 0xe7, 0xc9, 0x7f, 0xbe, 0xc7, 0xe8, 0xf3, 0x23, 0xa9, - 0x7a, 0x7e, 0x36, 0xcc, 0x88, 0xbe, 0x0f, 0x1d, 0x45, 0xb7, - 0xff, 0x58, 0x5a, 0xc5, 0x4b, 0xd4, 0x07, 0xb2, 0x2b, 0x41, - 0x54, 0xaa, 0xcc, 0x8f, 0x6d, 0x7e, 0xbf, 0x48, 0xe1, 0xd8, - 0x14, 0xcc, 0x5e, 0xd2, 0x0f, 0x80, 0x37, 0xe0, 0xa7, 0x97, - 0x15, 0xee, 0xf2, 0x9b, 0xe3, 0x28, 0x06, 0xa1, 0xd5, 0x8b, - 0xb7, 0xc5, 0xda, 0x76, 0xf5, 0x50, 0xaa, 0x3d, 0x8a, 0x1f, - 0xbf, 0xf0, 0xeb, 0x19, 0xcc, 0xb1, 0xa3, 0x13, 0xd5, 0x5c, - 0xda, 0x56, 0xc9, 0xec, 0x2e, 0xf2, 0x96, 0x32, 0x38, 0x7f, - 0xe8, 0xd7, 0x6e, 0x3c, 0x04, 0x68, 0x04, 0x3e, 0x8f, 0x66, - 0x3f, 0x48, 0x60, 0xee, 0x12, 0xbf, 0x2d, 0x5b, 0x0b, 0x74, - 0x74, 0xd6, 0xe6, 0x94, 0xf9, 0x1e, 0x6d, 0xbe, 0x11, 0x59, - 0x74, 0xa3, 0x92, 0x6f, 0x12, 0xfe, 0xe5, 0xe4, 0x38, 0x77, - 0x7c, 0xb6, 0xa9, 0x32, 0xdf, 0x8c, 0xd8, 0xbe, 0xc4, 0xd0, - 0x73, 0xb9, 0x31, 0xba, 0x3b, 0xc8, 0x32, 0xb6, 0x8d, 0x9d, - 0xd3, 0x00, 0x74, 0x1f, 0xa7, 0xbf, 0x8a, 0xfc, 0x47, 0xed, - 0x25, 0x76, 0xf6, 0x93, 0x6b, 0xa4, 0x24, 0x66, 0x3a, 0xab, - 0x63, 0x9c, 0x5a, 0xe4, 0xf5, 0x68, 0x34, 0x23, 0xb4, 0x74, - 0x2b, 0xf1, 0xc9, 0x78, 0x23, 0x8f, 0x16, 0xcb, 0xe3, 0x9d, - 0x65, 0x2d, 0xe3, 0xfd, 0xb8, 0xbe, 0xfc, 0x84, 0x8a, 0xd9, - 0x22, 0x22, 0x2e, 0x04, 0xa4, 0x03, 0x7c, 0x07, 0x13, 0xeb, - 0x57, 0xa8, 0x1a, 0x23, 0xf0, 0xc7, 0x34, 0x73, 0xfc, 0x64, - 0x6c, 0xea, 0x30, 0x6b, 0x4b, 0xcb, 0xc8, 0x86, 0x2f, 0x83, - 0x85, 0xdd, 0xfa, 0x9d, 0x4b, 0x7f, 0xa2, 0xc0, 0x87, 0xe8, - 0x79, 0x68, 0x33, 0x03, 0xed, 0x5b, 0xdd, 0x3a, 0x06, 0x2b, - 0x3c, 0xf5, 0xb3, 0xa2, 0x78, 0xa6, 0x6d, 0x2a, 0x13, 0xf8, - 0x3f, 0x44, 0xf8, 0x2d, 0xdf, 0x31, 0x0e, 0xe0, 0x74, 0xab, - 0x6a, 0x36, 0x45, 0x97, 0xe8, 0x99, 0xa0, 0x25, 0x5d, 0xc1, - 0x64, 0xf3, 0x1c, 0xc5, 0x08, 0x46, 0x85, 0x1d, 0xf9, 0xab, - 0x48, 0x19, 0x5d, 0xed, 0x7e, 0xa1, 0xb1, 0xd5, 0x10, 0xbd, - 0x7e, 0xe7, 0x4d, 0x73, 0xfa, 0xf3, 0x6b, 0xc3, 0x1e, 0xcf, - 0xa2, 0x68, 0x35, 0x90, 0x46, 0xf4, 0xeb, 0x87, 0x9f, 0x92, - 0x40, 0x09, 0x43, 0x8b, 0x48, 0x1c, 0x6c, 0xd7, 0x88, 0x9a, - 0x00, 0x2e, 0xd5, 0xee, 0x38, 0x2b, 0xc9, 0x19, 0x0d, 0xa6, - 0xfc, 0x02, 0x6e, 0x47, 0x95, 0x58, 0xe4, 0x47, 0x56, 0x77, - 0xe9, 0xaa, 0x9e, 0x30, 0x50, 0xe2, 0x76, 0x56, 0x94, 0xdf, - 0xc8, 0x1f, 0x56, 0xe8, 0x80, 0xb9, 0x6e, 0x71, 0x60, 0xc9, - 0x80, 0xdd, 0x98, 0xed, 0xd3, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff }; + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, + 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, + 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, + 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, + 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, + 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, + 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, + 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36, + 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, + 0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, + 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08, + 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, + 0xec, 0x07, 0xa2, 0x8f, 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, + 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7c, + 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, + 0x04, 0x50, 0x7a, 0x33, 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, + 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, 0x8a, 0xea, 0x71, 0x57, + 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, + 0x4a, 0x25, 0x61, 0x9d, 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, + 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, 0xd8, 0x76, 0x02, 0x73, + 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, + 0xba, 0xd9, 0x46, 0xe2, 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, + 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, 0x4b, 0x82, 0xd1, 0x20, + 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, 0xa7, 0x87, 0xe6, 0xd7, + 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, + 0x6a, 0xf4, 0xe2, 0x3c, 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, + 0x25, 0x83, 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, 0xdb, 0xbb, 0xc2, 0xdb, + 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, 0xca, 0xa6, + 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, 0x99, 0xb2, 0x96, 0x4f, + 0xa0, 0x90, 0xc3, 0xa2, 0x23, 0x3b, 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, + 0x1f, 0x61, 0x29, 0x70, 0xce, 0xe2, 0xd7, 0xaf, 0xb8, 0x1b, 0xdd, 0x76, + 0x21, 0x70, 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, + 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, 0xb7, 0xdc, + 0x90, 0xa6, 0xc0, 0x8f, 0x4d, 0xf4, 0x35, 0xc9, 0x34, 0x02, 0x84, 0x92, + 0x36, 0xc3, 0xfa, 0xb4, 0xd2, 0x7c, 0x70, 0x26, 0xc1, 0xd4, 0xdc, 0xb2, + 0x60, 0x26, 0x46, 0xde, 0xc9, 0x75, 0x1e, 0x76, 0x3d, 0xba, 0x37, 0xbd, + 0xf8, 0xff, 0x94, 0x06, 0xad, 0x9e, 0x53, 0x0e, 0xe5, 0xdb, 0x38, 0x2f, + 0x41, 0x30, 0x01, 0xae, 0xb0, 0x6a, 0x53, 0xed, 0x90, 0x27, 0xd8, 0x31, + 0x17, 0x97, 0x27, 0xb0, 0x86, 0x5a, 0x89, 0x18, 0xda, 0x3e, 0xdb, 0xeb, + 0xcf, 0x9b, 0x14, 0xed, 0x44, 0xce, 0x6c, 0xba, 0xce, 0xd4, 0xbb, 0x1b, + 0xdb, 0x7f, 0x14, 0x47, 0xe6, 0xcc, 0x25, 0x4b, 0x33, 0x20, 0x51, 0x51, + 0x2b, 0xd7, 0xaf, 0x42, 0x6f, 0xb8, 0xf4, 0x01, 0x37, 0x8c, 0xd2, 0xbf, + 0x59, 0x83, 0xca, 0x01, 0xc6, 0x4b, 0x92, 0xec, 0xf0, 0x32, 0xea, 0x15, + 0xd1, 0x72, 0x1d, 0x03, 0xf4, 0x82, 0xd7, 0xce, 0x6e, 0x74, 0xfe, 0xf6, + 0xd5, 0x5e, 0x70, 0x2f, 0x46, 0x98, 0x0c, 0x82, 0xb5, 0xa8, 0x40, 0x31, + 0x90, 0x0b, 0x1c, 0x9e, 0x59, 0xe7, 0xc9, 0x7f, 0xbe, 0xc7, 0xe8, 0xf3, + 0x23, 0xa9, 0x7a, 0x7e, 0x36, 0xcc, 0x88, 0xbe, 0x0f, 0x1d, 0x45, 0xb7, + 0xff, 0x58, 0x5a, 0xc5, 0x4b, 0xd4, 0x07, 0xb2, 0x2b, 0x41, 0x54, 0xaa, + 0xcc, 0x8f, 0x6d, 0x7e, 0xbf, 0x48, 0xe1, 0xd8, 0x14, 0xcc, 0x5e, 0xd2, + 0x0f, 0x80, 0x37, 0xe0, 0xa7, 0x97, 0x15, 0xee, 0xf2, 0x9b, 0xe3, 0x28, + 0x06, 0xa1, 0xd5, 0x8b, 0xb7, 0xc5, 0xda, 0x76, 0xf5, 0x50, 0xaa, 0x3d, + 0x8a, 0x1f, 0xbf, 0xf0, 0xeb, 0x19, 0xcc, 0xb1, 0xa3, 0x13, 0xd5, 0x5c, + 0xda, 0x56, 0xc9, 0xec, 0x2e, 0xf2, 0x96, 0x32, 0x38, 0x7f, 0xe8, 0xd7, + 0x6e, 0x3c, 0x04, 0x68, 0x04, 0x3e, 0x8f, 0x66, 0x3f, 0x48, 0x60, 0xee, + 0x12, 0xbf, 0x2d, 0x5b, 0x0b, 0x74, 0x74, 0xd6, 0xe6, 0x94, 0xf9, 0x1e, + 0x6d, 0xbe, 0x11, 0x59, 0x74, 0xa3, 0x92, 0x6f, 0x12, 0xfe, 0xe5, 0xe4, + 0x38, 0x77, 0x7c, 0xb6, 0xa9, 0x32, 0xdf, 0x8c, 0xd8, 0xbe, 0xc4, 0xd0, + 0x73, 0xb9, 0x31, 0xba, 0x3b, 0xc8, 0x32, 0xb6, 0x8d, 0x9d, 0xd3, 0x00, + 0x74, 0x1f, 0xa7, 0xbf, 0x8a, 0xfc, 0x47, 0xed, 0x25, 0x76, 0xf6, 0x93, + 0x6b, 0xa4, 0x24, 0x66, 0x3a, 0xab, 0x63, 0x9c, 0x5a, 0xe4, 0xf5, 0x68, + 0x34, 0x23, 0xb4, 0x74, 0x2b, 0xf1, 0xc9, 0x78, 0x23, 0x8f, 0x16, 0xcb, + 0xe3, 0x9d, 0x65, 0x2d, 0xe3, 0xfd, 0xb8, 0xbe, 0xfc, 0x84, 0x8a, 0xd9, + 0x22, 0x22, 0x2e, 0x04, 0xa4, 0x03, 0x7c, 0x07, 0x13, 0xeb, 0x57, 0xa8, + 0x1a, 0x23, 0xf0, 0xc7, 0x34, 0x73, 0xfc, 0x64, 0x6c, 0xea, 0x30, 0x6b, + 0x4b, 0xcb, 0xc8, 0x86, 0x2f, 0x83, 0x85, 0xdd, 0xfa, 0x9d, 0x4b, 0x7f, + 0xa2, 0xc0, 0x87, 0xe8, 0x79, 0x68, 0x33, 0x03, 0xed, 0x5b, 0xdd, 0x3a, + 0x06, 0x2b, 0x3c, 0xf5, 0xb3, 0xa2, 0x78, 0xa6, 0x6d, 0x2a, 0x13, 0xf8, + 0x3f, 0x44, 0xf8, 0x2d, 0xdf, 0x31, 0x0e, 0xe0, 0x74, 0xab, 0x6a, 0x36, + 0x45, 0x97, 0xe8, 0x99, 0xa0, 0x25, 0x5d, 0xc1, 0x64, 0xf3, 0x1c, 0xc5, + 0x08, 0x46, 0x85, 0x1d, 0xf9, 0xab, 0x48, 0x19, 0x5d, 0xed, 0x7e, 0xa1, + 0xb1, 0xd5, 0x10, 0xbd, 0x7e, 0xe7, 0x4d, 0x73, 0xfa, 0xf3, 0x6b, 0xc3, + 0x1e, 0xcf, 0xa2, 0x68, 0x35, 0x90, 0x46, 0xf4, 0xeb, 0x87, 0x9f, 0x92, + 0x40, 0x09, 0x43, 0x8b, 0x48, 0x1c, 0x6c, 0xd7, 0x88, 0x9a, 0x00, 0x2e, + 0xd5, 0xee, 0x38, 0x2b, 0xc9, 0x19, 0x0d, 0xa6, 0xfc, 0x02, 0x6e, 0x47, + 0x95, 0x58, 0xe4, 0x47, 0x56, 0x77, 0xe9, 0xaa, 0x9e, 0x30, 0x50, 0xe2, + 0x76, 0x56, 0x94, 0xdf, 0xc8, 0x1f, 0x56, 0xe8, 0x80, 0xb9, 0x6e, 0x71, + 0x60, 0xc9, 0x80, 0xdd, 0x98, 0xed, 0xd3, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff}; typedef struct { const char* name; @@ -400,14 +341,14 @@ typedef struct { static const modp_group modp_groups[] = { #define V(var) reinterpret_cast(var) - { "modp1", V(group_modp1), sizeof(group_modp1), V(two_generator), 1 }, - { "modp2", V(group_modp2), sizeof(group_modp2), V(two_generator), 1 }, - { "modp5", V(group_modp5), sizeof(group_modp5), V(two_generator), 1 }, - { "modp14", V(group_modp14), sizeof(group_modp14), V(two_generator), 1 }, - { "modp15", V(group_modp15), sizeof(group_modp15), V(two_generator), 1 }, - { "modp16", V(group_modp16), sizeof(group_modp16), V(two_generator), 1 }, - { "modp17", V(group_modp17), sizeof(group_modp17), V(two_generator), 1 }, - { "modp18", V(group_modp18), sizeof(group_modp18), V(two_generator), 1 } + {"modp1", V(group_modp1), sizeof(group_modp1), V(two_generator), 1}, + {"modp2", V(group_modp2), sizeof(group_modp2), V(two_generator), 1}, + {"modp5", V(group_modp5), sizeof(group_modp5), V(two_generator), 1}, + {"modp14", V(group_modp14), sizeof(group_modp14), V(two_generator), 1}, + {"modp15", V(group_modp15), sizeof(group_modp15), V(two_generator), 1}, + {"modp16", V(group_modp16), sizeof(group_modp16), V(two_generator), 1}, + {"modp17", V(group_modp17), sizeof(group_modp17), V(two_generator), 1}, + {"modp18", V(group_modp18), sizeof(group_modp18), V(two_generator), 1} #undef V }; diff --git a/src/node_debug_options.cc b/src/node_debug_options.cc index 5fc29059ddc84f..ec766eb9e7eaff 100644 --- a/src/node_debug_options.cc +++ b/src/node_debug_options.cc @@ -21,8 +21,8 @@ int parse_and_validate_port(const std::string& port) { char* endptr; errno = 0; const long result = strtol(port.c_str(), &endptr, 10); // NOLINT(runtime/int) - if (errno != 0 || *endptr != '\0'|| - (result != 0 && result < 1024) || result > 65535) { + if (errno != 0 || *endptr != '\0' || (result != 0 && result < 1024) || + result > 65535) { fprintf(stderr, "Debug port must be 0 or in range 1024 to 65535.\n"); exit(12); } @@ -33,8 +33,7 @@ std::pair split_host_port(const std::string& arg) { // remove_brackets only works if no port is specified // so if it has an effect only an IPv6 address was specified std::string host = remove_brackets(arg); - if (host.length() < arg.length()) - return {host, -1}; + if (host.length() < arg.length()) return {host, -1}; size_t colon = arg.rfind(':'); if (colon == std::string::npos) { @@ -54,12 +53,13 @@ std::pair split_host_port(const std::string& arg) { } // namespace -DebugOptions::DebugOptions() : - inspector_enabled_(false), - deprecated_debug_(false), - break_first_line_(false), - break_node_first_line_(false), - host_name_("127.0.0.1"), port_(-1) { } +DebugOptions::DebugOptions() + : inspector_enabled_(false), + deprecated_debug_(false), + break_first_line_(false), + break_node_first_line_(false), + host_name_("127.0.0.1"), + port_(-1) {} bool DebugOptions::ParseOption(const char* argv0, const std::string& option) { bool has_argument = false; @@ -97,11 +97,9 @@ bool DebugOptions::ParseOption(const char* argv0, const std::string& option) { } else if (option_name == "--debug-brk") { break_first_line_ = true; deprecated_debug_ = true; - } else if (option_name == "--debug-port" || - option_name == "--inspect-port") { + } else if (option_name == "--debug-port" || option_name == "--inspect-port") { if (!has_argument) { - fprintf(stderr, "%s: %s requires an argument\n", - argv0, option.c_str()); + fprintf(stderr, "%s: %s requires an argument\n", argv0, option.c_str()); exit(9); } } else { diff --git a/src/node_debug_options.h b/src/node_debug_options.h index 98922ab099ac77..470cc3e938c2e5 100644 --- a/src/node_debug_options.h +++ b/src/node_debug_options.h @@ -12,9 +12,7 @@ class DebugOptions { bool ParseOption(const char* argv0, const std::string& option); bool inspector_enabled() const { return inspector_enabled_; } bool deprecated_invocation() const { - return deprecated_debug_ && - inspector_enabled_ && - break_first_line_; + return deprecated_debug_ && inspector_enabled_ && break_first_line_; } bool invalid_invocation() const { return deprecated_debug_ && !inspector_enabled_; diff --git a/src/node_domain.cc b/src/node_domain.cc index f4f585ac4f43e2..6f7af0c443ec1b 100644 --- a/src/node_domain.cc +++ b/src/node_domain.cc @@ -1,5 +1,5 @@ -#include "v8.h" #include "node_internals.h" +#include "v8.h" namespace node { namespace domain { @@ -11,7 +11,6 @@ using v8::Local; using v8::Object; using v8::Value; - void Enable(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); diff --git a/src/node_dtrace.cc b/src/node_dtrace.cc index 66e24afcacd974..7cfdfd203cecae 100644 --- a/src/node_dtrace.cc +++ b/src/node_dtrace.cc @@ -59,91 +59,89 @@ using v8::Object; using v8::String; using v8::Value; -#define SLURP_STRING(obj, member, valp) \ - if (!(obj)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected object for " #obj " to contain string member " #member); \ - } \ - node::Utf8Value _##member(env->isolate(), \ - obj->Get(OneByteString(env->isolate(), #member))); \ - if ((*(const char **)valp = *_##member) == nullptr) \ - *(const char **)valp = ""; - -#define SLURP_INT(obj, member, valp) \ - if (!(obj)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected object for " #obj " to contain integer member " #member);\ - } \ - *valp = obj->Get(OneByteString(env->isolate(), #member)) \ - ->Int32Value(); - -#define SLURP_OBJECT(obj, member, valp) \ - if (!(obj)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected object for " #obj " to contain object member " #member); \ - } \ +#define SLURP_STRING(obj, member, valp) \ + if (!(obj)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, \ + "expected object for " #obj " to contain string member " #member); \ + } \ + node::Utf8Value _##member(env->isolate(), \ + obj->Get(OneByteString(env->isolate(), #member))); \ + if ((*(const char**)valp = *_##member) == nullptr) \ + *(const char**)valp = ""; + +#define SLURP_INT(obj, member, valp) \ + if (!(obj)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, \ + "expected object for " #obj " to contain integer member " #member); \ + } \ + *valp = obj->Get(OneByteString(env->isolate(), #member))->Int32Value(); + +#define SLURP_OBJECT(obj, member, valp) \ + if (!(obj)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, \ + "expected object for " #obj " to contain object member " #member); \ + } \ *valp = Local::Cast(obj->Get(OneByteString(env->isolate(), #member))); -#define SLURP_CONNECTION(arg, conn) \ - if (!(arg)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected argument " #arg " to be a connection object"); \ - } \ - node_dtrace_connection_t conn; \ - Local _##conn = Local::Cast(arg); \ - Local _handle = \ - (_##conn)->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "_handle")); \ - if (_handle->IsObject()) { \ - SLURP_INT(_handle.As(), fd, &conn.fd); \ - } else { \ - conn.fd = -1; \ - } \ - SLURP_STRING(_##conn, remoteAddress, &conn.remote); \ - SLURP_INT(_##conn, remotePort, &conn.port); \ +#define SLURP_CONNECTION(arg, conn) \ + if (!(arg)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, "expected argument " #arg " to be a connection object"); \ + } \ + node_dtrace_connection_t conn; \ + Local _##conn = Local::Cast(arg); \ + Local _handle = \ + (_##conn)->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "_handle")); \ + if (_handle->IsObject()) { \ + SLURP_INT(_handle.As(), fd, &conn.fd); \ + } else { \ + conn.fd = -1; \ + } \ + SLURP_STRING(_##conn, remoteAddress, &conn.remote); \ + SLURP_INT(_##conn, remotePort, &conn.port); \ SLURP_INT(_##conn, bufferSize, &conn.buffered); -#define SLURP_CONNECTION_HTTP_CLIENT(arg, conn) \ - if (!(arg)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected argument " #arg " to be a connection object"); \ - } \ - node_dtrace_connection_t conn; \ - Local _##conn = Local::Cast(arg); \ - SLURP_INT(_##conn, fd, &conn.fd); \ - SLURP_STRING(_##conn, host, &conn.remote); \ - SLURP_INT(_##conn, port, &conn.port); \ +#define SLURP_CONNECTION_HTTP_CLIENT(arg, conn) \ + if (!(arg)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, "expected argument " #arg " to be a connection object"); \ + } \ + node_dtrace_connection_t conn; \ + Local _##conn = Local::Cast(arg); \ + SLURP_INT(_##conn, fd, &conn.fd); \ + SLURP_STRING(_##conn, host, &conn.remote); \ + SLURP_INT(_##conn, port, &conn.port); \ SLURP_INT(_##conn, bufferSize, &conn.buffered); -#define SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(arg0, arg1, conn) \ - if (!(arg0)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected argument " #arg0 " to be a connection object"); \ - } \ - if (!(arg1)->IsObject()) { \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - "expected argument " #arg1 " to be a connection object"); \ - } \ - node_dtrace_connection_t conn; \ - Local _##conn = Local::Cast(arg0); \ - SLURP_INT(_##conn, fd, &conn.fd); \ - SLURP_INT(_##conn, bufferSize, &conn.buffered); \ - _##conn = Local::Cast(arg1); \ - SLURP_STRING(_##conn, host, &conn.remote); \ +#define SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(arg0, arg1, conn) \ + if (!(arg0)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, "expected argument " #arg0 " to be a connection object"); \ + } \ + if (!(arg1)->IsObject()) { \ + return node::THROW_ERR_INVALID_ARG_TYPE( \ + env, "expected argument " #arg1 " to be a connection object"); \ + } \ + node_dtrace_connection_t conn; \ + Local _##conn = Local::Cast(arg0); \ + SLURP_INT(_##conn, fd, &conn.fd); \ + SLURP_INT(_##conn, bufferSize, &conn.buffered); \ + _##conn = Local::Cast(arg1); \ + SLURP_STRING(_##conn, host, &conn.remote); \ SLURP_INT(_##conn, port, &conn.port); - void DTRACE_NET_SERVER_CONNECTION(const FunctionCallbackInfo& args) { - if (!NODE_NET_SERVER_CONNECTION_ENABLED()) - return; + if (!NODE_NET_SERVER_CONNECTION_ENABLED()) return; Environment* env = Environment::GetCurrent(args); SLURP_CONNECTION(args[0], conn); NODE_NET_SERVER_CONNECTION(&conn, conn.remote, conn.port, conn.fd); } - void DTRACE_NET_STREAM_END(const FunctionCallbackInfo& args) { - if (!NODE_NET_STREAM_END_ENABLED()) - return; + if (!NODE_NET_STREAM_END_ENABLED()) return; Environment* env = Environment::GetCurrent(args); SLURP_CONNECTION(args[0], conn); NODE_NET_STREAM_END(&conn, conn.remote, conn.port, conn.fd); @@ -152,8 +150,7 @@ void DTRACE_NET_STREAM_END(const FunctionCallbackInfo& args) { void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo& args) { node_dtrace_http_server_request_t req; - if (!NODE_HTTP_SERVER_REQUEST_ENABLED()) - return; + if (!NODE_HTTP_SERVER_REQUEST_ENABLED()) return; Environment* env = Environment::GetCurrent(args); HandleScope scope(env->isolate()); @@ -167,8 +164,8 @@ void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo& args) { SLURP_OBJECT(arg0, headers, &headers); if (!(headers)->IsObject()) { - return node::THROW_ERR_INVALID_ARG_TYPE(env, - "expected object for request to contain string member headers"); + return node::THROW_ERR_INVALID_ARG_TYPE( + env, "expected object for request to contain string member headers"); } Local strfwdfor = headers->Get(env->x_forwarded_string()); @@ -178,26 +175,22 @@ void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo& args) { req.forwardedFor = const_cast(""); SLURP_CONNECTION(args[1], conn); - NODE_HTTP_SERVER_REQUEST(&req, &conn, conn.remote, conn.port, req.method, \ - req.url, conn.fd); + NODE_HTTP_SERVER_REQUEST( + &req, &conn, conn.remote, conn.port, req.method, req.url, conn.fd); } - void DTRACE_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo& args) { - if (!NODE_HTTP_SERVER_RESPONSE_ENABLED()) - return; + if (!NODE_HTTP_SERVER_RESPONSE_ENABLED()) return; Environment* env = Environment::GetCurrent(args); SLURP_CONNECTION(args[0], conn); NODE_HTTP_SERVER_RESPONSE(&conn, conn.remote, conn.port, conn.fd); } - void DTRACE_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo& args) { node_dtrace_http_client_request_t req; char* header; - if (!NODE_HTTP_CLIENT_REQUEST_ENABLED()) - return; + if (!NODE_HTTP_CLIENT_REQUEST_ENABLED()) return; Environment* env = Environment::GetCurrent(args); HandleScope scope(env->isolate()); @@ -213,48 +206,40 @@ void DTRACE_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo& args) { req.method = header; - while (*header != '\0' && *header != ' ') - header++; + while (*header != '\0' && *header != ' ') header++; - if (*header != '\0') - *header++ = '\0'; + if (*header != '\0') *header++ = '\0'; req.url = header; - while (*header != '\0' && *header != ' ') - header++; + while (*header != '\0' && *header != ' ') header++; *header = '\0'; SLURP_CONNECTION_HTTP_CLIENT(args[1], conn); - NODE_HTTP_CLIENT_REQUEST(&req, &conn, conn.remote, conn.port, req.method, \ - req.url, conn.fd); + NODE_HTTP_CLIENT_REQUEST( + &req, &conn, conn.remote, conn.port, req.method, req.url, conn.fd); } - void DTRACE_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo& args) { - if (!NODE_HTTP_CLIENT_RESPONSE_ENABLED()) - return; + if (!NODE_HTTP_CLIENT_RESPONSE_ENABLED()) return; Environment* env = Environment::GetCurrent(args); SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(args[0], args[1], conn); NODE_HTTP_CLIENT_RESPONSE(&conn, conn.remote, conn.port, conn.fd); } - void dtrace_gc_start(Isolate* isolate, GCType type, GCCallbackFlags flags) { // Previous versions of this probe point only logged type and flags. // That's why for reasons of backwards compatibility the isolate goes last. NODE_GC_START(type, flags, isolate); } - void dtrace_gc_done(Isolate* isolate, GCType type, GCCallbackFlags flags) { // Previous versions of this probe point only logged type and flags. // That's why for reasons of backwards compatibility the isolate goes last. NODE_GC_DONE(type, flags, isolate); } - void InitDTrace(Environment* env, Local target) { HandleScope scope(env->isolate()); @@ -263,12 +248,12 @@ void InitDTrace(Environment* env, Local target) { void (*func)(const FunctionCallbackInfo&); } tab[] = { #define NODE_PROBE(name) #name, name - { NODE_PROBE(DTRACE_NET_SERVER_CONNECTION) }, - { NODE_PROBE(DTRACE_NET_STREAM_END) }, - { NODE_PROBE(DTRACE_HTTP_SERVER_REQUEST) }, - { NODE_PROBE(DTRACE_HTTP_SERVER_RESPONSE) }, - { NODE_PROBE(DTRACE_HTTP_CLIENT_REQUEST) }, - { NODE_PROBE(DTRACE_HTTP_CLIENT_RESPONSE) } + {NODE_PROBE(DTRACE_NET_SERVER_CONNECTION)}, + {NODE_PROBE(DTRACE_NET_STREAM_END)}, + {NODE_PROBE(DTRACE_HTTP_SERVER_REQUEST)}, + {NODE_PROBE(DTRACE_HTTP_SERVER_RESPONSE)}, + {NODE_PROBE(DTRACE_HTTP_CLIENT_REQUEST)}, + {NODE_PROBE(DTRACE_HTTP_CLIENT_RESPONSE)} #undef NODE_PROBE }; diff --git a/src/node_dtrace.h b/src/node_dtrace.h index d16e23ddb384b7..8e6bff6c09f2a2 100644 --- a/src/node_dtrace.h +++ b/src/node_dtrace.h @@ -63,7 +63,7 @@ typedef struct { typedef struct { union { uint32_t version; - uintptr_t unused; /* for compat. with old 64-bit struct */ + uintptr_t unused; /* for compat. with old 64-bit struct */ } _un; char* url; char* method; diff --git a/src/node_encoding.cc b/src/node_encoding.cc index d5c6bcab488dd2..a24e950c4ac7aa 100644 --- a/src/node_encoding.cc +++ b/src/node_encoding.cc @@ -1,5 +1,5 @@ -#include "node.h" #include "env-inl.h" +#include "node.h" #include "string_bytes.h" #include "util-inl.h" #include "v8.h" @@ -19,35 +19,29 @@ enum encoding ParseEncoding(const char* encoding, if (encoding[1] == 't' && encoding[2] == 'f') { // Skip `-` encoding += encoding[3] == '-' ? 4 : 3; - if (encoding[0] == '8' && encoding[1] == '\0') - return UTF8; - if (strncmp(encoding, "16le", 4) == 0) - return UCS2; + if (encoding[0] == '8' && encoding[1] == '\0') return UTF8; + if (strncmp(encoding, "16le", 4) == 0) return UCS2; - // ucs2 + // ucs2 } else if (encoding[1] == 'c' && encoding[2] == 's') { encoding += encoding[3] == '-' ? 4 : 3; - if (encoding[0] == '2' && encoding[1] == '\0') - return UCS2; + if (encoding[0] == '2' && encoding[1] == '\0') return UCS2; } break; case 'l': // latin1 if (encoding[1] == 'a') { - if (strncmp(encoding + 2, "tin1", 4) == 0) - return LATIN1; + if (strncmp(encoding + 2, "tin1", 4) == 0) return LATIN1; } break; case 'b': // binary if (encoding[1] == 'i') { - if (strncmp(encoding + 2, "nary", 4) == 0) - return LATIN1; + if (strncmp(encoding + 2, "nary", 4) == 0) return LATIN1; - // buffer + // buffer } else if (encoding[1] == 'u') { - if (strncmp(encoding + 2, "ffer", 4) == 0) - return BUFFER; + if (strncmp(encoding + 2, "ffer", 4) == 0) return BUFFER; } break; case '\0': @@ -85,14 +79,12 @@ enum encoding ParseEncoding(const char* encoding, } } - enum encoding ParseEncoding(Isolate* isolate, Local encoding_v, enum encoding default_encoding) { CHECK(!encoding_v.IsEmpty()); - if (!encoding_v->IsString()) - return default_encoding; + if (!encoding_v->IsString()) return default_encoding; Utf8Value encoding(isolate, encoding_v); @@ -111,8 +103,7 @@ Local Encode(Isolate* isolate, Local Encode(Isolate* isolate, const uint16_t* buf, size_t len) { Local error; - return StringBytes::Encode(isolate, buf, len, &error) - .ToLocalChecked(); + return StringBytes::Encode(isolate, buf, len, &error).ToLocalChecked(); } // Returns -1 if the handle was not valid for decoding diff --git a/src/node_errors.h b/src/node_errors.h index fdfb670af636af..26370c86101ba6 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -3,9 +3,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "env-inl.h" #include "node.h" #include "util-inl.h" -#include "env-inl.h" #include "v8.h" // Use ostringstream to print exact-width integer types @@ -20,71 +20,73 @@ namespace node { // `node::ERR_INVALID_ARG_TYPE(isolate, "message")` returning // a `Local` containing the TypeError with proper code and message -#define ERRORS_WITH_CODE(V) \ - V(ERR_BUFFER_OUT_OF_BOUNDS, RangeError) \ - V(ERR_BUFFER_TOO_LARGE, Error) \ - V(ERR_CANNOT_TRANSFER_OBJECT, TypeError) \ - V(ERR_CLOSED_MESSAGE_PORT, Error) \ - V(ERR_CONSTRUCT_CALL_REQUIRED, Error) \ - V(ERR_INDEX_OUT_OF_RANGE, RangeError) \ - V(ERR_INVALID_ARG_VALUE, TypeError) \ - V(ERR_INVALID_ARG_TYPE, TypeError) \ - V(ERR_INVALID_TRANSFER_OBJECT, TypeError) \ - V(ERR_MEMORY_ALLOCATION_FAILED, Error) \ - V(ERR_MISSING_ARGS, TypeError) \ - V(ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, TypeError) \ - V(ERR_MISSING_MODULE, Error) \ - V(ERR_MISSING_PLATFORM_FOR_WORKER, Error) \ - V(ERR_SCRIPT_EXECUTION_INTERRUPTED, Error) \ - V(ERR_SCRIPT_EXECUTION_TIMEOUT, Error) \ - V(ERR_STRING_TOO_LONG, Error) \ - V(ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER, TypeError) \ - -#define V(code, type) \ - inline v8::Local code(v8::Isolate* isolate, \ - const char* message) { \ - v8::Local js_code = OneByteString(isolate, #code); \ - v8::Local js_msg = OneByteString(isolate, message); \ - v8::Local e = \ - v8::Exception::type(js_msg)->ToObject( \ - isolate->GetCurrentContext()).ToLocalChecked(); \ - e->Set(isolate->GetCurrentContext(), OneByteString(isolate, "code"), \ - js_code).FromJust(); \ - return e; \ - } \ - inline void THROW_ ## code(Environment* env, const char* message) { \ - env->isolate()->ThrowException(code(env->isolate(), message)); \ +#define ERRORS_WITH_CODE(V) \ + V(ERR_BUFFER_OUT_OF_BOUNDS, RangeError) \ + V(ERR_BUFFER_TOO_LARGE, Error) \ + V(ERR_CANNOT_TRANSFER_OBJECT, TypeError) \ + V(ERR_CLOSED_MESSAGE_PORT, Error) \ + V(ERR_CONSTRUCT_CALL_REQUIRED, Error) \ + V(ERR_INDEX_OUT_OF_RANGE, RangeError) \ + V(ERR_INVALID_ARG_VALUE, TypeError) \ + V(ERR_INVALID_ARG_TYPE, TypeError) \ + V(ERR_INVALID_TRANSFER_OBJECT, TypeError) \ + V(ERR_MEMORY_ALLOCATION_FAILED, Error) \ + V(ERR_MISSING_ARGS, TypeError) \ + V(ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, TypeError) \ + V(ERR_MISSING_MODULE, Error) \ + V(ERR_MISSING_PLATFORM_FOR_WORKER, Error) \ + V(ERR_SCRIPT_EXECUTION_INTERRUPTED, Error) \ + V(ERR_SCRIPT_EXECUTION_TIMEOUT, Error) \ + V(ERR_STRING_TOO_LONG, Error) \ + V(ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER, TypeError) + +#define V(code, type) \ + inline v8::Local code(v8::Isolate* isolate, \ + const char* message) { \ + v8::Local js_code = OneByteString(isolate, #code); \ + v8::Local js_msg = OneByteString(isolate, message); \ + v8::Local e = v8::Exception::type(js_msg) \ + ->ToObject(isolate->GetCurrentContext()) \ + .ToLocalChecked(); \ + e->Set(isolate->GetCurrentContext(), \ + OneByteString(isolate, "code"), \ + js_code) \ + .FromJust(); \ + return e; \ + } \ + inline void THROW_##code(Environment* env, const char* message) { \ + env->isolate()->ThrowException(code(env->isolate(), message)); \ } - ERRORS_WITH_CODE(V) +ERRORS_WITH_CODE(V) #undef V // Errors with predefined static messages -#define PREDEFINED_ERROR_MESSAGES(V) \ - V(ERR_CANNOT_TRANSFER_OBJECT, "Cannot transfer object of unsupported type")\ - V(ERR_CLOSED_MESSAGE_PORT, "Cannot send data on closed MessagePort") \ - V(ERR_CONSTRUCT_CALL_REQUIRED, "Cannot call constructor without `new`") \ - V(ERR_INDEX_OUT_OF_RANGE, "Index out of range") \ - V(ERR_INVALID_TRANSFER_OBJECT, "Found invalid object in transferList") \ - V(ERR_MEMORY_ALLOCATION_FAILED, "Failed to allocate memory") \ - V(ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, \ - "MessagePort was found in message but not listed in transferList") \ - V(ERR_MISSING_PLATFORM_FOR_WORKER, \ - "The V8 platform used by this instance of Node does not support " \ - "creating Workers") \ - V(ERR_SCRIPT_EXECUTION_INTERRUPTED, \ - "Script execution was interrupted by `SIGINT`") \ - V(ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER, \ - "Cannot serialize externalized SharedArrayBuffer") \ - -#define V(code, message) \ - inline v8::Local code(v8::Isolate* isolate) { \ - return code(isolate, message); \ - } \ - inline void THROW_ ## code(Environment* env) { \ - env->isolate()->ThrowException(code(env->isolate(), message)); \ +#define PREDEFINED_ERROR_MESSAGES(V) \ + V(ERR_CANNOT_TRANSFER_OBJECT, "Cannot transfer object of unsupported type") \ + V(ERR_CLOSED_MESSAGE_PORT, "Cannot send data on closed MessagePort") \ + V(ERR_CONSTRUCT_CALL_REQUIRED, "Cannot call constructor without `new`") \ + V(ERR_INDEX_OUT_OF_RANGE, "Index out of range") \ + V(ERR_INVALID_TRANSFER_OBJECT, "Found invalid object in transferList") \ + V(ERR_MEMORY_ALLOCATION_FAILED, "Failed to allocate memory") \ + V(ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, \ + "MessagePort was found in message but not listed in transferList") \ + V(ERR_MISSING_PLATFORM_FOR_WORKER, \ + "The V8 platform used by this instance of Node does not support " \ + "creating Workers") \ + V(ERR_SCRIPT_EXECUTION_INTERRUPTED, \ + "Script execution was interrupted by `SIGINT`") \ + V(ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER, \ + "Cannot serialize externalized SharedArrayBuffer") + +#define V(code, message) \ + inline v8::Local code(v8::Isolate* isolate) { \ + return code(isolate, message); \ + } \ + inline void THROW_##code(Environment* env) { \ + env->isolate()->ThrowException(code(env->isolate(), message)); \ } - PREDEFINED_ERROR_MESSAGES(V) +PREDEFINED_ERROR_MESSAGES(V) #undef V // Errors with predefined non-static messages @@ -98,32 +100,34 @@ inline void THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(Environment* env, inline v8::Local ERR_BUFFER_TOO_LARGE(v8::Isolate* isolate) { char message[128]; - snprintf(message, sizeof(message), - "Cannot create a Buffer larger than 0x%zx bytes", - v8::TypedArray::kMaxLength); + snprintf(message, + sizeof(message), + "Cannot create a Buffer larger than 0x%zx bytes", + v8::TypedArray::kMaxLength); return ERR_BUFFER_TOO_LARGE(isolate, message); } inline v8::Local ERR_STRING_TOO_LONG(v8::Isolate* isolate) { char message[128]; - snprintf(message, sizeof(message), - "Cannot create a string longer than 0x%x characters", - v8::String::kMaxLength); + snprintf(message, + sizeof(message), + "Cannot create a string longer than 0x%x characters", + v8::String::kMaxLength); return ERR_STRING_TOO_LONG(isolate, message); } -#define THROW_AND_RETURN_IF_NOT_BUFFER(env, val, prefix) \ - do { \ - if (!Buffer::HasInstance(val)) \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - prefix " must be a buffer"); \ +#define THROW_AND_RETURN_IF_NOT_BUFFER(env, val, prefix) \ + do { \ + if (!Buffer::HasInstance(val)) \ + return node::THROW_ERR_INVALID_ARG_TYPE(env, \ + prefix " must be a buffer"); \ } while (0) -#define THROW_AND_RETURN_IF_NOT_STRING(env, val, prefix) \ - do { \ - if (!val->IsString()) \ - return node::THROW_ERR_INVALID_ARG_TYPE(env, \ - prefix " must be a string"); \ +#define THROW_AND_RETURN_IF_NOT_STRING(env, val, prefix) \ + do { \ + if (!val->IsString()) \ + return node::THROW_ERR_INVALID_ARG_TYPE(env, \ + prefix " must be a string"); \ } while (0) } // namespace node diff --git a/src/node_file.cc b/src/node_file.cc index 16f2506d1f2e2b..db3bda64343eba 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -19,11 +19,11 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +#include "node_file.h" #include "aliased_buffer.h" #include "node_buffer.h" #include "node_internals.h" #include "node_stat_watcher.h" -#include "node_file.h" #include "tracing/trace_event.h" #include "req_wrap-inl.h" @@ -31,15 +31,15 @@ #include "string_bytes.h" #include "string_search.h" -#include -#include -#include -#include #include +#include #include +#include +#include +#include #if defined(__MINGW32__) || defined(_MSC_VER) -# include +#include #endif #include @@ -73,27 +73,27 @@ using v8::Undefined; using v8::Value; #ifndef MIN -# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #define GET_OFFSET(a) ((a)->IsNumber() ? (a).As()->Value() : -1) #define TRACE_NAME(name) "fs.sync." #name -#define GET_TRACE_ENABLED \ - (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED \ - (TRACING_CATEGORY_NODE2(fs, sync)) != 0) -#define FS_SYNC_TRACE_BEGIN(syscall, ...) \ - if (GET_TRACE_ENABLED) \ - TRACE_EVENT_BEGIN(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), \ - ##__VA_ARGS__); -#define FS_SYNC_TRACE_END(syscall, ...) \ - if (GET_TRACE_ENABLED) \ - TRACE_EVENT_END(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), \ - ##__VA_ARGS__); +#define GET_TRACE_ENABLED \ + (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( \ + TRACING_CATEGORY_NODE2(fs, sync)) != 0) +#define FS_SYNC_TRACE_BEGIN(syscall, ...) \ + if (GET_TRACE_ENABLED) \ + TRACE_EVENT_BEGIN( \ + TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), ##__VA_ARGS__); +#define FS_SYNC_TRACE_END(syscall, ...) \ + if (GET_TRACE_ENABLED) \ + TRACE_EVENT_END( \ + TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), ##__VA_ARGS__); // We sometimes need to convert a C++ lambda function to a raw C-style function. // This is helpful, because ReqWrap::Dispatch() does not recognize lambda // functions, and thus does not wrap them properly. -typedef void(*uv_fs_callback_t)(uv_fs_t*); +typedef void (*uv_fs_callback_t)(uv_fs_t*); // The FileHandle object wraps a file descriptor and will close it on garbage // collection if necessary. If that happens, a process warning will be @@ -101,17 +101,21 @@ typedef void(*uv_fs_callback_t)(uv_fs_t*); FileHandle::FileHandle(Environment* env, int fd, Local obj) : AsyncWrap(env, obj.IsEmpty() ? env->fd_constructor_template() - ->NewInstance(env->context()).ToLocalChecked() : obj, + ->NewInstance(env->context()) + .ToLocalChecked() + : obj, AsyncWrap::PROVIDER_FILEHANDLE), StreamBase(env), fd_(fd) { MakeWeak(); v8::PropertyAttribute attr = static_cast(v8::ReadOnly | v8::DontDelete); - object()->DefineOwnProperty(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "fd"), - Integer::New(env->isolate(), fd), - attr).FromJust(); + object() + ->DefineOwnProperty(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "fd"), + Integer::New(env->isolate(), fd), + attr) + .FromJust(); } void FileHandle::New(const FunctionCallbackInfo& args) { @@ -133,7 +137,6 @@ FileHandle::~FileHandle() { CHECK(closed_); // We have to be closed at the point } - // Close the file descriptor if it hasn't already been closed. A process // warning will be emitted using a SetImmediate to avoid calling back to // JS during GC. If closing the fd fails at this point, a fatal exception @@ -145,39 +148,47 @@ inline void FileHandle::Close() { uv_fs_req_cleanup(&req); AfterClose(); - struct err_detail { int ret; int fd; }; + struct err_detail { + int ret; + int fd; + }; - err_detail* detail = new err_detail { ret, fd_ }; + err_detail* detail = new err_detail{ret, fd_}; if (ret < 0) { // Do not unref this - env()->SetImmediate([](Environment* env, void* data) { - char msg[70]; - err_detail* detail = static_cast(data); - snprintf(msg, arraysize(msg), - "Closing file descriptor %d on garbage collection failed", - detail->fd); - // This exception will end up being fatal for the process because - // it is being thrown from within the SetImmediate handler and - // there is no JS stack to bubble it to. In other words, tearing - // down the process is the only reasonable thing we can do here. - HandleScope handle_scope(env->isolate()); - env->ThrowUVException(detail->ret, "close", msg); - delete detail; - }, detail); + env()->SetImmediate( + [](Environment* env, void* data) { + char msg[70]; + err_detail* detail = static_cast(data); + snprintf(msg, + arraysize(msg), + "Closing file descriptor %d on garbage collection failed", + detail->fd); + // This exception will end up being fatal for the process because + // it is being thrown from within the SetImmediate handler and + // there is no JS stack to bubble it to. In other words, tearing + // down the process is the only reasonable thing we can do here. + HandleScope handle_scope(env->isolate()); + env->ThrowUVException(detail->ret, "close", msg); + delete detail; + }, + detail); return; } // If the close was successful, we still want to emit a process warning // to notify that the file descriptor was gc'd. We want to be noisy about // this because not explicitly closing the FileHandle is a bug. - env()->SetUnrefImmediate([](Environment* env, void* data) { - err_detail* detail = static_cast(data); - ProcessEmitWarning(env, - "Closing file descriptor %d on garbage collection", - detail->fd); - delete detail; - }, detail); + env()->SetUnrefImmediate( + [](Environment* env, void* data) { + err_detail* detail = static_cast(data); + ProcessEmitWarning(env, + "Closing file descriptor %d on garbage collection", + detail->fd); + delete detail; + }, + detail); } void FileHandle::CloseReq::Resolve() { @@ -251,7 +262,6 @@ void FileHandle::Close(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(fd->ClosePromise().ToLocalChecked()); } - void FileHandle::ReleaseFD(const FunctionCallbackInfo& args) { FileHandle* fd; ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder()); @@ -259,27 +269,22 @@ void FileHandle::ReleaseFD(const FunctionCallbackInfo& args) { fd->AfterClose(); } - void FileHandle::AfterClose() { closing_ = false; closed_ = true; - if (reading_ && !persistent().IsEmpty()) - EmitRead(UV_EOF); + if (reading_ && !persistent().IsEmpty()) EmitRead(UV_EOF); } - FileHandleReadWrap::FileHandleReadWrap(FileHandle* handle, Local obj) - : ReqWrap(handle->env(), obj, AsyncWrap::PROVIDER_FSREQWRAP), - file_handle_(handle) {} + : ReqWrap(handle->env(), obj, AsyncWrap::PROVIDER_FSREQWRAP), + file_handle_(handle) {} int FileHandle::ReadStart() { - if (!IsAlive() || IsClosing()) - return UV_EOF; + if (!IsAlive() || IsClosing()) return UV_EOF; reading_ = true; - if (current_read_) - return 0; + if (current_read_) return 0; std::unique_ptr read_wrap; @@ -302,8 +307,10 @@ int FileHandle::ReadStart() { read_wrap->AsyncReset(); read_wrap->file_handle_ = this; } else { - Local wrap_obj = env()->filehandlereadwrap_template() - ->NewInstance(env()->context()).ToLocalChecked(); + Local wrap_obj = env() + ->filehandlereadwrap_template() + ->NewInstance(env()->context()) + .ToLocalChecked(); read_wrap.reset(new FileHandleReadWrap(this, wrap_obj)); } } @@ -315,65 +322,63 @@ int FileHandle::ReadStart() { current_read_ = std::move(read_wrap); - current_read_->Dispatch(uv_fs_read, - fd_, - ¤t_read_->buffer_, - 1, - read_offset_, - uv_fs_callback_t{[](uv_fs_t* req) { - FileHandle* handle; - { - FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req); - handle = req_wrap->file_handle_; - CHECK_EQ(handle->current_read_.get(), req_wrap); - } - - // ReadStart() checks whether current_read_ is set to determine whether - // a read is in progress. Moving it into a local variable makes sure that - // the ReadStart() call below doesn't think we're still actively reading. - std::unique_ptr read_wrap = - std::move(handle->current_read_); - - int result = req->result; - uv_buf_t buffer = read_wrap->buffer_; - - uv_fs_req_cleanup(req); + current_read_->Dispatch( + uv_fs_read, + fd_, + ¤t_read_->buffer_, + 1, + read_offset_, + uv_fs_callback_t{[](uv_fs_t* req) { + FileHandle* handle; + { + FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req); + handle = req_wrap->file_handle_; + CHECK_EQ(handle->current_read_.get(), req_wrap); + } - // Push the read wrap back to the freelist, or let it be destroyed - // once we’re exiting the current scope. - constexpr size_t wanted_freelist_fill = 100; - auto& freelist = handle->env()->file_handle_read_wrap_freelist(); - if (freelist.size() < wanted_freelist_fill) { - read_wrap->Reset(); - freelist.emplace_back(std::move(read_wrap)); - } + // ReadStart() checks whether current_read_ is set to determine whether + // a read is in progress. Moving it into a local variable makes sure + // that the ReadStart() call below doesn't think we're still actively + // reading. + std::unique_ptr read_wrap = + std::move(handle->current_read_); + + int result = req->result; + uv_buf_t buffer = read_wrap->buffer_; + + uv_fs_req_cleanup(req); + + // Push the read wrap back to the freelist, or let it be destroyed + // once we’re exiting the current scope. + constexpr size_t wanted_freelist_fill = 100; + auto& freelist = handle->env()->file_handle_read_wrap_freelist(); + if (freelist.size() < wanted_freelist_fill) { + read_wrap->Reset(); + freelist.emplace_back(std::move(read_wrap)); + } - if (result >= 0) { - // Read at most as many bytes as we originally planned to. - if (handle->read_length_ >= 0 && handle->read_length_ < result) - result = handle->read_length_; + if (result >= 0) { + // Read at most as many bytes as we originally planned to. + if (handle->read_length_ >= 0 && handle->read_length_ < result) + result = handle->read_length_; - // If we read data and we have an expected length, decrease it by - // how much we have read. - if (handle->read_length_ >= 0) - handle->read_length_ -= result; + // If we read data and we have an expected length, decrease it by + // how much we have read. + if (handle->read_length_ >= 0) handle->read_length_ -= result; - // If we have an offset, increase it by how much we have read. - if (handle->read_offset_ >= 0) - handle->read_offset_ += result; - } + // If we have an offset, increase it by how much we have read. + if (handle->read_offset_ >= 0) handle->read_offset_ += result; + } - // Reading 0 bytes from a file always means EOF, or that we reached - // the end of the requested range. - if (result == 0) - result = UV_EOF; + // Reading 0 bytes from a file always means EOF, or that we reached + // the end of the requested range. + if (result == 0) result = UV_EOF; - handle->EmitRead(result, buffer); + handle->EmitRead(result, buffer); - // Start over, if EmitRead() didn’t tell us to stop. - if (handle->reading_) - handle->ReadStart(); - }}); + // Start over, if EmitRead() didn’t tell us to stop. + if (handle->reading_) handle->ReadStart(); + }}); return 0; } @@ -392,21 +397,21 @@ ShutdownWrap* FileHandle::CreateShutdownWrap(Local object) { int FileHandle::DoShutdown(ShutdownWrap* req_wrap) { FileHandleCloseWrap* wrap = static_cast(req_wrap); closing_ = true; - wrap->Dispatch(uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) { - FileHandleCloseWrap* wrap = static_cast( - FileHandleCloseWrap::from_req(req)); - FileHandle* handle = static_cast(wrap->stream()); - handle->AfterClose(); - - int result = req->result; - uv_fs_req_cleanup(req); - wrap->Done(result); - }}); + wrap->Dispatch( + uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) { + FileHandleCloseWrap* wrap = static_cast( + FileHandleCloseWrap::from_req(req)); + FileHandle* handle = static_cast(wrap->stream()); + handle->AfterClose(); + + int result = req->result; + uv_fs_req_cleanup(req); + wrap->Done(result); + }}); return 0; } - void FSReqWrap::Reject(Local reject) { MakeCallback(env()->oncomplete_string(), 1, &reject); } @@ -416,10 +421,7 @@ void FSReqWrap::ResolveStat(const uv_stat_t* stat) { } void FSReqWrap::Resolve(Local value) { - Local argv[2] { - Null(env()->isolate()), - value - }; + Local argv[2]{Null(env()->isolate()), value}; MakeCallback(env()->oncomplete_string(), value->IsUndefined() ? 1 : arraysize(argv), argv); @@ -478,8 +480,7 @@ void AfterNoArgs(uv_fs_t* req) { FSReqBase* req_wrap = FSReqBase::from_req(req); FSReqAfterScope after(req_wrap, req); - if (after.Proceed()) - req_wrap->Resolve(Undefined(req_wrap->env()->isolate())); + if (after.Proceed()) req_wrap->Resolve(Undefined(req_wrap->env()->isolate())); } void AfterStat(uv_fs_t* req) { @@ -560,45 +561,39 @@ void AfterScanDir(uv_fs_t* req) { Local name_argv[NODE_PUSH_VAL_TO_ARRAY_MAX]; size_t name_idx = 0; - for (int i = 0; ; i++) { + for (int i = 0;; i++) { uv_dirent_t ent; r = uv_fs_scandir_next(req, &ent); - if (r == UV_EOF) - break; + if (r == UV_EOF) break; if (r != 0) { return req_wrap->Reject( - UVException(r, nullptr, req_wrap->syscall(), + UVException(r, + nullptr, + req_wrap->syscall(), static_cast(req->path))); } - MaybeLocal filename = - StringBytes::Encode(env->isolate(), - ent.name, - req_wrap->encoding(), - &error); - if (filename.IsEmpty()) - return req_wrap->Reject(error); + MaybeLocal filename = StringBytes::Encode( + env->isolate(), ent.name, req_wrap->encoding(), &error); + if (filename.IsEmpty()) return req_wrap->Reject(error); name_argv[name_idx++] = filename.ToLocalChecked(); if (name_idx >= arraysize(name_argv)) { - fn->Call(env->context(), names, name_idx, name_argv) - .ToLocalChecked(); + fn->Call(env->context(), names, name_idx, name_argv).ToLocalChecked(); name_idx = 0; } } if (name_idx > 0) { - fn->Call(env->context(), names, name_idx, name_argv) - .ToLocalChecked(); + fn->Call(env->context(), names, name_idx, name_argv).ToLocalChecked(); } req_wrap->Resolve(names); } } - // This class is only used on sync fs calls. // For async calls FSReqWrap is used. class FSReqWrapSync { @@ -614,10 +609,15 @@ class FSReqWrapSync { // Returns nullptr if the operation fails from the start. template inline FSReqBase* AsyncDestCall(Environment* env, - FSReqBase* req_wrap, - const FunctionCallbackInfo& args, - const char* syscall, const char* dest, size_t len, - enum encoding enc, uv_fs_cb after, Func fn, Args... fn_args) { + FSReqBase* req_wrap, + const FunctionCallbackInfo& args, + const char* syscall, + const char* dest, + size_t len, + enum encoding enc, + uv_fs_cb after, + Func fn, + Args... fn_args) { CHECK_NOT_NULL(req_wrap); req_wrap->Init(syscall, dest, len, enc); int err = req_wrap->Dispatch(fn, fn_args..., after); @@ -637,13 +637,15 @@ inline FSReqBase* AsyncDestCall(Environment* env, // Returns nullptr if the operation fails from the start. template inline FSReqBase* AsyncCall(Environment* env, - FSReqBase* req_wrap, - const FunctionCallbackInfo& args, - const char* syscall, enum encoding enc, - uv_fs_cb after, Func fn, Args... fn_args) { - return AsyncDestCall(env, req_wrap, args, - syscall, nullptr, 0, enc, - after, fn, fn_args...); + FSReqBase* req_wrap, + const FunctionCallbackInfo& args, + const char* syscall, + enum encoding enc, + uv_fs_cb after, + Func fn, + Args... fn_args) { + return AsyncDestCall( + env, req_wrap, args, syscall, nullptr, 0, enc, after, fn, fn_args...); } // Template counterpart of SYNC_CALL, except that it only puts @@ -651,25 +653,29 @@ inline FSReqBase* AsyncCall(Environment* env, // creating an error in the C++ land. // ctx must be checked using value->IsObject() before being passed. template -inline int SyncCall(Environment* env, Local ctx, FSReqWrapSync* req_wrap, - const char* syscall, Func fn, Args... args) { +inline int SyncCall(Environment* env, + Local ctx, + FSReqWrapSync* req_wrap, + const char* syscall, + Func fn, + Args... args) { env->PrintSyncTrace(); int err = fn(env->event_loop(), &(req_wrap->req), args..., nullptr); if (err < 0) { Local context = env->context(); Local ctx_obj = ctx.As(); Isolate* isolate = env->isolate(); - ctx_obj->Set(context, - env->errno_string(), - Integer::New(isolate, err)).FromJust(); - ctx_obj->Set(context, - env->syscall_string(), - OneByteString(isolate, syscall)).FromJust(); + ctx_obj->Set(context, env->errno_string(), Integer::New(isolate, err)) + .FromJust(); + ctx_obj + ->Set(context, env->syscall_string(), OneByteString(isolate, syscall)) + .FromJust(); } return err; } -inline FSReqBase* GetReqWrap(Environment* env, Local value, +inline FSReqBase* GetReqWrap(Environment* env, + Local value, bool use_bigint = false) { if (value->IsObject()) { return Unwrap(value.As()); @@ -698,8 +704,15 @@ void Access(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // access(path, mode, req) - AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs, - uv_fs_access, *path, mode); + AsyncCall(env, + req_wrap_async, + args, + "access", + UTF8, + AfterNoArgs, + uv_fs_access, + *path, + mode); } else { // access(path, mode, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; @@ -709,7 +722,6 @@ void Access(const FunctionCallbackInfo& args) { } } - void Close(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -721,8 +733,8 @@ void Close(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[1]); if (req_wrap_async != nullptr) { // close(fd, req) - AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs, - uv_fs_close, fd); + AsyncCall( + env, req_wrap_async, args, "close", UTF8, AfterNoArgs, uv_fs_close, fd); } else { // close(fd, undefined, ctx) CHECK_EQ(argc, 3); FSReqWrapSync req_wrap_sync; @@ -732,7 +744,6 @@ void Close(const FunctionCallbackInfo& args) { } } - // Used to speed up module loading. Returns the contents of the file as // a string or undefined when the file cannot be opened or "main" is not found // in the file. @@ -743,8 +754,7 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo& args) { CHECK(args[0]->IsString()); node::Utf8Value path(env->isolate(), args[0]); - if (strlen(*path) != path.length()) - return; // Contains a nul byte. + if (strlen(*path) != path.length()) return; // Contains a nul byte. uv_fs_t open_req; const int fd = uv_fs_open(loop, &open_req, *path, O_RDONLY, 0, nullptr); @@ -754,7 +764,7 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo& args) { return; } - std::shared_ptr defer_close(nullptr, [fd, loop] (...) { + std::shared_ptr defer_close(nullptr, [fd, loop](...) { uv_fs_t close_req; CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr)); uv_fs_req_cleanup(&close_req); @@ -776,8 +786,7 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo& args) { numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr); uv_fs_req_cleanup(&read_req); - if (numchars < 0) - return; + if (numchars < 0) return; offset += numchars; } while (static_cast(numchars) == kBlockSize); @@ -792,10 +801,9 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo& args) { return; } else { Local chars_string = - String::NewFromUtf8(env->isolate(), - &chars[start], - v8::NewStringType::kNormal, - size).ToLocalChecked(); + String::NewFromUtf8( + env->isolate(), &chars[start], v8::NewStringType::kNormal, size) + .ToLocalChecked(); args.GetReturnValue().Set(chars_string); } } @@ -832,8 +840,8 @@ static void Stat(const FunctionCallbackInfo& args) { bool use_bigint = args[1]->IsTrue(); FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint); if (req_wrap_async != nullptr) { // stat(path, use_bigint, req) - AsyncCall(env, req_wrap_async, args, "stat", UTF8, AfterStat, - uv_fs_stat, *path); + AsyncCall( + env, req_wrap_async, args, "stat", UTF8, AfterStat, uv_fs_stat, *path); } else { // stat(path, use_bigint, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; @@ -844,8 +852,8 @@ static void Stat(const FunctionCallbackInfo& args) { return; // error info is in ctx } - Local arr = node::FillGlobalStatsArray(env, - static_cast(req_wrap_sync.req.ptr), use_bigint); + Local arr = node::FillGlobalStatsArray( + env, static_cast(req_wrap_sync.req.ptr), use_bigint); args.GetReturnValue().Set(arr); } } @@ -862,21 +870,27 @@ static void LStat(const FunctionCallbackInfo& args) { bool use_bigint = args[1]->IsTrue(); FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint); if (req_wrap_async != nullptr) { // lstat(path, use_bigint, req) - AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat, - uv_fs_lstat, *path); + AsyncCall(env, + req_wrap_async, + args, + "lstat", + UTF8, + AfterStat, + uv_fs_lstat, + *path); } else { // lstat(path, use_bigint, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(lstat); - int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat, - *path); + int err = + SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat, *path); FS_SYNC_TRACE_END(lstat); if (err != 0) { return; // error info is in ctx } - Local arr = node::FillGlobalStatsArray(env, - static_cast(req_wrap_sync.req.ptr), use_bigint); + Local arr = node::FillGlobalStatsArray( + env, static_cast(req_wrap_sync.req.ptr), use_bigint); args.GetReturnValue().Set(arr); } } @@ -893,8 +907,8 @@ static void FStat(const FunctionCallbackInfo& args) { bool use_bigint = args[1]->IsTrue(); FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint); if (req_wrap_async != nullptr) { // fstat(fd, use_bigint, req) - AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat, - uv_fs_fstat, fd); + AsyncCall( + env, req_wrap_async, args, "fstat", UTF8, AfterStat, uv_fs_fstat, fd); } else { // fstat(fd, use_bigint, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; @@ -905,8 +919,8 @@ static void FStat(const FunctionCallbackInfo& args) { return; // error info is in ctx } - Local arr = node::FillGlobalStatsArray(env, - static_cast(req_wrap_sync.req.ptr), use_bigint); + Local arr = node::FillGlobalStatsArray( + env, static_cast(req_wrap_sync.req.ptr), use_bigint); args.GetReturnValue().Set(arr); } } @@ -927,14 +941,30 @@ static void Symlink(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // symlink(target, path, flags, req) - AsyncDestCall(env, req_wrap_async, args, "symlink", *path, path.length(), - UTF8, AfterNoArgs, uv_fs_symlink, *target, *path, flags); + AsyncDestCall(env, + req_wrap_async, + args, + "symlink", + *path, + path.length(), + UTF8, + AfterNoArgs, + uv_fs_symlink, + *target, + *path, + flags); } else { // symlink(target, path, flags, undefinec, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(symlink); - SyncCall(env, args[4], &req_wrap_sync, "symlink", - uv_fs_symlink, *target, *path, flags); + SyncCall(env, + args[4], + &req_wrap_sync, + "symlink", + uv_fs_symlink, + *target, + *path, + flags); FS_SYNC_TRACE_END(symlink); } } @@ -953,14 +983,22 @@ static void Link(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // link(src, dest, req) - AsyncDestCall(env, req_wrap_async, args, "link", *dest, dest.length(), UTF8, - AfterNoArgs, uv_fs_link, *src, *dest); + AsyncDestCall(env, + req_wrap_async, + args, + "link", + *dest, + dest.length(), + UTF8, + AfterNoArgs, + uv_fs_link, + *src, + *dest); } else { // link(src, dest) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(link); - SyncCall(env, args[3], &req_wrap_sync, "link", - uv_fs_link, *src, *dest); + SyncCall(env, args[3], &req_wrap_sync, "link", uv_fs_link, *src, *dest); FS_SYNC_TRACE_END(link); } } @@ -978,14 +1016,20 @@ static void ReadLink(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // readlink(path, encoding, req) - AsyncCall(env, req_wrap_async, args, "readlink", encoding, AfterStringPtr, - uv_fs_readlink, *path); + AsyncCall(env, + req_wrap_async, + args, + "readlink", + encoding, + AfterStringPtr, + uv_fs_readlink, + *path); } else { CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(readlink); - int err = SyncCall(env, args[3], &req_wrap_sync, "readlink", - uv_fs_readlink, *path); + int err = SyncCall( + env, args[3], &req_wrap_sync, "readlink", uv_fs_readlink, *path); FS_SYNC_TRACE_END(readlink); if (err < 0) { return; // syscall failed, no need to continue, error info is in ctx @@ -993,10 +1037,8 @@ static void ReadLink(const FunctionCallbackInfo& args) { const char* link_path = static_cast(req_wrap_sync.req.ptr); Local error; - MaybeLocal rc = StringBytes::Encode(env->isolate(), - link_path, - encoding, - &error); + MaybeLocal rc = + StringBytes::Encode(env->isolate(), link_path, encoding, &error); if (rc.IsEmpty()) { Local ctx = args[3].As(); ctx->Set(env->context(), env->error_string(), error).FromJust(); @@ -1020,15 +1062,28 @@ static void Rename(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { - AsyncDestCall(env, req_wrap_async, args, "rename", *new_path, - new_path.length(), UTF8, AfterNoArgs, uv_fs_rename, - *old_path, *new_path); + AsyncDestCall(env, + req_wrap_async, + args, + "rename", + *new_path, + new_path.length(), + UTF8, + AfterNoArgs, + uv_fs_rename, + *old_path, + *new_path); } else { CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(rename); - SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename, - *old_path, *new_path); + SyncCall(env, + args[3], + &req_wrap_sync, + "rename", + uv_fs_rename, + *old_path, + *new_path); FS_SYNC_TRACE_END(rename); } } @@ -1047,14 +1102,21 @@ static void FTruncate(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { - AsyncCall(env, req_wrap_async, args, "ftruncate", UTF8, AfterNoArgs, - uv_fs_ftruncate, fd, len); + AsyncCall(env, + req_wrap_async, + args, + "ftruncate", + UTF8, + AfterNoArgs, + uv_fs_ftruncate, + fd, + len); } else { CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(ftruncate); - SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd, - len); + SyncCall( + env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd, len); FS_SYNC_TRACE_END(ftruncate); } } @@ -1070,8 +1132,14 @@ static void Fdatasync(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[1]); if (req_wrap_async != nullptr) { - AsyncCall(env, req_wrap_async, args, "fdatasync", UTF8, AfterNoArgs, - uv_fs_fdatasync, fd); + AsyncCall(env, + req_wrap_async, + args, + "fdatasync", + UTF8, + AfterNoArgs, + uv_fs_fdatasync, + fd); } else { CHECK_EQ(argc, 3); FSReqWrapSync req_wrap_sync; @@ -1092,8 +1160,8 @@ static void Fsync(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[1]); if (req_wrap_async != nullptr) { - AsyncCall(env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs, - uv_fs_fsync, fd); + AsyncCall( + env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs, uv_fs_fsync, fd); } else { CHECK_EQ(argc, 3); FSReqWrapSync req_wrap_sync; @@ -1114,8 +1182,14 @@ static void Unlink(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[1]); if (req_wrap_async != nullptr) { - AsyncCall(env, req_wrap_async, args, "unlink", UTF8, AfterNoArgs, - uv_fs_unlink, *path); + AsyncCall(env, + req_wrap_async, + args, + "unlink", + UTF8, + AfterNoArgs, + uv_fs_unlink, + *path); } else { CHECK_EQ(argc, 3); FSReqWrapSync req_wrap_sync; @@ -1136,14 +1210,19 @@ static void RMDir(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[1]); // rmdir(path, req) if (req_wrap_async != nullptr) { - AsyncCall(env, req_wrap_async, args, "rmdir", UTF8, AfterNoArgs, - uv_fs_rmdir, *path); + AsyncCall(env, + req_wrap_async, + args, + "rmdir", + UTF8, + AfterNoArgs, + uv_fs_rmdir, + *path); } else { // rmdir(path, undefined, ctx) CHECK_EQ(argc, 3); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(rmdir); - SyncCall(env, args[2], &req_wrap_sync, "rmdir", - uv_fs_rmdir, *path); + SyncCall(env, args[2], &req_wrap_sync, "rmdir", uv_fs_rmdir, *path); FS_SYNC_TRACE_END(rmdir); } } @@ -1162,14 +1241,20 @@ static void MKDir(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // mkdir(path, mode, req) - AsyncCall(env, req_wrap_async, args, "mkdir", UTF8, AfterNoArgs, - uv_fs_mkdir, *path, mode); + AsyncCall(env, + req_wrap_async, + args, + "mkdir", + UTF8, + AfterNoArgs, + uv_fs_mkdir, + *path, + mode); } else { // mkdir(path, mode, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(mkdir); - SyncCall(env, args[3], &req_wrap_sync, "mkdir", - uv_fs_mkdir, *path, mode); + SyncCall(env, args[3], &req_wrap_sync, "mkdir", uv_fs_mkdir, *path, mode); FS_SYNC_TRACE_END(mkdir); } } @@ -1187,14 +1272,20 @@ static void RealPath(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // realpath(path, encoding, req) - AsyncCall(env, req_wrap_async, args, "realpath", encoding, AfterStringPtr, - uv_fs_realpath, *path); + AsyncCall(env, + req_wrap_async, + args, + "realpath", + encoding, + AfterStringPtr, + uv_fs_realpath, + *path); } else { // realpath(path, encoding, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(realpath); - int err = SyncCall(env, args[3], &req_wrap_sync, "realpath", - uv_fs_realpath, *path); + int err = SyncCall( + env, args[3], &req_wrap_sync, "realpath", uv_fs_realpath, *path); FS_SYNC_TRACE_END(realpath); if (err < 0) { return; // syscall failed, no need to continue, error info is in ctx @@ -1203,10 +1294,8 @@ static void RealPath(const FunctionCallbackInfo& args) { const char* link_path = static_cast(req_wrap_sync.req.ptr); Local error; - MaybeLocal rc = StringBytes::Encode(env->isolate(), - link_path, - encoding, - &error); + MaybeLocal rc = + StringBytes::Encode(env->isolate(), link_path, encoding, &error); if (rc.IsEmpty()) { Local ctx = args[3].As(); ctx->Set(env->context(), env->error_string(), error).FromJust(); @@ -1230,14 +1319,26 @@ static void ReadDir(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // readdir(path, encoding, req) - AsyncCall(env, req_wrap_async, args, "scandir", encoding, AfterScanDir, - uv_fs_scandir, *path, 0 /*flags*/); + AsyncCall(env, + req_wrap_async, + args, + "scandir", + encoding, + AfterScanDir, + uv_fs_scandir, + *path, + 0 /*flags*/); } else { // readdir(path, encoding, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(readdir); - int err = SyncCall(env, args[3], &req_wrap_sync, "scandir", - uv_fs_scandir, *path, 0 /*flags*/); + int err = SyncCall(env, + args[3], + &req_wrap_sync, + "scandir", + uv_fs_scandir, + *path, + 0 /*flags*/); FS_SYNC_TRACE_END(readdir); if (err < 0) { return; // syscall failed, no need to continue, error info is in ctx @@ -1250,26 +1351,27 @@ static void ReadDir(const FunctionCallbackInfo& args) { Local name_v[NODE_PUSH_VAL_TO_ARRAY_MAX]; size_t name_idx = 0; - for (int i = 0; ; i++) { + for (int i = 0;; i++) { uv_dirent_t ent; r = uv_fs_scandir_next(&(req_wrap_sync.req), &ent); - if (r == UV_EOF) - break; + if (r == UV_EOF) break; if (r != 0) { Local ctx = args[3].As(); - ctx->Set(env->context(), env->errno_string(), - Integer::New(env->isolate(), r)).FromJust(); - ctx->Set(env->context(), env->syscall_string(), - OneByteString(env->isolate(), "readdir")).FromJust(); + ctx->Set(env->context(), + env->errno_string(), + Integer::New(env->isolate(), r)) + .FromJust(); + ctx->Set(env->context(), + env->syscall_string(), + OneByteString(env->isolate(), "readdir")) + .FromJust(); return; } Local error; - MaybeLocal filename = StringBytes::Encode(env->isolate(), - ent.name, - encoding, - &error); + MaybeLocal filename = + StringBytes::Encode(env->isolate(), ent.name, encoding, &error); if (filename.IsEmpty()) { Local ctx = args[3].As(); ctx->Set(env->context(), env->error_string(), error).FromJust(); @@ -1279,8 +1381,8 @@ static void ReadDir(const FunctionCallbackInfo& args) { name_v[name_idx++] = filename.ToLocalChecked(); if (name_idx >= arraysize(name_v)) { - MaybeLocal ret = fn->Call(env->context(), names, name_idx, - name_v); + MaybeLocal ret = + fn->Call(env->context(), names, name_idx, name_v); if (ret.IsEmpty()) { return; } @@ -1316,14 +1418,22 @@ static void Open(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // open(path, flags, mode, req) - AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger, - uv_fs_open, *path, flags, mode); + AsyncCall(env, + req_wrap_async, + args, + "open", + UTF8, + AfterInteger, + uv_fs_open, + *path, + flags, + mode); } else { // open(path, flags, mode, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(open); - int result = SyncCall(env, args[4], &req_wrap_sync, "open", - uv_fs_open, *path, flags, mode); + int result = SyncCall( + env, args[4], &req_wrap_sync, "open", uv_fs_open, *path, flags, mode); FS_SYNC_TRACE_END(open); args.GetReturnValue().Set(result); } @@ -1346,14 +1456,22 @@ static void OpenFileHandle(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // openFileHandle(path, flags, mode, req) - AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterOpenFileHandle, - uv_fs_open, *path, flags, mode); + AsyncCall(env, + req_wrap_async, + args, + "open", + UTF8, + AfterOpenFileHandle, + uv_fs_open, + *path, + flags, + mode); } else { // openFileHandle(path, flags, mode, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(open); - int result = SyncCall(env, args[4], &req_wrap_sync, "open", - uv_fs_open, *path, flags, mode); + int result = SyncCall( + env, args[4], &req_wrap_sync, "open", uv_fs_open, *path, flags, mode); FS_SYNC_TRACE_END(open); if (result < 0) { return; // syscall failed, no need to continue, error info is in ctx @@ -1381,20 +1499,34 @@ static void CopyFile(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // copyFile(src, dest, flags, req) - AsyncDestCall(env, req_wrap_async, args, "copyfile", - *dest, dest.length(), UTF8, AfterNoArgs, - uv_fs_copyfile, *src, *dest, flags); + AsyncDestCall(env, + req_wrap_async, + args, + "copyfile", + *dest, + dest.length(), + UTF8, + AfterNoArgs, + uv_fs_copyfile, + *src, + *dest, + flags); } else { // copyFile(src, dest, flags, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(copyfile); - SyncCall(env, args[4], &req_wrap_sync, "copyfile", - uv_fs_copyfile, *src, *dest, flags); + SyncCall(env, + args[4], + &req_wrap_sync, + "copyfile", + uv_fs_copyfile, + *src, + *dest, + flags); FS_SYNC_TRACE_END(copyfile); } } - // Wrapper for write(2). // // bytesWritten = write(fd, buffer, offset, length, position, callback) @@ -1435,20 +1567,28 @@ static void WriteBuffer(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[5]); if (req_wrap_async != nullptr) { // write(fd, buffer, off, len, pos, req) - AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger, - uv_fs_write, fd, &uvbuf, 1, pos); + AsyncCall(env, + req_wrap_async, + args, + "write", + UTF8, + AfterInteger, + uv_fs_write, + fd, + &uvbuf, + 1, + pos); } else { // write(fd, buffer, off, len, pos, undefined, ctx) CHECK_EQ(argc, 7); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(write); - int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write", - uv_fs_write, fd, &uvbuf, 1, pos); + int bytesWritten = SyncCall( + env, args[6], &req_wrap_sync, "write", uv_fs_write, fd, &uvbuf, 1, pos); FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten); args.GetReturnValue().Set(bytesWritten); } } - // Wrapper for writev(2). // // bytesWritten = writev(fd, chunks, position, callback) @@ -1480,20 +1620,35 @@ static void WriteBuffers(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // writeBuffers(fd, chunks, pos, req) - AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger, - uv_fs_write, fd, *iovs, iovs.length(), pos); + AsyncCall(env, + req_wrap_async, + args, + "write", + UTF8, + AfterInteger, + uv_fs_write, + fd, + *iovs, + iovs.length(), + pos); } else { // writeBuffers(fd, chunks, pos, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(write); - int bytesWritten = SyncCall(env, args[4], &req_wrap_sync, "write", - uv_fs_write, fd, *iovs, iovs.length(), pos); + int bytesWritten = SyncCall(env, + args[4], + &req_wrap_sync, + "write", + uv_fs_write, + fd, + *iovs, + iovs.length(), + pos); FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten); args.GetReturnValue().Set(bytesWritten); } } - // Wrapper for write(2). // // bytesWritten = write(fd, string, position, enc, callback) @@ -1552,12 +1707,8 @@ static void WriteString(const FunctionCallbackInfo& args) { len = StringBytes::Write(env->isolate(), *stack_buffer, len, args[1], enc); stack_buffer.SetLengthAndZeroTerminate(len); uv_buf_t uvbuf = uv_buf_init(*stack_buffer, len); - int err = req_wrap_async->Dispatch(uv_fs_write, - fd, - &uvbuf, - 1, - pos, - AfterInteger); + int err = + req_wrap_async->Dispatch(uv_fs_write, fd, &uvbuf, 1, pos, AfterInteger); if (err < 0) { uv_fs_t* uv_req = req_wrap_async->req(); uv_req->result = err; @@ -1576,21 +1727,20 @@ static void WriteString(const FunctionCallbackInfo& args) { stack_buffer.AllocateSufficientStorage(len + 1); // StorageSize may return too large a char, so correct the actual length // by the write size - len = StringBytes::Write(env->isolate(), *stack_buffer, - len, args[1], enc); + len = + StringBytes::Write(env->isolate(), *stack_buffer, len, args[1], enc); stack_buffer.SetLengthAndZeroTerminate(len); buf = *stack_buffer; } uv_buf_t uvbuf = uv_buf_init(buf, len); FS_SYNC_TRACE_BEGIN(write); - int bytesWritten = SyncCall(env, args[5], &req_wrap_sync, "write", - uv_fs_write, fd, &uvbuf, 1, pos); + int bytesWritten = SyncCall( + env, args[5], &req_wrap_sync, "write", uv_fs_write, fd, &uvbuf, 1, pos); FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten); args.GetReturnValue().Set(bytesWritten); } } - /* * Wrapper for read(2). * @@ -1632,20 +1782,28 @@ static void Read(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[5]); if (req_wrap_async != nullptr) { // read(fd, buffer, offset, len, pos, req) - AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger, - uv_fs_read, fd, &uvbuf, 1, pos); + AsyncCall(env, + req_wrap_async, + args, + "read", + UTF8, + AfterInteger, + uv_fs_read, + fd, + &uvbuf, + 1, + pos); } else { // read(fd, buffer, offset, len, pos, undefined, ctx) CHECK_EQ(argc, 7); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(read); - const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read", - uv_fs_read, fd, &uvbuf, 1, pos); + const int bytesRead = SyncCall( + env, args[6], &req_wrap_sync, "read", uv_fs_read, fd, &uvbuf, 1, pos); FS_SYNC_TRACE_END(read, "bytesRead", bytesRead); args.GetReturnValue().Set(bytesRead); } } - /* fs.chmod(path, mode); * Wrapper for chmod(1) / EIO_CHMOD */ @@ -1663,19 +1821,24 @@ static void Chmod(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // chmod(path, mode, req) - AsyncCall(env, req_wrap_async, args, "chmod", UTF8, AfterNoArgs, - uv_fs_chmod, *path, mode); + AsyncCall(env, + req_wrap_async, + args, + "chmod", + UTF8, + AfterNoArgs, + uv_fs_chmod, + *path, + mode); } else { // chmod(path, mode, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(chmod); - SyncCall(env, args[3], &req_wrap_sync, "chmod", - uv_fs_chmod, *path, mode); + SyncCall(env, args[3], &req_wrap_sync, "chmod", uv_fs_chmod, *path, mode); FS_SYNC_TRACE_END(chmod); } } - /* fs.fchmod(fd, mode); * Wrapper for fchmod(1) / EIO_FCHMOD */ @@ -1693,19 +1856,24 @@ static void FChmod(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // fchmod(fd, mode, req) - AsyncCall(env, req_wrap_async, args, "fchmod", UTF8, AfterNoArgs, - uv_fs_fchmod, fd, mode); + AsyncCall(env, + req_wrap_async, + args, + "fchmod", + UTF8, + AfterNoArgs, + uv_fs_fchmod, + fd, + mode); } else { // fchmod(fd, mode, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(fchmod); - SyncCall(env, args[3], &req_wrap_sync, "fchmod", - uv_fs_fchmod, fd, mode); + SyncCall(env, args[3], &req_wrap_sync, "fchmod", uv_fs_fchmod, fd, mode); FS_SYNC_TRACE_END(fchmod); } } - /* fs.chown(path, uid, gid); * Wrapper for chown(1) / EIO_CHOWN */ @@ -1726,19 +1894,26 @@ static void Chown(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // chown(path, uid, gid, req) - AsyncCall(env, req_wrap_async, args, "chown", UTF8, AfterNoArgs, - uv_fs_chown, *path, uid, gid); + AsyncCall(env, + req_wrap_async, + args, + "chown", + UTF8, + AfterNoArgs, + uv_fs_chown, + *path, + uid, + gid); } else { // chown(path, uid, gid, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(chown); - SyncCall(env, args[4], &req_wrap_sync, "chown", - uv_fs_chown, *path, uid, gid); + SyncCall( + env, args[4], &req_wrap_sync, "chown", uv_fs_chown, *path, uid, gid); FS_SYNC_TRACE_END(chown); } } - /* fs.fchown(fd, uid, gid); * Wrapper for fchown(1) / EIO_FCHOWN */ @@ -1759,19 +1934,26 @@ static void FChown(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // fchown(fd, uid, gid, req) - AsyncCall(env, req_wrap_async, args, "fchown", UTF8, AfterNoArgs, - uv_fs_fchown, fd, uid, gid); + AsyncCall(env, + req_wrap_async, + args, + "fchown", + UTF8, + AfterNoArgs, + uv_fs_fchown, + fd, + uid, + gid); } else { // fchown(fd, uid, gid, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(fchown); - SyncCall(env, args[4], &req_wrap_sync, "fchown", - uv_fs_fchown, fd, uid, gid); + SyncCall( + env, args[4], &req_wrap_sync, "fchown", uv_fs_fchown, fd, uid, gid); FS_SYNC_TRACE_END(fchown); } } - static void LChown(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1789,19 +1971,26 @@ static void LChown(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // lchown(path, uid, gid, req) - AsyncCall(env, req_wrap_async, args, "lchown", UTF8, AfterNoArgs, - uv_fs_lchown, *path, uid, gid); + AsyncCall(env, + req_wrap_async, + args, + "lchown", + UTF8, + AfterNoArgs, + uv_fs_lchown, + *path, + uid, + gid); } else { // lchown(path, uid, gid, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(lchown); - SyncCall(env, args[4], &req_wrap_sync, "lchown", - uv_fs_lchown, *path, uid, gid); + SyncCall( + env, args[4], &req_wrap_sync, "lchown", uv_fs_lchown, *path, uid, gid); FS_SYNC_TRACE_END(lchown); } } - static void UTimes(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -1819,14 +2008,28 @@ static void UTimes(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // utimes(path, atime, mtime, req) - AsyncCall(env, req_wrap_async, args, "utime", UTF8, AfterNoArgs, - uv_fs_utime, *path, atime, mtime); + AsyncCall(env, + req_wrap_async, + args, + "utime", + UTF8, + AfterNoArgs, + uv_fs_utime, + *path, + atime, + mtime); } else { // utimes(path, atime, mtime, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(utimes); - SyncCall(env, args[4], &req_wrap_sync, "utime", - uv_fs_utime, *path, atime, mtime); + SyncCall(env, + args[4], + &req_wrap_sync, + "utime", + uv_fs_utime, + *path, + atime, + mtime); FS_SYNC_TRACE_END(utimes); } } @@ -1848,14 +2051,22 @@ static void FUTimes(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[3]); if (req_wrap_async != nullptr) { // futimes(fd, atime, mtime, req) - AsyncCall(env, req_wrap_async, args, "futime", UTF8, AfterNoArgs, - uv_fs_futime, fd, atime, mtime); + AsyncCall(env, + req_wrap_async, + args, + "futime", + UTF8, + AfterNoArgs, + uv_fs_futime, + fd, + atime, + mtime); } else { // futimes(fd, atime, mtime, undefined, ctx) CHECK_EQ(argc, 5); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(futimes); - SyncCall(env, args[4], &req_wrap_sync, "futime", - uv_fs_futime, fd, atime, mtime); + SyncCall( + env, args[4], &req_wrap_sync, "futime", uv_fs_futime, fd, atime, mtime); FS_SYNC_TRACE_END(futimes); } } @@ -1873,14 +2084,19 @@ static void Mkdtemp(const FunctionCallbackInfo& args) { FSReqBase* req_wrap_async = GetReqWrap(env, args[2]); if (req_wrap_async != nullptr) { // mkdtemp(tmpl, encoding, req) - AsyncCall(env, req_wrap_async, args, "mkdtemp", encoding, AfterStringPath, - uv_fs_mkdtemp, *tmpl); + AsyncCall(env, + req_wrap_async, + args, + "mkdtemp", + encoding, + AfterStringPath, + uv_fs_mkdtemp, + *tmpl); } else { // mkdtemp(tmpl, encoding, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(mkdtemp); - SyncCall(env, args[3], &req_wrap_sync, "mkdtemp", - uv_fs_mkdtemp, *tmpl); + SyncCall(env, args[3], &req_wrap_sync, "mkdtemp", uv_fs_mkdtemp, *tmpl); FS_SYNC_TRACE_END(mkdtemp); const char* path = static_cast(req_wrap_sync.req.path); @@ -1942,18 +2158,23 @@ void Initialize(Local target, env->SetMethod(target, "mkdtemp", Mkdtemp); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kFsStatsFieldsLength"), - Integer::New(env->isolate(), env->kFsStatsFieldsLength)) - .FromJust(); + target + ->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "kFsStatsFieldsLength"), + Integer::New(env->isolate(), env->kFsStatsFieldsLength)) + .FromJust(); - target->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "statValues"), - env->fs_stats_field_array()->GetJSArray()).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "statValues"), + env->fs_stats_field_array()->GetJSArray()) + .FromJust(); - target->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "bigintStatValues"), - env->fs_stats_field_bigint_array()->GetJSArray()).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "bigintStatValues"), + env->fs_stats_field_bigint_array()->GetJSArray()) + .FromJust(); StatWatcher::Initialize(env, target); @@ -1962,8 +2183,7 @@ void Initialize(Local target, FunctionTemplate::New(env->isolate(), NewFSReqWrap); fst->InstanceTemplate()->SetInternalFieldCount(1); AsyncWrap::AddWrapMethods(env, fst); - Local wrapString = - FIXED_ONE_BYTE_STRING(env->isolate(), "FSReqWrap"); + Local wrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "FSReqWrap"); fst->SetClassName(wrapString); target->Set(context, wrapString, fst->GetFunction()).FromJust(); @@ -1975,8 +2195,7 @@ void Initialize(Local target, Local fhWrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "FileHandleReqWrap"); fh_rw->SetClassName(fhWrapString); - env->set_filehandlereadwrap_template( - fst->InstanceTemplate()); + env->set_filehandlereadwrap_template(fst->InstanceTemplate()); // Create Function Template for FSReqPromise Local fpt = FunctionTemplate::New(env->isolate()); @@ -1996,7 +2215,7 @@ void Initialize(Local target, Local fdt = fd->InstanceTemplate(); fdt->SetInternalFieldCount(1); Local handleString = - FIXED_ONE_BYTE_STRING(env->isolate(), "FileHandle"); + FIXED_ONE_BYTE_STRING(env->isolate(), "FileHandle"); fd->SetClassName(handleString); StreamBase::AddMethods(env, fd); target->Set(context, handleString, fd->GetFunction()).FromJust(); @@ -2004,20 +2223,21 @@ void Initialize(Local target, // Create FunctionTemplate for FileHandle::CloseReq Local fdclose = FunctionTemplate::New(env->isolate()); - fdclose->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), - "FileHandleCloseReq")); + fdclose->SetClassName( + FIXED_ONE_BYTE_STRING(env->isolate(), "FileHandleCloseReq")); AsyncWrap::AddWrapMethods(env, fdclose); Local fdcloset = fdclose->InstanceTemplate(); fdcloset->SetInternalFieldCount(1); env->set_fdclose_constructor_template(fdcloset); - Local use_promises_symbol = - Symbol::New(env->isolate(), - FIXED_ONE_BYTE_STRING(env->isolate(), "use promises")); + Local use_promises_symbol = Symbol::New( + env->isolate(), FIXED_ONE_BYTE_STRING(env->isolate(), "use promises")); env->set_fs_use_promises_symbol(use_promises_symbol); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kUsePromises"), - use_promises_symbol).FromJust(); + target + ->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "kUsePromises"), + use_promises_symbol) + .FromJust(); } } // namespace fs diff --git a/src/node_file.h b/src/node_file.h index 73202d9c4464b9..bf4aaaf85cdcf3 100644 --- a/src/node_file.h +++ b/src/node_file.h @@ -4,8 +4,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "node.h" -#include "stream_base.h" #include "req_wrap-inl.h" +#include "stream_base.h" namespace node { @@ -21,15 +21,15 @@ using v8::Value; namespace fs { - class FSReqBase : public ReqWrap { public: typedef MaybeStackBuffer FSReqBuffer; - FSReqBase(Environment* env, Local req, AsyncWrap::ProviderType type, + FSReqBase(Environment* env, + Local req, + AsyncWrap::ProviderType type, bool use_bigint) - : ReqWrap(env, req, type), use_bigint_(use_bigint) { - } + : ReqWrap(env, req, type), use_bigint_(use_bigint) {} void Init(const char* syscall, const char* data, @@ -47,8 +47,7 @@ class FSReqBase : public ReqWrap { } } - FSReqBuffer& Init(const char* syscall, size_t len, - enum encoding encoding) { + FSReqBuffer& Init(const char* syscall, size_t len, enum encoding encoding) { syscall_ = syscall; encoding_ = encoding; @@ -88,7 +87,7 @@ class FSReqBase : public ReqWrap { class FSReqWrap : public FSReqBase { public: FSReqWrap(Environment* env, Local req, bool use_bigint) - : FSReqBase(env, req, AsyncWrap::PROVIDER_FSREQWRAP, use_bigint) { } + : FSReqBase(env, req, AsyncWrap::PROVIDER_FSREQWRAP, use_bigint) {} void Reject(Local reject) override; void Resolve(Local value) override; @@ -111,13 +110,13 @@ class FSReqPromise : public FSReqBase { explicit FSReqPromise(Environment* env, bool use_bigint) : FSReqBase(env, env->fsreqpromise_constructor_template() - ->NewInstance(env->context()).ToLocalChecked(), + ->NewInstance(env->context()) + .ToLocalChecked(), AsyncWrap::PROVIDER_FSREQPROMISE, use_bigint), stats_field_array_(env->isolate(), env->kFsStatsFieldsLength) { auto resolver = Promise::Resolver::New(env->context()).ToLocalChecked(); - object()->Set(env->context(), env->promise_string(), - resolver).FromJust(); + object()->Set(env->context(), env->promise_string(), resolver).FromJust(); } ~FSReqPromise() override { @@ -129,9 +128,9 @@ class FSReqPromise : public FSReqBase { finished_ = true; HandleScope scope(env()->isolate()); InternalCallbackScope callback_scope(this); - Local value = - object()->Get(env()->context(), - env()->promise_string()).ToLocalChecked(); + Local value = object() + ->Get(env()->context(), env()->promise_string()) + .ToLocalChecked(); Local resolver = value.As(); resolver->Reject(env()->context(), reject).FromJust(); } @@ -140,9 +139,9 @@ class FSReqPromise : public FSReqBase { finished_ = true; HandleScope scope(env()->isolate()); InternalCallbackScope callback_scope(this); - Local val = - object()->Get(env()->context(), - env()->promise_string()).ToLocalChecked(); + Local val = object() + ->Get(env()->context(), env()->promise_string()) + .ToLocalChecked(); Local resolver = val.As(); resolver->Resolve(env()->context(), value).FromJust(); } @@ -152,9 +151,9 @@ class FSReqPromise : public FSReqBase { } void SetReturnValue(const FunctionCallbackInfo& args) override { - Local val = - object()->Get(env()->context(), - env()->promise_string()).ToLocalChecked(); + Local val = object() + ->Get(env()->context(), env()->promise_string()) + .ToLocalChecked(); Local resolver = val.As(); args.GetReturnValue().Set(resolver->GetPromise()); } @@ -267,12 +266,11 @@ class FileHandle : public AsyncWrap, public StreamBase { class CloseReq : public ReqWrap { public: - CloseReq(Environment* env, - Local promise, - Local ref) + CloseReq(Environment* env, Local promise, Local ref) : ReqWrap(env, env->fdclose_constructor_template() - ->NewInstance(env->context()).ToLocalChecked(), + ->NewInstance(env->context()) + .ToLocalChecked(), AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) { promise_.Reset(env->isolate(), promise); ref_.Reset(env->isolate(), ref); @@ -319,7 +317,6 @@ class FileHandle : public AsyncWrap, public StreamBase { bool reading_ = false; std::unique_ptr current_read_ = nullptr; - DISALLOW_COPY_AND_ASSIGN(FileHandle); }; diff --git a/src/node_http2.cc b/src/node_http2.cc index 1274bc7f5b8d4d..520b16700e2561 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -1,8 +1,8 @@ +#include "node_http2.h" #include "aliased_buffer.h" #include "debug_utils.h" #include "node.h" #include "node_buffer.h" -#include "node_http2.h" #include "node_http2_state.h" #include "node_internals.h" #include "node_perf.h" @@ -35,8 +35,7 @@ inline Http2Stream* GetStream(Http2Session* session, int32_t id, nghttp2_data_source* source) { Http2Stream* stream = static_cast(source->ptr); - if (stream == nullptr) - stream = session->FindStream(id); + if (stream == nullptr) stream = session->FindStream(id); CHECK_NOT_NULL(stream); CHECK_EQ(id, stream->id()); return stream; @@ -48,8 +47,7 @@ inline Http2Stream* GetStream(Http2Session* session, // two sets of callback functions, one that is used if a padding callback // is set, and other that does not include the padding callback. const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = { - Callbacks(false), - Callbacks(true)}; + Callbacks(false), Callbacks(true)}; // The Http2Scope object is used to queue a write to the i/o stream. It is // used whenever any action is take on the underlying nghttp2 API that may @@ -65,11 +63,10 @@ const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = { Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {} Http2Scope::Http2Scope(Http2Session* session) { - if (session == nullptr) - return; + if (session == nullptr) return; - if (session->flags_ & (SESSION_STATE_HAS_SCOPE | - SESSION_STATE_WRITE_SCHEDULED)) { + if (session->flags_ & + (SESSION_STATE_HAS_SCOPE | SESSION_STATE_WRITE_SCHEDULED)) { // There is another scope further below on the stack, or it is already // known that a write is scheduled. In either case, there is nothing to do. return; @@ -84,8 +81,7 @@ Http2Scope::Http2Scope(Http2Session* session) { } Http2Scope::~Http2Scope() { - if (session_ == nullptr) - return; + if (session_ == nullptr) return; session_->flags_ &= ~SESSION_STATE_HAS_SCOPE; session_->MaybeScheduleWrite(); @@ -117,28 +113,24 @@ Http2Options::Http2Options(Environment* env) { if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) { nghttp2_option_set_max_deflate_dynamic_table_size( - options_, - buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]); + options_, buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]); } if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) { nghttp2_option_set_max_reserved_remote_streams( - options_, - buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]); + options_, buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]); } if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) { nghttp2_option_set_max_send_header_block_length( - options_, - buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]); + options_, buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]); } // Recommended default nghttp2_option_set_peer_max_concurrent_streams(options_, 100); if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) { nghttp2_option_set_peer_max_concurrent_streams( - options_, - buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]); + options_, buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]); } // The padding strategy sets the mechanism by which we determine how much @@ -146,9 +138,8 @@ Http2Options::Http2Options(Environment* env) { // this is set on a per-session basis, but eventually we may switch to // a per-stream setting, giving users greater control if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) { - padding_strategy_type strategy = - static_cast( - buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY)); + padding_strategy_type strategy = static_cast( + buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY)); SetPaddingStrategy(strategy); } @@ -198,13 +189,11 @@ void Http2Session::Http2Settings::Init() { size_t n = 0; -#define GRABSETTING(N, trace) \ - if (flags & (1 << IDX_SETTINGS_##N)) { \ - uint32_t val = buffer[IDX_SETTINGS_##N]; \ - if (session_ != nullptr) \ - Debug(session_, "setting " trace ": %d\n", val); \ - entries_[n++] = \ - nghttp2_settings_entry {NGHTTP2_SETTINGS_##N, val}; \ +#define GRABSETTING(N, trace) \ + if (flags & (1 << IDX_SETTINGS_##N)) { \ + uint32_t val = buffer[IDX_SETTINGS_##N]; \ + if (session_ != nullptr) Debug(session_, "setting " trace ": %d\n", val); \ + entries_[n++] = nghttp2_settings_entry{NGHTTP2_SETTINGS_##N, val}; \ } GRABSETTING(HEADER_TABLE_SIZE, "header table size"); @@ -219,30 +208,29 @@ void Http2Session::Http2Settings::Init() { count_ = n; } -Http2Session::Http2Settings::Http2Settings( - Environment* env) - : AsyncWrap(env, - env->http2settings_constructor_template() - ->NewInstance(env->context()) - .ToLocalChecked(), - AsyncWrap::PROVIDER_HTTP2SETTINGS), - session_(nullptr), - startTime_(0) { +Http2Session::Http2Settings::Http2Settings(Environment* env) + : AsyncWrap(env, + env->http2settings_constructor_template() + ->NewInstance(env->context()) + .ToLocalChecked(), + AsyncWrap::PROVIDER_HTTP2SETTINGS), + session_(nullptr), + startTime_(0) { Init(); } // The Http2Settings class is used to configure a SETTINGS frame that is // to be sent to the connected peer. The settings are set using a TypedArray // that is shared with the JavaScript side. -Http2Session::Http2Settings::Http2Settings( - Http2Session* session) - : AsyncWrap(session->env(), - session->env()->http2settings_constructor_template() - ->NewInstance(session->env()->context()) - .ToLocalChecked(), - AsyncWrap::PROVIDER_HTTP2SETTINGS), - session_(session), - startTime_(uv_hrtime()) { +Http2Session::Http2Settings::Http2Settings(Http2Session* session) + : AsyncWrap(session->env(), + session->env() + ->http2settings_constructor_template() + ->NewInstance(session->env()->context()) + .ToLocalChecked(), + AsyncWrap::PROVIDER_HTTP2SETTINGS), + session_(session), + startTime_(uv_hrtime()) { Init(); } @@ -252,10 +240,8 @@ Http2Session::Http2Settings::Http2Settings( Local Http2Session::Http2Settings::Pack() { const size_t len = count_ * 6; Local buf = Buffer::New(env(), len).ToLocalChecked(); - ssize_t ret = - nghttp2_pack_settings_payload( - reinterpret_cast(Buffer::Data(buf)), len, - &entries_[0], count_); + ssize_t ret = nghttp2_pack_settings_payload( + reinterpret_cast(Buffer::Data(buf)), len, &entries_[0], count_); if (ret >= 0) return buf; else @@ -288,39 +274,33 @@ void Http2Session::Http2Settings::RefreshDefaults(Environment* env) { AliasedBuffer& buffer = env->http2_state()->settings_buffer; - buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = - DEFAULT_SETTINGS_HEADER_TABLE_SIZE; - buffer[IDX_SETTINGS_ENABLE_PUSH] = - DEFAULT_SETTINGS_ENABLE_PUSH; + buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = DEFAULT_SETTINGS_HEADER_TABLE_SIZE; + buffer[IDX_SETTINGS_ENABLE_PUSH] = DEFAULT_SETTINGS_ENABLE_PUSH; buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] = DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; - buffer[IDX_SETTINGS_MAX_FRAME_SIZE] = - DEFAULT_SETTINGS_MAX_FRAME_SIZE; + buffer[IDX_SETTINGS_MAX_FRAME_SIZE] = DEFAULT_SETTINGS_MAX_FRAME_SIZE; buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] = DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE; - buffer[IDX_SETTINGS_COUNT] = - (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) | - (1 << IDX_SETTINGS_ENABLE_PUSH) | - (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) | - (1 << IDX_SETTINGS_MAX_FRAME_SIZE) | - (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE); + buffer[IDX_SETTINGS_COUNT] = (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) | + (1 << IDX_SETTINGS_ENABLE_PUSH) | + (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) | + (1 << IDX_SETTINGS_MAX_FRAME_SIZE) | + (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE); } - void Http2Session::Http2Settings::Send() { Http2Scope h2scope(session_); - CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE, - &entries_[0], count_), 0); + CHECK_EQ(nghttp2_submit_settings( + **session_, NGHTTP2_FLAG_NONE, &entries_[0], count_), + 0); } void Http2Session::Http2Settings::Done(bool ack) { uint64_t end = uv_hrtime(); double duration = (end - startTime_) / 1e6; - Local argv[2] = { - Boolean::New(env()->isolate(), ack), - Number::New(env()->isolate(), duration) - }; + Local argv[2] = {Boolean::New(env()->isolate(), ack), + Number::New(env()->isolate(), duration)}; MakeCallback(env()->ondone_string(), arraysize(argv), argv); delete this; } @@ -336,17 +316,21 @@ Http2Priority::Http2Priority(Environment* env, int32_t parent_ = parent->Int32Value(context).ToChecked(); int32_t weight_ = weight->Int32Value(context).ToChecked(); bool exclusive_ = exclusive->BooleanValue(context).ToChecked(); - Debug(env, DebugCategory::HTTP2STREAM, + Debug(env, + DebugCategory::HTTP2STREAM, "Http2Priority: parent: %d, weight: %d, exclusive: %d\n", - parent_, weight_, exclusive_); + parent_, + weight_, + exclusive_); nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0); } - const char* Http2Session::TypeName() const { switch (session_type_) { - case NGHTTP2_SESSION_SERVER: return "server"; - case NGHTTP2_SESSION_CLIENT: return "client"; + case NGHTTP2_SESSION_SERVER: + return "server"; + case NGHTTP2_SESSION_CLIENT: + return "client"; default: // This should never happen ABORT(); @@ -381,10 +365,11 @@ Headers::Headers(Isolate* isolate, nghttp2_nv* const nva = reinterpret_cast(start); CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length()); - CHECK_EQ(header_string.As() - ->WriteOneByte(reinterpret_cast(header_contents), - 0, header_string_len, - String::NO_NULL_TERMINATION), + CHECK_EQ(header_string.As()->WriteOneByte( + reinterpret_cast(header_contents), + 0, + header_string_len, + String::NO_NULL_TERMINATION), header_string_len); size_t n = 0; @@ -411,42 +396,37 @@ Headers::Headers(Isolate* isolate, } } - // Sets the various callback functions that nghttp2 will use to notify us // about significant events while processing http2 stuff. Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) { CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0); nghttp2_session_callbacks_set_on_begin_headers_callback( - callbacks, OnBeginHeadersCallback); - nghttp2_session_callbacks_set_on_header_callback2( - callbacks, OnHeaderCallback); - nghttp2_session_callbacks_set_on_frame_recv_callback( - callbacks, OnFrameReceive); - nghttp2_session_callbacks_set_on_stream_close_callback( - callbacks, OnStreamClose); + callbacks, OnBeginHeadersCallback); + nghttp2_session_callbacks_set_on_header_callback2(callbacks, + OnHeaderCallback); + nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, + OnFrameReceive); + nghttp2_session_callbacks_set_on_stream_close_callback(callbacks, + OnStreamClose); nghttp2_session_callbacks_set_on_data_chunk_recv_callback( - callbacks, OnDataChunkReceived); - nghttp2_session_callbacks_set_on_frame_not_send_callback( - callbacks, OnFrameNotSent); - nghttp2_session_callbacks_set_on_invalid_header_callback2( - callbacks, OnInvalidHeader); - nghttp2_session_callbacks_set_error_callback( - callbacks, OnNghttpError); - nghttp2_session_callbacks_set_send_data_callback( - callbacks, OnSendData); - nghttp2_session_callbacks_set_on_invalid_frame_recv_callback( - callbacks, OnInvalidFrame); - nghttp2_session_callbacks_set_on_frame_send_callback( - callbacks, OnFrameSent); + callbacks, OnDataChunkReceived); + nghttp2_session_callbacks_set_on_frame_not_send_callback(callbacks, + OnFrameNotSent); + nghttp2_session_callbacks_set_on_invalid_header_callback2(callbacks, + OnInvalidHeader); + nghttp2_session_callbacks_set_error_callback(callbacks, OnNghttpError); + nghttp2_session_callbacks_set_send_data_callback(callbacks, OnSendData); + nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(callbacks, + OnInvalidFrame); + nghttp2_session_callbacks_set_on_frame_send_callback(callbacks, OnFrameSent); if (kHasGetPaddingCallback) { - nghttp2_session_callbacks_set_select_padding_callback( - callbacks, OnSelectPadding); + nghttp2_session_callbacks_set_select_padding_callback(callbacks, + OnSelectPadding); } } - Http2Session::Callbacks::~Callbacks() { nghttp2_session_callbacks_del(callbacks); } @@ -455,7 +435,7 @@ Http2Session::Callbacks::~Callbacks() { class Http2Session::MemoryAllocatorInfo { public: explicit MemoryAllocatorInfo(Http2Session* session) - : info({ session, H2Malloc, H2Free, H2Calloc, H2Realloc }) {} + : info({session, H2Malloc, H2Free, H2Calloc, H2Realloc}) {} static void* H2Malloc(size_t size, void* user_data) { return H2Realloc(nullptr, size, user_data); @@ -464,8 +444,7 @@ class Http2Session::MemoryAllocatorInfo { static void* H2Calloc(size_t nmemb, size_t size, void* user_data) { size_t real_size = MultiplyWithOverflowCheck(nmemb, size); void* mem = H2Malloc(real_size, user_data); - if (mem != nullptr) - memset(mem, 0, real_size); + if (mem != nullptr) memset(mem, 0, real_size); return mem; } @@ -492,8 +471,7 @@ class Http2Session::MemoryAllocatorInfo { if (previous_size == 0) { // Fall back to the standard Realloc() function. char* ret = UncheckedRealloc(original_ptr, size); - if (ret != nullptr) - ret += sizeof(size_t); + if (ret != nullptr) ret += sizeof(size_t); return ret; } } @@ -522,8 +500,8 @@ class Http2Session::MemoryAllocatorInfo { } static void StopTracking(Http2Session* session, void* ptr) { - size_t* original_ptr = reinterpret_cast( - static_cast(ptr) - sizeof(size_t)); + size_t* original_ptr = + reinterpret_cast(static_cast(ptr) - sizeof(size_t)); session->current_nghttp2_memory_ -= *original_ptr; *original_ptr = 0; } @@ -553,23 +531,21 @@ Http2Session::Http2Session(Environment* env, uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs(); max_header_pairs_ = type == NGHTTP2_SESSION_SERVER - ? std::max(maxHeaderPairs, 4U) // minimum # of request headers - : std::max(maxHeaderPairs, 1U); // minimum # of response headers + ? std::max(maxHeaderPairs, 4U) // minimum # of request headers + : std::max(maxHeaderPairs, 1U); // minimum # of response headers max_outstanding_pings_ = opts.GetMaxOutstandingPings(); max_outstanding_settings_ = opts.GetMaxOutstandingSettings(); padding_strategy_ = opts.GetPaddingStrategy(); - bool hasGetPaddingCallback = - padding_strategy_ != PADDING_STRATEGY_NONE; + bool hasGetPaddingCallback = padding_strategy_ != PADDING_STRATEGY_NONE; - nghttp2_session_callbacks* callbacks - = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks; + nghttp2_session_callbacks* callbacks = + callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks; - auto fn = type == NGHTTP2_SESSION_SERVER ? - nghttp2_session_server_new3 : - nghttp2_session_client_new3; + auto fn = type == NGHTTP2_SESSION_SERVER ? nghttp2_session_server_new3 + : nghttp2_session_client_new3; MemoryAllocatorInfo allocator_info(this); @@ -587,15 +563,14 @@ Http2Session::Http2Session(Environment* env, Http2Session::~Http2Session() { CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0); Debug(this, "freeing nghttp2 session"); - for (const auto& iter : streams_) - iter.second->session_ = nullptr; + for (const auto& iter : streams_) iter.second->session_ = nullptr; nghttp2_session_del(session_); CHECK_EQ(current_nghttp2_memory_, 0); } std::string Http2Session::diagnostic_name() const { return std::string("Http2Session ") + TypeName() + " (" + - std::to_string(static_cast(get_async_id())) + ")"; + std::to_string(static_cast(get_async_id())) + ")"; } inline bool HasHttp2Observer(Environment* env) { @@ -605,84 +580,83 @@ inline bool HasHttp2Observer(Environment* env) { } void Http2Stream::EmitStatistics() { - if (!HasHttp2Observer(env())) - return; + if (!HasHttp2Observer(env())) return; Http2StreamPerformanceEntry* entry = - new Http2StreamPerformanceEntry(env(), id_, statistics_); - env()->SetImmediate([](Environment* env, void* data) { - // This takes ownership, the entry is destroyed at the end of this scope. - std::unique_ptr entry { - static_cast(data) }; - if (!HasHttp2Observer(env)) - return; - HandleScope handle_scope(env->isolate()); - AliasedBuffer& buffer = - env->http2_state()->stream_stats_buffer; - buffer[IDX_STREAM_STATS_ID] = entry->id(); - if (entry->first_byte() != 0) { - buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = - (entry->first_byte() - entry->startTimeNano()) / 1e6; - } else { - buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0; - } - if (entry->first_header() != 0) { - buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = - (entry->first_header() - entry->startTimeNano()) / 1e6; - } else { - buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0; - } - if (entry->first_byte_sent() != 0) { - buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = - (entry->first_byte_sent() - entry->startTimeNano()) / 1e6; - } else { - buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0; - } - buffer[IDX_STREAM_STATS_SENTBYTES] = entry->sent_bytes(); - buffer[IDX_STREAM_STATS_RECEIVEDBYTES] = entry->received_bytes(); - entry->Notify(entry->ToObject()); - }, static_cast(entry)); + new Http2StreamPerformanceEntry(env(), id_, statistics_); + env()->SetImmediate( + [](Environment* env, void* data) { + // This takes ownership, the entry is destroyed at the end of this + // scope. + std::unique_ptr entry{ + static_cast(data)}; + if (!HasHttp2Observer(env)) return; + HandleScope handle_scope(env->isolate()); + AliasedBuffer& buffer = + env->http2_state()->stream_stats_buffer; + buffer[IDX_STREAM_STATS_ID] = entry->id(); + if (entry->first_byte() != 0) { + buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = + (entry->first_byte() - entry->startTimeNano()) / 1e6; + } else { + buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0; + } + if (entry->first_header() != 0) { + buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = + (entry->first_header() - entry->startTimeNano()) / 1e6; + } else { + buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0; + } + if (entry->first_byte_sent() != 0) { + buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = + (entry->first_byte_sent() - entry->startTimeNano()) / 1e6; + } else { + buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0; + } + buffer[IDX_STREAM_STATS_SENTBYTES] = entry->sent_bytes(); + buffer[IDX_STREAM_STATS_RECEIVEDBYTES] = entry->received_bytes(); + entry->Notify(entry->ToObject()); + }, + static_cast(entry)); } void Http2Session::EmitStatistics() { - if (!HasHttp2Observer(env())) - return; + if (!HasHttp2Observer(env())) return; Http2SessionPerformanceEntry* entry = - new Http2SessionPerformanceEntry(env(), statistics_, session_type_); - env()->SetImmediate([](Environment* env, void* data) { - // This takes ownership, the entr is destroyed at the end of this scope. - std::unique_ptr entry { - static_cast(data) }; - if (!HasHttp2Observer(env)) - return; - HandleScope handle_scope(env->isolate()); - AliasedBuffer& buffer = - env->http2_state()->session_stats_buffer; - buffer[IDX_SESSION_STATS_TYPE] = entry->type(); - buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6; - buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count(); - buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent(); - buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count(); - buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] = - entry->stream_average_duration(); - buffer[IDX_SESSION_STATS_DATA_SENT] = entry->data_sent(); - buffer[IDX_SESSION_STATS_DATA_RECEIVED] = entry->data_received(); - buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] = - entry->max_concurrent_streams(); - entry->Notify(entry->ToObject()); - }, static_cast(entry)); + new Http2SessionPerformanceEntry(env(), statistics_, session_type_); + env()->SetImmediate( + [](Environment* env, void* data) { + // This takes ownership, the entr is destroyed at the end of this scope. + std::unique_ptr entry{ + static_cast(data)}; + if (!HasHttp2Observer(env)) return; + HandleScope handle_scope(env->isolate()); + AliasedBuffer& buffer = + env->http2_state()->session_stats_buffer; + buffer[IDX_SESSION_STATS_TYPE] = entry->type(); + buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6; + buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count(); + buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent(); + buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count(); + buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] = + entry->stream_average_duration(); + buffer[IDX_SESSION_STATS_DATA_SENT] = entry->data_sent(); + buffer[IDX_SESSION_STATS_DATA_RECEIVED] = entry->data_received(); + buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] = + entry->max_concurrent_streams(); + entry->Notify(entry->ToObject()); + }, + static_cast(entry)); } // Closes the session and frees the associated resources void Http2Session::Close(uint32_t code, bool socket_closed) { Debug(this, "closing session"); - if (flags_ & SESSION_STATE_CLOSING) - return; + if (flags_ & SESSION_STATE_CLOSING) return; flags_ |= SESSION_STATE_CLOSING; // Stop reading on the i/o stream - if (stream_ != nullptr) - stream_->ReadStop(); + if (stream_ != nullptr) stream_->ReadStop(); // If the socket is not closed, then attempt to send a closing GOAWAY // frame. There is no guarantee that this GOAWAY will be received by @@ -703,9 +677,11 @@ void Http2Session::Close(uint32_t code, bool socket_closed) { // javascript since this may be called during garbage collection. while (!outstanding_pings_.empty()) { Http2Session::Http2Ping* ping = PopPing(); - env()->SetImmediate([](Environment* env, void* data) { - static_cast(data)->Done(false); - }, static_cast(ping)); + env()->SetImmediate( + [](Environment* env, void* data) { + static_cast(data)->Done(false); + }, + static_cast(ping)); } statistics_.end_time = uv_hrtime(); @@ -720,9 +696,8 @@ inline Http2Stream* Http2Session::FindStream(int32_t id) { } inline bool Http2Session::CanAddStream() { - uint32_t maxConcurrentStreams = - nghttp2_session_get_local_settings( - session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); + uint32_t maxConcurrentStreams = nghttp2_session_get_local_settings( + session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); size_t maxSize = std::min(streams_.max_size(), static_cast(maxConcurrentStreams)); // We can add a new stream so long as we are less than the current @@ -740,7 +715,6 @@ inline void Http2Session::AddStream(Http2Stream* stream) { IncrementCurrentSessionMemory(sizeof(*stream)); } - inline void Http2Session::RemoveStream(Http2Stream* stream) { if (streams_.empty() || stream == nullptr) return; // Nothing to remove, item was never added? @@ -779,8 +753,7 @@ ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen, // to determine the amount of padding for the current frame. This option is // rather more expensive because of the JS boundary cross. It generally should // not be the preferred option. -ssize_t Http2Session::OnCallbackPadding(size_t frameLen, - size_t maxPayloadLen) { +ssize_t Http2Session::OnCallbackPadding(size_t frameLen, size_t maxPayloadLen) { if (frameLen == 0) return 0; Debug(this, "using callback to determine padding"); Isolate* isolate = env()->isolate(); @@ -801,7 +774,6 @@ ssize_t Http2Session::OnCallbackPadding(size_t frameLen, return retval; } - // Write data received from the i/o stream to the underlying nghttp2_session. // On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the // various callback functions. Each of these will typically result in a call @@ -813,17 +785,15 @@ ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) { // will trigger a number of other callbacks. Those will, in turn have // multiple side effects. for (size_t n = 0; n < nbufs; n++) { - Debug(this, "receiving %d bytes [wants data? %d]", + Debug(this, + "receiving %d bytes [wants data? %d]", bufs[n].len, nghttp2_session_want_read(session_)); - ssize_t ret = - nghttp2_session_mem_recv(session_, - reinterpret_cast(bufs[n].base), - bufs[n].len); + ssize_t ret = nghttp2_session_mem_recv( + session_, reinterpret_cast(bufs[n].base), bufs[n].len); CHECK_NE(ret, NGHTTP2_ERR_NOMEM); - if (ret < 0) - return ret; + if (ret < 0) return ret; total += ret; } @@ -834,15 +804,13 @@ ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) { return total; } - inline int32_t GetFrameID(const nghttp2_frame* frame) { // If this is a push promise, we want to grab the id of the promised stream - return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ? - frame->push_promise.promised_stream_id : - frame->hd.stream_id; + return (frame->hd.type == NGHTTP2_PUSH_PROMISE) + ? frame->push_promise.promised_stream_id + : frame->hd.stream_id; } - // Called by nghttp2 at the start of receiving a HEADERS frame. We use this // callback to determine if a new stream is being created or if we are simply // adding a new block of headers to an existing stream. The header pairs @@ -858,8 +826,8 @@ int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle, if (stream == nullptr) { if (!session->CanAddStream()) { // Too many concurrent streams being opened - nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id, - NGHTTP2_ENHANCE_YOUR_CALM); + nghttp2_submit_rst_stream( + **session, NGHTTP2_FLAG_NONE, id, NGHTTP2_ENHANCE_YOUR_CALM); return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } new Http2Stream(session, id, frame->headers.cat); @@ -892,7 +860,6 @@ int Http2Session::OnHeaderCallback(nghttp2_session* handle, return 0; } - // Called by nghttp2 when a complete HTTP2 frame has been received. There are // only a handful of frame types tha we care about handling here. int Http2Session::OnFrameReceive(nghttp2_session* handle, @@ -900,8 +867,7 @@ int Http2Session::OnFrameReceive(nghttp2_session* handle, void* user_data) { Http2Session* session = static_cast(user_data); session->statistics_.frame_count++; - Debug(session, "complete frame received: type: %d", - frame->hd.type); + Debug(session, "complete frame received: type: %d", frame->hd.type); switch (frame->hd.type) { case NGHTTP2_DATA: session->HandleDataFrame(frame); @@ -966,8 +932,10 @@ int Http2Session::OnFrameNotSent(nghttp2_session* handle, void* user_data) { Http2Session* session = static_cast(user_data); Environment* env = session->env(); - Debug(session, "frame type %d was not sent, code: %d", - frame->hd.type, error_code); + Debug(session, + "frame type %d was not sent, code: %d", + frame->hd.type, + error_code); // Do not report if the frame was not sent due to the session closing if (error_code != NGHTTP2_ERR_SESSION_CLOSING && error_code != NGHTTP2_ERR_STREAM_CLOSED && @@ -977,11 +945,9 @@ int Http2Session::OnFrameNotSent(nghttp2_session* handle, Local context = env->context(); Context::Scope context_scope(context); - Local argv[3] = { - Integer::New(isolate, frame->hd.stream_id), - Integer::New(isolate, frame->hd.type), - Integer::New(isolate, error_code) - }; + Local argv[3] = {Integer::New(isolate, frame->hd.stream_id), + Integer::New(isolate, frame->hd.type), + Integer::New(isolate, error_code)}; session->MakeCallback(env->onframeerror_string(), arraysize(argv), argv); } return 0; @@ -1017,13 +983,11 @@ int Http2Session::OnStreamClose(nghttp2_session* handle, // to destroying the stream. We can check this by looking for the // onstreamclose function. If it exists, then the stream has already // been passed on to javascript. - Local fn = - stream->object()->Get(context, env->onstreamclose_string()) - .ToLocalChecked(); + Local fn = stream->object() + ->Get(context, env->onstreamclose_string()) + .ToLocalChecked(); if (fn->IsFunction()) { - Local argv[] = { - Integer::NewFromUnsigned(isolate, code) - }; + Local argv[] = {Integer::NewFromUnsigned(isolate, code)}; stream->MakeCallback(fn.As(), arraysize(argv), argv); } else { stream->Destroy(); @@ -1057,8 +1021,12 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle, size_t len, void* user_data) { Http2Session* session = static_cast(user_data); - Debug(session, "buffering data chunk for stream %d, size: " - "%d, flags: %d", id, len, flags); + Debug(session, + "buffering data chunk for stream %d, size: " + "%d, flags: %d", + id, + len, + flags); Environment* env = session->env(); HandleScope scope(env->isolate()); // We should never actually get a 0-length chunk so this check is @@ -1070,8 +1038,7 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle, CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0); Http2Stream* stream = session->FindStream(id); // If the stream has been destroyed, ignore this chunk - if (stream->IsDestroyed()) - return 0; + if (stream->IsDestroyed()) return 0; stream->statistics_.received_bytes += len; @@ -1083,8 +1050,7 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle, do { uv_buf_t buf = stream->EmitAlloc(len); ssize_t avail = len; - if (static_cast(buf.len) < avail) - avail = buf.len; + if (static_cast(buf.len) < avail) avail = buf.len; // `buf.base == nullptr` is the default Http2StreamListener's way // of saying that it wants a pointer to the raw original. @@ -1137,9 +1103,10 @@ ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle, return padding; } -#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we " \ - "expected SETTINGS frame. Perhaps, peer does not " \ - "support HTTP/2 properly." +#define BAD_PEER_MESSAGE \ + "Remote peer returned unexpected data while we " \ + "expected SETTINGS frame. Perhaps, peer does not " \ + "support HTTP/2 properly." // We use this currently to determine when an attempt is made to use the http2 // protocol with a non-http2 peer. @@ -1198,7 +1165,6 @@ void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { stream->CallJSOnreadMethod(nread, buffer); } - // Called by OnFrameReceived to notify JavaScript land that a complete // HEADERS frame has been received and processed. This method converts the // received headers into a JavaScript array and pushes those out to JS. @@ -1213,8 +1179,7 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) { Http2Stream* stream = FindStream(id); // If the stream has already been destroyed, ignore. - if (stream->IsDestroyed()) - return; + if (stream->IsDestroyed()) return; std::vector headers(stream->move_headers()); @@ -1238,10 +1203,8 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) { while (n < headers.size() && j < arraysize(argv) / 2) { nghttp2_header item = headers[n++]; // The header name and value are passed as external one-byte strings - name_str = - ExternalHeader::New(this, item.name).ToLocalChecked(); - value_str = - ExternalHeader::New(this, item.value).ToLocalChecked(); + name_str = ExternalHeader::New(this, item.name).ToLocalChecked(); + value_str = ExternalHeader::New(this, item.value).ToLocalChecked(); argv[j * 2] = name_str; argv[j * 2 + 1] = value_str; j++; @@ -1254,17 +1217,14 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) { } } - Local args[5] = { - stream->object(), - Integer::New(isolate, id), - Integer::New(isolate, stream->headers_category()), - Integer::New(isolate, frame->hd.flags), - holder - }; + Local args[5] = {stream->object(), + Integer::New(isolate, id), + Integer::New(isolate, stream->headers_category()), + Integer::New(isolate, frame->hd.flags), + holder}; MakeCallback(env()->onheaders_string(), arraysize(args), args); } - // Called by OnFrameReceived when a complete PRIORITY frame has been // received. Notifies JS land about the priority change. Note that priorities // are considered advisory only, so this has no real effect other than to @@ -1281,16 +1241,13 @@ void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) { // Priority frame stream ID should never be <= 0. nghttp2 handles this for us nghttp2_priority_spec spec = priority_frame.pri_spec; - Local argv[4] = { - Integer::New(isolate, id), - Integer::New(isolate, spec.stream_id), - Integer::New(isolate, spec.weight), - Boolean::New(isolate, spec.exclusive) - }; + Local argv[4] = {Integer::New(isolate, id), + Integer::New(isolate, spec.stream_id), + Integer::New(isolate, spec.weight), + Boolean::New(isolate, spec.exclusive)}; MakeCallback(env()->onpriority_string(), arraysize(argv), argv); } - // Called by OnFrameReceived when a complete DATA frame has been received. // If we know that this was the last DATA frame (because the END_STREAM flag // is set), then we'll terminate the readable side of the StreamBase. @@ -1303,7 +1260,6 @@ void Http2Session::HandleDataFrame(const nghttp2_frame* frame) { stream->EmitRead(UV_EOF); } - // Called by OnFrameReceived when a complete GOAWAY frame has been received. void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) { Isolate* isolate = env()->isolate(); @@ -1315,16 +1271,16 @@ void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) { Debug(this, "handling goaway frame"); Local argv[3] = { - Integer::NewFromUnsigned(isolate, goaway_frame.error_code), - Integer::New(isolate, goaway_frame.last_stream_id), - Undefined(isolate) - }; + Integer::NewFromUnsigned(isolate, goaway_frame.error_code), + Integer::New(isolate, goaway_frame.last_stream_id), + Undefined(isolate)}; size_t length = goaway_frame.opaque_data_len; if (length > 0) { - argv[2] = Buffer::Copy(isolate, - reinterpret_cast(goaway_frame.opaque_data), - length).ToLocalChecked(); + argv[2] = + Buffer::Copy( + isolate, reinterpret_cast(goaway_frame.opaque_data), length) + .ToLocalChecked(); } MakeCallback(env()->ongoawaydata_string(), arraysize(argv), argv); @@ -1344,15 +1300,17 @@ void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) { Debug(this, "handling altsvc frame"); Local argv[3] = { - Integer::New(isolate, id), - String::NewFromOneByte(isolate, - altsvc->origin, - v8::NewStringType::kNormal, - altsvc->origin_len).ToLocalChecked(), - String::NewFromOneByte(isolate, - altsvc->field_value, - v8::NewStringType::kNormal, - altsvc->field_value_len).ToLocalChecked(), + Integer::New(isolate, id), + String::NewFromOneByte(isolate, + altsvc->origin, + v8::NewStringType::kNormal, + altsvc->origin_len) + .ToLocalChecked(), + String::NewFromOneByte(isolate, + altsvc->field_value, + v8::NewStringType::kNormal, + altsvc->field_value_len) + .ToLocalChecked(), }; MakeCallback(env()->onaltsvc_string(), arraysize(argv), argv); @@ -1436,30 +1394,32 @@ void Http2Session::MaybeScheduleWrite() { HandleScope handle_scope(env()->isolate()); Debug(this, "scheduling write"); flags_ |= SESSION_STATE_WRITE_SCHEDULED; - env()->SetImmediate([](Environment* env, void* data) { - Http2Session* session = static_cast(data); - if (session->session_ == nullptr || - !(session->flags_ & SESSION_STATE_WRITE_SCHEDULED)) { - // This can happen e.g. when a stream was reset before this turn - // of the event loop, in which case SendPendingData() is called early, - // or the session was destroyed in the meantime. - return; - } - - // Sending data may call arbitrary JS code, so keep track of - // async context. - HandleScope handle_scope(env->isolate()); - InternalCallbackScope callback_scope(session); - session->SendPendingData(); - }, static_cast(this), object()); + env()->SetImmediate( + [](Environment* env, void* data) { + Http2Session* session = static_cast(data); + if (session->session_ == nullptr || + !(session->flags_ & SESSION_STATE_WRITE_SCHEDULED)) { + // This can happen e.g. when a stream was reset before this turn + // of the event loop, in which case SendPendingData() is called + // early, or the session was destroyed in the meantime. + return; + } + + // Sending data may call arbitrary JS code, so keep track of + // async context. + HandleScope handle_scope(env->isolate()); + InternalCallbackScope callback_scope(session); + session->SendPendingData(); + }, + static_cast(this), + object()); } } void Http2Session::MaybeStopReading() { int want_read = nghttp2_session_want_read(session_); Debug(this, "wants read? %d", want_read); - if (want_read == 0) - stream_->ReadStop(); + if (want_read == 0) stream_->ReadStop(); } // Unset the sending state, finish up all current writes, and reset @@ -1476,8 +1436,7 @@ void Http2Session::ClearOutgoing(int status) { current_outgoing_buffers_.swap(outgoing_buffers_); for (const nghttp2_stream_write& wr : current_outgoing_buffers_) { WriteWrap* wrap = wr.req_wrap; - if (wrap != nullptr) - wrap->Done(status); + if (wrap != nullptr) wrap->Done(status); } } @@ -1491,8 +1450,7 @@ void Http2Session::ClearOutgoing(int status) { for (int32_t stream_id : current_pending_rst_streams) { Http2Stream* stream = FindStream(stream_id); - if (stream != nullptr) - stream->FlushRstStream(); + if (stream != nullptr) stream->FlushRstStream(); } } } @@ -1509,9 +1467,8 @@ void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) { // of the outgoing_buffers_ vector may invalidate the pointer. // The correct base pointers will be set later, before writing to the // underlying socket. - outgoing_buffers_.emplace_back(nghttp2_stream_write { - uv_buf_init(nullptr, src_length) - }); + outgoing_buffers_.emplace_back( + nghttp2_stream_write{uv_buf_init(nullptr, src_length)}); } // Prompts nghttp2 to begin serializing it's pending data and pushes each @@ -1524,13 +1481,11 @@ uint8_t Http2Session::SendPendingData() { // Do not attempt to send data on the socket if the destroying flag has // been set. That means everything is shutting down and the socket // will not be usable. - if (IsDestroyed()) - return 0; + if (IsDestroyed()) return 0; flags_ &= ~SESSION_STATE_WRITE_SCHEDULED; // SendPendingData should not be called recursively. - if (flags_ & SESSION_STATE_SENDING) - return 1; + if (flags_ & SESSION_STATE_SENDING) return 1; // This is cleared by ClearOutgoing(). flags_ |= SESSION_STATE_SENDING; @@ -1596,18 +1551,16 @@ uint8_t Http2Session::SendPendingData() { return 0; } - // This callback is called from nghttp2 when it wants to send DATA frames for a // given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier // in the Http2Stream::Provider::Stream::OnRead callback. // We take the write information directly out of the stream's data queue. -int Http2Session::OnSendData( - nghttp2_session* session_, - nghttp2_frame* frame, - const uint8_t* framehd, - size_t length, - nghttp2_data_source* source, - void* user_data) { +int Http2Session::OnSendData(nghttp2_session* session_, + nghttp2_frame* frame, + const uint8_t* framehd, + size_t length, + nghttp2_data_source* source, + void* user_data) { Http2Session* session = static_cast(user_data); Http2Stream* stream = GetStream(session, frame->hd.stream_id, source); @@ -1635,9 +1588,8 @@ int Http2Session::OnSendData( } // Slice off `length` bytes of the first write in the queue. - session->outgoing_buffers_.emplace_back(nghttp2_stream_write { - uv_buf_init(write.buf.base, length) - }); + session->outgoing_buffers_.emplace_back( + nghttp2_stream_write{uv_buf_init(write.buf.base, length)}); write.buf.base += length; write.buf.len -= length; break; @@ -1645,21 +1597,19 @@ int Http2Session::OnSendData( if (frame->data.padlen > 0) { // Send padding if that was requested. - session->outgoing_buffers_.emplace_back(nghttp2_stream_write { - uv_buf_init(const_cast(zero_bytes_256), frame->data.padlen - 1) - }); + session->outgoing_buffers_.emplace_back(nghttp2_stream_write{uv_buf_init( + const_cast(zero_bytes_256), frame->data.padlen - 1)}); } return 0; } // Creates a new Http2Stream and submits a new http2 request. -Http2Stream* Http2Session::SubmitRequest( - nghttp2_priority_spec* prispec, - nghttp2_nv* nva, - size_t len, - int32_t* ret, - int options) { +Http2Stream* Http2Session::SubmitRequest(nghttp2_priority_spec* prispec, + nghttp2_nv* nva, + size_t len, + int32_t* ret, + int options) { Debug(this, "submitting request"); Http2Scope h2scope(this); Http2Stream* stream = nullptr; @@ -1707,11 +1657,8 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { // Create an array buffer for the read data. DATA frames will be emitted // as slices of this array buffer to avoid having to copy memory. - stream_buf_ab_ = - ArrayBuffer::New(isolate, - buf.base, - nread, - v8::ArrayBufferCreationMode::kInternalized); + stream_buf_ab_ = ArrayBuffer::New( + isolate, buf.base, nread, v8::ArrayBufferCreationMode::kInternalized); statistics_.data_received += nread; ssize_t ret = Write(&stream_buf_, 1); @@ -1720,7 +1667,7 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { Debug(this, "fatal error receiving data: %d", ret); Local argv[] = { - Integer::New(isolate, ret), + Integer::New(isolate, ret), }; MakeCallback(env()->error_string(), arraysize(argv), argv); } else { @@ -1738,8 +1685,7 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) { for (const nghttp2_stream_write& wr : outgoing_buffers_) { - if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream) - return true; + if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream) return true; } return false; } @@ -1754,56 +1700,50 @@ void Http2Session::Consume(Local external) { Debug(this, "i/o stream consumed"); } - -Http2Stream::Http2Stream( - Http2Session* session, - int32_t id, - nghttp2_headers_category category, - int options) : AsyncWrap(session->env(), - session->env()->http2stream_constructor_template() - ->NewInstance(session->env()->context()) - .ToLocalChecked(), - AsyncWrap::PROVIDER_HTTP2STREAM), - StreamBase(session->env()), - session_(session), - id_(id), - current_headers_category_(category) { +Http2Stream::Http2Stream(Http2Session* session, + int32_t id, + nghttp2_headers_category category, + int options) + : AsyncWrap(session->env(), + session->env() + ->http2stream_constructor_template() + ->NewInstance(session->env()->context()) + .ToLocalChecked(), + AsyncWrap::PROVIDER_HTTP2STREAM), + StreamBase(session->env()), + session_(session), + id_(id), + current_headers_category_(category) { MakeWeak(); statistics_.start_time = uv_hrtime(); // Limit the number of header pairs max_header_pairs_ = session->GetMaxHeaderPairs(); - if (max_header_pairs_ == 0) - max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS; + if (max_header_pairs_ == 0) max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS; current_headers_.reserve(max_header_pairs_); // Limit the number of header octets max_header_length_ = - std::min( - nghttp2_session_get_local_settings( - session->session(), - NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE), - MAX_MAX_HEADER_LIST_SIZE); + std::min(nghttp2_session_get_local_settings( + session->session(), NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE), + MAX_MAX_HEADER_LIST_SIZE); if (options & STREAM_OPTION_GET_TRAILERS) flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS; PushStreamListener(&stream_listener_); - if (options & STREAM_OPTION_EMPTY_PAYLOAD) - Shutdown(); + if (options & STREAM_OPTION_EMPTY_PAYLOAD) Shutdown(); session->AddStream(this); } - Http2Stream::~Http2Stream() { for (nghttp2_header& header : current_headers_) { nghttp2_rcbuf_decref(header.name); nghttp2_rcbuf_decref(header.value); } - if (session_ == nullptr) - return; + if (session_ == nullptr) return; Debug(this, "tearing down stream"); session_->RemoveStream(this); session_ = nullptr; @@ -1811,8 +1751,8 @@ Http2Stream::~Http2Stream() { std::string Http2Stream::diagnostic_name() const { return "HttpStream " + std::to_string(id()) + " (" + - std::to_string(static_cast(get_async_id())) + ") [" + - session()->diagnostic_name() + "]"; + std::to_string(static_cast(get_async_id())) + ") [" + + session()->diagnostic_name() + "]"; } // Notify the Http2Stream that a new block of HEADERS is being processed. @@ -1824,7 +1764,6 @@ void Http2Stream::StartHeaders(nghttp2_headers_category category) { current_headers_category_ = category; } - nghttp2_stream* Http2Stream::operator*() { return nghttp2_session_find_stream(**session_, id_); } @@ -1837,14 +1776,12 @@ void Http2Stream::Close(int32_t code) { } int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) { - if (IsDestroyed()) - return UV_EPIPE; + if (IsDestroyed()) return UV_EPIPE; { Http2Scope h2scope(this); flags_ |= NGHTTP2_STREAM_FLAG_SHUT; - CHECK_NE(nghttp2_session_resume_data(**session_, id_), - NGHTTP2_ERR_NOMEM); + CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM); Debug(this, "writable side shutdown"); } req_wrap->Done(0); @@ -1856,44 +1793,44 @@ int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) { // using the SetImmediate queue. void Http2Stream::Destroy() { // Do nothing if this stream instance is already destroyed - if (IsDestroyed()) - return; - if (session_->HasPendingRstStream(id_)) - FlushRstStream(); + if (IsDestroyed()) return; + if (session_->HasPendingRstStream(id_)) FlushRstStream(); flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED; Debug(this, "destroying stream"); // Wait until the start of the next loop to delete because there // may still be some pending operations queued for this stream. - env()->SetImmediate([](Environment* env, void* data) { - Http2Stream* stream = static_cast(data); - // Free any remaining outgoing data chunks here. This should be done - // here because it's possible for destroy to have been called while - // we still have queued outbound writes. - while (!stream->queue_.empty()) { - nghttp2_stream_write& head = stream->queue_.front(); - if (head.req_wrap != nullptr) - head.req_wrap->Done(UV_ECANCELED); - stream->queue_.pop(); - } - - // We can destroy the stream now if there are no writes for it - // already on the socket. Otherwise, we'll wait for the garbage collector - // to take care of cleaning up. - if (stream->session() == nullptr || - !stream->session()->HasWritesOnSocketForStream(stream)) - delete stream; - }, this, this->object()); + env()->SetImmediate( + [](Environment* env, void* data) { + Http2Stream* stream = static_cast(data); + // Free any remaining outgoing data chunks here. This should be done + // here because it's possible for destroy to have been called while + // we still have queued outbound writes. + while (!stream->queue_.empty()) { + nghttp2_stream_write& head = stream->queue_.front(); + if (head.req_wrap != nullptr) head.req_wrap->Done(UV_ECANCELED); + stream->queue_.pop(); + } + + // We can destroy the stream now if there are no writes for it + // already on the socket. Otherwise, we'll wait for the garbage + // collector to take care of cleaning up. + if (stream->session() == nullptr || + !stream->session()->HasWritesOnSocketForStream(stream)) + delete stream; + }, + this, + this->object()); statistics_.end_time = uv_hrtime(); session_->statistics_.stream_average_duration = ((statistics_.end_time - statistics_.start_time) / - session_->statistics_.stream_count) / 1e6; + session_->statistics_.stream_count) / + 1e6; EmitStatistics(); } - // Initiates a response on the Http2Stream using data provided via the // StreamBase Streams API. int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) { @@ -1903,8 +1840,7 @@ int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) { if (options & STREAM_OPTION_GET_TRAILERS) flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS; - if (!IsWritable()) - options |= STREAM_OPTION_EMPTY_PAYLOAD; + if (!IsWritable()) options |= STREAM_OPTION_EMPTY_PAYLOAD; Http2Stream::Provider::Stream prov(this, options); int ret = nghttp2_submit_response(**session_, id_, nva, len, *prov); @@ -1912,16 +1848,13 @@ int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) { return ret; } - // Submit informational headers for a stream. int Http2Stream::SubmitInfo(nghttp2_nv* nva, size_t len) { CHECK(!this->IsDestroyed()); Http2Scope h2scope(this); Debug(this, "sending %d informational headers", len); - int ret = nghttp2_submit_headers(**session_, - NGHTTP2_FLAG_NONE, - id_, nullptr, - nva, len, nullptr); + int ret = nghttp2_submit_headers( + **session_, NGHTTP2_FLAG_NONE, id_, nullptr, nva, len, nullptr); CHECK_NE(ret, NGHTTP2_ERR_NOMEM); return ret; } @@ -1957,17 +1890,14 @@ int Http2Stream::SubmitTrailers(nghttp2_nv* nva, size_t len) { } // Submit a PRIORITY frame to the connected peer. -int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec, - bool silent) { +int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec, bool silent) { CHECK(!this->IsDestroyed()); Http2Scope h2scope(this); Debug(this, "sending priority spec"); - int ret = silent ? - nghttp2_session_change_stream_priority(**session_, - id_, prispec) : - nghttp2_submit_priority(**session_, - NGHTTP2_FLAG_NONE, - id_, prispec); + int ret = + silent ? nghttp2_session_change_stream_priority(**session_, id_, prispec) + : nghttp2_submit_priority( + **session_, NGHTTP2_FLAG_NONE, id_, prispec); CHECK_NE(ret, NGHTTP2_ERR_NOMEM); return ret; } @@ -1990,14 +1920,12 @@ void Http2Stream::SubmitRstStream(const uint32_t code) { } void Http2Stream::FlushRstStream() { - if (IsDestroyed()) - return; + if (IsDestroyed()) return; Http2Scope h2scope(this); - CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE, - id_, code_), 0); + CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE, id_, code_), + 0); } - // Submit a push promise and create the associated Http2Stream if successful. Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva, size_t len, @@ -2006,8 +1934,8 @@ Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva, CHECK(!this->IsDestroyed()); Http2Scope h2scope(this); Debug(this, "sending push promise"); - *ret = nghttp2_submit_push_promise(**session_, NGHTTP2_FLAG_NONE, - id_, nva, len, nullptr); + *ret = nghttp2_submit_push_promise( + **session_, NGHTTP2_FLAG_NONE, id_, nva, len, nullptr); CHECK_NE(*ret, NGHTTP2_ERR_NOMEM); Http2Stream* stream = nullptr; if (*ret > 0) @@ -2028,9 +1956,8 @@ int Http2Stream::ReadStart() { // Tell nghttp2 about our consumption of the data that was handed // off to JS land. - nghttp2_session_consume_stream(**session_, - id_, - inbound_consumed_data_while_paused_); + nghttp2_session_consume_stream( + **session_, id_, inbound_consumed_data_while_paused_); inbound_consumed_data_while_paused_ = 0; return 0; @@ -2039,8 +1966,7 @@ int Http2Stream::ReadStart() { // Switch the StreamBase into paused mode. int Http2Stream::ReadStop() { CHECK(!this->IsDestroyed()); - if (!IsReading()) - return 0; + if (!IsReading()) return 0; flags_ |= NGHTTP2_STREAM_FLAG_READ_PAUSED; Debug(this, "reading stopped"); return 0; @@ -2070,10 +1996,8 @@ int Http2Stream::DoWrite(WriteWrap* req_wrap, for (size_t i = 0; i < nbufs; ++i) { // Store the req_wrap on the last write info in the queue, so that it is // only marked as finished once all buffers associated with it are finished. - queue_.emplace(nghttp2_stream_write { - i == nbufs - 1 ? req_wrap : nullptr, - bufs[i] - }); + queue_.emplace( + nghttp2_stream_write{i == nbufs - 1 ? req_wrap : nullptr, bufs[i]}); IncrementAvailableOutboundLength(bufs[i].len); } CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM); @@ -2091,8 +2015,8 @@ bool Http2Stream::AddHeader(nghttp2_rcbuf* name, CHECK(!this->IsDestroyed()); if (this->statistics_.first_header == 0) this->statistics_.first_header = uv_hrtime(); - size_t length = nghttp2_rcbuf_get_buf(name).len + - nghttp2_rcbuf_get_buf(value).len + 32; + size_t length = + nghttp2_rcbuf_get_buf(name).len + nghttp2_rcbuf_get_buf(value).len + 32; // A header can only be added if we have not exceeded the maximum number // of headers and the session has memory available for it. if (!session_->IsAvailableSessionMemory(length) || @@ -2153,7 +2077,7 @@ ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle, stream->statistics_.first_byte_sent = uv_hrtime(); CHECK_EQ(id, stream->id()); - size_t amount = 0; // amount of data being sent in this data frame. + size_t amount = 0; // amount of data being sent in this data frame. // Remove all empty chunks from the head of the queue. // This is done here so that .write('', cb) is still a meaningful way to @@ -2162,8 +2086,7 @@ ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle, while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) { WriteWrap* finished = stream->queue_.front().req_wrap; stream->queue_.pop(); - if (finished != nullptr) - finished->Done(0); + if (finished != nullptr) finished->Done(0); } if (!stream->queue_.empty()) { @@ -2212,7 +2135,6 @@ inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) { session_->DecrementCurrentSessionMemory(amount); } - // Implementation of the JavaScript API // Fetches the string description of a nghttp2 error code and passes that @@ -2224,10 +2146,10 @@ void HttpErrorString(const FunctionCallbackInfo& args) { String::NewFromOneByte( env->isolate(), reinterpret_cast(nghttp2_strerror(val)), - v8::NewStringType::kInternalized).ToLocalChecked()); + v8::NewStringType::kInternalized) + .ToLocalChecked()); } - // Serializes the settings object into a Buffer instance that // would be suitable, for instance, for creating the Base64 // output for an HTTP2-Settings header field. @@ -2305,7 +2227,6 @@ void Http2Session::RefreshState(const FunctionCallbackInfo& args) { nghttp2_session_get_hd_inflate_dynamic_table_size(s); } - // Constructor for new Http2Session instances. void Http2Session::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -2317,7 +2238,6 @@ void Http2Session::New(const FunctionCallbackInfo& args) { Debug(session, "session created"); } - // Binds the Http2Session with a StreamBase used for i/o void Http2Session::Consume(const FunctionCallbackInfo& args) { Http2Session* session; @@ -2358,9 +2278,8 @@ void Http2Session::Request(const FunctionCallbackInfo& args) { Debug(session, "request submitted"); int32_t ret = 0; - Http2Stream* stream = - session->Http2Session::SubmitRequest(*priority, *list, list.length(), - &ret, options); + Http2Stream* stream = session->Http2Session::SubmitRequest( + *priority, *list, list.length(), &ret, options); if (ret <= 0) { Debug(session, "could not submit request: %s", nghttp2_strerror(ret)); @@ -2378,16 +2297,15 @@ void Http2Session::Goaway(uint32_t code, int32_t lastStreamID, uint8_t* data, size_t len) { - if (IsDestroyed()) - return; + if (IsDestroyed()) return; Http2Scope h2scope(this); // the last proc stream id is the most recently created Http2Stream. if (lastStreamID <= 0) lastStreamID = nghttp2_session_get_last_proc_stream_id(session_); Debug(this, "submitting goaway"); - nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE, - lastStreamID, code, data, len); + nghttp2_submit_goaway( + session_, NGHTTP2_FLAG_NONE, lastStreamID, code, data, len); } // Submits a GOAWAY frame to signal that the Http2Session is in the process @@ -2424,9 +2342,11 @@ void Http2Session::UpdateChunksSent(const FunctionCallbackInfo& args) { uint32_t length = session->chunks_sent_since_last_write_; - session->object()->Set(env->context(), - env->chunks_sent_since_last_write_string(), - Integer::NewFromUnsigned(isolate, length)).FromJust(); + session->object() + ->Set(env->context(), + env->chunks_sent_since_last_write_string(), + Integer::NewFromUnsigned(isolate, length)) + .FromJust(); args.GetReturnValue().Set(length); } @@ -2463,7 +2383,6 @@ void Http2Stream::Respond(const FunctionCallbackInfo& args) { Debug(stream, "response submitted"); } - // Submits informational headers on the Http2Stream void Http2Stream::Info(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -2533,8 +2452,8 @@ void Http2Stream::PushPromise(const FunctionCallbackInfo& args) { Debug(parent, "creating push promise"); int32_t ret = 0; - Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(), - &ret, options); + Http2Stream* stream = + parent->SubmitPushPromise(*list, list.length(), &ret, options); if (ret <= 0) { Debug(parent, "failed to create push stream: %d", ret); return args.GetReturnValue().Set(ret); @@ -2577,14 +2496,12 @@ void Http2Stream::RefreshState(const FunctionCallbackInfo& args) { buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE; buffer[IDX_STREAM_STATE_WEIGHT] = buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] = - buffer[IDX_STREAM_STATE_LOCAL_CLOSE] = - buffer[IDX_STREAM_STATE_REMOTE_CLOSE] = - buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0; + buffer[IDX_STREAM_STATE_LOCAL_CLOSE] = + buffer[IDX_STREAM_STATE_REMOTE_CLOSE] = + buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0; } else { - buffer[IDX_STREAM_STATE] = - nghttp2_stream_get_state(str); - buffer[IDX_STREAM_STATE_WEIGHT] = - nghttp2_stream_get_weight(str); + buffer[IDX_STREAM_STATE] = nghttp2_stream_get_state(str); + buffer[IDX_STREAM_STATE_WEIGHT] = nghttp2_stream_get_weight(str); buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] = nghttp2_stream_get_sum_dependency_weight(str); buffer[IDX_STREAM_STATE_LOCAL_CLOSE] = @@ -2602,8 +2519,14 @@ void Http2Session::AltSvc(int32_t id, uint8_t* value, size_t value_len) { Http2Scope h2scope(this); - CHECK_EQ(nghttp2_submit_altsvc(session_, NGHTTP2_FLAG_NONE, id, - origin, origin_len, value, value_len), 0); + CHECK_EQ(nghttp2_submit_altsvc(session_, + NGHTTP2_FLAG_NONE, + id, + origin, + origin_len, + value, + value_len), + 0); } // Submits an AltSvc frame to be sent to the connected peer. @@ -2687,7 +2610,6 @@ void Http2Session::Settings(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(true); } - Http2Session::Http2Ping* Http2Session::PopPing() { Http2Ping* ping = nullptr; if (!outstanding_pings_.empty()) { @@ -2699,8 +2621,7 @@ Http2Session::Http2Ping* Http2Session::PopPing() { } bool Http2Session::AddPing(Http2Session::Http2Ping* ping) { - if (outstanding_pings_.size() == max_outstanding_pings_) - return false; + if (outstanding_pings_.size() == max_outstanding_pings_) return false; outstanding_pings_.push(ping); IncrementCurrentSessionMemory(sizeof(*ping)); return true; @@ -2717,22 +2638,21 @@ Http2Session::Http2Settings* Http2Session::PopSettings() { } bool Http2Session::AddSettings(Http2Session::Http2Settings* settings) { - if (outstanding_settings_.size() == max_outstanding_settings_) - return false; + if (outstanding_settings_.size() == max_outstanding_settings_) return false; outstanding_settings_.push(settings); IncrementCurrentSessionMemory(sizeof(*settings)); return true; } -Http2Session::Http2Ping::Http2Ping( - Http2Session* session) - : AsyncWrap(session->env(), - session->env()->http2ping_constructor_template() - ->NewInstance(session->env()->context()) - .ToLocalChecked(), - AsyncWrap::PROVIDER_HTTP2PING), - session_(session), - startTime_(uv_hrtime()) { } +Http2Session::Http2Ping::Http2Ping(Http2Session* session) + : AsyncWrap(session->env(), + session->env() + ->http2ping_constructor_template() + ->NewInstance(session->env()->context()) + .ToLocalChecked(), + AsyncWrap::PROVIDER_HTTP2PING), + session_(session), + startTime_(uv_hrtime()) {} void Http2Session::Http2Ping::Send(uint8_t* payload) { uint8_t data[8]; @@ -2750,21 +2670,18 @@ void Http2Session::Http2Ping::Done(bool ack, const uint8_t* payload) { Local buf = Undefined(env()->isolate()); if (payload != nullptr) { - buf = Buffer::Copy(env()->isolate(), - reinterpret_cast(payload), - 8).ToLocalChecked(); + buf = Buffer::Copy( + env()->isolate(), reinterpret_cast(payload), 8) + .ToLocalChecked(); } - Local argv[3] = { - Boolean::New(env()->isolate(), ack), - Number::New(env()->isolate(), duration), - buf - }; + Local argv[3] = {Boolean::New(env()->isolate(), ack), + Number::New(env()->isolate(), duration), + buf}; MakeCallback(env()->ondone_string(), arraysize(argv), argv); delete this; } - void nghttp2_stream_write::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackThis(this); if (req_wrap != nullptr) @@ -2772,14 +2689,12 @@ void nghttp2_stream_write::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("buf", buf); } - void nghttp2_header::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackThis(this); tracker->TrackFieldWithSize("name", nghttp2_rcbuf_get_buf(name).len); tracker->TrackFieldWithSize("value", nghttp2_rcbuf_get_buf(value).len); } - // Set up the process.binding('http2') binding. void Initialize(Local target, Local unused, @@ -2791,28 +2706,22 @@ void Initialize(Local target, std::unique_ptr state(new Http2State(isolate)); -#define SET_STATE_TYPEDARRAY(name, field) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(isolate, (name)), \ - (field)).FromJust() +#define SET_STATE_TYPEDARRAY(name, field) \ + target->Set(context, FIXED_ONE_BYTE_STRING(isolate, (name)), (field)) \ + .FromJust() // Initialize the buffer used for padding callbacks - SET_STATE_TYPEDARRAY( - "paddingBuffer", state->padding_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("paddingBuffer", state->padding_buffer.GetJSArray()); // Initialize the buffer used to store the session state - SET_STATE_TYPEDARRAY( - "sessionState", state->session_state_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("sessionState", + state->session_state_buffer.GetJSArray()); // Initialize the buffer used to store the stream state - SET_STATE_TYPEDARRAY( - "streamState", state->stream_state_buffer.GetJSArray()); - SET_STATE_TYPEDARRAY( - "settingsBuffer", state->settings_buffer.GetJSArray()); - SET_STATE_TYPEDARRAY( - "optionsBuffer", state->options_buffer.GetJSArray()); - SET_STATE_TYPEDARRAY( - "streamStats", state->stream_stats_buffer.GetJSArray()); - SET_STATE_TYPEDARRAY( - "sessionStats", state->session_stats_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("streamState", state->stream_state_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("settingsBuffer", state->settings_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("optionsBuffer", state->options_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("streamStats", state->stream_stats_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY("sessionStats", + state->session_stats_buffer.GetJSArray()); #undef SET_STATE_TYPEDARRAY env->set_http2_state(std::move(state)); @@ -2825,7 +2734,7 @@ void Initialize(Local target, env->SetMethod(target, "nghttp2ErrorString", HttpErrorString); Local http2SessionClassName = - FIXED_ONE_BYTE_STRING(isolate, "Http2Session"); + FIXED_ONE_BYTE_STRING(isolate, "Http2Session"); Local ping = FunctionTemplate::New(env->isolate()); ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping")); @@ -2858,12 +2767,13 @@ void Initialize(Local target, Local streamt = stream->InstanceTemplate(); streamt->SetInternalFieldCount(1); env->set_http2stream_constructor_template(streamt); - target->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"), - stream->GetFunction()).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"), + stream->GetFunction()) + .FromJust(); - Local session = - env->NewFunctionTemplate(Http2Session::New); + Local session = env->NewFunctionTemplate(Http2Session::New); session->SetClassName(http2SessionClassName); session->InstanceTemplate()->SetInternalFieldCount(1); AsyncWrap::AddWrapMethods(env, session); @@ -2874,52 +2784,53 @@ void Initialize(Local target, env->SetProtoMethod(session, "goaway", Http2Session::Goaway); env->SetProtoMethod(session, "settings", Http2Session::Settings); env->SetProtoMethod(session, "request", Http2Session::Request); - env->SetProtoMethod(session, "setNextStreamID", - Http2Session::SetNextStreamID); - env->SetProtoMethod(session, "updateChunksSent", - Http2Session::UpdateChunksSent); + env->SetProtoMethod( + session, "setNextStreamID", Http2Session::SetNextStreamID); + env->SetProtoMethod( + session, "updateChunksSent", Http2Session::UpdateChunksSent); env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState); env->SetProtoMethod( - session, "localSettings", + session, + "localSettings", Http2Session::RefreshSettings); env->SetProtoMethod( - session, "remoteSettings", + session, + "remoteSettings", Http2Session::RefreshSettings); - target->Set(context, - http2SessionClassName, - session->GetFunction()).FromJust(); + target->Set(context, http2SessionClassName, session->GetFunction()) + .FromJust(); Local constants = Object::New(isolate); Local name_for_error_code = Array::New(isolate); -#define NODE_NGHTTP2_ERROR_CODES(V) \ - V(NGHTTP2_SESSION_SERVER); \ - V(NGHTTP2_SESSION_CLIENT); \ - V(NGHTTP2_STREAM_STATE_IDLE); \ - V(NGHTTP2_STREAM_STATE_OPEN); \ - V(NGHTTP2_STREAM_STATE_RESERVED_LOCAL); \ - V(NGHTTP2_STREAM_STATE_RESERVED_REMOTE); \ - V(NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL); \ - V(NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE); \ - V(NGHTTP2_STREAM_STATE_CLOSED); \ - V(NGHTTP2_NO_ERROR); \ - V(NGHTTP2_PROTOCOL_ERROR); \ - V(NGHTTP2_INTERNAL_ERROR); \ - V(NGHTTP2_FLOW_CONTROL_ERROR); \ - V(NGHTTP2_SETTINGS_TIMEOUT); \ - V(NGHTTP2_STREAM_CLOSED); \ - V(NGHTTP2_FRAME_SIZE_ERROR); \ - V(NGHTTP2_REFUSED_STREAM); \ - V(NGHTTP2_CANCEL); \ - V(NGHTTP2_COMPRESSION_ERROR); \ - V(NGHTTP2_CONNECT_ERROR); \ - V(NGHTTP2_ENHANCE_YOUR_CALM); \ - V(NGHTTP2_INADEQUATE_SECURITY); \ - V(NGHTTP2_HTTP_1_1_REQUIRED); \ - -#define V(name) \ - NODE_DEFINE_CONSTANT(constants, name); \ - name_for_error_code->Set(static_cast(name), \ +#define NODE_NGHTTP2_ERROR_CODES(V) \ + V(NGHTTP2_SESSION_SERVER); \ + V(NGHTTP2_SESSION_CLIENT); \ + V(NGHTTP2_STREAM_STATE_IDLE); \ + V(NGHTTP2_STREAM_STATE_OPEN); \ + V(NGHTTP2_STREAM_STATE_RESERVED_LOCAL); \ + V(NGHTTP2_STREAM_STATE_RESERVED_REMOTE); \ + V(NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL); \ + V(NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE); \ + V(NGHTTP2_STREAM_STATE_CLOSED); \ + V(NGHTTP2_NO_ERROR); \ + V(NGHTTP2_PROTOCOL_ERROR); \ + V(NGHTTP2_INTERNAL_ERROR); \ + V(NGHTTP2_FLOW_CONTROL_ERROR); \ + V(NGHTTP2_SETTINGS_TIMEOUT); \ + V(NGHTTP2_STREAM_CLOSED); \ + V(NGHTTP2_FRAME_SIZE_ERROR); \ + V(NGHTTP2_REFUSED_STREAM); \ + V(NGHTTP2_CANCEL); \ + V(NGHTTP2_COMPRESSION_ERROR); \ + V(NGHTTP2_CONNECT_ERROR); \ + V(NGHTTP2_ENHANCE_YOUR_CALM); \ + V(NGHTTP2_INADEQUATE_SECURITY); \ + V(NGHTTP2_HTTP_1_1_REQUIRED); + +#define V(name) \ + NODE_DEFINE_CONSTANT(constants, name); \ + name_for_error_code->Set(static_cast(name), \ FIXED_ONE_BYTE_STRING(isolate, #name)); NODE_NGHTTP2_ERROR_CODES(V) #undef V @@ -2967,29 +2878,30 @@ void Initialize(Local target, NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_MAX); NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_CALLBACK); -#define STRING_CONSTANT(NAME, VALUE) \ - NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE); -HTTP_KNOWN_HEADERS(STRING_CONSTANT) +#define STRING_CONSTANT(NAME, VALUE) \ + NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" #NAME, VALUE); + HTTP_KNOWN_HEADERS(STRING_CONSTANT) #undef STRING_CONSTANT -#define STRING_CONSTANT(NAME, VALUE) \ - NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE); -HTTP_KNOWN_METHODS(STRING_CONSTANT) +#define STRING_CONSTANT(NAME, VALUE) \ + NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" #NAME, VALUE); + HTTP_KNOWN_METHODS(STRING_CONSTANT) #undef STRING_CONSTANT #define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name); -HTTP_STATUS_CODES(V) + HTTP_STATUS_CODES(V) #undef V env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings); env->SetMethod(target, "packSettings", PackSettings); - target->Set(context, - FIXED_ONE_BYTE_STRING(isolate, "constants"), - constants).FromJust(); - target->Set(context, - FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"), - name_for_error_code).FromJust(); + target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "constants"), constants) + .FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"), + name_for_error_code) + .FromJust(); } } // namespace http2 } // namespace node diff --git a/src/node_http2.h b/src/node_http2.h index d7f8d9acae91cb..ece94cea165fd1 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -49,14 +49,9 @@ using performance::PerformanceEntry; #define MAX_BUFFER_COUNT 16 -enum nghttp2_session_type { - NGHTTP2_SESSION_SERVER, - NGHTTP2_SESSION_CLIENT -}; +enum nghttp2_session_type { NGHTTP2_SESSION_SERVER, NGHTTP2_SESSION_CLIENT }; -enum nghttp2_shutdown_flags { - NGHTTP2_SHUTDOWN_FLAG_GRACEFUL -}; +enum nghttp2_shutdown_flags { NGHTTP2_SHUTDOWN_FLAG_GRACEFUL }; enum nghttp2_stream_flags { NGHTTP2_STREAM_FLAG_NONE = 0x0, @@ -88,8 +83,8 @@ struct nghttp2_stream_write : public MemoryRetainer { uv_buf_t buf; inline explicit nghttp2_stream_write(uv_buf_t buf_) : buf(buf_) {} - inline nghttp2_stream_write(WriteWrap* req, uv_buf_t buf_) : - req_wrap(req), buf(buf_) {} + inline nghttp2_stream_write(WriteWrap* req, uv_buf_t buf_) + : req_wrap(req), buf(buf_) {} void MemoryInfo(MemoryTracker* tracker) const override; }; @@ -102,210 +97,209 @@ struct nghttp2_header : public MemoryRetainer { void MemoryInfo(MemoryTracker* tracker) const override; }; - // Unlike the HTTP/1 implementation, the HTTP/2 implementation is not limited // to a fixed number of known supported HTTP methods. These constants, therefore // are provided strictly as a convenience to users and are exposed via the // require('http2').constants object. -#define HTTP_KNOWN_METHODS(V) \ - V(ACL, "ACL") \ - V(BASELINE_CONTROL, "BASELINE-CONTROL") \ - V(BIND, "BIND") \ - V(CHECKIN, "CHECKIN") \ - V(CHECKOUT, "CHECKOUT") \ - V(CONNECT, "CONNECT") \ - V(COPY, "COPY") \ - V(DELETE, "DELETE") \ - V(GET, "GET") \ - V(HEAD, "HEAD") \ - V(LABEL, "LABEL") \ - V(LINK, "LINK") \ - V(LOCK, "LOCK") \ - V(MERGE, "MERGE") \ - V(MKACTIVITY, "MKACTIVITY") \ - V(MKCALENDAR, "MKCALENDAR") \ - V(MKCOL, "MKCOL") \ - V(MKREDIRECTREF, "MKREDIRECTREF") \ - V(MKWORKSPACE, "MKWORKSPACE") \ - V(MOVE, "MOVE") \ - V(OPTIONS, "OPTIONS") \ - V(ORDERPATCH, "ORDERPATCH") \ - V(PATCH, "PATCH") \ - V(POST, "POST") \ - V(PRI, "PRI") \ - V(PROPFIND, "PROPFIND") \ - V(PROPPATCH, "PROPPATCH") \ - V(PUT, "PUT") \ - V(REBIND, "REBIND") \ - V(REPORT, "REPORT") \ - V(SEARCH, "SEARCH") \ - V(TRACE, "TRACE") \ - V(UNBIND, "UNBIND") \ - V(UNCHECKOUT, "UNCHECKOUT") \ - V(UNLINK, "UNLINK") \ - V(UNLOCK, "UNLOCK") \ - V(UPDATE, "UPDATE") \ - V(UPDATEREDIRECTREF, "UPDATEREDIRECTREF") \ +#define HTTP_KNOWN_METHODS(V) \ + V(ACL, "ACL") \ + V(BASELINE_CONTROL, "BASELINE-CONTROL") \ + V(BIND, "BIND") \ + V(CHECKIN, "CHECKIN") \ + V(CHECKOUT, "CHECKOUT") \ + V(CONNECT, "CONNECT") \ + V(COPY, "COPY") \ + V(DELETE, "DELETE") \ + V(GET, "GET") \ + V(HEAD, "HEAD") \ + V(LABEL, "LABEL") \ + V(LINK, "LINK") \ + V(LOCK, "LOCK") \ + V(MERGE, "MERGE") \ + V(MKACTIVITY, "MKACTIVITY") \ + V(MKCALENDAR, "MKCALENDAR") \ + V(MKCOL, "MKCOL") \ + V(MKREDIRECTREF, "MKREDIRECTREF") \ + V(MKWORKSPACE, "MKWORKSPACE") \ + V(MOVE, "MOVE") \ + V(OPTIONS, "OPTIONS") \ + V(ORDERPATCH, "ORDERPATCH") \ + V(PATCH, "PATCH") \ + V(POST, "POST") \ + V(PRI, "PRI") \ + V(PROPFIND, "PROPFIND") \ + V(PROPPATCH, "PROPPATCH") \ + V(PUT, "PUT") \ + V(REBIND, "REBIND") \ + V(REPORT, "REPORT") \ + V(SEARCH, "SEARCH") \ + V(TRACE, "TRACE") \ + V(UNBIND, "UNBIND") \ + V(UNCHECKOUT, "UNCHECKOUT") \ + V(UNLINK, "UNLINK") \ + V(UNLOCK, "UNLOCK") \ + V(UPDATE, "UPDATE") \ + V(UPDATEREDIRECTREF, "UPDATEREDIRECTREF") \ V(VERSION_CONTROL, "VERSION-CONTROL") // These are provided strictly as a convenience to users and are exposed via the // require('http2').constants objects -#define HTTP_KNOWN_HEADERS(V) \ - V(STATUS, ":status") \ - V(METHOD, ":method") \ - V(AUTHORITY, ":authority") \ - V(SCHEME, ":scheme") \ - V(PATH, ":path") \ - V(ACCEPT_CHARSET, "accept-charset") \ - V(ACCEPT_ENCODING, "accept-encoding") \ - V(ACCEPT_LANGUAGE, "accept-language") \ - V(ACCEPT_RANGES, "accept-ranges") \ - V(ACCEPT, "accept") \ - V(ACCESS_CONTROL_ALLOW_CREDENTIALS, "access-control-allow-credentials") \ - V(ACCESS_CONTROL_ALLOW_HEADERS, "access-control-allow-headers") \ - V(ACCESS_CONTROL_ALLOW_METHODS, "access-control-allow-methods") \ - V(ACCESS_CONTROL_ALLOW_ORIGIN, "access-control-allow-origin") \ - V(ACCESS_CONTROL_EXPOSE_HEADERS, "access-control-expose-headers") \ - V(ACCESS_CONTROL_MAX_AGE, "access-control-max-age") \ - V(ACCESS_CONTROL_REQUEST_HEADERS, "access-control-request-headers") \ - V(ACCESS_CONTROL_REQUEST_METHOD, "access-control-request-method") \ - V(AGE, "age") \ - V(ALLOW, "allow") \ - V(AUTHORIZATION, "authorization") \ - V(CACHE_CONTROL, "cache-control") \ - V(CONNECTION, "connection") \ - V(CONTENT_DISPOSITION, "content-disposition") \ - V(CONTENT_ENCODING, "content-encoding") \ - V(CONTENT_LANGUAGE, "content-language") \ - V(CONTENT_LENGTH, "content-length") \ - V(CONTENT_LOCATION, "content-location") \ - V(CONTENT_MD5, "content-md5") \ - V(CONTENT_RANGE, "content-range") \ - V(CONTENT_TYPE, "content-type") \ - V(COOKIE, "cookie") \ - V(DATE, "date") \ - V(DNT, "dnt") \ - V(ETAG, "etag") \ - V(EXPECT, "expect") \ - V(EXPIRES, "expires") \ - V(FORWARDED, "forwarded") \ - V(FROM, "from") \ - V(HOST, "host") \ - V(IF_MATCH, "if-match") \ - V(IF_MODIFIED_SINCE, "if-modified-since") \ - V(IF_NONE_MATCH, "if-none-match") \ - V(IF_RANGE, "if-range") \ - V(IF_UNMODIFIED_SINCE, "if-unmodified-since") \ - V(LAST_MODIFIED, "last-modified") \ - V(LINK, "link") \ - V(LOCATION, "location") \ - V(MAX_FORWARDS, "max-forwards") \ - V(PREFER, "prefer") \ - V(PROXY_AUTHENTICATE, "proxy-authenticate") \ - V(PROXY_AUTHORIZATION, "proxy-authorization") \ - V(RANGE, "range") \ - V(REFERER, "referer") \ - V(REFRESH, "refresh") \ - V(RETRY_AFTER, "retry-after") \ - V(SERVER, "server") \ - V(SET_COOKIE, "set-cookie") \ - V(STRICT_TRANSPORT_SECURITY, "strict-transport-security") \ - V(TRAILER, "trailer") \ - V(TRANSFER_ENCODING, "transfer-encoding") \ - V(TE, "te") \ - V(TK, "tk") \ - V(UPGRADE_INSECURE_REQUESTS, "upgrade-insecure-requests") \ - V(UPGRADE, "upgrade") \ - V(USER_AGENT, "user-agent") \ - V(VARY, "vary") \ - V(VIA, "via") \ - V(WARNING, "warning") \ - V(WWW_AUTHENTICATE, "www-authenticate") \ - V(X_CONTENT_TYPE_OPTIONS, "x-content-type-options") \ - V(X_FRAME_OPTIONS, "x-frame-options") \ - V(HTTP2_SETTINGS, "http2-settings") \ - V(KEEP_ALIVE, "keep-alive") \ +#define HTTP_KNOWN_HEADERS(V) \ + V(STATUS, ":status") \ + V(METHOD, ":method") \ + V(AUTHORITY, ":authority") \ + V(SCHEME, ":scheme") \ + V(PATH, ":path") \ + V(ACCEPT_CHARSET, "accept-charset") \ + V(ACCEPT_ENCODING, "accept-encoding") \ + V(ACCEPT_LANGUAGE, "accept-language") \ + V(ACCEPT_RANGES, "accept-ranges") \ + V(ACCEPT, "accept") \ + V(ACCESS_CONTROL_ALLOW_CREDENTIALS, "access-control-allow-credentials") \ + V(ACCESS_CONTROL_ALLOW_HEADERS, "access-control-allow-headers") \ + V(ACCESS_CONTROL_ALLOW_METHODS, "access-control-allow-methods") \ + V(ACCESS_CONTROL_ALLOW_ORIGIN, "access-control-allow-origin") \ + V(ACCESS_CONTROL_EXPOSE_HEADERS, "access-control-expose-headers") \ + V(ACCESS_CONTROL_MAX_AGE, "access-control-max-age") \ + V(ACCESS_CONTROL_REQUEST_HEADERS, "access-control-request-headers") \ + V(ACCESS_CONTROL_REQUEST_METHOD, "access-control-request-method") \ + V(AGE, "age") \ + V(ALLOW, "allow") \ + V(AUTHORIZATION, "authorization") \ + V(CACHE_CONTROL, "cache-control") \ + V(CONNECTION, "connection") \ + V(CONTENT_DISPOSITION, "content-disposition") \ + V(CONTENT_ENCODING, "content-encoding") \ + V(CONTENT_LANGUAGE, "content-language") \ + V(CONTENT_LENGTH, "content-length") \ + V(CONTENT_LOCATION, "content-location") \ + V(CONTENT_MD5, "content-md5") \ + V(CONTENT_RANGE, "content-range") \ + V(CONTENT_TYPE, "content-type") \ + V(COOKIE, "cookie") \ + V(DATE, "date") \ + V(DNT, "dnt") \ + V(ETAG, "etag") \ + V(EXPECT, "expect") \ + V(EXPIRES, "expires") \ + V(FORWARDED, "forwarded") \ + V(FROM, "from") \ + V(HOST, "host") \ + V(IF_MATCH, "if-match") \ + V(IF_MODIFIED_SINCE, "if-modified-since") \ + V(IF_NONE_MATCH, "if-none-match") \ + V(IF_RANGE, "if-range") \ + V(IF_UNMODIFIED_SINCE, "if-unmodified-since") \ + V(LAST_MODIFIED, "last-modified") \ + V(LINK, "link") \ + V(LOCATION, "location") \ + V(MAX_FORWARDS, "max-forwards") \ + V(PREFER, "prefer") \ + V(PROXY_AUTHENTICATE, "proxy-authenticate") \ + V(PROXY_AUTHORIZATION, "proxy-authorization") \ + V(RANGE, "range") \ + V(REFERER, "referer") \ + V(REFRESH, "refresh") \ + V(RETRY_AFTER, "retry-after") \ + V(SERVER, "server") \ + V(SET_COOKIE, "set-cookie") \ + V(STRICT_TRANSPORT_SECURITY, "strict-transport-security") \ + V(TRAILER, "trailer") \ + V(TRANSFER_ENCODING, "transfer-encoding") \ + V(TE, "te") \ + V(TK, "tk") \ + V(UPGRADE_INSECURE_REQUESTS, "upgrade-insecure-requests") \ + V(UPGRADE, "upgrade") \ + V(USER_AGENT, "user-agent") \ + V(VARY, "vary") \ + V(VIA, "via") \ + V(WARNING, "warning") \ + V(WWW_AUTHENTICATE, "www-authenticate") \ + V(X_CONTENT_TYPE_OPTIONS, "x-content-type-options") \ + V(X_FRAME_OPTIONS, "x-frame-options") \ + V(HTTP2_SETTINGS, "http2-settings") \ + V(KEEP_ALIVE, "keep-alive") \ V(PROXY_CONNECTION, "proxy-connection") enum http_known_headers { -HTTP_KNOWN_HEADER_MIN, + HTTP_KNOWN_HEADER_MIN, #define V(name, value) HTTP_HEADER_##name, -HTTP_KNOWN_HEADERS(V) + HTTP_KNOWN_HEADERS(V) #undef V -HTTP_KNOWN_HEADER_MAX + HTTP_KNOWN_HEADER_MAX }; // While some of these codes are used within the HTTP/2 implementation in // core, they are provided strictly as a convenience to users and are exposed // via the require('http2').constants object. -#define HTTP_STATUS_CODES(V) \ - V(CONTINUE, 100) \ - V(SWITCHING_PROTOCOLS, 101) \ - V(PROCESSING, 102) \ - V(EARLY_HINTS, 103) \ - V(OK, 200) \ - V(CREATED, 201) \ - V(ACCEPTED, 202) \ - V(NON_AUTHORITATIVE_INFORMATION, 203) \ - V(NO_CONTENT, 204) \ - V(RESET_CONTENT, 205) \ - V(PARTIAL_CONTENT, 206) \ - V(MULTI_STATUS, 207) \ - V(ALREADY_REPORTED, 208) \ - V(IM_USED, 226) \ - V(MULTIPLE_CHOICES, 300) \ - V(MOVED_PERMANENTLY, 301) \ - V(FOUND, 302) \ - V(SEE_OTHER, 303) \ - V(NOT_MODIFIED, 304) \ - V(USE_PROXY, 305) \ - V(TEMPORARY_REDIRECT, 307) \ - V(PERMANENT_REDIRECT, 308) \ - V(BAD_REQUEST, 400) \ - V(UNAUTHORIZED, 401) \ - V(PAYMENT_REQUIRED, 402) \ - V(FORBIDDEN, 403) \ - V(NOT_FOUND, 404) \ - V(METHOD_NOT_ALLOWED, 405) \ - V(NOT_ACCEPTABLE, 406) \ - V(PROXY_AUTHENTICATION_REQUIRED, 407) \ - V(REQUEST_TIMEOUT, 408) \ - V(CONFLICT, 409) \ - V(GONE, 410) \ - V(LENGTH_REQUIRED, 411) \ - V(PRECONDITION_FAILED, 412) \ - V(PAYLOAD_TOO_LARGE, 413) \ - V(URI_TOO_LONG, 414) \ - V(UNSUPPORTED_MEDIA_TYPE, 415) \ - V(RANGE_NOT_SATISFIABLE, 416) \ - V(EXPECTATION_FAILED, 417) \ - V(TEAPOT, 418) \ - V(MISDIRECTED_REQUEST, 421) \ - V(UNPROCESSABLE_ENTITY, 422) \ - V(LOCKED, 423) \ - V(FAILED_DEPENDENCY, 424) \ - V(UNORDERED_COLLECTION, 425) \ - V(UPGRADE_REQUIRED, 426) \ - V(PRECONDITION_REQUIRED, 428) \ - V(TOO_MANY_REQUESTS, 429) \ - V(REQUEST_HEADER_FIELDS_TOO_LARGE, 431) \ - V(UNAVAILABLE_FOR_LEGAL_REASONS, 451) \ - V(INTERNAL_SERVER_ERROR, 500) \ - V(NOT_IMPLEMENTED, 501) \ - V(BAD_GATEWAY, 502) \ - V(SERVICE_UNAVAILABLE, 503) \ - V(GATEWAY_TIMEOUT, 504) \ - V(HTTP_VERSION_NOT_SUPPORTED, 505) \ - V(VARIANT_ALSO_NEGOTIATES, 506) \ - V(INSUFFICIENT_STORAGE, 507) \ - V(LOOP_DETECTED, 508) \ - V(BANDWIDTH_LIMIT_EXCEEDED, 509) \ - V(NOT_EXTENDED, 510) \ +#define HTTP_STATUS_CODES(V) \ + V(CONTINUE, 100) \ + V(SWITCHING_PROTOCOLS, 101) \ + V(PROCESSING, 102) \ + V(EARLY_HINTS, 103) \ + V(OK, 200) \ + V(CREATED, 201) \ + V(ACCEPTED, 202) \ + V(NON_AUTHORITATIVE_INFORMATION, 203) \ + V(NO_CONTENT, 204) \ + V(RESET_CONTENT, 205) \ + V(PARTIAL_CONTENT, 206) \ + V(MULTI_STATUS, 207) \ + V(ALREADY_REPORTED, 208) \ + V(IM_USED, 226) \ + V(MULTIPLE_CHOICES, 300) \ + V(MOVED_PERMANENTLY, 301) \ + V(FOUND, 302) \ + V(SEE_OTHER, 303) \ + V(NOT_MODIFIED, 304) \ + V(USE_PROXY, 305) \ + V(TEMPORARY_REDIRECT, 307) \ + V(PERMANENT_REDIRECT, 308) \ + V(BAD_REQUEST, 400) \ + V(UNAUTHORIZED, 401) \ + V(PAYMENT_REQUIRED, 402) \ + V(FORBIDDEN, 403) \ + V(NOT_FOUND, 404) \ + V(METHOD_NOT_ALLOWED, 405) \ + V(NOT_ACCEPTABLE, 406) \ + V(PROXY_AUTHENTICATION_REQUIRED, 407) \ + V(REQUEST_TIMEOUT, 408) \ + V(CONFLICT, 409) \ + V(GONE, 410) \ + V(LENGTH_REQUIRED, 411) \ + V(PRECONDITION_FAILED, 412) \ + V(PAYLOAD_TOO_LARGE, 413) \ + V(URI_TOO_LONG, 414) \ + V(UNSUPPORTED_MEDIA_TYPE, 415) \ + V(RANGE_NOT_SATISFIABLE, 416) \ + V(EXPECTATION_FAILED, 417) \ + V(TEAPOT, 418) \ + V(MISDIRECTED_REQUEST, 421) \ + V(UNPROCESSABLE_ENTITY, 422) \ + V(LOCKED, 423) \ + V(FAILED_DEPENDENCY, 424) \ + V(UNORDERED_COLLECTION, 425) \ + V(UPGRADE_REQUIRED, 426) \ + V(PRECONDITION_REQUIRED, 428) \ + V(TOO_MANY_REQUESTS, 429) \ + V(REQUEST_HEADER_FIELDS_TOO_LARGE, 431) \ + V(UNAVAILABLE_FOR_LEGAL_REASONS, 451) \ + V(INTERNAL_SERVER_ERROR, 500) \ + V(NOT_IMPLEMENTED, 501) \ + V(BAD_GATEWAY, 502) \ + V(SERVICE_UNAVAILABLE, 503) \ + V(GATEWAY_TIMEOUT, 504) \ + V(HTTP_VERSION_NOT_SUPPORTED, 505) \ + V(VARIANT_ALSO_NEGOTIATES, 506) \ + V(INSUFFICIENT_STORAGE, 507) \ + V(LOOP_DETECTED, 508) \ + V(BANDWIDTH_LIMIT_EXCEEDED, 509) \ + V(NOT_EXTENDED, 510) \ V(NETWORK_AUTHENTICATION_REQUIRED, 511) enum http_status_codes { #define V(name, code) HTTP_STATUS_##name = code, -HTTP_STATUS_CODES(V) + HTTP_STATUS_CODES(V) #undef V }; @@ -338,8 +332,8 @@ enum session_state_flags { // This allows for 4 default-sized frames with their frame headers static const size_t kAllocBufferSize = 4 * (16384 + 9); -typedef uint32_t(*get_setting)(nghttp2_session* session, - nghttp2_settings_id id); +typedef uint32_t (*get_setting)(nghttp2_session* session, + nghttp2_settings_id id); class Http2Session; class Http2Stream; @@ -366,53 +360,33 @@ class Http2Options { public: explicit Http2Options(Environment* env); - ~Http2Options() { - nghttp2_option_del(options_); - } + ~Http2Options() { nghttp2_option_del(options_); } - nghttp2_option* operator*() const { - return options_; - } + nghttp2_option* operator*() const { return options_; } - void SetMaxHeaderPairs(uint32_t max) { - max_header_pairs_ = max; - } + void SetMaxHeaderPairs(uint32_t max) { max_header_pairs_ = max; } - uint32_t GetMaxHeaderPairs() const { - return max_header_pairs_; - } + uint32_t GetMaxHeaderPairs() const { return max_header_pairs_; } void SetPaddingStrategy(padding_strategy_type val) { padding_strategy_ = static_cast(val); } - padding_strategy_type GetPaddingStrategy() const { - return padding_strategy_; - } + padding_strategy_type GetPaddingStrategy() const { return padding_strategy_; } - void SetMaxOutstandingPings(size_t max) { - max_outstanding_pings_ = max; - } + void SetMaxOutstandingPings(size_t max) { max_outstanding_pings_ = max; } - size_t GetMaxOutstandingPings() { - return max_outstanding_pings_; - } + size_t GetMaxOutstandingPings() { return max_outstanding_pings_; } void SetMaxOutstandingSettings(size_t max) { max_outstanding_settings_ = max; } - size_t GetMaxOutstandingSettings() { - return max_outstanding_settings_; - } + size_t GetMaxOutstandingSettings() { return max_outstanding_settings_; } - void SetMaxSessionMemory(uint64_t max) { - max_session_memory_ = max; - } + void SetMaxSessionMemory(uint64_t max) { max_session_memory_ = max; } - uint64_t GetMaxSessionMemory() { - return max_session_memory_; - } + uint64_t GetMaxSessionMemory() { return max_session_memory_; } private: nghttp2_option* options_; @@ -430,9 +404,8 @@ class Http2Priority { Local weight, Local exclusive); - nghttp2_priority_spec* operator*() { - return &spec; - } + nghttp2_priority_spec* operator*() { return &spec; } + private: nghttp2_priority_spec spec; }; @@ -443,8 +416,7 @@ class Http2StreamListener : public StreamListener { void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override; }; -class Http2Stream : public AsyncWrap, - public StreamBase { +class Http2Stream : public AsyncWrap, public StreamBase { public: Http2Stream(Http2Session* session, int32_t id, @@ -462,7 +434,6 @@ class Http2Stream : public AsyncWrap, // Process a Data Chunk void OnDataChunk(uv_buf_t* chunk); - // Required for StreamBase int ReadStart() override; @@ -493,12 +464,10 @@ class Http2Stream : public AsyncWrap, void FlushRstStream(); // Submits a PUSH_PROMISE frame with this stream as the parent. - Http2Stream* SubmitPushPromise( - nghttp2_nv* nva, - size_t len, - int32_t* ret, - int options = 0); - + Http2Stream* SubmitPushPromise(nghttp2_nv* nva, + size_t len, + int32_t* ret, + int options = 0); void Close(int32_t code); @@ -517,9 +486,7 @@ class Http2Stream : public AsyncWrap, return flags_ & NGHTTP2_STREAM_FLAG_READ_PAUSED; } - inline bool IsClosed() const { - return flags_ & NGHTTP2_STREAM_FLAG_CLOSED; - } + inline bool IsClosed() const { return flags_ & NGHTTP2_STREAM_FLAG_CLOSED; } inline bool HasTrailers() const { return flags_ & NGHTTP2_STREAM_FLAG_TRAILERS; @@ -555,18 +522,16 @@ class Http2Stream : public AsyncWrap, void StartHeaders(nghttp2_headers_category category); // Required for StreamBase - bool IsAlive() override { - return true; - } + bool IsAlive() override { return true; } // Required for StreamBase - bool IsClosing() override { - return false; - } + bool IsClosing() override { return false; } AsyncWrap* GetAsyncWrap() override { return this; } - int DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count, + int DoWrite(WriteWrap* w, + uv_buf_t* bufs, + size_t count, uv_stream_t* send_handle) override; void MemoryInfo(MemoryTracker* tracker) const override { @@ -606,10 +571,10 @@ class Http2Stream : public AsyncWrap, Statistics statistics_ = {}; private: - Http2Session* session_ = nullptr; // The Parent HTTP/2 Session - int32_t id_ = 0; // The Stream Identifier - int32_t code_ = NGHTTP2_NO_ERROR; // The RST_STREAM code (if any) - int flags_ = NGHTTP2_STREAM_FLAG_NONE; // Internal state flags + Http2Session* session_ = nullptr; // The Parent HTTP/2 Session + int32_t id_ = 0; // The Stream Identifier + int32_t code_ = NGHTTP2_NO_ERROR; // The RST_STREAM code (if any) + int flags_ = NGHTTP2_STREAM_FLAG_NONE; // Internal state flags uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS; uint32_t max_header_length_ = DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE; @@ -643,12 +608,11 @@ class Http2Stream::Provider { explicit Provider(int options); virtual ~Provider(); - nghttp2_data_provider* operator*() { - return !empty_ ? &provider_ : nullptr; - } + nghttp2_data_provider* operator*() { return !empty_ ? &provider_ : nullptr; } class FD; class Stream; + protected: nghttp2_data_provider provider_; @@ -670,7 +634,6 @@ class Http2Stream::Provider::Stream : public Http2Stream::Provider { void* user_data); }; - class Http2Session : public AsyncWrap, public StreamListener { public: Http2Session(Environment* env, @@ -690,8 +653,7 @@ class Http2Session : public AsyncWrap, public StreamListener { void Start(); void Stop(); - void Close(uint32_t code = NGHTTP2_NO_ERROR, - bool socket_closed = false); + void Close(uint32_t code = NGHTTP2_NO_ERROR, bool socket_closed = false); void Consume(Local external); void Unconsume(); void Goaway(uint32_t code, int32_t lastStreamID, uint8_t* data, size_t len); @@ -708,12 +670,11 @@ class Http2Session : public AsyncWrap, public StreamListener { // Submits a new request. If the request is a success, assigned // will be a pointer to the Http2Stream instance assigned. // This only works if the session is a client session. - Http2Stream* SubmitRequest( - nghttp2_priority_spec* prispec, - nghttp2_nv* nva, - size_t len, - int32_t* ret, - int options = 0); + Http2Stream* SubmitRequest(nghttp2_priority_spec* prispec, + nghttp2_nv* nva, + size_t len, + int32_t* ret, + int options = 0); inline nghttp2_session_type type() const { return session_type_; } @@ -803,9 +764,7 @@ class Http2Session : public AsyncWrap, public StreamListener { template static void GetSettings(const FunctionCallbackInfo& args); - uv_loop_t* event_loop() const { - return env()->event_loop(); - } + uv_loop_t* event_loop() const { return env()->event_loop(); } Http2Ping* PopPing(); bool AddPing(Http2Ping* ping); @@ -856,12 +815,9 @@ class Http2Session : public AsyncWrap, public StreamListener { private: // Frame Padding Strategies - ssize_t OnDWordAlignedPadding(size_t frameLength, - size_t maxPayloadLen); - ssize_t OnMaxFrameSizePadding(size_t frameLength, - size_t maxPayloadLen); - ssize_t OnCallbackPadding(size_t frameLength, - size_t maxPayloadLen); + ssize_t OnDWordAlignedPadding(size_t frameLength, size_t maxPayloadLen); + ssize_t OnMaxFrameSizePadding(size_t frameLength, size_t maxPayloadLen); + ssize_t OnCallbackPadding(size_t frameLength, size_t maxPayloadLen); // Frame Handler void HandleDataFrame(const nghttp2_frame* frame); @@ -873,71 +829,59 @@ class Http2Session : public AsyncWrap, public StreamListener { void HandleAltSvcFrame(const nghttp2_frame* frame); // nghttp2 callbacks - static int OnBeginHeadersCallback( - nghttp2_session* session, - const nghttp2_frame* frame, - void* user_data); - static int OnHeaderCallback( - nghttp2_session* session, - const nghttp2_frame* frame, - nghttp2_rcbuf* name, - nghttp2_rcbuf* value, - uint8_t flags, - void* user_data); - static int OnFrameReceive( - nghttp2_session* session, - const nghttp2_frame* frame, - void* user_data); - static int OnFrameNotSent( - nghttp2_session* session, - const nghttp2_frame* frame, - int error_code, - void* user_data); - static int OnFrameSent( - nghttp2_session* session, - const nghttp2_frame* frame, - void* user_data); - static int OnStreamClose( - nghttp2_session* session, - int32_t id, - uint32_t code, - void* user_data); - static int OnInvalidHeader( - nghttp2_session* session, - const nghttp2_frame* frame, - nghttp2_rcbuf* name, - nghttp2_rcbuf* value, - uint8_t flags, - void* user_data); - static int OnDataChunkReceived( - nghttp2_session* session, - uint8_t flags, - int32_t id, - const uint8_t* data, - size_t len, - void* user_data); - static ssize_t OnSelectPadding( - nghttp2_session* session, - const nghttp2_frame* frame, - size_t maxPayloadLen, - void* user_data); - static int OnNghttpError( - nghttp2_session* session, - const char* message, - size_t len, - void* user_data); - static int OnSendData( - nghttp2_session* session, - nghttp2_frame* frame, - const uint8_t* framehd, - size_t length, - nghttp2_data_source* source, - void* user_data); - static int OnInvalidFrame( - nghttp2_session* session, - const nghttp2_frame* frame, - int lib_error_code, - void* user_data); + static int OnBeginHeadersCallback(nghttp2_session* session, + const nghttp2_frame* frame, + void* user_data); + static int OnHeaderCallback(nghttp2_session* session, + const nghttp2_frame* frame, + nghttp2_rcbuf* name, + nghttp2_rcbuf* value, + uint8_t flags, + void* user_data); + static int OnFrameReceive(nghttp2_session* session, + const nghttp2_frame* frame, + void* user_data); + static int OnFrameNotSent(nghttp2_session* session, + const nghttp2_frame* frame, + int error_code, + void* user_data); + static int OnFrameSent(nghttp2_session* session, + const nghttp2_frame* frame, + void* user_data); + static int OnStreamClose(nghttp2_session* session, + int32_t id, + uint32_t code, + void* user_data); + static int OnInvalidHeader(nghttp2_session* session, + const nghttp2_frame* frame, + nghttp2_rcbuf* name, + nghttp2_rcbuf* value, + uint8_t flags, + void* user_data); + static int OnDataChunkReceived(nghttp2_session* session, + uint8_t flags, + int32_t id, + const uint8_t* data, + size_t len, + void* user_data); + static ssize_t OnSelectPadding(nghttp2_session* session, + const nghttp2_frame* frame, + size_t maxPayloadLen, + void* user_data); + static int OnNghttpError(nghttp2_session* session, + const char* message, + size_t len, + void* user_data); + static int OnSendData(nghttp2_session* session, + nghttp2_frame* frame, + const uint8_t* framehd, + size_t length, + nghttp2_data_source* source, + void* user_data); + static int OnInvalidFrame(nghttp2_session* session, + const nghttp2_frame* frame, + int lib_error_code, + void* user_data); struct Callbacks { inline explicit Callbacks(bool kHasGetPaddingCallback); @@ -997,22 +941,20 @@ class Http2Session : public AsyncWrap, public StreamListener { class Http2SessionPerformanceEntry : public PerformanceEntry { public: - Http2SessionPerformanceEntry( - Environment* env, - const Http2Session::Statistics& stats, - nghttp2_session_type type) : - PerformanceEntry(env, "Http2Session", "http2", - stats.start_time, - stats.end_time), - ping_rtt_(stats.ping_rtt), - data_sent_(stats.data_sent), - data_received_(stats.data_received), - frame_count_(stats.frame_count), - frame_sent_(stats.frame_sent), - stream_count_(stats.stream_count), - max_concurrent_streams_(stats.max_concurrent_streams), - stream_average_duration_(stats.stream_average_duration), - session_type_(type) { } + Http2SessionPerformanceEntry(Environment* env, + const Http2Session::Statistics& stats, + nghttp2_session_type type) + : PerformanceEntry( + env, "Http2Session", "http2", stats.start_time, stats.end_time), + ping_rtt_(stats.ping_rtt), + data_sent_(stats.data_sent), + data_received_(stats.data_received), + frame_count_(stats.frame_count), + frame_sent_(stats.frame_sent), + stream_count_(stats.stream_count), + max_concurrent_streams_(stats.max_concurrent_streams), + stream_average_duration_(stats.stream_average_duration), + session_type_(type) {} uint64_t ping_rtt() const { return ping_rtt_; } uint64_t data_sent() const { return data_sent_; } @@ -1042,19 +984,17 @@ class Http2SessionPerformanceEntry : public PerformanceEntry { class Http2StreamPerformanceEntry : public PerformanceEntry { public: - Http2StreamPerformanceEntry( - Environment* env, - int32_t id, - const Http2Stream::Statistics& stats) : - PerformanceEntry(env, "Http2Stream", "http2", - stats.start_time, - stats.end_time), - id_(id), - first_header_(stats.first_header), - first_byte_(stats.first_byte), - first_byte_sent_(stats.first_byte_sent), - sent_bytes_(stats.sent_bytes), - received_bytes_(stats.received_bytes) { } + Http2StreamPerformanceEntry(Environment* env, + int32_t id, + const Http2Stream::Statistics& stats) + : PerformanceEntry( + env, "Http2Stream", "http2", stats.start_time, stats.end_time), + id_(id), + first_header_(stats.first_header), + first_byte_(stats.first_byte), + first_byte_sent_(stats.first_byte_sent), + sent_bytes_(stats.sent_bytes), + received_bytes_(stats.received_bytes) {} int32_t id() const { return id_; } uint64_t first_header() const { return first_header_; } @@ -1122,9 +1062,7 @@ class Http2Session::Http2Settings : public AsyncWrap { static void RefreshDefaults(Environment* env); // Update the local or remote settings for the given session - static void Update(Environment* env, - Http2Session* session, - get_setting fn); + static void Update(Environment* env, Http2Session* session, get_setting fn); private: void Init(); @@ -1134,12 +1072,10 @@ class Http2Session::Http2Settings : public AsyncWrap { nghttp2_settings_entry entries_[IDX_SETTINGS_COUNT]; }; -class ExternalHeader : - public String::ExternalOneByteStringResource { +class ExternalHeader : public String::ExternalOneByteStringResource { public: explicit ExternalHeader(nghttp2_rcbuf* buf) - : buf_(buf), vec_(nghttp2_rcbuf_get_buf(buf)) { - } + : buf_(buf), vec_(nghttp2_rcbuf_get_buf(buf)) {} ~ExternalHeader() override { nghttp2_rcbuf_decref(buf_); @@ -1150,17 +1086,12 @@ class ExternalHeader : return const_cast(reinterpret_cast(vec_.base)); } - size_t length() const override { - return vec_.len; - } + size_t length() const override { return vec_.len; } - static inline - MaybeLocal GetInternalizedString(Environment* env, - const nghttp2_vec& vec) { - return String::NewFromOneByte(env->isolate(), - vec.base, - v8::NewStringType::kInternalized, - vec.len); + static inline MaybeLocal GetInternalizedString( + Environment* env, const nghttp2_vec& vec) { + return String::NewFromOneByte( + env->isolate(), vec.base, v8::NewStringType::kInternalized, vec.len); } template @@ -1195,8 +1126,7 @@ class ExternalHeader : session->StopTrackingRcbuf(buf); ExternalHeader* h_str = new ExternalHeader(buf); MaybeLocal str = String::NewExternalOneByte(env->isolate(), h_str); - if (str.IsEmpty()) - delete h_str; + if (str.IsEmpty()) delete h_str; return str; } @@ -1211,13 +1141,9 @@ class Headers { Headers(Isolate* isolate, Local context, Local headers); ~Headers() {} - nghttp2_nv* operator*() { - return reinterpret_cast(*buf_); - } + nghttp2_nv* operator*() { return reinterpret_cast(*buf_); } - size_t length() const { - return count_; - } + size_t length() const { return count_; } private: size_t count_; diff --git a/src/node_http2_state.h b/src/node_http2_state.h index 64a0942f7ffa67..7981e395e622ca 100644 --- a/src/node_http2_state.h +++ b/src/node_http2_state.h @@ -8,124 +8,116 @@ namespace node { namespace http2 { - enum Http2SettingsIndex { - IDX_SETTINGS_HEADER_TABLE_SIZE, - IDX_SETTINGS_ENABLE_PUSH, - IDX_SETTINGS_INITIAL_WINDOW_SIZE, - IDX_SETTINGS_MAX_FRAME_SIZE, - IDX_SETTINGS_MAX_CONCURRENT_STREAMS, - IDX_SETTINGS_MAX_HEADER_LIST_SIZE, - IDX_SETTINGS_COUNT - }; +enum Http2SettingsIndex { + IDX_SETTINGS_HEADER_TABLE_SIZE, + IDX_SETTINGS_ENABLE_PUSH, + IDX_SETTINGS_INITIAL_WINDOW_SIZE, + IDX_SETTINGS_MAX_FRAME_SIZE, + IDX_SETTINGS_MAX_CONCURRENT_STREAMS, + IDX_SETTINGS_MAX_HEADER_LIST_SIZE, + IDX_SETTINGS_COUNT +}; - enum Http2SessionStateIndex { - IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE, - IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH, - IDX_SESSION_STATE_NEXT_STREAM_ID, - IDX_SESSION_STATE_LOCAL_WINDOW_SIZE, - IDX_SESSION_STATE_LAST_PROC_STREAM_ID, - IDX_SESSION_STATE_REMOTE_WINDOW_SIZE, - IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE, - IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE, - IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE, - IDX_SESSION_STATE_COUNT - }; +enum Http2SessionStateIndex { + IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE, + IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH, + IDX_SESSION_STATE_NEXT_STREAM_ID, + IDX_SESSION_STATE_LOCAL_WINDOW_SIZE, + IDX_SESSION_STATE_LAST_PROC_STREAM_ID, + IDX_SESSION_STATE_REMOTE_WINDOW_SIZE, + IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE, + IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE, + IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE, + IDX_SESSION_STATE_COUNT +}; - enum Http2StreamStateIndex { - IDX_STREAM_STATE, - IDX_STREAM_STATE_WEIGHT, - IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT, - IDX_STREAM_STATE_LOCAL_CLOSE, - IDX_STREAM_STATE_REMOTE_CLOSE, - IDX_STREAM_STATE_LOCAL_WINDOW_SIZE, - IDX_STREAM_STATE_COUNT - }; +enum Http2StreamStateIndex { + IDX_STREAM_STATE, + IDX_STREAM_STATE_WEIGHT, + IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT, + IDX_STREAM_STATE_LOCAL_CLOSE, + IDX_STREAM_STATE_REMOTE_CLOSE, + IDX_STREAM_STATE_LOCAL_WINDOW_SIZE, + IDX_STREAM_STATE_COUNT +}; - enum Http2OptionsIndex { - IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE, - IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS, - IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH, - IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS, - IDX_OPTIONS_PADDING_STRATEGY, - IDX_OPTIONS_MAX_HEADER_LIST_PAIRS, - IDX_OPTIONS_MAX_OUTSTANDING_PINGS, - IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS, - IDX_OPTIONS_MAX_SESSION_MEMORY, - IDX_OPTIONS_FLAGS - }; +enum Http2OptionsIndex { + IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE, + IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS, + IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH, + IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS, + IDX_OPTIONS_PADDING_STRATEGY, + IDX_OPTIONS_MAX_HEADER_LIST_PAIRS, + IDX_OPTIONS_MAX_OUTSTANDING_PINGS, + IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS, + IDX_OPTIONS_MAX_SESSION_MEMORY, + IDX_OPTIONS_FLAGS +}; - enum Http2PaddingBufferFields { - PADDING_BUF_FRAME_LENGTH, - PADDING_BUF_MAX_PAYLOAD_LENGTH, - PADDING_BUF_RETURN_VALUE, - PADDING_BUF_FIELD_COUNT - }; +enum Http2PaddingBufferFields { + PADDING_BUF_FRAME_LENGTH, + PADDING_BUF_MAX_PAYLOAD_LENGTH, + PADDING_BUF_RETURN_VALUE, + PADDING_BUF_FIELD_COUNT +}; - enum Http2StreamStatisticsIndex { - IDX_STREAM_STATS_ID, - IDX_STREAM_STATS_TIMETOFIRSTBYTE, - IDX_STREAM_STATS_TIMETOFIRSTHEADER, - IDX_STREAM_STATS_TIMETOFIRSTBYTESENT, - IDX_STREAM_STATS_SENTBYTES, - IDX_STREAM_STATS_RECEIVEDBYTES, - IDX_STREAM_STATS_COUNT - }; +enum Http2StreamStatisticsIndex { + IDX_STREAM_STATS_ID, + IDX_STREAM_STATS_TIMETOFIRSTBYTE, + IDX_STREAM_STATS_TIMETOFIRSTHEADER, + IDX_STREAM_STATS_TIMETOFIRSTBYTESENT, + IDX_STREAM_STATS_SENTBYTES, + IDX_STREAM_STATS_RECEIVEDBYTES, + IDX_STREAM_STATS_COUNT +}; - enum Http2SessionStatisticsIndex { - IDX_SESSION_STATS_TYPE, - IDX_SESSION_STATS_PINGRTT, - IDX_SESSION_STATS_FRAMESRECEIVED, - IDX_SESSION_STATS_FRAMESSENT, - IDX_SESSION_STATS_STREAMCOUNT, - IDX_SESSION_STATS_STREAMAVERAGEDURATION, - IDX_SESSION_STATS_DATA_SENT, - IDX_SESSION_STATS_DATA_RECEIVED, - IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS, - IDX_SESSION_STATS_COUNT - }; +enum Http2SessionStatisticsIndex { + IDX_SESSION_STATS_TYPE, + IDX_SESSION_STATS_PINGRTT, + IDX_SESSION_STATS_FRAMESRECEIVED, + IDX_SESSION_STATS_FRAMESSENT, + IDX_SESSION_STATS_STREAMCOUNT, + IDX_SESSION_STATS_STREAMAVERAGEDURATION, + IDX_SESSION_STATS_DATA_SENT, + IDX_SESSION_STATS_DATA_RECEIVED, + IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS, + IDX_SESSION_STATS_COUNT +}; class Http2State { public: - explicit Http2State(v8::Isolate* isolate) : - root_buffer( - isolate, - sizeof(http2_state_internal)), - session_state_buffer( - isolate, - offsetof(http2_state_internal, session_state_buffer), - IDX_SESSION_STATE_COUNT, - root_buffer), - stream_state_buffer( - isolate, - offsetof(http2_state_internal, stream_state_buffer), - IDX_STREAM_STATE_COUNT, - root_buffer), - stream_stats_buffer( - isolate, - offsetof(http2_state_internal, stream_stats_buffer), - IDX_STREAM_STATS_COUNT, - root_buffer), - session_stats_buffer( - isolate, - offsetof(http2_state_internal, session_stats_buffer), - IDX_SESSION_STATS_COUNT, - root_buffer), - padding_buffer( - isolate, - offsetof(http2_state_internal, padding_buffer), - PADDING_BUF_FIELD_COUNT, - root_buffer), - options_buffer( - isolate, - offsetof(http2_state_internal, options_buffer), - IDX_OPTIONS_FLAGS + 1, - root_buffer), - settings_buffer( - isolate, - offsetof(http2_state_internal, settings_buffer), - IDX_SETTINGS_COUNT + 1, - root_buffer) { - } + explicit Http2State(v8::Isolate* isolate) + : root_buffer(isolate, sizeof(http2_state_internal)), + session_state_buffer( + isolate, + offsetof(http2_state_internal, session_state_buffer), + IDX_SESSION_STATE_COUNT, + root_buffer), + stream_state_buffer(isolate, + offsetof(http2_state_internal, stream_state_buffer), + IDX_STREAM_STATE_COUNT, + root_buffer), + stream_stats_buffer(isolate, + offsetof(http2_state_internal, stream_stats_buffer), + IDX_STREAM_STATS_COUNT, + root_buffer), + session_stats_buffer( + isolate, + offsetof(http2_state_internal, session_stats_buffer), + IDX_SESSION_STATS_COUNT, + root_buffer), + padding_buffer(isolate, + offsetof(http2_state_internal, padding_buffer), + PADDING_BUF_FIELD_COUNT, + root_buffer), + options_buffer(isolate, + offsetof(http2_state_internal, options_buffer), + IDX_OPTIONS_FLAGS + 1, + root_buffer), + settings_buffer(isolate, + offsetof(http2_state_internal, settings_buffer), + IDX_SETTINGS_COUNT + 1, + root_buffer) {} AliasedBuffer root_buffer; AliasedBuffer session_state_buffer; diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index 318ad0b8e6bf73..0794969c92f0f9 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -44,7 +44,6 @@ // No copying is performed when slicing the buffer, only small reference // allocations. - namespace node { namespace { @@ -72,7 +71,6 @@ const uint32_t kOnBody = 2; const uint32_t kOnMessageComplete = 3; const uint32_t kOnExecute = 4; - // helper class for the Parser struct StringPtr { StringPtr() { @@ -80,11 +78,7 @@ struct StringPtr { Reset(); } - - ~StringPtr() { - Reset(); - } - + ~StringPtr() { Reset(); } // If str_ does not point to a heap string yet, this function makes it do // so. This is called at the end of each http_parser_execute() so as not @@ -98,7 +92,6 @@ struct StringPtr { } } - void Reset() { if (on_heap_) { delete[] str_; @@ -109,7 +102,6 @@ struct StringPtr { size_ = 0; } - void Update(const char* str, size_t size) { if (str_ == nullptr) { str_ = str; @@ -130,7 +122,6 @@ struct StringPtr { size_ += size; } - Local ToString(Environment* env) const { if (str_) return OneByteString(env->isolate(), str_, size_); @@ -138,13 +129,11 @@ struct StringPtr { return String::Empty(env->isolate()); } - const char* str_; bool on_heap_; size_t size_; }; - class Parser : public AsyncWrap, public StreamListener { public: Parser(Environment* env, Local wrap, enum http_parser_type type) @@ -154,7 +143,6 @@ class Parser : public AsyncWrap, public StreamListener { Init(type); } - void MemoryInfo(MemoryTracker* tracker) const override { tracker->TrackThis(this); tracker->TrackField("current_buffer", current_buffer_); @@ -169,19 +157,16 @@ class Parser : public AsyncWrap, public StreamListener { return 0; } - int on_url(const char* at, size_t length) { url_.Update(at, length); return 0; } - int on_status(const char* at, size_t length) { status_message_.Update(at, length); return 0; } - int on_header_field(const char* at, size_t length) { if (num_fields_ == num_values_) { // start of new field name @@ -203,7 +188,6 @@ class Parser : public AsyncWrap, public StreamListener { return 0; } - int on_header_value(const char* at, size_t length) { if (num_values_ != num_fields_) { // start of new header value @@ -219,7 +203,6 @@ class Parser : public AsyncWrap, public StreamListener { return 0; } - int on_headers_complete() { // Arguments for the on-headers-complete javascript callback. This // list needs to be kept in sync with the actual argument list for @@ -241,12 +224,10 @@ class Parser : public AsyncWrap, public StreamListener { Local obj = object(); Local cb = obj->Get(kOnHeadersComplete); - if (!cb->IsFunction()) - return 0; + if (!cb->IsFunction()) return 0; Local undefined = Undefined(env()->isolate()); - for (size_t i = 0; i < arraysize(argv); i++) - argv[i] = undefined; + for (size_t i = 0; i < arraysize(argv); i++) argv[i] = undefined; if (have_flushed_) { // Slow case, flush remaining headers. @@ -254,8 +235,7 @@ class Parser : public AsyncWrap, public StreamListener { } else { // Fast case, pass headers and URL to JS land. argv[A_HEADERS] = CreateHeaders(); - if (parser_.type == HTTP_REQUEST) - argv[A_URL] = url_.ToString(env()); + if (parser_.type == HTTP_REQUEST) argv[A_URL] = url_.ToString(env()); } num_fields_ = 0; @@ -269,8 +249,7 @@ class Parser : public AsyncWrap, public StreamListener { // STATUS if (parser_.type == HTTP_RESPONSE) { - argv[A_STATUS_CODE] = - Integer::New(env()->isolate(), parser_.status_code); + argv[A_STATUS_CODE] = Integer::New(env()->isolate(), parser_.status_code); argv[A_STATUS_MESSAGE] = status_message_.ToString(env()); } @@ -296,34 +275,30 @@ class Parser : public AsyncWrap, public StreamListener { return head_response.ToLocalChecked()->IntegerValue(); } - int on_body(const char* at, size_t length) { EscapableHandleScope scope(env()->isolate()); Local obj = object(); Local cb = obj->Get(kOnBody); - if (!cb->IsFunction()) - return 0; + if (!cb->IsFunction()) return 0; // We came from consumed stream if (current_buffer_.IsEmpty()) { // Make sure Buffer will be in parent HandleScope - current_buffer_ = scope.Escape(Buffer::Copy( - env()->isolate(), - current_buffer_data_, - current_buffer_len_).ToLocalChecked()); + current_buffer_ = scope.Escape(Buffer::Copy(env()->isolate(), + current_buffer_data_, + current_buffer_len_) + .ToLocalChecked()); } Local argv[3] = { - current_buffer_, - Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_), - Integer::NewFromUnsigned(env()->isolate(), length) - }; + current_buffer_, + Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_), + Integer::NewFromUnsigned(env()->isolate(), length)}; - MaybeLocal r = MakeCallback(cb.As(), - arraysize(argv), - argv); + MaybeLocal r = + MakeCallback(cb.As(), arraysize(argv), argv); if (r.IsEmpty()) { got_exception_ = true; @@ -333,18 +308,15 @@ class Parser : public AsyncWrap, public StreamListener { return 0; } - int on_message_complete() { HandleScope scope(env()->isolate()); - if (num_fields_) - Flush(); // Flush trailing HTTP headers. + if (num_fields_) Flush(); // Flush trailing HTTP headers. Local obj = object(); Local cb = obj->Get(kOnMessageComplete); - if (!cb->IsFunction()) - return 0; + if (!cb->IsFunction()) return 0; Environment::AsyncCallbackScope callback_scope(env()); @@ -358,7 +330,6 @@ class Parser : public AsyncWrap, public StreamListener { return 0; } - static void New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); http_parser_type type = @@ -367,7 +338,6 @@ class Parser : public AsyncWrap, public StreamListener { new Parser(env, args.This(), type); } - static void Close(const FunctionCallbackInfo& args) { Parser* parser; ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder()); @@ -375,7 +345,6 @@ class Parser : public AsyncWrap, public StreamListener { delete parser; } - static void Free(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Parser* parser; @@ -387,7 +356,6 @@ class Parser : public AsyncWrap, public StreamListener { parser->EmitDestroy(env, parser->get_async_id()); } - void Save() { url_.Save(); status_message_.Save(); @@ -401,7 +369,6 @@ class Parser : public AsyncWrap, public StreamListener { } } - // var bytesParsed = parser->execute(buffer); static void Execute(const FunctionCallbackInfo& args) { Parser* parser; @@ -422,11 +389,9 @@ class Parser : public AsyncWrap, public StreamListener { Local ret = parser->Execute(buffer_data, buffer_len); - if (!ret.IsEmpty()) - args.GetReturnValue().Set(ret); + if (!ret.IsEmpty()) args.GetReturnValue().Set(ret); } - static void Finish(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -438,8 +403,7 @@ class Parser : public AsyncWrap, public StreamListener { int rv = http_parser_execute(&(parser->parser_), &settings, nullptr, 0); - if (parser->got_exception_) - return; + if (parser->got_exception_) return; if (rv != 0) { enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_); @@ -454,7 +418,6 @@ class Parser : public AsyncWrap, public StreamListener { } } - static void Reinitialize(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -471,7 +434,6 @@ class Parser : public AsyncWrap, public StreamListener { parser->Init(type); } - template static void Pause(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -482,7 +444,6 @@ class Parser : public AsyncWrap, public StreamListener { http_parser_pause(&parser->parser_, should_pause); } - static void Consume(const FunctionCallbackInfo& args) { Parser* parser; ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder()); @@ -493,27 +454,24 @@ class Parser : public AsyncWrap, public StreamListener { stream->PushStreamListener(parser); } - static void Unconsume(const FunctionCallbackInfo& args) { Parser* parser; ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder()); // Already unconsumed - if (parser->stream_ == nullptr) - return; + if (parser->stream_ == nullptr) return; parser->stream_->RemoveStreamListener(parser); } - static void GetCurrentBuffer(const FunctionCallbackInfo& args) { Parser* parser; ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder()); - Local ret = Buffer::Copy( - parser->env(), - parser->current_buffer_data_, - parser->current_buffer_len_).ToLocalChecked(); + Local ret = Buffer::Copy(parser->env(), + parser->current_buffer_data_, + parser->current_buffer_len_) + .ToLocalChecked(); args.GetReturnValue().Set(ret); } @@ -536,7 +494,6 @@ class Parser : public AsyncWrap, public StreamListener { return uv_buf_init(env()->http_parser_buffer(), kAllocBufferSize); } - void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override { HandleScope scope(env()->isolate()); // Once we’re done here, either indicate that the HTTP parser buffer @@ -555,21 +512,18 @@ class Parser : public AsyncWrap, public StreamListener { } // Ignore, empty reads have special meaning in http parser - if (nread == 0) - return; + if (nread == 0) return; current_buffer_.Clear(); Local ret = Execute(buf.base, nread); // Exception - if (ret.IsEmpty()) - return; + if (ret.IsEmpty()) return; Local cb = object()->Get(env()->context(), kOnExecute).ToLocalChecked(); - if (!cb->IsFunction()) - return; + if (!cb->IsFunction()) return; // Hooks for GetCurrentBuffer current_buffer_len_ = nread; @@ -581,7 +535,6 @@ class Parser : public AsyncWrap, public StreamListener { current_buffer_data_ = nullptr; } - Local Execute(char* data, size_t len) { EscapableHandleScope scope(env()->isolate()); @@ -589,8 +542,7 @@ class Parser : public AsyncWrap, public StreamListener { current_buffer_data_ = data; got_exception_ = false; - size_t nparsed = - http_parser_execute(&parser_, &settings, data, len); + size_t nparsed = http_parser_execute(&parser_, &settings, data, len); Save(); @@ -600,8 +552,7 @@ class Parser : public AsyncWrap, public StreamListener { current_buffer_data_ = nullptr; // If there was an exception in one of the callbacks - if (got_exception_) - return scope.Escape(Local()); + if (got_exception_) return scope.Escape(Local()); Local nparsed_obj = Integer::New(env()->isolate(), nparsed); // If there was a parse error in one of the callbacks @@ -642,7 +593,6 @@ class Parser : public AsyncWrap, public StreamListener { return headers; } - // spill headers and request path to JS land void Flush() { HandleScope scope(env()->isolate()); @@ -650,26 +600,19 @@ class Parser : public AsyncWrap, public StreamListener { Local obj = object(); Local cb = obj->Get(kOnHeaders); - if (!cb->IsFunction()) - return; + if (!cb->IsFunction()) return; - Local argv[2] = { - CreateHeaders(), - url_.ToString(env()) - }; + Local argv[2] = {CreateHeaders(), url_.ToString(env())}; - MaybeLocal r = MakeCallback(cb.As(), - arraysize(argv), - argv); + MaybeLocal r = + MakeCallback(cb.As(), arraysize(argv), argv); - if (r.IsEmpty()) - got_exception_ = true; + if (r.IsEmpty()) got_exception_ = true; url_.Reset(); have_flushed_ = true; } - void Init(enum http_parser_type type) { http_parser_init(&parser_, type); url_.Reset(); @@ -680,7 +623,6 @@ class Parser : public AsyncWrap, public StreamListener { got_exception_ = false; } - http_parser parser_; StringPtr fields_[32]; // header fields StringPtr values_[32]; // header values @@ -696,10 +638,11 @@ class Parser : public AsyncWrap, public StreamListener { // These are helper functions for filling `http_parser_settings`, which turn // a member function of Parser into a C-style HTTP parser callback. - template struct Proxy; - template + template + struct Proxy; + template struct Proxy { - static int Raw(http_parser* p, Args ... args) { + static int Raw(http_parser* p, Args... args) { Parser* parser = ContainerOf(&Parser::parser_, p); return (parser->*Member)(std::forward(args)...); } @@ -712,19 +655,18 @@ class Parser : public AsyncWrap, public StreamListener { }; const struct http_parser_settings Parser::settings = { - Proxy::Raw, - Proxy::Raw, - Proxy::Raw, - Proxy::Raw, - Proxy::Raw, - Proxy::Raw, - Proxy::Raw, - Proxy::Raw, - nullptr, // on_chunk_header - nullptr // on_chunk_complete + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + nullptr, // on_chunk_header + nullptr // on_chunk_complete }; - void Initialize(Local target, Local unused, Local context, @@ -750,8 +692,8 @@ void Initialize(Local target, Integer::NewFromUnsigned(env->isolate(), kOnExecute)); Local methods = Array::New(env->isolate()); -#define V(num, name, string) \ - methods->Set(num, FIXED_ONE_BYTE_STRING(env->isolate(), #string)); +#define V(num, name, string) \ + methods->Set(num, FIXED_ONE_BYTE_STRING(env->isolate(), #string)); HTTP_METHOD_MAP(V) #undef V target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "methods"), methods); diff --git a/src/node_i18n.cc b/src/node_i18n.cc index e6c198fb634b48..17539834f130ef 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -39,38 +39,37 @@ * See: http://bugs.icu-project.org/trac/ticket/10924 */ - #include "node_i18n.h" #if defined(NODE_HAVE_I18N_SUPPORT) +#include "base_object-inl.h" +#include "env-inl.h" #include "node.h" #include "node_buffer.h" #include "node_errors.h" -#include "env-inl.h" #include "util-inl.h" -#include "base_object-inl.h" #include "v8.h" -#include #include +#include #include #include +#include #include #include -#include -#include -#include -#include #include +#include +#include +#include +#include #include #include -#include #ifdef NODE_HAVE_SMALL_ICU /* if this is defined, we have a 'secondary' entry point. compare following to utypes.h defs for U_ICUDATA_ENTRY_POINT */ -#define SMALL_ICUDATA_ENTRY_POINT \ +#define SMALL_ICUDATA_ENTRY_POINT \ SMALL_DEF2(U_ICU_VERSION_MAJOR_NUM, U_LIB_SUFFIX_C_NAME) #define SMALL_DEF2(major, suff) SMALL_DEF(major, suff) #ifndef U_LIB_SUFFIX_C_NAME @@ -101,8 +100,7 @@ namespace { template MaybeLocal ToBufferEndian(Environment* env, MaybeStackBuffer* buf) { MaybeLocal ret = Buffer::New(env, buf); - if (ret.IsEmpty()) - return ret; + if (ret.IsEmpty()) return ret; static_assert(sizeof(T) == 1 || sizeof(T) == 2, "Currently only one- or two-byte buffers are supported"); @@ -125,8 +123,8 @@ struct Converter { } } - explicit Converter(UConverter* converter, - const char* sub = nullptr) : conv(converter) { + explicit Converter(UConverter* converter, const char* sub = nullptr) + : conv(converter) { CHECK_NOT_NULL(conv); UErrorCode status = U_ZERO_ERROR; if (sub != nullptr) { @@ -134,9 +132,7 @@ struct Converter { } } - ~Converter() { - ucnv_close(conv); - } + ~Converter() { ucnv_close(conv); } UConverter* conv; }; @@ -144,8 +140,8 @@ struct Converter { class ConverterObject : public BaseObject, Converter { public: enum ConverterFlags { - CONVERTER_FLAGS_FLUSH = 0x1, - CONVERTER_FLAGS_FATAL = 0x2, + CONVERTER_FLAGS_FLUSH = 0x1, + CONVERTER_FLAGS_FATAL = 0x2, CONVERTER_FLAGS_IGNORE_BOM = 0x4 }; @@ -171,20 +167,18 @@ class ConverterObject : public BaseObject, Converter { CHECK_GE(args.Length(), 2); Utf8Value label(env->isolate(), args[0]); int flags = args[1]->Uint32Value(env->context()).ToChecked(); - bool fatal = - (flags & CONVERTER_FLAGS_FATAL) == CONVERTER_FLAGS_FATAL; + bool fatal = (flags & CONVERTER_FLAGS_FATAL) == CONVERTER_FLAGS_FATAL; bool ignoreBOM = (flags & CONVERTER_FLAGS_IGNORE_BOM) == CONVERTER_FLAGS_IGNORE_BOM; UErrorCode status = U_ZERO_ERROR; UConverter* conv = ucnv_open(*label, &status); - if (U_FAILURE(status)) - return; + if (U_FAILURE(status)) return; if (fatal) { status = U_ZERO_ERROR; - ucnv_setToUCallBack(conv, UCNV_TO_U_CALLBACK_STOP, - nullptr, nullptr, nullptr, &status); + ucnv_setToUCallBack( + conv, UCNV_TO_U_CALLBACK_STOP, nullptr, nullptr, nullptr, &status); } Local t = ObjectTemplate::New(env->isolate()); @@ -208,10 +202,8 @@ class ConverterObject : public BaseObject, Converter { UErrorCode status = U_ZERO_ERROR; MaybeStackBuffer result; MaybeLocal ret; - size_t limit = ucnv_getMinCharSize(converter->conv) * - input_obj_length; - if (limit > 0) - result.AllocateSufficientStorage(limit); + size_t limit = ucnv_getMinCharSize(converter->conv) * input_obj_length; + if (limit > 0) result.AllocateSufficientStorage(limit); UBool flush = (flags & CONVERTER_FLAGS_FLUSH) == CONVERTER_FLAGS_FLUSH; @@ -228,13 +220,16 @@ class ConverterObject : public BaseObject, Converter { UChar* target = *result; ucnv_toUnicode(converter->conv, - &target, target + (limit * sizeof(UChar)), - &source, source + source_length, - nullptr, flush, &status); + &target, + target + (limit * sizeof(UChar)), + &source, + source + source_length, + nullptr, + flush, + &status); if (U_SUCCESS(status)) { - if (limit > 0) - result.SetLength(target - &result[0]); + if (limit > 0) result.SetLength(target - &result[0]); ret = ToBufferEndian(env, &result); args.GetReturnValue().Set(ret.ToLocalChecked()); goto reset; @@ -242,7 +237,7 @@ class ConverterObject : public BaseObject, Converter { args.GetReturnValue().Set(status); - reset: + reset: if (flush) { // Reset the converter state converter->bomSeen_ = false; @@ -261,10 +256,10 @@ class ConverterObject : public BaseObject, Converter { v8::Local wrap, UConverter* converter, bool ignoreBOM, - const char* sub = nullptr) : - BaseObject(env, wrap), - Converter(converter, sub), - ignoreBOM_(ignoreBOM) { + const char* sub = nullptr) + : BaseObject(env, wrap), + Converter(converter, sub), + ignoreBOM_(ignoreBOM) { MakeWeak(); switch (ucnv_getType(converter)) { @@ -279,9 +274,9 @@ class ConverterObject : public BaseObject, Converter { } private: - bool unicode_ = false; // True if this is a Unicode converter - bool ignoreBOM_ = false; // True if the BOM should be ignored on Unicode - bool bomSeen_ = false; // True if the BOM has been seen + bool unicode_ = false; // True if this is a Unicode converter + bool ignoreBOM_ = false; // True if the BOM should be ignored on Unicode + bool bomSeen_ = false; // True if the BOM has been seen }; // One-Shot Converters @@ -319,9 +314,19 @@ MaybeLocal Transcode(Environment* env, const uint32_t limit = source_length * ucnv_getMaxCharSize(to.conv); result.AllocateSufficientStorage(limit); char* target = *result; - ucnv_convertEx(to.conv, from.conv, &target, target + limit, - &source, source + source_length, nullptr, nullptr, - nullptr, nullptr, true, true, status); + ucnv_convertEx(to.conv, + from.conv, + &target, + target + limit, + &source, + source + source_length, + nullptr, + nullptr, + nullptr, + nullptr, + true, + true, + status); if (U_SUCCESS(*status)) { result.SetLength(target - &result[0]); ret = ToBufferEndian(env, &result); @@ -340,10 +345,9 @@ MaybeLocal TranscodeToUcs2(Environment* env, MaybeStackBuffer destbuf(source_length); Converter from(fromEncoding); const size_t length_in_chars = source_length * sizeof(UChar); - ucnv_toUChars(from.conv, *destbuf, length_in_chars, - source, source_length, status); - if (U_SUCCESS(*status)) - ret = ToBufferEndian(env, &destbuf); + ucnv_toUChars( + from.conv, *destbuf, length_in_chars, source, source_length, status); + if (U_SUCCESS(*status)) ret = ToBufferEndian(env, &destbuf); return ret; } @@ -360,8 +364,8 @@ MaybeLocal TranscodeFromUcs2(Environment* env, const size_t length_in_chars = source_length / sizeof(UChar); CopySourceBuffer(&sourcebuf, source, source_length, length_in_chars); MaybeStackBuffer destbuf(length_in_chars); - const uint32_t len = ucnv_fromUChars(to.conv, *destbuf, length_in_chars, - *sourcebuf, length_in_chars, status); + const uint32_t len = ucnv_fromUChars( + to.conv, *destbuf, length_in_chars, *sourcebuf, length_in_chars, status); if (U_SUCCESS(*status)) { destbuf.SetLength(len); ret = ToBufferEndian(env, &destbuf); @@ -378,8 +382,12 @@ MaybeLocal TranscodeUcs2FromUtf8(Environment* env, *status = U_ZERO_ERROR; MaybeStackBuffer destbuf; int32_t result_length; - u_strFromUTF8(*destbuf, destbuf.capacity(), &result_length, - source, source_length, status); + u_strFromUTF8(*destbuf, + destbuf.capacity(), + &result_length, + source, + source_length, + status); MaybeLocal ret; if (U_SUCCESS(*status)) { destbuf.SetLength(result_length); @@ -387,8 +395,8 @@ MaybeLocal TranscodeUcs2FromUtf8(Environment* env, } else if (*status == U_BUFFER_OVERFLOW_ERROR) { *status = U_ZERO_ERROR; destbuf.AllocateSufficientStorage(result_length); - u_strFromUTF8(*destbuf, result_length, &result_length, - source, source_length, status); + u_strFromUTF8( + *destbuf, result_length, &result_length, source, source_length, status); if (U_SUCCESS(*status)) { destbuf.SetLength(result_length); ret = ToBufferEndian(env, &destbuf); @@ -410,16 +418,24 @@ MaybeLocal TranscodeUtf8FromUcs2(Environment* env, MaybeStackBuffer sourcebuf; MaybeStackBuffer destbuf; CopySourceBuffer(&sourcebuf, source, source_length, length_in_chars); - u_strToUTF8(*destbuf, destbuf.capacity(), &result_length, - *sourcebuf, length_in_chars, status); + u_strToUTF8(*destbuf, + destbuf.capacity(), + &result_length, + *sourcebuf, + length_in_chars, + status); if (U_SUCCESS(*status)) { destbuf.SetLength(result_length); ret = ToBufferEndian(env, &destbuf); } else if (*status == U_BUFFER_OVERFLOW_ERROR) { *status = U_ZERO_ERROR; destbuf.AllocateSufficientStorage(result_length); - u_strToUTF8(*destbuf, result_length, &result_length, *sourcebuf, - length_in_chars, status); + u_strToUTF8(*destbuf, + result_length, + &result_length, + *sourcebuf, + length_in_chars, + status); if (U_SUCCESS(*status)) { destbuf.SetLength(result_length); ret = ToBufferEndian(env, &destbuf); @@ -430,11 +446,16 @@ MaybeLocal TranscodeUtf8FromUcs2(Environment* env, const char* EncodingName(const enum encoding encoding) { switch (encoding) { - case ASCII: return "us-ascii"; - case LATIN1: return "iso8859-1"; - case UCS2: return "utf16le"; - case UTF8: return "utf-8"; - default: return nullptr; + case ASCII: + return "us-ascii"; + case LATIN1: + return "iso8859-1"; + case UCS2: + return "utf16le"; + case UTF8: + return "utf-8"; + default: + return nullptr; } } @@ -443,12 +464,14 @@ bool SupportedEncoding(const enum encoding encoding) { case ASCII: case LATIN1: case UCS2: - case UTF8: return true; - default: return false; + case UTF8: + return true; + default: + return false; } } -void Transcode(const FunctionCallbackInfo&args) { +void Transcode(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); UErrorCode status = U_ZERO_ERROR; @@ -464,12 +487,10 @@ void Transcode(const FunctionCallbackInfo&args) { switch (fromEncoding) { case ASCII: case LATIN1: - if (toEncoding == UCS2) - tfn = &TranscodeToUcs2; + if (toEncoding == UCS2) tfn = &TranscodeToUcs2; break; case UTF8: - if (toEncoding == UCS2) - tfn = &TranscodeUcs2FromUtf8; + if (toEncoding == UCS2) tfn = &TranscodeUcs2FromUtf8; break; case UCS2: switch (toEncoding) { @@ -488,14 +509,17 @@ void Transcode(const FunctionCallbackInfo&args) { ABORT(); } - result = tfn(env, EncodingName(fromEncoding), EncodingName(toEncoding), - ts_obj_data, ts_obj_length, &status); + result = tfn(env, + EncodingName(fromEncoding), + EncodingName(toEncoding), + ts_obj_data, + ts_obj_length, + &status); } else { status = U_ILLEGAL_ARGUMENT_ERROR; } - if (result.IsEmpty()) - return args.GetReturnValue().Set(status); + if (result.IsEmpty()) return args.GetReturnValue().Set(status); return args.GetReturnValue().Set(result.ToLocalChecked()); } @@ -503,10 +527,10 @@ void Transcode(const FunctionCallbackInfo&args) { void ICUErrorName(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); UErrorCode status = static_cast(args[0]->Int32Value()); - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - u_errorName(status), - v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), + u_errorName(status), + v8::NewStringType::kNormal) + .ToLocalChecked()); } #define TYPE_ICU "icu" @@ -545,14 +569,13 @@ const char* GetVersion(const char* type, void GetVersion(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - if ( args.Length() == 0 ) { + if (args.Length() == 0) { // With no args - return a comma-separated list of allowed values - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - TYPE_ICU "," - TYPE_UNICODE "," - TYPE_CLDR "," - TYPE_TZ, v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set( + String::NewFromUtf8(env->isolate(), + TYPE_ICU "," TYPE_UNICODE "," TYPE_CLDR "," TYPE_TZ, + v8::NewStringType::kNormal) + .ToLocalChecked()); } else { CHECK_GE(args.Length(), 1); CHECK(args[0]->IsString()); @@ -563,9 +586,10 @@ void GetVersion(const FunctionCallbackInfo& args) { if (U_SUCCESS(status) && versionString) { // Success. - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - versionString, v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), + versionString, + v8::NewStringType::kNormal) + .ToLocalChecked()); } } } @@ -578,7 +602,7 @@ bool InitializeICUDirectory(const std::string& path) { #ifdef NODE_HAVE_SMALL_ICU // install the 'small' data. udata_setCommonData(&SMALL_ICUDATA_ENTRY_POINT, &status); -#else // !NODE_HAVE_SMALL_ICU +#else // !NODE_HAVE_SMALL_ICU // no small data, so nothing to do. #endif // !NODE_HAVE_SMALL_ICU } else { @@ -594,15 +618,11 @@ int32_t ToUnicode(MaybeStackBuffer* buf, UErrorCode status = U_ZERO_ERROR; uint32_t options = UIDNA_NONTRANSITIONAL_TO_UNICODE; UIDNA* uidna = uidna_openUTS46(options, &status); - if (U_FAILURE(status)) - return -1; + if (U_FAILURE(status)) return -1; UIDNAInfo info = UIDNA_INFO_INITIALIZER; - int32_t len = uidna_nameToUnicodeUTF8(uidna, - input, length, - **buf, buf->capacity(), - &info, - &status); + int32_t len = uidna_nameToUnicodeUTF8( + uidna, input, length, **buf, buf->capacity(), &info, &status); // Do not check info.errors like we do with ToASCII since ToUnicode always // returns a string, despite any possible errors that may have occurred. @@ -610,11 +630,8 @@ int32_t ToUnicode(MaybeStackBuffer* buf, if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; buf->AllocateSufficientStorage(len); - len = uidna_nameToUnicodeUTF8(uidna, - input, length, - **buf, buf->capacity(), - &info, - &status); + len = uidna_nameToUnicodeUTF8( + uidna, input, length, **buf, buf->capacity(), &info, &status); } // info.errors is ignored as UTS #46 ToUnicode always produces a Unicode @@ -636,10 +653,10 @@ int32_t ToASCII(MaybeStackBuffer* buf, size_t length, enum idna_mode mode) { UErrorCode status = U_ZERO_ERROR; - uint32_t options = // CheckHyphens = false; handled later - UIDNA_CHECK_BIDI | // CheckBidi = true - UIDNA_CHECK_CONTEXTJ | // CheckJoiners = true - UIDNA_NONTRANSITIONAL_TO_ASCII; // Nontransitional_Processing + uint32_t options = // CheckHyphens = false; handled later + UIDNA_CHECK_BIDI | // CheckBidi = true + UIDNA_CHECK_CONTEXTJ | // CheckJoiners = true + UIDNA_NONTRANSITIONAL_TO_ASCII; // Nontransitional_Processing if (mode == IDNA_STRICT) { options |= UIDNA_USE_STD3_RULES; // UseSTD3ASCIIRules = beStrict // VerifyDnsLength = beStrict; @@ -647,24 +664,17 @@ int32_t ToASCII(MaybeStackBuffer* buf, } UIDNA* uidna = uidna_openUTS46(options, &status); - if (U_FAILURE(status)) - return -1; + if (U_FAILURE(status)) return -1; UIDNAInfo info = UIDNA_INFO_INITIALIZER; - int32_t len = uidna_nameToASCII_UTF8(uidna, - input, length, - **buf, buf->capacity(), - &info, - &status); + int32_t len = uidna_nameToASCII_UTF8( + uidna, input, length, **buf, buf->capacity(), &info, &status); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; buf->AllocateSufficientStorage(len); - len = uidna_nameToASCII_UTF8(uidna, - input, length, - **buf, buf->capacity(), - &info, - &status); + len = uidna_nameToASCII_UTF8( + uidna, input, length, **buf, buf->capacity(), &info, &status); } // In UTS #46 which specifies ToASCII, certain error conditions are @@ -720,10 +730,8 @@ static void ToUnicode(const FunctionCallbackInfo& args) { } args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - *buf, - v8::NewStringType::kNormal, - len).ToLocalChecked()); + String::NewFromUtf8(env->isolate(), *buf, v8::NewStringType::kNormal, len) + .ToLocalChecked()); } static void ToASCII(const FunctionCallbackInfo& args) { @@ -743,10 +751,8 @@ static void ToASCII(const FunctionCallbackInfo& args) { } args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - *buf, - v8::NewStringType::kNormal, - len).ToLocalChecked()); + String::NewFromUtf8(env->isolate(), *buf, v8::NewStringType::kNormal, len) + .ToLocalChecked()); } // This is similar to wcwidth except that it takes the current unicode @@ -767,9 +773,11 @@ static void ToASCII(const FunctionCallbackInfo& args) { // are technically Wide. But many terminals (including Konsole and // VTE/GLib-based) implement all medials and finals as 0-width. // -// Refs: https://eev.ee/blog/2015/09/12/dark-corners-of-unicode/#combining-characters-and-character-width +// Refs: +// https://eev.ee/blog/2015/09/12/dark-corners-of-unicode/#combining-characters-and-character-width // Refs: https://github.com/GNOME/glib/blob/79e4d4c6be/glib/guniprop.c#L388-L420 -// Refs: https://github.com/KDE/konsole/blob/8c6a5d13c0/src/konsole_wcwidth.cpp#L101-L223 +// Refs: +// https://github.com/KDE/konsole/blob/8c6a5d13c0/src/konsole_wcwidth.cpp#L101-L223 static int GetColumnWidth(UChar32 codepoint, bool ambiguous_as_full_width = false) { const auto zero_width_mask = U_GC_CC_MASK | // C0/C1 control code @@ -812,16 +820,14 @@ static int GetColumnWidth(UChar32 codepoint, // Returns the column width for the given String. static void GetStringWidth(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - if (args.Length() < 1) - return; + if (args.Length() < 1) return; bool ambiguous_as_full_width = args[1]->BooleanValue(); bool expand_emoji_sequence = args[2]->BooleanValue(); if (args[0]->IsNumber()) { args.GetReturnValue().Set( - GetColumnWidth(args[0]->Uint32Value(), - ambiguous_as_full_width)); + GetColumnWidth(args[0]->Uint32Value(), ambiguous_as_full_width)); return; } @@ -848,8 +854,8 @@ static void GetStringWidth(const FunctionCallbackInfo& args) { // in advance if a particular sequence is going to be supported. // The expand_emoji_sequence option allows the caller to skip this // check and count each code within an emoji sequence separately. - if (!expand_emoji_sequence && - n > 0 && p == 0x200d && // 0x200d == ZWJ (zero width joiner) + if (!expand_emoji_sequence && n > 0 && + p == 0x200d && // 0x200d == ZWJ (zero width joiner) (u_hasBinaryProperty(c, UCHAR_EMOJI_PRESENTATION) || u_hasBinaryProperty(c, UCHAR_EMOJI_MODIFIER))) { continue; diff --git a/src/node_i18n.h b/src/node_i18n.h index 70a0c79f76cf30..21e26262cb0b7a 100644 --- a/src/node_i18n.h +++ b/src/node_i18n.h @@ -24,8 +24,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_internals.h" #include +#include "node_internals.h" #if defined(NODE_HAVE_I18N_SUPPORT) diff --git a/src/node_internals.h b/src/node_internals.h index a27e5f3567b673..2f1db384dae582 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -24,17 +24,17 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "env-inl.h" #include "node.h" +#include "node_api.h" +#include "node_debug_options.h" #include "node_mutex.h" +#include "node_perf_common.h" #include "node_persistent.h" +#include "tracing/trace_event.h" #include "util-inl.h" -#include "env-inl.h" #include "uv.h" #include "v8.h" -#include "tracing/trace_event.h" -#include "node_perf_common.h" -#include "node_debug_options.h" -#include "node_api.h" #include #include @@ -60,32 +60,33 @@ #define Z_DEFAULT_LEVEL Z_DEFAULT_COMPRESSION enum { - NM_F_BUILTIN = 1 << 0, - NM_F_LINKED = 1 << 1, + NM_F_BUILTIN = 1 << 0, + NM_F_LINKED = 1 << 1, NM_F_INTERNAL = 1 << 2, }; struct sockaddr; // Variation on NODE_DEFINE_CONSTANT that sets a String value. -#define NODE_DEFINE_STRING_CONSTANT(target, name, constant) \ - do { \ - v8::Isolate* isolate = target->GetIsolate(); \ - v8::Local constant_name = \ - v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kNormal) \ - .ToLocalChecked(); \ - v8::Local constant_value = \ - v8::String::NewFromUtf8(isolate, constant, v8::NewStringType::kNormal)\ - .ToLocalChecked(); \ - v8::PropertyAttribute constant_attributes = \ - static_cast(v8::ReadOnly | v8::DontDelete); \ - target->DefineOwnProperty(isolate->GetCurrentContext(), \ - constant_name, \ - constant_value, \ - constant_attributes).FromJust(); \ +#define NODE_DEFINE_STRING_CONSTANT(target, name, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kNormal) \ + .ToLocalChecked(); \ + v8::Local constant_value = \ + v8::String::NewFromUtf8(isolate, constant, v8::NewStringType::kNormal) \ + .ToLocalChecked(); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | v8::DontDelete); \ + target \ + ->DefineOwnProperty(isolate->GetCurrentContext(), \ + constant_name, \ + constant_value, \ + constant_attributes) \ + .FromJust(); \ } while (0) - #if HAVE_OPENSSL #define NODE_BUILTIN_OPENSSL_MODULES(V) V(crypto) V(tls_wrap) #else @@ -104,69 +105,65 @@ struct sockaddr; // function. This helps the built-in modules are loaded properly when // node is built as static library. No need to depends on the // __attribute__((constructor)) like mechanism in GCC. -#define NODE_BUILTIN_STANDARD_MODULES(V) \ - V(async_wrap) \ - V(buffer) \ - V(cares_wrap) \ - V(config) \ - V(contextify) \ - V(domain) \ - V(fs) \ - V(fs_event_wrap) \ - V(heap_utils) \ - V(http2) \ - V(http_parser) \ - V(inspector) \ - V(js_stream) \ - V(messaging) \ - V(module_wrap) \ - V(os) \ - V(performance) \ - V(pipe_wrap) \ - V(process_wrap) \ - V(serdes) \ - V(signal_wrap) \ - V(spawn_sync) \ - V(stream_pipe) \ - V(stream_wrap) \ - V(string_decoder) \ - V(symbols) \ - V(tcp_wrap) \ - V(timers) \ - V(trace_events) \ - V(tty_wrap) \ - V(types) \ - V(udp_wrap) \ - V(url) \ - V(util) \ - V(uv) \ - V(v8) \ - V(worker) \ - V(zlib) - -#define NODE_BUILTIN_MODULES(V) \ - NODE_BUILTIN_STANDARD_MODULES(V) \ - NODE_BUILTIN_OPENSSL_MODULES(V) \ +#define NODE_BUILTIN_STANDARD_MODULES(V) \ + V(async_wrap) \ + V(buffer) \ + V(cares_wrap) \ + V(config) \ + V(contextify) \ + V(domain) \ + V(fs) \ + V(fs_event_wrap) \ + V(heap_utils) \ + V(http2) \ + V(http_parser) \ + V(inspector) \ + V(js_stream) \ + V(messaging) \ + V(module_wrap) \ + V(os) \ + V(performance) \ + V(pipe_wrap) \ + V(process_wrap) \ + V(serdes) \ + V(signal_wrap) \ + V(spawn_sync) \ + V(stream_pipe) \ + V(stream_wrap) \ + V(string_decoder) \ + V(symbols) \ + V(tcp_wrap) \ + V(timers) \ + V(trace_events) \ + V(tty_wrap) \ + V(types) \ + V(udp_wrap) \ + V(url) \ + V(util) \ + V(uv) \ + V(v8) \ + V(worker) \ + V(zlib) + +#define NODE_BUILTIN_MODULES(V) \ + NODE_BUILTIN_STANDARD_MODULES(V) \ + NODE_BUILTIN_OPENSSL_MODULES(V) \ NODE_BUILTIN_ICU_MODULES(V) -#define NODE_MODULE_CONTEXT_AWARE_CPP(modname, regfunc, priv, flags) \ - static node::node_module _module = { \ - NODE_MODULE_VERSION, \ - flags, \ - nullptr, \ - __FILE__, \ - nullptr, \ - (node::addon_context_register_func) (regfunc), \ - NODE_STRINGIFY(modname), \ - priv, \ - nullptr \ - }; \ - void _register_ ## modname() { \ - node_module_register(&_module); \ - } - - -#define NODE_BUILTIN_MODULE_CONTEXT_AWARE(modname, regfunc) \ +#define NODE_MODULE_CONTEXT_AWARE_CPP(modname, regfunc, priv, flags) \ + static node::node_module _module = { \ + NODE_MODULE_VERSION, \ + flags, \ + nullptr, \ + __FILE__, \ + nullptr, \ + (node::addon_context_register_func)(regfunc), \ + NODE_STRINGIFY(modname), \ + priv, \ + nullptr}; \ + void _register_##modname() { node_module_register(&_module); } + +#define NODE_BUILTIN_MODULE_CONTEXT_AWARE(modname, regfunc) \ NODE_MODULE_CONTEXT_AWARE_CPP(modname, regfunc, nullptr, NM_F_BUILTIN) namespace node { @@ -241,8 +238,7 @@ class Environment; // reference to the object. template inline v8::Local PersistentToLocal( - v8::Isolate* isolate, - const Persistent& persistent); + v8::Isolate* isolate, const Persistent& persistent); // Convert a struct sockaddr to a { address: '1.2.3.4', port: 1234 } JS object. // Sets address and port properties on the info object and returns it. @@ -255,16 +251,14 @@ v8::Local AddressToJS( template void GetSockOrPeerName(const v8::FunctionCallbackInfo& args) { T* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK(args[0]->IsObject()); sockaddr_storage storage; int addrlen = sizeof(storage); sockaddr* const addr = reinterpret_cast(&storage); const int err = F(&wrap->handle_, addr, &addrlen); - if (err == 0) - AddressToJS(wrap->env(), addr, args[0].As()); + if (err == 0) AddressToJS(wrap->env(), addr, args[0].As()); args.GetReturnValue().Set(err); } @@ -272,7 +266,6 @@ void FatalException(v8::Isolate* isolate, v8::Local error, v8::Local message); - void SignalExit(int signo); #ifdef __POSIX__ void RegisterSignalHandler(int signal, @@ -286,16 +279,18 @@ std::string GetHumanReadableProcessName(); void GetHumanReadableProcessName(char (*name)[1024]); template -constexpr size_t arraysize(const T(&)[N]) { return N; } +constexpr size_t arraysize(const T (&)[N]) { + return N; +} #ifndef ROUND_UP -# define ROUND_UP(a, b) ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a)) +#define ROUND_UP(a, b) ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a)) #endif #ifdef __GNUC__ -# define MUST_USE_RESULT __attribute__((warn_unused_result)) +#define MUST_USE_RESULT __attribute__((warn_unused_result)) #else -# define MUST_USE_RESULT +#define MUST_USE_RESULT #endif bool IsExceptionDecorated(Environment* env, v8::Local er); @@ -322,8 +317,7 @@ class FatalTryCatch : public v8::TryCatch { class SlicedArguments { public: inline explicit SlicedArguments( - const v8::FunctionCallbackInfo& args, - size_t start = 0); + const v8::FunctionCallbackInfo& args, size_t start = 0); inline size_t size() const { return size_; } inline v8::Local* data() { return data_; } @@ -335,8 +329,8 @@ class SlicedArguments { }; SlicedArguments::SlicedArguments( - const v8::FunctionCallbackInfo& args, - size_t start) : size_(0), data_(fixed_) { + const v8::FunctionCallbackInfo& args, size_t start) + : size_(0), data_(fixed_) { const size_t length = static_cast(args.Length()); if (start >= length) return; const size_t size = length - start; @@ -346,8 +340,7 @@ SlicedArguments::SlicedArguments( data_ = dynamic_.data(); } - for (size_t i = 0; i < size; ++i) - data_[i] = args[i + start]; + for (size_t i = 0; i < size; ++i) data_[i] = args[i + start]; size_ = size; } @@ -363,7 +356,8 @@ v8::Maybe ProcessEmitDeprecationWarning(Environment* env, template v8::Local FillStatsArray(AliasedBuffer* fields_ptr, - const uv_stat_t* s, int offset = 0) { + const uv_stat_t* s, + int offset = 0) { AliasedBuffer& fields = *fields_ptr; fields[offset + 0] = s->st_dev; fields[offset + 1] = s->st_mode; @@ -385,11 +379,11 @@ v8::Local FillStatsArray(AliasedBuffer* fields_ptr, #endif // Dates. // NO-LINT because the fields are 'long' and we just want to cast to `unsigned` -#define X(idx, name) \ - /* NOLINTNEXTLINE(runtime/int) */ \ - fields[offset + idx] = ((unsigned long)(s->st_##name.tv_sec) * 1e3) + \ - /* NOLINTNEXTLINE(runtime/int) */ \ - ((unsigned long)(s->st_##name.tv_nsec) / 1e6); \ +#define X(idx, name) \ + /* NOLINTNEXTLINE(runtime/int) */ \ + fields[offset + idx] = ((unsigned long)(s->st_##name.tv_sec) * \ + 1e3) + /* NOLINTNEXTLINE(runtime/int) */ \ + ((unsigned long)(s->st_##name.tv_nsec) / 1e6); X(10, atim) X(11, mtim) @@ -405,15 +399,13 @@ inline v8::Local FillGlobalStatsArray(Environment* env, bool use_bigint = false, int offset = 0) { if (use_bigint) { - return node::FillStatsArray( - env->fs_stats_field_bigint_array(), s, offset); + return node::FillStatsArray(env->fs_stats_field_bigint_array(), s, offset); } else { return node::FillStatsArray(env->fs_stats_field_array(), s, offset); } } -void SetupBootstrapObject(Environment* env, - v8::Local bootstrapper); +void SetupBootstrapObject(Environment* env, v8::Local bootstrapper); void SetupProcessObject(Environment* env, int argc, const char* const* argv, @@ -436,9 +428,7 @@ inline enum Endianness GetEndianness() { const union { uint8_t u8[2]; uint16_t u16; - } u = { - { 1, 0 } - }; + } u = {{1, 0}}; return u.u16 == 1 ? kLittleEndian : kBigEndian; } @@ -455,8 +445,9 @@ class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { inline uint32_t* zero_fill_field() { return &zero_fill_field_; } virtual void* Allocate(size_t size); // Defined in src/node.cc - virtual void* AllocateUninitialized(size_t size) - { return node::UncheckedMalloc(size); } + virtual void* AllocateUninitialized(size_t size) { + return node::UncheckedMalloc(size); + } virtual void Free(void* data, size_t) { free(data); } private: @@ -477,16 +468,14 @@ v8::MaybeLocal New(Environment* env, // Mixing operator new and free() is undefined behavior so don't do that. v8::MaybeLocal New(Environment* env, char* data, size_t length); -inline -v8::MaybeLocal New(Environment* env, - v8::Local ab, - size_t byte_offset, - size_t length) { +inline v8::MaybeLocal New(Environment* env, + v8::Local ab, + size_t byte_offset, + size_t length) { v8::Local ui = v8::Uint8Array::New(ab, byte_offset, length); v8::Maybe mb = ui->SetPrototype(env->context(), env->buffer_prototype_object()); - if (mb.IsNothing()) - return v8::MaybeLocal(); + if (mb.IsNothing()) return v8::MaybeLocal(); return ui; } @@ -510,11 +499,9 @@ static v8::MaybeLocal New(Environment* env, else if (!buf->IsInvalidated()) ret = Copy(env, src, len_in_bytes); - if (ret.IsEmpty()) - return ret; + if (ret.IsEmpty()) return ret; - if (buf->IsAllocated()) - buf->Release(); + if (buf->IsAllocated()) buf->Release(); return ret; } @@ -595,342 +582,342 @@ int ThreadPoolWork::CancelWork() { } static inline const char* errno_string(int errorno) { -#define ERRNO_CASE(e) case e: return #e; +#define ERRNO_CASE(e) \ + case e: \ + return #e; switch (errorno) { #ifdef EACCES - ERRNO_CASE(EACCES); + ERRNO_CASE(EACCES); #endif #ifdef EADDRINUSE - ERRNO_CASE(EADDRINUSE); + ERRNO_CASE(EADDRINUSE); #endif #ifdef EADDRNOTAVAIL - ERRNO_CASE(EADDRNOTAVAIL); + ERRNO_CASE(EADDRNOTAVAIL); #endif #ifdef EAFNOSUPPORT - ERRNO_CASE(EAFNOSUPPORT); + ERRNO_CASE(EAFNOSUPPORT); #endif #ifdef EAGAIN - ERRNO_CASE(EAGAIN); + ERRNO_CASE(EAGAIN); #endif #ifdef EWOULDBLOCK -# if EAGAIN != EWOULDBLOCK - ERRNO_CASE(EWOULDBLOCK); -# endif +#if EAGAIN != EWOULDBLOCK + ERRNO_CASE(EWOULDBLOCK); +#endif #endif #ifdef EALREADY - ERRNO_CASE(EALREADY); + ERRNO_CASE(EALREADY); #endif #ifdef EBADF - ERRNO_CASE(EBADF); + ERRNO_CASE(EBADF); #endif #ifdef EBADMSG - ERRNO_CASE(EBADMSG); + ERRNO_CASE(EBADMSG); #endif #ifdef EBUSY - ERRNO_CASE(EBUSY); + ERRNO_CASE(EBUSY); #endif #ifdef ECANCELED - ERRNO_CASE(ECANCELED); + ERRNO_CASE(ECANCELED); #endif #ifdef ECHILD - ERRNO_CASE(ECHILD); + ERRNO_CASE(ECHILD); #endif #ifdef ECONNABORTED - ERRNO_CASE(ECONNABORTED); + ERRNO_CASE(ECONNABORTED); #endif #ifdef ECONNREFUSED - ERRNO_CASE(ECONNREFUSED); + ERRNO_CASE(ECONNREFUSED); #endif #ifdef ECONNRESET - ERRNO_CASE(ECONNRESET); + ERRNO_CASE(ECONNRESET); #endif #ifdef EDEADLK - ERRNO_CASE(EDEADLK); + ERRNO_CASE(EDEADLK); #endif #ifdef EDESTADDRREQ - ERRNO_CASE(EDESTADDRREQ); + ERRNO_CASE(EDESTADDRREQ); #endif #ifdef EDOM - ERRNO_CASE(EDOM); + ERRNO_CASE(EDOM); #endif #ifdef EDQUOT - ERRNO_CASE(EDQUOT); + ERRNO_CASE(EDQUOT); #endif #ifdef EEXIST - ERRNO_CASE(EEXIST); + ERRNO_CASE(EEXIST); #endif #ifdef EFAULT - ERRNO_CASE(EFAULT); + ERRNO_CASE(EFAULT); #endif #ifdef EFBIG - ERRNO_CASE(EFBIG); + ERRNO_CASE(EFBIG); #endif #ifdef EHOSTUNREACH - ERRNO_CASE(EHOSTUNREACH); + ERRNO_CASE(EHOSTUNREACH); #endif #ifdef EIDRM - ERRNO_CASE(EIDRM); + ERRNO_CASE(EIDRM); #endif #ifdef EILSEQ - ERRNO_CASE(EILSEQ); + ERRNO_CASE(EILSEQ); #endif #ifdef EINPROGRESS - ERRNO_CASE(EINPROGRESS); + ERRNO_CASE(EINPROGRESS); #endif #ifdef EINTR - ERRNO_CASE(EINTR); + ERRNO_CASE(EINTR); #endif #ifdef EINVAL - ERRNO_CASE(EINVAL); + ERRNO_CASE(EINVAL); #endif #ifdef EIO - ERRNO_CASE(EIO); + ERRNO_CASE(EIO); #endif #ifdef EISCONN - ERRNO_CASE(EISCONN); + ERRNO_CASE(EISCONN); #endif #ifdef EISDIR - ERRNO_CASE(EISDIR); + ERRNO_CASE(EISDIR); #endif #ifdef ELOOP - ERRNO_CASE(ELOOP); + ERRNO_CASE(ELOOP); #endif #ifdef EMFILE - ERRNO_CASE(EMFILE); + ERRNO_CASE(EMFILE); #endif #ifdef EMLINK - ERRNO_CASE(EMLINK); + ERRNO_CASE(EMLINK); #endif #ifdef EMSGSIZE - ERRNO_CASE(EMSGSIZE); + ERRNO_CASE(EMSGSIZE); #endif #ifdef EMULTIHOP - ERRNO_CASE(EMULTIHOP); + ERRNO_CASE(EMULTIHOP); #endif #ifdef ENAMETOOLONG - ERRNO_CASE(ENAMETOOLONG); + ERRNO_CASE(ENAMETOOLONG); #endif #ifdef ENETDOWN - ERRNO_CASE(ENETDOWN); + ERRNO_CASE(ENETDOWN); #endif #ifdef ENETRESET - ERRNO_CASE(ENETRESET); + ERRNO_CASE(ENETRESET); #endif #ifdef ENETUNREACH - ERRNO_CASE(ENETUNREACH); + ERRNO_CASE(ENETUNREACH); #endif #ifdef ENFILE - ERRNO_CASE(ENFILE); + ERRNO_CASE(ENFILE); #endif #ifdef ENOBUFS - ERRNO_CASE(ENOBUFS); + ERRNO_CASE(ENOBUFS); #endif #ifdef ENODATA - ERRNO_CASE(ENODATA); + ERRNO_CASE(ENODATA); #endif #ifdef ENODEV - ERRNO_CASE(ENODEV); + ERRNO_CASE(ENODEV); #endif #ifdef ENOENT - ERRNO_CASE(ENOENT); + ERRNO_CASE(ENOENT); #endif #ifdef ENOEXEC - ERRNO_CASE(ENOEXEC); + ERRNO_CASE(ENOEXEC); #endif #ifdef ENOLINK - ERRNO_CASE(ENOLINK); + ERRNO_CASE(ENOLINK); #endif #ifdef ENOLCK -# if ENOLINK != ENOLCK - ERRNO_CASE(ENOLCK); -# endif +#if ENOLINK != ENOLCK + ERRNO_CASE(ENOLCK); +#endif #endif #ifdef ENOMEM - ERRNO_CASE(ENOMEM); + ERRNO_CASE(ENOMEM); #endif #ifdef ENOMSG - ERRNO_CASE(ENOMSG); + ERRNO_CASE(ENOMSG); #endif #ifdef ENOPROTOOPT - ERRNO_CASE(ENOPROTOOPT); + ERRNO_CASE(ENOPROTOOPT); #endif #ifdef ENOSPC - ERRNO_CASE(ENOSPC); + ERRNO_CASE(ENOSPC); #endif #ifdef ENOSR - ERRNO_CASE(ENOSR); + ERRNO_CASE(ENOSR); #endif #ifdef ENOSTR - ERRNO_CASE(ENOSTR); + ERRNO_CASE(ENOSTR); #endif #ifdef ENOSYS - ERRNO_CASE(ENOSYS); + ERRNO_CASE(ENOSYS); #endif #ifdef ENOTCONN - ERRNO_CASE(ENOTCONN); + ERRNO_CASE(ENOTCONN); #endif #ifdef ENOTDIR - ERRNO_CASE(ENOTDIR); + ERRNO_CASE(ENOTDIR); #endif #ifdef ENOTEMPTY -# if ENOTEMPTY != EEXIST - ERRNO_CASE(ENOTEMPTY); -# endif +#if ENOTEMPTY != EEXIST + ERRNO_CASE(ENOTEMPTY); +#endif #endif #ifdef ENOTSOCK - ERRNO_CASE(ENOTSOCK); + ERRNO_CASE(ENOTSOCK); #endif #ifdef ENOTSUP - ERRNO_CASE(ENOTSUP); + ERRNO_CASE(ENOTSUP); #else -# ifdef EOPNOTSUPP - ERRNO_CASE(EOPNOTSUPP); -# endif +#ifdef EOPNOTSUPP + ERRNO_CASE(EOPNOTSUPP); +#endif #endif #ifdef ENOTTY - ERRNO_CASE(ENOTTY); + ERRNO_CASE(ENOTTY); #endif #ifdef ENXIO - ERRNO_CASE(ENXIO); + ERRNO_CASE(ENXIO); #endif - #ifdef EOVERFLOW - ERRNO_CASE(EOVERFLOW); + ERRNO_CASE(EOVERFLOW); #endif #ifdef EPERM - ERRNO_CASE(EPERM); + ERRNO_CASE(EPERM); #endif #ifdef EPIPE - ERRNO_CASE(EPIPE); + ERRNO_CASE(EPIPE); #endif #ifdef EPROTO - ERRNO_CASE(EPROTO); + ERRNO_CASE(EPROTO); #endif #ifdef EPROTONOSUPPORT - ERRNO_CASE(EPROTONOSUPPORT); + ERRNO_CASE(EPROTONOSUPPORT); #endif #ifdef EPROTOTYPE - ERRNO_CASE(EPROTOTYPE); + ERRNO_CASE(EPROTOTYPE); #endif #ifdef ERANGE - ERRNO_CASE(ERANGE); + ERRNO_CASE(ERANGE); #endif #ifdef EROFS - ERRNO_CASE(EROFS); + ERRNO_CASE(EROFS); #endif #ifdef ESPIPE - ERRNO_CASE(ESPIPE); + ERRNO_CASE(ESPIPE); #endif #ifdef ESRCH - ERRNO_CASE(ESRCH); + ERRNO_CASE(ESRCH); #endif #ifdef ESTALE - ERRNO_CASE(ESTALE); + ERRNO_CASE(ESTALE); #endif #ifdef ETIME - ERRNO_CASE(ETIME); + ERRNO_CASE(ETIME); #endif #ifdef ETIMEDOUT - ERRNO_CASE(ETIMEDOUT); + ERRNO_CASE(ETIMEDOUT); #endif #ifdef ETXTBSY - ERRNO_CASE(ETXTBSY); + ERRNO_CASE(ETXTBSY); #endif #ifdef EXDEV - ERRNO_CASE(EXDEV); + ERRNO_CASE(EXDEV); #endif - default: return ""; + default: + return ""; } } -#define NODE_MODULE_CONTEXT_AWARE_INTERNAL(modname, regfunc) \ +#define NODE_MODULE_CONTEXT_AWARE_INTERNAL(modname, regfunc) \ NODE_MODULE_CONTEXT_AWARE_CPP(modname, regfunc, nullptr, NM_F_INTERNAL) #define TRACING_CATEGORY_NODE "node" -#define TRACING_CATEGORY_NODE1(one) \ - TRACING_CATEGORY_NODE "," \ - TRACING_CATEGORY_NODE "." #one -#define TRACING_CATEGORY_NODE2(one, two) \ - TRACING_CATEGORY_NODE "," \ - TRACING_CATEGORY_NODE "." #one "," \ - TRACING_CATEGORY_NODE "." #one "." #two +#define TRACING_CATEGORY_NODE1(one) \ + TRACING_CATEGORY_NODE "," TRACING_CATEGORY_NODE "." #one +#define TRACING_CATEGORY_NODE2(one, two) \ + TRACING_CATEGORY_NODE "," TRACING_CATEGORY_NODE "." #one \ + "," TRACING_CATEGORY_NODE "." #one "." #two // Functions defined in node.cc that are exposed via the bootstrapper object diff --git a/src/node_main.cc b/src/node_main.cc index bea1af7bdde5e3..42a61d90f57f02 100644 --- a/src/node_main.cc +++ b/src/node_main.cc @@ -19,18 +19,19 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node.h" #include +#include "node.h" #ifdef _WIN32 -#include #include #include +#include int wmain(int argc, wchar_t* wargv[]) { if (!IsWindows7OrGreater()) { - fprintf(stderr, "This application is only supported on Windows 7, " - "Windows Server 2008 R2, or higher."); + fprintf(stderr, + "This application is only supported on Windows 7, " + "Windows Server 2008 R2, or higher."); exit(ERROR_EXE_MACHINE_TYPE_MISMATCH); } @@ -38,14 +39,8 @@ int wmain(int argc, wchar_t* wargv[]) { char** argv = new char*[argc + 1]; for (int i = 0; i < argc; i++) { // Compute the size of the required buffer - DWORD size = WideCharToMultiByte(CP_UTF8, - 0, - wargv[i], - -1, - nullptr, - 0, - nullptr, - nullptr); + DWORD size = WideCharToMultiByte( + CP_UTF8, 0, wargv[i], -1, nullptr, 0, nullptr, nullptr); if (size == 0) { // This should never happen. fprintf(stderr, "Could not convert arguments to utf8."); @@ -53,14 +48,8 @@ int wmain(int argc, wchar_t* wargv[]) { } // Do the actual conversion argv[i] = new char[size]; - DWORD result = WideCharToMultiByte(CP_UTF8, - 0, - wargv[i], - -1, - argv[i], - size, - nullptr, - nullptr); + DWORD result = WideCharToMultiByte( + CP_UTF8, 0, wargv[i], -1, argv[i], size, nullptr, nullptr); if (result == 0) { // This should never happen. fprintf(stderr, "Could not convert arguments to utf8."); @@ -83,12 +72,12 @@ int wmain(int argc, wchar_t* wargv[]) { extern char** environ; #endif // __linux__ #if defined(__POSIX__) && defined(NODE_SHARED_MODE) -#include #include +#include #endif namespace node { - extern bool linux_at_secure; +extern bool linux_at_secure; } // namespace node int main(int argc, char* argv[]) { @@ -108,7 +97,8 @@ int main(int argc, char* argv[]) { #if defined(__linux__) char** envp = environ; - while (*envp++ != nullptr) {} + while (*envp++ != nullptr) { + } Elf_auxv_t* auxv = reinterpret_cast(envp); for (; auxv->a_type != AT_NULL; auxv++) { if (auxv->a_type == AT_SECURE) { diff --git a/src/node_messaging.cc b/src/node_messaging.cc index 20e0c7673b8fa9..7cd65cb385f5fa 100644 --- a/src/node_messaging.cc +++ b/src/node_messaging.cc @@ -1,12 +1,12 @@ -#include "debug_utils.h" #include "node_messaging.h" -#include "node_internals.h" +#include "async_wrap-inl.h" +#include "async_wrap.h" +#include "debug_utils.h" #include "node_buffer.h" #include "node_errors.h" -#include "util.h" +#include "node_internals.h" #include "util-inl.h" -#include "async_wrap.h" -#include "async_wrap-inl.h" +#include "util.h" using v8::Array; using v8::ArrayBuffer; @@ -43,20 +43,19 @@ namespace { // `MessagePort`s and `SharedArrayBuffer`s, and make new JS objects out of them. class DeserializerDelegate : public ValueDeserializer::Delegate { public: - DeserializerDelegate(Message* m, - Environment* env, - const std::vector& message_ports, - const std::vector>& - shared_array_buffers) - : message_ports_(message_ports), - shared_array_buffers_(shared_array_buffers) {} + DeserializerDelegate( + Message* m, + Environment* env, + const std::vector& message_ports, + const std::vector>& shared_array_buffers) + : message_ports_(message_ports), + shared_array_buffers_(shared_array_buffers) {} MaybeLocal ReadHostObject(Isolate* isolate) override { // Currently, only MessagePort hosts objects are supported, so identifying // by the index in the message's MessagePort array is sufficient. uint32_t id; - if (!deserializer->ReadUint32(&id)) - return MaybeLocal(); + if (!deserializer->ReadUint32(&id)) return MaybeLocal(); CHECK_LE(id, message_ports_.size()); return message_ports_[id]->object(isolate); }; @@ -84,9 +83,7 @@ MaybeLocal Message::Deserialize(Environment* env, // Create all necessary MessagePort handles. std::vector ports(message_ports_.size()); for (uint32_t i = 0; i < message_ports_.size(); ++i) { - ports[i] = MessagePort::New(env, - context, - std::move(message_ports_[i])); + ports[i] = MessagePort::New(env, context, std::move(message_ports_[i])); if (ports[i] == nullptr) { for (MessagePort* port : ports) { // This will eventually release the MessagePort object itself. @@ -101,8 +98,9 @@ MaybeLocal Message::Deserialize(Environment* env, // Attach all transfered SharedArrayBuffers to their new Isolate. for (uint32_t i = 0; i < shared_array_buffers_.size(); ++i) { Local sab; - if (!shared_array_buffers_[i]->GetSharedArrayBuffer(env, context) - .ToLocal(&sab)) + if (!shared_array_buffers_[i] + ->GetSharedArrayBuffer(env, context) + .ToLocal(&sab)) return MaybeLocal(); shared_array_buffers.push_back(sab); } @@ -127,8 +125,7 @@ MaybeLocal Message::Deserialize(Environment* env, } array_buffer_contents_.clear(); - if (deserializer.ReadHeader(context).IsNothing()) - return MaybeLocal(); + if (deserializer.ReadHeader(context).IsNothing()) return MaybeLocal(); return handle_scope.Escape( deserializer.ReadValue(context).FromMaybe(Local())); } @@ -146,14 +143,12 @@ namespace { void ThrowDataCloneException(Environment* env, Local message) { Local argv[] = { - message, - FIXED_ONE_BYTE_STRING(env->isolate(), "DataCloneError") - }; + message, FIXED_ONE_BYTE_STRING(env->isolate(), "DataCloneError")}; Local exception; Local domexception_ctor = env->domexception_function(); CHECK(!domexception_ctor.IsEmpty()); if (!domexception_ctor->NewInstance(env->context(), arraysize(argv), argv) - .ToLocal(&exception)) { + .ToLocal(&exception)) { return; } env->isolate()->ThrowException(exception); @@ -181,18 +176,14 @@ class SerializerDelegate : public ValueSerializer::Delegate { } Maybe GetSharedArrayBufferId( - Isolate* isolate, - Local shared_array_buffer) override { + Isolate* isolate, Local shared_array_buffer) override { uint32_t i; for (i = 0; i < seen_shared_array_buffers_.size(); ++i) { - if (seen_shared_array_buffers_[i] == shared_array_buffer) - return Just(i); + if (seen_shared_array_buffers_[i] == shared_array_buffer) return Just(i); } auto reference = SharedArrayBufferMetadata::ForSharedArrayBuffer( - env_, - context_, - shared_array_buffer); + env_, context_, shared_array_buffer); if (!reference) { return Nothing(); } @@ -234,7 +225,7 @@ class SerializerDelegate : public ValueSerializer::Delegate { friend class worker::Message; }; -} // anynomous namespace +} // namespace Maybe Message::Serialize(Environment* env, Local context, @@ -264,16 +255,14 @@ Maybe Message::Serialize(Environment* env, Local ab = entry.As(); // If we cannot render the ArrayBuffer unusable in this Isolate and // take ownership of its memory, copying the buffer will have to do. - if (!ab->IsNeuterable() || ab->IsExternal()) - continue; + if (!ab->IsNeuterable() || ab->IsExternal()) continue; // We simply use the array index in the `array_buffers` list as the // ID that we write into the serialized buffer. uint32_t id = array_buffers.size(); array_buffers.push_back(ab); serializer.TransferArrayBuffer(id, ab); continue; - } else if (env->message_port_constructor_template() - ->HasInstance(entry)) { + } else if (env->message_port_constructor_template()->HasInstance(entry)) { // Check if the source MessagePort is being transferred. if (!source_port.IsEmpty() && entry == source_port) { ThrowDataCloneException( @@ -311,9 +300,8 @@ Maybe Message::Serialize(Environment* env, // it inaccessible in this Isolate. ArrayBuffer::Contents contents = ab->Externalize(); ab->Neuter(); - array_buffer_contents_.push_back( - MallocedBuffer { static_cast(contents.Data()), - contents.ByteLength() }); + array_buffer_contents_.push_back(MallocedBuffer{ + static_cast(contents.Data()), contents.ByteLength()}); } delegate.Finish(); @@ -328,12 +316,13 @@ Maybe Message::Serialize(Environment* env, void Message::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackThis(this); tracker->TrackField("array_buffer_contents", array_buffer_contents_); - tracker->TrackFieldWithSize("shared_array_buffers", + tracker->TrackFieldWithSize( + "shared_array_buffers", shared_array_buffers_.size() * sizeof(shared_array_buffers_[0])); tracker->TrackField("message_ports", message_ports_); } -MessagePortData::MessagePortData(MessagePort* owner) : owner_(owner) { } +MessagePortData::MessagePortData(MessagePort* owner) : owner_(owner) {} MessagePortData::~MessagePortData() { CHECK_EQ(owner_, nullptr); @@ -372,8 +361,7 @@ void MessagePortData::Entangle(MessagePortData* a, MessagePortData* b) { void MessagePortData::PingOwnerAfterDisentanglement() { Mutex::ScopedLock lock(mutex_); - if (owner_ != nullptr) - owner_->TriggerAsync(); + if (owner_ != nullptr) owner_->TriggerAsync(); } void MessagePortData::Disentangle() { @@ -398,31 +386,27 @@ void MessagePortData::Disentangle() { } MessagePort::~MessagePort() { - if (data_) - data_->owner_ = nullptr; + if (data_) data_->owner_ = nullptr; } MessagePort::MessagePort(Environment* env, Local context, Local wrap) - : HandleWrap(env, - wrap, - reinterpret_cast(new uv_async_t()), - AsyncWrap::PROVIDER_MESSAGEPORT), - data_(new MessagePortData(this)) { + : HandleWrap(env, + wrap, + reinterpret_cast(new uv_async_t()), + AsyncWrap::PROVIDER_MESSAGEPORT), + data_(new MessagePortData(this)) { auto onmessage = [](uv_async_t* handle) { // Called when data has been put into the queue. MessagePort* channel = static_cast(handle->data); channel->OnMessage(); }; - CHECK_EQ(uv_async_init(env->event_loop(), - async(), - onmessage), 0); + CHECK_EQ(uv_async_init(env->event_loop(), async(), onmessage), 0); async()->data = static_cast(this); Local fn; - if (!wrap->Get(context, env->oninit_string()).ToLocal(&fn)) - return; + if (!wrap->Get(context, env->oninit_string()).ToLocal(&fn)) return; if (fn->IsFunction()) { Local init = fn.As(); @@ -475,21 +459,18 @@ void MessagePort::New(const FunctionCallbackInfo& args) { new MessagePort(env, context, args.This()); } -MessagePort* MessagePort::New( - Environment* env, - Local context, - std::unique_ptr data) { +MessagePort* MessagePort::New(Environment* env, + Local context, + std::unique_ptr data) { Context::Scope context_scope(context); Local ctor; - if (!GetMessagePortConstructor(env, context).ToLocal(&ctor)) - return nullptr; + if (!GetMessagePortConstructor(env, context).ToLocal(&ctor)) return nullptr; MessagePort* port = nullptr; // Construct a new instance, then assign the listener instance and possibly // the MessagePortData to it. Local instance; - if (!ctor->NewInstance(context).ToLocal(&instance)) - return nullptr; + if (!ctor->NewInstance(context).ToLocal(&instance)) return nullptr; ASSIGN_OR_RETURN_UNWRAP(&port, instance, nullptr); if (data) { port->Detach(); @@ -524,13 +505,12 @@ void MessagePort::OnMessage() { break; } - Debug(this, "MessagePort has message, receiving = %d", + Debug(this, + "MessagePort has message, receiving = %d", static_cast(data_->receiving_messages_)); - if (!data_->receiving_messages_) - break; - if (data_->incoming_messages_.empty()) - break; + if (!data_->receiving_messages_) break; + if (data_->incoming_messages_.empty()) break; received = std::move(data_->incoming_messages_.front()); data_->incoming_messages_.pop_front(); } @@ -546,14 +526,12 @@ void MessagePort::OnMessage() { HandleScope handle_scope(env()->isolate()); Context::Scope context_scope(context); Local args[] = { - received.Deserialize(env(), context).FromMaybe(Local()) - }; + received.Deserialize(env(), context).FromMaybe(Local())}; if (args[0].IsEmpty() || MakeCallback(env()->onmessage_string(), 1, args).IsEmpty()) { // Re-schedule OnMessage() execution in case of failure. - if (data_) - TriggerAsync(); + if (data_) TriggerAsync(); return; } } @@ -585,7 +563,6 @@ std::unique_ptr MessagePort::Detach() { return std::move(data_); } - Maybe MessagePort::PostMessage(Environment* env, Local message_v, Local transfer_v) { @@ -615,15 +592,15 @@ Maybe MessagePort::PostMessage(Environment* env, for (const auto& port_data : msg.message_ports()) { if (data_->sibling_ == port_data.get()) { doomed = true; - ProcessEmitWarning(env, "The target port was posted to itself, and " - "the communication channel was lost"); + ProcessEmitWarning(env, + "The target port was posted to itself, and " + "the communication channel was lost"); break; } } } - if (data_->sibling_ == nullptr || doomed) - return Just(true); + if (data_->sibling_ == nullptr || doomed) return Just(true); data_->sibling_->AddToIncomingQueue(std::move(msg)); return Just(true); @@ -632,8 +609,9 @@ Maybe MessagePort::PostMessage(Environment* env, void MessagePort::PostMessage(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (args.Length() == 0) { - return THROW_ERR_MISSING_ARGS(env, "Not enough arguments to " - "MessagePort.postMessage"); + return THROW_ERR_MISSING_ARGS(env, + "Not enough arguments to " + "MessagePort.postMessage"); } MessagePort* port = Unwrap(args.This()); @@ -655,8 +633,7 @@ void MessagePort::Start() { Mutex::ScopedLock lock(data_->mutex_); Debug(this, "Start receiving messages"); data_->receiving_messages_ = true; - if (!data_->incoming_messages_.empty()) - TriggerAsync(); + if (!data_->incoming_messages_.empty()) TriggerAsync(); } void MessagePort::Stop() { @@ -710,13 +687,12 @@ void MessagePort::Entangle(MessagePort* a, MessagePortData* b) { MessagePortData::Entangle(a->data_.get(), b); } -MaybeLocal GetMessagePortConstructor( - Environment* env, Local context) { +MaybeLocal GetMessagePortConstructor(Environment* env, + Local context) { // Factor generating the MessagePort JS constructor into its own piece // of code, because it is needed early on in the child environment setup. Local templ = env->message_port_constructor_template(); - if (!templ.IsEmpty()) - return templ->GetFunction(context); + if (!templ.IsEmpty()) return templ->GetFunction(context); { Local m = env->NewFunctionTemplate(MessagePort::New); @@ -753,9 +729,11 @@ static void MessageChannel(const FunctionCallbackInfo& args) { MessagePort* port2 = MessagePort::New(env, context); MessagePort::Entangle(port1, port2); - args.This()->Set(env->context(), env->port1_string(), port1->object()) + args.This() + ->Set(env->context(), env->port1_string(), port1->object()) .FromJust(); - args.This()->Set(env->context(), env->port2_string(), port2->object()) + args.This() + ->Set(env->context(), env->port2_string(), port2->object()) .FromJust(); } @@ -777,15 +755,18 @@ static void InitMessaging(Local target, FIXED_ONE_BYTE_STRING(env->isolate(), "MessageChannel"); Local templ = env->NewFunctionTemplate(MessageChannel); templ->SetClassName(message_channel_string); - target->Set(env->context(), - message_channel_string, - templ->GetFunction(context).ToLocalChecked()).FromJust(); + target + ->Set(env->context(), + message_channel_string, + templ->GetFunction(context).ToLocalChecked()) + .FromJust(); } - target->Set(context, - env->message_port_constructor_string(), - GetMessagePortConstructor(env, context).ToLocalChecked()) - .FromJust(); + target + ->Set(context, + env->message_port_constructor_string(), + GetMessagePortConstructor(env, context).ToLocalChecked()) + .FromJust(); env->SetMethod(target, "registerDOMException", RegisterDOMException); } diff --git a/src/node_messaging.h b/src/node_messaging.h index b7fd392ccc6fab..d1bab1bbb28a9f 100644 --- a/src/node_messaging.h +++ b/src/node_messaging.h @@ -3,10 +3,10 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include #include "env.h" #include "node_mutex.h" #include "sharedarraybuffer_metadata.h" -#include namespace node { namespace worker { @@ -34,12 +34,12 @@ class Message : public MemoryRetainer { // deserialization. // The source_port parameter, if provided, will make Serialize() throw a // "DataCloneError" DOMException if source_port is found in transfer_list. - v8::Maybe Serialize(Environment* env, - v8::Local context, - v8::Local input, - v8::Local transfer_list, - v8::Local source_port = - v8::Local()); + v8::Maybe Serialize( + Environment* env, + v8::Local context, + v8::Local input, + v8::Local transfer_list, + v8::Local source_port = v8::Local()); // Internal method of Message that is called when a new SharedArrayBuffer // object is encountered in the incoming value's structure. @@ -213,5 +213,4 @@ v8::MaybeLocal GetMessagePortConstructor( #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS - #endif // SRC_NODE_MESSAGING_H_ diff --git a/src/node_mutex.h b/src/node_mutex.h index 9e1d31654f7dbf..141bbdff9f3da1 100644 --- a/src/node_mutex.h +++ b/src/node_mutex.h @@ -6,8 +6,10 @@ namespace node { -template class ConditionVariableBase; -template class MutexBase; +template +class ConditionVariableBase; +template +class MutexBase; struct LibuvMutexTraits; using ConditionVariable = ConditionVariableBase; @@ -31,7 +33,8 @@ class MutexBase { inline ~ScopedLock(); private: - template friend class ConditionVariableBase; + template + friend class ConditionVariableBase; friend class ScopedUnlock; const MutexBase& mutex_; DISALLOW_COPY_AND_ASSIGN(ScopedLock); @@ -49,7 +52,8 @@ class MutexBase { }; private: - template friend class ConditionVariableBase; + template + friend class ConditionVariableBase; mutable typename Traits::MutexT mutex_; DISALLOW_COPY_AND_ASSIGN(MutexBase); }; @@ -74,41 +78,25 @@ struct LibuvMutexTraits { using CondT = uv_cond_t; using MutexT = uv_mutex_t; - static inline int cond_init(CondT* cond) { - return uv_cond_init(cond); - } + static inline int cond_init(CondT* cond) { return uv_cond_init(cond); } - static inline int mutex_init(MutexT* mutex) { - return uv_mutex_init(mutex); - } + static inline int mutex_init(MutexT* mutex) { return uv_mutex_init(mutex); } - static inline void cond_broadcast(CondT* cond) { - uv_cond_broadcast(cond); - } + static inline void cond_broadcast(CondT* cond) { uv_cond_broadcast(cond); } - static inline void cond_destroy(CondT* cond) { - uv_cond_destroy(cond); - } + static inline void cond_destroy(CondT* cond) { uv_cond_destroy(cond); } - static inline void cond_signal(CondT* cond) { - uv_cond_signal(cond); - } + static inline void cond_signal(CondT* cond) { uv_cond_signal(cond); } static inline void cond_wait(CondT* cond, MutexT* mutex) { uv_cond_wait(cond, mutex); } - static inline void mutex_destroy(MutexT* mutex) { - uv_mutex_destroy(mutex); - } + static inline void mutex_destroy(MutexT* mutex) { uv_mutex_destroy(mutex); } - static inline void mutex_lock(MutexT* mutex) { - uv_mutex_lock(mutex); - } + static inline void mutex_lock(MutexT* mutex) { uv_mutex_lock(mutex); } - static inline void mutex_unlock(MutexT* mutex) { - uv_mutex_unlock(mutex); - } + static inline void mutex_unlock(MutexT* mutex) { uv_mutex_unlock(mutex); } }; template diff --git a/src/node_object_wrap.h b/src/node_object_wrap.h index b8ed2f99135a65..ebd25da70f0c77 100644 --- a/src/node_object_wrap.h +++ b/src/node_object_wrap.h @@ -22,28 +22,22 @@ #ifndef SRC_NODE_OBJECT_WRAP_H_ #define SRC_NODE_OBJECT_WRAP_H_ -#include "v8.h" #include - +#include "v8.h" namespace node { class ObjectWrap { public: - ObjectWrap() { - refs_ = 0; - } - + ObjectWrap() { refs_ = 0; } virtual ~ObjectWrap() { - if (persistent().IsEmpty()) - return; + if (persistent().IsEmpty()) return; assert(persistent().IsNearDeath()); persistent().ClearWeak(); persistent().Reset(); } - template static inline T* Unwrap(v8::Local handle) { assert(!handle.IsEmpty()); @@ -55,21 +49,15 @@ class ObjectWrap { return static_cast(wrap); } - inline v8::Local handle() { return handle(v8::Isolate::GetCurrent()); } - inline v8::Local handle(v8::Isolate* isolate) { return v8::Local::New(isolate, persistent()); } - - inline v8::Persistent& persistent() { - return handle_; - } - + inline v8::Persistent& persistent() { return handle_; } protected: inline void Wrap(v8::Local handle) { @@ -80,7 +68,6 @@ class ObjectWrap { MakeWeak(); } - inline void MakeWeak(void) { persistent().SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); } @@ -108,15 +95,13 @@ class ObjectWrap { assert(!persistent().IsEmpty()); assert(!persistent().IsWeak()); assert(refs_ > 0); - if (--refs_ == 0) - MakeWeak(); + if (--refs_ == 0) MakeWeak(); } int refs_; // ro private: - static void WeakCallback( - const v8::WeakCallbackInfo& data) { + static void WeakCallback(const v8::WeakCallbackInfo& data) { ObjectWrap* wrap = data.GetParameter(); assert(wrap->refs_ == 0); wrap->handle_.Reset(); diff --git a/src/node_os.cc b/src/node_os.cc index c9eef808b0addf..4ea6b434a4904c 100644 --- a/src/node_os.cc +++ b/src/node_os.cc @@ -26,20 +26,20 @@ #include #ifdef __MINGW32__ -# include +#include #endif // __MINGW32__ #ifdef __POSIX__ -# include // PATH_MAX on Solaris. -# include // MAXHOSTNAMELEN on Solaris. -# include // gethostname, sysconf -# include // MAXHOSTNAMELEN on Linux and the BSDs. -# include -#endif // __POSIX__ +#include // PATH_MAX on Solaris. +#include // MAXHOSTNAMELEN on Solaris. +#include // MAXHOSTNAMELEN on Linux and the BSDs. +#include +#include // gethostname, sysconf +#endif // __POSIX__ // Add Windows fallback. #ifndef MAXHOSTNAMELEN -# define MAXHOSTNAMELEN 256 +#define MAXHOSTNAMELEN 256 #endif // MAXHOSTNAMELEN namespace node { @@ -61,7 +61,6 @@ using v8::Object; using v8::String; using v8::Value; - static void GetHostname(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); char buf[MAXHOSTNAMELEN + 1]; @@ -69,7 +68,7 @@ static void GetHostname(const FunctionCallbackInfo& args) { if (gethostname(buf, sizeof(buf))) { #ifdef __POSIX__ int errorno = errno; -#else // __MINGW32__ +#else // __MINGW32__ int errorno = WSAGetLastError(); #endif // __POSIX__ CHECK_GE(args.Length(), 1); @@ -81,7 +80,6 @@ static void GetHostname(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(OneByteString(env->isolate(), buf)); } - static void GetOSType(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); const char* rval; @@ -94,14 +92,13 @@ static void GetOSType(const FunctionCallbackInfo& args) { return args.GetReturnValue().SetUndefined(); } rval = info.sysname; -#else // __MINGW32__ +#else // __MINGW32__ rval = "Windows_NT"; #endif // __POSIX__ args.GetReturnValue().Set(OneByteString(env->isolate(), rval)); } - static void GetOSRelease(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); const char* rval; @@ -113,24 +110,22 @@ static void GetOSRelease(const FunctionCallbackInfo& args) { env->CollectExceptionInfo(args[args.Length() - 1], errno, "uname"); return args.GetReturnValue().SetUndefined(); } -# ifdef _AIX +#ifdef _AIX char release[256]; - snprintf(release, sizeof(release), - "%s.%s", info.version, info.release); + snprintf(release, sizeof(release), "%s.%s", info.version, info.release); rval = release; -# else +#else rval = info.release; -# endif +#endif #else // Windows char release[256]; OSVERSIONINFOW info; info.dwOSVersionInfoSize = sizeof(info); - // Don't complain that GetVersionEx is deprecated; there is no alternative. - #pragma warning(suppress : 4996) - if (GetVersionExW(&info) == 0) - return; +// Don't complain that GetVersionEx is deprecated; there is no alternative. +#pragma warning(suppress : 4996) + if (GetVersionExW(&info) == 0) return; snprintf(release, sizeof(release), @@ -144,15 +139,13 @@ static void GetOSRelease(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(OneByteString(env->isolate(), rval)); } - static void GetCPUInfo(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); uv_cpu_info_t* cpu_infos; int count, i, field_idx; int err = uv_cpu_info(&cpu_infos, &count); - if (err) - return; + if (err) return; CHECK(args[0]->IsFunction()); Local addfn = args[0].As(); @@ -195,31 +188,24 @@ static void GetCPUInfo(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(cpus); } - static void GetFreeMemory(const FunctionCallbackInfo& args) { double amount = uv_get_free_memory(); - if (amount < 0) - return; + if (amount < 0) return; args.GetReturnValue().Set(amount); } - static void GetTotalMemory(const FunctionCallbackInfo& args) { double amount = uv_get_total_memory(); - if (amount < 0) - return; + if (amount < 0) return; args.GetReturnValue().Set(amount); } - static void GetUptime(const FunctionCallbackInfo& args) { double uptime; int err = uv_uptime(&uptime); - if (err == 0) - args.GetReturnValue().Set(uptime); + if (err == 0) args.GetReturnValue().Set(uptime); } - static void GetLoadAvg(const FunctionCallbackInfo& args) { CHECK(args[0]->IsFloat64Array()); Local array = args[0].As(); @@ -229,7 +215,6 @@ static void GetLoadAvg(const FunctionCallbackInfo& args) { uv_loadavg(loadavg); } - static void GetInterfaceAddresses(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); uv_interface_address_t* interfaces; @@ -249,8 +234,8 @@ static void GetInterfaceAddresses(const FunctionCallbackInfo& args) { return args.GetReturnValue().Set(ret); } else if (err) { CHECK_GE(args.Length(), 1); - env->CollectUVExceptionInfo(args[args.Length() - 1], errno, - "uv_interface_addresses"); + env->CollectUVExceptionInfo( + args[args.Length() - 1], errno, "uv_interface_addresses"); return args.GetReturnValue().SetUndefined(); } @@ -262,8 +247,9 @@ static void GetInterfaceAddresses(const FunctionCallbackInfo& args) { // to assume UTF8 as the default as well. It’s what people will expect if // they name the interface from any input that uses UTF-8, which should be // the most frequent case by far these days.) - name = String::NewFromUtf8(env->isolate(), raw_name, - v8::NewStringType::kNormal).ToLocalChecked(); + name = String::NewFromUtf8( + env->isolate(), raw_name, v8::NewStringType::kNormal) + .ToLocalChecked(); if (ret->Has(env->context(), name).FromJust()) { ifarr = Local::Cast(ret->Get(name)); @@ -318,7 +304,6 @@ static void GetInterfaceAddresses(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ret); } - static void GetHomeDirectory(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); char buf[PATH_MAX]; @@ -332,14 +317,12 @@ static void GetHomeDirectory(const FunctionCallbackInfo& args) { return args.GetReturnValue().SetUndefined(); } - Local home = String::NewFromUtf8(env->isolate(), - buf, - v8::NewStringType::kNormal, - len).ToLocalChecked(); + Local home = + String::NewFromUtf8(env->isolate(), buf, v8::NewStringType::kNormal, len) + .ToLocalChecked(); args.GetReturnValue().Set(home); } - static void GetUserInfo(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); uv_passwd_t pwd; @@ -347,10 +330,9 @@ static void GetUserInfo(const FunctionCallbackInfo& args) { if (args[0]->IsObject()) { Local options = args[0].As(); - MaybeLocal maybe_encoding = options->Get(env->context(), - env->encoding_string()); - if (maybe_encoding.IsEmpty()) - return; + MaybeLocal maybe_encoding = + options->Get(env->context(), env->encoding_string()); + if (maybe_encoding.IsEmpty()) return; Local encoding_opt = maybe_encoding.ToLocalChecked(); encoding = ParseEncoding(env->isolate(), encoding_opt, UTF8); @@ -362,8 +344,8 @@ static void GetUserInfo(const FunctionCallbackInfo& args) { if (err) { CHECK_GE(args.Length(), 2); - env->CollectUVExceptionInfo(args[args.Length() - 1], err, - "uv_os_get_passwd"); + env->CollectUVExceptionInfo( + args[args.Length() - 1], err, "uv_os_get_passwd"); return args.GetReturnValue().SetUndefined(); } @@ -371,14 +353,10 @@ static void GetUserInfo(const FunctionCallbackInfo& args) { Local uid = Number::New(env->isolate(), pwd.uid); Local gid = Number::New(env->isolate(), pwd.gid); - MaybeLocal username = StringBytes::Encode(env->isolate(), - pwd.username, - encoding, - &error); - MaybeLocal homedir = StringBytes::Encode(env->isolate(), - pwd.homedir, - encoding, - &error); + MaybeLocal username = + StringBytes::Encode(env->isolate(), pwd.username, encoding, &error); + MaybeLocal homedir = + StringBytes::Encode(env->isolate(), pwd.homedir, encoding, &error); MaybeLocal shell; if (pwd.shell == nullptr) @@ -404,7 +382,6 @@ static void GetUserInfo(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(entry); } - void Initialize(Local target, Local unused, Local context) { diff --git a/src/node_perf.cc b/src/node_perf.cc index a1ca57e2d5c100..0aec051e1ec8de 100644 --- a/src/node_perf.cc +++ b/src/node_perf.cc @@ -1,5 +1,5 @@ -#include "node_internals.h" #include "node_perf.h" +#include "node_internals.h" #ifdef __POSIX__ #include // gettimeofday @@ -38,13 +38,12 @@ uint64_t performance_v8_start; uint64_t performance_last_gc_start_mark_ = 0; v8::GCType performance_last_gc_type_ = v8::GCType::kGCTypeAll; -void performance_state::Mark(enum PerformanceMilestone milestone, - uint64_t ts) { +void performance_state::Mark(enum PerformanceMilestone milestone, uint64_t ts) { this->milestones[milestone] = ts; - TRACE_EVENT_INSTANT_WITH_TIMESTAMP0( - TRACING_CATEGORY_NODE1(bootstrap), - GetPerformanceMilestoneName(milestone), - TRACE_EVENT_SCOPE_THREAD, ts / 1000); + TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(TRACING_CATEGORY_NODE1(bootstrap), + GetPerformanceMilestoneName(milestone), + TRACE_EVENT_SCOPE_THREAD, + ts / 1000); } double GetCurrentTimeInMicroseconds() { @@ -53,8 +52,8 @@ double GetCurrentTimeInMicroseconds() { #define TICKS_TO_UNIX_EPOCH 116444736000000000LL FILETIME ft; GetSystemTimeAsFileTime(&ft); - uint64_t filetime_int = static_cast(ft.dwHighDateTime) << 32 | - ft.dwLowDateTime; + uint64_t filetime_int = + static_cast(ft.dwHighDateTime) << 32 | ft.dwLowDateTime; // FILETIME is measured in terms of 100 ns. Convert that to 1 us (1000 ns). return (filetime_int - TICKS_TO_UNIX_EPOCH) / 10.; #else @@ -71,37 +70,39 @@ inline void InitObject(const PerformanceEntry& entry, Local obj) { Local context = env->context(); v8::PropertyAttribute attr = static_cast(v8::ReadOnly | v8::DontDelete); - obj->DefineOwnProperty(context, - env->name_string(), - String::NewFromUtf8(isolate, - entry.name().c_str(), - v8::NewStringType::kNormal) - .ToLocalChecked(), - attr) + obj->DefineOwnProperty( + context, + env->name_string(), + String::NewFromUtf8( + isolate, entry.name().c_str(), v8::NewStringType::kNormal) + .ToLocalChecked(), + attr) .FromJust(); - obj->DefineOwnProperty(context, - FIXED_ONE_BYTE_STRING(isolate, "entryType"), - String::NewFromUtf8(isolate, - entry.type().c_str(), - v8::NewStringType::kNormal) - .ToLocalChecked(), - attr) + obj->DefineOwnProperty( + context, + FIXED_ONE_BYTE_STRING(isolate, "entryType"), + String::NewFromUtf8( + isolate, entry.type().c_str(), v8::NewStringType::kNormal) + .ToLocalChecked(), + attr) .FromJust(); obj->DefineOwnProperty(context, FIXED_ONE_BYTE_STRING(isolate, "startTime"), Number::New(isolate, entry.startTime()), - attr).FromJust(); + attr) + .FromJust(); obj->DefineOwnProperty(context, FIXED_ONE_BYTE_STRING(isolate, "duration"), Number::New(isolate, entry.duration()), - attr).FromJust(); + attr) + .FromJust(); } // Create a new PerformanceEntry object const Local PerformanceEntry::ToObject() const { - Local obj = - env_->performance_entry_template() - ->NewInstance(env_->context()).ToLocalChecked(); + Local obj = env_->performance_entry_template() + ->NewInstance(env_->context()) + .ToLocalChecked(); InitObject(*this, obj); return obj; } @@ -126,12 +127,12 @@ void PerformanceEntry::Notify(Environment* env, Context::Scope scope(env->context()); AliasedBuffer& observers = env->performance_state()->observers; - if (type != NODE_PERFORMANCE_ENTRY_TYPE_INVALID && - observers[type]) { + if (type != NODE_PERFORMANCE_ENTRY_TYPE_INVALID && observers[type]) { node::MakeCallback(env->isolate(), object.As(), env->performance_entry_callback(), - 1, &object, + 1, + &object, node::async_context{0, 0}); } } @@ -146,8 +147,7 @@ void Mark(const FunctionCallbackInfo& args) { (*marks)[*name] = now; TRACE_EVENT_COPY_MARK_WITH_TIMESTAMP( - TRACING_CATEGORY_NODE2(perf, usertiming), - *name, now / 1000); + TRACING_CATEGORY_NODE2(perf, usertiming), *name, now / 1000); PerformanceEntry entry(env, *name, "mark", now, now); Local obj = entry.ToObject(); @@ -202,15 +202,18 @@ void Measure(const FunctionCallbackInfo& args) { endTimestamp = milestones[milestone]; } - if (endTimestamp < startTimestamp) - endTimestamp = startTimestamp; + if (endTimestamp < startTimestamp) endTimestamp = startTimestamp; TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( TRACING_CATEGORY_NODE2(perf, usertiming), - *name, *name, startTimestamp / 1000); + *name, + *name, + startTimestamp / 1000); TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0( TRACING_CATEGORY_NODE2(perf, usertiming), - *name, *name, endTimestamp / 1000); + *name, + *name, + endTimestamp / 1000); PerformanceEntry entry(env, *name, "measure", startTimestamp, endTimestamp); Local obj = entry.ToObject(); @@ -222,14 +225,12 @@ void Measure(const FunctionCallbackInfo& args) { void MarkMilestone(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Local context = env->context(); - PerformanceMilestone milestone = - static_cast( - args[0]->Int32Value(context).ToChecked()); + PerformanceMilestone milestone = static_cast( + args[0]->Int32Value(context).ToChecked()); if (milestone != NODE_PERFORMANCE_MILESTONE_INVALID) env->performance_state()->Mark(milestone); } - void SetupPerformanceObservers(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsFunction()); @@ -251,7 +252,8 @@ void PerformanceGCCallback(Environment* env, void* ptr) { obj->DefineOwnProperty(context, FIXED_ONE_BYTE_STRING(env->isolate(), "kind"), Integer::New(env->isolate(), entry->gckind()), - attr).FromJust(); + attr) + .FromJust(); PerformanceEntry::Notify(env, entry->kind(), obj); } @@ -277,11 +279,9 @@ void MarkGarbageCollectionEnd(Isolate* isolate, static_cast(type), performance_last_gc_start_mark_, PERFORMANCE_NOW()); - env->SetUnrefImmediate(PerformanceGCCallback, - entry); + env->SetUnrefImmediate(PerformanceGCCallback, entry); } - inline void SetupGarbageCollectionTracking(Environment* env) { env->isolate()->AddGCPrologueCallback(MarkGarbageCollectionStart); env->isolate()->AddGCEpilogueCallback(MarkGarbageCollectionEnd, @@ -320,15 +320,12 @@ void TimerFunctionCall(const FunctionCallbackInfo& args) { if (args.IsConstructCall()) { start = PERFORMANCE_NOW(); TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( - TRACING_CATEGORY_NODE2(perf, timerify), - *name, *name, start / 1000); - v8::MaybeLocal ret = fn->NewInstance(context, - call_args.size(), - call_args.data()); + TRACING_CATEGORY_NODE2(perf, timerify), *name, *name, start / 1000); + v8::MaybeLocal ret = + fn->NewInstance(context, call_args.size(), call_args.data()); end = PERFORMANCE_NOW(); TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0( - TRACING_CATEGORY_NODE2(perf, timerify), - *name, *name, end / 1000); + TRACING_CATEGORY_NODE2(perf, timerify), *name, *name, end / 1000); if (ret.IsEmpty()) { try_catch.ReThrow(); @@ -338,16 +335,12 @@ void TimerFunctionCall(const FunctionCallbackInfo& args) { } else { start = PERFORMANCE_NOW(); TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( - TRACING_CATEGORY_NODE2(perf, timerify), - *name, *name, start / 1000); - v8::MaybeLocal ret = fn->Call(context, - args.This(), - call_args.size(), - call_args.data()); + TRACING_CATEGORY_NODE2(perf, timerify), *name, *name, start / 1000); + v8::MaybeLocal ret = + fn->Call(context, args.This(), call_args.size(), call_args.data()); end = PERFORMANCE_NOW(); TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0( - TRACING_CATEGORY_NODE2(perf, timerify), - *name, *name, end / 1000); + TRACING_CATEGORY_NODE2(perf, timerify), *name, *name, end / 1000); if (ret.IsEmpty()) { try_catch.ReThrow(); @@ -358,8 +351,7 @@ void TimerFunctionCall(const FunctionCallbackInfo& args) { AliasedBuffer& observers = env->performance_state()->observers; - if (!observers[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION]) - return; + if (!observers[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION]) return; PerformanceEntry entry(env, *name, "function", start, end); Local obj = entry.ToObject(); @@ -381,7 +373,6 @@ void Timerify(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(wrap); } - void Initialize(Local target, Local unused, Local context) { @@ -389,12 +380,16 @@ void Initialize(Local target, Isolate* isolate = env->isolate(); performance_state* state = env->performance_state(); - target->Set(context, - FIXED_ONE_BYTE_STRING(isolate, "observerCounts"), - state->observers.GetJSArray()).FromJust(); - target->Set(context, - FIXED_ONE_BYTE_STRING(isolate, "milestones"), - state->milestones.GetJSArray()).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "observerCounts"), + state->observers.GetJSArray()) + .FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "milestones"), + state->milestones.GetJSArray()) + .FromJust(); Local performanceEntryString = FIXED_ONE_BYTE_STRING(isolate, "PerformanceEntry"); @@ -419,12 +414,12 @@ void Initialize(Local target, NODE_DEFINE_CONSTANT(constants, NODE_PERFORMANCE_GC_INCREMENTAL); NODE_DEFINE_CONSTANT(constants, NODE_PERFORMANCE_GC_WEAKCB); -#define V(name, _) \ +#define V(name, _) \ NODE_DEFINE_HIDDEN_CONSTANT(constants, NODE_PERFORMANCE_ENTRY_TYPE_##name); NODE_PERFORMANCE_ENTRY_TYPES(V) #undef V -#define V(name, _) \ +#define V(name, _) \ NODE_DEFINE_HIDDEN_CONSTANT(constants, NODE_PERFORMANCE_MILESTONE_##name); NODE_PERFORMANCE_MILESTONES(V) #undef V @@ -432,21 +427,23 @@ void Initialize(Local target, v8::PropertyAttribute attr = static_cast(v8::ReadOnly | v8::DontDelete); - target->DefineOwnProperty(context, - FIXED_ONE_BYTE_STRING(isolate, "timeOrigin"), - v8::Number::New(isolate, timeOrigin / 1e6), - attr).ToChecked(); - - target->DefineOwnProperty( - context, - FIXED_ONE_BYTE_STRING(isolate, "timeOriginTimestamp"), - v8::Number::New(isolate, timeOriginTimestamp / MICROS_PER_MILLIS), - attr).ToChecked(); - - target->DefineOwnProperty(context, - env->constants_string(), - constants, - attr).ToChecked(); + target + ->DefineOwnProperty(context, + FIXED_ONE_BYTE_STRING(isolate, "timeOrigin"), + v8::Number::New(isolate, timeOrigin / 1e6), + attr) + .ToChecked(); + + target + ->DefineOwnProperty( + context, + FIXED_ONE_BYTE_STRING(isolate, "timeOriginTimestamp"), + v8::Number::New(isolate, timeOriginTimestamp / MICROS_PER_MILLIS), + attr) + .ToChecked(); + + target->DefineOwnProperty(context, env->constants_string(), constants, attr) + .ToChecked(); SetupGarbageCollectionTracking(env); } diff --git a/src/node_perf.h b/src/node_perf.h index 703ef81ce48def..485b1295d3c2da 100644 --- a/src/node_perf.h +++ b/src/node_perf.h @@ -3,14 +3,14 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "base_object-inl.h" +#include "env.h" #include "node.h" #include "node_internals.h" #include "node_perf_common.h" -#include "env.h" -#include "base_object-inl.h" -#include "v8.h" #include "uv.h" +#include "v8.h" #include @@ -30,8 +30,10 @@ double GetCurrentTimeInMicroseconds(); static inline const char* GetPerformanceMilestoneName( enum PerformanceMilestone milestone) { switch (milestone) { -#define V(name, label) case NODE_PERFORMANCE_MILESTONE_##name: return label; - NODE_PERFORMANCE_MILESTONES(V) +#define V(name, label) \ + case NODE_PERFORMANCE_MILESTONE_##name: \ + return label; + NODE_PERFORMANCE_MILESTONES(V) #undef V default: UNREACHABLE(); @@ -40,7 +42,7 @@ static inline const char* GetPerformanceMilestoneName( } static inline PerformanceMilestone ToPerformanceMilestoneEnum(const char* str) { -#define V(name, label) \ +#define V(name, label) \ if (strcmp(str, label) == 0) return NODE_PERFORMANCE_MILESTONE_##name; NODE_PERFORMANCE_MILESTONES(V) #undef V @@ -49,7 +51,7 @@ static inline PerformanceMilestone ToPerformanceMilestoneEnum(const char* str) { static inline PerformanceEntryType ToPerformanceEntryTypeEnum( const char* type) { -#define V(name, label) \ +#define V(name, label) \ if (strcmp(type, label) == 0) return NODE_PERFORMANCE_ENTRY_TYPE_##name; NODE_PERFORMANCE_ENTRY_TYPES(V) #undef V @@ -68,13 +70,14 @@ class PerformanceEntry { const char* name, const char* type, uint64_t startTime, - uint64_t endTime) : env_(env), - name_(name), - type_(type), - startTime_(startTime), - endTime_(endTime) { } + uint64_t endTime) + : env_(env), + name_(name), + type_(type), + startTime_(startTime), + endTime_(endTime) {} - virtual ~PerformanceEntry() { } + virtual ~PerformanceEntry() {} virtual const Local ToObject() const; @@ -116,9 +119,9 @@ class GCPerformanceEntry : public PerformanceEntry { GCPerformanceEntry(Environment* env, PerformanceGCKind gckind, uint64_t startTime, - uint64_t endTime) : - PerformanceEntry(env, "gc", "gc", startTime, endTime), - gckind_(gckind) { } + uint64_t endTime) + : PerformanceEntry(env, "gc", "gc", startTime, endTime), + gckind_(gckind) {} PerformanceGCKind gckind() const { return gckind_; } diff --git a/src/node_perf_common.h b/src/node_perf_common.h index 8f90c93060dc4c..e5882735de0875 100644 --- a/src/node_perf_common.h +++ b/src/node_perf_common.h @@ -18,55 +18,49 @@ namespace performance { extern uint64_t performance_node_start; extern uint64_t performance_v8_start; -#define NODE_PERFORMANCE_MILESTONES(V) \ - V(ENVIRONMENT, "environment") \ - V(NODE_START, "nodeStart") \ - V(V8_START, "v8Start") \ - V(LOOP_START, "loopStart") \ - V(LOOP_EXIT, "loopExit") \ +#define NODE_PERFORMANCE_MILESTONES(V) \ + V(ENVIRONMENT, "environment") \ + V(NODE_START, "nodeStart") \ + V(V8_START, "v8Start") \ + V(LOOP_START, "loopStart") \ + V(LOOP_EXIT, "loopExit") \ V(BOOTSTRAP_COMPLETE, "bootstrapComplete") - -#define NODE_PERFORMANCE_ENTRY_TYPES(V) \ - V(NODE, "node") \ - V(MARK, "mark") \ - V(MEASURE, "measure") \ - V(GC, "gc") \ - V(FUNCTION, "function") \ +#define NODE_PERFORMANCE_ENTRY_TYPES(V) \ + V(NODE, "node") \ + V(MARK, "mark") \ + V(MEASURE, "measure") \ + V(GC, "gc") \ + V(FUNCTION, "function") \ V(HTTP2, "http2") enum PerformanceMilestone { #define V(name, _) NODE_PERFORMANCE_MILESTONE_##name, NODE_PERFORMANCE_MILESTONES(V) #undef V - NODE_PERFORMANCE_MILESTONE_INVALID + NODE_PERFORMANCE_MILESTONE_INVALID }; enum PerformanceEntryType { #define V(name, _) NODE_PERFORMANCE_ENTRY_TYPE_##name, NODE_PERFORMANCE_ENTRY_TYPES(V) #undef V - NODE_PERFORMANCE_ENTRY_TYPE_INVALID + NODE_PERFORMANCE_ENTRY_TYPE_INVALID }; class performance_state { public: - explicit performance_state(v8::Isolate* isolate) : - root( - isolate, - sizeof(performance_state_internal)), - milestones( - isolate, - offsetof(performance_state_internal, milestones), - NODE_PERFORMANCE_MILESTONE_INVALID, - root), - observers( - isolate, - offsetof(performance_state_internal, observers), - NODE_PERFORMANCE_ENTRY_TYPE_INVALID, - root) { - for (size_t i = 0; i < milestones.Length(); i++) - milestones[i] = -1.; + explicit performance_state(v8::Isolate* isolate) + : root(isolate, sizeof(performance_state_internal)), + milestones(isolate, + offsetof(performance_state_internal, milestones), + NODE_PERFORMANCE_MILESTONE_INVALID, + root), + observers(isolate, + offsetof(performance_state_internal, observers), + NODE_PERFORMANCE_ENTRY_TYPE_INVALID, + root) { + for (size_t i = 0; i < milestones.Length(); i++) milestones[i] = -1.; } AliasedBuffer root; diff --git a/src/node_platform.cc b/src/node_platform.cc index 6a3ae2e5dc84ab..36162e1beb4a21 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc @@ -1,9 +1,9 @@ #include "node_platform.h" #include "node_internals.h" +#include #include "env-inl.h" #include "util.h" -#include namespace node { @@ -18,8 +18,8 @@ using v8::TracingController; namespace { static void PlatformWorkerThread(void* data) { - TRACE_EVENT_METADATA1("__metadata", "thread_name", "name", - "PlatformWorkerThread"); + TRACE_EVENT_METADATA1( + "__metadata", "thread_name", "name", "PlatformWorkerThread"); TaskQueue* pending_worker_tasks = static_cast*>(data); while (std::unique_ptr task = pending_worker_tasks->BlockingPop()) { task->Run(); @@ -31,9 +31,9 @@ static void PlatformWorkerThread(void* data) { WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) { for (int i = 0; i < thread_pool_size; i++) { - std::unique_ptr t { new uv_thread_t() }; - if (uv_thread_create(t.get(), PlatformWorkerThread, - &pending_worker_tasks_) != 0) { + std::unique_ptr t{new uv_thread_t()}; + if (uv_thread_create( + t.get(), PlatformWorkerThread, &pending_worker_tasks_) != 0) { break; } threads_.push_back(std::move(t)); @@ -64,9 +64,9 @@ int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const { return threads_.size(); } -PerIsolatePlatformData::PerIsolatePlatformData( - v8::Isolate* isolate, uv_loop_t* loop) - : loop_(loop) { +PerIsolatePlatformData::PerIsolatePlatformData(v8::Isolate* isolate, + uv_loop_t* loop) + : loop_(loop) { flush_tasks_ = new uv_async_t(); CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks)); flush_tasks_->data = static_cast(this); @@ -88,8 +88,8 @@ void PerIsolatePlatformData::PostTask(std::unique_ptr task) { uv_async_send(flush_tasks_); } -void PerIsolatePlatformData::PostDelayedTask( - std::unique_ptr task, double delay_in_seconds) { +void PerIsolatePlatformData::PostDelayedTask(std::unique_ptr task, + double delay_in_seconds) { CHECK_NE(flush_tasks_, nullptr); std::unique_ptr delayed(new DelayedTask()); delayed->task = std::move(task); @@ -104,16 +104,16 @@ PerIsolatePlatformData::~PerIsolatePlatformData() { } void PerIsolatePlatformData::Shutdown() { - if (flush_tasks_ == nullptr) - return; + if (flush_tasks_ == nullptr) return; - while (FlushForegroundTasksInternal()) {} + while (FlushForegroundTasksInternal()) { + } CancelPendingDelayedTasks(); uv_close(reinterpret_cast(flush_tasks_), [](uv_handle_t* handle) { - delete reinterpret_cast(handle); - }); + delete reinterpret_cast(handle); + }); flush_tasks_ = nullptr; } @@ -178,8 +178,8 @@ void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr task) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Environment* env = Environment::GetCurrent(isolate); - InternalCallbackScope cb_scope(env, Local(), { 0, 0 }, - InternalCallbackScope::kAllowEmptyResource); + InternalCallbackScope cb_scope( + env, Local(), {0, 0}, InternalCallbackScope::kAllowEmptyResource); task->Run(); } @@ -187,8 +187,8 @@ void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) { auto it = std::find_if(scheduled_delayed_tasks_.begin(), scheduled_delayed_tasks_.end(), [task](const DelayedTaskPointer& delayed) -> bool { - return delayed.get() == task; - }); + return delayed.get() == task; + }); CHECK_NE(it, scheduled_delayed_tasks_.end()); scheduled_delayed_tasks_.erase(it); } @@ -216,7 +216,7 @@ bool PerIsolatePlatformData::FlushForegroundTasksInternal() { bool did_work = false; while (std::unique_ptr delayed = - foreground_delayed_tasks_.Pop()) { + foreground_delayed_tasks_.Pop()) { did_work = true; uint64_t delay_millis = static_cast(delayed->timeout + 0.5) * 1000; @@ -227,13 +227,13 @@ bool PerIsolatePlatformData::FlushForegroundTasksInternal() { uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0); uv_unref(reinterpret_cast(&delayed->timer)); - scheduled_delayed_tasks_.emplace_back(delayed.release(), - [](DelayedTask* delayed) { - uv_close(reinterpret_cast(&delayed->timer), - [](uv_handle_t* handle) { - delete static_cast(handle->data); - }); - }); + scheduled_delayed_tasks_.emplace_back( + delayed.release(), [](DelayedTask* delayed) { + uv_close(reinterpret_cast(&delayed->timer), + [](uv_handle_t* handle) { + delete static_cast(handle->data); + }); + }); } // Move all foreground tasks into a separate queue and flush that queue. // This way tasks that are posted while flushing the queue will be run on the @@ -258,9 +258,8 @@ void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr task, delay_in_seconds); } - -std::shared_ptr -NodePlatform::ForIsolate(Isolate* isolate) { +std::shared_ptr NodePlatform::ForIsolate( + Isolate* isolate) { Mutex::ScopedLock lock(per_isolate_mutex_); std::shared_ptr data = per_isolate_[isolate]; CHECK(data); @@ -274,8 +273,8 @@ void NodePlatform::CallOnForegroundThread(Isolate* isolate, Task* task) { void NodePlatform::CallDelayedOnForegroundThread(Isolate* isolate, Task* task, double delay_in_seconds) { - ForIsolate(isolate)->PostDelayedTask( - std::unique_ptr(task), delay_in_seconds); + ForIsolate(isolate)->PostDelayedTask(std::unique_ptr(task), + delay_in_seconds); } bool NodePlatform::FlushForegroundTasks(v8::Isolate* isolate) { @@ -286,10 +285,12 @@ void NodePlatform::CancelPendingDelayedTasks(v8::Isolate* isolate) { ForIsolate(isolate)->CancelPendingDelayedTasks(); } -bool NodePlatform::IdleTasksEnabled(Isolate* isolate) { return false; } +bool NodePlatform::IdleTasksEnabled(Isolate* isolate) { + return false; +} -std::shared_ptr -NodePlatform::GetForegroundTaskRunner(Isolate* isolate) { +std::shared_ptr NodePlatform::GetForegroundTaskRunner( + Isolate* isolate) { return ForIsolate(isolate); } @@ -308,8 +309,12 @@ TracingController* NodePlatform::GetTracingController() { template TaskQueue::TaskQueue() - : lock_(), tasks_available_(), tasks_drained_(), - outstanding_tasks_(0), stopped_(false), task_queue_() { } + : lock_(), + tasks_available_(), + tasks_drained_(), + outstanding_tasks_(0), + stopped_(false), + task_queue_() {} template void TaskQueue::Push(std::unique_ptr task) { diff --git a/src/node_platform.h b/src/node_platform.h index 62301a302b22e0..9121d07cd60153 100644 --- a/src/node_platform.h +++ b/src/node_platform.h @@ -1,10 +1,10 @@ #ifndef SRC_NODE_PLATFORM_H_ #define SRC_NODE_PLATFORM_H_ +#include #include #include #include -#include #include "libplatform/libplatform.h" #include "node.h" @@ -48,9 +48,9 @@ struct DelayedTask { }; // This acts as the foreground task runner for a given Isolate. -class PerIsolatePlatformData : - public v8::TaskRunner, - public std::enable_shared_from_this { +class PerIsolatePlatformData + : public v8::TaskRunner, + public std::enable_shared_from_this { public: PerIsolatePlatformData(v8::Isolate* isolate, uv_loop_t* loop); ~PerIsolatePlatformData(); @@ -99,8 +99,7 @@ class WorkerThreadsTaskRunner { explicit WorkerThreadsTaskRunner(int thread_pool_size); void PostTask(std::unique_ptr task); - void PostDelayedTask(std::unique_ptr task, - double delay_in_seconds); + void PostDelayedTask(std::unique_ptr task, double delay_in_seconds); void BlockingDrain(); void Shutdown(); @@ -127,7 +126,8 @@ class NodePlatform : public MultiIsolatePlatform { void CallDelayedOnWorkerThread(std::unique_ptr task, double delay_in_seconds) override; void CallOnForegroundThread(v8::Isolate* isolate, v8::Task* task) override; - void CallDelayedOnForegroundThread(v8::Isolate* isolate, v8::Task* task, + void CallDelayedOnForegroundThread(v8::Isolate* isolate, + v8::Task* task, double delay_in_seconds) override; bool IdleTasksEnabled(v8::Isolate* isolate) override; double MonotonicallyIncreasingTime() override; @@ -145,8 +145,8 @@ class NodePlatform : public MultiIsolatePlatform { std::shared_ptr ForIsolate(v8::Isolate* isolate); Mutex per_isolate_mutex_; - std::unordered_map> per_isolate_; + std::unordered_map> + per_isolate_; std::unique_ptr tracing_controller_; std::shared_ptr worker_thread_task_runner_; diff --git a/src/node_postmortem_metadata.cc b/src/node_postmortem_metadata.cc index 93bf5a4dd7d8f4..3b1885b600be4b 100644 --- a/src/node_postmortem_metadata.cc +++ b/src/node_postmortem_metadata.cc @@ -1,46 +1,60 @@ -#include "env.h" #include "base_object-inl.h" +#include "env.h" #include "handle_wrap.h" -#include "util-inl.h" +#include "node_context_data.h" #include "req_wrap.h" +#include "util-inl.h" #include "v8abbr.h" -#include "node_context_data.h" -#define NODEDBG_SYMBOL(Name) nodedbg_ ## Name +#define NODEDBG_SYMBOL(Name) nodedbg_##Name // nodedbg_offset_CLASS__MEMBER__TYPE: Describes the offset to a class member. -#define NODEDBG_OFFSET(Class, Member, Type) \ - NODEDBG_SYMBOL(offset_ ## Class ## __ ## Member ## __ ## Type) +#define NODEDBG_OFFSET(Class, Member, Type) \ + NODEDBG_SYMBOL(offset_##Class##__##Member##__##Type) // These are the constants describing Node internal structures. Every constant // should use the format described above. These constants are declared as // global integers so that they'll be present in the generated node binary. They // also need to be declared outside any namespace to avoid C++ name-mangling. -#define NODE_OFFSET_POSTMORTEM_METADATA(V) \ - V(BaseObject, persistent_handle_, v8_Persistent_v8_Object, \ - BaseObject::persistent_handle_) \ - V(Environment, handle_wrap_queue_, Environment_HandleWrapQueue, \ - Environment::handle_wrap_queue_) \ - V(Environment, req_wrap_queue_, Environment_ReqWrapQueue, \ - Environment::req_wrap_queue_) \ - V(HandleWrap, handle_wrap_queue_, ListNode_HandleWrap, \ - HandleWrap::handle_wrap_queue_) \ - V(Environment_HandleWrapQueue, head_, ListNode_HandleWrap, \ - Environment::HandleWrapQueue::head_) \ - V(ListNode_HandleWrap, next_, uintptr_t, ListNode::next_) \ - V(ReqWrap, req_wrap_queue_, ListNode_ReqWrapQueue, \ - ReqWrap::req_wrap_queue_) \ - V(Environment_ReqWrapQueue, head_, ListNode_ReqWrapQueue, \ - Environment::ReqWrapQueue::head_) \ +#define NODE_OFFSET_POSTMORTEM_METADATA(V) \ + V(BaseObject, \ + persistent_handle_, \ + v8_Persistent_v8_Object, \ + BaseObject::persistent_handle_) \ + V(Environment, \ + handle_wrap_queue_, \ + Environment_HandleWrapQueue, \ + Environment::handle_wrap_queue_) \ + V(Environment, \ + req_wrap_queue_, \ + Environment_ReqWrapQueue, \ + Environment::req_wrap_queue_) \ + V(HandleWrap, \ + handle_wrap_queue_, \ + ListNode_HandleWrap, \ + HandleWrap::handle_wrap_queue_) \ + V(Environment_HandleWrapQueue, \ + head_, \ + ListNode_HandleWrap, \ + Environment::HandleWrapQueue::head_) \ + V(ListNode_HandleWrap, next_, uintptr_t, ListNode::next_) \ + V(ReqWrap, \ + req_wrap_queue_, \ + ListNode_ReqWrapQueue, \ + ReqWrap::req_wrap_queue_) \ + V(Environment_ReqWrapQueue, \ + head_, \ + ListNode_ReqWrapQueue, \ + Environment::ReqWrapQueue::head_) \ V(ListNode_ReqWrap, next_, uintptr_t, ListNode>::next_) extern "C" { int nodedbg_const_ContextEmbedderIndex__kEnvironment__int; uintptr_t nodedbg_offset_ExternalString__data__uintptr_t; -#define V(Class, Member, Type, Accessor) \ +#define V(Class, Member, Type, Accessor) \ NODE_EXTERN uintptr_t NODEDBG_OFFSET(Class, Member, Type); - NODE_OFFSET_POSTMORTEM_METADATA(V) +NODE_OFFSET_POSTMORTEM_METADATA(V) #undef V } @@ -52,10 +66,10 @@ int GenDebugSymbols() { nodedbg_offset_ExternalString__data__uintptr_t = NODE_OFF_EXTSTR_DATA; - #define V(Class, Member, Type, Accessor) \ - NODEDBG_OFFSET(Class, Member, Type) = OffsetOf(&Accessor); - NODE_OFFSET_POSTMORTEM_METADATA(V) - #undef V +#define V(Class, Member, Type, Accessor) \ + NODEDBG_OFFSET(Class, Member, Type) = OffsetOf(&Accessor); + NODE_OFFSET_POSTMORTEM_METADATA(V) +#undef V return 1; } diff --git a/src/node_process.cc b/src/node_process.cc index d816c32f8dd298..93de75075167dc 100644 --- a/src/node_process.cc +++ b/src/node_process.cc @@ -1,6 +1,6 @@ +#include "env-inl.h" #include "node.h" #include "node_internals.h" -#include "env-inl.h" #include "util-inl.h" #include "uv.h" #include "v8.h" @@ -16,13 +16,13 @@ typedef int mode_t; #else #include #include // getrlimit, setrlimit -#include // tcgetattr, tcsetattr -#include // setuid, getuid +#include // tcgetattr, tcsetattr +#include // setuid, getuid #endif #if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__) -#include // getpwnam() #include // getgrnam() +#include // getpwnam() #endif namespace node { @@ -109,17 +109,15 @@ void Cwd(const FunctionCallbackInfo& args) { char buf[CHDIR_BUFSIZE]; size_t cwd_len = sizeof(buf); int err = uv_cwd(buf, &cwd_len); - if (err) - return env->ThrowUVException(err, "uv_cwd"); + if (err) return env->ThrowUVException(err, "uv_cwd"); - Local cwd = String::NewFromUtf8(env->isolate(), - buf, - v8::NewStringType::kNormal, - cwd_len).ToLocalChecked(); + Local cwd = + String::NewFromUtf8( + env->isolate(), buf, v8::NewStringType::kNormal, cwd_len) + .ToLocalChecked(); args.GetReturnValue().Set(cwd); } - // Hrtime exposes libuv's uv_hrtime() high-resolution timer. // This is the legacy version of hrtime before BigInt was introduced in @@ -151,8 +149,7 @@ void HrtimeBigInt(const FunctionCallbackInfo& args) { void Kill(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - if (args.Length() != 2) - return env->ThrowError("Bad argument."); + if (args.Length() != 2) return env->ThrowError("Bad argument."); int pid = args[0]->Int32Value(); int sig = args[1]->Int32Value(); @@ -160,14 +157,12 @@ void Kill(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } - void MemoryUsage(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); size_t rss; int err = uv_resident_set_memory(&rss); - if (err) - return env->ThrowUVException(err, "uv_resident_set_memory"); + if (err) return env->ThrowUVException(err, "uv_resident_set_memory"); Isolate* isolate = env->isolate(); // V8 memory usage @@ -204,7 +199,6 @@ void StartProfilerIdleNotifier(const FunctionCallbackInfo& args) { env->StartProfilerIdleNotifier(); } - void StopProfilerIdleNotifier(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); env->StopProfilerIdleNotifier(); @@ -237,13 +231,11 @@ void Uptime(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(Number::New(env->isolate(), uptime / 1000)); } - #if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__) static const uid_t uid_not_found = static_cast(-1); static const gid_t gid_not_found = static_cast(-1); - static uid_t uid_by_name(const char* name) { struct passwd pwd; struct passwd* pp; @@ -258,7 +250,6 @@ static uid_t uid_by_name(const char* name) { return uid_not_found; } - static char* name_by_uid(uid_t uid) { struct passwd pwd; struct passwd* pp; @@ -273,13 +264,11 @@ static char* name_by_uid(uid_t uid) { return strdup(pp->pw_name); } - if (rc == 0) - errno = ENOENT; + if (rc == 0) errno = ENOENT; return nullptr; } - static gid_t gid_by_name(const char* name) { struct group pwd; struct group* pp; @@ -294,7 +283,6 @@ static gid_t gid_by_name(const char* name) { return gid_not_found; } - #if 0 // For future use. static const char* name_by_gid(gid_t gid) { struct group pwd; @@ -317,7 +305,6 @@ static const char* name_by_gid(gid_t gid) { } #endif - static uid_t uid_by_name(Isolate* isolate, Local value) { if (value->IsUint32()) { return static_cast(value->Uint32Value()); @@ -327,7 +314,6 @@ static uid_t uid_by_name(Isolate* isolate, Local value) { } } - static gid_t gid_by_name(Isolate* isolate, Local value) { if (value->IsUint32()) { return static_cast(value->Uint32Value()); @@ -342,25 +328,21 @@ void GetUid(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(static_cast(getuid())); } - void GetGid(const FunctionCallbackInfo& args) { // gid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(getgid())); } - void GetEUid(const FunctionCallbackInfo& args) { // uid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(geteuid())); } - void GetEGid(const FunctionCallbackInfo& args) { // gid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(getegid())); } - void SetGid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(env->is_main_thread()); @@ -380,7 +362,6 @@ void SetGid(const FunctionCallbackInfo& args) { } } - void SetEGid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(env->is_main_thread()); @@ -400,7 +381,6 @@ void SetEGid(const FunctionCallbackInfo& args) { } } - void SetUid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(env->is_main_thread()); @@ -420,7 +400,6 @@ void SetUid(const FunctionCallbackInfo& args) { } } - void SetEUid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(env->is_main_thread()); @@ -440,14 +419,12 @@ void SetEUid(const FunctionCallbackInfo& args) { } } - void GetGroups(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); int ngroups = getgroups(0, nullptr); - if (ngroups == -1) - return env->ThrowErrnoException(errno, "getgroups"); + if (ngroups == -1) return env->ThrowErrnoException(errno, "getgroups"); gid_t* groups = new gid_t[ngroups]; @@ -464,8 +441,7 @@ void GetGroups(const FunctionCallbackInfo& args) { for (int i = 0; i < ngroups; i++) { groups_list->Set(i, Integer::New(env->isolate(), groups[i])); - if (groups[i] == egid) - seen_egid = true; + if (groups[i] == egid) seen_egid = true; } delete[] groups; @@ -476,7 +452,6 @@ void GetGroups(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(groups_list); } - void SetGroups(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -503,13 +478,11 @@ void SetGroups(const FunctionCallbackInfo& args) { int rc = setgroups(size, groups); delete[] groups; - if (rc == -1) - return env->ThrowErrnoException(errno, "setgroups"); + if (rc == -1) return env->ThrowErrnoException(errno, "setgroups"); args.GetReturnValue().Set(0); } - void InitGroups(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -538,19 +511,16 @@ void InitGroups(const FunctionCallbackInfo& args) { extra_group = gid_by_name(env->isolate(), args[1]); if (extra_group == gid_not_found) { - if (must_free) - free(user); + if (must_free) free(user); // Tells JS to throw ERR_INVALID_CREDENTIAL return args.GetReturnValue().Set(2); } int rc = initgroups(user, extra_group); - if (must_free) - free(user); + if (must_free) free(user); - if (rc) - return env->ThrowErrnoException(errno, "initgroups"); + if (rc) return env->ThrowErrnoException(errno, "initgroups"); args.GetReturnValue().Set(0); } diff --git a/src/node_revert.h b/src/node_revert.h index c5963afeafd027..bb9ef92dd9e061 100644 --- a/src/node_revert.h +++ b/src/node_revert.h @@ -27,7 +27,9 @@ enum reversion { extern unsigned int reverted; inline const char* RevertMessage(const reversion cve) { -#define V(code, label, msg) case SECURITY_REVERT_##code: return label ": " msg; +#define V(code, label, msg) \ + case SECURITY_REVERT_##code: \ + return label ": " msg; switch (cve) { SECURITY_REVERSIONS(V) default: @@ -42,7 +44,7 @@ inline void Revert(const reversion cve) { } inline void Revert(const char* cve) { -#define V(code, label, _) \ +#define V(code, label, _) \ if (strcmp(cve, label) == 0) return Revert(SECURITY_REVERT_##code); SECURITY_REVERSIONS(V) #undef V @@ -55,7 +57,7 @@ inline bool IsReverted(const reversion cve) { } inline bool IsReverted(const char* cve) { -#define V(code, label, _) \ +#define V(code, label, _) \ if (strcmp(cve, label) == 0) return IsReverted(SECURITY_REVERT_##code); SECURITY_REVERSIONS(V) return false; diff --git a/src/node_serdes.cc b/src/node_serdes.cc index 5de0ddd81909b0..dad96f11078444 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -1,7 +1,7 @@ -#include "node_internals.h" +#include "base_object-inl.h" #include "node_buffer.h" #include "node_errors.h" -#include "base_object-inl.h" +#include "node_internals.h" namespace node { @@ -27,11 +27,9 @@ using v8::ValueSerializer; namespace { -class SerializerContext : public BaseObject, - public ValueSerializer::Delegate { +class SerializerContext : public BaseObject, public ValueSerializer::Delegate { public: - SerializerContext(Environment* env, - Local wrap); + SerializerContext(Environment* env, Local wrap); ~SerializerContext() {} @@ -98,24 +96,20 @@ class DeserializerContext : public BaseObject, }; SerializerContext::SerializerContext(Environment* env, Local wrap) - : BaseObject(env, wrap), - serializer_(env->isolate(), this) { + : BaseObject(env, wrap), serializer_(env->isolate(), this) { MakeWeak(); } void SerializerContext::ThrowDataCloneError(Local message) { - Local args[1] = { message }; + Local args[1] = {message}; Local get_data_clone_error = - object()->Get(env()->context(), - env()->get_data_clone_error_string()) - .ToLocalChecked(); + object() + ->Get(env()->context(), env()->get_data_clone_error_string()) + .ToLocalChecked(); CHECK(get_data_clone_error->IsFunction()); - MaybeLocal error = - get_data_clone_error.As()->Call(env()->context(), - object(), - arraysize(args), - args); + MaybeLocal error = get_data_clone_error.As()->Call( + env()->context(), object(), arraysize(args), args); if (error.IsEmpty()) return; @@ -124,22 +118,19 @@ void SerializerContext::ThrowDataCloneError(Local message) { Maybe SerializerContext::GetSharedArrayBufferId( Isolate* isolate, Local shared_array_buffer) { - Local args[1] = { shared_array_buffer }; + Local args[1] = {shared_array_buffer}; Local get_shared_array_buffer_id = - object()->Get(env()->context(), - env()->get_shared_array_buffer_id_string()) - .ToLocalChecked(); + object() + ->Get(env()->context(), env()->get_shared_array_buffer_id_string()) + .ToLocalChecked(); if (!get_shared_array_buffer_id->IsFunction()) { return ValueSerializer::Delegate::GetSharedArrayBufferId( isolate, shared_array_buffer); } - MaybeLocal id = - get_shared_array_buffer_id.As()->Call(env()->context(), - object(), - arraysize(args), - args); + MaybeLocal id = get_shared_array_buffer_id.As()->Call( + env()->context(), object(), arraysize(args), args); if (id.IsEmpty()) return Nothing(); @@ -149,23 +140,21 @@ Maybe SerializerContext::GetSharedArrayBufferId( Maybe SerializerContext::WriteHostObject(Isolate* isolate, Local input) { MaybeLocal ret; - Local args[1] = { input }; + Local args[1] = {input}; Local write_host_object = - object()->Get(env()->context(), - env()->write_host_object_string()).ToLocalChecked(); + object() + ->Get(env()->context(), env()->write_host_object_string()) + .ToLocalChecked(); if (!write_host_object->IsFunction()) { return ValueSerializer::Delegate::WriteHostObject(isolate, input); } - ret = write_host_object.As()->Call(env()->context(), - object(), - arraysize(args), - args); + ret = write_host_object.As()->Call( + env()->context(), object(), arraysize(args), args); - if (ret.IsEmpty()) - return Nothing(); + if (ret.IsEmpty()) return Nothing(); return Just(true); } @@ -185,8 +174,7 @@ void SerializerContext::WriteHeader(const FunctionCallbackInfo& args) { void SerializerContext::WriteValue(const FunctionCallbackInfo& args) { SerializerContext* ctx; ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder()); - Maybe ret = - ctx->serializer_.WriteValue(ctx->env()->context(), args[0]); + Maybe ret = ctx->serializer_.WriteValue(ctx->env()->context(), args[0]); if (ret.IsJust()) args.GetReturnValue().Set(ret.FromJust()); } @@ -206,9 +194,8 @@ void SerializerContext::ReleaseBuffer(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder()); std::pair ret = ctx->serializer_.Release(); - auto buf = Buffer::New(ctx->env(), - reinterpret_cast(ret.first), - ret.second); + auto buf = + Buffer::New(ctx->env(), reinterpret_cast(ret.first), ret.second); if (!buf.IsEmpty()) { args.GetReturnValue().Set(buf.ToLocalChecked()); @@ -248,8 +235,7 @@ void SerializerContext::WriteUint64(const FunctionCallbackInfo& args) { Maybe arg0 = args[0]->Uint32Value(ctx->env()->context()); Maybe arg1 = args[1]->Uint32Value(ctx->env()->context()); - if (arg0.IsNothing() || arg1.IsNothing()) - return; + if (arg0.IsNothing() || arg1.IsNothing()) return; uint64_t hi = arg0.FromJust(); uint64_t lo = arg1.FromJust(); @@ -271,8 +257,8 @@ void SerializerContext::WriteRawBytes(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder()); if (!args[0]->IsUint8Array()) { - return node::THROW_ERR_INVALID_ARG_TYPE( - ctx->env(), "source must be a Uint8Array"); + return node::THROW_ERR_INVALID_ARG_TYPE(ctx->env(), + "source must be a Uint8Array"); } ctx->serializer_.WriteRawBytes(Buffer::Data(args[0]), @@ -282,10 +268,10 @@ void SerializerContext::WriteRawBytes(const FunctionCallbackInfo& args) { DeserializerContext::DeserializerContext(Environment* env, Local wrap, Local buffer) - : BaseObject(env, wrap), - data_(reinterpret_cast(Buffer::Data(buffer))), - length_(Buffer::Length(buffer)), - deserializer_(env->isolate(), data_, length_, this) { + : BaseObject(env, wrap), + data_(reinterpret_cast(Buffer::Data(buffer))), + length_(Buffer::Length(buffer)), + deserializer_(env->isolate(), data_, length_, this) { object()->Set(env->context(), env->buffer_string(), buffer).FromJust(); MakeWeak(); @@ -293,21 +279,18 @@ DeserializerContext::DeserializerContext(Environment* env, MaybeLocal DeserializerContext::ReadHostObject(Isolate* isolate) { Local read_host_object = - object()->Get(env()->context(), - env()->read_host_object_string()).ToLocalChecked(); + object() + ->Get(env()->context(), env()->read_host_object_string()) + .ToLocalChecked(); if (!read_host_object->IsFunction()) { return ValueDeserializer::Delegate::ReadHostObject(isolate); } - MaybeLocal ret = - read_host_object.As()->Call(env()->context(), - object(), - 0, - nullptr); + MaybeLocal ret = read_host_object.As()->Call( + env()->context(), object(), 0, nullptr); - if (ret.IsEmpty()) - return MaybeLocal(); + if (ret.IsEmpty()) return MaybeLocal(); Local return_value = ret.ToLocalChecked(); if (!return_value->IsObject()) { @@ -322,8 +305,7 @@ void DeserializerContext::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsUint8Array()) { - return node::THROW_ERR_INVALID_ARG_TYPE( - env, "buffer must be a Uint8Array"); + return node::THROW_ERR_INVALID_ARG_TYPE(env, "buffer must be a Uint8Array"); } new DeserializerContext(env, args.This(), args[0]); @@ -454,9 +436,8 @@ void Initialize(Local target, env->SetProtoMethod(ser, "writeHeader", SerializerContext::WriteHeader); env->SetProtoMethod(ser, "writeValue", SerializerContext::WriteValue); env->SetProtoMethod(ser, "releaseBuffer", SerializerContext::ReleaseBuffer); - env->SetProtoMethod(ser, - "transferArrayBuffer", - SerializerContext::TransferArrayBuffer); + env->SetProtoMethod( + ser, "transferArrayBuffer", SerializerContext::TransferArrayBuffer); env->SetProtoMethod(ser, "writeUint32", SerializerContext::WriteUint32); env->SetProtoMethod(ser, "writeUint64", SerializerContext::WriteUint64); env->SetProtoMethod(ser, "writeDouble", SerializerContext::WriteDouble); @@ -468,9 +449,11 @@ void Initialize(Local target, Local serializerString = FIXED_ONE_BYTE_STRING(env->isolate(), "Serializer"); ser->SetClassName(serializerString); - target->Set(env->context(), - serializerString, - ser->GetFunction(env->context()).ToLocalChecked()).FromJust(); + target + ->Set(env->context(), + serializerString, + ser->GetFunction(env->context()).ToLocalChecked()) + .FromJust(); Local des = env->NewFunctionTemplate(DeserializerContext::New); @@ -479,12 +462,10 @@ void Initialize(Local target, env->SetProtoMethod(des, "readHeader", DeserializerContext::ReadHeader); env->SetProtoMethod(des, "readValue", DeserializerContext::ReadValue); - env->SetProtoMethod(des, - "getWireFormatVersion", - DeserializerContext::GetWireFormatVersion); - env->SetProtoMethod(des, - "transferArrayBuffer", - DeserializerContext::TransferArrayBuffer); + env->SetProtoMethod( + des, "getWireFormatVersion", DeserializerContext::GetWireFormatVersion); + env->SetProtoMethod( + des, "transferArrayBuffer", DeserializerContext::TransferArrayBuffer); env->SetProtoMethod(des, "readUint32", DeserializerContext::ReadUint32); env->SetProtoMethod(des, "readUint64", DeserializerContext::ReadUint64); env->SetProtoMethod(des, "readDouble", DeserializerContext::ReadDouble); @@ -493,9 +474,11 @@ void Initialize(Local target, Local deserializerString = FIXED_ONE_BYTE_STRING(env->isolate(), "Deserializer"); des->SetClassName(deserializerString); - target->Set(env->context(), - deserializerString, - des->GetFunction(env->context()).ToLocalChecked()).FromJust(); + target + ->Set(env->context(), + deserializerString, + des->GetFunction(env->context()).ToLocalChecked()) + .FromJust(); } } // anonymous namespace diff --git a/src/node_stat_watcher.cc b/src/node_stat_watcher.cc index 5e47476fd97a0c..ff751e36be55f3 100644 --- a/src/node_stat_watcher.cc +++ b/src/node_stat_watcher.cc @@ -20,13 +20,13 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_stat_watcher.h" -#include "node_internals.h" #include "async_wrap-inl.h" #include "env-inl.h" +#include "node_internals.h" #include "util-inl.h" -#include #include +#include namespace node { @@ -41,7 +41,6 @@ using v8::String; using v8::Uint32; using v8::Value; - void StatWatcher::Initialize(Environment* env, Local target) { HandleScope scope(env->isolate()); @@ -59,10 +58,7 @@ void StatWatcher::Initialize(Environment* env, Local target) { target->Set(statWatcherString, t->GetFunction()); } - -StatWatcher::StatWatcher(Environment* env, - Local wrap, - bool use_bigint) +StatWatcher::StatWatcher(Environment* env, Local wrap, bool use_bigint) : HandleWrap(env, wrap, reinterpret_cast(&watcher_), @@ -71,7 +67,6 @@ StatWatcher::StatWatcher(Environment* env, CHECK_EQ(0, uv_fs_poll_init(env->event_loop(), &watcher_)); } - void StatWatcher::Callback(uv_fs_poll_t* handle, int status, const uv_stat_t* prev, @@ -81,19 +76,14 @@ void StatWatcher::Callback(uv_fs_poll_t* handle, HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); - Local arr = node::FillGlobalStatsArray(env, curr, - wrap->use_bigint_); - node::FillGlobalStatsArray(env, prev, wrap->use_bigint_, - env->kFsStatsFieldsLength); + Local arr = node::FillGlobalStatsArray(env, curr, wrap->use_bigint_); + node::FillGlobalStatsArray( + env, prev, wrap->use_bigint_, env->kFsStatsFieldsLength); - Local argv[2] { - Integer::New(env->isolate(), status), - arr - }; + Local argv[2]{Integer::New(env->isolate(), status), arr}; wrap->MakeCallback(env->onchange_string(), arraysize(argv), argv); } - void StatWatcher::New(const FunctionCallbackInfo& args) { CHECK(args.IsConstructCall()); Environment* env = Environment::GetCurrent(args); diff --git a/src/node_stat_watcher.h b/src/node_stat_watcher.h index 33c90ad3cde737..28de3824685629 100644 --- a/src/node_stat_watcher.h +++ b/src/node_stat_watcher.h @@ -24,9 +24,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" -#include "handle_wrap.h" #include "env.h" +#include "handle_wrap.h" +#include "node.h" #include "uv.h" #include "v8.h" @@ -37,9 +37,7 @@ class StatWatcher : public HandleWrap { static void Initialize(Environment* env, v8::Local target); protected: - StatWatcher(Environment* env, - v8::Local wrap, - bool use_bigint); + StatWatcher(Environment* env, v8::Local wrap, bool use_bigint); static void New(const v8::FunctionCallbackInfo& args); static void Start(const v8::FunctionCallbackInfo& args); diff --git a/src/node_trace_events.cc b/src/node_trace_events.cc index 684ea41a66cc58..36021626529556 100644 --- a/src/node_trace_events.cc +++ b/src/node_trace_events.cc @@ -1,8 +1,8 @@ +#include "base_object-inl.h" +#include "env.h" #include "node.h" #include "node_internals.h" #include "tracing/agent.h" -#include "env.h" -#include "base_object-inl.h" #include #include @@ -37,8 +37,8 @@ class NodeCategorySet : public BaseObject { private: NodeCategorySet(Environment* env, Local wrap, - std::set categories) : - BaseObject(env, wrap), categories_(categories) { + std::set categories) + : BaseObject(env, wrap), categories_(categories) { MakeWeak(); } @@ -88,10 +88,10 @@ void GetEnabledCategories(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); std::string categories = env->tracing_agent()->GetEnabledCategories(); if (!categories.empty()) { - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - categories.c_str(), - v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), + categories.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()); } } @@ -133,7 +133,7 @@ static void Emit(const FunctionCallbackInfo& args) { // enabled. const char* category_group = GetCategoryGroup(env, args[1]); const uint8_t* category_group_enabled = - GetCategoryGroupEnabled(category_group); + GetCategoryGroupEnabled(category_group); if (*category_group_enabled == 0) return; // get trace_event phase @@ -201,10 +201,17 @@ static void Emit(const FunctionCallbackInfo& args) { const char* scope = node::tracing::kGlobalScope; uint64_t bind_id = node::tracing::kNoId; - TRACE_EVENT_API_ADD_TRACE_EVENT( - phase, category_group_enabled, name, scope, id, bind_id, - num_args, arg_names, arg_types, arg_values, - flags); + TRACE_EVENT_API_ADD_TRACE_EVENT(phase, + category_group_enabled, + name, + scope, + id, + bind_id, + num_args, + arg_names, + arg_types, + arg_values, + flags); } static void CategoryGroupEnabled(const FunctionCallbackInfo& args) { @@ -212,7 +219,7 @@ static void CategoryGroupEnabled(const FunctionCallbackInfo& args) { const char* category_group = GetCategoryGroup(env, args[0]); const uint8_t* category_group_enabled = - GetCategoryGroupEnabled(category_group); + GetCategoryGroupEnabled(category_group); args.GetReturnValue().Set(*category_group_enabled > 0); } @@ -242,11 +249,13 @@ void Initialize(Local target, // Grab the trace and isTraceCategoryEnabled intrinsics from the binding // object and expose those to our binding layer. Local binding = context->GetExtrasBindingObject(); - target->Set(context, isTraceCategoryEnabled, - binding->Get(context, isTraceCategoryEnabled).ToLocalChecked()) - .FromJust(); - target->Set(context, trace, - binding->Get(context, trace).ToLocalChecked()).FromJust(); + target + ->Set(context, + isTraceCategoryEnabled, + binding->Get(context, isTraceCategoryEnabled).ToLocalChecked()) + .FromJust(); + target->Set(context, trace, binding->Get(context, trace).ToLocalChecked()) + .FromJust(); } } // namespace node diff --git a/src/node_types.cc b/src/node_types.cc index 4872491c924989..7a54c40314d313 100644 --- a/src/node_types.cc +++ b/src/node_types.cc @@ -9,46 +9,45 @@ using v8::Value; namespace node { namespace { -#define VALUE_METHOD_MAP(V) \ - V(External) \ - V(Date) \ - V(ArgumentsObject) \ - V(BigIntObject) \ - V(BooleanObject) \ - V(NumberObject) \ - V(StringObject) \ - V(SymbolObject) \ - V(NativeError) \ - V(RegExp) \ - V(AsyncFunction) \ - V(GeneratorFunction) \ - V(GeneratorObject) \ - V(Promise) \ - V(Map) \ - V(Set) \ - V(MapIterator) \ - V(SetIterator) \ - V(WeakMap) \ - V(WeakSet) \ - V(ArrayBuffer) \ - V(DataView) \ - V(SharedArrayBuffer) \ - V(Proxy) \ - V(WebAssemblyCompiledModule) \ - V(ModuleNamespaceObject) \ +#define VALUE_METHOD_MAP(V) \ + V(External) \ + V(Date) \ + V(ArgumentsObject) \ + V(BigIntObject) \ + V(BooleanObject) \ + V(NumberObject) \ + V(StringObject) \ + V(SymbolObject) \ + V(NativeError) \ + V(RegExp) \ + V(AsyncFunction) \ + V(GeneratorFunction) \ + V(GeneratorObject) \ + V(Promise) \ + V(Map) \ + V(Set) \ + V(MapIterator) \ + V(SetIterator) \ + V(WeakMap) \ + V(WeakSet) \ + V(ArrayBuffer) \ + V(DataView) \ + V(SharedArrayBuffer) \ + V(Proxy) \ + V(WebAssemblyCompiledModule) \ + V(ModuleNamespaceObject) - -#define V(type) \ - static void Is##type(const FunctionCallbackInfo& args) { \ - args.GetReturnValue().Set(args[0]->Is##type()); \ +#define V(type) \ + static void Is##type(const FunctionCallbackInfo& args) { \ + args.GetReturnValue().Set(args[0]->Is##type()); \ } - VALUE_METHOD_MAP(V) +VALUE_METHOD_MAP(V) #undef V static void IsAnyArrayBuffer(const FunctionCallbackInfo& args) { - args.GetReturnValue().Set( - args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer()); + args.GetReturnValue().Set(args[0]->IsArrayBuffer() || + args[0]->IsSharedArrayBuffer()); } void InitializeTypes(Local target, @@ -56,9 +55,7 @@ void InitializeTypes(Local target, Local context) { Environment* env = Environment::GetCurrent(context); -#define V(type) env->SetMethodNoSideEffect(target, \ - "is" #type, \ - Is##type); +#define V(type) env->SetMethodNoSideEffect(target, "is" #type, Is##type); VALUE_METHOD_MAP(V) #undef V diff --git a/src/node_url.cc b/src/node_url.cc index 1cdb179ed254f5..3cd1f874980482 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -1,12 +1,12 @@ #include "node_url.h" -#include "node_internals.h" #include "base_object-inl.h" #include "node_i18n.h" +#include "node_internals.h" -#include -#include #include #include +#include +#include namespace node { @@ -28,10 +28,9 @@ using v8::Undefined; using v8::Value; inline Local Utf8String(Isolate* isolate, const std::string& str) { - return String::NewFromUtf8(isolate, - str.data(), - v8::NewStringType::kNormal, - str.length()).ToLocalChecked(); + return String::NewFromUtf8( + isolate, str.data(), v8::NewStringType::kNormal, str.length()) + .ToLocalChecked(); } namespace url { @@ -107,13 +106,13 @@ class URLHost { inline void SetOpaque(std::string&& string) { Reset(); type_ = HostType::H_OPAQUE; - new(&value_.domain_or_opaque) std::string(std::move(string)); + new (&value_.domain_or_opaque) std::string(std::move(string)); } inline void SetDomain(std::string&& string) { Reset(); type_ = HostType::H_DOMAIN; - new(&value_.domain_or_opaque) std::string(std::move(string)); + new (&value_.domain_or_opaque) std::string(std::move(string)); } }; @@ -121,21 +120,21 @@ URLHost::~URLHost() { Reset(); } -#define ARGS(XX) \ - XX(ARG_FLAGS) \ - XX(ARG_PROTOCOL) \ - XX(ARG_USERNAME) \ - XX(ARG_PASSWORD) \ - XX(ARG_HOST) \ - XX(ARG_PORT) \ - XX(ARG_PATH) \ - XX(ARG_QUERY) \ - XX(ARG_FRAGMENT) \ +#define ARGS(XX) \ + XX(ARG_FLAGS) \ + XX(ARG_PROTOCOL) \ + XX(ARG_USERNAME) \ + XX(ARG_PASSWORD) \ + XX(ARG_HOST) \ + XX(ARG_PORT) \ + XX(ARG_PATH) \ + XX(ARG_QUERY) \ + XX(ARG_FRAGMENT) \ XX(ARG_COUNT) // This one has to be last. -#define ERR_ARGS(XX) \ - XX(ERR_ARG_FLAGS) \ - XX(ERR_ARG_INPUT) \ +#define ERR_ARGS(XX) \ + XX(ERR_ARG_FLAGS) \ + XX(ERR_ARG_INPUT) enum url_cb_args { #define XX(name) name, @@ -149,26 +148,26 @@ enum url_error_cb_args { #undef XX }; -#define CHAR_TEST(bits, name, expr) \ - template \ - inline bool name(const T ch) { \ - static_assert(sizeof(ch) >= (bits) / 8, \ - "Character must be wider than " #bits " bits"); \ - return (expr); \ +#define CHAR_TEST(bits, name, expr) \ + template \ + inline bool name(const T ch) { \ + static_assert(sizeof(ch) >= (bits) / 8, \ + "Character must be wider than " #bits " bits"); \ + return (expr); \ } -#define TWO_CHAR_STRING_TEST(bits, name, expr) \ - template \ - inline bool name(const T ch1, const T ch2) { \ - static_assert(sizeof(ch1) >= (bits) / 8, \ - "Character must be wider than " #bits " bits"); \ - return (expr); \ - } \ - template \ - inline bool name(const std::basic_string& str) { \ - static_assert(sizeof(str[0]) >= (bits) / 8, \ - "Character must be wider than " #bits " bits"); \ - return str.length() >= 2 && name(str[0], str[1]); \ +#define TWO_CHAR_STRING_TEST(bits, name, expr) \ + template \ + inline bool name(const T ch1, const T ch2) { \ + static_assert(sizeof(ch1) >= (bits) / 8, \ + "Character must be wider than " #bits " bits"); \ + return (expr); \ + } \ + template \ + inline bool name(const std::basic_string& str) { \ + static_assert(sizeof(str[0]) >= (bits) / 8, \ + "Character must be wider than " #bits " bits"); \ + return str.length() >= 2 && name(str[0], str[1]); \ } // https://infra.spec.whatwg.org/#ascii-tab-or-newline @@ -181,13 +180,15 @@ CHAR_TEST(8, IsC0ControlOrSpace, (ch >= '\0' && ch <= ' ')) CHAR_TEST(8, IsASCIIDigit, (ch >= '0' && ch <= '9')) // https://infra.spec.whatwg.org/#ascii-hex-digit -CHAR_TEST(8, IsASCIIHexDigit, (IsASCIIDigit(ch) || - (ch >= 'A' && ch <= 'F') || - (ch >= 'a' && ch <= 'f'))) +CHAR_TEST(8, + IsASCIIHexDigit, + (IsASCIIDigit(ch) || (ch >= 'A' && ch <= 'F') || + (ch >= 'a' && ch <= 'f'))) // https://infra.spec.whatwg.org/#ascii-alpha -CHAR_TEST(8, IsASCIIAlpha, ((ch >= 'A' && ch <= 'Z') || - (ch >= 'a' && ch <= 'z'))) +CHAR_TEST(8, + IsASCIIAlpha, + ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) // https://infra.spec.whatwg.org/#ascii-alphanumeric CHAR_TEST(8, IsASCIIAlphanumeric, (IsASCIIDigit(ch) || IsASCIIAlpha(ch))) @@ -199,18 +200,20 @@ inline T ASCIILowercase(T ch) { } // https://url.spec.whatwg.org/#forbidden-host-code-point -CHAR_TEST(8, IsForbiddenHostCodePoint, - ch == '\0' || ch == '\t' || ch == '\n' || ch == '\r' || - ch == ' ' || ch == '#' || ch == '%' || ch == '/' || - ch == ':' || ch == '?' || ch == '@' || ch == '[' || - ch == '\\' || ch == ']') +CHAR_TEST(8, + IsForbiddenHostCodePoint, + ch == '\0' || ch == '\t' || ch == '\n' || ch == '\r' || ch == ' ' || + ch == '#' || ch == '%' || ch == '/' || ch == ':' || ch == '?' || + ch == '@' || ch == '[' || ch == '\\' || ch == ']') // https://url.spec.whatwg.org/#windows-drive-letter -TWO_CHAR_STRING_TEST(8, IsWindowsDriveLetter, +TWO_CHAR_STRING_TEST(8, + IsWindowsDriveLetter, (IsASCIIAlpha(ch1) && (ch2 == ':' || ch2 == '|'))) // https://url.spec.whatwg.org/#normalized-windows-drive-letter -TWO_CHAR_STRING_TEST(8, IsNormalizedWindowsDriveLetter, +TWO_CHAR_STRING_TEST(8, + IsNormalizedWindowsDriveLetter, (IsASCIIAlpha(ch1) && ch2 == ':')) // If a UTF-16 character is a low/trailing surrogate. @@ -226,375 +229,360 @@ CHAR_TEST(16, IsUnicodeSurrogateTrail, (ch & 0x400) != 0) #undef TWO_CHAR_STRING_TEST const char* hex[256] = { - "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", - "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F", - "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", - "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", - "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", - "%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F", - "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", - "%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", - "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47", - "%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F", - "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", - "%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F", - "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", - "%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F", - "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", - "%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F", - "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87", - "%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F", - "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", - "%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F", - "%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7", - "%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF", - "%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7", - "%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF", - "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7", - "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF", - "%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7", - "%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF", - "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7", - "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF", - "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7", - "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF" -}; + "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0A", + "%0B", "%0C", "%0D", "%0E", "%0F", "%10", "%11", "%12", "%13", "%14", "%15", + "%16", "%17", "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%20", + "%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29", "%2A", "%2B", + "%2C", "%2D", "%2E", "%2F", "%30", "%31", "%32", "%33", "%34", "%35", "%36", + "%37", "%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%40", "%41", + "%42", "%43", "%44", "%45", "%46", "%47", "%48", "%49", "%4A", "%4B", "%4C", + "%4D", "%4E", "%4F", "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", + "%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F", "%60", "%61", "%62", + "%63", "%64", "%65", "%66", "%67", "%68", "%69", "%6A", "%6B", "%6C", "%6D", + "%6E", "%6F", "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", "%78", + "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F", "%80", "%81", "%82", "%83", + "%84", "%85", "%86", "%87", "%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", + "%8F", "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", "%98", "%99", + "%9A", "%9B", "%9C", "%9D", "%9E", "%9F", "%A0", "%A1", "%A2", "%A3", "%A4", + "%A5", "%A6", "%A7", "%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF", + "%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7", "%B8", "%B9", "%BA", + "%BB", "%BC", "%BD", "%BE", "%BF", "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", + "%C6", "%C7", "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF", "%D0", + "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7", "%D8", "%D9", "%DA", "%DB", + "%DC", "%DD", "%DE", "%DF", "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", + "%E7", "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF", "%F0", "%F1", + "%F2", "%F3", "%F4", "%F5", "%F6", "%F7", "%F8", "%F9", "%FA", "%FB", "%FC", + "%FD", "%FE", "%FF"}; const uint8_t C0_CONTROL_ENCODE_SET[32] = { - // 00 01 02 03 04 05 06 07 + // 00 01 02 03 04 05 06 07 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 08 09 0A 0B 0C 0D 0E 0F + // 08 09 0A 0B 0C 0D 0E 0F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 10 11 12 13 14 15 16 17 + // 10 11 12 13 14 15 16 17 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 18 19 1A 1B 1C 1D 1E 1F + // 18 19 1A 1B 1C 1D 1E 1F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 20 21 22 23 24 25 26 27 + // 20 21 22 23 24 25 26 27 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 28 29 2A 2B 2C 2D 2E 2F + // 28 29 2A 2B 2C 2D 2E 2F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 30 31 32 33 34 35 36 37 + // 30 31 32 33 34 35 36 37 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 38 39 3A 3B 3C 3D 3E 3F + // 38 39 3A 3B 3C 3D 3E 3F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 40 41 42 43 44 45 46 47 + // 40 41 42 43 44 45 46 47 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 48 49 4A 4B 4C 4D 4E 4F + // 48 49 4A 4B 4C 4D 4E 4F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 50 51 52 53 54 55 56 57 + // 50 51 52 53 54 55 56 57 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 58 59 5A 5B 5C 5D 5E 5F + // 58 59 5A 5B 5C 5D 5E 5F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 60 61 62 63 64 65 66 67 + // 60 61 62 63 64 65 66 67 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 68 69 6A 6B 6C 6D 6E 6F + // 68 69 6A 6B 6C 6D 6E 6F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 70 71 72 73 74 75 76 77 + // 70 71 72 73 74 75 76 77 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 78 79 7A 7B 7C 7D 7E 7F + // 78 79 7A 7B 7C 7D 7E 7F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80, - // 80 81 82 83 84 85 86 87 + // 80 81 82 83 84 85 86 87 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 88 89 8A 8B 8C 8D 8E 8F + // 88 89 8A 8B 8C 8D 8E 8F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 90 91 92 93 94 95 96 97 + // 90 91 92 93 94 95 96 97 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 98 99 9A 9B 9C 9D 9E 9F + // 98 99 9A 9B 9C 9D 9E 9F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A0 A1 A2 A3 A4 A5 A6 A7 + // A0 A1 A2 A3 A4 A5 A6 A7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A8 A9 AA AB AC AD AE AF + // A8 A9 AA AB AC AD AE AF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B0 B1 B2 B3 B4 B5 B6 B7 + // B0 B1 B2 B3 B4 B5 B6 B7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B8 B9 BA BB BC BD BE BF + // B8 B9 BA BB BC BD BE BF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C0 C1 C2 C3 C4 C5 C6 C7 + // C0 C1 C2 C3 C4 C5 C6 C7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C8 C9 CA CB CC CD CE CF + // C8 C9 CA CB CC CD CE CF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D0 D1 D2 D3 D4 D5 D6 D7 + // D0 D1 D2 D3 D4 D5 D6 D7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D8 D9 DA DB DC DD DE DF + // D8 D9 DA DB DC DD DE DF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E0 E1 E2 E3 E4 E5 E6 E7 + // E0 E1 E2 E3 E4 E5 E6 E7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E8 E9 EA EB EC ED EE EF + // E8 E9 EA EB EC ED EE EF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F0 F1 F2 F3 F4 F5 F6 F7 + // F0 F1 F2 F3 F4 F5 F6 F7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F8 F9 FA FB FC FD FE FF - 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80 -}; + // F8 F9 FA FB FC FD FE FF + 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80}; const uint8_t FRAGMENT_ENCODE_SET[32] = { - // 00 01 02 03 04 05 06 07 + // 00 01 02 03 04 05 06 07 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 08 09 0A 0B 0C 0D 0E 0F + // 08 09 0A 0B 0C 0D 0E 0F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 10 11 12 13 14 15 16 17 + // 10 11 12 13 14 15 16 17 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 18 19 1A 1B 1C 1D 1E 1F + // 18 19 1A 1B 1C 1D 1E 1F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 20 21 22 23 24 25 26 27 + // 20 21 22 23 24 25 26 27 0x01 | 0x00 | 0x04 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 28 29 2A 2B 2C 2D 2E 2F + // 28 29 2A 2B 2C 2D 2E 2F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 30 31 32 33 34 35 36 37 + // 30 31 32 33 34 35 36 37 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 38 39 3A 3B 3C 3D 3E 3F + // 38 39 3A 3B 3C 3D 3E 3F 0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00, - // 40 41 42 43 44 45 46 47 + // 40 41 42 43 44 45 46 47 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 48 49 4A 4B 4C 4D 4E 4F + // 48 49 4A 4B 4C 4D 4E 4F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 50 51 52 53 54 55 56 57 + // 50 51 52 53 54 55 56 57 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 58 59 5A 5B 5C 5D 5E 5F + // 58 59 5A 5B 5C 5D 5E 5F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 60 61 62 63 64 65 66 67 + // 60 61 62 63 64 65 66 67 0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 68 69 6A 6B 6C 6D 6E 6F + // 68 69 6A 6B 6C 6D 6E 6F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 70 71 72 73 74 75 76 77 + // 70 71 72 73 74 75 76 77 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 78 79 7A 7B 7C 7D 7E 7F + // 78 79 7A 7B 7C 7D 7E 7F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80, - // 80 81 82 83 84 85 86 87 + // 80 81 82 83 84 85 86 87 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 88 89 8A 8B 8C 8D 8E 8F + // 88 89 8A 8B 8C 8D 8E 8F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 90 91 92 93 94 95 96 97 + // 90 91 92 93 94 95 96 97 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 98 99 9A 9B 9C 9D 9E 9F + // 98 99 9A 9B 9C 9D 9E 9F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A0 A1 A2 A3 A4 A5 A6 A7 + // A0 A1 A2 A3 A4 A5 A6 A7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A8 A9 AA AB AC AD AE AF + // A8 A9 AA AB AC AD AE AF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B0 B1 B2 B3 B4 B5 B6 B7 + // B0 B1 B2 B3 B4 B5 B6 B7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B8 B9 BA BB BC BD BE BF + // B8 B9 BA BB BC BD BE BF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C0 C1 C2 C3 C4 C5 C6 C7 + // C0 C1 C2 C3 C4 C5 C6 C7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C8 C9 CA CB CC CD CE CF + // C8 C9 CA CB CC CD CE CF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D0 D1 D2 D3 D4 D5 D6 D7 + // D0 D1 D2 D3 D4 D5 D6 D7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D8 D9 DA DB DC DD DE DF + // D8 D9 DA DB DC DD DE DF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E0 E1 E2 E3 E4 E5 E6 E7 + // E0 E1 E2 E3 E4 E5 E6 E7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E8 E9 EA EB EC ED EE EF + // E8 E9 EA EB EC ED EE EF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F0 F1 F2 F3 F4 F5 F6 F7 + // F0 F1 F2 F3 F4 F5 F6 F7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F8 F9 FA FB FC FD FE FF - 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80 -}; - + // F8 F9 FA FB FC FD FE FF + 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80}; const uint8_t PATH_ENCODE_SET[32] = { - // 00 01 02 03 04 05 06 07 + // 00 01 02 03 04 05 06 07 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 08 09 0A 0B 0C 0D 0E 0F + // 08 09 0A 0B 0C 0D 0E 0F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 10 11 12 13 14 15 16 17 + // 10 11 12 13 14 15 16 17 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 18 19 1A 1B 1C 1D 1E 1F + // 18 19 1A 1B 1C 1D 1E 1F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 20 21 22 23 24 25 26 27 + // 20 21 22 23 24 25 26 27 0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00, - // 28 29 2A 2B 2C 2D 2E 2F + // 28 29 2A 2B 2C 2D 2E 2F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 30 31 32 33 34 35 36 37 + // 30 31 32 33 34 35 36 37 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 38 39 3A 3B 3C 3D 3E 3F + // 38 39 3A 3B 3C 3D 3E 3F 0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x80, - // 40 41 42 43 44 45 46 47 + // 40 41 42 43 44 45 46 47 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 48 49 4A 4B 4C 4D 4E 4F + // 48 49 4A 4B 4C 4D 4E 4F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 50 51 52 53 54 55 56 57 + // 50 51 52 53 54 55 56 57 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 58 59 5A 5B 5C 5D 5E 5F + // 58 59 5A 5B 5C 5D 5E 5F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 60 61 62 63 64 65 66 67 + // 60 61 62 63 64 65 66 67 0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 68 69 6A 6B 6C 6D 6E 6F + // 68 69 6A 6B 6C 6D 6E 6F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 70 71 72 73 74 75 76 77 + // 70 71 72 73 74 75 76 77 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 78 79 7A 7B 7C 7D 7E 7F + // 78 79 7A 7B 7C 7D 7E 7F 0x00 | 0x00 | 0x00 | 0x08 | 0x00 | 0x20 | 0x00 | 0x80, - // 80 81 82 83 84 85 86 87 + // 80 81 82 83 84 85 86 87 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 88 89 8A 8B 8C 8D 8E 8F + // 88 89 8A 8B 8C 8D 8E 8F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 90 91 92 93 94 95 96 97 + // 90 91 92 93 94 95 96 97 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 98 99 9A 9B 9C 9D 9E 9F + // 98 99 9A 9B 9C 9D 9E 9F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A0 A1 A2 A3 A4 A5 A6 A7 + // A0 A1 A2 A3 A4 A5 A6 A7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A8 A9 AA AB AC AD AE AF + // A8 A9 AA AB AC AD AE AF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B0 B1 B2 B3 B4 B5 B6 B7 + // B0 B1 B2 B3 B4 B5 B6 B7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B8 B9 BA BB BC BD BE BF + // B8 B9 BA BB BC BD BE BF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C0 C1 C2 C3 C4 C5 C6 C7 + // C0 C1 C2 C3 C4 C5 C6 C7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C8 C9 CA CB CC CD CE CF + // C8 C9 CA CB CC CD CE CF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D0 D1 D2 D3 D4 D5 D6 D7 + // D0 D1 D2 D3 D4 D5 D6 D7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D8 D9 DA DB DC DD DE DF + // D8 D9 DA DB DC DD DE DF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E0 E1 E2 E3 E4 E5 E6 E7 + // E0 E1 E2 E3 E4 E5 E6 E7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E8 E9 EA EB EC ED EE EF + // E8 E9 EA EB EC ED EE EF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F0 F1 F2 F3 F4 F5 F6 F7 + // F0 F1 F2 F3 F4 F5 F6 F7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F8 F9 FA FB FC FD FE FF - 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80 -}; + // F8 F9 FA FB FC FD FE FF + 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80}; const uint8_t USERINFO_ENCODE_SET[32] = { - // 00 01 02 03 04 05 06 07 + // 00 01 02 03 04 05 06 07 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 08 09 0A 0B 0C 0D 0E 0F + // 08 09 0A 0B 0C 0D 0E 0F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 10 11 12 13 14 15 16 17 + // 10 11 12 13 14 15 16 17 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 18 19 1A 1B 1C 1D 1E 1F + // 18 19 1A 1B 1C 1D 1E 1F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 20 21 22 23 24 25 26 27 + // 20 21 22 23 24 25 26 27 0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00, - // 28 29 2A 2B 2C 2D 2E 2F + // 28 29 2A 2B 2C 2D 2E 2F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80, - // 30 31 32 33 34 35 36 37 + // 30 31 32 33 34 35 36 37 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 38 39 3A 3B 3C 3D 3E 3F + // 38 39 3A 3B 3C 3D 3E 3F 0x00 | 0x00 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 40 41 42 43 44 45 46 47 + // 40 41 42 43 44 45 46 47 0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 48 49 4A 4B 4C 4D 4E 4F + // 48 49 4A 4B 4C 4D 4E 4F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 50 51 52 53 54 55 56 57 + // 50 51 52 53 54 55 56 57 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 58 59 5A 5B 5C 5D 5E 5F + // 58 59 5A 5B 5C 5D 5E 5F 0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x00, - // 60 61 62 63 64 65 66 67 + // 60 61 62 63 64 65 66 67 0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 68 69 6A 6B 6C 6D 6E 6F + // 68 69 6A 6B 6C 6D 6E 6F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 70 71 72 73 74 75 76 77 + // 70 71 72 73 74 75 76 77 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 78 79 7A 7B 7C 7D 7E 7F + // 78 79 7A 7B 7C 7D 7E 7F 0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x00 | 0x80, - // 80 81 82 83 84 85 86 87 + // 80 81 82 83 84 85 86 87 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 88 89 8A 8B 8C 8D 8E 8F + // 88 89 8A 8B 8C 8D 8E 8F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 90 91 92 93 94 95 96 97 + // 90 91 92 93 94 95 96 97 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 98 99 9A 9B 9C 9D 9E 9F + // 98 99 9A 9B 9C 9D 9E 9F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A0 A1 A2 A3 A4 A5 A6 A7 + // A0 A1 A2 A3 A4 A5 A6 A7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A8 A9 AA AB AC AD AE AF + // A8 A9 AA AB AC AD AE AF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B0 B1 B2 B3 B4 B5 B6 B7 + // B0 B1 B2 B3 B4 B5 B6 B7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B8 B9 BA BB BC BD BE BF + // B8 B9 BA BB BC BD BE BF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C0 C1 C2 C3 C4 C5 C6 C7 + // C0 C1 C2 C3 C4 C5 C6 C7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C8 C9 CA CB CC CD CE CF + // C8 C9 CA CB CC CD CE CF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D0 D1 D2 D3 D4 D5 D6 D7 + // D0 D1 D2 D3 D4 D5 D6 D7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D8 D9 DA DB DC DD DE DF + // D8 D9 DA DB DC DD DE DF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E0 E1 E2 E3 E4 E5 E6 E7 + // E0 E1 E2 E3 E4 E5 E6 E7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E8 E9 EA EB EC ED EE EF + // E8 E9 EA EB EC ED EE EF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F0 F1 F2 F3 F4 F5 F6 F7 + // F0 F1 F2 F3 F4 F5 F6 F7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F8 F9 FA FB FC FD FE FF - 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80 -}; + // F8 F9 FA FB FC FD FE FF + 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80}; const uint8_t QUERY_ENCODE_SET[32] = { - // 00 01 02 03 04 05 06 07 + // 00 01 02 03 04 05 06 07 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 08 09 0A 0B 0C 0D 0E 0F + // 08 09 0A 0B 0C 0D 0E 0F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 10 11 12 13 14 15 16 17 + // 10 11 12 13 14 15 16 17 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 18 19 1A 1B 1C 1D 1E 1F + // 18 19 1A 1B 1C 1D 1E 1F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 20 21 22 23 24 25 26 27 + // 20 21 22 23 24 25 26 27 0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00, - // 28 29 2A 2B 2C 2D 2E 2F + // 28 29 2A 2B 2C 2D 2E 2F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 30 31 32 33 34 35 36 37 + // 30 31 32 33 34 35 36 37 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 38 39 3A 3B 3C 3D 3E 3F + // 38 39 3A 3B 3C 3D 3E 3F 0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00, - // 40 41 42 43 44 45 46 47 + // 40 41 42 43 44 45 46 47 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 48 49 4A 4B 4C 4D 4E 4F + // 48 49 4A 4B 4C 4D 4E 4F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 50 51 52 53 54 55 56 57 + // 50 51 52 53 54 55 56 57 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 58 59 5A 5B 5C 5D 5E 5F + // 58 59 5A 5B 5C 5D 5E 5F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 60 61 62 63 64 65 66 67 + // 60 61 62 63 64 65 66 67 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 68 69 6A 6B 6C 6D 6E 6F + // 68 69 6A 6B 6C 6D 6E 6F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 70 71 72 73 74 75 76 77 + // 70 71 72 73 74 75 76 77 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00, - // 78 79 7A 7B 7C 7D 7E 7F + // 78 79 7A 7B 7C 7D 7E 7F 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80, - // 80 81 82 83 84 85 86 87 + // 80 81 82 83 84 85 86 87 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 88 89 8A 8B 8C 8D 8E 8F + // 88 89 8A 8B 8C 8D 8E 8F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 90 91 92 93 94 95 96 97 + // 90 91 92 93 94 95 96 97 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // 98 99 9A 9B 9C 9D 9E 9F + // 98 99 9A 9B 9C 9D 9E 9F 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A0 A1 A2 A3 A4 A5 A6 A7 + // A0 A1 A2 A3 A4 A5 A6 A7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // A8 A9 AA AB AC AD AE AF + // A8 A9 AA AB AC AD AE AF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B0 B1 B2 B3 B4 B5 B6 B7 + // B0 B1 B2 B3 B4 B5 B6 B7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // B8 B9 BA BB BC BD BE BF + // B8 B9 BA BB BC BD BE BF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C0 C1 C2 C3 C4 C5 C6 C7 + // C0 C1 C2 C3 C4 C5 C6 C7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // C8 C9 CA CB CC CD CE CF + // C8 C9 CA CB CC CD CE CF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D0 D1 D2 D3 D4 D5 D6 D7 + // D0 D1 D2 D3 D4 D5 D6 D7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // D8 D9 DA DB DC DD DE DF + // D8 D9 DA DB DC DD DE DF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E0 E1 E2 E3 E4 E5 E6 E7 + // E0 E1 E2 E3 E4 E5 E6 E7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // E8 E9 EA EB EC ED EE EF + // E8 E9 EA EB EC ED EE EF 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F0 F1 F2 F3 F4 F5 F6 F7 + // F0 F1 F2 F3 F4 F5 F6 F7 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, - // F8 F9 FA FB FC FD FE FF - 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80 -}; + // F8 F9 FA FB FC FD FE FF + 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80}; inline bool BitAt(const uint8_t a[], const uint8_t i) { return !!(a[i >> 3] & (1 << (i & 7))); @@ -613,19 +601,15 @@ inline void AppendOrEscape(std::string* str, template inline unsigned hex2bin(const T ch) { - if (ch >= '0' && ch <= '9') - return ch - '0'; - if (ch >= 'A' && ch <= 'F') - return 10 + (ch - 'A'); - if (ch >= 'a' && ch <= 'f') - return 10 + (ch - 'a'); + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'A' && ch <= 'F') return 10 + (ch - 'A'); + if (ch >= 'a' && ch <= 'f') return 10 + (ch - 'a'); return static_cast(-1); } inline std::string PercentDecode(const char* input, size_t len) { std::string dest; - if (len == 0) - return dest; + if (len == 0) return dest; dest.reserve(len); const char* pointer = input; const char* end = input + len; @@ -635,8 +619,7 @@ inline std::string PercentDecode(const char* input, size_t len) { const size_t remaining = end - pointer - 1; if (ch != '%' || remaining < 2 || (ch == '%' && - (!IsASCIIHexDigit(pointer[1]) || - !IsASCIIHexDigit(pointer[2])))) { + (!IsASCIIHexDigit(pointer[1]) || !IsASCIIHexDigit(pointer[2])))) { dest += ch; pointer++; continue; @@ -651,17 +634,18 @@ inline std::string PercentDecode(const char* input, size_t len) { return dest; } -#define SPECIALS(XX) \ - XX("ftp:", 21) \ - XX("file:", -1) \ - XX("gopher:", 70) \ - XX("http:", 80) \ - XX("https:", 443) \ - XX("ws:", 80) \ +#define SPECIALS(XX) \ + XX("ftp:", 21) \ + XX("file:", -1) \ + XX("gopher:", 70) \ + XX("http:", 80) \ + XX("https:", 443) \ + XX("ws:", 80) \ XX("wss:", 443) inline bool IsSpecial(const std::string& scheme) { -#define XX(name, _) if (scheme == name) return true; +#define XX(name, _) \ + if (scheme == name) return true; SPECIALS(XX); #undef XX return false; @@ -670,17 +654,14 @@ inline bool IsSpecial(const std::string& scheme) { // https://url.spec.whatwg.org/#start-with-a-windows-drive-letter inline bool StartsWithWindowsDriveLetter(const char* p, const char* end) { const size_t length = end - p; - return length >= 2 && - IsWindowsDriveLetter(p[0], p[1]) && - (length == 2 || - p[2] == '/' || - p[2] == '\\' || - p[2] == '?' || - p[2] == '#'); + return length >= 2 && IsWindowsDriveLetter(p[0], p[1]) && + (length == 2 || p[2] == '/' || p[2] == '\\' || p[2] == '?' || + p[2] == '#'); } inline int NormalizePort(const std::string& scheme, int p) { -#define XX(name, port) if (scheme == name && p == port) return -1; +#define XX(name, port) \ + if (scheme == name && p == port) return -1; SPECIALS(XX); #undef XX return p; @@ -689,16 +670,14 @@ inline int NormalizePort(const std::string& scheme, int p) { #if defined(NODE_HAVE_I18N_SUPPORT) inline bool ToUnicode(const std::string& input, std::string* output) { MaybeStackBuffer buf; - if (i18n::ToUnicode(&buf, input.c_str(), input.length()) < 0) - return false; + if (i18n::ToUnicode(&buf, input.c_str(), input.length()) < 0) return false; output->assign(*buf, buf.length()); return true; } inline bool ToASCII(const std::string& input, std::string* output) { MaybeStackBuffer buf; - if (i18n::ToASCII(&buf, input.c_str(), input.length()) < 0) - return false; + if (i18n::ToASCII(&buf, input.c_str(), input.length()) < 0) return false; output->assign(*buf, buf.length()); return true; } @@ -717,8 +696,7 @@ inline bool ToASCII(const std::string& input, std::string* output) { void URLHost::ParseIPv6Host(const char* input, size_t length) { CHECK_EQ(type_, HostType::H_FAILED); - for (unsigned n = 0; n < 8; n++) - value_.ipv6[n] = 0; + for (unsigned n = 0; n < 8; n++) value_.ipv6[n] = 0; uint16_t* piece_pointer = &value_.ipv6[0]; uint16_t* const buffer_end = piece_pointer + 8; uint16_t* compress_pointer = nullptr; @@ -727,19 +705,16 @@ void URLHost::ParseIPv6Host(const char* input, size_t length) { unsigned value, len, swaps, numbers_seen; char ch = pointer < end ? pointer[0] : kEOL; if (ch == ':') { - if (length < 2 || pointer[1] != ':') - return; + if (length < 2 || pointer[1] != ':') return; pointer += 2; ch = pointer < end ? pointer[0] : kEOL; piece_pointer++; compress_pointer = piece_pointer; } while (ch != kEOL) { - if (piece_pointer >= buffer_end) - return; + if (piece_pointer >= buffer_end) return; if (ch == ':') { - if (compress_pointer != nullptr) - return; + if (compress_pointer != nullptr) return; pointer++; ch = pointer < end ? pointer[0] : kEOL; piece_pointer++; @@ -756,12 +731,10 @@ void URLHost::ParseIPv6Host(const char* input, size_t length) { } switch (ch) { case '.': - if (len == 0) - return; + if (len == 0) return; pointer -= len; ch = pointer < end ? pointer[0] : kEOL; - if (piece_pointer > buffer_end - 2) - return; + if (piece_pointer > buffer_end - 2) return; numbers_seen = 0; while (ch != kEOL) { value = 0xffffffff; @@ -773,8 +746,7 @@ void URLHost::ParseIPv6Host(const char* input, size_t length) { return; } } - if (!IsASCIIDigit(ch)) - return; + if (!IsASCIIDigit(ch)) return; while (IsASCIIDigit(ch)) { unsigned number = ch - '0'; if (value == 0xffffffff) { @@ -784,24 +756,20 @@ void URLHost::ParseIPv6Host(const char* input, size_t length) { } else { value = value * 10 + number; } - if (value > 255) - return; + if (value > 255) return; pointer++; ch = pointer < end ? pointer[0] : kEOL; } *piece_pointer = *piece_pointer * 0x100 + value; numbers_seen++; - if (numbers_seen == 2 || numbers_seen == 4) - piece_pointer++; + if (numbers_seen == 2 || numbers_seen == 4) piece_pointer++; } - if (numbers_seen != 4) - return; + if (numbers_seen != 4) return; continue; case ':': pointer++; ch = pointer < end ? pointer[0] : kEOL; - if (ch == kEOL) - return; + if (ch == kEOL) return; break; case kEOL: break; @@ -820,11 +788,10 @@ void URLHost::ParseIPv6Host(const char* input, size_t length) { uint16_t* swap_piece = compress_pointer + swaps - 1; *piece_pointer = *swap_piece; *swap_piece = temp; - piece_pointer--; - swaps--; + piece_pointer--; + swaps--; } - } else if (compress_pointer == nullptr && - piece_pointer != buffer_end) { + } else if (compress_pointer == nullptr && piece_pointer != buffer_end) { return; } type_ = HostType::H_IPV6; @@ -848,16 +815,13 @@ inline int64_t ParseNumber(const char* start, const char* end) { const char ch = p[0]; switch (R) { case 8: - if (ch < '0' || ch > '7') - return -1; + if (ch < '0' || ch > '7') return -1; break; case 10: - if (!IsASCIIDigit(ch)) - return -1; + if (!IsASCIIDigit(ch)) return -1; break; case 16: - if (!IsASCIIHexDigit(ch)) - return -1; + if (!IsASCIIHexDigit(ch)) return -1; break; } p++; @@ -875,28 +839,23 @@ void URLHost::ParseIPv4Host(const char* input, size_t length, bool* is_ipv4) { uint32_t val = 0; uint64_t numbers[4]; int tooBigNumbers = 0; - if (length == 0) - return; + if (length == 0) return; while (pointer <= end) { const char ch = pointer < end ? pointer[0] : kEOL; const int remaining = end - pointer - 1; if (ch == '.' || ch == kEOL) { - if (++parts > 4) - return; - if (pointer == mark) - return; + if (++parts > 4) return; + if (pointer == mark) return; int64_t n = ParseNumber(mark, pointer); - if (n < 0) - return; + if (n < 0) return; if (n > 255) { tooBigNumbers++; } numbers[parts - 1] = n; mark = pointer + 1; - if (ch == '.' && remaining == 0) - break; + if (ch == '.' && remaining == 0) break; } pointer++; } @@ -906,8 +865,7 @@ void URLHost::ParseIPv4Host(const char* input, size_t length, bool* is_ipv4) { // If any but the last item in numbers is greater than 255, return failure. // If the last item in numbers is greater than or equal to // 256^(5 - the number of items in numbers), return failure. - if (tooBigNumbers > 1 || - (tooBigNumbers == 1 && numbers[parts - 1] <= 255) || + if (tooBigNumbers > 1 || (tooBigNumbers == 1 && numbers[parts - 1] <= 255) || numbers[parts - 1] >= pow(256, static_cast(5 - parts))) { return; } @@ -945,24 +903,20 @@ void URLHost::ParseHost(const char* input, CHECK_EQ(type_, HostType::H_FAILED); const char* pointer = input; - if (length == 0) - return; + if (length == 0) return; if (pointer[0] == '[') { - if (pointer[length - 1] != ']') - return; + if (pointer[length - 1] != ']') return; return ParseIPv6Host(++pointer, length - 2); } - if (!is_special) - return ParseOpaqueHost(input, length); + if (!is_special) return ParseOpaqueHost(input, length); // First, we have to percent decode std::string decoded = PercentDecode(input, length); // Then we have to punycode toASCII - if (!ToASCII(decoded, &decoded)) - return; + if (!ToASCII(decoded, &decoded)) return; // If any of the following characters are still present, we have to fail for (size_t n = 0; n < decoded.size(); n++) { @@ -975,12 +929,10 @@ void URLHost::ParseHost(const char* input, // Check to see if it's an IPv4 IP address bool is_ipv4; ParseIPv4Host(decoded.c_str(), decoded.length(), &is_ipv4); - if (is_ipv4) - return; + if (is_ipv4) return; // If the unicode flag is set, run the result through punycode ToUnicode - if (unicode && !ToUnicode(decoded, &decoded)) - return; + if (unicode && !ToUnicode(decoded, &decoded)) return; // It's not an IPv4 or IPv6 address, it must be a domain SetDomain(std::move(decoded)); @@ -999,8 +951,7 @@ inline T* FindLongestZeroSequence(T* values, size_t len) { while (start < end) { if (*start == 0) { - if (current == nullptr) - current = start; + if (current == nullptr) current = start; counter++; } else { if (counter > longest) { @@ -1012,8 +963,7 @@ inline T* FindLongestZeroSequence(T* values, size_t len) { } start++; } - if (counter > longest) - result = current; + if (counter > longest) result = current; return result; } @@ -1046,8 +996,7 @@ std::string URLHost::ToString() const { char buf[4]; snprintf(buf, sizeof(buf), "%d", value % 256); dest.insert(0, buf); - if (n < 3) - dest.insert(0, 1, '.'); + if (n < 3) dest.insert(0, 1, '.'); value /= 256; } break; @@ -1056,8 +1005,7 @@ std::string URLHost::ToString() const { dest.reserve(41); dest += '['; const uint16_t* start = &value_.ipv6[0]; - const uint16_t* compress_pointer = - FindLongestZeroSequence(start, 8); + const uint16_t* compress_pointer = FindLongestZeroSequence(start, 8); bool ignore0 = false; for (int n = 0; n <= 7; n++) { const uint16_t* piece = &value_.ipv6[n]; @@ -1073,8 +1021,7 @@ std::string URLHost::ToString() const { char buf[5]; snprintf(buf, sizeof(buf), "%x", *piece); dest += buf; - if (n < 7) - dest += ':'; + if (n < 7) dest += ':'; } dest += ']'; break; @@ -1095,8 +1042,7 @@ bool ParseHost(const std::string& input, } URLHost host; host.ParseHost(input.c_str(), input.length(), is_special, unicode); - if (host.ParsingFailed()) - return false; + if (host.ParsingFailed()) return false; *output = host.ToStringMove(); return true; } @@ -1105,8 +1051,7 @@ inline std::vector FromJSStringArray(Environment* env, Local array) { std::vector vec; const int32_t len = array->Length(); - if (len == 0) - return vec; // nothing to copy + if (len == 0) return vec; // nothing to copy vec.reserve(len); for (int32_t n = 0; n < len; n++) { Local val = array->Get(env->context(), n).ToLocalChecked(); @@ -1132,14 +1077,13 @@ inline url_data HarvestBase(Environment* env, Local base_obj) { Local context = env->context(); Local flags = base_obj->Get(env->context(), env->flags_string()).ToLocalChecked(); - if (flags->IsInt32()) - base.flags = flags->Int32Value(context).FromJust(); + if (flags->IsInt32()) base.flags = flags->Int32Value(context).FromJust(); Local scheme = base_obj->Get(env->context(), env->scheme_string()).ToLocalChecked(); base.scheme = Utf8Value(env->isolate(), scheme).out(); - auto GetStr = [&](std::string url_data::* member, + auto GetStr = [&](std::string url_data::*member, int flag, Local name) { Local value = base_obj->Get(env->context(), name).ToLocalChecked(); @@ -1157,11 +1101,10 @@ inline url_data HarvestBase(Environment* env, Local base_obj) { Local port = base_obj->Get(env->context(), env->port_string()).ToLocalChecked(); - if (port->IsInt32()) - base.port = port.As()->Value(); + if (port->IsInt32()) base.port = port.As()->Value(); - Local - path = base_obj->Get(env->context(), env->path_string()).ToLocalChecked(); + Local path = + base_obj->Get(env->context(), env->path_string()).ToLocalChecked(); if (path->IsArray()) { base.flags |= URL_FLAGS_HAS_PATH; base.path = FromJSStringArray(env, path.As()); @@ -1175,11 +1118,8 @@ inline url_data HarvestContext(Environment* env, Local context_obj) { context_obj->Get(env->context(), env->flags_string()).ToLocalChecked(); if (flags->IsInt32()) { static const int32_t copy_flags_mask = - URL_FLAGS_SPECIAL | - URL_FLAGS_CANNOT_BE_BASE | - URL_FLAGS_HAS_USERNAME | - URL_FLAGS_HAS_PASSWORD | - URL_FLAGS_HAS_HOST; + URL_FLAGS_SPECIAL | URL_FLAGS_CANNOT_BE_BASE | URL_FLAGS_HAS_USERNAME | + URL_FLAGS_HAS_PASSWORD | URL_FLAGS_HAS_HOST; context.flags |= flags.As()->Value() & copy_flags_mask; } Local scheme = @@ -1190,27 +1130,25 @@ inline url_data HarvestContext(Environment* env, Local context_obj) { } Local port = context_obj->Get(env->context(), env->port_string()).ToLocalChecked(); - if (port->IsInt32()) - context.port = port.As()->Value(); + if (port->IsInt32()) context.port = port.As()->Value(); if (context.flags & URL_FLAGS_HAS_USERNAME) { Local username = - context_obj->Get(env->context(), - env->username_string()).ToLocalChecked(); + context_obj->Get(env->context(), env->username_string()) + .ToLocalChecked(); CHECK(username->IsString()); Utf8Value value(env->isolate(), username); context.username.assign(*value, value.length()); } if (context.flags & URL_FLAGS_HAS_PASSWORD) { Local password = - context_obj->Get(env->context(), - env->password_string()).ToLocalChecked(); + context_obj->Get(env->context(), env->password_string()) + .ToLocalChecked(); CHECK(password->IsString()); Utf8Value value(env->isolate(), password); context.password.assign(*value, value.length()); } Local host = - context_obj->Get(env->context(), - env->host_string()).ToLocalChecked(); + context_obj->Get(env->context(), env->host_string()).ToLocalChecked(); if (host->IsString()) { Utf8Value value(env->isolate(), host); context.host.assign(*value, value.length()); @@ -1224,9 +1162,7 @@ inline bool IsSingleDotSegment(const std::string& str) { case 1: return str == "."; case 3: - return str[0] == '%' && - str[1] == '2' && - ASCIILowercase(str[2]) == 'e'; + return str[0] == '%' && str[1] == '2' && ASCIILowercase(str[2]) == 'e'; default: return false; } @@ -1240,23 +1176,14 @@ inline bool IsDoubleDotSegment(const std::string& str) { case 2: return str == ".."; case 4: - if (str[0] != '.' && str[0] != '%') - return false; - return ((str[0] == '.' && - str[1] == '%' && - str[2] == '2' && + if (str[0] != '.' && str[0] != '%') return false; + return ((str[0] == '.' && str[1] == '%' && str[2] == '2' && ASCIILowercase(str[3]) == 'e') || - (str[0] == '%' && - str[1] == '2' && - ASCIILowercase(str[2]) == 'e' && - str[3] == '.')); + (str[0] == '%' && str[1] == '2' && + ASCIILowercase(str[2]) == 'e' && str[3] == '.')); case 6: - return (str[0] == '%' && - str[1] == '2' && - ASCIILowercase(str[2]) == 'e' && - str[3] == '%' && - str[4] == '2' && - ASCIILowercase(str[5]) == 'e'); + return (str[0] == '%' && str[1] == '2' && ASCIILowercase(str[2]) == 'e' && + str[3] == '%' && str[4] == '2' && ASCIILowercase(str[5]) == 'e'); default: return false; } @@ -1265,7 +1192,8 @@ inline bool IsDoubleDotSegment(const std::string& str) { inline void ShortenUrlPath(struct url_data* url) { if (url->path.empty()) return; if (url->path.size() == 1 && url->scheme == "file:" && - IsNormalizedWindowsDriveLetter(url->path[0])) return; + IsNormalizedWindowsDriveLetter(url->path[0])) + return; url->path.pop_back(); } @@ -1302,16 +1230,14 @@ void URL::Parse(const char* input, // contents, but in the general case we avoid the overhead. std::string whitespace_stripped; for (const char* ptr = p; ptr < end; ptr++) { - if (!IsASCIITabOrNewline(*ptr)) - continue; + if (!IsASCIITabOrNewline(*ptr)) continue; // Hit tab or newline. Allocate storage, copy what we have until now, // and then iterate and filter all similar characters out. whitespace_stripped.reserve(len - 1); whitespace_stripped.assign(p, ptr - p); // 'ptr + 1' skips the current char, which we know to be tab or newline. for (ptr = ptr + 1; ptr < end; ptr++) { - if (!IsASCIITabOrNewline(*ptr)) - whitespace_stripped += *ptr; + if (!IsASCIITabOrNewline(*ptr)) whitespace_stripped += *ptr; } // Update variables like they should have looked like if the string @@ -1323,16 +1249,16 @@ void URL::Parse(const char* input, break; } - bool atflag = false; // Set when @ has been seen. - bool square_bracket_flag = false; // Set inside of [...] + bool atflag = false; // Set when @ has been seen. + bool square_bracket_flag = false; // Set inside of [...] bool password_token_seen_flag = false; // Set after a : after an username. std::string buffer; // Set the initial parse state. const bool has_state_override = state_override != kUnknownState; - enum url_parse_state state = has_state_override ? state_override : - kSchemeStart; + enum url_parse_state state = + has_state_override ? state_override : kSchemeStart; if (state < kSchemeStart || state > kFragment) { url->flags |= URL_FLAGS_INVALID_PARSE_STATE; @@ -1394,13 +1320,10 @@ void URL::Parse(const char* input, special = false; } buffer.clear(); - if (has_state_override) - return; + if (has_state_override) return; if (url->scheme == "file:") { state = kFile; - } else if (special && - has_base && - url->scheme == base->scheme) { + } else if (special && has_base && url->scheme == base->scheme) { state = kSpecialRelativeOrAuthority; } else if (special) { state = kSpecialAuthoritySlashes; @@ -1451,8 +1374,7 @@ void URL::Parse(const char* input, } url->flags |= URL_FLAGS_CANNOT_BE_BASE; state = kFragment; - } else if (has_base && - base->scheme != "file:") { + } else if (has_base && base->scheme != "file:") { state = kRelative; continue; } else { @@ -1651,10 +1573,7 @@ void URL::Parse(const char* input, } } buffer.clear(); - } else if (ch == kEOL || - ch == '/' || - ch == '?' || - ch == '#' || + } else if (ch == kEOL || ch == '/' || ch == '?' || ch == '#' || special_back_slash) { if (atflag && buffer.size() == 0) { url->flags |= URL_FLAGS_FAILED; @@ -1687,18 +1606,14 @@ void URL::Parse(const char* input, if (state_override == kHostname) { return; } - } else if (ch == kEOL || - ch == '/' || - ch == '?' || - ch == '#' || + } else if (ch == kEOL || ch == '/' || ch == '?' || ch == '#' || special_back_slash) { p--; if (special && buffer.size() == 0) { url->flags |= URL_FLAGS_FAILED; return; } - if (has_state_override && - buffer.size() == 0 && + if (has_state_override && buffer.size() == 0 && ((url->username.size() > 0 || url->password.size() > 0) || url->port != -1)) { url->flags |= URL_FLAGS_TERMINATED; @@ -1715,22 +1630,16 @@ void URL::Parse(const char* input, return; } } else { - if (ch == '[') - square_bracket_flag = true; - if (ch == ']') - square_bracket_flag = false; + if (ch == '[') square_bracket_flag = true; + if (ch == ']') square_bracket_flag = false; buffer += ch; } break; case kPort: if (IsASCIIDigit(ch)) { buffer += ch; - } else if (has_state_override || - ch == kEOL || - ch == '/' || - ch == '?' || - ch == '#' || - special_back_slash) { + } else if (has_state_override || ch == kEOL || ch == '/' || ch == '?' || + ch == '#' || special_back_slash) { if (buffer.size() > 0) { unsigned port = 0; // the condition port <= 0xffff prevents integer overflow @@ -1749,8 +1658,7 @@ void URL::Parse(const char* input, } // the port is valid url->port = NormalizePort(url->scheme, static_cast(port)); - if (url->port == -1) - url->flags |= URL_FLAGS_IS_DEFAULT_SCHEME_PORT; + if (url->port == -1) url->flags |= URL_FLAGS_IS_DEFAULT_SCHEME_PORT; buffer.clear(); } else if (has_state_override) { // TODO(TimothyGu): Similar case as above. @@ -1841,8 +1749,7 @@ void URL::Parse(const char* input, if (ch == '/' || ch == '\\') { state = kFileHost; } else { - if (has_base && - base->scheme == "file:" && + if (has_base && base->scheme == "file:" && !StartsWithWindowsDriveLetter(p, end)) { if (IsNormalizedWindowsDriveLetter(base->path[0])) { url->flags |= URL_FLAGS_HAS_PATH; @@ -1862,20 +1769,14 @@ void URL::Parse(const char* input, } break; case kFileHost: - if (ch == kEOL || - ch == '/' || - ch == '\\' || - ch == '?' || - ch == '#') { - if (!has_state_override && - buffer.size() == 2 && + if (ch == kEOL || ch == '/' || ch == '\\' || ch == '?' || ch == '#') { + if (!has_state_override && buffer.size() == 2 && IsWindowsDriveLetter(buffer)) { state = kPath; } else if (buffer.size() == 0) { url->flags |= URL_FLAGS_HAS_HOST; url->host.clear(); - if (has_state_override) - return; + if (has_state_override) return; state = kPathStart; } else { std::string host; @@ -1883,12 +1784,10 @@ void URL::Parse(const char* input, url->flags |= URL_FLAGS_FAILED; return; } - if (host == "localhost") - host.clear(); + if (host == "localhost") host.clear(); url->flags |= URL_FLAGS_HAS_HOST; url->host = host; - if (has_state_override) - return; + if (has_state_override) return; buffer.clear(); state = kPathStart; } @@ -1919,9 +1818,7 @@ void URL::Parse(const char* input, } break; case kPath: - if (ch == kEOL || - ch == '/' || - special_back_slash || + if (ch == kEOL || ch == '/' || special_back_slash || (!has_state_override && (ch == '?' || ch == '#'))) { if (IsDoubleDotSegment(buffer)) { ShortenUrlPath(url); @@ -1929,17 +1826,14 @@ void URL::Parse(const char* input, url->flags |= URL_FLAGS_HAS_PATH; url->path.emplace_back(""); } - } else if (IsSingleDotSegment(buffer) && - ch != '/' && !special_back_slash) { + } else if (IsSingleDotSegment(buffer) && ch != '/' && + !special_back_slash) { url->flags |= URL_FLAGS_HAS_PATH; url->path.emplace_back(""); } else if (!IsSingleDotSegment(buffer)) { - if (url->scheme == "file:" && - url->path.empty() && - buffer.size() == 2 && - IsWindowsDriveLetter(buffer)) { - if ((url->flags & URL_FLAGS_HAS_HOST) && - !url->host.empty()) { + if (url->scheme == "file:" && url->path.empty() && + buffer.size() == 2 && IsWindowsDriveLetter(buffer)) { + if ((url->flags & URL_FLAGS_HAS_HOST) && !url->host.empty()) { url->host.clear(); url->flags |= URL_FLAGS_HAS_HOST; } @@ -1950,9 +1844,7 @@ void URL::Parse(const char* input, } buffer.clear(); if (url->scheme == "file:" && - (ch == kEOL || - ch == '?' || - ch == '#')) { + (ch == kEOL || ch == '?' || ch == '#')) { while (url->path.size() > 1 && url->path[0].length() == 0) { url->path.erase(url->path.begin()); } @@ -1976,8 +1868,7 @@ void URL::Parse(const char* input, state = kFragment; break; default: - if (url->path.size() == 0) - url->path.push_back(""); + if (url->path.size() == 0) url->path.push_back(""); if (url->path.size() > 0 && ch != kEOL) AppendOrEscape(&url->path[0], ch, C0_CONTROL_ENCODE_SET); } @@ -1987,8 +1878,7 @@ void URL::Parse(const char* input, url->flags |= URL_FLAGS_HAS_QUERY; url->query = std::move(buffer); buffer.clear(); - if (ch == '#') - state = kFragment; + if (ch == '#') state = kFragment; } else { AppendOrEscape(&buffer, ch, QUERY_ENCODE_SET); } @@ -2030,8 +1920,7 @@ static inline void SetArgs(Environment* env, argv[ARG_QUERY] = Utf8String(isolate, url.query); if (url.flags & URL_FLAGS_HAS_FRAGMENT) argv[ARG_FRAGMENT] = Utf8String(isolate, url.fragment); - if (url.port > -1) - argv[ARG_PORT] = Integer::New(isolate, url.port); + if (url.port > -1) argv[ARG_PORT] = Integer::New(isolate, url.port); if (url.flags & URL_FLAGS_HAS_PATH) argv[ARG_PATH] = ToJSStringArray(env, url.path); } @@ -2055,15 +1944,12 @@ static void Parse(Environment* env, url_data base; url_data url; - if (has_context) - url = HarvestContext(env, context_obj.As()); - if (has_base) - base = HarvestBase(env, base_obj.As()); + if (has_context) url = HarvestContext(env, context_obj.As()); + if (has_base) base = HarvestBase(env, base_obj.As()); URL::Parse(input, len, state_override, &url, has_context, &base, has_base); if ((url.flags & URL_FLAGS_INVALID_PARSE_STATE) || - ((state_override != kUnknownState) && - (url.flags & URL_FLAGS_TERMINATED))) + ((state_override != kUnknownState) && (url.flags & URL_FLAGS_TERMINATED))) return; // Define the return value placeholders @@ -2071,26 +1957,26 @@ static void Parse(Environment* env, const Local null = Null(isolate); if (!(url.flags & URL_FLAGS_FAILED)) { Local argv[] = { - undef, - undef, - undef, - undef, - null, // host defaults to null - null, // port defaults to null - undef, - null, // query defaults to null - null, // fragment defaults to null + undef, + undef, + undef, + undef, + null, // host defaults to null + null, // port defaults to null + undef, + null, // query defaults to null + null, // fragment defaults to null }; SetArgs(env, argv, url); cb->Call(context, recv, arraysize(argv), argv).FromMaybe(Local()); } else if (error_cb->IsFunction()) { - Local argv[2] = { undef, undef }; + Local argv[2] = {undef, undef}; argv[ERR_ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags); argv[ERR_ARG_INPUT] = - String::NewFromUtf8(env->isolate(), - input, - v8::NewStringType::kNormal).ToLocalChecked(); - error_cb.As()->Call(context, recv, arraysize(argv), argv) + String::NewFromUtf8(env->isolate(), input, v8::NewStringType::kNormal) + .ToLocalChecked(); + error_cb.As() + ->Call(context, recv, arraysize(argv), argv) .FromMaybe(Local()); } } @@ -2098,14 +1984,12 @@ static void Parse(Environment* env, static void Parse(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 5); - CHECK(args[0]->IsString()); // input + CHECK(args[0]->IsString()); // input CHECK(args[2]->IsUndefined() || // base context - args[2]->IsNull() || - args[2]->IsObject()); + args[2]->IsNull() || args[2]->IsObject()); CHECK(args[3]->IsUndefined() || // context - args[3]->IsNull() || - args[3]->IsObject()); - CHECK(args[4]->IsFunction()); // complete callback + args[3]->IsNull() || args[3]->IsObject()); + CHECK(args[4]->IsFunction()); // complete callback CHECK(args[5]->IsUndefined() || args[5]->IsFunction()); // error callback Utf8Value input(env->isolate(), args[0]); @@ -2115,8 +1999,10 @@ static void Parse(const FunctionCallbackInfo& args) { args[1]->Uint32Value(env->context()).FromJust()); } - Parse(env, args.This(), - *input, input.length(), + Parse(env, + args.This(), + *input, + input.length(), state_override, args[2], args[3], @@ -2136,10 +2022,10 @@ static void EncodeAuthSet(const FunctionCallbackInfo& args) { const char ch = (*value)[n]; AppendOrEscape(&output, ch, USERINFO_ENCODE_SET); } - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - output.c_str(), - v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), + output.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()); } static void ToUSVString(const FunctionCallbackInfo& args) { @@ -2171,10 +2057,9 @@ static void ToUSVString(const FunctionCallbackInfo& args) { } args.GetReturnValue().Set( - String::NewFromTwoByte(env->isolate(), - *value, - v8::NewStringType::kNormal, - n).ToLocalChecked()); + String::NewFromTwoByte( + env->isolate(), *value, v8::NewStringType::kNormal, n) + .ToLocalChecked()); } static void DomainToASCII(const FunctionCallbackInfo& args) { @@ -2191,10 +2076,10 @@ static void DomainToASCII(const FunctionCallbackInfo& args) { return; } std::string out = host.ToStringMove(); - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - out.c_str(), - v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), + out.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()); } static void DomainToUnicode(const FunctionCallbackInfo& args) { @@ -2211,10 +2096,10 @@ static void DomainToUnicode(const FunctionCallbackInfo& args) { return; } std::string out = host.ToStringMove(); - args.GetReturnValue().Set( - String::NewFromUtf8(env->isolate(), - out.c_str(), - v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), + out.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()); } std::string URL::ToFilePath() const { @@ -2224,16 +2109,11 @@ std::string URL::ToFilePath() const { #ifdef _WIN32 const char* slash = "\\"; - auto is_slash = [] (char ch) { - return ch == '/' || ch == '\\'; - }; + auto is_slash = [](char ch) { return ch == '/' || ch == '\\'; }; #else const char* slash = "/"; - auto is_slash = [] (char ch) { - return ch == '/'; - }; - if ((context_.flags & URL_FLAGS_HAS_HOST) && - context_.host.length() > 0) { + auto is_slash = [](char ch) { return ch == '/'; }; + if ((context_.flags & URL_FLAGS_HAS_HOST) && context_.host.length() > 0) { return ""; } #endif @@ -2256,8 +2136,7 @@ std::string URL::ToFilePath() const { // need to worry about percent encoding because the URL parser will have // already taken care of that for us. Note that this only causes IDNs with an // appropriate `xn--` prefix to be decoded. - if ((context_.flags & URL_FLAGS_HAS_HOST) && - context_.host.length() > 0) { + if ((context_.flags & URL_FLAGS_HAS_HOST) && context_.host.length() > 0) { std::string unicode_host; if (!ToUnicode(context_.host, &unicode_host)) { return ""; @@ -2268,8 +2147,7 @@ std::string URL::ToFilePath() const { if (decoded_path.length() < 3) { return ""; } - if (decoded_path[2] != ':' || - !IsASCIIAlpha(decoded_path[1])) { + if (decoded_path[2] != ':' || !IsASCIIAlpha(decoded_path[1])) { return ""; } // Strip out the leading '\'. @@ -2290,19 +2168,18 @@ const Local URL::ToObject(Environment* env) const { const Local undef = Undefined(isolate); const Local null = Null(isolate); - if (context_.flags & URL_FLAGS_FAILED) - return Local(); + if (context_.flags & URL_FLAGS_FAILED) return Local(); Local argv[] = { - undef, - undef, - undef, - undef, - null, // host defaults to null - null, // port defaults to null - undef, - null, // query defaults to null - null, // fragment defaults to null + undef, + undef, + undef, + undef, + null, // host defaults to null + null, // port defaults to null + undef, + null, // query defaults to null + null, // fragment defaults to null }; SetArgs(env, argv, context_); @@ -2314,8 +2191,8 @@ const Local URL::ToObject(Environment* env) const { // set the constructor function used below. SetURLConstructor is // called automatically when the internal/url.js module is loaded // during the internal/bootstrap/node.js processing. - ret = env->url_constructor_function() - ->Call(env->context(), undef, arraysize(argv), argv); + ret = env->url_constructor_function()->Call( + env->context(), undef, arraysize(argv), argv); } return ret.ToLocalChecked(); diff --git a/src/node_url.h b/src/node_url.h index b2eadf9923a7ea..a6b112ee88c525 100644 --- a/src/node_url.h +++ b/src/node_url.h @@ -3,8 +3,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" #include "env-inl.h" +#include "node.h" #include @@ -14,44 +14,43 @@ namespace url { using v8::Local; using v8::Value; - -#define PARSESTATES(XX) \ - XX(kSchemeStart) \ - XX(kScheme) \ - XX(kNoScheme) \ - XX(kSpecialRelativeOrAuthority) \ - XX(kPathOrAuthority) \ - XX(kRelative) \ - XX(kRelativeSlash) \ - XX(kSpecialAuthoritySlashes) \ - XX(kSpecialAuthorityIgnoreSlashes) \ - XX(kAuthority) \ - XX(kHost) \ - XX(kHostname) \ - XX(kPort) \ - XX(kFile) \ - XX(kFileSlash) \ - XX(kFileHost) \ - XX(kPathStart) \ - XX(kPath) \ - XX(kCannotBeBase) \ - XX(kQuery) \ +#define PARSESTATES(XX) \ + XX(kSchemeStart) \ + XX(kScheme) \ + XX(kNoScheme) \ + XX(kSpecialRelativeOrAuthority) \ + XX(kPathOrAuthority) \ + XX(kRelative) \ + XX(kRelativeSlash) \ + XX(kSpecialAuthoritySlashes) \ + XX(kSpecialAuthorityIgnoreSlashes) \ + XX(kAuthority) \ + XX(kHost) \ + XX(kHostname) \ + XX(kPort) \ + XX(kFile) \ + XX(kFileSlash) \ + XX(kFileHost) \ + XX(kPathStart) \ + XX(kPath) \ + XX(kCannotBeBase) \ + XX(kQuery) \ XX(kFragment) -#define FLAGS(XX) \ - XX(URL_FLAGS_NONE, 0) \ - XX(URL_FLAGS_FAILED, 0x01) \ - XX(URL_FLAGS_CANNOT_BE_BASE, 0x02) \ - XX(URL_FLAGS_INVALID_PARSE_STATE, 0x04) \ - XX(URL_FLAGS_TERMINATED, 0x08) \ - XX(URL_FLAGS_SPECIAL, 0x10) \ - XX(URL_FLAGS_HAS_USERNAME, 0x20) \ - XX(URL_FLAGS_HAS_PASSWORD, 0x40) \ - XX(URL_FLAGS_HAS_HOST, 0x80) \ - XX(URL_FLAGS_HAS_PATH, 0x100) \ - XX(URL_FLAGS_HAS_QUERY, 0x200) \ - XX(URL_FLAGS_HAS_FRAGMENT, 0x400) \ - XX(URL_FLAGS_IS_DEFAULT_SCHEME_PORT, 0x800) \ +#define FLAGS(XX) \ + XX(URL_FLAGS_NONE, 0) \ + XX(URL_FLAGS_FAILED, 0x01) \ + XX(URL_FLAGS_CANNOT_BE_BASE, 0x02) \ + XX(URL_FLAGS_INVALID_PARSE_STATE, 0x04) \ + XX(URL_FLAGS_TERMINATED, 0x08) \ + XX(URL_FLAGS_SPECIAL, 0x10) \ + XX(URL_FLAGS_HAS_USERNAME, 0x20) \ + XX(URL_FLAGS_HAS_PASSWORD, 0x40) \ + XX(URL_FLAGS_HAS_HOST, 0x80) \ + XX(URL_FLAGS_HAS_PATH, 0x100) \ + XX(URL_FLAGS_HAS_QUERY, 0x200) \ + XX(URL_FLAGS_HAS_FRAGMENT, 0x400) \ + XX(URL_FLAGS_IS_DEFAULT_SCHEME_PORT, 0x800) enum url_parse_state { kUnknownState = -1, @@ -94,68 +93,51 @@ class URL { URL(const char* input, const size_t len, const URL* base) { if (base != nullptr) - Parse(input, len, kUnknownState, - &context_, false, - &(base->context_), true); + Parse( + input, len, kUnknownState, &context_, false, &(base->context_), true); else Parse(input, len, kUnknownState, &context_, false, nullptr, false); } - URL(const char* input, const size_t len, - const char* base, const size_t baselen) { + URL(const char* input, + const size_t len, + const char* base, + const size_t baselen) { if (base != nullptr && baselen > 0) { URL _base(base, baselen); - Parse(input, len, kUnknownState, - &context_, false, - &(_base.context_), true); + Parse( + input, len, kUnknownState, &context_, false, &(_base.context_), true); } else { Parse(input, len, kUnknownState, &context_, false, nullptr, false); } } - explicit URL(std::string input) : - URL(input.c_str(), input.length()) {} + explicit URL(std::string input) : URL(input.c_str(), input.length()) {} - URL(std::string input, const URL* base) : - URL(input.c_str(), input.length(), base) {} + URL(std::string input, const URL* base) + : URL(input.c_str(), input.length(), base) {} - URL(std::string input, const URL& base) : - URL(input.c_str(), input.length(), &base) {} + URL(std::string input, const URL& base) + : URL(input.c_str(), input.length(), &base) {} - URL(std::string input, std::string base) : - URL(input.c_str(), input.length(), base.c_str(), base.length()) {} + URL(std::string input, std::string base) + : URL(input.c_str(), input.length(), base.c_str(), base.length()) {} - int32_t flags() { - return context_.flags; - } + int32_t flags() { return context_.flags; } - int port() { - return context_.port; - } + int port() { return context_.port; } - const std::string& protocol() const { - return context_.scheme; - } + const std::string& protocol() const { return context_.scheme; } - const std::string& username() const { - return context_.username; - } + const std::string& username() const { return context_.username; } - const std::string& password() const { - return context_.password; - } + const std::string& password() const { return context_.password; } - const std::string& host() const { - return context_.host; - } + const std::string& host() const { return context_.host; } - const std::string& query() const { - return context_.query; - } + const std::string& query() const { return context_.query; } - const std::string& fragment() const { - return context_.fragment; - } + const std::string& fragment() const { return context_.fragment; } std::string path() const { std::string ret; diff --git a/src/node_util.cc b/src/node_util.cc index 41b1307bb4912c..d04f57cd0aa795 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -18,8 +18,7 @@ using v8::Value; static void GetPromiseDetails(const FunctionCallbackInfo& args) { // Return undefined if it's not a Promise. - if (!args[0]->IsPromise()) - return; + if (!args[0]->IsPromise()) return; auto isolate = args.GetIsolate(); @@ -28,16 +27,14 @@ static void GetPromiseDetails(const FunctionCallbackInfo& args) { int state = promise->State(); ret->Set(0, Integer::New(isolate, state)); - if (state != Promise::PromiseState::kPending) - ret->Set(1, promise->Result()); + if (state != Promise::PromiseState::kPending) ret->Set(1, promise->Result()); args.GetReturnValue().Set(ret); } static void GetProxyDetails(const FunctionCallbackInfo& args) { // Return undefined if it's not a proxy. - if (!args[0]->IsProxy()) - return; + if (!args[0]->IsProxy()) return; Local proxy = args[0].As(); @@ -49,8 +46,7 @@ static void GetProxyDetails(const FunctionCallbackInfo& args) { } static void PreviewEntries(const FunctionCallbackInfo& args) { - if (!args[0]->IsObject()) - return; + if (!args[0]->IsObject()) return; Environment* env = Environment::GetCurrent(args); bool is_key_value; @@ -58,8 +54,7 @@ static void PreviewEntries(const FunctionCallbackInfo& args) { if (!args[0].As()->PreviewEntries(&is_key_value).ToLocal(&entries)) return; // Fast path for WeakMap, WeakSet and Set iterators. - if (args.Length() == 1) - return args.GetReturnValue().Set(entries); + if (args.Length() == 1) return args.GetReturnValue().Set(entries); Local ret = Array::New(env->isolate(), 2); ret->Set(env->context(), 0, entries).FromJust(); ret->Set(env->context(), 1, v8::Boolean::New(env->isolate(), is_key_value)) @@ -75,9 +70,8 @@ static void SafeToString(const FunctionCallbackInfo& args) { inline Local IndexToPrivateSymbol(Environment* env, uint32_t index) { #define V(name, _) &Environment::name, - static Local (Environment::*const methods[])() const = { - PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) - }; + static Local (Environment::*const methods[])() + const = {PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)}; #undef V CHECK_LT(index, arraysize(methods)); return (env->*methods[index])(); @@ -111,19 +105,16 @@ static void SetHiddenValue(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(maybe_value.FromJust()); } - void StartSigintWatchdog(const FunctionCallbackInfo& args) { int ret = SigintWatchdogHelper::GetInstance()->Start(); args.GetReturnValue().Set(ret == 0); } - void StopSigintWatchdog(const FunctionCallbackInfo& args) { bool had_pending_signals = SigintWatchdogHelper::GetInstance()->Stop(); args.GetReturnValue().Set(had_pending_signals); } - void WatchdogHasPendingSigint(const FunctionCallbackInfo& args) { bool ret = SigintWatchdogHelper::GetInstance()->HasPendingSignal(); args.GetReturnValue().Set(ret); @@ -134,10 +125,10 @@ void SafeGetenv(const FunctionCallbackInfo& args) { Utf8Value strenvtag(args.GetIsolate(), args[0]); std::string text; if (!node::SafeGetenv(*strenvtag, &text)) return; - args.GetReturnValue() - .Set(String::NewFromUtf8( - args.GetIsolate(), text.c_str(), - v8::NewStringType::kNormal).ToLocalChecked()); + args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), + text.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()); } void Initialize(Local target, @@ -145,27 +136,32 @@ void Initialize(Local target, Local context) { Environment* env = Environment::GetCurrent(context); -#define V(name, _) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ - Integer::NewFromUnsigned(env->isolate(), index++)).FromJust(); +#define V(name, _) \ + target \ + ->Set(context, \ + FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ + Integer::NewFromUnsigned(env->isolate(), index++)) \ + .FromJust(); { uint32_t index = 0; PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) } #undef V - target->DefineOwnProperty( - env->context(), - OneByteString(env->isolate(), "pushValToArrayMax"), - Integer::NewFromUnsigned(env->isolate(), NODE_PUSH_VAL_TO_ARRAY_MAX), - v8::ReadOnly).FromJust(); - -#define V(name) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ - Integer::New(env->isolate(), Promise::PromiseState::name)) \ - .FromJust() + target + ->DefineOwnProperty( + env->context(), + OneByteString(env->isolate(), "pushValToArrayMax"), + Integer::NewFromUnsigned(env->isolate(), NODE_PUSH_VAL_TO_ARRAY_MAX), + v8::ReadOnly) + .FromJust(); + +#define V(name) \ + target \ + ->Set(context, \ + FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ + Integer::New(env->isolate(), Promise::PromiseState::name)) \ + .FromJust() V(kPending); V(kFulfilled); V(kRejected); @@ -180,8 +176,8 @@ void Initialize(Local target, env->SetMethod(target, "startSigintWatchdog", StartSigintWatchdog); env->SetMethod(target, "stopSigintWatchdog", StopSigintWatchdog); - env->SetMethodNoSideEffect(target, "watchdogHasPendingSigint", - WatchdogHasPendingSigint); + env->SetMethodNoSideEffect( + target, "watchdogHasPendingSigint", WatchdogHasPendingSigint); env->SetMethod(target, "safeGetenv", SafeGetenv); } diff --git a/src/node_v8.cc b/src/node_v8.cc index fb0a9fea1e5d27..ef5e1dcf0d365f 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -19,9 +19,9 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +#include "env-inl.h" #include "node.h" #include "node_internals.h" -#include "env-inl.h" #include "util-inl.h" #include "v8.h" @@ -44,15 +44,15 @@ using v8::Uint32; using v8::V8; using v8::Value; -#define HEAP_STATISTICS_PROPERTIES(V) \ - V(0, total_heap_size, kTotalHeapSizeIndex) \ - V(1, total_heap_size_executable, kTotalHeapSizeExecutableIndex) \ - V(2, total_physical_size, kTotalPhysicalSizeIndex) \ - V(3, total_available_size, kTotalAvailableSize) \ - V(4, used_heap_size, kUsedHeapSizeIndex) \ - V(5, heap_size_limit, kHeapSizeLimitIndex) \ - V(6, malloced_memory, kMallocedMemoryIndex) \ - V(7, peak_malloced_memory, kPeakMallocedMemoryIndex) \ +#define HEAP_STATISTICS_PROPERTIES(V) \ + V(0, total_heap_size, kTotalHeapSizeIndex) \ + V(1, total_heap_size_executable, kTotalHeapSizeExecutableIndex) \ + V(2, total_physical_size, kTotalPhysicalSizeIndex) \ + V(3, total_available_size, kTotalAvailableSize) \ + V(4, used_heap_size, kUsedHeapSizeIndex) \ + V(5, heap_size_limit, kHeapSizeLimitIndex) \ + V(6, malloced_memory, kMallocedMemoryIndex) \ + V(7, peak_malloced_memory, kPeakMallocedMemoryIndex) \ V(8, does_zap_garbage, kDoesZapGarbageIndex) #define V(a, b, c) +1 @@ -60,10 +60,10 @@ static const size_t kHeapStatisticsPropertiesCount = HEAP_STATISTICS_PROPERTIES(V); #undef V -#define HEAP_SPACE_STATISTICS_PROPERTIES(V) \ - V(0, space_size, kSpaceSizeIndex) \ - V(1, space_used_size, kSpaceUsedSizeIndex) \ - V(2, space_available_size, kSpaceAvailableSizeIndex) \ +#define HEAP_SPACE_STATISTICS_PROPERTIES(V) \ + V(0, space_size, kSpaceSizeIndex) \ + V(1, space_used_size, kSpaceUsedSizeIndex) \ + V(2, space_available_size, kSpaceAvailableSizeIndex) \ V(3, physical_space_size, kPhysicalSpaceSizeIndex) #define V(a, b, c) +1 @@ -71,16 +71,13 @@ static const size_t kHeapSpaceStatisticsPropertiesCount = HEAP_SPACE_STATISTICS_PROPERTIES(V); #undef V - void CachedDataVersionTag(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - Local result = - Integer::NewFromUnsigned(env->isolate(), - ScriptCompiler::CachedDataVersionTag()); + Local result = Integer::NewFromUnsigned( + env->isolate(), ScriptCompiler::CachedDataVersionTag()); args.GetReturnValue().Set(result); } - void UpdateHeapStatisticsArrayBuffer(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); HeapStatistics s; @@ -91,7 +88,6 @@ void UpdateHeapStatisticsArrayBuffer(const FunctionCallbackInfo& args) { #undef V } - void UpdateHeapSpaceStatisticsBuffer(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); HeapSpaceStatistics s; @@ -102,28 +98,26 @@ void UpdateHeapSpaceStatisticsBuffer(const FunctionCallbackInfo& args) { for (size_t i = 0; i < number_of_heap_spaces; i++) { isolate->GetHeapSpaceStatistics(&s, i); size_t const property_offset = i * kHeapSpaceStatisticsPropertiesCount; -#define V(index, name, _) buffer[property_offset + index] = \ - static_cast(s.name()); - HEAP_SPACE_STATISTICS_PROPERTIES(V) +#define V(index, name, _) \ + buffer[property_offset + index] = static_cast(s.name()); + HEAP_SPACE_STATISTICS_PROPERTIES(V) #undef V } } - void SetFlagsFromString(const FunctionCallbackInfo& args) { CHECK(args[0]->IsString()); String::Utf8Value flags(args.GetIsolate(), args[0]); V8::SetFlagsFromString(*flags, flags.length()); } - void Initialize(Local target, Local unused, Local context) { Environment* env = Environment::GetCurrent(context); - env->SetMethodNoSideEffect(target, "cachedDataVersionTag", - CachedDataVersionTag); + env->SetMethodNoSideEffect( + target, "cachedDataVersionTag", CachedDataVersionTag); env->SetMethod(target, "updateHeapStatisticsArrayBuffer", @@ -134,14 +128,14 @@ void Initialize(Local target, const size_t heap_statistics_buffer_byte_length = sizeof(*env->heap_statistics_buffer()) * kHeapStatisticsPropertiesCount; - target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), - "heapStatisticsArrayBuffer"), - ArrayBuffer::New(env->isolate(), - env->heap_statistics_buffer(), - heap_statistics_buffer_byte_length)); + target->Set( + FIXED_ONE_BYTE_STRING(env->isolate(), "heapStatisticsArrayBuffer"), + ArrayBuffer::New(env->isolate(), + env->heap_statistics_buffer(), + heap_statistics_buffer_byte_length)); -#define V(i, _, name) \ - target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ +#define V(i, _, name) \ + target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ Uint32::NewFromUnsigned(env->isolate(), i)); HEAP_STATISTICS_PROPERTIES(V) @@ -157,14 +151,14 @@ void Initialize(Local target, // Heap space names are extracted once and exposed to JavaScript to // avoid excessive creation of heap space name Strings. HeapSpaceStatistics s; - const Local heap_spaces = Array::New(env->isolate(), - number_of_heap_spaces); + const Local heap_spaces = + Array::New(env->isolate(), number_of_heap_spaces); for (size_t i = 0; i < number_of_heap_spaces; i++) { env->isolate()->GetHeapSpaceStatistics(&s, i); - Local heap_space_name = String::NewFromUtf8(env->isolate(), - s.space_name(), - NewStringType::kNormal) - .ToLocalChecked(); + Local heap_space_name = + String::NewFromUtf8( + env->isolate(), s.space_name(), NewStringType::kNormal) + .ToLocalChecked(); heap_spaces->Set(i, heap_space_name); } target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kHeapSpaces"), @@ -175,21 +169,20 @@ void Initialize(Local target, UpdateHeapSpaceStatisticsBuffer); env->set_heap_space_statistics_buffer( - new double[kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces]); + new double[kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces]); const size_t heap_space_statistics_buffer_byte_length = sizeof(*env->heap_space_statistics_buffer()) * - kHeapSpaceStatisticsPropertiesCount * - number_of_heap_spaces; + kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces; - target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), - "heapSpaceStatisticsArrayBuffer"), - ArrayBuffer::New(env->isolate(), - env->heap_space_statistics_buffer(), - heap_space_statistics_buffer_byte_length)); + target->Set( + FIXED_ONE_BYTE_STRING(env->isolate(), "heapSpaceStatisticsArrayBuffer"), + ArrayBuffer::New(env->isolate(), + env->heap_space_statistics_buffer(), + heap_space_statistics_buffer_byte_length)); -#define V(i, _, name) \ - target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ +#define V(i, _, name) \ + target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ Uint32::NewFromUnsigned(env->isolate(), i)); HEAP_SPACE_STATISTICS_PROPERTIES(V) diff --git a/src/node_version.h b/src/node_version.h index 3c4eb70771b64c..0691a2bccac609 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -41,35 +41,34 @@ #endif #ifndef NODE_TAG -# if NODE_VERSION_IS_RELEASE -# define NODE_TAG "" -# else -# define NODE_TAG "-pre" -# endif +#if NODE_VERSION_IS_RELEASE +#define NODE_TAG "" +#else +#define NODE_TAG "-pre" +#endif #else // NODE_TAG is passed without quotes when rc.exe is run from msbuild -# define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ - NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ - NODE_STRINGIFY(NODE_PATCH_VERSION) \ - NODE_STRINGIFY(NODE_TAG) +#define NODE_EXE_VERSION \ + NODE_STRINGIFY(NODE_MAJOR_VERSION) \ + "." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY( \ + NODE_PATCH_VERSION) NODE_STRINGIFY(NODE_TAG) #endif -# define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ - NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ - NODE_STRINGIFY(NODE_PATCH_VERSION) \ - NODE_TAG +#define NODE_VERSION_STRING \ + NODE_STRINGIFY(NODE_MAJOR_VERSION) \ + "." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY( \ + NODE_PATCH_VERSION) NODE_TAG #ifndef NODE_EXE_VERSION -# define NODE_EXE_VERSION NODE_VERSION_STRING +#define NODE_EXE_VERSION NODE_VERSION_STRING #endif #define NODE_VERSION "v" NODE_VERSION_STRING - -#define NODE_VERSION_AT_LEAST(major, minor, patch) \ - (( (major) < NODE_MAJOR_VERSION) \ - || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) \ - || ((major) == NODE_MAJOR_VERSION && \ - (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION)) +#define NODE_VERSION_AT_LEAST(major, minor, patch) \ + (((major) < NODE_MAJOR_VERSION) || \ + ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) || \ + ((major) == NODE_MAJOR_VERSION && (minor) == NODE_MINOR_VERSION && \ + (patch) <= NODE_PATCH_VERSION)) /** * Node.js will refuse to load modules that weren't compiled against its own @@ -115,6 +114,6 @@ #define NODE_MODULE_VERSION 65 // the NAPI_VERSION provided by this version of the runtime -#define NAPI_VERSION 3 +#define NAPI_VERSION 3 #endif // SRC_NODE_VERSION_H_ diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index 09b10d169371da..b375f1d3e56712 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -20,22 +20,20 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_watchdog.h" -#include "node_internals.h" -#include "debug_utils.h" #include +#include "debug_utils.h" +#include "node_internals.h" namespace node { Watchdog::Watchdog(v8::Isolate* isolate, uint64_t ms, bool* timed_out) : isolate_(isolate), timed_out_(timed_out) { - int rc; loop_ = new uv_loop_t; CHECK(loop_); rc = uv_loop_init(loop_); if (rc != 0) { - FatalError("node::Watchdog::Watchdog()", - "Failed to initialize uv loop."); + FatalError("node::Watchdog::Watchdog()", "Failed to initialize uv loop."); } rc = uv_async_init(loop_, &async_, &Watchdog::Async); @@ -51,7 +49,6 @@ Watchdog::Watchdog(v8::Isolate* isolate, uint64_t ms, bool* timed_out) CHECK_EQ(0, rc); } - Watchdog::~Watchdog() { uv_async_send(&async_); uv_thread_join(&thread_); @@ -66,7 +63,6 @@ Watchdog::~Watchdog() { loop_ = nullptr; } - void Watchdog::Run(void* arg) { Watchdog* wd = static_cast(arg); @@ -79,13 +75,11 @@ void Watchdog::Run(void* arg) { uv_close(reinterpret_cast(&wd->timer_), nullptr); } - void Watchdog::Async(uv_async_t* async) { Watchdog* w = ContainerOf(&Watchdog::async_, async); uv_stop(w->loop_); } - void Watchdog::Timer(uv_timer_t* timer) { Watchdog* w = ContainerOf(&Watchdog::timer_, timer); *w->timed_out_ = true; @@ -93,9 +87,7 @@ void Watchdog::Timer(uv_timer_t* timer) { uv_stop(w->loop_); } - -SigintWatchdog::SigintWatchdog( - v8::Isolate* isolate, bool* received_signal) +SigintWatchdog::SigintWatchdog(v8::Isolate* isolate, bool* received_signal) : isolate_(isolate), received_signal_(received_signal) { // Register this watchdog with the global SIGINT/Ctrl+C listener. SigintWatchdogHelper::GetInstance()->Register(this); @@ -103,13 +95,11 @@ SigintWatchdog::SigintWatchdog( SigintWatchdogHelper::GetInstance()->Start(); } - SigintWatchdog::~SigintWatchdog() { SigintWatchdogHelper::GetInstance()->Unregister(this); SigintWatchdogHelper::GetInstance()->Stop(); } - void SigintWatchdog::HandleSigint() { *received_signal_ = true; isolate_->TerminateExecution(); @@ -128,7 +118,6 @@ void* SigintWatchdogHelper::RunSigintWatchdog(void* arg) { return nullptr; } - void SigintWatchdogHelper::HandleSignal(int signum) { uv_sem_post(&instance.sem_); } @@ -150,7 +139,6 @@ BOOL WINAPI SigintWatchdogHelper::WinCtrlCHandlerRoutine(DWORD dwCtrlType) { } #endif - bool SigintWatchdogHelper::InformWatchdogsAboutSignal() { Mutex::ScopedLock list_lock(instance.list_mutex_); @@ -165,13 +153,11 @@ bool SigintWatchdogHelper::InformWatchdogsAboutSignal() { instance.has_pending_signal_ = true; } - for (auto it : instance.watchdogs_) - it->HandleSigint(); + for (auto it : instance.watchdogs_) it->HandleSigint(); return is_stopping; } - int SigintWatchdogHelper::Start() { Mutex::ScopedLock lock(mutex_); @@ -206,7 +192,6 @@ int SigintWatchdogHelper::Start() { return 0; } - bool SigintWatchdogHelper::Stop() { bool had_pending_signal; Mutex::ScopedLock lock(mutex_); @@ -253,21 +238,18 @@ bool SigintWatchdogHelper::Stop() { return had_pending_signal; } - bool SigintWatchdogHelper::HasPendingSignal() { Mutex::ScopedLock lock(list_mutex_); return has_pending_signal_; } - void SigintWatchdogHelper::Register(SigintWatchdog* wd) { Mutex::ScopedLock lock(list_mutex_); watchdogs_.push_back(wd); } - void SigintWatchdogHelper::Unregister(SigintWatchdog* wd) { Mutex::ScopedLock lock(list_mutex_); @@ -277,10 +259,8 @@ void SigintWatchdogHelper::Unregister(SigintWatchdog* wd) { watchdogs_.erase(it); } - SigintWatchdogHelper::SigintWatchdogHelper() - : start_stop_count_(0), - has_pending_signal_(false) { + : start_stop_count_(0), has_pending_signal_(false) { #ifdef __POSIX__ has_running_thread_ = false; stopping_ = false; @@ -290,7 +270,6 @@ SigintWatchdogHelper::SigintWatchdogHelper() #endif } - SigintWatchdogHelper::~SigintWatchdogHelper() { start_stop_count_ = 0; Stop(); diff --git a/src/node_watchdog.h b/src/node_watchdog.h index 2cc7eab837cb88..831d3661346834 100644 --- a/src/node_watchdog.h +++ b/src/node_watchdog.h @@ -24,10 +24,10 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "v8.h" -#include "uv.h" -#include "node_mutex.h" #include +#include "node_mutex.h" +#include "uv.h" +#include "v8.h" #ifdef __POSIX__ #include diff --git a/src/node_win32_etw_provider-inl.h b/src/node_win32_etw_provider-inl.h index a7846f413a204c..bb2f911b12ce1e 100644 --- a/src/node_win32_etw_provider-inl.h +++ b/src/node_win32_etw_provider-inl.h @@ -24,8 +24,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_win32_etw_provider.h" #include "node_etw_provider.h" +#include "node_win32_etw_provider.h" namespace node { @@ -34,143 +34,149 @@ extern REGHANDLE node_provider; extern EventWriteFunc event_write; extern int events_enabled; -#define ETW_WRITE_STRING_DATA(data_descriptor, data) \ - EventDataDescCreate(data_descriptor, \ - data, \ - (strlen(data) + 1) * sizeof(*data)); +#define ETW_WRITE_STRING_DATA(data_descriptor, data) \ + EventDataDescCreate( \ + data_descriptor, data, (strlen(data) + 1) * sizeof(*data)); -#define ETW_WRITE_INT32_DATA(data_descriptor, data) \ +#define ETW_WRITE_INT32_DATA(data_descriptor, data) \ EventDataDescCreate(data_descriptor, data, sizeof(int32_t)); -#define ETW_WRITE_INT64_DATA(data_descriptor, data) \ +#define ETW_WRITE_INT64_DATA(data_descriptor, data) \ EventDataDescCreate(data_descriptor, data, sizeof(int64_t)); -#define ETW_WRITE_ADDRESS_DATA(data_descriptor, data) \ +#define ETW_WRITE_ADDRESS_DATA(data_descriptor, data) \ EventDataDescCreate(data_descriptor, data, sizeof(intptr_t)); -#define ETW_WRITE_INT16_DATA(data_descriptor, data) \ +#define ETW_WRITE_INT16_DATA(data_descriptor, data) \ EventDataDescCreate(data_descriptor, data, sizeof(int16_t)); -#define ETW_WRITE_WSTRING_DATA_LENGTH(data_descriptor, data, data_len_bytes) \ - EventDataDescCreate(data_descriptor, \ - data, \ - data_len_bytes); +#define ETW_WRITE_WSTRING_DATA_LENGTH(data_descriptor, data, data_len_bytes) \ + EventDataDescCreate(data_descriptor, data, data_len_bytes); -#define ETW_WRITE_NET_CONNECTION(descriptors, conn) \ - ETW_WRITE_INT32_DATA(descriptors, &conn->fd); \ - ETW_WRITE_INT32_DATA(descriptors + 1, &conn->port); \ - ETW_WRITE_STRING_DATA(descriptors + 2, conn->remote); \ +#define ETW_WRITE_NET_CONNECTION(descriptors, conn) \ + ETW_WRITE_INT32_DATA(descriptors, &conn->fd); \ + ETW_WRITE_INT32_DATA(descriptors + 1, &conn->port); \ + ETW_WRITE_STRING_DATA(descriptors + 2, conn->remote); \ ETW_WRITE_INT32_DATA(descriptors + 3, &conn->buffered); -#define ETW_WRITE_HTTP_SERVER_REQUEST(descriptors, req) \ - ETW_WRITE_STRING_DATA(descriptors, req->url); \ - ETW_WRITE_STRING_DATA(descriptors + 1, req->method); \ +#define ETW_WRITE_HTTP_SERVER_REQUEST(descriptors, req) \ + ETW_WRITE_STRING_DATA(descriptors, req->url); \ + ETW_WRITE_STRING_DATA(descriptors + 1, req->method); \ ETW_WRITE_STRING_DATA(descriptors + 2, req->forwardedFor); -#define ETW_WRITE_HTTP_CLIENT_REQUEST(descriptors, req) \ - ETW_WRITE_STRING_DATA(descriptors, req->url); \ +#define ETW_WRITE_HTTP_CLIENT_REQUEST(descriptors, req) \ + ETW_WRITE_STRING_DATA(descriptors, req->url); \ ETW_WRITE_STRING_DATA(descriptors + 1, req->method); -#define ETW_WRITE_GC(descriptors, type, flags) \ - ETW_WRITE_INT32_DATA(descriptors, &type); \ +#define ETW_WRITE_GC(descriptors, type, flags) \ + ETW_WRITE_INT32_DATA(descriptors, &type); \ ETW_WRITE_INT32_DATA(descriptors + 1, &flags); -#define ETW_WRITE_V8ADDRESSCHANGE(descriptors, addr1, addr2) \ - ETW_WRITE_ADDRESS_DATA(descriptors, &addr1); \ - ETW_WRITE_ADDRESS_DATA(descriptors + 1, &addr2); - -#define ETW_WRITE_JSMETHOD_LOADUNLOAD(descriptors, \ - context, \ - startAddr, \ - size, \ - id, \ - flags, \ - rangeId, \ - sourceId, \ - line, \ - col, \ - name, \ - name_len_bytes) \ - ETW_WRITE_ADDRESS_DATA(descriptors, &context); \ - ETW_WRITE_ADDRESS_DATA(descriptors + 1, &startAddr); \ - ETW_WRITE_INT64_DATA(descriptors + 2, &size); \ - ETW_WRITE_INT32_DATA(descriptors + 3, &id); \ - ETW_WRITE_INT16_DATA(descriptors + 4, &flags); \ - ETW_WRITE_INT16_DATA(descriptors + 5, &rangeId); \ - ETW_WRITE_INT64_DATA(descriptors + 6, &sourceId); \ - ETW_WRITE_INT32_DATA(descriptors + 7, &line); \ - ETW_WRITE_INT32_DATA(descriptors + 8, &col); \ - ETW_WRITE_WSTRING_DATA_LENGTH(descriptors + 9, name, name_len_bytes); - - -#define ETW_WRITE_EVENT(eventDescriptor, dataDescriptors) \ - DWORD status = event_write(node_provider, \ - &eventDescriptor, \ - sizeof(dataDescriptors) / \ - sizeof(*dataDescriptors), \ - dataDescriptors); \ +#define ETW_WRITE_V8ADDRESSCHANGE(descriptors, addr1, addr2) \ + ETW_WRITE_ADDRESS_DATA(descriptors, &addr1); \ + ETW_WRITE_ADDRESS_DATA(descriptors + 1, &addr2); + +#define ETW_WRITE_JSMETHOD_LOADUNLOAD(descriptors, \ + context, \ + startAddr, \ + size, \ + id, \ + flags, \ + rangeId, \ + sourceId, \ + line, \ + col, \ + name, \ + name_len_bytes) \ + ETW_WRITE_ADDRESS_DATA(descriptors, &context); \ + ETW_WRITE_ADDRESS_DATA(descriptors + 1, &startAddr); \ + ETW_WRITE_INT64_DATA(descriptors + 2, &size); \ + ETW_WRITE_INT32_DATA(descriptors + 3, &id); \ + ETW_WRITE_INT16_DATA(descriptors + 4, &flags); \ + ETW_WRITE_INT16_DATA(descriptors + 5, &rangeId); \ + ETW_WRITE_INT64_DATA(descriptors + 6, &sourceId); \ + ETW_WRITE_INT32_DATA(descriptors + 7, &line); \ + ETW_WRITE_INT32_DATA(descriptors + 8, &col); \ + ETW_WRITE_WSTRING_DATA_LENGTH(descriptors + 9, name, name_len_bytes); + +#define ETW_WRITE_EVENT(eventDescriptor, dataDescriptors) \ + DWORD status = \ + event_write(node_provider, \ + &eventDescriptor, \ + sizeof(dataDescriptors) / sizeof(*dataDescriptors), \ + dataDescriptors); \ CHECK_EQ(status, ERROR_SUCCESS); -#define ETW_WRITE_EMPTY_EVENT(eventDescriptor) \ - DWORD status = event_write(node_provider, \ - &eventDescriptor, \ - 0, \ - NULL); // NOLINT (readability/null_usage) \ +#define ETW_WRITE_EMPTY_EVENT(eventDescriptor) \ + DWORD status = \ + event_write(node_provider, \ + &eventDescriptor, \ + 0, \ + NULL); // NOLINT (readability/null_usage) \ CHECK_EQ(status, ERROR_SUCCESS); - void NODE_HTTP_SERVER_REQUEST(node_dtrace_http_server_request_t* req, - node_dtrace_connection_t* conn, const char* remote, int port, - const char* method, const char* url, int fd) { + node_dtrace_connection_t* conn, + const char* remote, + int port, + const char* method, + const char* url, + int fd) { EVENT_DATA_DESCRIPTOR descriptors[7]; ETW_WRITE_HTTP_SERVER_REQUEST(descriptors, req); ETW_WRITE_NET_CONNECTION(descriptors + 3, conn); ETW_WRITE_EVENT(NODE_HTTP_SERVER_REQUEST_EVENT, descriptors); } - void NODE_HTTP_SERVER_RESPONSE(node_dtrace_connection_t* conn, - const char* remote, int port, int fd) { + const char* remote, + int port, + int fd) { EVENT_DATA_DESCRIPTOR descriptors[4]; ETW_WRITE_NET_CONNECTION(descriptors, conn); ETW_WRITE_EVENT(NODE_HTTP_SERVER_RESPONSE_EVENT, descriptors); } - void NODE_HTTP_CLIENT_REQUEST(node_dtrace_http_client_request_t* req, - node_dtrace_connection_t* conn, const char* remote, int port, - const char* method, const char* url, int fd) { + node_dtrace_connection_t* conn, + const char* remote, + int port, + const char* method, + const char* url, + int fd) { EVENT_DATA_DESCRIPTOR descriptors[6]; ETW_WRITE_HTTP_CLIENT_REQUEST(descriptors, req); ETW_WRITE_NET_CONNECTION(descriptors + 2, conn); ETW_WRITE_EVENT(NODE_HTTP_CLIENT_REQUEST_EVENT, descriptors); } - void NODE_HTTP_CLIENT_RESPONSE(node_dtrace_connection_t* conn, - const char* remote, int port, int fd) { + const char* remote, + int port, + int fd) { EVENT_DATA_DESCRIPTOR descriptors[4]; ETW_WRITE_NET_CONNECTION(descriptors, conn); ETW_WRITE_EVENT(NODE_HTTP_CLIENT_RESPONSE_EVENT, descriptors); } - void NODE_NET_SERVER_CONNECTION(node_dtrace_connection_t* conn, - const char* remote, int port, int fd) { + const char* remote, + int port, + int fd) { EVENT_DATA_DESCRIPTOR descriptors[4]; ETW_WRITE_NET_CONNECTION(descriptors, conn); ETW_WRITE_EVENT(NODE_NET_SERVER_CONNECTION_EVENT, descriptors); } - void NODE_NET_STREAM_END(node_dtrace_connection_t* conn, - const char* remote, int port, int fd) { + const char* remote, + int port, + int fd) { EVENT_DATA_DESCRIPTOR descriptors[4]; ETW_WRITE_NET_CONNECTION(descriptors, conn); ETW_WRITE_EVENT(NODE_NET_STREAM_END_EVENT, descriptors); } - void NODE_GC_START(v8::GCType type, v8::GCCallbackFlags flags, v8::Isolate* isolate) { @@ -181,7 +187,6 @@ void NODE_GC_START(v8::GCType type, } } - void NODE_GC_DONE(v8::GCType type, v8::GCCallbackFlags flags, v8::Isolate* isolate) { @@ -192,7 +197,6 @@ void NODE_GC_DONE(v8::GCType type, } } - void NODE_V8SYMBOL_REMOVE(const void* addr1, const void* addr2) { if (events_enabled > 0) { EVENT_DATA_DESCRIPTOR descriptors[2]; @@ -201,7 +205,6 @@ void NODE_V8SYMBOL_REMOVE(const void* addr1, const void* addr2) { } } - void NODE_V8SYMBOL_MOVE(const void* addr1, const void* addr2) { if (events_enabled > 0) { EVENT_DATA_DESCRIPTOR descriptors[2]; @@ -210,15 +213,14 @@ void NODE_V8SYMBOL_MOVE(const void* addr1, const void* addr2) { } } - void NODE_V8SYMBOL_RESET() { if (events_enabled > 0) { ETW_WRITE_EMPTY_EVENT(NODE_V8SYMBOL_RESET_EVENT); } } -#define SETSYMBUF(s) \ - wcscpy(symbuf, s); \ +#define SETSYMBUF(s) \ + wcscpy(symbuf, s); \ symbol_len = arraysize(s) - 1; void NODE_V8SYMBOL_ADD(LPCSTR symbol, @@ -230,12 +232,8 @@ void NODE_V8SYMBOL_ADD(LPCSTR symbol, if (symbol == nullptr) { SETSYMBUF(L"nullptr"); } else { - symbol_len = MultiByteToWideChar(CP_ACP, - 0, - symbol, - symbol_len, - symbuf, - 128); + symbol_len = + MultiByteToWideChar(CP_ACP, 0, symbol, symbol_len, symbuf, 128); if (symbol_len == 0) { SETSYMBUF(L"Invalid"); } else { @@ -271,14 +269,27 @@ void NODE_V8SYMBOL_ADD(LPCSTR symbol, } #undef SETSYMBUF - -bool NODE_HTTP_SERVER_REQUEST_ENABLED() { return events_enabled > 0; } -bool NODE_HTTP_SERVER_RESPONSE_ENABLED() { return events_enabled > 0; } -bool NODE_HTTP_CLIENT_REQUEST_ENABLED() { return events_enabled > 0; } -bool NODE_HTTP_CLIENT_RESPONSE_ENABLED() { return events_enabled > 0; } -bool NODE_NET_SERVER_CONNECTION_ENABLED() { return events_enabled > 0; } -bool NODE_NET_STREAM_END_ENABLED() { return events_enabled > 0; } -bool NODE_V8SYMBOL_ENABLED() { return events_enabled > 0; } +bool NODE_HTTP_SERVER_REQUEST_ENABLED() { + return events_enabled > 0; +} +bool NODE_HTTP_SERVER_RESPONSE_ENABLED() { + return events_enabled > 0; +} +bool NODE_HTTP_CLIENT_REQUEST_ENABLED() { + return events_enabled > 0; +} +bool NODE_HTTP_CLIENT_RESPONSE_ENABLED() { + return events_enabled > 0; +} +bool NODE_NET_SERVER_CONNECTION_ENABLED() { + return events_enabled > 0; +} +bool NODE_NET_STREAM_END_ENABLED() { + return events_enabled > 0; +} +bool NODE_V8SYMBOL_ENABLED() { + return events_enabled > 0; +} } // namespace node diff --git a/src/node_win32_etw_provider.cc b/src/node_win32_etw_provider.cc index 8a854767d6aed8..da1ef9bdc423c8 100644 --- a/src/node_win32_etw_provider.cc +++ b/src/node_win32_etw_provider.cc @@ -45,12 +45,13 @@ struct v8tags { // Many of these are internal to v8. // The trace_codes array specifies which types are written. struct v8tags trace_codes[] = { -#define MAKE_V8TAG(s) { s, sizeof(s) - 1 } - MAKE_V8TAG("LazyCompile:"), - MAKE_V8TAG("Script:"), - MAKE_V8TAG("Function:"), - MAKE_V8TAG("RegExp:"), - MAKE_V8TAG("Eval:") +#define MAKE_V8TAG(s) \ + { s, sizeof(s) - 1 } + MAKE_V8TAG("LazyCompile:"), + MAKE_V8TAG("Script:"), + MAKE_V8TAG("Function:"), + MAKE_V8TAG("RegExp:"), + MAKE_V8TAG("Eval:") #undef MAKE_V8TAG }; @@ -72,7 +73,6 @@ struct v8tags trace_codes[] = { #define V8_MARKER1 '*' #define V8_MARKER2 '~' - // If prefix is not in filtered list return -1, // else return length of prefix and marker. int FilterCodeEvents(const char* name, size_t len) { @@ -80,8 +80,7 @@ int FilterCodeEvents(const char* name, size_t len) { size_t prelen = trace_codes[i].prelen; if (prelen < len) { if (strncmp(name, trace_codes[i].prefix, prelen) == 0) { - if (name[prelen] == V8_MARKER1 || name[prelen] == V8_MARKER2) - prelen++; + if (name[prelen] == V8_MARKER1 || name[prelen] == V8_MARKER2) prelen++; return prelen; } } @@ -89,35 +88,33 @@ int FilterCodeEvents(const char* name, size_t len) { return -1; } - // callback from V8 module passes symbol and address info for stack walk void CodeAddressNotification(const JitCodeEvent* jevent) { int pre_offset = 0; if (NODE_V8SYMBOL_ENABLED()) { switch (jevent->type) { - case JitCodeEvent::CODE_ADDED: - pre_offset = FilterCodeEvents(jevent->name.str, jevent->name.len); - if (pre_offset >= 0) { - // skip over prefix and marker - NODE_V8SYMBOL_ADD(jevent->name.str + pre_offset, - jevent->name.len - pre_offset, - jevent->code_start, - jevent->code_len); - } - break; - case JitCodeEvent::CODE_REMOVED: - NODE_V8SYMBOL_REMOVE(jevent->code_start, 0); - break; - case JitCodeEvent::CODE_MOVED: - NODE_V8SYMBOL_MOVE(jevent->code_start, jevent->new_code_start); - break; - default: - break; + case JitCodeEvent::CODE_ADDED: + pre_offset = FilterCodeEvents(jevent->name.str, jevent->name.len); + if (pre_offset >= 0) { + // skip over prefix and marker + NODE_V8SYMBOL_ADD(jevent->name.str + pre_offset, + jevent->name.len - pre_offset, + jevent->code_start, + jevent->code_len); + } + break; + case JitCodeEvent::CODE_REMOVED: + NODE_V8SYMBOL_REMOVE(jevent->code_start, 0); + break; + case JitCodeEvent::CODE_MOVED: + NODE_V8SYMBOL_MOVE(jevent->code_start, jevent->new_code_start); + break; + default: + break; } } } - // Call v8 to enable or disable code event callbacks. // Must be on default thread to do this. // Note: It is possible to call v8 from ETW thread, but then @@ -127,28 +124,24 @@ void etw_events_change_async(uv_async_t* handle) { if (events_enabled > 0) { NODE_V8SYMBOL_RESET(); v8::Isolate::GetCurrent()->SetJitCodeEventHandler( - v8::kJitCodeEventEnumExisting, - CodeAddressNotification); + v8::kJitCodeEventEnumExisting, CodeAddressNotification); } else { - v8::Isolate::GetCurrent()->SetJitCodeEventHandler( - v8::kJitCodeEventDefault, - nullptr); + v8::Isolate::GetCurrent()->SetJitCodeEventHandler(v8::kJitCodeEventDefault, + nullptr); } } - // This callback is called by ETW when consumers of our provider // are enabled or disabled. // The callback is dispatched on ETW thread. // Before calling into V8 to enable code events, switch to default thread. -void NTAPI etw_events_enable_callback( - LPCGUID SourceId, - ULONG IsEnabled, - UCHAR Level, - ULONGLONG MatchAnyKeyword, - ULONGLONG MatchAllKeywords, - PEVENT_FILTER_DESCRIPTOR FilterData, - PVOID CallbackContext) { +void NTAPI etw_events_enable_callback(LPCGUID SourceId, + ULONG IsEnabled, + UCHAR Level, + ULONGLONG MatchAnyKeyword, + ULONGLONG MatchAllKeywords, + PEVENT_FILTER_DESCRIPTOR FilterData, + PVOID CallbackContext) { if (IsEnabled) { events_enabled++; if (events_enabled == 1) { @@ -162,22 +155,21 @@ void NTAPI etw_events_enable_callback( } } - void init_etw() { events_enabled = 0; advapi = LoadLibraryW(L"advapi32.dll"); if (advapi) { - event_register = (EventRegisterFunc) - GetProcAddress(advapi, "EventRegister"); - event_unregister = (EventUnregisterFunc) - GetProcAddress(advapi, "EventUnregister"); + event_register = (EventRegisterFunc)GetProcAddress(advapi, "EventRegister"); + event_unregister = + (EventUnregisterFunc)GetProcAddress(advapi, "EventUnregister"); event_write = (EventWriteFunc)GetProcAddress(advapi, "EventWrite"); // create async object used to invoke main thread from callback - CHECK_EQ(0, uv_async_init(uv_default_loop(), - &dispatch_etw_events_change_async, - etw_events_change_async)); + CHECK_EQ(0, + uv_async_init(uv_default_loop(), + &dispatch_etw_events_change_async, + etw_events_change_async)); uv_unref(reinterpret_cast(&dispatch_etw_events_change_async)); if (event_register) { @@ -190,7 +182,6 @@ void init_etw() { } } - void shutdown_etw() { if (advapi && event_unregister && node_provider) { event_unregister(node_provider); @@ -198,9 +189,8 @@ void shutdown_etw() { } events_enabled = 0; - v8::Isolate::GetCurrent()->SetJitCodeEventHandler( - v8::kJitCodeEventDefault, - nullptr); + v8::Isolate::GetCurrent()->SetJitCodeEventHandler(v8::kJitCodeEventDefault, + nullptr); if (advapi) { FreeLibrary(advapi); diff --git a/src/node_win32_etw_provider.h b/src/node_win32_etw_provider.h index 0f84a86f0ac3fc..203863372adb73 100644 --- a/src/node_win32_etw_provider.h +++ b/src/node_win32_etw_provider.h @@ -24,52 +24,62 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_dtrace.h" #include +#include "node_dtrace.h" namespace node { #if defined(_MSC_VER) -# define INLINE __forceinline +#define INLINE __forceinline #else -# define INLINE inline +#define INLINE inline #endif -typedef ULONG (NTAPI* EventRegisterFunc)( - LPCGUID ProviderId, - PENABLECALLBACK EnableCallback, - PVOID CallbackContext, - PREGHANDLE RegHandle -); +typedef ULONG(NTAPI* EventRegisterFunc)(LPCGUID ProviderId, + PENABLECALLBACK EnableCallback, + PVOID CallbackContext, + PREGHANDLE RegHandle); -typedef ULONG (NTAPI* EventUnregisterFunc)( - REGHANDLE RegHandle -); +typedef ULONG(NTAPI* EventUnregisterFunc)(REGHANDLE RegHandle); -typedef ULONG (NTAPI* EventWriteFunc)( - REGHANDLE RegHandle, - PCEVENT_DESCRIPTOR EventDescriptor, - ULONG UserDataCount, - PEVENT_DATA_DESCRIPTOR UserData -); +typedef ULONG(NTAPI* EventWriteFunc)(REGHANDLE RegHandle, + PCEVENT_DESCRIPTOR EventDescriptor, + ULONG UserDataCount, + PEVENT_DATA_DESCRIPTOR UserData); void init_etw(); void shutdown_etw(); INLINE void NODE_HTTP_SERVER_REQUEST(node_dtrace_http_server_request_t* req, - node_dtrace_connection_t* conn, const char* remote, int port, - const char* method, const char* url, int fd); + node_dtrace_connection_t* conn, + const char* remote, + int port, + const char* method, + const char* url, + int fd); INLINE void NODE_HTTP_SERVER_RESPONSE(node_dtrace_connection_t* conn, - const char* remote, int port, int fd); + const char* remote, + int port, + int fd); INLINE void NODE_HTTP_CLIENT_REQUEST(node_dtrace_http_client_request_t* req, - node_dtrace_connection_t* conn, const char* remote, int port, - const char* method, const char* url, int fd); + node_dtrace_connection_t* conn, + const char* remote, + int port, + const char* method, + const char* url, + int fd); INLINE void NODE_HTTP_CLIENT_RESPONSE(node_dtrace_connection_t* conn, - const char* remote, int port, int fd); + const char* remote, + int port, + int fd); INLINE void NODE_NET_SERVER_CONNECTION(node_dtrace_connection_t* conn, - const char* remote, int port, int fd); + const char* remote, + int port, + int fd); INLINE void NODE_NET_STREAM_END(node_dtrace_connection_t* conn, - const char* remote, int port, int fd); + const char* remote, + int port, + int fd); INLINE void NODE_GC_START(v8::GCType type, v8::GCCallbackFlags flags, v8::Isolate* isolate); diff --git a/src/node_win32_perfctr_provider.cc b/src/node_win32_perfctr_provider.cc index 7e94db9fed97ea..f4f210c079c981 100644 --- a/src/node_win32_perfctr_provider.cc +++ b/src/node_win32_perfctr_provider.cc @@ -20,74 +20,70 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #define __INIT_node_perfctr_provider_IMP -#include "node_counters.h" #include "node_win32_perfctr_provider.h" +#include "node_counters.h" #include #include "node_perfctr_provider.h" +typedef ULONG(WINAPI* PerfStartProviderExFunc)(__in LPGUID ProviderGuid, + __in_opt PPERF_PROVIDER_CONTEXT + ProviderContext, + __out PHANDLE Provider); -typedef ULONG (WINAPI* PerfStartProviderExFunc)( - __in LPGUID ProviderGuid, - __in_opt PPERF_PROVIDER_CONTEXT ProviderContext, - __out PHANDLE Provider); +typedef ULONG(WINAPI* PerfStopProviderFunc)(__in HANDLE ProviderHandle); -typedef ULONG (WINAPI* PerfStopProviderFunc)( - __in HANDLE ProviderHandle); - -typedef ULONG (WINAPI* PerfSetCounterSetInfoFunc)( +typedef ULONG(WINAPI* PerfSetCounterSetInfoFunc)( __in HANDLE ProviderHandle, __inout_bcount(TemplateSize) PPERF_COUNTERSET_INFO Template, __in ULONG TemplateSize); -typedef PPERF_COUNTERSET_INSTANCE (WINAPI* PerfCreateInstanceFunc)( +typedef PPERF_COUNTERSET_INSTANCE(WINAPI* PerfCreateInstanceFunc)( __in HANDLE ProviderHandle, __in LPCGUID CounterSetGuid, __in PCWSTR Name, __in ULONG Id); -typedef ULONG (WINAPI* PerfDeleteInstanceFunc)( - __in HANDLE Provider, - __in PPERF_COUNTERSET_INSTANCE InstanceBlock); +typedef ULONG(WINAPI* PerfDeleteInstanceFunc)( + __in HANDLE Provider, __in PPERF_COUNTERSET_INSTANCE InstanceBlock); -typedef ULONG (WINAPI* PerfSetULongCounterValueFunc)( +typedef ULONG(WINAPI* PerfSetULongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONG Value); -typedef ULONG (WINAPI* PerfSetULongLongCounterValueFunc)( +typedef ULONG(WINAPI* PerfSetULongLongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONGLONG Value); -typedef ULONG (WINAPI* PerfIncrementULongCounterValueFunc)( +typedef ULONG(WINAPI* PerfIncrementULongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONG Value); -typedef ULONG (WINAPI* PerfIncrementULongLongCounterValueFunc)( +typedef ULONG(WINAPI* PerfIncrementULongLongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONGLONG Value); -typedef ULONG (WINAPI* PerfDecrementULongCounterValueFunc)( +typedef ULONG(WINAPI* PerfDecrementULongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONG Value); -typedef ULONG (WINAPI* PerfDecrementULongLongCounterValueFunc)( +typedef ULONG(WINAPI* PerfDecrementULongLongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONGLONG Value); - HMODULE advapimod; PerfStartProviderExFunc perfctr_startProvider; PerfStopProviderFunc perfctr_stopProvider; @@ -103,22 +99,19 @@ PerfDecrementULongLongCounterValueFunc perfctr_decrementULongLongValue; PPERF_COUNTERSET_INSTANCE perfctr_instance; - -#define NODE_COUNTER_HTTP_SERVER_REQUEST 1 -#define NODE_COUNTER_HTTP_SERVER_RESPONSE 2 -#define NODE_COUNTER_HTTP_CLIENT_REQUEST 3 -#define NODE_COUNTER_HTTP_CLIENT_RESPONSE 4 -#define NODE_COUNTER_SERVER_CONNS 5 -#define NODE_COUNTER_NET_BYTES_SENT 6 -#define NODE_COUNTER_NET_BYTES_RECV 7 -#define NODE_COUNTER_GC_PERCENTTIME 8 -#define NODE_COUNTER_PIPE_BYTES_SENT 9 -#define NODE_COUNTER_PIPE_BYTES_RECV 10 - +#define NODE_COUNTER_HTTP_SERVER_REQUEST 1 +#define NODE_COUNTER_HTTP_SERVER_RESPONSE 2 +#define NODE_COUNTER_HTTP_CLIENT_REQUEST 3 +#define NODE_COUNTER_HTTP_CLIENT_RESPONSE 4 +#define NODE_COUNTER_SERVER_CONNS 5 +#define NODE_COUNTER_NET_BYTES_SENT 6 +#define NODE_COUNTER_NET_BYTES_RECV 7 +#define NODE_COUNTER_GC_PERCENTTIME 8 +#define NODE_COUNTER_PIPE_BYTES_SENT 9 +#define NODE_COUNTER_PIPE_BYTES_RECV 10 namespace node { - HANDLE NodeCounterProvider = nullptr; void InitPerfCountersWin32() { @@ -126,9 +119,9 @@ void InitPerfCountersWin32() { PERF_PROVIDER_CONTEXT providerContext; // create instance name using pid -#define INST_MAX_LEN 32 -#define INST_PREFIX_LEN 5 -#define INST_PREFIX L"node_" +#define INST_MAX_LEN 32 +#define INST_PREFIX_LEN 5 +#define INST_PREFIX L"node_" wchar_t Inst[INST_MAX_LEN]; DWORD pid = GetCurrentProcessId(); @@ -137,42 +130,45 @@ void InitPerfCountersWin32() { advapimod = LoadLibraryW(L"advapi32.dll"); if (advapimod) { - perfctr_startProvider = (PerfStartProviderExFunc) - GetProcAddress(advapimod, "PerfStartProviderEx"); - perfctr_stopProvider = (PerfStopProviderFunc) - GetProcAddress(advapimod, "PerfStopProvider"); - perfctr_setCounterSetInfo = (PerfSetCounterSetInfoFunc) - GetProcAddress(advapimod, "PerfSetCounterSetInfo"); - perfctr_createInstance = (PerfCreateInstanceFunc) - GetProcAddress(advapimod, "PerfCreateInstance"); - perfctr_deleteInstance = (PerfDeleteInstanceFunc) - GetProcAddress(advapimod, "PerfDeleteInstance"); - perfctr_setULongValue = (PerfSetULongCounterValueFunc) - GetProcAddress(advapimod, "PerfSetULongCounterValue"); - perfctr_setULongLongValue = (PerfSetULongLongCounterValueFunc) - GetProcAddress(advapimod, "PerfSetULongLongCounterValue"); - perfctr_incrementULongValue = (PerfIncrementULongCounterValueFunc) - GetProcAddress(advapimod, "PerfIncrementULongCounterValue"); - perfctr_incrementULongLongValue = (PerfIncrementULongLongCounterValueFunc) - GetProcAddress(advapimod, "PerfIncrementULongLongCounterValue"); - perfctr_decrementULongValue = (PerfDecrementULongCounterValueFunc) - GetProcAddress(advapimod, "PerfDecrementULongCounterValue"); - perfctr_decrementULongLongValue = (PerfDecrementULongLongCounterValueFunc) - GetProcAddress(advapimod, "PerfDecrementULongLongCounterValue"); + perfctr_startProvider = (PerfStartProviderExFunc)GetProcAddress( + advapimod, "PerfStartProviderEx"); + perfctr_stopProvider = + (PerfStopProviderFunc)GetProcAddress(advapimod, "PerfStopProvider"); + perfctr_setCounterSetInfo = (PerfSetCounterSetInfoFunc)GetProcAddress( + advapimod, "PerfSetCounterSetInfo"); + perfctr_createInstance = + (PerfCreateInstanceFunc)GetProcAddress(advapimod, "PerfCreateInstance"); + perfctr_deleteInstance = + (PerfDeleteInstanceFunc)GetProcAddress(advapimod, "PerfDeleteInstance"); + perfctr_setULongValue = (PerfSetULongCounterValueFunc)GetProcAddress( + advapimod, "PerfSetULongCounterValue"); + perfctr_setULongLongValue = + (PerfSetULongLongCounterValueFunc)GetProcAddress( + advapimod, "PerfSetULongLongCounterValue"); + perfctr_incrementULongValue = + (PerfIncrementULongCounterValueFunc)GetProcAddress( + advapimod, "PerfIncrementULongCounterValue"); + perfctr_incrementULongLongValue = + (PerfIncrementULongLongCounterValueFunc)GetProcAddress( + advapimod, "PerfIncrementULongLongCounterValue"); + perfctr_decrementULongValue = + (PerfDecrementULongCounterValueFunc)GetProcAddress( + advapimod, "PerfDecrementULongCounterValue"); + perfctr_decrementULongLongValue = + (PerfDecrementULongLongCounterValueFunc)GetProcAddress( + advapimod, "PerfDecrementULongLongCounterValue"); ZeroMemory(&providerContext, sizeof(providerContext)); providerContext.ContextSize = sizeof(providerContext); - if (!perfctr_startProvider || - !perfctr_setCounterSetInfo || + if (!perfctr_startProvider || !perfctr_setCounterSetInfo || !perfctr_createInstance) { NodeCounterProvider = nullptr; return; } - status = perfctr_startProvider(&NodeCounterSetGuid, - &providerContext, - &NodeCounterProvider); + status = perfctr_startProvider( + &NodeCounterSetGuid, &providerContext, &NodeCounterProvider); if (status != ERROR_SUCCESS) { NodeCounterProvider = nullptr; return; @@ -187,10 +183,8 @@ void InitPerfCountersWin32() { return; } - perfctr_instance = perfctr_createInstance(NodeCounterProvider, - &NodeCounterSetGuid, - Inst, - 1); + perfctr_instance = perfctr_createInstance( + NodeCounterProvider, &NodeCounterSetGuid, Inst, 1); if (perfctr_instance == nullptr) { perfctr_stopProvider(NodeCounterProvider); NodeCounterProvider = nullptr; @@ -198,10 +192,8 @@ void InitPerfCountersWin32() { } } - void TermPerfCountersWin32() { - if (NodeCounterProvider != nullptr && - perfctr_stopProvider != nullptr) { + if (NodeCounterProvider != nullptr && perfctr_stopProvider != nullptr) { perfctr_stopProvider(NodeCounterProvider); NodeCounterProvider = nullptr; } @@ -212,7 +204,6 @@ void TermPerfCountersWin32() { } } - void NODE_COUNT_HTTP_SERVER_REQUEST() { if (NodeCounterProvider != nullptr && perfctr_incrementULongValue != nullptr) { @@ -223,7 +214,6 @@ void NODE_COUNT_HTTP_SERVER_REQUEST() { } } - void NODE_COUNT_HTTP_SERVER_RESPONSE() { if (NodeCounterProvider != nullptr && perfctr_incrementULongValue != nullptr) { @@ -234,7 +224,6 @@ void NODE_COUNT_HTTP_SERVER_RESPONSE() { } } - void NODE_COUNT_HTTP_CLIENT_REQUEST() { if (NodeCounterProvider != nullptr && perfctr_incrementULongValue != nullptr) { @@ -245,7 +234,6 @@ void NODE_COUNT_HTTP_CLIENT_REQUEST() { } } - void NODE_COUNT_HTTP_CLIENT_RESPONSE() { if (NodeCounterProvider != nullptr && perfctr_incrementULongValue != nullptr) { @@ -256,29 +244,22 @@ void NODE_COUNT_HTTP_CLIENT_RESPONSE() { } } - void NODE_COUNT_SERVER_CONN_OPEN() { if (NodeCounterProvider != nullptr && perfctr_incrementULongValue != nullptr) { - perfctr_incrementULongValue(NodeCounterProvider, - perfctr_instance, - NODE_COUNTER_SERVER_CONNS, - 1); + perfctr_incrementULongValue( + NodeCounterProvider, perfctr_instance, NODE_COUNTER_SERVER_CONNS, 1); } } - void NODE_COUNT_SERVER_CONN_CLOSE() { if (NodeCounterProvider != nullptr && perfctr_decrementULongValue != nullptr) { - perfctr_decrementULongValue(NodeCounterProvider, - perfctr_instance, - NODE_COUNTER_SERVER_CONNS, - 1); + perfctr_decrementULongValue( + NodeCounterProvider, perfctr_instance, NODE_COUNTER_SERVER_CONNS, 1); } } - void NODE_COUNT_NET_BYTES_SENT(int bytes) { if (NodeCounterProvider != nullptr && perfctr_incrementULongLongValue != nullptr) { @@ -289,7 +270,6 @@ void NODE_COUNT_NET_BYTES_SENT(int bytes) { } } - void NODE_COUNT_NET_BYTES_RECV(int bytes) { if (NodeCounterProvider != nullptr && perfctr_incrementULongLongValue != nullptr) { @@ -300,7 +280,6 @@ void NODE_COUNT_NET_BYTES_RECV(int bytes) { } } - uint64_t NODE_COUNT_GET_GC_RAWTIME() { LARGE_INTEGER timegc; if (QueryPerformanceCounter(&timegc)) { @@ -310,7 +289,6 @@ uint64_t NODE_COUNT_GET_GC_RAWTIME() { } } - void NODE_COUNT_GC_PERCENTTIME(unsigned int percent) { if (NodeCounterProvider != nullptr && perfctr_setULongValue != nullptr) { perfctr_setULongValue(NodeCounterProvider, @@ -320,7 +298,6 @@ void NODE_COUNT_GC_PERCENTTIME(unsigned int percent) { } } - void NODE_COUNT_PIPE_BYTES_SENT(int bytes) { if (NodeCounterProvider != nullptr && perfctr_incrementULongLongValue != nullptr) { @@ -331,7 +308,6 @@ void NODE_COUNT_PIPE_BYTES_SENT(int bytes) { } } - void NODE_COUNT_PIPE_BYTES_RECV(int bytes) { if (NodeCounterProvider != nullptr && perfctr_incrementULongLongValue != nullptr) { diff --git a/src/node_win32_perfctr_provider.h b/src/node_win32_perfctr_provider.h index 35185aa187e1f8..db20fad07c4ba9 100644 --- a/src/node_win32_perfctr_provider.h +++ b/src/node_win32_perfctr_provider.h @@ -25,16 +25,18 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #if defined(_MSC_VER) -# define INLINE __forceinline +#define INLINE __forceinline #else -# define INLINE inline +#define INLINE inline #endif namespace node { extern HANDLE NodeCounterProvider; -INLINE bool NODE_COUNTER_ENABLED() { return NodeCounterProvider != nullptr; } +INLINE bool NODE_COUNTER_ENABLED() { + return NodeCounterProvider != nullptr; +} void NODE_COUNT_HTTP_SERVER_REQUEST(); void NODE_COUNT_HTTP_SERVER_RESPONSE(); void NODE_COUNT_HTTP_CLIENT_REQUEST(); diff --git a/src/node_worker.cc b/src/node_worker.cc index d3bffba51f3954..f521db653571af 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -1,13 +1,13 @@ #include "node_worker.h" +#include "async_wrap-inl.h" +#include "async_wrap.h" #include "debug_utils.h" +#include "node_buffer.h" #include "node_errors.h" #include "node_internals.h" -#include "node_buffer.h" #include "node_perf.h" -#include "util.h" #include "util-inl.h" -#include "async_wrap.h" -#include "async_wrap-inl.h" +#include "util.h" #include @@ -48,8 +48,8 @@ Worker::Worker(Environment* env, Local wrap) Debug(this, "Creating worker with id %llu", thread_id_); wrap->Set(env->context(), env->thread_id_string(), - Number::New(env->isolate(), - static_cast(thread_id_))).FromJust(); + Number::New(env->isolate(), static_cast(thread_id_))) + .FromJust(); // Set up everything that needs to be set up in the parent environment. parent_port_ = MessagePort::New(env, env->context()); @@ -61,9 +61,9 @@ Worker::Worker(Environment* env, Local wrap) child_port_data_.reset(new MessagePortData(nullptr)); MessagePort::Entangle(parent_port_, child_port_data_.get()); - object()->Set(env->context(), - env->message_port_string(), - parent_port_->object()).FromJust(); + object() + ->Set(env->context(), env->message_port_string(), parent_port_->object()) + .FromJust(); array_buffer_allocator_.reset(CreateArrayBufferAllocator()); @@ -73,11 +73,13 @@ Worker::Worker(Environment* env, Local wrap) thread_exit_async_.reset(new uv_async_t); thread_exit_async_->data = this; - CHECK_EQ(uv_async_init(env->event_loop(), - thread_exit_async_.get(), - [](uv_async_t* handle) { - static_cast(handle->data)->OnThreadStopped(); - }), 0); + CHECK_EQ( + uv_async_init(env->event_loop(), + thread_exit_async_.get(), + [](uv_async_t* handle) { + static_cast(handle->data)->OnThreadStopped(); + }), + 0); { // Enter an environment capable of executing code in the child Isolate @@ -96,9 +98,7 @@ Worker::Worker(Environment* env, Local wrap) Context::Scope context_scope(context); // TODO(addaleax): Use CreateEnvironment(), or generally another public API. - env_.reset(new Environment(isolate_data_.get(), - context, - nullptr)); + env_.reset(new Environment(isolate_data_.get(), context, nullptr)); CHECK_NE(env_, nullptr); env_->set_abort_on_uncaught_exception(false); env_->set_worker_context(this); @@ -122,8 +122,7 @@ void Worker::Run() { std::string name = "WorkerThread "; name += std::to_string(thread_id_); TRACE_EVENT_METADATA1( - "__metadata", "thread_name", "name", - TRACE_STR_COPY(name.c_str())); + "__metadata", "thread_name", "name", TRACE_STR_COPY(name.c_str())); MultiIsolatePlatform* platform = isolate_data_->platform(); CHECK_NE(platform, nullptr); @@ -141,9 +140,8 @@ void Worker::Run() { HandleScope handle_scope(isolate_); Mutex::ScopedLock lock(mutex_); // Set up the message channel for receiving messages in the child. - child_port_ = MessagePort::New(env_.get(), - env_->context(), - std::move(child_port_data_)); + child_port_ = MessagePort::New( + env_.get(), env_->context(), std::move(child_port_data_)); // MessagePort::New() may return nullptr if execution is terminated // within it. if (child_port_ != nullptr) @@ -176,8 +174,7 @@ void Worker::Run() { platform->DrainTasks(isolate_); more = uv_loop_alive(&loop_); - if (more && !is_stopped()) - continue; + if (more && !is_stopped()) continue; EmitBeforeExit(env_.get()); @@ -193,19 +190,19 @@ void Worker::Run() { { int exit_code; bool stopped = is_stopped(); - if (!stopped) - exit_code = EmitExit(env_.get()); + if (!stopped) exit_code = EmitExit(env_.get()); Mutex::ScopedLock lock(mutex_); - if (exit_code_ == 0 && !stopped) - exit_code_ = exit_code; + if (exit_code_ == 0 && !stopped) exit_code_ = exit_code; - Debug(this, "Exiting thread for worker %llu with exit code %d", - thread_id_, exit_code_); + Debug(this, + "Exiting thread for worker %llu with exit code %d", + thread_id_, + exit_code_); } env_->set_can_call_into_js(false); - Isolate::DisallowJavascriptExecutionScope disallow_js(isolate_, - Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); + Isolate::DisallowJavascriptExecutionScope disallow_js( + isolate_, Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); // Grab the parent-to-child channel and render is unusable. MessagePort* child_port; @@ -254,8 +251,7 @@ void Worker::Run() { } void Worker::DisposeIsolate() { - if (isolate_ == nullptr) - return; + if (isolate_ == nullptr) return; Debug(this, "Worker %llu dispose isolate", thread_id_); CHECK(isolate_data_); @@ -269,20 +265,17 @@ void Worker::DisposeIsolate() { } void Worker::JoinThread() { - if (thread_joined_) - return; + if (thread_joined_) return; CHECK_EQ(uv_thread_join(&tid_), 0); thread_joined_ = true; env()->remove_sub_worker_context(this); if (thread_exit_async_) { - env()->CloseHandle(thread_exit_async_.release(), [](uv_async_t* async) { - delete async; - }); + env()->CloseHandle(thread_exit_async_.release(), + [](uv_async_t* async) { delete async; }); - if (scheduled_on_thread_stopped_) - OnThreadStopped(); + if (scheduled_on_thread_stopped_) OnThreadStopped(); } } @@ -310,9 +303,11 @@ void Worker::OnThreadStopped() { Context::Scope context_scope(env()->context()); // Reset the parent port as we're closing it now anyway. - object()->Set(env()->context(), - env()->message_port_string(), - Undefined(env()->isolate())).FromJust(); + object() + ->Set(env()->context(), + env()->message_port_string(), + Undefined(env()->isolate())) + .FromJust(); Local code = Integer::New(env()->isolate(), exit_code_); MakeCallback(env()->onexit_string(), 1, &code); @@ -359,9 +354,10 @@ void Worker::StartThread(const FunctionCallbackInfo& args) { w->env()->add_sub_worker_context(w); w->stopped_ = false; - CHECK_EQ(uv_thread_create(&w->tid_, [](void* arg) { - static_cast(arg)->Run(); - }, static_cast(w)), 0); + CHECK_EQ(uv_thread_create(&w->tid_, + [](void* arg) { static_cast(arg)->Run(); }, + static_cast(w)), + 0); w->thread_joined_ = false; } @@ -397,8 +393,7 @@ void Worker::Exit(int code) { CHECK_NE(env_, nullptr); stopped_ = true; exit_code_ = code; - if (child_port_ != nullptr) - child_port_->StopEventLoop(); + if (child_port_ != nullptr) child_port_->StopEventLoop(); isolate_->TerminateExecution(); } } @@ -442,10 +437,11 @@ void InitWorker(Local target, env->SetMethod(target, "getEnvMessagePort", GetEnvMessagePort); auto thread_id_string = FIXED_ONE_BYTE_STRING(env->isolate(), "threadId"); - target->Set(env->context(), - thread_id_string, - Number::New(env->isolate(), - static_cast(env->thread_id()))).FromJust(); + target + ->Set(env->context(), + thread_id_string, + Number::New(env->isolate(), static_cast(env->thread_id()))) + .FromJust(); } } // anonymous namespace diff --git a/src/node_worker.h b/src/node_worker.h index 33df36e04ce670..7ff9d81868b9ec 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -3,8 +3,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_messaging.h" #include +#include "node_messaging.h" namespace node { namespace worker { @@ -33,7 +33,6 @@ class Worker : public AsyncWrap { tracker->TrackField("parent_port", parent_port_); } - ADD_MEMORY_INFO_NAME(Worker) bool is_stopped() const; @@ -89,5 +88,4 @@ class Worker : public AsyncWrap { #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS - #endif // SRC_NODE_WORKER_H_ diff --git a/src/node_wrap.h b/src/node_wrap.h index 42caca2dc6452d..8432de6153c7cb 100644 --- a/src/node_wrap.h +++ b/src/node_wrap.h @@ -35,30 +35,29 @@ namespace node { // TODO(addaleax): Use real inheritance for the JS object templates to avoid // this unnecessary case switching. -#define WITH_GENERIC_UV_STREAM(env, obj, BODY) \ - do { \ - if (env->tcp_constructor_template().IsEmpty() == false && \ - env->tcp_constructor_template()->HasInstance(obj)) { \ - TCPWrap* const wrap = Unwrap(obj); \ - BODY \ - } else if (env->tty_constructor_template().IsEmpty() == false && \ - env->tty_constructor_template()->HasInstance(obj)) { \ - TTYWrap* const wrap = Unwrap(obj); \ - BODY \ - } else if (env->pipe_constructor_template().IsEmpty() == false && \ - env->pipe_constructor_template()->HasInstance(obj)) { \ - PipeWrap* const wrap = Unwrap(obj); \ - BODY \ - } \ - } while (0) +#define WITH_GENERIC_UV_STREAM(env, obj, BODY) \ + do { \ + if (env->tcp_constructor_template().IsEmpty() == false && \ + env->tcp_constructor_template()->HasInstance(obj)) { \ + TCPWrap* const wrap = Unwrap(obj); \ + BODY \ + } else if (env->tty_constructor_template().IsEmpty() == false && \ + env->tty_constructor_template()->HasInstance(obj)) { \ + TTYWrap* const wrap = Unwrap(obj); \ + BODY \ + } else if (env->pipe_constructor_template().IsEmpty() == false && \ + env->pipe_constructor_template()->HasInstance(obj)) { \ + PipeWrap* const wrap = Unwrap(obj); \ + BODY \ + } \ + } while (0) inline uv_stream_t* HandleToStream(Environment* env, v8::Local obj) { v8::HandleScope scope(env->isolate()); WITH_GENERIC_UV_STREAM(env, obj, { - if (wrap == nullptr) - return nullptr; + if (wrap == nullptr) return nullptr; return reinterpret_cast(wrap->UVHandle()); }); diff --git a/src/node_zlib.cc b/src/node_zlib.cc index 774d319249ce63..a052ced2b9fe89 100644 --- a/src/node_zlib.cc +++ b/src/node_zlib.cc @@ -94,7 +94,6 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { MakeWeak(); } - ~ZCtx() override { CHECK_EQ(false, write_in_progress_ && "write in progress"); Close(); @@ -130,14 +129,12 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { } } - static void Close(const FunctionCallbackInfo& args) { ZCtx* ctx; ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder()); ctx->Close(); } - // write(flush, in, in_off, in_len, out, out_off, out_len) template static void Write(const FunctionCallbackInfo& args) { @@ -157,11 +154,8 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { unsigned int flush = args[0]->Uint32Value(); - if (flush != Z_NO_FLUSH && - flush != Z_PARTIAL_FLUSH && - flush != Z_SYNC_FLUSH && - flush != Z_FULL_FLUSH && - flush != Z_FINISH && + if (flush != Z_NO_FLUSH && flush != Z_PARTIAL_FLUSH && + flush != Z_SYNC_FLUSH && flush != Z_FULL_FLUSH && flush != Z_FINISH && flush != Z_BLOCK) { CHECK(0 && "Invalid flush value"); } @@ -186,7 +180,7 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { in_len = args[3]->Uint32Value(); CHECK(Buffer::IsWithinBounds(in_off, in_len, Buffer::Length(in_buf))); - in = reinterpret_cast(Buffer::Data(in_buf) + in_off); + in = reinterpret_cast(Buffer::Data(in_buf) + in_off); } CHECK(Buffer::HasInstance(args[4])); @@ -194,7 +188,7 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { out_off = args[5]->Uint32Value(); out_len = args[6]->Uint32Value(); CHECK(Buffer::IsWithinBounds(out_off, out_len, Buffer::Length(out_buf))); - out = reinterpret_cast(Buffer::Data(out_buf) + out_off); + out = reinterpret_cast(Buffer::Data(out_buf) + out_off); ctx->strm_.avail_in = in_len; ctx->strm_.next_in = in; @@ -287,8 +281,7 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { // If data was encoded with dictionary (INFLATERAW will have it set in // SetDictionary, don't repeat that here) - if (mode_ != INFLATERAW && - err_ == Z_NEED_DICT && + if (mode_ != INFLATERAW && err_ == Z_NEED_DICT && dictionary_ != nullptr) { // Load it err_ = inflateSetDictionary(&strm_, dictionary_, dictionary_len_); @@ -303,9 +296,7 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { } } - while (strm_.avail_in > 0 && - mode_ == GUNZIP && - err_ == Z_STREAM_END && + while (strm_.avail_in > 0 && mode_ == GUNZIP && err_ == Z_STREAM_END && strm_.next_in[0] != 0x00) { // Bytes remain in input buffer. Perhaps this is another compressed // member in the same archive, or just trailing garbage. @@ -327,35 +318,33 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { // or shift the queue and call Process. } - bool CheckError() { // Acceptable error states depend on the type of zlib stream. switch (err_) { - case Z_OK: - case Z_BUF_ERROR: - if (strm_.avail_out != 0 && flush_ == Z_FINISH) { - Error("unexpected end of file"); + case Z_OK: + case Z_BUF_ERROR: + if (strm_.avail_out != 0 && flush_ == Z_FINISH) { + Error("unexpected end of file"); + return false; + } + case Z_STREAM_END: + // normal statuses, not fatal + break; + case Z_NEED_DICT: + if (dictionary_ == nullptr) + Error("Missing dictionary"); + else + Error("Bad dictionary"); + return false; + default: + // something else. + Error("Zlib error"); return false; - } - case Z_STREAM_END: - // normal statuses, not fatal - break; - case Z_NEED_DICT: - if (dictionary_ == nullptr) - Error("Missing dictionary"); - else - Error("Bad dictionary"); - return false; - default: - // something else. - Error("Zlib error"); - return false; } return true; } - // v8 land! void AfterThreadPoolWork(int status) override { AllocScope alloc_scope(this); @@ -372,20 +361,18 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { HandleScope handle_scope(env()->isolate()); Context::Scope context_scope(env()->context()); - if (!CheckError()) - return; + if (!CheckError()) return; write_result_[0] = strm_.avail_out; write_result_[1] = strm_.avail_in; // call the write() cb - Local cb = PersistentToLocal(env()->isolate(), - write_js_callback_); + Local cb = + PersistentToLocal(env()->isolate(), write_js_callback_); MakeCallback(cb, 0, nullptr); Unref(); - if (pending_close_) - Close(); + if (pending_close_) Close(); } // TODO(addaleax): Switch to modern error system (node_errors.h). @@ -398,18 +385,14 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { } HandleScope scope(env()->isolate()); - Local args[2] = { - OneByteString(env()->isolate(), message), - Number::New(env()->isolate(), err_) - }; + Local args[2] = {OneByteString(env()->isolate(), message), + Number::New(env()->isolate(), err_)}; MakeCallback(env()->onerror_string(), arraysize(args), args); // no hope of rescue. - if (write_in_progress_) - Unref(); + if (write_in_progress_) Unref(); write_in_progress_ = false; - if (pending_close_) - Close(); + if (pending_close_) Close(); } static void New(const FunctionCallbackInfo& args) { @@ -425,15 +408,15 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { // Refs: https://github.com/nodejs/node/issues/14161 if (args.Length() == 5) { fprintf(stderr, - "WARNING: You are likely using a version of node-tar or npm that " - "is incompatible with this version of Node.js.\nPlease use " - "either the version of npm that is bundled with Node.js, or " - "a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) " - "that is compatible with Node.js 9 and above.\n"); + "WARNING: You are likely using a version of node-tar or npm that " + "is incompatible with this version of Node.js.\nPlease use " + "either the version of npm that is bundled with Node.js, or " + "a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) " + "that is compatible with Node.js 9 and above.\n"); } - CHECK(args.Length() == 7 && - "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," - " dictionary)"); + CHECK(args.Length() == 7 && "init(windowBits, level, memLevel, strategy, " + "writeResult, writeCallback," + " dictionary)"); ZCtx* ctx; ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder()); @@ -442,28 +425,26 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { // But on the decompression side, a value of 0 for windowBits tells zlib // to use the window size in the zlib header of the compressed stream. int windowBits = args[0]->Uint32Value(); - if (!((windowBits == 0) && - (ctx->mode_ == INFLATE || - ctx->mode_ == GUNZIP || - ctx->mode_ == UNZIP))) { - CHECK((windowBits >= Z_MIN_WINDOWBITS && - windowBits <= Z_MAX_WINDOWBITS) && "invalid windowBits"); + if (!((windowBits == 0) && (ctx->mode_ == INFLATE || ctx->mode_ == GUNZIP || + ctx->mode_ == UNZIP))) { + CHECK( + (windowBits >= Z_MIN_WINDOWBITS && windowBits <= Z_MAX_WINDOWBITS) && + "invalid windowBits"); } int level = args[1]->Int32Value(); CHECK((level >= Z_MIN_LEVEL && level <= Z_MAX_LEVEL) && - "invalid compression level"); + "invalid compression level"); int memLevel = args[2]->Uint32Value(); CHECK((memLevel >= Z_MIN_MEMLEVEL && memLevel <= Z_MAX_MEMLEVEL) && - "invalid memlevel"); + "invalid memlevel"); int strategy = args[3]->Uint32Value(); - CHECK((strategy == Z_FILTERED || - strategy == Z_HUFFMAN_ONLY || - strategy == Z_RLE || - strategy == Z_FIXED || - strategy == Z_DEFAULT_STRATEGY) && "invalid strategy"); + CHECK((strategy == Z_FILTERED || strategy == Z_HUFFMAN_ONLY || + strategy == Z_RLE || strategy == Z_FIXED || + strategy == Z_DEFAULT_STRATEGY) && + "invalid strategy"); CHECK(args[4]->IsUint32Array()); Local array = args[4].As(); @@ -482,13 +463,20 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { memcpy(dictionary, dictionary_, dictionary_len); } - bool ret = Init(ctx, level, windowBits, memLevel, strategy, write_result, - write_js_callback, dictionary, dictionary_len); + bool ret = Init(ctx, + level, + windowBits, + memLevel, + strategy, + write_result, + write_js_callback, + dictionary, + dictionary_len); if (!ret) goto end; ctx->SetDictionary(); - end: + end: return args.GetReturnValue().Set(ret); } @@ -499,16 +487,21 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { ctx->Params(args[0]->Int32Value(), args[1]->Int32Value()); } - static void Reset(const FunctionCallbackInfo &args) { + static void Reset(const FunctionCallbackInfo& args) { ZCtx* ctx; ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder()); ctx->Reset(); ctx->SetDictionary(); } - static bool Init(ZCtx* ctx, int level, int windowBits, int memLevel, - int strategy, uint32_t* write_result, - Local write_js_callback, char* dictionary, + static bool Init(ZCtx* ctx, + int level, + int windowBits, + int memLevel, + int strategy, + uint32_t* write_result, + Local write_js_callback, + char* dictionary, size_t dictionary_len) { AllocScope alloc_scope(ctx); ctx->level_ = level; @@ -557,7 +550,7 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { UNREACHABLE(); } - ctx->dictionary_ = reinterpret_cast(dictionary); + ctx->dictionary_ = reinterpret_cast(dictionary); ctx->dictionary_len_ = dictionary_len; ctx->write_in_progress_ = false; @@ -578,8 +571,7 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { } void SetDictionary() { - if (dictionary_ == nullptr) - return; + if (dictionary_ == nullptr) return; err_ = Z_OK; @@ -650,10 +642,9 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { tracker->TrackThis(this); tracker->TrackFieldWithSize("dictionary", dictionary_len_); tracker->TrackFieldWithSize("zlib memory", - zlib_memory_ + unreported_allocations_); + zlib_memory_ + unreported_allocations_); } - ADD_MEMORY_INFO_NAME(ZCtx) private: @@ -678,9 +669,9 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { // field and later report it back from the main thread. static void* AllocForZlib(void* data, uInt items, uInt size) { ZCtx* ctx = static_cast(data); - size_t real_size = - MultiplyWithOverflowCheck(static_cast(items), - static_cast(size)) + sizeof(size_t); + size_t real_size = MultiplyWithOverflowCheck(static_cast(items), + static_cast(size)) + + sizeof(size_t); char* memory = UncheckedMalloc(real_size); if (UNLIKELY(memory == nullptr)) return nullptr; *reinterpret_cast(memory) = real_size; @@ -737,7 +728,6 @@ class ZCtx : public AsyncWrap, public ThreadPoolWork { size_t zlib_memory_ = 0; }; - void Initialize(Local target, Local unused, Local context, diff --git a/src/pipe_wrap.cc b/src/pipe_wrap.cc index a6044b6b267e47..55474d1120f298 100644 --- a/src/pipe_wrap.cc +++ b/src/pipe_wrap.cc @@ -22,6 +22,7 @@ #include "pipe_wrap.h" #include "async_wrap.h" +#include "connect_wrap.h" #include "connection_wrap.h" #include "env-inl.h" #include "handle_wrap.h" @@ -29,7 +30,6 @@ #include "node_buffer.h" #include "node_internals.h" #include "node_wrap.h" -#include "connect_wrap.h" #include "stream_base-inl.h" #include "stream_wrap.h" #include "util-inl.h" @@ -50,7 +50,6 @@ using v8::Value; using AsyncHooks = Environment::AsyncHooks; - Local PipeWrap::Instantiate(Environment* env, AsyncWrap* parent, PipeWrap::SocketType type) { @@ -65,7 +64,6 @@ Local PipeWrap::Instantiate(Environment* env, return handle_scope.Escape(instance); } - void PipeWrap::Initialize(Local target, Local unused, Local context) { @@ -109,12 +107,13 @@ void PipeWrap::Initialize(Local target, NODE_DEFINE_CONSTANT(constants, IPC); NODE_DEFINE_CONSTANT(constants, UV_READABLE); NODE_DEFINE_CONSTANT(constants, UV_WRITABLE); - target->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "constants"), - constants).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "constants"), + constants) + .FromJust(); } - void PipeWrap::New(const FunctionCallbackInfo& args) { // This constructor should not be exposed to public javascript. // Therefore we assert that we are not trying to call this as a @@ -148,7 +147,6 @@ void PipeWrap::New(const FunctionCallbackInfo& args) { new PipeWrap(env, args.This(), provider, ipc); } - PipeWrap::PipeWrap(Environment* env, Local object, ProviderType provider, @@ -159,7 +157,6 @@ PipeWrap::PipeWrap(Environment* env, // Suggestion: uv_pipe_init() returns void. } - void PipeWrap::Bind(const FunctionCallbackInfo& args) { PipeWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -168,7 +165,6 @@ void PipeWrap::Bind(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } - #ifdef _WIN32 void PipeWrap::SetPendingInstances(const FunctionCallbackInfo& args) { PipeWrap* wrap; @@ -178,29 +174,24 @@ void PipeWrap::SetPendingInstances(const FunctionCallbackInfo& args) { } #endif - void PipeWrap::Fchmod(const v8::FunctionCallbackInfo& args) { PipeWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); CHECK(args[0]->IsInt32()); int mode = args[0].As()->Value(); - int err = uv_pipe_chmod(reinterpret_cast(&wrap->handle_), - mode); + int err = uv_pipe_chmod(reinterpret_cast(&wrap->handle_), mode); args.GetReturnValue().Set(err); } - void PipeWrap::Listen(const FunctionCallbackInfo& args) { PipeWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); int backlog = args[0]->Int32Value(); - int err = uv_listen(reinterpret_cast(&wrap->handle_), - backlog, - OnConnection); + int err = uv_listen( + reinterpret_cast(&wrap->handle_), backlog, OnConnection); args.GetReturnValue().Set(err); } - void PipeWrap::Open(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -216,7 +207,6 @@ void PipeWrap::Open(const FunctionCallbackInfo& args) { env->isolate()->ThrowException(UVException(err, "uv_pipe_open")); } - void PipeWrap::Connect(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -231,15 +221,11 @@ void PipeWrap::Connect(const FunctionCallbackInfo& args) { ConnectWrap* req_wrap = new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_PIPECONNECTWRAP); - req_wrap->Dispatch(uv_pipe_connect, - &wrap->handle_, - *name, - AfterConnect); + req_wrap->Dispatch(uv_pipe_connect, &wrap->handle_, *name, AfterConnect); args.GetReturnValue().Set(0); // uv_pipe_connect() doesn't return errors. } - } // namespace node NODE_BUILTIN_MODULE_CONTEXT_AWARE(pipe_wrap, node::PipeWrap::Initialize) diff --git a/src/pipe_wrap.h b/src/pipe_wrap.h index 7faf5145abdcfe..2556bf9459daf9 100644 --- a/src/pipe_wrap.h +++ b/src/pipe_wrap.h @@ -32,11 +32,7 @@ namespace node { class PipeWrap : public ConnectionWrap { public: - enum SocketType { - SOCKET, - SERVER, - IPC - }; + enum SocketType { SOCKET, SERVER, IPC }; static v8::Local Instantiate(Environment* env, AsyncWrap* parent, @@ -70,7 +66,6 @@ class PipeWrap : public ConnectionWrap { static void Fchmod(const v8::FunctionCallbackInfo& args); }; - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/process_wrap.cc b/src/process_wrap.cc index b54e17f21192d8..64fe1fb134a719 100644 --- a/src/process_wrap.cc +++ b/src/process_wrap.cc @@ -26,8 +26,8 @@ #include "stream_base-inl.h" #include "util-inl.h" -#include #include +#include namespace node { @@ -117,9 +117,8 @@ class ProcessWrap : public HandleWrap { Local handle = stdio->Get(context, handle_key).ToLocalChecked().As(); CHECK(!handle.IsEmpty()); - options->stdio[i].data.stream = - reinterpret_cast( - Unwrap(handle)->UVHandle()); + options->stdio[i].data.stream = reinterpret_cast( + Unwrap(handle)->UVHandle()); } else if (type->Equals(env->wrap_string())) { Local handle_key = env->handle_string(); Local handle = @@ -216,7 +215,7 @@ class ProcessWrap : public HandleWrap { if (!env_v.IsEmpty() && env_v->IsArray()) { Local env_opt = Local::Cast(env_v); int envc = env_opt->Length(); - CHECK_GT(envc + 1, 0); // Check for overflow. + CHECK_GT(envc + 1, 0); // Check for overflow. options.env = new char*[envc + 1]; // Heap allocated to detect errors. for (int i = 0; i < envc; i++) { node::Utf8Value pair(env->isolate(), @@ -260,19 +259,21 @@ class ProcessWrap : public HandleWrap { if (err == 0) { CHECK_EQ(wrap->process_.data, wrap); - wrap->object()->Set(context, env->pid_string(), - Integer::New(env->isolate(), - wrap->process_.pid)).FromJust(); + wrap->object() + ->Set(context, + env->pid_string(), + Integer::New(env->isolate(), wrap->process_.pid)) + .FromJust(); } if (options.args) { for (int i = 0; options.args[i]; i++) free(options.args[i]); - delete [] options.args; + delete[] options.args; } if (options.env) { for (int i = 0; options.env[i]; i++) free(options.env[i]); - delete [] options.env; + delete[] options.env; } delete[] options.stdio; @@ -301,9 +302,8 @@ class ProcessWrap : public HandleWrap { Context::Scope context_scope(env->context()); Local argv[] = { - Number::New(env->isolate(), static_cast(exit_status)), - OneByteString(env->isolate(), signo_string(term_signal)) - }; + Number::New(env->isolate(), static_cast(exit_status)), + OneByteString(env->isolate(), signo_string(term_signal))}; wrap->MakeCallback(env->onexit_string(), arraysize(argv), argv); } @@ -311,7 +311,6 @@ class ProcessWrap : public HandleWrap { uv_process_t process_; }; - } // anonymous namespace } // namespace node diff --git a/src/req_wrap-inl.h b/src/req_wrap-inl.h index 4f9da1c4f35d9e..c5e9e1359b6c45 100644 --- a/src/req_wrap-inl.h +++ b/src/req_wrap-inl.h @@ -3,9 +3,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "req_wrap.h" #include "async_wrap-inl.h" #include "env-inl.h" +#include "req_wrap.h" #include "util-inl.h" #include "uv.h" @@ -16,7 +16,6 @@ ReqWrap::ReqWrap(Environment* env, v8::Local object, AsyncWrap::ProviderType provider) : AsyncWrap(env, object, provider) { - // FIXME(bnoordhuis) The fact that a reinterpret_cast is needed is // arguably a good indicator that there should be more than one queue. env->req_wrap_queue()->PushBack(reinterpret_cast*>(this)); @@ -66,8 +65,8 @@ struct CallLibuvFunction; // Detect `int uv_foo(uv_loop_t* loop, uv_req_t* request, ...);`. template -struct CallLibuvFunction { - using T = int(*)(uv_loop_t*, ReqT*, Args...); +struct CallLibuvFunction { + using T = int (*)(uv_loop_t*, ReqT*, Args...); template static int Call(T fn, uv_loop_t* loop, ReqT* req, PassedArgs... args) { return fn(loop, req, args...); @@ -76,8 +75,8 @@ struct CallLibuvFunction { // Detect `int uv_foo(uv_req_t* request, ...);`. template -struct CallLibuvFunction { - using T = int(*)(ReqT*, Args...); +struct CallLibuvFunction { + using T = int (*)(ReqT*, Args...); template static int Call(T fn, uv_loop_t* loop, ReqT* req, PassedArgs... args) { return fn(req, args...); @@ -86,8 +85,8 @@ struct CallLibuvFunction { // Detect `void uv_foo(uv_req_t* request, ...);`. template -struct CallLibuvFunction { - using T = void(*)(ReqT*, Args...); +struct CallLibuvFunction { + using T = void (*)(ReqT*, Args...); template static int Call(T fn, uv_loop_t* loop, ReqT* req, PassedArgs... args) { fn(req, args...); @@ -112,8 +111,8 @@ struct MakeLibuvRequestCallback { // Match the `void callback(uv_req_t*, ...);` signature that all libuv // callbacks use. template -struct MakeLibuvRequestCallback { - using F = void(*)(ReqT* req, Args... args); +struct MakeLibuvRequestCallback { + using F = void (*)(ReqT* req, Args... args); static void Wrapper(ReqT* req, Args... args) { ReqWrap* req_wrap = ContainerOf(&ReqWrap::req_, req); @@ -154,8 +153,7 @@ int ReqWrap::Dispatch(LibuvFunction fn, Args... args) { env()->event_loop(), req(), MakeLibuvRequestCallback::For(this, args)...); - if (err >= 0) - env()->IncreaseWaitingRequestCounter(); + if (err >= 0) env()->IncreaseWaitingRequestCounter(); return err; } diff --git a/src/sharedarraybuffer_metadata.cc b/src/sharedarraybuffer_metadata.cc index 3d5b96051ead6e..0e12324ecbfefb 100644 --- a/src/sharedarraybuffer_metadata.cc +++ b/src/sharedarraybuffer_metadata.cc @@ -1,6 +1,6 @@ #include "sharedarraybuffer_metadata.h" -#include "base_object.h" #include "base_object-inl.h" +#include "base_object.h" #include "node_errors.h" using v8::Context; @@ -22,16 +22,15 @@ namespace { // Yield a JS constructor for SABLifetimePartner objects in the form of a // standard API object, that has a single field for containing the raw // SABLiftimePartner* pointer. -Local GetSABLifetimePartnerConstructor( - Environment* env, Local context) { +Local GetSABLifetimePartnerConstructor(Environment* env, + Local context) { Local templ; templ = env->sab_lifetimepartner_constructor_template(); - if (!templ.IsEmpty()) - return templ->GetFunction(context).ToLocalChecked(); + if (!templ.IsEmpty()) return templ->GetFunction(context).ToLocalChecked(); templ = BaseObject::MakeLazilyInitializedJSTemplate(env); - templ->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), - "SABLifetimePartner")); + templ->SetClassName( + FIXED_ONE_BYTE_STRING(env->isolate(), "SABLifetimePartner")); env->set_sab_lifetimepartner_constructor_template(templ); return GetSABLifetimePartnerConstructor(env, context); @@ -42,8 +41,7 @@ class SABLifetimePartner : public BaseObject { SABLifetimePartner(Environment* env, Local obj, SharedArrayBufferMetadataReference r) - : BaseObject(env, obj), - reference(r) { + : BaseObject(env, obj), reference(r) { MakeWeak(); } @@ -60,20 +58,17 @@ class SABLifetimePartner : public BaseObject { SharedArrayBufferMetadataReference SharedArrayBufferMetadata::ForSharedArrayBuffer( - Environment* env, - Local context, - Local source) { + Environment* env, Local context, Local source) { Local lifetime_partner; - if (!source->GetPrivate(context, - env->sab_lifetimepartner_symbol()) - .ToLocal(&lifetime_partner)) { + if (!source->GetPrivate(context, env->sab_lifetimepartner_symbol()) + .ToLocal(&lifetime_partner)) { return nullptr; } if (lifetime_partner->IsObject() && - env->sab_lifetimepartner_constructor_template() - ->HasInstance(lifetime_partner)) { + env->sab_lifetimepartner_constructor_template()->HasInstance( + lifetime_partner)) { CHECK(source->IsExternal()); SABLifetimePartner* partner = Unwrap(lifetime_partner.As()); @@ -91,30 +86,26 @@ SharedArrayBufferMetadata::ForSharedArrayBuffer( } SharedArrayBuffer::Contents contents = source->Externalize(); - SharedArrayBufferMetadataReference r(new SharedArrayBufferMetadata( - contents.Data(), contents.ByteLength())); + SharedArrayBufferMetadataReference r( + new SharedArrayBufferMetadata(contents.Data(), contents.ByteLength())); if (r->AssignToSharedArrayBuffer(env, context, source).IsNothing()) return nullptr; return r; } Maybe SharedArrayBufferMetadata::AssignToSharedArrayBuffer( - Environment* env, Local context, - Local target) { + Environment* env, Local context, Local target) { CHECK(target->IsExternal()); Local ctor = GetSABLifetimePartnerConstructor(env, context); Local obj; - if (!ctor->NewInstance(context).ToLocal(&obj)) - return Nothing(); + if (!ctor->NewInstance(context).ToLocal(&obj)) return Nothing(); new SABLifetimePartner(env, obj, shared_from_this()); - return target->SetPrivate(context, - env->sab_lifetimepartner_symbol(), - obj); + return target->SetPrivate(context, env->sab_lifetimepartner_symbol(), obj); } SharedArrayBufferMetadata::SharedArrayBufferMetadata(void* data, size_t size) - : data(data), size(size) { } + : data(data), size(size) {} SharedArrayBufferMetadata::~SharedArrayBufferMetadata() { free(data); diff --git a/src/sharedarraybuffer_metadata.h b/src/sharedarraybuffer_metadata.h index 84bfd224fabcf8..c82bbb1fdbc2a7 100644 --- a/src/sharedarraybuffer_metadata.h +++ b/src/sharedarraybuffer_metadata.h @@ -3,8 +3,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" #include +#include "node.h" namespace node { namespace worker { @@ -39,10 +39,10 @@ class SharedArrayBufferMetadata Environment* env, v8::Local context); SharedArrayBufferMetadata(SharedArrayBufferMetadata&& other) = delete; - SharedArrayBufferMetadata& operator=( - SharedArrayBufferMetadata&& other) = delete; - SharedArrayBufferMetadata& operator=( - const SharedArrayBufferMetadata&) = delete; + SharedArrayBufferMetadata& operator=(SharedArrayBufferMetadata&& other) = + delete; + SharedArrayBufferMetadata& operator=(const SharedArrayBufferMetadata&) = + delete; SharedArrayBufferMetadata(const SharedArrayBufferMetadata&) = delete; private: @@ -63,5 +63,4 @@ class SharedArrayBufferMetadata #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS - #endif // SRC_SHAREDARRAYBUFFER_METADATA_H_ diff --git a/src/signal_wrap.cc b/src/signal_wrap.cc index 463a8a50d5e772..e37f43a6d30973 100644 --- a/src/signal_wrap.cc +++ b/src/signal_wrap.cc @@ -123,9 +123,7 @@ class SignalWrap : public HandleWrap { uv_signal_t handle_; }; - } // anonymous namespace } // namespace node - NODE_BUILTIN_MODULE_CONTEXT_AWARE(signal_wrap, node::SignalWrap::Initialize) diff --git a/src/spawn_sync.cc b/src/spawn_sync.cc index 1e966e42c68ce6..ad2aa868ded871 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -27,7 +27,6 @@ #include - namespace node { using v8::Array; @@ -44,12 +43,7 @@ using v8::Object; using v8::String; using v8::Value; - -SyncProcessOutputBuffer::SyncProcessOutputBuffer() - : used_(0), - next_(nullptr) { -} - +SyncProcessOutputBuffer::SyncProcessOutputBuffer() : used_(0), next_(nullptr) {} void SyncProcessOutputBuffer::OnAlloc(size_t suggested_size, uv_buf_t* buf) const { @@ -59,40 +53,33 @@ void SyncProcessOutputBuffer::OnAlloc(size_t suggested_size, *buf = uv_buf_init(data_ + used(), available()); } - void SyncProcessOutputBuffer::OnRead(const uv_buf_t* buf, size_t nread) { // If we hand out the same chunk twice, this should catch it. CHECK_EQ(buf->base, data_ + used()); used_ += static_cast(nread); } - size_t SyncProcessOutputBuffer::Copy(char* dest) const { memcpy(dest, data_, used()); return used(); } - unsigned int SyncProcessOutputBuffer::available() const { return sizeof data_ - used(); } - unsigned int SyncProcessOutputBuffer::used() const { return used_; } - SyncProcessOutputBuffer* SyncProcessOutputBuffer::next() const { return next_; } - void SyncProcessOutputBuffer::set_next(SyncProcessOutputBuffer* next) { next_ = next; } - SyncProcessStdioPipe::SyncProcessStdioPipe(SyncProcessRunner* process_handler, bool readable, bool writable, @@ -113,7 +100,6 @@ SyncProcessStdioPipe::SyncProcessStdioPipe(SyncProcessRunner* process_handler, CHECK(readable || writable); } - SyncProcessStdioPipe::~SyncProcessStdioPipe() { CHECK(lifecycle_ == kUninitialized || lifecycle_ == kClosed); @@ -126,13 +112,11 @@ SyncProcessStdioPipe::~SyncProcessStdioPipe() { } } - int SyncProcessStdioPipe::Initialize(uv_loop_t* loop) { CHECK_EQ(lifecycle_, kUninitialized); int r = uv_pipe_init(loop, uv_pipe(), 0); - if (r < 0) - return r; + if (r < 0) return r; uv_pipe()->data = this; @@ -140,7 +124,6 @@ int SyncProcessStdioPipe::Initialize(uv_loop_t* loop) { return 0; } - int SyncProcessStdioPipe::Start() { CHECK_EQ(lifecycle_, kInitialized); @@ -152,30 +135,23 @@ int SyncProcessStdioPipe::Start() { if (input_buffer_.len > 0) { CHECK_NOT_NULL(input_buffer_.base); - int r = uv_write(&write_req_, - uv_stream(), - &input_buffer_, - 1, - WriteCallback); - if (r < 0) - return r; + int r = + uv_write(&write_req_, uv_stream(), &input_buffer_, 1, WriteCallback); + if (r < 0) return r; } int r = uv_shutdown(&shutdown_req_, uv_stream(), ShutdownCallback); - if (r < 0) - return r; + if (r < 0) return r; } if (writable()) { int r = uv_read_start(uv_stream(), AllocCallback, ReadCallback); - if (r < 0) - return r; + if (r < 0) return r; } return 0; } - void SyncProcessStdioPipe::Close() { CHECK(lifecycle_ == kInitialized || lifecycle_ == kStarted); @@ -184,7 +160,6 @@ void SyncProcessStdioPipe::Close() { lifecycle_ = kClosing; } - Local SyncProcessStdioPipe::GetOutputAsBuffer(Environment* env) const { size_t length = OutputLength(); Local js_buffer = Buffer::New(env, length).ToLocalChecked(); @@ -192,46 +167,37 @@ Local SyncProcessStdioPipe::GetOutputAsBuffer(Environment* env) const { return js_buffer; } - bool SyncProcessStdioPipe::readable() const { return readable_; } - bool SyncProcessStdioPipe::writable() const { return writable_; } - uv_stdio_flags SyncProcessStdioPipe::uv_flags() const { unsigned int flags; flags = UV_CREATE_PIPE; - if (readable()) - flags |= UV_READABLE_PIPE; - if (writable()) - flags |= UV_WRITABLE_PIPE; + if (readable()) flags |= UV_READABLE_PIPE; + if (writable()) flags |= UV_WRITABLE_PIPE; return static_cast(flags); } - uv_pipe_t* SyncProcessStdioPipe::uv_pipe() const { CHECK_LT(lifecycle_, kClosing); return &uv_pipe_; } - uv_stream_t* SyncProcessStdioPipe::uv_stream() const { return reinterpret_cast(uv_pipe()); } - uv_handle_t* SyncProcessStdioPipe::uv_handle() const { return reinterpret_cast(uv_pipe()); } - size_t SyncProcessStdioPipe::OutputLength() const { SyncProcessOutputBuffer* buf; size_t size = 0; @@ -242,7 +208,6 @@ size_t SyncProcessStdioPipe::OutputLength() const { return size; } - void SyncProcessStdioPipe::CopyOutput(char* dest) const { SyncProcessOutputBuffer* buf; size_t offset = 0; @@ -251,7 +216,6 @@ void SyncProcessStdioPipe::CopyOutput(char* dest) const { offset += buf->Copy(dest + offset); } - void SyncProcessStdioPipe::OnAlloc(size_t suggested_size, uv_buf_t* buf) { // This function assumes that libuv will never allocate two buffers for the // same stream at the same time. There's an assert in @@ -273,7 +237,6 @@ void SyncProcessStdioPipe::OnAlloc(size_t suggested_size, uv_buf_t* buf) { last_output_buffer_->OnAlloc(suggested_size, buf); } - void SyncProcessStdioPipe::OnRead(const uv_buf_t* buf, ssize_t nread) { if (nread == UV_EOF) { // Libuv implicitly stops reading on EOF. @@ -289,30 +252,23 @@ void SyncProcessStdioPipe::OnRead(const uv_buf_t* buf, ssize_t nread) { } } - void SyncProcessStdioPipe::OnWriteDone(int result) { - if (result < 0) - SetError(result); + if (result < 0) SetError(result); } - void SyncProcessStdioPipe::OnShutdownDone(int result) { - if (result < 0) - SetError(result); + if (result < 0) SetError(result); } - void SyncProcessStdioPipe::OnClose() { lifecycle_ = kClosed; } - void SyncProcessStdioPipe::SetError(int error) { CHECK_NE(error, 0); process_handler_->SetPipeError(error); } - void SyncProcessStdioPipe::AllocCallback(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { @@ -321,23 +277,20 @@ void SyncProcessStdioPipe::AllocCallback(uv_handle_t* handle, self->OnAlloc(suggested_size, buf); } - void SyncProcessStdioPipe::ReadCallback(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { SyncProcessStdioPipe* self = - reinterpret_cast(stream->data); + reinterpret_cast(stream->data); self->OnRead(buf, nread); } - void SyncProcessStdioPipe::WriteCallback(uv_write_t* req, int result) { SyncProcessStdioPipe* self = reinterpret_cast(req->handle->data); self->OnWriteDone(result); } - void SyncProcessStdioPipe::ShutdownCallback(uv_shutdown_t* req, int result) { SyncProcessStdioPipe* self = reinterpret_cast(req->handle->data); @@ -346,20 +299,17 @@ void SyncProcessStdioPipe::ShutdownCallback(uv_shutdown_t* req, int result) { // when the other end has closed the connection fails with ENOTCONN. // Libuv is not the right place to handle that because it can't tell // if the error is genuine but we here can. - if (result == UV_ENOTCONN) - result = 0; + if (result == UV_ENOTCONN) result = 0; self->OnShutdownDone(result); } - void SyncProcessStdioPipe::CloseCallback(uv_handle_t* handle) { SyncProcessStdioPipe* self = reinterpret_cast(handle->data); self->OnClose(); } - void SyncProcessRunner::Initialize(Local target, Local unused, Local context) { @@ -367,7 +317,6 @@ void SyncProcessRunner::Initialize(Local target, env->SetMethod(target, "spawn", Spawn); } - void SyncProcessRunner::Spawn(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); env->PrintSyncTrace(); @@ -376,7 +325,6 @@ void SyncProcessRunner::Spawn(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(result); } - SyncProcessRunner::SyncProcessRunner(Environment* env) : max_buffer_(0), timeout_(0), @@ -410,9 +358,7 @@ SyncProcessRunner::SyncProcessRunner(Environment* env) lifecycle_(kUninitialized), - env_(env) { -} - + env_(env) {} SyncProcessRunner::~SyncProcessRunner() { CHECK_EQ(lifecycle_, kHandlesClosed); @@ -425,12 +371,10 @@ SyncProcessRunner::~SyncProcessRunner() { delete[] uv_stdio_containers_; } - Environment* SyncProcessRunner::env() const { return env_; } - Local SyncProcessRunner::Run(Local options) { EscapableHandleScope scope(env()->isolate()); @@ -444,7 +388,6 @@ Local SyncProcessRunner::Run(Local options) { return scope.Escape(result); } - void SyncProcessRunner::TryInitializeAndRunLoop(Local options) { int r; @@ -454,18 +397,15 @@ void SyncProcessRunner::TryInitializeAndRunLoop(Local options) { lifecycle_ = kInitialized; uv_loop_ = new uv_loop_t; - if (uv_loop_ == nullptr) - return SetError(UV_ENOMEM); + if (uv_loop_ == nullptr) return SetError(UV_ENOMEM); CHECK_EQ(uv_loop_init(uv_loop_), 0); r = ParseOptions(options); - if (r < 0) - return SetError(r); + if (r < 0) return SetError(r); if (timeout_ > 0) { r = uv_timer_init(uv_loop_, &uv_timer_); - if (r < 0) - return SetError(r); + if (r < 0) return SetError(r); uv_unref(reinterpret_cast(&uv_timer_)); @@ -477,22 +417,19 @@ void SyncProcessRunner::TryInitializeAndRunLoop(Local options) { // which implicitly stops it, so there is no risk that the timeout callback // runs when the process didn't start. r = uv_timer_start(&uv_timer_, KillTimerCallback, timeout_, 0); - if (r < 0) - return SetError(r); + if (r < 0) return SetError(r); } uv_process_options_.exit_cb = ExitCallback; r = uv_spawn(uv_loop_, &uv_process_, &uv_process_options_); - if (r < 0) - return SetError(r); + if (r < 0) return SetError(r); uv_process_.data = this; for (uint32_t i = 0; i < stdio_count_; i++) { SyncProcessStdioPipe* h = stdio_pipes_[i].get(); if (h != nullptr) { r = h->Start(); - if (r < 0) - return SetPipeError(r); + if (r < 0) return SetPipeError(r); } } @@ -505,7 +442,6 @@ void SyncProcessRunner::TryInitializeAndRunLoop(Local options) { CHECK_GE(exit_status_, 0); } - void SyncProcessRunner::CloseHandlesAndDeleteLoop() { CHECK_LT(lifecycle_, kHandlesClosed); @@ -526,8 +462,7 @@ void SyncProcessRunner::CloseHandlesAndDeleteLoop() { // Give closing watchers a chance to finish closing and get their close // callbacks called. int r = uv_run(uv_loop_, UV_RUN_DEFAULT); - if (r < 0) - ABORT(); + if (r < 0) ABORT(); CheckedUvLoopClose(uv_loop_); delete uv_loop_; @@ -542,7 +477,6 @@ void SyncProcessRunner::CloseHandlesAndDeleteLoop() { lifecycle_ = kHandlesClosed; } - void SyncProcessRunner::CloseStdioPipes() { CHECK_LT(lifecycle_, kHandlesClosed); @@ -551,15 +485,13 @@ void SyncProcessRunner::CloseStdioPipes() { CHECK_NOT_NULL(uv_loop_); for (uint32_t i = 0; i < stdio_count_; i++) { - if (stdio_pipes_[i]) - stdio_pipes_[i]->Close(); + if (stdio_pipes_[i]) stdio_pipes_[i]->Close(); } stdio_pipes_initialized_ = false; } } - void SyncProcessRunner::CloseKillTimer() { CHECK_LT(lifecycle_, kHandlesClosed); @@ -575,11 +507,9 @@ void SyncProcessRunner::CloseKillTimer() { } } - void SyncProcessRunner::Kill() { // Only attempt to kill once. - if (killed_) - return; + if (killed_) return; killed_ = true; // We might get here even if the process we spawned has already exited. This @@ -608,7 +538,6 @@ void SyncProcessRunner::Kill() { CloseKillTimer(); } - void SyncProcessRunner::IncrementBufferSizeAndCheckOverflow(ssize_t length) { buffered_output_size_ += length; @@ -618,22 +547,18 @@ void SyncProcessRunner::IncrementBufferSizeAndCheckOverflow(ssize_t length) { } } - void SyncProcessRunner::OnExit(int64_t exit_status, int term_signal) { - if (exit_status < 0) - return SetError(static_cast(exit_status)); + if (exit_status < 0) return SetError(static_cast(exit_status)); exit_status_ = exit_status; term_signal_ = term_signal; } - void SyncProcessRunner::OnKillTimerTimeout() { SetError(UV_ETIMEDOUT); Kill(); } - int SyncProcessRunner::GetError() { if (error_ != 0) return error_; @@ -641,19 +566,14 @@ int SyncProcessRunner::GetError() { return pipe_error_; } - void SyncProcessRunner::SetError(int error) { - if (error_ == 0) - error_ = error; + if (error_ == 0) error_ = error; } - void SyncProcessRunner::SetPipeError(int pipe_error) { - if (pipe_error_ == 0) - pipe_error_ = pipe_error; + if (pipe_error_ == 0) pipe_error_ = pipe_error; } - Local SyncProcessRunner::BuildResultObject() { EscapableHandleScope scope(env()->isolate()); Local context = env()->context(); @@ -661,50 +581,60 @@ Local SyncProcessRunner::BuildResultObject() { Local js_result = Object::New(env()->isolate()); if (GetError() != 0) { - js_result->Set(context, env()->error_string(), - Integer::New(env()->isolate(), GetError())).FromJust(); + js_result + ->Set(context, + env()->error_string(), + Integer::New(env()->isolate(), GetError())) + .FromJust(); } if (exit_status_ >= 0) { if (term_signal_ > 0) { - js_result->Set(context, env()->status_string(), - Null(env()->isolate())).FromJust(); + js_result->Set(context, env()->status_string(), Null(env()->isolate())) + .FromJust(); } else { - js_result->Set(context, env()->status_string(), - Number::New(env()->isolate(), - static_cast(exit_status_))).FromJust(); + js_result + ->Set( + context, + env()->status_string(), + Number::New(env()->isolate(), static_cast(exit_status_))) + .FromJust(); } } else { // If exit_status_ < 0 the process was never started because of some error. - js_result->Set(context, env()->status_string(), - Null(env()->isolate())).FromJust(); + js_result->Set(context, env()->status_string(), Null(env()->isolate())) + .FromJust(); } if (term_signal_ > 0) - js_result->Set(context, env()->signal_string(), - String::NewFromUtf8(env()->isolate(), - signo_string(term_signal_), - v8::NewStringType::kNormal) - .ToLocalChecked()) + js_result + ->Set(context, + env()->signal_string(), + String::NewFromUtf8(env()->isolate(), + signo_string(term_signal_), + v8::NewStringType::kNormal) + .ToLocalChecked()) .FromJust(); else - js_result->Set(context, env()->signal_string(), - Null(env()->isolate())).FromJust(); + js_result->Set(context, env()->signal_string(), Null(env()->isolate())) + .FromJust(); if (exit_status_ >= 0) - js_result->Set(context, env()->output_string(), - BuildOutputArray()).FromJust(); + js_result->Set(context, env()->output_string(), BuildOutputArray()) + .FromJust(); else - js_result->Set(context, env()->output_string(), - Null(env()->isolate())).FromJust(); + js_result->Set(context, env()->output_string(), Null(env()->isolate())) + .FromJust(); - js_result->Set(context, env()->pid_string(), - Number::New(env()->isolate(), uv_process_.pid)).FromJust(); + js_result + ->Set(context, + env()->pid_string(), + Number::New(env()->isolate(), uv_process_.pid)) + .FromJust(); return scope.Escape(js_result); } - Local SyncProcessRunner::BuildOutputArray() { CHECK_GE(lifecycle_, kInitialized); CHECK(stdio_pipes_); @@ -724,13 +654,11 @@ Local SyncProcessRunner::BuildOutputArray() { return scope.Escape(js_output); } - int SyncProcessRunner::ParseOptions(Local js_value) { HandleScope scope(env()->isolate()); int r; - if (!js_value->IsObject()) - return UV_EINVAL; + if (!js_value->IsObject()) return UV_EINVAL; Local context = env()->context(); Local js_options = js_value.As(); @@ -738,23 +666,20 @@ int SyncProcessRunner::ParseOptions(Local js_value) { Local js_file = js_options->Get(context, env()->file_string()).ToLocalChecked(); r = CopyJsString(js_file, &file_buffer_); - if (r < 0) - return r; + if (r < 0) return r; uv_process_options_.file = file_buffer_; Local js_args = js_options->Get(context, env()->args_string()).ToLocalChecked(); r = CopyJsStringArray(js_args, &args_buffer_); - if (r < 0) - return r; + if (r < 0) return r; uv_process_options_.args = reinterpret_cast(args_buffer_); Local js_cwd = js_options->Get(context, env()->cwd_string()).ToLocalChecked(); if (IsSet(js_cwd)) { r = CopyJsString(js_cwd, &cwd_buffer_); - if (r < 0) - return r; + if (r < 0) return r; uv_process_options_.cwd = cwd_buffer_; } @@ -762,8 +687,7 @@ int SyncProcessRunner::ParseOptions(Local js_value) { js_options->Get(context, env()->env_pairs_string()).ToLocalChecked(); if (IsSet(js_env_pairs)) { r = CopyJsStringArray(js_env_pairs, &env_buffer_); - if (r < 0) - return r; + if (r < 0) return r; uv_process_options_.env = reinterpret_cast(env_buffer_); } @@ -827,19 +751,16 @@ int SyncProcessRunner::ParseOptions(Local js_value) { Local js_stdio = js_options->Get(context, env()->stdio_string()).ToLocalChecked(); r = ParseStdioOptions(js_stdio); - if (r < 0) - return r; + if (r < 0) return r; return 0; } - int SyncProcessRunner::ParseStdioOptions(Local js_value) { HandleScope scope(env()->isolate()); Local js_stdio_options; - if (!js_value->IsArray()) - return UV_EINVAL; + if (!js_value->IsArray()) return UV_EINVAL; Local context = env()->context(); js_stdio_options = js_value.As(); @@ -847,20 +768,17 @@ int SyncProcessRunner::ParseStdioOptions(Local js_value) { stdio_count_ = js_stdio_options->Length(); uv_stdio_containers_ = new uv_stdio_container_t[stdio_count_]; - stdio_pipes_.reset( - new std::unique_ptr[stdio_count_]()); + stdio_pipes_.reset(new std::unique_ptr[stdio_count_]()); stdio_pipes_initialized_ = true; for (uint32_t i = 0; i < stdio_count_; i++) { Local js_stdio_option = js_stdio_options->Get(context, i).ToLocalChecked(); - if (!js_stdio_option->IsObject()) - return UV_EINVAL; + if (!js_stdio_option->IsObject()) return UV_EINVAL; int r = ParseStdioOption(i, js_stdio_option.As()); - if (r < 0) - return r; + if (r < 0) return r; } uv_process_options_.stdio = uv_stdio_containers_; @@ -869,7 +787,6 @@ int SyncProcessRunner::ParseStdioOptions(Local js_value) { return 0; } - int SyncProcessRunner::ParseStdioOption(int child_fd, Local js_stdio_option) { Local context = env()->context(); @@ -884,10 +801,13 @@ int SyncProcessRunner::ParseStdioOption(int child_fd, Local ws = env()->writable_string(); bool readable = js_stdio_option->Get(context, rs) - .ToLocalChecked()->BooleanValue(context).FromJust(); - bool writable = - js_stdio_option->Get(context, ws) - .ToLocalChecked()->BooleanValue(context).FromJust(); + .ToLocalChecked() + ->BooleanValue(context) + .FromJust(); + bool writable = js_stdio_option->Get(context, ws) + .ToLocalChecked() + ->BooleanValue(context) + .FromJust(); uv_buf_t buf = uv_buf_init(nullptr, 0); @@ -910,7 +830,9 @@ int SyncProcessRunner::ParseStdioOption(int child_fd, } else if (js_type->StrictEquals(env()->inherit_string()) || js_type->StrictEquals(env()->fd_string())) { int inherit_fd = js_stdio_option->Get(context, env()->fd_string()) - .ToLocalChecked()->Int32Value(context).FromJust(); + .ToLocalChecked() + ->Int32Value(context) + .FromJust(); return AddStdioInheritFD(child_fd, inherit_fd); } else { @@ -919,7 +841,6 @@ int SyncProcessRunner::ParseStdioOption(int child_fd, } } - int SyncProcessRunner::AddStdioIgnore(uint32_t child_fd) { CHECK_LT(child_fd, stdio_count_); CHECK(!stdio_pipes_[child_fd]); @@ -929,7 +850,6 @@ int SyncProcessRunner::AddStdioIgnore(uint32_t child_fd) { return 0; } - int SyncProcessRunner::AddStdioPipe(uint32_t child_fd, bool readable, bool writable, @@ -954,7 +874,6 @@ int SyncProcessRunner::AddStdioPipe(uint32_t child_fd, return 0; } - int SyncProcessRunner::AddStdioInheritFD(uint32_t child_fd, int inherit_fd) { CHECK_LT(child_fd, stdio_count_); CHECK(!stdio_pipes_[child_fd]); @@ -965,12 +884,10 @@ int SyncProcessRunner::AddStdioInheritFD(uint32_t child_fd, int inherit_fd) { return 0; } - bool SyncProcessRunner::IsSet(Local value) { return !value->IsUndefined() && !value->IsNull(); } - int SyncProcessRunner::CopyJsString(Local js_value, const char** target) { Isolate* isolate = env()->isolate(); @@ -995,9 +912,7 @@ int SyncProcessRunner::CopyJsString(Local js_value, return 0; } - -int SyncProcessRunner::CopyJsStringArray(Local js_value, - char** target) { +int SyncProcessRunner::CopyJsStringArray(Local js_value, char** target) { Isolate* isolate = env()->isolate(); Local js_array; uint32_t length; @@ -1005,8 +920,7 @@ int SyncProcessRunner::CopyJsStringArray(Local js_value, char** list; char* buffer; - if (!js_value->IsArray()) - return UV_EINVAL; + if (!js_value->IsArray()) return UV_EINVAL; Local context = env()->context(); js_array = js_value.As()->Clone().As(); @@ -1039,11 +953,8 @@ int SyncProcessRunner::CopyJsStringArray(Local js_value, for (uint32_t i = 0; i < length; i++) { list[i] = buffer + data_offset; auto value = js_array->Get(context, i).ToLocalChecked(); - data_offset += StringBytes::Write(isolate, - buffer + data_offset, - -1, - value, - UTF8); + data_offset += + StringBytes::Write(isolate, buffer + data_offset, -1, value, UTF8); buffer[data_offset++] = '\0'; data_offset = ROUND_UP(data_offset, sizeof(void*)); } @@ -1054,7 +965,6 @@ int SyncProcessRunner::CopyJsStringArray(Local js_value, return 0; } - void SyncProcessRunner::ExitCallback(uv_process_t* handle, int64_t exit_status, int term_signal) { @@ -1063,13 +973,11 @@ void SyncProcessRunner::ExitCallback(uv_process_t* handle, self->OnExit(exit_status, term_signal); } - void SyncProcessRunner::KillTimerCallback(uv_timer_t* handle) { SyncProcessRunner* self = reinterpret_cast(handle->data); self->OnKillTimerTimeout(); } - void SyncProcessRunner::KillTimerCloseCallback(uv_handle_t* handle) { // No-op. } @@ -1077,4 +985,4 @@ void SyncProcessRunner::KillTimerCloseCallback(uv_handle_t* handle) { } // namespace node NODE_BUILTIN_MODULE_CONTEXT_AWARE(spawn_sync, - node::SyncProcessRunner::Initialize) + node::SyncProcessRunner::Initialize) diff --git a/src/spawn_sync.h b/src/spawn_sync.h index fed14532960326..1302f6d23a74af 100644 --- a/src/spawn_sync.h +++ b/src/spawn_sync.h @@ -24,18 +24,15 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_internals.h" #include "node_buffer.h" +#include "node_internals.h" namespace node { - - class SyncProcessOutputBuffer; class SyncProcessStdioPipe; class SyncProcessRunner; - class SyncProcessOutputBuffer { static const unsigned int kBufferSize = 65536; @@ -61,7 +58,6 @@ class SyncProcessOutputBuffer { SyncProcessOutputBuffer* next_; }; - class SyncProcessStdioPipe { enum Lifecycle { kUninitialized = 0, @@ -130,13 +126,8 @@ class SyncProcessStdioPipe { Lifecycle lifecycle_; }; - class SyncProcessRunner { - enum Lifecycle { - kUninitialized = 0, - kInitialized, - kHandlesClosed - }; + enum Lifecycle { kUninitialized = 0, kInitialized, kHandlesClosed }; public: static void Initialize(v8::Local target, diff --git a/src/stream_base-inl.h b/src/stream_base-inl.h index 027b938d30df1c..ad68fbae6b6a81 100644 --- a/src/stream_base-inl.h +++ b/src/stream_base-inl.h @@ -5,13 +5,12 @@ #include "stream_base.h" -#include "node.h" #include "env-inl.h" +#include "node.h" #include "v8.h" namespace node { -using v8::Signature; using v8::External; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; @@ -20,6 +19,7 @@ using v8::Local; using v8::Object; using v8::PropertyAttribute; using v8::PropertyCallbackInfo; +using v8::Signature; using v8::String; using v8::Value; @@ -46,8 +46,7 @@ inline v8::Local StreamReq::object() { } inline StreamListener::~StreamListener() { - if (stream_ != nullptr) - stream_->RemoveStreamListener(this); + if (stream_ != nullptr) stream_->RemoveStreamListener(this); } inline void StreamListener::PassReadErrorToPreviousListener(ssize_t nread) { @@ -73,8 +72,7 @@ inline StreamResource::~StreamResource() { // in `OnStreamDestroy()` implementations easier, because they // may call generic cleanup functions which can just remove the // listener unconditionally. - if (listener == listener_) - RemoveStreamListener(listener_); + if (listener == listener_) RemoveStreamListener(listener_); } } @@ -97,7 +95,8 @@ inline void StreamResource::RemoveStreamListener(StreamListener* listener) { // Remove from the linked list. for (current = listener_, previous = nullptr; /* No loop condition because we want a crash if listener is not found */ - ; previous = current, current = current->previous_listener_) { + ; // NOLINT(whitespace/semicolon) + previous = current, current = current->previous_listener_) { CHECK_NOT_NULL(current); if (current == listener) { if (previous != nullptr) @@ -123,8 +122,7 @@ inline void StreamResource::EmitRead(ssize_t nread, const uv_buf_t& buf) { #ifdef DEBUG v8::SealHandleScope handle_scope(v8::Isolate::GetCurrent()); #endif - if (nread > 0) - bytes_read_ += static_cast(nread); + if (nread > 0) bytes_read_ += static_cast(nread); listener_->OnStreamRead(nread, buf); } @@ -163,9 +161,9 @@ inline int StreamBase::Shutdown(v8::Local req_wrap_obj) { HandleScope handle_scope(env->isolate()); if (req_wrap_obj.IsEmpty()) { - req_wrap_obj = - env->shutdown_wrap_template() - ->NewInstance(env->context()).ToLocalChecked(); + req_wrap_obj = env->shutdown_wrap_template() + ->NewInstance(env->context()) + .ToLocalChecked(); StreamReq::ResetObject(req_wrap_obj); } @@ -186,32 +184,30 @@ inline int StreamBase::Shutdown(v8::Local req_wrap_obj) { return err; } -inline StreamWriteResult StreamBase::Write( - uv_buf_t* bufs, - size_t count, - uv_stream_t* send_handle, - v8::Local req_wrap_obj) { +inline StreamWriteResult StreamBase::Write(uv_buf_t* bufs, + size_t count, + uv_stream_t* send_handle, + v8::Local req_wrap_obj) { Environment* env = stream_env(); int err; size_t total_bytes = 0; - for (size_t i = 0; i < count; ++i) - total_bytes += bufs[i].len; + for (size_t i = 0; i < count; ++i) total_bytes += bufs[i].len; bytes_written_ += total_bytes; if (send_handle == nullptr) { err = DoTryWrite(&bufs, &count); if (err != 0 || count == 0) { - return StreamWriteResult { false, err, nullptr, total_bytes }; + return StreamWriteResult{false, err, nullptr, total_bytes}; } } HandleScope handle_scope(env->isolate()); if (req_wrap_obj.IsEmpty()) { - req_wrap_obj = - env->write_wrap_template() - ->NewInstance(env->context()).ToLocalChecked(); + req_wrap_obj = env->write_wrap_template() + ->NewInstance(env->context()) + .ToLocalChecked(); StreamReq::ResetObject(req_wrap_obj); } @@ -232,18 +228,16 @@ inline StreamWriteResult StreamBase::Write( ClearError(); } - return StreamWriteResult { async, err, req_wrap, total_bytes }; + return StreamWriteResult{async, err, req_wrap, total_bytes}; } template SimpleShutdownWrap::SimpleShutdownWrap( - StreamBase* stream, - v8::Local req_wrap_obj) - : ShutdownWrap(stream, req_wrap_obj), - OtherBase(stream->stream_env(), - req_wrap_obj, - AsyncWrap::PROVIDER_SHUTDOWNWRAP) { -} + StreamBase* stream, v8::Local req_wrap_obj) + : ShutdownWrap(stream, req_wrap_obj), + OtherBase(stream->stream_env(), + req_wrap_obj, + AsyncWrap::PROVIDER_SHUTDOWNWRAP) {} inline ShutdownWrap* StreamBase::CreateShutdownWrap( v8::Local object) { @@ -251,17 +245,13 @@ inline ShutdownWrap* StreamBase::CreateShutdownWrap( } template -SimpleWriteWrap::SimpleWriteWrap( - StreamBase* stream, - v8::Local req_wrap_obj) - : WriteWrap(stream, req_wrap_obj), - OtherBase(stream->stream_env(), - req_wrap_obj, - AsyncWrap::PROVIDER_WRITEWRAP) { -} +SimpleWriteWrap::SimpleWriteWrap(StreamBase* stream, + v8::Local req_wrap_obj) + : WriteWrap(stream, req_wrap_obj), + OtherBase( + stream->stream_env(), req_wrap_obj, AsyncWrap::PROVIDER_WRITEWRAP) {} -inline WriteWrap* StreamBase::CreateWriteWrap( - v8::Local object) { +inline WriteWrap* StreamBase::CreateWriteWrap(v8::Local object) { return new SimpleWriteWrap(this, object); } @@ -269,9 +259,8 @@ template void StreamBase::AddMethods(Environment* env, Local t) { HandleScope scope(env->isolate()); - enum PropertyAttribute attributes = - static_cast( - v8::ReadOnly | v8::DontDelete | v8::DontEnum); + enum PropertyAttribute attributes = static_cast( + v8::ReadOnly | v8::DontDelete | v8::DontEnum); Local signature = Signature::New(env->isolate(), t); @@ -300,10 +289,8 @@ void StreamBase::AddMethods(Environment* env, Local t) { v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasNoSideEffect); - t->PrototypeTemplate()->SetAccessorProperty(env->fd_string(), - get_fd_templ, - Local(), - attributes); + t->PrototypeTemplate()->SetAccessorProperty( + env->fd_string(), get_fd_templ, Local(), attributes); t->PrototypeTemplate()->SetAccessorProperty(env->external_stream_string(), get_external_templ, @@ -324,35 +311,28 @@ void StreamBase::AddMethods(Environment* env, Local t) { env->SetProtoMethod(t, "readStop", JSMethod); env->SetProtoMethod(t, "shutdown", JSMethod); env->SetProtoMethod(t, "writev", JSMethod); - env->SetProtoMethod(t, - "writeBuffer", - JSMethod); - env->SetProtoMethod(t, - "writeAsciiString", - JSMethod >); - env->SetProtoMethod(t, - "writeUtf8String", - JSMethod >); - env->SetProtoMethod(t, - "writeUcs2String", - JSMethod >); + env->SetProtoMethod( + t, "writeBuffer", JSMethod); + env->SetProtoMethod( + t, "writeAsciiString", JSMethod >); + env->SetProtoMethod( + t, "writeUtf8String", JSMethod >); + env->SetProtoMethod( + t, "writeUcs2String", JSMethod >); env->SetProtoMethod(t, "writeLatin1String", JSMethod >); } - template void StreamBase::GetFD(const FunctionCallbackInfo& args) { // Mimic implementation of StreamBase::GetFD() and UDPWrap::GetFD(). Base* handle; - ASSIGN_OR_RETURN_UNWRAP(&handle, - args.This(), - args.GetReturnValue().Set(UV_EINVAL)); + ASSIGN_OR_RETURN_UNWRAP( + &handle, args.This(), args.GetReturnValue().Set(UV_EINVAL)); StreamBase* wrap = static_cast(handle); - if (!wrap->IsAlive()) - return args.GetReturnValue().Set(UV_EINVAL); + if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL); args.GetReturnValue().Set(wrap->GetFD()); } @@ -360,9 +340,7 @@ void StreamBase::GetFD(const FunctionCallbackInfo& args) { template void StreamBase::GetBytesRead(const FunctionCallbackInfo& args) { Base* handle; - ASSIGN_OR_RETURN_UNWRAP(&handle, - args.This(), - args.GetReturnValue().Set(0)); + ASSIGN_OR_RETURN_UNWRAP(&handle, args.This(), args.GetReturnValue().Set(0)); StreamBase* wrap = static_cast(handle); // uint64_t -> double. 53bits is enough for all real cases. @@ -372,9 +350,7 @@ void StreamBase::GetBytesRead(const FunctionCallbackInfo& args) { template void StreamBase::GetBytesWritten(const FunctionCallbackInfo& args) { Base* handle; - ASSIGN_OR_RETURN_UNWRAP(&handle, - args.This(), - args.GetReturnValue().Set(0)); + ASSIGN_OR_RETURN_UNWRAP(&handle, args.This(), args.GetReturnValue().Set(0)); StreamBase* wrap = static_cast(handle); // uint64_t -> double. 53bits is enough for all real cases. @@ -391,7 +367,6 @@ void StreamBase::GetExternal(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ext); } - template & args)> void StreamBase::JSMethod(const FunctionCallbackInfo& args) { @@ -399,14 +374,12 @@ void StreamBase::JSMethod(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&handle, args.Holder()); StreamBase* wrap = static_cast(handle); - if (!wrap->IsAlive()) - return args.GetReturnValue().Set(UV_EINVAL); + if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL); AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(handle); args.GetReturnValue().Set((wrap->*Method)(args)); } - inline void ShutdownWrap::OnDone(int status) { stream()->EmitAfterShutdown(this, status); Dispose(); @@ -450,7 +423,6 @@ inline void StreamReq::ResetObject(v8::Local obj) { obj->SetAlignedPointerInInternalField(StreamReq::kStreamReqField, nullptr); } - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/stream_base.cc b/src/stream_base.cc index bb46ea1febbca0..e4612ace1aecff 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -1,12 +1,12 @@ #include "stream_base-inl.h" #include "stream_wrap.h" +#include "env-inl.h" +#include "js_stream.h" #include "node.h" #include "node_buffer.h" #include "node_errors.h" #include "node_internals.h" -#include "env-inl.h" -#include "js_stream.h" #include "string_bytes.h" #include "util-inl.h" #include "v8.h" @@ -36,22 +36,18 @@ template int StreamBase::WriteString( template int StreamBase::WriteString( const FunctionCallbackInfo& args); - struct Free { void operator()(char* ptr) const { free(ptr); } }; - int StreamBase::ReadStartJS(const FunctionCallbackInfo& args) { return ReadStart(); } - int StreamBase::ReadStopJS(const FunctionCallbackInfo& args) { return ReadStop(); } - int StreamBase::Shutdown(const FunctionCallbackInfo& args) { CHECK(args[0]->IsObject()); Local req_wrap_obj = args[0].As(); @@ -59,18 +55,18 @@ int StreamBase::Shutdown(const FunctionCallbackInfo& args) { return Shutdown(req_wrap_obj); } -inline void SetWriteResultPropertiesOnWrapObject( - Environment* env, - Local req_wrap_obj, - const StreamWriteResult& res) { - req_wrap_obj->Set( - env->context(), - env->bytes_string(), - Number::New(env->isolate(), res.bytes)).FromJust(); - req_wrap_obj->Set( - env->context(), - env->async(), - Boolean::New(env->isolate(), res.async)).FromJust(); +inline void SetWriteResultPropertiesOnWrapObject(Environment* env, + Local req_wrap_obj, + const StreamWriteResult& res) { + req_wrap_obj + ->Set(env->context(), + env->bytes_string(), + Number::New(env->isolate(), res.bytes)) + .FromJust(); + req_wrap_obj + ->Set( + env->context(), env->async(), Boolean::New(env->isolate(), res.async)) + .FromJust(); } int StreamBase::Writev(const FunctionCallbackInfo& args) { @@ -99,14 +95,13 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { for (size_t i = 0; i < count; i++) { Local chunk = chunks->Get(i * 2); - if (Buffer::HasInstance(chunk)) - continue; - // Buffer chunk, no additional storage required + if (Buffer::HasInstance(chunk)) continue; + // Buffer chunk, no additional storage required // String chunk Local string = chunk->ToString(env->context()).ToLocalChecked(); - enum encoding encoding = ParseEncoding(env->isolate(), - chunks->Get(i * 2 + 1)); + enum encoding encoding = + ParseEncoding(env->isolate(), chunks->Get(i * 2 + 1)); size_t chunk_size; if (encoding == UTF8 && string->Length() > 65535) chunk_size = StringBytes::Size(env->isolate(), string, encoding); @@ -116,8 +111,7 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { storage_size += chunk_size; } - if (storage_size > INT_MAX) - return UV_ENOBUFS; + if (storage_size > INT_MAX) return UV_ENOBUFS; } else { for (size_t i = 0; i < count; i++) { Local chunk = chunks->Get(i); @@ -148,13 +142,10 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { size_t str_size = storage_size - offset; Local string = chunk->ToString(env->context()).ToLocalChecked(); - enum encoding encoding = ParseEncoding(env->isolate(), - chunks->Get(i * 2 + 1)); - str_size = StringBytes::Write(env->isolate(), - str_storage, - str_size, - string, - encoding); + enum encoding encoding = + ParseEncoding(env->isolate(), chunks->Get(i * 2 + 1)); + str_size = StringBytes::Write( + env->isolate(), str_storage, str_size, string, encoding); bufs[i].base = str_storage; bufs[i].len = str_size; offset += str_size; @@ -169,7 +160,6 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { return res.err; } - int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { CHECK(args[0]->IsObject()); @@ -195,7 +185,6 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { return res.err; } - template int StreamBase::WriteString(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -205,8 +194,7 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { Local req_wrap_obj = args[0].As(); Local string = args[1].As(); Local send_handle_obj; - if (args[2]->IsObject()) - send_handle_obj = args[2].As(); + if (args[2]->IsObject()) send_handle_obj = args[2].As(); int err; @@ -219,8 +207,7 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { else storage_size = StringBytes::StorageSize(env->isolate(), string, enc); - if (storage_size > INT_MAX) - return UV_ENOBUFS; + if (storage_size > INT_MAX) return UV_ENOBUFS; // Try writing immediately if write size isn't too big char stack_storage[16384]; // 16kb @@ -231,11 +218,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { bool try_write = storage_size <= sizeof(stack_storage) && (!IsIPCPipe() || send_handle_obj.IsEmpty()); if (try_write) { - data_size = StringBytes::Write(env->isolate(), - stack_storage, - storage_size, - string, - enc); + data_size = StringBytes::Write( + env->isolate(), stack_storage, storage_size, string, enc); buf = uv_buf_init(stack_storage, data_size); uv_buf_t* bufs = &buf; @@ -251,9 +235,10 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { if (err != 0 || count == 0) { req_wrap_obj->Set(env->context(), env->async(), False(env->isolate())) .FromJust(); - req_wrap_obj->Set(env->context(), - env->bytes_string(), - Integer::NewFromUnsigned(env->isolate(), data_size)) + req_wrap_obj + ->Set(env->context(), + env->bytes_string(), + Integer::NewFromUnsigned(env->isolate(), data_size)) .FromJust(); return err; } @@ -272,11 +257,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { } else { // Write it data = std::unique_ptr(Malloc(storage_size)); - data_size = StringBytes::Write(env->isolate(), - data.get(), - storage_size, - string, - enc); + data_size = StringBytes::Write( + env->isolate(), data.get(), storage_size, string, enc); } CHECK_LE(data_size, storage_size); @@ -305,60 +287,47 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { return res.err; } - void StreamBase::CallJSOnreadMethod(ssize_t nread, Local buf) { Environment* env = env_; - Local argv[] = { - Integer::New(env->isolate(), nread), - buf - }; + Local argv[] = {Integer::New(env->isolate(), nread), buf}; - if (argv[1].IsEmpty()) - argv[1] = Undefined(env->isolate()); + if (argv[1].IsEmpty()) argv[1] = Undefined(env->isolate()); AsyncWrap* wrap = GetAsyncWrap(); CHECK_NOT_NULL(wrap); wrap->MakeCallback(env->onread_string(), arraysize(argv), argv); } - bool StreamBase::IsIPCPipe() { return false; } - int StreamBase::GetFD() { return -1; } - Local StreamBase::GetObject() { return GetAsyncWrap()->object(); } - int StreamResource::DoTryWrite(uv_buf_t** bufs, size_t* count) { // No TryWrite by default return 0; } - const char* StreamResource::Error() const { return nullptr; } - void StreamResource::ClearError() { // No-op } - uv_buf_t StreamListener::OnStreamAlloc(size_t suggested_size) { return uv_buf_init(Malloc(suggested_size), suggested_size); } - void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { CHECK_NOT_NULL(stream_); StreamBase* stream = static_cast(stream_); @@ -366,10 +335,9 @@ void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); - if (nread <= 0) { + if (nread <= 0) { free(buf.base); - if (nread < 0) - stream->CallJSOnreadMethod(nread, Local()); + if (nread < 0) stream->CallJSOnreadMethod(nread, Local()); return; } @@ -380,7 +348,6 @@ void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { stream->CallJSOnreadMethod(nread, obj); } - void ReportWritesToJSStreamListener::OnStreamAfterReqFinished( StreamReq* req_wrap, int status) { StreamBase* stream = static_cast(stream_); @@ -391,11 +358,9 @@ void ReportWritesToJSStreamListener::OnStreamAfterReqFinished( CHECK(!async_wrap->persistent().IsEmpty()); Local req_wrap_obj = async_wrap->object(); - Local argv[] = { - Integer::New(env->isolate(), status), - stream->GetObject(), - Undefined(env->isolate()) - }; + Local argv[] = {Integer::New(env->isolate(), status), + stream->GetObject(), + Undefined(env->isolate())}; const char* msg = stream->Error(); if (msg != nullptr) { @@ -407,8 +372,8 @@ void ReportWritesToJSStreamListener::OnStreamAfterReqFinished( async_wrap->MakeCallback(env->oncomplete_string(), arraysize(argv), argv); } -void ReportWritesToJSStreamListener::OnStreamAfterWrite( - WriteWrap* req_wrap, int status) { +void ReportWritesToJSStreamListener::OnStreamAfterWrite(WriteWrap* req_wrap, + int status) { OnStreamAfterReqFinished(req_wrap, status); } @@ -417,5 +382,4 @@ void ReportWritesToJSStreamListener::OnStreamAfterShutdown( OnStreamAfterReqFinished(req_wrap, status); } - } // namespace node diff --git a/src/stream_base.h b/src/stream_base.h index 05c2a9623625d6..fb33a4ad30cb88 100644 --- a/src/stream_base.h +++ b/src/stream_base.h @@ -3,8 +3,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "env.h" #include "async_wrap-inl.h" +#include "env.h" #include "node.h" #include "util.h" @@ -25,13 +25,12 @@ struct StreamWriteResult { size_t bytes; }; - class StreamReq { public: static constexpr int kStreamReqField = 1; - explicit StreamReq(StreamBase* stream, - v8::Local req_wrap_obj) : stream_(stream) { + explicit StreamReq(StreamBase* stream, v8::Local req_wrap_obj) + : stream_(stream) { AttachToObject(req_wrap_obj); } @@ -64,9 +63,8 @@ class StreamReq { class ShutdownWrap : public StreamReq { public: - ShutdownWrap(StreamBase* stream, - v8::Local req_wrap_obj) - : StreamReq(stream, req_wrap_obj) { } + ShutdownWrap(StreamBase* stream, v8::Local req_wrap_obj) + : StreamReq(stream, req_wrap_obj) {} // Call stream()->EmitAfterShutdown() and dispose of this request wrap. void OnDone(int status) override; @@ -78,13 +76,10 @@ class WriteWrap : public StreamReq { size_t StorageSize() const; void SetAllocatedStorage(char* data, size_t size); - WriteWrap(StreamBase* stream, - v8::Local req_wrap_obj) - : StreamReq(stream, req_wrap_obj) { } + WriteWrap(StreamBase* stream, v8::Local req_wrap_obj) + : StreamReq(stream, req_wrap_obj) {} - ~WriteWrap() { - free(storage_); - } + ~WriteWrap() { free(storage_); } // Call stream()->EmitAfterWrite() and dispose of this request wrap. void OnDone(int status) override; @@ -94,7 +89,6 @@ class WriteWrap : public StreamReq { size_t storage_size_ = 0; }; - // This is the generic interface for objects that control Node.js' C++ streams. // For example, the default `EmitToJSStreamListener` emits a stream's data // as Buffers in JS, or `TLSWrap` reads and decrypts data from a stream. @@ -123,8 +117,7 @@ class StreamListener { // with base nullptr in case of an error. // `nread` is the number of read bytes (which is at most the buffer length), // or, if negative, a libuv error code. - virtual void OnStreamRead(ssize_t nread, - const uv_buf_t& buf) = 0; + virtual void OnStreamRead(ssize_t nread, const uv_buf_t& buf) = 0; // This is called once a write has finished. `status` may be 0 or, // if negative, a libuv error code. @@ -164,7 +157,6 @@ class StreamListener { friend class StreamResource; }; - // An (incomplete) stream listener class that calls the `.oncomplete()` // method of the JS objects associated with the wrap objects. class ReportWritesToJSStreamListener : public StreamListener { @@ -176,7 +168,6 @@ class ReportWritesToJSStreamListener : public StreamListener { void OnStreamAfterReqFinished(StreamReq* req_wrap, int status); }; - // A default emitter that just pushes data chunks as Buffer instances to // JS land via the handle’s .ondata method. class EmitToJSStreamListener : public ReportWritesToJSStreamListener { @@ -184,7 +175,6 @@ class EmitToJSStreamListener : public ReportWritesToJSStreamListener { void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override; }; - // A generic stream, comparable to JS land’s `Duplex` streams. // A stream is always controlled through one `StreamListener` instance. class StreamResource { @@ -252,7 +242,6 @@ class StreamResource { friend class StreamListener; }; - class StreamBase : public StreamResource { public: template @@ -323,7 +312,7 @@ class StreamBase : public StreamResource { template & args)> + const v8::FunctionCallbackInfo& args)> static void JSMethod(const v8::FunctionCallbackInfo& args); private: @@ -334,7 +323,6 @@ class StreamBase : public StreamResource { friend class ShutdownWrap; }; - // These are helpers for creating `ShutdownWrap`/`WriteWrap` instances. // `OtherBase` must have a constructor that matches the `AsyncWrap` // constructors’s (Environment*, Local, AsyncWrap::Provider) signature @@ -342,8 +330,7 @@ class StreamBase : public StreamResource { template class SimpleShutdownWrap : public ShutdownWrap, public OtherBase { public: - SimpleShutdownWrap(StreamBase* stream, - v8::Local req_wrap_obj); + SimpleShutdownWrap(StreamBase* stream, v8::Local req_wrap_obj); AsyncWrap* GetAsyncWrap() override { return this; } @@ -357,8 +344,7 @@ class SimpleShutdownWrap : public ShutdownWrap, public OtherBase { template class SimpleWriteWrap : public WriteWrap, public OtherBase { public: - SimpleWriteWrap(StreamBase* stream, - v8::Local req_wrap_obj); + SimpleWriteWrap(StreamBase* stream, v8::Local req_wrap_obj); AsyncWrap* GetAsyncWrap() override { return this; } @@ -367,7 +353,6 @@ class SimpleWriteWrap : public WriteWrap, public OtherBase { tracker->TrackFieldWithSize("storage", StorageSize()); } - ADD_MEMORY_INFO_NAME(SimpleWriteWrap) }; diff --git a/src/stream_pipe.cc b/src/stream_pipe.cc index e19f98e35d2821..c1992c5c2d199b 100644 --- a/src/stream_pipe.cc +++ b/src/stream_pipe.cc @@ -1,7 +1,7 @@ #include "stream_pipe.h" -#include "stream_base-inl.h" #include "node_buffer.h" #include "node_internals.h" +#include "stream_base-inl.h" using v8::Context; using v8::External; @@ -13,9 +13,7 @@ using v8::Value; namespace node { -StreamPipe::StreamPipe(StreamBase* source, - StreamBase* sink, - Local obj) +StreamPipe::StreamPipe(StreamBase* source, StreamBase* sink, Local obj) : AsyncWrap(source->stream_env(), obj, AsyncWrap::PROVIDER_STREAMPIPE) { MakeWeak(); @@ -33,11 +31,13 @@ StreamPipe::StreamPipe(StreamBase* source, // weak references). obj->Set(env()->context(), env()->source_string(), source->GetObject()) .FromJust(); - source->GetObject()->Set(env()->context(), env()->pipe_target_string(), obj) + source->GetObject() + ->Set(env()->context(), env()->pipe_target_string(), obj) .FromJust(); obj->Set(env()->context(), env()->sink_string(), sink->GetObject()) .FromJust(); - sink->GetObject()->Set(env()->context(), env()->pipe_source_string(), obj) + sink->GetObject() + ->Set(env()->context(), env()->pipe_source_string(), obj) .FromJust(); } @@ -54,14 +54,12 @@ StreamBase* StreamPipe::sink() { } void StreamPipe::Unpipe() { - if (is_closed_) - return; + if (is_closed_) return; // Note that we possibly cannot use virtual methods on `source` and `sink` // here, because this function can be called from their destructors via // `OnStreamDestroy()`. - if (!source_destroyed_) - source()->ReadStop(); + if (!source_destroyed_) source()->ReadStop(); is_closed_ = true; is_reading_ = false; @@ -71,38 +69,42 @@ void StreamPipe::Unpipe() { // Delay the JS-facing part with SetImmediate, because this might be from // inside the garbage collector, so we can’t run JS here. HandleScope handle_scope(env()->isolate()); - env()->SetImmediate([](Environment* env, void* data) { - StreamPipe* pipe = static_cast(data); - - HandleScope handle_scope(env->isolate()); - Context::Scope context_scope(env->context()); - Local object = pipe->object(); - - if (object->Has(env->context(), env->onunpipe_string()).FromJust()) { - pipe->MakeCallback(env->onunpipe_string(), 0, nullptr).ToLocalChecked(); - } - - // Set all the links established in the constructor to `null`. - Local null = Null(env->isolate()); - - Local source_v; - Local sink_v; - source_v = object->Get(env->context(), env->source_string()) - .ToLocalChecked(); - sink_v = object->Get(env->context(), env->sink_string()) - .ToLocalChecked(); - CHECK(source_v->IsObject()); - CHECK(sink_v->IsObject()); - - object->Set(env->context(), env->source_string(), null).FromJust(); - object->Set(env->context(), env->sink_string(), null).FromJust(); - source_v.As()->Set(env->context(), - env->pipe_target_string(), - null).FromJust(); - sink_v.As()->Set(env->context(), - env->pipe_source_string(), - null).FromJust(); - }, static_cast(this), object()); + env()->SetImmediate( + [](Environment* env, void* data) { + StreamPipe* pipe = static_cast(data); + + HandleScope handle_scope(env->isolate()); + Context::Scope context_scope(env->context()); + Local object = pipe->object(); + + if (object->Has(env->context(), env->onunpipe_string()).FromJust()) { + pipe->MakeCallback(env->onunpipe_string(), 0, nullptr) + .ToLocalChecked(); + } + + // Set all the links established in the constructor to `null`. + Local null = Null(env->isolate()); + + Local source_v; + Local sink_v; + source_v = + object->Get(env->context(), env->source_string()).ToLocalChecked(); + sink_v = + object->Get(env->context(), env->sink_string()).ToLocalChecked(); + CHECK(source_v->IsObject()); + CHECK(sink_v->IsObject()); + + object->Set(env->context(), env->source_string(), null).FromJust(); + object->Set(env->context(), env->sink_string(), null).FromJust(); + source_v.As() + ->Set(env->context(), env->pipe_target_string(), null) + .FromJust(); + sink_v.As() + ->Set(env->context(), env->pipe_source_string(), null) + .FromJust(); + }, + static_cast(this), + object()); } uv_buf_t StreamPipe::ReadableListener::OnStreamAlloc(size_t suggested_size) { @@ -146,8 +148,7 @@ void StreamPipe::ProcessData(size_t nread, const uv_buf_t& buf) { is_writing_ = true; is_reading_ = false; res.wrap->SetAllocatedStorage(buf.base, buf.len); - if (source() != nullptr) - source()->ReadStop(); + if (source() != nullptr) source()->ReadStop(); } } @@ -202,8 +203,7 @@ void StreamPipe::WritableListener::OnStreamDestroy() { void StreamPipe::WritableListener::OnStreamWantsWrite(size_t suggested_size) { StreamPipe* pipe = ContainerOf(&StreamPipe::writable_listener_, this); pipe->wanted_data_ = suggested_size; - if (pipe->is_reading_ || pipe->is_closed_) - return; + if (pipe->is_reading_ || pipe->is_closed_) return; AsyncScope async_scope(pipe); pipe->is_reading_ = true; pipe->source()->ReadStart(); @@ -267,5 +267,4 @@ void InitializeStreamPipe(Local target, } // namespace node -NODE_MODULE_CONTEXT_AWARE_INTERNAL(stream_pipe, - node::InitializeStreamPipe) +NODE_MODULE_CONTEXT_AWARE_INTERNAL(stream_pipe, node::InitializeStreamPipe) diff --git a/src/stream_wrap.cc b/src/stream_wrap.cc index 60a17545427b16..c208167de6efd8 100644 --- a/src/stream_wrap.cc +++ b/src/stream_wrap.cc @@ -32,9 +32,8 @@ #include "udp_wrap.h" #include "util-inl.h" -#include // memcpy() #include // INT_MAX - +#include // memcpy() namespace node { @@ -50,7 +49,6 @@ using v8::ReadOnly; using v8::Signature; using v8::Value; - void LibuvStreamWrap::Initialize(Local target, Local unused, Local context) { @@ -58,9 +56,9 @@ void LibuvStreamWrap::Initialize(Local target, auto is_construct_call_callback = [](const FunctionCallbackInfo& args) { - CHECK(args.IsConstructCall()); - StreamReq::ResetObject(args.This()); - }; + CHECK(args.IsConstructCall()); + StreamReq::ResetObject(args.This()); + }; Local sw = FunctionTemplate::New(env->isolate(), is_construct_call_callback); sw->InstanceTemplate()->SetInternalFieldCount(StreamReq::kStreamReqField + 1); @@ -82,19 +80,13 @@ void LibuvStreamWrap::Initialize(Local target, env->set_write_wrap_template(ww->InstanceTemplate()); } - LibuvStreamWrap::LibuvStreamWrap(Environment* env, Local object, uv_stream_t* stream, AsyncWrap::ProviderType provider) - : HandleWrap(env, - object, - reinterpret_cast(stream), - provider), + : HandleWrap(env, object, reinterpret_cast(stream), provider), StreamBase(env), - stream_(stream) { -} - + stream_(stream) {} void LibuvStreamWrap::AddMethods(Environment* env, v8::Local target) { @@ -112,7 +104,6 @@ void LibuvStreamWrap::AddMethods(Environment* env, StreamBase::AddMethods(env, target); } - int LibuvStreamWrap::GetFD() { #ifdef _WIN32 return fd_; @@ -124,43 +115,38 @@ int LibuvStreamWrap::GetFD() { #endif } - bool LibuvStreamWrap::IsAlive() { return HandleWrap::IsAlive(this); } - bool LibuvStreamWrap::IsClosing() { return uv_is_closing(reinterpret_cast(stream())); } - AsyncWrap* LibuvStreamWrap::GetAsyncWrap() { return static_cast(this); } - bool LibuvStreamWrap::IsIPCPipe() { return is_named_pipe_ipc(); } - int LibuvStreamWrap::ReadStart() { - return uv_read_start(stream(), [](uv_handle_t* handle, - size_t suggested_size, - uv_buf_t* buf) { - static_cast(handle->data)->OnUvAlloc(suggested_size, buf); - }, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { - static_cast(stream->data)->OnUvRead(nread, buf); - }); + return uv_read_start( + stream(), + [](uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { + static_cast(handle->data) + ->OnUvAlloc(suggested_size, buf); + }, + [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { + static_cast(stream->data)->OnUvRead(nread, buf); + }); } - int LibuvStreamWrap::ReadStop() { return uv_read_stop(stream()); } - void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); @@ -168,8 +154,6 @@ void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) { *buf = EmitAlloc(suggested_size); } - - template static Local AcceptHandle(Environment* env, LibuvStreamWrap* parent) { EscapableHandleScope scope(env->isolate()); @@ -177,8 +161,7 @@ static Local AcceptHandle(Environment* env, LibuvStreamWrap* parent) { UVType* handle; wrap_obj = WrapType::Instantiate(env, parent, WrapType::SOCKET); - if (wrap_obj.IsEmpty()) - return Local(); + if (wrap_obj.IsEmpty()) return Local(); WrapType* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, wrap_obj, Local()); @@ -190,7 +173,6 @@ static Local AcceptHandle(Environment* env, LibuvStreamWrap* parent) { return scope.Escape(wrap_obj); } - void LibuvStreamWrap::OnUvRead(ssize_t nread, const uv_buf_t* buf) { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); @@ -225,16 +207,15 @@ void LibuvStreamWrap::OnUvRead(ssize_t nread, const uv_buf_t* buf) { } if (!pending_obj.IsEmpty()) { - object()->Set(env()->context(), - env()->pending_handle_string(), - pending_obj).FromJust(); + object() + ->Set(env()->context(), env()->pending_handle_string(), pending_obj) + .FromJust(); } } EmitRead(nread, *buf); } - void LibuvStreamWrap::GetWriteQueueSize( const FunctionCallbackInfo& info) { LibuvStreamWrap* wrap; @@ -249,14 +230,12 @@ void LibuvStreamWrap::GetWriteQueueSize( info.GetReturnValue().Set(write_queue_size); } - void LibuvStreamWrap::SetBlocking(const FunctionCallbackInfo& args) { LibuvStreamWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); CHECK_GT(args.Length(), 0); - if (!wrap->IsAlive()) - return args.GetReturnValue().Set(UV_EINVAL); + if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL); bool enable = args[0]->IsTrue(); args.GetReturnValue().Set(uv_stream_set_blocking(wrap->stream(), enable)); @@ -273,23 +252,20 @@ WriteWrap* LibuvStreamWrap::CreateWriteWrap(Local object) { return new LibuvWriteWrap(this, object); } - int LibuvStreamWrap::DoShutdown(ShutdownWrap* req_wrap_) { LibuvShutdownWrap* req_wrap = static_cast(req_wrap_); return req_wrap->Dispatch(uv_shutdown, stream(), AfterUvShutdown); } - void LibuvStreamWrap::AfterUvShutdown(uv_shutdown_t* req, int status) { - LibuvShutdownWrap* req_wrap = static_cast( - LibuvShutdownWrap::from_req(req)); + LibuvShutdownWrap* req_wrap = + static_cast(LibuvShutdownWrap::from_req(req)); CHECK_NOT_NULL(req_wrap); HandleScope scope(req_wrap->env()->isolate()); Context::Scope context_scope(req_wrap->env()->context()); req_wrap->Done(status); } - // NOTE: Call to this function could change both `buf`'s and `count`'s // values, shifting their base and decrementing their length. This is // required in order to skip the data that was successfully written via @@ -301,10 +277,8 @@ int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) { size_t vcount = *count; err = uv_try_write(stream(), vbufs, vcount); - if (err == UV_ENOSYS || err == UV_EAGAIN) - return 0; - if (err < 0) - return err; + if (err == UV_ENOSYS || err == UV_EAGAIN) return 0; + if (err < 0) return err; // Slice off the buffers: skip all written buffers and slice the one that // was partially written. @@ -317,7 +291,7 @@ int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) { written = 0; break; - // Discard + // Discard } else { written -= vbufs[0].len; } @@ -329,7 +303,6 @@ int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) { return 0; } - int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap, uv_buf_t* bufs, size_t count, @@ -339,18 +312,13 @@ int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap, if (send_handle == nullptr) { r = w->Dispatch(uv_write, stream(), bufs, count, AfterUvWrite); } else { - r = w->Dispatch(uv_write2, - stream(), - bufs, - count, - send_handle, - AfterUvWrite); + r = w->Dispatch( + uv_write2, stream(), bufs, count, send_handle, AfterUvWrite); } if (!r) { size_t bytes = 0; - for (size_t i = 0; i < count; i++) - bytes += bufs[i].len; + for (size_t i = 0; i < count; i++) bytes += bufs[i].len; if (stream()->type == UV_TCP) { NODE_COUNT_NET_BYTES_SENT(bytes); } else if (stream()->type == UV_NAMED_PIPE) { @@ -361,11 +329,9 @@ int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap, return r; } - - void LibuvStreamWrap::AfterUvWrite(uv_write_t* req, int status) { - LibuvWriteWrap* req_wrap = static_cast( - LibuvWriteWrap::from_req(req)); + LibuvWriteWrap* req_wrap = + static_cast(LibuvWriteWrap::from_req(req)); CHECK_NOT_NULL(req_wrap); HandleScope scope(req_wrap->env()->isolate()); Context::Scope context_scope(req_wrap->env()->context()); diff --git a/src/stream_wrap.h b/src/stream_wrap.h index 487a40b7ffc7f9..7f9fc3704a6187 100644 --- a/src/stream_wrap.h +++ b/src/stream_wrap.h @@ -56,22 +56,16 @@ class LibuvStreamWrap : public HandleWrap, public StreamBase { size_t count, uv_stream_t* send_handle) override; - inline uv_stream_t* stream() const { - return stream_; - } + inline uv_stream_t* stream() const { return stream_; } - inline bool is_named_pipe() const { - return stream()->type == UV_NAMED_PIPE; - } + inline bool is_named_pipe() const { return stream()->type == UV_NAMED_PIPE; } inline bool is_named_pipe_ipc() const { return is_named_pipe() && reinterpret_cast(stream())->ipc != 0; } - inline bool is_tcp() const { - return stream()->type == UV_TCP; - } + inline bool is_tcp() const { return stream()->type == UV_TCP; } ShutdownWrap* CreateShutdownWrap(v8::Local object) override; WriteWrap* CreateWriteWrap(v8::Local object) override; @@ -94,7 +88,6 @@ class LibuvStreamWrap : public HandleWrap, public StreamBase { #endif } - private: static void GetWriteQueueSize( const v8::FunctionCallbackInfo& info); @@ -120,7 +113,6 @@ class LibuvStreamWrap : public HandleWrap, public StreamBase { #endif }; - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 83c74d2f182021..1e9dc3dac6225d 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -22,9 +22,9 @@ #include "string_bytes.h" #include "base64.h" -#include "node_internals.h" -#include "node_errors.h" #include "node_buffer.h" +#include "node_errors.h" +#include "node_internals.h" #include #include // memcpy @@ -49,31 +49,24 @@ using v8::Value; namespace { template -class ExternString: public ResourceType { +class ExternString : public ResourceType { public: ~ExternString() override { free(const_cast(data_)); isolate()->AdjustAmountOfExternalAllocatedMemory(-byte_length()); } - const TypeName* data() const override { - return data_; - } + const TypeName* data() const override { return data_; } - size_t length() const override { - return length_; - } + size_t length() const override { return length_; } - int64_t byte_length() const { - return length() * sizeof(*data()); - } + int64_t byte_length() const { return length() * sizeof(*data()); } static MaybeLocal NewFromCopy(Isolate* isolate, const TypeName* data, size_t length, Local* error) { - if (length == 0) - return String::Empty(isolate); + if (length == 0) return String::Empty(isolate); if (length < EXTERN_APEX) return NewSimpleFromCopy(isolate, data, length, error); @@ -85,10 +78,8 @@ class ExternString: public ResourceType { } memcpy(new_data, data, length * sizeof(*new_data)); - return ExternString::New(isolate, - new_data, - length, - error); + return ExternString::New( + isolate, new_data, length, error); } // uses "data" for external resource, and will be free'd on gc @@ -96,8 +87,7 @@ class ExternString: public ResourceType { TypeName* data, size_t length, Local* error) { - if (length == 0) - return String::Empty(isolate); + if (length == 0) return String::Empty(isolate); if (length < EXTERN_APEX) { MaybeLocal str = NewSimpleFromCopy(isolate, data, length, error); @@ -105,9 +95,8 @@ class ExternString: public ResourceType { return str; } - ExternString* h_str = new ExternString(isolate, - data, - length); + ExternString* h_str = + new ExternString(isolate, data, length); MaybeLocal str = NewExternal(isolate, h_str); isolate->AdjustAmountOfExternalAllocatedMemory(h_str->byte_length()); @@ -124,9 +113,8 @@ class ExternString: public ResourceType { private: ExternString(Isolate* isolate, const TypeName* data, size_t length) - : isolate_(isolate), data_(data), length_(length) { } - static MaybeLocal NewExternal(Isolate* isolate, - ExternString* h_str); + : isolate_(isolate), data_(data), length_(length) {} + static MaybeLocal NewExternal(Isolate* isolate, ExternString* h_str); // This method does not actually create ExternString instances. static MaybeLocal NewSimpleFromCopy(Isolate* isolate, @@ -139,23 +127,20 @@ class ExternString: public ResourceType { size_t length_; }; - -typedef ExternString ExternOneByteString; -typedef ExternString ExternTwoByteString; - +typedef ExternString + ExternOneByteString; +typedef ExternString + ExternTwoByteString; template <> -MaybeLocal ExternOneByteString::NewExternal( - Isolate* isolate, ExternOneByteString* h_str) { +MaybeLocal ExternOneByteString::NewExternal(Isolate* isolate, + ExternOneByteString* h_str) { return String::NewExternalOneByte(isolate, h_str).FromMaybe(Local()); } - template <> -MaybeLocal ExternTwoByteString::NewExternal( - Isolate* isolate, ExternTwoByteString* h_str) { +MaybeLocal ExternTwoByteString::NewExternal(Isolate* isolate, + ExternTwoByteString* h_str) { return String::NewExternalTwoByte(isolate, h_str).FromMaybe(Local()); } @@ -176,17 +161,13 @@ MaybeLocal ExternOneByteString::NewSimpleFromCopy(Isolate* isolate, return str.ToLocalChecked(); } - template <> MaybeLocal ExternTwoByteString::NewSimpleFromCopy(Isolate* isolate, const uint16_t* data, size_t length, Local* error) { MaybeLocal str = - String::NewFromTwoByte(isolate, - data, - v8::NewStringType::kNormal, - length); + String::NewFromTwoByte(isolate, data, v8::NewStringType::kNormal, length); if (str.IsEmpty()) { *error = node::ERR_STRING_TOO_LONG(isolate); return MaybeLocal(); @@ -197,44 +178,37 @@ MaybeLocal ExternTwoByteString::NewSimpleFromCopy(Isolate* isolate, } // anonymous namespace // supports regular and URL-safe base64 -const int8_t unbase64_table[256] = - { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - }; - - -static const int8_t unhex_table[256] = - { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - }; +const int8_t unbase64_table[256] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, + 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1}; + +static const int8_t unhex_table[256] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, + 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1}; static inline unsigned unhex(uint8_t x) { return unhex_table[x]; @@ -249,15 +223,13 @@ static size_t hex_decode(char* buf, for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { unsigned a = unhex(src[i * 2 + 0]); unsigned b = unhex(src[i * 2 + 1]); - if (!~a || !~b) - return i; + if (!~a || !~b) return i; buf[i] = (a << 4) | b; } return i; } - size_t StringBytes::WriteUCS2(char* buf, size_t buflen, Local str, @@ -295,7 +267,6 @@ size_t StringBytes::WriteUCS2(char* buf, return nchars * sizeof(*dst); } - size_t StringBytes::Write(Isolate* isolate, char* buf, size_t buflen, @@ -306,14 +277,12 @@ size_t StringBytes::Write(Isolate* isolate, size_t nbytes; int nchars; - if (chars_written == nullptr) - chars_written = &nchars; + if (chars_written == nullptr) chars_written = &nchars; CHECK(val->IsString() == true); Local str = val.As(); - int flags = String::HINT_MANY_WRITES_EXPECTED | - String::NO_NULL_TERMINATION | + int flags = String::HINT_MANY_WRITES_EXPECTED | String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8; switch (encoding) { @@ -345,8 +314,7 @@ size_t StringBytes::Write(Isolate* isolate, // the Buffer, so we need to reorder on BE platforms. See // https://nodejs.org/api/buffer.html regarding Node's "ucs2" // encoding specification - if (IsBigEndian()) - SwapBytes16(buf, nbytes); + if (IsBigEndian()) SwapBytes16(buf, nbytes); break; } @@ -381,16 +349,12 @@ size_t StringBytes::Write(Isolate* isolate, return nbytes; } - -bool StringBytes::IsValidString(Local string, - enum encoding enc) { - if (enc == HEX && string->Length() % 2 != 0) - return false; +bool StringBytes::IsValidString(Local string, enum encoding enc) { + if (enc == HEX && string->Length() % 2 != 0) return false; // TODO(bnoordhuis) Add BASE64 check? return true; } - // Quick and dirty size calculation // Will always be at least big enough, but may have some extra // UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes @@ -442,7 +406,6 @@ size_t StringBytes::StorageSize(Isolate* isolate, return data_size; } - size_t StringBytes::Size(Isolate* isolate, Local val, enum encoding encoding) { @@ -477,18 +440,13 @@ size_t StringBytes::Size(Isolate* isolate, UNREACHABLE(); } - - - static bool contains_non_ascii_slow(const char* buf, size_t len) { for (size_t i = 0; i < len; ++i) { - if (buf[i] & 0x80) - return true; + if (buf[i] & 0x80) return true; } return false; } - static bool contains_non_ascii(const char* src, size_t len) { if (len < 16) { return contains_non_ascii_slow(src, len); @@ -500,13 +458,11 @@ static bool contains_non_ascii(const char* src, size_t len) { if (unaligned > 0) { const unsigned n = bytes_per_word - unaligned; - if (contains_non_ascii_slow(src, n)) - return true; + if (contains_non_ascii_slow(src, n)) return true; src += n; len -= n; } - #if defined(_WIN64) || defined(_LP64) const uintptr_t mask = 0x8080808080808080ll; #else @@ -516,28 +472,24 @@ static bool contains_non_ascii(const char* src, size_t len) { const uintptr_t* srcw = reinterpret_cast(src); for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - if (srcw[i] & mask) - return true; + if (srcw[i] & mask) return true; } const unsigned remainder = len & align_mask; if (remainder > 0) { const size_t offset = len - remainder; - if (contains_non_ascii_slow(src + offset, remainder)) - return true; + if (contains_non_ascii_slow(src + offset, remainder)) return true; } return false; } - static void force_ascii_slow(const char* src, char* dst, size_t len) { for (size_t i = 0; i < len; ++i) { dst[i] = src[i] & 0x7f; } } - static void force_ascii(const char* src, char* dst, size_t len) { if (len < 16) { force_ascii_slow(src, dst, len); @@ -582,11 +534,9 @@ static void force_ascii(const char* src, char* dst, size_t len) { } } - static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { // We know how much we'll write, just make sure that there's space. - CHECK(dlen >= slen * 2 && - "not enough space provided for hex encode"); + CHECK(dlen >= slen * 2 && "not enough space provided for hex encode"); dlen = slen * 2; for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { @@ -599,16 +549,14 @@ static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { return dlen; } - -#define CHECK_BUFLEN_IN_RANGE(len) \ - do { \ - if ((len) > Buffer::kMaxLength) { \ - *error = node::ERR_BUFFER_TOO_LARGE(isolate); \ - return MaybeLocal(); \ - } \ +#define CHECK_BUFLEN_IN_RANGE(len) \ + do { \ + if ((len) > Buffer::kMaxLength) { \ + *error = node::ERR_BUFFER_TOO_LARGE(isolate); \ + return MaybeLocal(); \ + } \ } while (0) - MaybeLocal StringBytes::Encode(Isolate* isolate, const char* buf, size_t buflen, @@ -624,19 +572,18 @@ MaybeLocal StringBytes::Encode(Isolate* isolate, MaybeLocal val; switch (encoding) { - case BUFFER: - { - if (buflen > node::Buffer::kMaxLength) { - *error = node::ERR_BUFFER_TOO_LARGE(isolate); - return MaybeLocal(); - } - auto maybe_buf = Buffer::Copy(isolate, buf, buflen); - if (maybe_buf.IsEmpty()) { - *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate); - return MaybeLocal(); - } - return maybe_buf.ToLocalChecked(); + case BUFFER: { + if (buflen > node::Buffer::kMaxLength) { + *error = node::ERR_BUFFER_TOO_LARGE(isolate); + return MaybeLocal(); } + auto maybe_buf = Buffer::Copy(isolate, buf, buflen); + if (maybe_buf.IsEmpty()) { + *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate); + return MaybeLocal(); + } + return maybe_buf.ToLocalChecked(); + } case ASCII: if (contains_non_ascii(buf, buflen)) { @@ -652,10 +599,8 @@ MaybeLocal StringBytes::Encode(Isolate* isolate, } case UTF8: - val = String::NewFromUtf8(isolate, - buf, - v8::NewStringType::kNormal, - buflen); + val = + String::NewFromUtf8(isolate, buf, v8::NewStringType::kNormal, buflen); if (val.IsEmpty()) { *error = node::ERR_STRING_TOO_LONG(isolate); return MaybeLocal(); @@ -700,7 +645,6 @@ MaybeLocal StringBytes::Encode(Isolate* isolate, UNREACHABLE(); } - MaybeLocal StringBytes::Encode(Isolate* isolate, const uint16_t* buf, size_t buflen, @@ -738,19 +682,17 @@ MaybeLocal StringBytes::Encode(Isolate* isolate, // value if it's not aligned and ensures the appropriate byte order // on big endian architectures. const bool be = IsBigEndian(); - if (len % 2 != 0) - return ret; + if (len % 2 != 0) return ret; std::vector vec(len / 2); for (size_t i = 0, k = 0; i < len; i += 2, k += 1) { const uint8_t hi = static_cast(buf[i + 0]); const uint8_t lo = static_cast(buf[i + 1]); - vec[k] = be ? - static_cast(hi) << 8 | lo - : static_cast(lo) << 8 | hi; + vec[k] = be ? static_cast(hi) << 8 | lo + : static_cast(lo) << 8 | hi; } - ret = vec.empty() ? - static_cast< Local >(String::Empty(isolate)) - : StringBytes::Encode(isolate, &vec[0], vec.size(), error); + ret = vec.empty() + ? static_cast >(String::Empty(isolate)) + : StringBytes::Encode(isolate, &vec[0], vec.size(), error); } else { ret = StringBytes::Encode(isolate, buf, len, encoding, error); } diff --git a/src/string_bytes.h b/src/string_bytes.h index 7a70f06f63dec4..e177907b704084 100644 --- a/src/string_bytes.h +++ b/src/string_bytes.h @@ -26,8 +26,8 @@ // Decodes a v8::Local or Buffer to a raw char* -#include "v8.h" #include "env.h" +#include "v8.h" namespace node { @@ -45,15 +45,11 @@ class StringBytes { return false; } - const size_t storage = StringBytes::StorageSize(env->isolate(), - string, - enc); + const size_t storage = + StringBytes::StorageSize(env->isolate(), string, enc); AllocateSufficientStorage(storage); - const size_t length = StringBytes::Write(env->isolate(), - out(), - storage, - string, - enc); + const size_t length = + StringBytes::Write(env->isolate(), out(), storage, string, enc); // No zero terminator is included when using this method. SetLength(length); @@ -66,8 +62,7 @@ class StringBytes { // Does the string match the encoding? Quick but non-exhaustive. // Example: a HEX string must have a length that's a multiple of two. // FIXME(bnoordhuis) IsMaybeValidString()? Naming things is hard... - static bool IsValidString(v8::Local string, - enum encoding enc); + static bool IsValidString(v8::Local string, enum encoding enc); // Fast, but can be 2 bytes oversized for Base64, and // as much as triple UTF-8 strings <= 65536 chars in length diff --git a/src/string_decoder-inl.h b/src/string_decoder-inl.h index 8a04211906f759..90ae7ca160c015 100644 --- a/src/string_decoder-inl.h +++ b/src/string_decoder-inl.h @@ -30,9 +30,8 @@ char* StringDecoder::IncompleteCharacterBuffer() { return reinterpret_cast(state_ + kIncompleteCharactersStart); } - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_STRING_DECODER_INL_H_ +#endif // SRC_STRING_DECODER_INL_H_ diff --git a/src/string_decoder.cc b/src/string_decoder.cc index dcc99a09f9b3cd..0c9f37fe01502f 100644 --- a/src/string_decoder.cc +++ b/src/string_decoder.cc @@ -1,7 +1,7 @@ -#include "string_decoder-inl.h" -#include "string_bytes.h" -#include "node_internals.h" #include "node_buffer.h" +#include "node_internals.h" +#include "string_bytes.h" +#include "string_decoder-inl.h" using v8::Array; using v8::Context; @@ -26,27 +26,16 @@ MaybeLocal MakeString(Isolate* isolate, MaybeLocal ret; if (encoding == UTF8) { return String::NewFromUtf8( - isolate, - data, - v8::NewStringType::kNormal, - length); + isolate, data, v8::NewStringType::kNormal, length); } else if (encoding == UCS2) { #ifdef DEBUG CHECK_EQ(reinterpret_cast(data) % 2, 0); CHECK_EQ(length % 2, 0); #endif ret = StringBytes::Encode( - isolate, - reinterpret_cast(data), - length / 2, - &error); + isolate, reinterpret_cast(data), length / 2, &error); } else { - ret = StringBytes::Encode( - isolate, - data, - length, - encoding, - &error); + ret = StringBytes::Encode(isolate, data, length, encoding, &error); } if (ret.IsEmpty()) { @@ -62,7 +51,6 @@ MaybeLocal MakeString(Isolate* isolate, } // anonymous namespace - MaybeLocal StringDecoder::DecodeData(Isolate* isolate, const char* data, size_t* nread_ptr) { @@ -77,8 +65,7 @@ MaybeLocal StringDecoder::DecodeData(Isolate* isolate, // main body. if (MissingBytes() > 0) { // There are never more bytes missing than the pre-calculated maximum. - CHECK_LE(MissingBytes() + BufferedBytes(), - kIncompleteCharactersEnd); + CHECK_LE(MissingBytes() + BufferedBytes(), kIncompleteCharactersEnd); if (Encoding() == UTF8) { // For UTF-8, we need special treatment to align with the V8 decoder: // If an incomplete character is found at a chunk boundary, we turn @@ -98,11 +85,8 @@ MaybeLocal StringDecoder::DecodeData(Isolate* isolate, } } - size_t found_bytes = - std::min(nread, static_cast(MissingBytes())); - memcpy(IncompleteCharacterBuffer() + BufferedBytes(), - data, - found_bytes); + size_t found_bytes = std::min(nread, static_cast(MissingBytes())); + memcpy(IncompleteCharacterBuffer() + BufferedBytes(), data, found_bytes); // Adjust the two buffers. data += found_bytes; nread -= found_bytes; @@ -116,7 +100,8 @@ MaybeLocal StringDecoder::DecodeData(Isolate* isolate, if (!MakeString(isolate, IncompleteCharacterBuffer(), BufferedBytes(), - Encoding()).ToLocal(&prepend)) { + Encoding()) + .ToLocal(&prepend)) { return MaybeLocal(); } @@ -144,7 +129,7 @@ MaybeLocal StringDecoder::DecodeData(Isolate* isolate, // This is UTF-8 encoded data and we ended on a non-ASCII UTF-8 byte. // This means we'll need to figure out where the character to which // the byte belongs begins. - for (size_t i = nread - 1; ; --i) { + for (size_t i = nread - 1;; --i) { #ifdef DEBUG CHECK_LT(i, nread); #endif @@ -246,14 +231,10 @@ MaybeLocal StringDecoder::FlushData(Isolate* isolate) { state_[kBufferedBytes]--; } - if (BufferedBytes() == 0) - return String::Empty(isolate); + if (BufferedBytes() == 0) return String::Empty(isolate); - MaybeLocal ret = - MakeString(isolate, - IncompleteCharacterBuffer(), - BufferedBytes(), - Encoding()); + MaybeLocal ret = MakeString( + isolate, IncompleteCharacterBuffer(), BufferedBytes(), Encoding()); state_[kMissingBytes] = 0; state_[kBufferedBytes] = 0; @@ -270,8 +251,7 @@ void DecodeData(const FunctionCallbackInfo& args) { size_t nread = Buffer::Length(args[1]); MaybeLocal ret = decoder->DecodeData(args.GetIsolate(), Buffer::Data(args[1]), &nread); - if (!ret.IsEmpty()) - args.GetReturnValue().Set(ret.ToLocalChecked()); + if (!ret.IsEmpty()) args.GetReturnValue().Set(ret.ToLocalChecked()); } void FlushData(const FunctionCallbackInfo& args) { @@ -279,8 +259,7 @@ void FlushData(const FunctionCallbackInfo& args) { reinterpret_cast(Buffer::Data(args[0])); CHECK_NOT_NULL(decoder); MaybeLocal ret = decoder->FlushData(args.GetIsolate()); - if (!ret.IsEmpty()) - args.GetReturnValue().Set(ret.ToLocalChecked()); + if (!ret.IsEmpty()) args.GetReturnValue().Set(ret.ToLocalChecked()); } void InitializeStringDecoder(Local target, @@ -289,10 +268,12 @@ void InitializeStringDecoder(Local target, Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); -#define SET_DECODER_CONSTANT(name) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(isolate, #name), \ - Integer::New(isolate, StringDecoder::name)).FromJust() +#define SET_DECODER_CONSTANT(name) \ + target \ + ->Set(context, \ + FIXED_ONE_BYTE_STRING(isolate, #name), \ + Integer::New(isolate, StringDecoder::name)) \ + .FromJust() SET_DECODER_CONSTANT(kIncompleteCharactersStart); SET_DECODER_CONSTANT(kIncompleteCharactersEnd); @@ -302,10 +283,12 @@ void InitializeStringDecoder(Local target, SET_DECODER_CONSTANT(kNumFields); Local encodings = Array::New(isolate); -#define ADD_TO_ENCODINGS_ARRAY(cname, jsname) \ - encodings->Set(context, \ - static_cast(cname), \ - FIXED_ONE_BYTE_STRING(isolate, jsname)).FromJust() +#define ADD_TO_ENCODINGS_ARRAY(cname, jsname) \ + encodings \ + ->Set(context, \ + static_cast(cname), \ + FIXED_ONE_BYTE_STRING(isolate, jsname)) \ + .FromJust() ADD_TO_ENCODINGS_ARRAY(ASCII, "ascii"); ADD_TO_ENCODINGS_ARRAY(UTF8, "utf8"); ADD_TO_ENCODINGS_ARRAY(BASE64, "base64"); @@ -314,13 +297,14 @@ void InitializeStringDecoder(Local target, ADD_TO_ENCODINGS_ARRAY(BUFFER, "buffer"); ADD_TO_ENCODINGS_ARRAY(LATIN1, "latin1"); - target->Set(context, - FIXED_ONE_BYTE_STRING(isolate, "encodings"), - encodings).FromJust(); + target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "encodings"), encodings) + .FromJust(); - target->Set(context, - FIXED_ONE_BYTE_STRING(isolate, "kSize"), - Integer::New(isolate, sizeof(StringDecoder))).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "kSize"), + Integer::New(isolate, sizeof(StringDecoder))) + .FromJust(); env->SetMethod(target, "decode", DecodeData); env->SetMethod(target, "flush", FlushData); diff --git a/src/string_decoder.h b/src/string_decoder.h index 9059eeaa9d2eb7..47881ed95890ce 100644 --- a/src/string_decoder.h +++ b/src/string_decoder.h @@ -47,4 +47,4 @@ class StringDecoder { #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_STRING_DECODER_H_ +#endif // SRC_STRING_DECODER_H_ diff --git a/src/string_search.h b/src/string_search.h index 358a4c1b024e67..1b0e1df50e7f71 100644 --- a/src/string_search.h +++ b/src/string_search.h @@ -7,9 +7,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_internals.h" #include #include +#include "node_internals.h" namespace node { namespace stringsearch { @@ -49,7 +49,6 @@ class Vector { bool is_forward_; }; - //--------------------------------------------------------------------- // String Search object. //--------------------------------------------------------------------- @@ -93,8 +92,7 @@ class StringSearch : private StringSearchBase { public: typedef stringsearch::Vector Vector; - explicit StringSearch(Vector pattern) - : pattern_(pattern), start_(0) { + explicit StringSearch(Vector pattern) : pattern_(pattern), start_(0) { if (pattern.length() >= kBMMaxShift) { start_ = pattern.length() - kBMMaxShift; } @@ -125,9 +123,9 @@ class StringSearch : private StringSearchBase { return kUC16AlphabetSize; } - static_assert(sizeof(Char) == sizeof(uint8_t) || - sizeof(Char) == sizeof(uint16_t), - "sizeof(Char) == sizeof(uint16_t) || sizeof(uint8_t)"); + static_assert( + sizeof(Char) == sizeof(uint8_t) || sizeof(Char) == sizeof(uint16_t), + "sizeof(Char) == sizeof(uint16_t) || sizeof(uint8_t)"); } private: @@ -142,8 +140,7 @@ class StringSearch : private StringSearchBase { void PopulateBoyerMooreTable(); - static inline int CharOccurrence(int* bad_char_occurrence, - Char char_code) { + static inline int CharOccurrence(int* bad_char_occurrence, Char char_code) { if (sizeof(Char) == 1) { return bad_char_occurrence[static_cast(char_code)]; } @@ -160,27 +157,26 @@ class StringSearch : private StringSearchBase { size_t start_; }; - template inline T AlignDown(T value, U alignment) { return reinterpret_cast( (reinterpret_cast(value) & ~(alignment - 1))); } - inline uint8_t GetHighestValueByte(uint16_t character) { return std::max(static_cast(character & 0xFF), static_cast(character >> 8)); } - -inline uint8_t GetHighestValueByte(uint8_t character) { return character; } - +inline uint8_t GetHighestValueByte(uint8_t character) { + return character; +} // Searches for a byte value in a memory buffer, back to front. // Uses memrchr(3) on systems which support it, for speed. // Falls back to a vanilla for loop on non-GNU systems such as Windows. -inline const void* MemrchrFill(const void* haystack, uint8_t needle, +inline const void* MemrchrFill(const void* haystack, + uint8_t needle, size_t haystack_len) { #ifdef _GNU_SOURCE return memrchr(haystack, needle, haystack_len); @@ -195,12 +191,12 @@ inline const void* MemrchrFill(const void* haystack, uint8_t needle, #endif } - // Finds the first occurrence of *two-byte* character pattern[0] in the string // `subject`. Does not check that the whole pattern matches. template inline size_t FindFirstCharacter(Vector pattern, - Vector subject, size_t index) { + Vector subject, + size_t index) { const Char pattern_first_char = pattern[0]; const size_t max_n = (subject.length() - pattern.length() + 1); @@ -219,13 +215,11 @@ inline size_t FindFirstCharacter(Vector pattern, } else { CHECK_LE(pos, subject.length()); CHECK_LE(subject.length() - pos, SIZE_MAX / sizeof(Char)); - void_pos = MemrchrFill(subject.start() + pattern.length() - 1, - search_byte, - bytes_to_search); + void_pos = MemrchrFill( + subject.start() + pattern.length() - 1, search_byte, bytes_to_search); } const Char* char_pos = static_cast(void_pos); - if (char_pos == nullptr) - return subject.length(); + if (char_pos == nullptr) return subject.length(); // Then, for each match, verify that the full two bytes match pattern[0]. char_pos = AlignDown(char_pos, sizeof(Char)); @@ -241,7 +235,6 @@ inline size_t FindFirstCharacter(Vector pattern, return subject.length(); } - // Finds the first occurrence of the byte pattern[0] in string `subject`. // Does not verify that the whole pattern matches. template <> @@ -274,9 +267,7 @@ inline size_t FindFirstCharacter(Vector pattern, //--------------------------------------------------------------------- template -size_t StringSearch::SingleCharSearch( - Vector subject, - size_t index) { +size_t StringSearch::SingleCharSearch(Vector subject, size_t index) { CHECK_EQ(1, pattern_.length()); return FindFirstCharacter(pattern_, subject, index); } @@ -287,15 +278,12 @@ size_t StringSearch::SingleCharSearch( // Simple linear search for short patterns. Never bails out. template -size_t StringSearch::LinearSearch( - Vector subject, - size_t index) { +size_t StringSearch::LinearSearch(Vector subject, size_t index) { CHECK_GT(pattern_.length(), 1); const size_t n = subject.length() - pattern_.length(); for (size_t i = index; i <= n; i++) { i = FindFirstCharacter(pattern_, subject, i); - if (i == subject.length()) - return subject.length(); + if (i == subject.length()) return subject.length(); CHECK_LE(i, n); bool matches = true; @@ -317,9 +305,8 @@ size_t StringSearch::LinearSearch( //--------------------------------------------------------------------- template -size_t StringSearch::BoyerMooreSearch( - Vector subject, - size_t start_index) { +size_t StringSearch::BoyerMooreSearch(Vector subject, + size_t start_index) { const size_t subject_length = subject.length(); const size_t pattern_length = pattern_.length(); // Only preprocess at most kBMMaxShift last characters of pattern. @@ -350,9 +337,9 @@ size_t StringSearch::BoyerMooreSearch( if (j < start) { // we have matched more than our tables allow us to be smart about. // Fall back on BMH shift. - index += pattern_length - 1 - - CharOccurrence(bad_char_occurrence, - static_cast(last_char)); + index += + pattern_length - 1 - + CharOccurrence(bad_char_occurrence, static_cast(last_char)); } else { int gs_shift = good_suffix_shift[j + 1]; int bc_occ = CharOccurrence(bad_char_occurrence, c); @@ -437,9 +424,8 @@ void StringSearch::PopulateBoyerMooreTable() { //--------------------------------------------------------------------- template -size_t StringSearch::BoyerMooreHorspoolSearch( - Vector subject, - size_t start_index) { +size_t StringSearch::BoyerMooreHorspoolSearch(Vector subject, + size_t start_index) { const size_t subject_length = subject.length(); const size_t pattern_length = pattern_.length(); int* char_occurrences = bad_char_shift_table_; @@ -521,9 +507,7 @@ void StringSearch::PopulateBoyerMooreHorspoolTable() { // Simple linear search for short patterns, which bails out if the string // isn't found very early in the subject. Upgrades to BoyerMooreHorspool. template -size_t StringSearch::InitialSearch( - Vector subject, - size_t index) { +size_t StringSearch::InitialSearch(Vector subject, size_t index) { const size_t pattern_length = pattern_.length(); // Badness is a count of how much work we have done. When we have // done enough work we decide it's probably worth switching to a better @@ -536,8 +520,7 @@ size_t StringSearch::InitialSearch( badness++; if (badness <= 0) { i = FindFirstCharacter(pattern_, subject, i); - if (i == subject.length()) - return subject.length(); + if (i == subject.length()) return subject.length(); CHECK_LE(i, n); size_t j = 1; do { @@ -609,11 +592,15 @@ size_t SearchString(const Char* haystack, } template -size_t SearchString(const char* haystack, size_t haystack_length, +size_t SearchString(const char* haystack, + size_t haystack_length, const char (&needle)[N]) { - return SearchString( - reinterpret_cast(haystack), haystack_length, - reinterpret_cast(needle), N - 1, 0, true); + return SearchString(reinterpret_cast(haystack), + haystack_length, + reinterpret_cast(needle), + N - 1, + 0, + true); } } // namespace node diff --git a/src/tcp_wrap.cc b/src/tcp_wrap.cc index 805e566bfab08b..b366c06b697f82 100644 --- a/src/tcp_wrap.cc +++ b/src/tcp_wrap.cc @@ -21,19 +21,18 @@ #include "tcp_wrap.h" +#include "connect_wrap.h" #include "connection_wrap.h" #include "env-inl.h" #include "handle_wrap.h" #include "node_buffer.h" #include "node_internals.h" -#include "connect_wrap.h" #include "stream_base-inl.h" #include "stream_wrap.h" #include "util-inl.h" #include - namespace node { using v8::Boolean; @@ -52,7 +51,6 @@ using v8::Value; using AsyncHooks = Environment::AsyncHooks; - Local TCPWrap::Instantiate(Environment* env, AsyncWrap* parent, TCPWrap::SocketType type) { @@ -67,7 +65,6 @@ Local TCPWrap::Instantiate(Environment* env, return handle_scope.Escape(instance); } - void TCPWrap::Initialize(Local target, Local unused, Local context) { @@ -95,10 +92,10 @@ void TCPWrap::Initialize(Local target, env->SetProtoMethod(t, "connect", Connect); env->SetProtoMethod(t, "bind6", Bind6); env->SetProtoMethod(t, "connect6", Connect6); - env->SetProtoMethod(t, "getsockname", - GetSockOrPeerName); - env->SetProtoMethod(t, "getpeername", - GetSockOrPeerName); + env->SetProtoMethod( + t, "getsockname", GetSockOrPeerName); + env->SetProtoMethod( + t, "getpeername", GetSockOrPeerName); env->SetProtoMethod(t, "setNoDelay", SetNoDelay); env->SetProtoMethod(t, "setKeepAlive", SetKeepAlive); @@ -122,12 +119,13 @@ void TCPWrap::Initialize(Local target, Local constants = Object::New(env->isolate()); NODE_DEFINE_CONSTANT(constants, SOCKET); NODE_DEFINE_CONSTANT(constants, SERVER); - target->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "constants"), - constants).FromJust(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "constants"), + constants) + .FromJust(); } - void TCPWrap::New(const FunctionCallbackInfo& args) { // This constructor should not be exposed to public javascript. // Therefore we assert that we are not trying to call this as a @@ -154,7 +152,6 @@ void TCPWrap::New(const FunctionCallbackInfo& args) { new TCPWrap(env, args.This(), provider); } - TCPWrap::TCPWrap(Environment* env, Local object, ProviderType provider) : ConnectionWrap(env, object, provider) { int r = uv_tcp_init(env->event_loop(), &handle_); @@ -162,114 +159,94 @@ TCPWrap::TCPWrap(Environment* env, Local object, ProviderType provider) // Suggestion: uv_tcp_init() returns void. } - void TCPWrap::SetNoDelay(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int enable = static_cast(args[0]->BooleanValue()); int err = uv_tcp_nodelay(&wrap->handle_, enable); args.GetReturnValue().Set(err); } - void TCPWrap::SetKeepAlive(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int enable = args[0]->Int32Value(); unsigned int delay = args[1]->Uint32Value(); int err = uv_tcp_keepalive(&wrap->handle_, enable, delay); args.GetReturnValue().Set(err); } - #ifdef _WIN32 void TCPWrap::SetSimultaneousAccepts(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); bool enable = args[0]->BooleanValue(); int err = uv_tcp_simultaneous_accepts(&wrap->handle_, enable); args.GetReturnValue().Set(err); } #endif - void TCPWrap::Open(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int fd = static_cast(args[0]->IntegerValue()); int err = uv_tcp_open(&wrap->handle_, fd); - if (err == 0) - wrap->set_fd(fd); + if (err == 0) wrap->set_fd(fd); args.GetReturnValue().Set(err); } - void TCPWrap::Bind(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); node::Utf8Value ip_address(args.GetIsolate(), args[0]); int port = args[1]->Int32Value(); sockaddr_in addr; int err = uv_ip4_addr(*ip_address, port, &addr); if (err == 0) { - err = uv_tcp_bind(&wrap->handle_, - reinterpret_cast(&addr), - 0); + err = uv_tcp_bind( + &wrap->handle_, reinterpret_cast(&addr), 0); } args.GetReturnValue().Set(err); } - void TCPWrap::Bind6(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); node::Utf8Value ip6_address(args.GetIsolate(), args[0]); int port = args[1]->Int32Value(); sockaddr_in6 addr; int err = uv_ip6_addr(*ip6_address, port, &addr); if (err == 0) { - err = uv_tcp_bind(&wrap->handle_, - reinterpret_cast(&addr), - 0); + err = uv_tcp_bind( + &wrap->handle_, reinterpret_cast(&addr), 0); } args.GetReturnValue().Set(err); } - void TCPWrap::Listen(const FunctionCallbackInfo& args) { TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int backlog = args[0]->Int32Value(); - int err = uv_listen(reinterpret_cast(&wrap->handle_), - backlog, - OnConnection); + int err = uv_listen( + reinterpret_cast(&wrap->handle_), backlog, OnConnection); args.GetReturnValue().Set(err); } - void TCPWrap::Connect(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK(args[0]->IsObject()); CHECK(args[1]->IsString()); @@ -290,21 +267,18 @@ void TCPWrap::Connect(const FunctionCallbackInfo& args) { &wrap->handle_, reinterpret_cast(&addr), AfterConnect); - if (err) - delete req_wrap; + if (err) delete req_wrap; } args.GetReturnValue().Set(err); } - void TCPWrap::Connect6(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); TCPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK(args[0]->IsObject()); CHECK(args[1]->IsString()); @@ -325,14 +299,12 @@ void TCPWrap::Connect6(const FunctionCallbackInfo& args) { &wrap->handle_, reinterpret_cast(&addr), AfterConnect); - if (err) - delete req_wrap; + if (err) delete req_wrap; } args.GetReturnValue().Set(err); } - // also used by udp_wrap.cc Local AddressToJS(Environment* env, const sockaddr* addr, @@ -343,36 +315,34 @@ Local AddressToJS(Environment* env, const sockaddr_in6* a6; int port; - if (info.IsEmpty()) - info = Object::New(env->isolate()); + if (info.IsEmpty()) info = Object::New(env->isolate()); switch (addr->sa_family) { - case AF_INET6: - a6 = reinterpret_cast(addr); - uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip); - port = ntohs(a6->sin6_port); - info->Set(env->address_string(), OneByteString(env->isolate(), ip)); - info->Set(env->family_string(), env->ipv6_string()); - info->Set(env->port_string(), Integer::New(env->isolate(), port)); - break; - - case AF_INET: - a4 = reinterpret_cast(addr); - uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip); - port = ntohs(a4->sin_port); - info->Set(env->address_string(), OneByteString(env->isolate(), ip)); - info->Set(env->family_string(), env->ipv4_string()); - info->Set(env->port_string(), Integer::New(env->isolate(), port)); - break; - - default: - info->Set(env->address_string(), String::Empty(env->isolate())); + case AF_INET6: + a6 = reinterpret_cast(addr); + uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip); + port = ntohs(a6->sin6_port); + info->Set(env->address_string(), OneByteString(env->isolate(), ip)); + info->Set(env->family_string(), env->ipv6_string()); + info->Set(env->port_string(), Integer::New(env->isolate(), port)); + break; + + case AF_INET: + a4 = reinterpret_cast(addr); + uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip); + port = ntohs(a4->sin_port); + info->Set(env->address_string(), OneByteString(env->isolate(), ip)); + info->Set(env->family_string(), env->ipv4_string()); + info->Set(env->port_string(), Integer::New(env->isolate(), port)); + break; + + default: + info->Set(env->address_string(), String::Empty(env->isolate())); } return scope.Escape(info); } - } // namespace node NODE_BUILTIN_MODULE_CONTEXT_AWARE(tcp_wrap, node::TCPWrap::Initialize) diff --git a/src/tcp_wrap.h b/src/tcp_wrap.h index 829c1b22bf3aec..279f9c84702f99 100644 --- a/src/tcp_wrap.h +++ b/src/tcp_wrap.h @@ -25,17 +25,14 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "async_wrap.h" -#include "env.h" #include "connection_wrap.h" +#include "env.h" namespace node { class TCPWrap : public ConnectionWrap { public: - enum SocketType { - SOCKET, - SERVER - }; + enum SocketType { SOCKET, SERVER }; static v8::Local Instantiate(Environment* env, AsyncWrap* parent, @@ -66,7 +63,8 @@ class TCPWrap : public ConnectionWrap { int (*F)(const typename T::HandleType*, sockaddr*, int*)> friend void GetSockOrPeerName(const v8::FunctionCallbackInfo&); - TCPWrap(Environment* env, v8::Local object, + TCPWrap(Environment* env, + v8::Local object, ProviderType provider); static void New(const v8::FunctionCallbackInfo& args); @@ -85,7 +83,6 @@ class TCPWrap : public ConnectionWrap { #endif }; - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/timers.cc b/src/timers.cc index e9daf8d37cae92..057b188e9b289b 100644 --- a/src/timers.cc +++ b/src/timers.cc @@ -42,8 +42,8 @@ void ToggleImmediateRef(const FunctionCallbackInfo& args) { } void Initialize(Local target, - Local unused, - Local context) { + Local unused, + Local context) { Environment* env = Environment::GetCurrent(context); env->SetMethod(target, "getLibuvNow", GetLibuvNow); @@ -52,12 +52,13 @@ void Initialize(Local target, env->SetMethod(target, "toggleTimerRef", ToggleTimerRef); env->SetMethod(target, "toggleImmediateRef", ToggleImmediateRef); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "immediateInfo"), - env->immediate_info()->fields().GetJSArray()).FromJust(); + target + ->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "immediateInfo"), + env->immediate_info()->fields().GetJSArray()) + .FromJust(); } - } // anonymous namespace } // namespace node diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index 3efa6adb4edb0e..468a91aaae39ed 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -21,12 +21,12 @@ #include "tls_wrap.h" #include "async_wrap-inl.h" -#include "node_buffer.h" // Buffer -#include "node_crypto.h" // SecureContext +#include "node_buffer.h" // Buffer +#include "node_crypto.h" // SecureContext #include "node_crypto_bio.h" // NodeBIO // ClientHelloParser -#include "node_crypto_clienthello-inl.h" #include "node_counters.h" +#include "node_crypto_clienthello-inl.h" #include "node_internals.h" #include "stream_base-inl.h" #include "util-inl.h" @@ -55,7 +55,8 @@ TLSWrap::TLSWrap(Environment* env, SecureContext* sc) : AsyncWrap(env, env->tls_wrap_constructor_function() - ->NewInstance(env->context()).ToLocalChecked(), + ->NewInstance(env->context()) + .ToLocalChecked(), AsyncWrap::PROVIDER_TLSWRAP), SSLWrap(env, sc, kind), StreamBase(env), @@ -84,17 +85,14 @@ TLSWrap::TLSWrap(Environment* env, InitSSL(); } - TLSWrap::~TLSWrap() { enc_in_ = nullptr; enc_out_ = nullptr; sc_ = nullptr; } - bool TLSWrap::InvokeQueued(int status, const char* error_str) { - if (!write_callback_scheduled_) - return false; + if (!write_callback_scheduled_) return false; if (current_write_ != nullptr) { WriteWrap* w = current_write_; @@ -105,12 +103,10 @@ bool TLSWrap::InvokeQueued(int status, const char* error_str) { return true; } - void TLSWrap::NewSessionDoneCb() { Cycle(); } - void TLSWrap::InitSSL() { // Initialize SSL enc_in_ = crypto::NodeBIO::New(); @@ -152,7 +148,6 @@ void TLSWrap::InitSSL() { } } - void TLSWrap::Wrap(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -163,8 +158,8 @@ void TLSWrap::Wrap(const FunctionCallbackInfo& args) { Local stream_obj = args[0].As(); Local sc = args[1].As(); - Kind kind = args[2]->IsTrue() ? SSLWrap::kServer : - SSLWrap::kClient; + Kind kind = + args[2]->IsTrue() ? SSLWrap::kServer : SSLWrap::kClient; StreamBase* stream = static_cast(stream_obj->Value()); CHECK_NOT_NULL(stream); @@ -174,7 +169,6 @@ void TLSWrap::Wrap(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(res->object()); } - void TLSWrap::Receive(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -196,7 +190,6 @@ void TLSWrap::Receive(const FunctionCallbackInfo& args) { } } - void TLSWrap::Start(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -211,10 +204,8 @@ void TLSWrap::Start(const FunctionCallbackInfo& args) { wrap->EncOut(); } - void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { - if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE))) - return; + if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE))) return; // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants // a non-const SSL* in OpenSSL <= 0.9.7e. @@ -228,7 +219,7 @@ void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { if (where & SSL_CB_HANDSHAKE_START) { Local callback = object->Get(env->onhandshakestart_string()); if (callback->IsFunction()) { - Local argv[] = { env->GetNow() }; + Local argv[] = {env->GetNow()}; c->MakeCallback(callback.As(), arraysize(argv), argv); } } @@ -242,46 +233,38 @@ void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { } } - void TLSWrap::EncOut() { // Ignore cycling data if ClientHello wasn't yet parsed - if (!hello_parser_.IsEnded()) - return; + if (!hello_parser_.IsEnded()) return; // Write in progress - if (write_size_ != 0) - return; + if (write_size_ != 0) return; // Wait for `newSession` callback to be invoked - if (is_waiting_new_session()) - return; + if (is_waiting_new_session()) return; // Split-off queue if (established_ && current_write_ != nullptr) write_callback_scheduled_ = true; - if (ssl_ == nullptr) - return; + if (ssl_ == nullptr) return; // No data to write if (BIO_pending(enc_out_) == 0) { - if (pending_cleartext_input_.empty()) - InvokeQueued(0); + if (pending_cleartext_input_.empty()) InvokeQueued(0); return; } char* data[kSimultaneousBufferCount]; size_t size[arraysize(data)]; size_t count = arraysize(data); - write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, - size, - &count); + write_size_ = + crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count); CHECK(write_size_ != 0 && count != 0); uv_buf_t buf[arraysize(data)]; uv_buf_t* bufs = buf; - for (size_t i = 0; i < count; i++) - buf[i] = uv_buf_init(data[i], size[i]); + for (size_t i = 0; i < count; i++) buf[i] = uv_buf_init(data[i], size[i]); StreamWriteResult res = underlying_stream()->Write(bufs, count); if (res.err != 0) { @@ -295,13 +278,15 @@ void TLSWrap::EncOut() { HandleScope handle_scope(env()->isolate()); // Simulate asynchronous finishing, TLS cannot handle this at the moment. - env()->SetImmediate([](Environment* env, void* data) { - static_cast(data)->OnStreamAfterWrite(nullptr, 0); - }, this, object()); + env()->SetImmediate( + [](Environment* env, void* data) { + static_cast(data)->OnStreamAfterWrite(nullptr, 0); + }, + this, + object()); } } - void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) { if (current_empty_write_ != nullptr) { WriteWrap* finishing = current_empty_write_; @@ -310,14 +295,12 @@ void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) { return; } - if (ssl_ == nullptr) - status = UV_ECANCELED; + if (ssl_ == nullptr) status = UV_ECANCELED; // Handle error if (status) { // Ignore errors after shutdown - if (shutdown_) - return; + if (shutdown_) return; // Notify about error InvokeQueued(status); @@ -335,13 +318,11 @@ void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) { EncOut(); } - Local TLSWrap::GetSSLError(int status, int* err, std::string* msg) { EscapableHandleScope scope(env()->isolate()); // ssl_ is already destroyed in reading EOF by close notify alert. - if (ssl_ == nullptr) - return Local(); + if (ssl_ == nullptr) return Local(); *err = SSL_get_error(ssl_.get(), status); switch (*err) { @@ -353,43 +334,37 @@ Local TLSWrap::GetSSLError(int status, int* err, std::string* msg) { case SSL_ERROR_ZERO_RETURN: return scope.Escape(env()->zero_return_string()); break; - default: - { - CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL); + default: { + CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL); - BIO* bio = BIO_new(BIO_s_mem()); - ERR_print_errors(bio); + BIO* bio = BIO_new(BIO_s_mem()); + ERR_print_errors(bio); - BUF_MEM* mem; - BIO_get_mem_ptr(bio, &mem); + BUF_MEM* mem; + BIO_get_mem_ptr(bio, &mem); - Local message = - OneByteString(env()->isolate(), mem->data, mem->length); - Local exception = Exception::Error(message); + Local message = + OneByteString(env()->isolate(), mem->data, mem->length); + Local exception = Exception::Error(message); - if (msg != nullptr) - msg->assign(mem->data, mem->data + mem->length); + if (msg != nullptr) msg->assign(mem->data, mem->data + mem->length); - BIO_free_all(bio); + BIO_free_all(bio); - return scope.Escape(exception); - } + return scope.Escape(exception); + } } return Local(); } - void TLSWrap::ClearOut() { // Ignore cycling data if ClientHello wasn't yet parsed - if (!hello_parser_.IsEnded()) - return; + if (!hello_parser_.IsEnded()) return; // No reads after EOF - if (eof_) - return; + if (eof_) return; - if (ssl_ == nullptr) - return; + if (ssl_ == nullptr) return; crypto::MarkPopErrorOnReturn mark_pop_error_on_return; @@ -398,24 +373,21 @@ void TLSWrap::ClearOut() { for (;;) { read = SSL_read(ssl_.get(), out, sizeof(out)); - if (read <= 0) - break; + if (read <= 0) break; char* current = out; while (read > 0) { int avail = read; uv_buf_t buf = EmitAlloc(avail); - if (static_cast(buf.len) < avail) - avail = buf.len; + if (static_cast(buf.len) < avail) avail = buf.len; memcpy(buf.base, current, avail); EmitRead(avail, buf); // Caveat emptor: OnRead() calls into JS land which can result in // the SSL context object being destroyed. We have to carefully // check that ssl_ != nullptr afterwards. - if (ssl_ == nullptr) - return; + if (ssl_ == nullptr) return; read -= avail; current += avail; @@ -437,28 +409,23 @@ void TLSWrap::ClearOut() { Local arg = GetSSLError(read, &err, nullptr); // Ignore ZERO_RETURN after EOF, it is basically not a error - if (err == SSL_ERROR_ZERO_RETURN && eof_) - return; + if (err == SSL_ERROR_ZERO_RETURN && eof_) return; if (!arg.IsEmpty()) { // When TLS Alert are stored in wbio, // it should be flushed to socket before destroyed. - if (BIO_pending(enc_out_) != 0) - EncOut(); + if (BIO_pending(enc_out_) != 0) EncOut(); MakeCallback(env()->onerror_string(), 1, &arg); } } } - bool TLSWrap::ClearIn() { // Ignore cycling data if ClientHello wasn't yet parsed - if (!hello_parser_.IsEnded()) - return false; + if (!hello_parser_.IsEnded()) return false; - if (ssl_ == nullptr) - return false; + if (ssl_ == nullptr) return false; std::vector buffers; buffers.swap(pending_cleartext_input_); @@ -472,8 +439,7 @@ bool TLSWrap::ClearIn() { char* data = buffers[i].base; written = SSL_write(ssl_.get(), data, avail); CHECK(written == -1 || written == static_cast(avail)); - if (written == -1) - break; + if (written == -1) break; } // All written @@ -496,67 +462,52 @@ bool TLSWrap::ClearIn() { // Push back the not-yet-written pending buffers into their queue. // This can be skipped in the error case because no further writes // would succeed anyway. - pending_cleartext_input_.insert(pending_cleartext_input_.end(), - buffers.begin() + i, - buffers.end()); + pending_cleartext_input_.insert( + pending_cleartext_input_.end(), buffers.begin() + i, buffers.end()); } return false; } - AsyncWrap* TLSWrap::GetAsyncWrap() { return static_cast(this); } - bool TLSWrap::IsIPCPipe() { return underlying_stream()->IsIPCPipe(); } - int TLSWrap::GetFD() { return underlying_stream()->GetFD(); } - bool TLSWrap::IsAlive() { - return ssl_ != nullptr && - stream_ != nullptr && - underlying_stream()->IsAlive(); + return ssl_ != nullptr && stream_ != nullptr && + underlying_stream()->IsAlive(); } - bool TLSWrap::IsClosing() { return underlying_stream()->IsClosing(); } - - int TLSWrap::ReadStart() { - if (stream_ != nullptr) - return stream_->ReadStart(); + if (stream_ != nullptr) return stream_->ReadStart(); return 0; } - int TLSWrap::ReadStop() { - if (stream_ != nullptr) - return stream_->ReadStop(); + if (stream_ != nullptr) return stream_->ReadStop(); return 0; } - const char* TLSWrap::Error() const { return error_.empty() ? nullptr : error_.c_str(); } - void TLSWrap::ClearError() { error_.clear(); } - int TLSWrap::DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count, @@ -588,10 +539,13 @@ int TLSWrap::DoWrite(WriteWrap* w, StreamWriteResult res = underlying_stream()->Write(bufs, count, send_handle); if (!res.async) { - env()->SetImmediate([](Environment* env, void* data) { - TLSWrap* self = static_cast(data); - self->OnStreamAfterWrite(self->current_empty_write_, 0); - }, this, object()); + env()->SetImmediate( + [](Environment* env, void* data) { + TLSWrap* self = static_cast(data); + self->OnStreamAfterWrite(self->current_empty_write_, 0); + }, + this, + object()); } return 0; } @@ -613,8 +567,7 @@ int TLSWrap::DoWrite(WriteWrap* w, for (i = 0; i < count; i++) { written = SSL_write(ssl_.get(), bufs[i].base, bufs[i].len); CHECK(written == -1 || written == static_cast(bufs[i].len)); - if (written == -1) - break; + if (written == -1) break; } if (i != count) { @@ -625,9 +578,8 @@ int TLSWrap::DoWrite(WriteWrap* w, return UV_EPROTO; } - pending_cleartext_input_.insert(pending_cleartext_input_.end(), - &bufs[i], - &bufs[count]); + pending_cleartext_input_.insert( + pending_cleartext_input_.end(), &bufs[i], &bufs[count]); } // Try writing data immediately @@ -636,7 +588,6 @@ int TLSWrap::DoWrite(WriteWrap* w, return 0; } - uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) { CHECK_NOT_NULL(ssl_); @@ -645,16 +596,14 @@ uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) { return uv_buf_init(base, size); } - void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { - if (nread < 0) { + if (nread < 0) { // Error should be emitted only after all data was read ClearOut(); // Ignore EOF if received close_notify if (nread == UV_EOF) { - if (eof_) - return; + if (eof_) return; eof_ = true; } @@ -684,24 +633,20 @@ void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { Cycle(); } - ShutdownWrap* TLSWrap::CreateShutdownWrap(Local req_wrap_object) { return underlying_stream()->CreateShutdownWrap(req_wrap_object); } - int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) { crypto::MarkPopErrorOnReturn mark_pop_error_on_return; - if (ssl_ && SSL_shutdown(ssl_.get()) == 0) - SSL_shutdown(ssl_.get()); + if (ssl_ && SSL_shutdown(ssl_.get()) == 0) SSL_shutdown(ssl_.get()); shutdown_ = true; EncOut(); return stream_->DoShutdown(req_wrap); } - void TLSWrap::SetVerifyMode(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -720,8 +665,7 @@ void TLSWrap::SetVerifyMode(const FunctionCallbackInfo& args) { } else { bool reject_unauthorized = args[1]->IsTrue(); verify_mode = SSL_VERIFY_PEER; - if (reject_unauthorized) - verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + if (reject_unauthorized) verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; } } else { // Note request_cert and reject_unauthorized are ignored for clients. @@ -732,20 +676,16 @@ void TLSWrap::SetVerifyMode(const FunctionCallbackInfo& args) { SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback); } - -void TLSWrap::EnableSessionCallbacks( - const FunctionCallbackInfo& args) { +void TLSWrap::EnableSessionCallbacks(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); CHECK_NOT_NULL(wrap->ssl_); wrap->enable_session_callbacks(); crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength); - wrap->hello_parser_.Start(SSLWrap::OnClientHello, - OnClientHelloParseEnd, - wrap); + wrap->hello_parser_.Start( + SSLWrap::OnClientHello, OnClientHelloParseEnd, wrap); } - void TLSWrap::DestroySSL(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); @@ -761,24 +701,20 @@ void TLSWrap::DestroySSL(const FunctionCallbackInfo& args) { wrap->enc_in_ = nullptr; wrap->enc_out_ = nullptr; - if (wrap->stream_ != nullptr) - wrap->stream_->RemoveStreamListener(wrap); + if (wrap->stream_ != nullptr) wrap->stream_->RemoveStreamListener(wrap); } - void TLSWrap::EnableCertCb(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); wrap->WaitForCertCb(OnClientHelloParseEnd, wrap); } - void TLSWrap::OnClientHelloParseEnd(void* arg) { TLSWrap* c = static_cast(arg); c->Cycle(); } - void TLSWrap::GetServername(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -787,8 +723,8 @@ void TLSWrap::GetServername(const FunctionCallbackInfo& args) { CHECK_NOT_NULL(wrap->ssl_); - const char* servername = SSL_get_servername(wrap->ssl_.get(), - TLSEXT_NAMETYPE_host_name); + const char* servername = + SSL_get_servername(wrap->ssl_.get(), TLSEXT_NAMETYPE_host_name); if (servername != nullptr) { args.GetReturnValue().Set(OneByteString(env->isolate(), servername)); } else { @@ -796,7 +732,6 @@ void TLSWrap::GetServername(const FunctionCallbackInfo& args) { } } - void TLSWrap::SetServername(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -814,15 +749,13 @@ void TLSWrap::SetServername(const FunctionCallbackInfo& args) { SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername); } - int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) { TLSWrap* p = static_cast(SSL_get_app_data(s)); Environment* env = p->env(); const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); - if (servername == nullptr) - return SSL_TLSEXT_ERR_OK; + if (servername == nullptr) return SSL_TLSEXT_ERR_OK; HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); @@ -832,8 +765,7 @@ int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) { Local ctx = object->Get(env->sni_context_string()); // Not an object, probably undefined or null - if (!ctx->IsObject()) - return SSL_TLSEXT_ERR_NOACK; + if (!ctx->IsObject()) return SSL_TLSEXT_ERR_NOACK; Local cons = env->secure_context_constructor_template(); if (!cons->HasInstance(ctx)) { @@ -851,7 +783,6 @@ int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) { return SSL_TLSEXT_ERR_OK; } - void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo& info) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This()); @@ -865,7 +796,6 @@ void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo& info) { info.GetReturnValue().Set(write_queue_size); } - void TLSWrap::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackThis(this); tracker->TrackField("error", error_); @@ -876,7 +806,6 @@ void TLSWrap::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_)); } - void TLSWrap::Initialize(Local target, Local unused, Local context) { diff --git a/src/tls_wrap.h b/src/tls_wrap.h index aea8568b11b51c..6297f313af285f 100644 --- a/src/tls_wrap.h +++ b/src/tls_wrap.h @@ -43,7 +43,7 @@ class WriteWrap; namespace crypto { class SecureContext; class NodeBIO; -} +} // namespace crypto class TLSWrap : public AsyncWrap, public crypto::SSLWrap, @@ -110,8 +110,7 @@ class TLSWrap : public AsyncWrap, inline void Cycle() { // Prevent recursion - if (++cycle_depth_ > 1) - return; + if (++cycle_depth_ > 1) return; for (; cycle_depth_ > 0; cycle_depth_--) { ClearIn(); @@ -137,8 +136,7 @@ class TLSWrap : public AsyncWrap, static void SetVerifyMode(const v8::FunctionCallbackInfo& args); static void EnableSessionCallbacks( const v8::FunctionCallbackInfo& args); - static void EnableCertCb( - const v8::FunctionCallbackInfo& args); + static void EnableCertCb(const v8::FunctionCallbackInfo& args); static void DestroySSL(const v8::FunctionCallbackInfo& args); static void GetServername(const v8::FunctionCallbackInfo& args); static void SetServername(const v8::FunctionCallbackInfo& args); diff --git a/src/tracing/agent.cc b/src/tracing/agent.cc index a3ddfb61a95328..d56c0556c05914 100644 --- a/src/tracing/agent.cc +++ b/src/tracing/agent.cc @@ -13,7 +13,7 @@ namespace { class ScopedSuspendTracing { public: ScopedSuspendTracing(TracingController* controller, Agent* agent) - : controller_(controller), agent_(agent) { + : controller_(controller), agent_(agent) { controller->StopTracing(); } @@ -39,9 +39,9 @@ std::set flatten( } // namespace +using std::string; using v8::platform::tracing::TraceConfig; using v8::platform::tracing::TraceWriter; -using std::string; Agent::Agent(const std::string& log_file_pattern) : log_file_pattern_(log_file_pattern), file_writer_(EmptyClientHandle()) { @@ -50,13 +50,12 @@ Agent::Agent(const std::string& log_file_pattern) } void Agent::Start() { - if (started_) - return; + if (started_) return; CHECK_EQ(uv_loop_init(&tracing_loop_), 0); - NodeTraceBuffer* trace_buffer_ = new NodeTraceBuffer( - NodeTraceBuffer::kBufferChunks, this, &tracing_loop_); + NodeTraceBuffer* trace_buffer_ = + new NodeTraceBuffer(NodeTraceBuffer::kBufferChunks, this, &tracing_loop_); tracing_controller_->Initialize(trace_buffer_); // This thread should be created *after* async handles are created @@ -83,8 +82,7 @@ void Agent::Stop() { } void Agent::StopTracing() { - if (!started_) - return; + if (!started_) return; // Perform final Flush on TraceBuffer. We don't want the tracing controller // to flush the buffer again on destruction of the V8::Platform. tracing_controller_->StopTracing(); @@ -108,8 +106,7 @@ void Agent::ThreadCb(void* arg) { } void Agent::Enable(const std::string& categories) { - if (categories.empty()) - return; + if (categories.empty()) return; std::set categories_set; std::stringstream category_list(categories); while (category_list.good()) { @@ -122,10 +119,8 @@ void Agent::Enable(const std::string& categories) { void Agent::Enable(const std::set& categories) { std::string cats; - for (const std::string cat : categories) - cats += cat + ", "; - if (categories.empty()) - return; + for (const std::string cat : categories) cats += cat + ", "; + if (categories.empty()) return; file_writer_categories_.insert(categories.begin(), categories.end()); std::set full_list(file_writer_categories_.begin(), @@ -145,19 +140,16 @@ void Agent::Enable(const std::set& categories) { void Agent::Disable(const std::set& categories) { for (auto category : categories) { auto it = file_writer_categories_.find(category); - if (it != file_writer_categories_.end()) - file_writer_categories_.erase(it); + if (it != file_writer_categories_.end()) file_writer_categories_.erase(it); } - if (!file_writer_) - return; + if (!file_writer_) return; ScopedSuspendTracing suspend(tracing_controller_, this); - categories_[file_writer_->second] = { file_writer_categories_.begin(), - file_writer_categories_.end() }; + categories_[file_writer_->second] = {file_writer_categories_.begin(), + file_writer_categories_.end()}; } TraceConfig* Agent::CreateTraceConfig() { - if (categories_.empty()) - return nullptr; + if (categories_.empty()) return nullptr; TraceConfig* trace_config = new TraceConfig(); for (const auto& category : flatten(categories_)) { trace_config->AddIncludedCategory(category.c_str()); @@ -168,8 +160,7 @@ TraceConfig* Agent::CreateTraceConfig() { std::string Agent::GetEnabledCategories() { std::string categories; for (const auto& category : flatten(categories_)) { - if (!categories.empty()) - categories += ','; + if (!categories.empty()) categories += ','; categories += category; } return categories; @@ -181,8 +172,7 @@ void Agent::AppendTraceEvent(TraceObject* trace_event) { } void Agent::Flush(bool blocking) { - for (const auto& id_writer : writers_) - id_writer.second->Flush(blocking); + for (const auto& id_writer : writers_) id_writer.second->Flush(blocking); } } // namespace tracing } // namespace node diff --git a/src/tracing/agent.h b/src/tracing/agent.h index fd7984275969ba..9316aff5207c76 100644 --- a/src/tracing/agent.h +++ b/src/tracing/agent.h @@ -26,12 +26,9 @@ class TracingController : public v8::platform::tracing::TracingController { public: TracingController() : v8::platform::tracing::TracingController() {} - int64_t CurrentTimestampMicroseconds() override { - return uv_hrtime() / 1000; - } + int64_t CurrentTimestampMicroseconds() override { return uv_hrtime() / 1000; } }; - class Agent { public: // Resetting the pointer disconnects client diff --git a/src/tracing/node_trace_buffer.cc b/src/tracing/node_trace_buffer.cc index 70a0ad4b311610..d88b82f30bb7f6 100644 --- a/src/tracing/node_trace_buffer.cc +++ b/src/tracing/node_trace_buffer.cc @@ -3,10 +3,10 @@ namespace node { namespace tracing { -InternalTraceBuffer::InternalTraceBuffer(size_t max_chunks, uint32_t id, +InternalTraceBuffer::InternalTraceBuffer(size_t max_chunks, + uint32_t id, Agent* agent) - : flushing_(false), max_chunks_(max_chunks), - agent_(agent), id_(id) { + : flushing_(false), max_chunks_(max_chunks), agent_(agent), id_(id) { chunks_.resize(max_chunks); } @@ -69,15 +69,20 @@ void InternalTraceBuffer::Flush(bool blocking) { agent_->Flush(blocking); } -uint64_t InternalTraceBuffer::MakeHandle( - size_t chunk_index, uint32_t chunk_seq, size_t event_index) const { +uint64_t InternalTraceBuffer::MakeHandle(size_t chunk_index, + uint32_t chunk_seq, + size_t event_index) const { return ((static_cast(chunk_seq) * Capacity() + - chunk_index * TraceBufferChunk::kChunkSize + event_index) << 1) + id_; + chunk_index * TraceBufferChunk::kChunkSize + event_index) + << 1) + + id_; } -void InternalTraceBuffer::ExtractHandle( - uint64_t handle, uint32_t* buffer_id, size_t* chunk_index, - uint32_t* chunk_seq, size_t* event_index) const { +void InternalTraceBuffer::ExtractHandle(uint64_t handle, + uint32_t* buffer_id, + size_t* chunk_index, + uint32_t* chunk_seq, + size_t* event_index) const { *buffer_id = static_cast(handle & 0x1); handle >>= 1; *chunk_seq = static_cast(handle / Capacity()); @@ -87,15 +92,16 @@ void InternalTraceBuffer::ExtractHandle( } NodeTraceBuffer::NodeTraceBuffer(size_t max_chunks, - Agent* agent, uv_loop_t* tracing_loop) + Agent* agent, + uv_loop_t* tracing_loop) : tracing_loop_(tracing_loop), buffer1_(max_chunks, 0, agent), buffer2_(max_chunks, 1, agent) { current_buf_.store(&buffer1_); flush_signal_.data = this; - int err = uv_async_init(tracing_loop_, &flush_signal_, - NonBlockingFlushSignalCb); + int err = + uv_async_init(tracing_loop_, &flush_signal_, NonBlockingFlushSignalCb); CHECK_EQ(err, 0); exit_signal_.data = this; @@ -140,8 +146,8 @@ bool NodeTraceBuffer::TryLoadAvailableBuffer() { InternalTraceBuffer* prev_buf = current_buf_.load(); if (prev_buf->IsFull()) { uv_async_send(&flush_signal_); // trigger flush on a separate thread - InternalTraceBuffer* other_buf = prev_buf == &buffer1_ ? - &buffer2_ : &buffer1_; + InternalTraceBuffer* other_buf = + prev_buf == &buffer1_ ? &buffer2_ : &buffer1_; if (!other_buf->IsFull()) { current_buf_.store(other_buf); } else { @@ -168,12 +174,12 @@ void NodeTraceBuffer::ExitSignalCb(uv_async_t* signal) { uv_close(reinterpret_cast(&buffer->flush_signal_), nullptr); uv_close(reinterpret_cast(&buffer->exit_signal_), [](uv_handle_t* signal) { - NodeTraceBuffer* buffer = - reinterpret_cast(signal->data); - Mutex::ScopedLock scoped_lock(buffer->exit_mutex_); - buffer->exited_ = true; - buffer->exit_cond_.Signal(scoped_lock); - }); + NodeTraceBuffer* buffer = + reinterpret_cast(signal->data); + Mutex::ScopedLock scoped_lock(buffer->exit_mutex_); + buffer->exited_ = true; + buffer->exit_cond_.Signal(scoped_lock); + }); } } // namespace tracing diff --git a/src/tracing/node_trace_buffer.h b/src/tracing/node_trace_buffer.h index b59ae4f0a0e4ef..d5d3871cc23083 100644 --- a/src/tracing/node_trace_buffer.h +++ b/src/tracing/node_trace_buffer.h @@ -1,9 +1,9 @@ #ifndef SRC_TRACING_NODE_TRACE_BUFFER_H_ #define SRC_TRACING_NODE_TRACE_BUFFER_H_ -#include "tracing/agent.h" -#include "node_mutex.h" #include "libplatform/v8-tracing.h" +#include "node_mutex.h" +#include "tracing/agent.h" #include @@ -27,15 +27,17 @@ class InternalTraceBuffer { bool IsFull() const { return total_chunks_ == max_chunks_ && chunks_[total_chunks_ - 1]->IsFull(); } - bool IsFlushing() const { - return flushing_; - } + bool IsFlushing() const { return flushing_; } private: - uint64_t MakeHandle(size_t chunk_index, uint32_t chunk_seq, + uint64_t MakeHandle(size_t chunk_index, + uint32_t chunk_seq, size_t event_index) const; - void ExtractHandle(uint64_t handle, uint32_t* buffer_id, size_t* chunk_index, - uint32_t* chunk_seq, size_t* event_index) const; + void ExtractHandle(uint64_t handle, + uint32_t* buffer_id, + size_t* chunk_index, + uint32_t* chunk_seq, + size_t* event_index) const; size_t Capacity() const { return max_chunks_ * TraceBufferChunk::kChunkSize; } Mutex mutex_; diff --git a/src/tracing/node_trace_writer.cc b/src/tracing/node_trace_writer.cc index a2f7bebfc72f9a..9ffb018e710f64 100644 --- a/src/tracing/node_trace_writer.cc +++ b/src/tracing/node_trace_writer.cc @@ -1,7 +1,7 @@ #include "tracing/node_trace_writer.h" -#include #include +#include #include "util.h" @@ -75,8 +75,12 @@ void NodeTraceWriter::OpenNewFileForStreaming() { replace_substring(&filepath, "${pid}", std::to_string(uv_os_getpid())); replace_substring(&filepath, "${rotation}", std::to_string(file_num_)); - fd_ = uv_fs_open(tracing_loop_, &req, filepath.c_str(), - O_CREAT | O_WRONLY | O_TRUNC, 0644, nullptr); + fd_ = uv_fs_open(tracing_loop_, + &req, + filepath.c_str(), + O_CREAT | O_WRONLY | O_TRUNC, + 0644, + nullptr); CHECK_NE(fd_, -1); uv_fs_req_cleanup(&req); } @@ -150,7 +154,7 @@ void NodeTraceWriter::WriteToFile(std::string&& str, int highest_request_id) { write_req->writer = this; write_req->highest_request_id = highest_request_id; uv_buf_t uv_buf = uv_buf_init(const_cast(write_req->str.c_str()), - write_req->str.length()); + write_req->str.length()); request_mutex_.Lock(); // Manage a queue of WriteRequest objects because the behavior of uv_write is // undefined if the same WriteRequest object is used more than once @@ -158,8 +162,13 @@ void NodeTraceWriter::WriteToFile(std::string&& str, int highest_request_id) { // of the latest write request that actually been completed. write_req_queue_.push(write_req); request_mutex_.Unlock(); - int err = uv_fs_write(tracing_loop_, reinterpret_cast(write_req), - fd_, &uv_buf, 1, -1, WriteCb); + int err = uv_fs_write(tracing_loop_, + reinterpret_cast(write_req), + fd_, + &uv_buf, + 1, + -1, + WriteCb); CHECK_EQ(err, 0); } @@ -186,12 +195,12 @@ void NodeTraceWriter::ExitSignalCb(uv_async_t* signal) { nullptr); uv_close(reinterpret_cast(&trace_writer->exit_signal_), [](uv_handle_t* signal) { - NodeTraceWriter* trace_writer = - static_cast(signal->data); - Mutex::ScopedLock scoped_lock(trace_writer->request_mutex_); - trace_writer->exited_ = true; - trace_writer->exit_cond_.Signal(scoped_lock); - }); + NodeTraceWriter* trace_writer = + static_cast(signal->data); + Mutex::ScopedLock scoped_lock(trace_writer->request_mutex_); + trace_writer->exited_ = true; + trace_writer->exit_cond_.Signal(scoped_lock); + }); } } // namespace tracing diff --git a/src/tracing/node_trace_writer.h b/src/tracing/node_trace_writer.h index b2d5e7912fa01d..2e0f69bca68434 100644 --- a/src/tracing/node_trace_writer.h +++ b/src/tracing/node_trace_writer.h @@ -1,11 +1,11 @@ #ifndef SRC_TRACING_NODE_TRACE_WRITER_H_ #define SRC_TRACING_NODE_TRACE_WRITER_H_ -#include #include +#include -#include "node_mutex.h" #include "libplatform/v8-tracing.h" +#include "node_mutex.h" #include "tracing/agent.h" #include "uv.h" diff --git a/src/tracing/traced_value.cc b/src/tracing/traced_value.cc index b2a1badad1247d..4c99e18a63a2c5 100644 --- a/src/tracing/traced_value.cc +++ b/src/tracing/traced_value.cc @@ -4,9 +4,9 @@ #include "tracing/traced_value.h" +#include #include #include -#include #include #if defined(NODE_HAVE_I18N_SUPPORT) @@ -38,18 +38,33 @@ std::string EscapeString(const char* value) { UChar32 c; U8_NEXT_OR_FFFD(value, i, len, c); switch (c) { - case '\b': result += "\\b"; break; - case '\f': result += "\\f"; break; - case '\n': result += "\\n"; break; - case '\r': result += "\\r"; break; - case '\t': result += "\\t"; break; - case '\\': result += "\\\\"; break; - case '"': result += "\\\""; break; + case '\b': + result += "\\b"; + break; + case '\f': + result += "\\f"; + break; + case '\n': + result += "\\n"; + break; + case '\r': + result += "\\r"; + break; + case '\t': + result += "\\t"; + break; + case '\\': + result += "\\\\"; + break; + case '"': + result += "\\\""; + break; default: if (c < 32 || c > 126) { - snprintf( - number_buffer, arraysize(number_buffer), "\\u%04X", - static_cast(static_cast(c))); + snprintf(number_buffer, + arraysize(number_buffer), + "\\u%04X", + static_cast(static_cast(c))); result += number_buffer; } else { result.append(value + p, i - p); @@ -63,18 +78,33 @@ std::string EscapeString(const char* value) { while (*value) { char c = *value++; switch (c) { - case '\b': result += "\\b"; break; - case '\f': result += "\\f"; break; - case '\n': result += "\\n"; break; - case '\r': result += "\\r"; break; - case '\t': result += "\\t"; break; - case '\\': result += "\\\\"; break; - case '"': result += "\\\""; break; + case '\b': + result += "\\b"; + break; + case '\f': + result += "\\f"; + break; + case '\n': + result += "\\n"; + break; + case '\r': + result += "\\r"; + break; + case '\t': + result += "\\t"; + break; + case '\\': + result += "\\\\"; + break; + case '"': + result += "\\\""; + break; default: if (c < '\x20') { - snprintf( - number_buffer, arraysize(number_buffer), "\\u%04X", - static_cast(static_cast(c))); + snprintf(number_buffer, + arraysize(number_buffer), + "\\u%04X", + static_cast(static_cast(c))); result += number_buffer; } else { result += c; @@ -88,9 +118,12 @@ std::string EscapeString(const char* value) { std::string DoubleToCString(double v) { switch (FPCLASSIFY_NAMESPACE::fpclassify(v)) { - case FP_NAN: return "\"NaN\""; - case FP_INFINITE: return (v < 0.0 ? "\"-Infinity\"" : "\"Infinity\""); - case FP_ZERO: return "0"; + case FP_NAN: + return "\"NaN\""; + case FP_INFINITE: + return (v < 0.0 ? "\"-Infinity\"" : "\"Infinity\""); + case FP_ZERO: + return "0"; default: // This is a far less sophisticated version than the one used inside v8. std::ostringstream stream; @@ -110,8 +143,8 @@ std::unique_ptr TracedValue::CreateArray() { return std::unique_ptr(new TracedValue(true)); } -TracedValue::TracedValue(bool root_is_array) : - first_item_(true), root_is_array_(root_is_array) {} +TracedValue::TracedValue(bool root_is_array) + : first_item_(true), root_is_array_(root_is_array) {} TracedValue::~TracedValue() {} diff --git a/src/tty_wrap.cc b/src/tty_wrap.cc index 39d7ca1474ff8a..6da894da79a7fd 100644 --- a/src/tty_wrap.cc +++ b/src/tty_wrap.cc @@ -41,7 +41,6 @@ using v8::Object; using v8::String; using v8::Value; - void TTYWrap::Initialize(Local target, Local unused, Local context) { @@ -67,12 +66,10 @@ void TTYWrap::Initialize(Local target, env->set_tty_constructor_template(t); } - uv_tty_t* TTYWrap::UVHandle() { return &handle_; } - void TTYWrap::GuessHandleType(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); int fd = args[0]->Int32Value(); @@ -82,20 +79,31 @@ void TTYWrap::GuessHandleType(const FunctionCallbackInfo& args) { const char* type = nullptr; switch (t) { - case UV_TCP: type = "TCP"; break; - case UV_TTY: type = "TTY"; break; - case UV_UDP: type = "UDP"; break; - case UV_FILE: type = "FILE"; break; - case UV_NAMED_PIPE: type = "PIPE"; break; - case UV_UNKNOWN_HANDLE: type = "UNKNOWN"; break; - default: - ABORT(); + case UV_TCP: + type = "TCP"; + break; + case UV_TTY: + type = "TTY"; + break; + case UV_UDP: + type = "UDP"; + break; + case UV_FILE: + type = "FILE"; + break; + case UV_NAMED_PIPE: + type = "PIPE"; + break; + case UV_UNKNOWN_HANDLE: + type = "UNKNOWN"; + break; + default: + ABORT(); } args.GetReturnValue().Set(OneByteString(env->isolate(), type)); } - void TTYWrap::IsTTY(const FunctionCallbackInfo& args) { int fd = args[0]->Int32Value(); CHECK_GE(fd, 0); @@ -103,14 +111,12 @@ void TTYWrap::IsTTY(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(rc); } - void TTYWrap::GetWindowSize(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); TTYWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK(args[0]->IsArray()); int width, height; @@ -125,17 +131,14 @@ void TTYWrap::GetWindowSize(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(err); } - void TTYWrap::SetRawMode(const FunctionCallbackInfo& args) { TTYWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int err = uv_tty_set_mode(&wrap->handle_, args[0]->IsTrue()); args.GetReturnValue().Set(err); } - void TTYWrap::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -155,7 +158,6 @@ void TTYWrap::New(const FunctionCallbackInfo& args) { } } - TTYWrap::TTYWrap(Environment* env, Local object, int fd, @@ -167,8 +169,7 @@ TTYWrap::TTYWrap(Environment* env, AsyncWrap::PROVIDER_TTYWRAP) { *init_err = uv_tty_init(env->event_loop(), &handle_, fd, readable); set_fd(fd); - if (*init_err != 0) - MarkAsUninitialized(); + if (*init_err != 0) MarkAsUninitialized(); } } // namespace node diff --git a/src/tty_wrap.h b/src/tty_wrap.h index 45357cfa4637cf..ad3cbf5b62486a 100644 --- a/src/tty_wrap.h +++ b/src/tty_wrap.h @@ -25,8 +25,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "env.h" -#include "uv.h" #include "stream_wrap.h" +#include "uv.h" namespace node { diff --git a/src/udp_wrap.cc b/src/udp_wrap.cc index 2ef5c61358744a..b62f694d703a2d 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -21,14 +21,12 @@ #include "udp_wrap.h" #include "env-inl.h" +#include "handle_wrap.h" #include "node_buffer.h" #include "node_internals.h" -#include "handle_wrap.h" #include "req_wrap-inl.h" #include "util-inl.h" - - namespace node { using v8::Array; @@ -49,7 +47,6 @@ using v8::Value; using AsyncHooks = Environment::AsyncHooks; - class SendWrap : public ReqWrap { public: SendWrap(Environment* env, Local req_wrap_obj, bool have_callback); @@ -66,20 +63,16 @@ class SendWrap : public ReqWrap { const bool have_callback_; }; - SendWrap::SendWrap(Environment* env, Local req_wrap_obj, bool have_callback) : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_UDPSENDWRAP), - have_callback_(have_callback) { -} - + have_callback_(have_callback) {} inline bool SendWrap::have_callback() const { return have_callback_; } - UDPWrap::UDPWrap(Environment* env, Local object) : HandleWrap(env, object, @@ -89,7 +82,6 @@ UDPWrap::UDPWrap(Environment* env, Local object) CHECK_EQ(r, 0); // can't fail anyway } - void UDPWrap::Initialize(Local target, Local unused, Local context) { @@ -97,8 +89,7 @@ void UDPWrap::Initialize(Local target, Local t = env->NewFunctionTemplate(New); t->InstanceTemplate()->SetInternalFieldCount(1); - Local udpString = - FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"); + Local udpString = FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"); t->SetClassName(udpString); enum PropertyAttribute attributes = @@ -106,16 +97,11 @@ void UDPWrap::Initialize(Local target, Local signature = Signature::New(env->isolate(), t); - Local get_fd_templ = - FunctionTemplate::New(env->isolate(), - UDPWrap::GetFD, - env->as_external(), - signature); + Local get_fd_templ = FunctionTemplate::New( + env->isolate(), UDPWrap::GetFD, env->as_external(), signature); - t->PrototypeTemplate()->SetAccessorProperty(env->fd_string(), - get_fd_templ, - Local(), - attributes); + t->PrototypeTemplate()->SetAccessorProperty( + env->fd_string(), get_fd_templ, Local(), attributes); env->SetProtoMethod(t, "bind", Bind); env->SetProtoMethod(t, "send", Send); @@ -123,8 +109,8 @@ void UDPWrap::Initialize(Local target, env->SetProtoMethod(t, "send6", Send6); env->SetProtoMethod(t, "recvStart", RecvStart); env->SetProtoMethod(t, "recvStop", RecvStop); - env->SetProtoMethod(t, "getsockname", - GetSockOrPeerName); + env->SetProtoMethod( + t, "getsockname", GetSockOrPeerName); env->SetProtoMethod(t, "addMembership", AddMembership); env->SetProtoMethod(t, "dropMembership", DropMembership); env->SetProtoMethod(t, "setMulticastInterface", SetMulticastInterface); @@ -150,14 +136,12 @@ void UDPWrap::Initialize(Local target, target->Set(sendWrapString, swt->GetFunction()); } - void UDPWrap::New(const FunctionCallbackInfo& args) { CHECK(args.IsConstructCall()); Environment* env = Environment::GetCurrent(args); new UDPWrap(env, args.This()); } - void UDPWrap::GetFD(const FunctionCallbackInfo& args) { int fd = UV_EBADF; #if !defined(_WIN32) @@ -168,12 +152,10 @@ void UDPWrap::GetFD(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(fd); } - void UDPWrap::DoBind(const FunctionCallbackInfo& args, int family) { UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); // bind(ip, port, flags) CHECK_EQ(args.Length(), 3); @@ -185,49 +167,44 @@ void UDPWrap::DoBind(const FunctionCallbackInfo& args, int family) { int err; switch (family) { - case AF_INET: - err = uv_ip4_addr(*address, port, reinterpret_cast(&addr)); - break; - case AF_INET6: - err = uv_ip6_addr(*address, port, reinterpret_cast(&addr)); - break; - default: - CHECK(0 && "unexpected address family"); - ABORT(); + case AF_INET: + err = uv_ip4_addr(*address, port, reinterpret_cast(&addr)); + break; + case AF_INET6: + err = uv_ip6_addr(*address, port, reinterpret_cast(&addr)); + break; + default: + CHECK(0 && "unexpected address family"); + ABORT(); } if (err == 0) { - err = uv_udp_bind(&wrap->handle_, - reinterpret_cast(&addr), - flags); + err = uv_udp_bind( + &wrap->handle_, reinterpret_cast(&addr), flags); } args.GetReturnValue().Set(err); } - void UDPWrap::Bind(const FunctionCallbackInfo& args) { DoBind(args, AF_INET); } - void UDPWrap::Bind6(const FunctionCallbackInfo& args) { DoBind(args, AF_INET6); } - void UDPWrap::BufferSize(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK(args[0]->IsUint32()); CHECK(args[1]->IsBoolean()); bool is_recv = args[1].As()->Value(); - const char* uv_func_name = is_recv ? "uv_recv_buffer_size" : - "uv_send_buffer_size"; + const char* uv_func_name = + is_recv ? "uv_recv_buffer_size" : "uv_send_buffer_size"; if (!args[0]->IsInt32()) { env->CollectUVExceptionInfo(args[2], UV_EINVAL, uv_func_name); @@ -251,14 +228,13 @@ void UDPWrap::BufferSize(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(size); } - -#define X(name, fn) \ - void UDPWrap::name(const FunctionCallbackInfo& args) { \ - UDPWrap* wrap = Unwrap(args.Holder()); \ - CHECK_EQ(args.Length(), 1); \ - int flag = args[0]->Int32Value(); \ - int err = wrap == nullptr ? UV_EBADF : fn(&wrap->handle_, flag); \ - args.GetReturnValue().Set(err); \ +#define X(name, fn) \ + void UDPWrap::name(const FunctionCallbackInfo& args) { \ + UDPWrap* wrap = Unwrap(args.Holder()); \ + CHECK_EQ(args.Length(), 1); \ + int flag = args[0]->Int32Value(); \ + int err = wrap == nullptr ? UV_EBADF : fn(&wrap->handle_, flag); \ + args.GetReturnValue().Set(err); \ } X(SetTTL, uv_udp_set_ttl) @@ -270,9 +246,8 @@ X(SetMulticastLoopback, uv_udp_set_multicast_loop) void UDPWrap::SetMulticastInterface(const FunctionCallbackInfo& args) { UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsString()); @@ -288,9 +263,8 @@ void UDPWrap::SetMulticastInterface(const FunctionCallbackInfo& args) { void UDPWrap::SetMembership(const FunctionCallbackInfo& args, uv_membership membership) { UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); CHECK_EQ(args.Length(), 2); @@ -299,34 +273,28 @@ void UDPWrap::SetMembership(const FunctionCallbackInfo& args, const char* iface_cstr = *iface; if (args[1]->IsUndefined() || args[1]->IsNull()) { - iface_cstr = nullptr; + iface_cstr = nullptr; } - int err = uv_udp_set_membership(&wrap->handle_, - *address, - iface_cstr, - membership); + int err = + uv_udp_set_membership(&wrap->handle_, *address, iface_cstr, membership); args.GetReturnValue().Set(err); } - void UDPWrap::AddMembership(const FunctionCallbackInfo& args) { SetMembership(args, UV_JOIN_GROUP); } - void UDPWrap::DropMembership(const FunctionCallbackInfo& args) { SetMembership(args, UV_LEAVE_GROUP); } - void UDPWrap::DoSend(const FunctionCallbackInfo& args, int family) { Environment* env = Environment::GetCurrent(args); UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); // send(req, list, list.length, port, address, hasCallback) CHECK(args[0]->IsObject()); @@ -370,15 +338,15 @@ void UDPWrap::DoSend(const FunctionCallbackInfo& args, int family) { int err; switch (family) { - case AF_INET: - err = uv_ip4_addr(*address, port, reinterpret_cast(&addr)); - break; - case AF_INET6: - err = uv_ip6_addr(*address, port, reinterpret_cast(&addr)); - break; - default: - CHECK(0 && "unexpected address family"); - ABORT(); + case AF_INET: + err = uv_ip4_addr(*address, port, reinterpret_cast(&addr)); + break; + case AF_INET6: + err = uv_ip6_addr(*address, port, reinterpret_cast(&addr)); + break; + default: + CHECK(0 && "unexpected address family"); + ABORT(); } if (err == 0) { @@ -390,46 +358,37 @@ void UDPWrap::DoSend(const FunctionCallbackInfo& args, int family) { OnSend); } - if (err) - delete req_wrap; + if (err) delete req_wrap; args.GetReturnValue().Set(err); } - void UDPWrap::Send(const FunctionCallbackInfo& args) { DoSend(args, AF_INET); } - void UDPWrap::Send6(const FunctionCallbackInfo& args) { DoSend(args, AF_INET6); } - void UDPWrap::RecvStart(const FunctionCallbackInfo& args) { UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv); // UV_EALREADY means that the socket is already bound but that's okay - if (err == UV_EALREADY) - err = 0; + if (err == UV_EALREADY) err = 0; args.GetReturnValue().Set(err); } - void UDPWrap::RecvStop(const FunctionCallbackInfo& args) { UDPWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, - args.Holder(), - args.GetReturnValue().Set(UV_EBADF)); + ASSIGN_OR_RETURN_UNWRAP( + &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF)); int r = uv_udp_recv_stop(&wrap->handle_); args.GetReturnValue().Set(r); } - void UDPWrap::OnSend(uv_udp_send_t* req, int status) { SendWrap* req_wrap = static_cast(req->data); if (req_wrap->have_callback()) { @@ -437,15 +396,14 @@ void UDPWrap::OnSend(uv_udp_send_t* req, int status) { HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); Local arg[] = { - Integer::New(env->isolate(), status), - Integer::New(env->isolate(), req_wrap->msg_size), + Integer::New(env->isolate(), status), + Integer::New(env->isolate(), req_wrap->msg_size), }; req_wrap->MakeCallback(env->oncomplete_string(), 2, arg); } delete req_wrap; } - void UDPWrap::OnAlloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { @@ -453,15 +411,13 @@ void UDPWrap::OnAlloc(uv_handle_t* handle, buf->len = suggested_size; } - void UDPWrap::OnRecv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags) { if (nread == 0 && addr == nullptr) { - if (buf->base != nullptr) - free(buf->base); + if (buf->base != nullptr) free(buf->base); return; } @@ -472,16 +428,13 @@ void UDPWrap::OnRecv(uv_udp_t* handle, Context::Scope context_scope(env->context()); Local wrap_obj = wrap->object(); - Local argv[] = { - Integer::New(env->isolate(), nread), - wrap_obj, - Undefined(env->isolate()), - Undefined(env->isolate()) - }; + Local argv[] = {Integer::New(env->isolate(), nread), + wrap_obj, + Undefined(env->isolate()), + Undefined(env->isolate())}; if (nread < 0) { - if (buf->base != nullptr) - free(buf->base); + if (buf->base != nullptr) free(buf->base); wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv); return; } @@ -492,7 +445,6 @@ void UDPWrap::OnRecv(uv_udp_t* handle, wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv); } - Local UDPWrap::Instantiate(Environment* env, AsyncWrap* parent, UDPWrap::SocketType type) { @@ -502,16 +454,15 @@ Local UDPWrap::Instantiate(Environment* env, // If this assert fires then Initialize hasn't been called yet. CHECK_EQ(env->udp_constructor_function().IsEmpty(), false); Local instance = env->udp_constructor_function() - ->NewInstance(env->context()).ToLocalChecked(); + ->NewInstance(env->context()) + .ToLocalChecked(); return scope.Escape(instance); } - uv_udp_t* UDPWrap::UVHandle() { return &handle_; } - } // namespace node NODE_BUILTIN_MODULE_CONTEXT_AWARE(udp_wrap, node::UDPWrap::Initialize) diff --git a/src/udp_wrap.h b/src/udp_wrap.h index ca048f5aef98af..b978cab6337966 100644 --- a/src/udp_wrap.h +++ b/src/udp_wrap.h @@ -32,11 +32,9 @@ namespace node { -class UDPWrap: public HandleWrap { +class UDPWrap : public HandleWrap { public: - enum SocketType { - SOCKET - }; + enum SocketType { SOCKET }; static void Initialize(v8::Local target, v8::Local unused, v8::Local context); diff --git a/src/util-inl.h b/src/util-inl.h index c6cd263aa2714a..ee72d92c708462 100644 --- a/src/util-inl.h +++ b/src/util-inl.h @@ -24,8 +24,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "util.h" #include +#include "util.h" #if defined(_MSC_VER) #include @@ -34,20 +34,17 @@ #define BSWAP_8(x) _byteswap_uint64(x) #else #define BSWAP_2(x) ((x) << 8) | ((x) >> 8) -#define BSWAP_4(x) \ - (((x) & 0xFF) << 24) | \ - (((x) & 0xFF00) << 8) | \ - (((x) >> 8) & 0xFF00) | \ - (((x) >> 24) & 0xFF) -#define BSWAP_8(x) \ - (((x) & 0xFF00000000000000ull) >> 56) | \ - (((x) & 0x00FF000000000000ull) >> 40) | \ - (((x) & 0x0000FF0000000000ull) >> 24) | \ - (((x) & 0x000000FF00000000ull) >> 8) | \ - (((x) & 0x00000000FF000000ull) << 8) | \ - (((x) & 0x0000000000FF0000ull) << 24) | \ - (((x) & 0x000000000000FF00ull) << 40) | \ - (((x) & 0x00000000000000FFull) << 56) +#define BSWAP_4(x) \ + (((x)&0xFF) << 24) | (((x)&0xFF00) << 8) | (((x) >> 8) & 0xFF00) | \ + (((x) >> 24) & 0xFF) +#define BSWAP_8(x) \ + (((x)&0xFF00000000000000ull) >> 56) | (((x)&0x00FF000000000000ull) >> 40) | \ + (((x)&0x0000FF0000000000ull) >> 24) | \ + (((x)&0x000000FF00000000ull) >> 8) | \ + (((x)&0x00000000FF000000ull) << 8) | \ + (((x)&0x0000000000FF0000ull) << 24) | \ + (((x)&0x000000000000FF00ull) << 40) | \ + (((x)&0x00000000000000FFull) << 56) #endif namespace node { @@ -73,33 +70,32 @@ bool ListNode::IsEmpty() const { return prev_ == this; } -template (T::*M)> +template (T::*M)> ListHead::Iterator::Iterator(ListNode* node) : node_(node) {} -template (T::*M)> +template (T::*M)> T* ListHead::Iterator::operator*() const { return ContainerOf(M, node_); } -template (T::*M)> -const typename ListHead::Iterator& -ListHead::Iterator::operator++() { +template (T::*M)> +const typename ListHead::Iterator& ListHead::Iterator:: +operator++() { node_ = node_->next_; return *this; } -template (T::*M)> +template (T::*M)> bool ListHead::Iterator::operator!=(const Iterator& that) const { return node_ != that.node_; } -template (T::*M)> +template (T::*M)> ListHead::~ListHead() { - while (IsEmpty() == false) - head_.next_->Remove(); + while (IsEmpty() == false) head_.next_->Remove(); } -template (T::*M)> +template (T::*M)> void ListHead::PushBack(T* element) { ListNode* that = &(element->*M); head_.prev_->next_ = that; @@ -108,7 +104,7 @@ void ListHead::PushBack(T* element) { head_.prev_ = that; } -template (T::*M)> +template (T::*M)> void ListHead::PushFront(T* element) { ListNode* that = &(element->*M); head_.next_->prev_ = that; @@ -117,26 +113,25 @@ void ListHead::PushFront(T* element) { head_.next_ = that; } -template (T::*M)> +template (T::*M)> bool ListHead::IsEmpty() const { return head_.IsEmpty(); } -template (T::*M)> +template (T::*M)> T* ListHead::PopFront() { - if (IsEmpty()) - return nullptr; + if (IsEmpty()) return nullptr; ListNode* node = head_.next_; node->Remove(); return ContainerOf(M, node); } -template (T::*M)> +template (T::*M)> typename ListHead::Iterator ListHead::begin() const { return Iterator(head_.next_); } -template (T::*M)> +template (T::*M)> typename ListHead::Iterator ListHead::end() const { return Iterator(const_cast*>(&head_)); } @@ -149,9 +144,8 @@ constexpr uintptr_t OffsetOf(Inner Outer::*field) { template ContainerOfHelper::ContainerOfHelper(Inner Outer::*field, Inner* pointer) - : pointer_( - reinterpret_cast( - reinterpret_cast(pointer) - OffsetOf(field))) {} + : pointer_(reinterpret_cast(reinterpret_cast(pointer) - + OffsetOf(field))) {} template template @@ -167,8 +161,7 @@ inline ContainerOfHelper ContainerOf(Inner Outer::*field, template inline v8::Local PersistentToLocal( - v8::Isolate* isolate, - const Persistent& persistent) { + v8::Isolate* isolate, const Persistent& persistent) { if (persistent.IsWeak()) { return WeakPersistentToLocal(isolate, persistent); } else { @@ -185,8 +178,7 @@ inline v8::Local StrongPersistentToLocal( template inline v8::Local WeakPersistentToLocal( - v8::Isolate* isolate, - const Persistent& persistent) { + v8::Isolate* isolate, const Persistent& persistent) { return v8::Local::New(isolate, persistent); } @@ -196,7 +188,8 @@ inline v8::Local OneByteString(v8::Isolate* isolate, return v8::String::NewFromOneByte(isolate, reinterpret_cast(data), v8::NewStringType::kNormal, - length).ToLocalChecked(); + length) + .ToLocalChecked(); } inline v8::Local OneByteString(v8::Isolate* isolate, @@ -205,7 +198,8 @@ inline v8::Local OneByteString(v8::Isolate* isolate, return v8::String::NewFromOneByte(isolate, reinterpret_cast(data), v8::NewStringType::kNormal, - length).ToLocalChecked(); + length) + .ToLocalChecked(); } inline v8::Local OneByteString(v8::Isolate* isolate, @@ -214,7 +208,8 @@ inline v8::Local OneByteString(v8::Isolate* isolate, return v8::String::NewFromOneByte(isolate, reinterpret_cast(data), v8::NewStringType::kNormal, - length).ToLocalChecked(); + length) + .ToLocalChecked(); } void SwapBytes16(char* data, size_t nbytes) { @@ -295,27 +290,22 @@ char ToLower(char c) { std::string ToLower(const std::string& in) { std::string out(in.size(), 0); - for (size_t i = 0; i < in.size(); ++i) - out[i] = ToLower(in[i]); + for (size_t i = 0; i < in.size(); ++i) out[i] = ToLower(in[i]); return out; } bool StringEqualNoCase(const char* a, const char* b) { do { - if (*a == '\0') - return *b == '\0'; - if (*b == '\0') - return *a == '\0'; + if (*a == '\0') return *b == '\0'; + if (*b == '\0') return *a == '\0'; } while (ToLower(*a++) == ToLower(*b++)); return false; } bool StringEqualNoCaseN(const char* a, const char* b, size_t length) { for (size_t i = 0; i < length; i++) { - if (ToLower(a[i]) != ToLower(b[i])) - return false; - if (a[i] == '\0') - return true; + if (ToLower(a[i]) != ToLower(b[i])) return false; + if (a[i] == '\0') return true; } return true; } @@ -323,8 +313,7 @@ bool StringEqualNoCaseN(const char* a, const char* b, size_t length) { template inline T MultiplyWithOverflowCheck(T a, T b) { auto ret = a * b; - if (a != 0) - CHECK_EQ(b, ret / a); + if (a != 0) CHECK_EQ(b, ret / a); return ret; } @@ -392,10 +381,18 @@ inline T* Calloc(size_t n) { } // Shortcuts for char*. -inline char* Malloc(size_t n) { return Malloc(n); } -inline char* Calloc(size_t n) { return Calloc(n); } -inline char* UncheckedMalloc(size_t n) { return UncheckedMalloc(n); } -inline char* UncheckedCalloc(size_t n) { return UncheckedCalloc(n); } +inline char* Malloc(size_t n) { + return Malloc(n); +} +inline char* Calloc(size_t n) { + return Calloc(n); +} +inline char* UncheckedMalloc(size_t n) { + return UncheckedMalloc(n); +} +inline char* UncheckedCalloc(size_t n) { + return UncheckedCalloc(n); +} } // namespace node diff --git a/src/util.cc b/src/util.cc index 3e808e13fe87d8..0430a128a32920 100644 --- a/src/util.cc +++ b/src/util.cc @@ -19,11 +19,11 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "string_bytes.h" +#include #include "node_buffer.h" #include "node_internals.h" +#include "string_bytes.h" #include "uv.h" -#include namespace node { @@ -33,37 +33,30 @@ using v8::String; using v8::Value; template -static void MakeUtf8String(Isolate* isolate, - Local value, - T* target) { +static void MakeUtf8String(Isolate* isolate, Local value, T* target) { Local string = value->ToString(isolate); - if (string.IsEmpty()) - return; + if (string.IsEmpty()) return; const size_t storage = StringBytes::StorageSize(isolate, string, UTF8) + 1; target->AllocateSufficientStorage(storage); - const int flags = - String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8; + const int flags = String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8; const int length = string->WriteUtf8(target->out(), storage, 0, flags); target->SetLengthAndZeroTerminate(length); } Utf8Value::Utf8Value(Isolate* isolate, Local value) { - if (value.IsEmpty()) - return; + if (value.IsEmpty()) return; MakeUtf8String(isolate, value, this); } - TwoByteValue::TwoByteValue(Isolate* isolate, Local value) { if (value.IsEmpty()) { return; } Local string = value->ToString(isolate); - if (string.IsEmpty()) - return; + if (string.IsEmpty()) return; // Allocate enough space to include the null terminator const size_t storage = string->Length() + 1; diff --git a/src/util.h b/src/util.h index f7dcc5ea35abf8..e6804edf5ebbc6 100644 --- a/src/util.h +++ b/src/util.h @@ -34,8 +34,8 @@ #include #include -#include #include // std::function +#include namespace node { @@ -87,13 +87,13 @@ NO_RETURN void Abort(); NO_RETURN void Assert(const char* const (*args)[4]); void DumpBacktrace(FILE* fp); -#define FIXED_ONE_BYTE_STRING(isolate, string) \ +#define FIXED_ONE_BYTE_STRING(isolate, string) \ (node::OneByteString((isolate), (string), sizeof(string) - 1)) -#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - void operator=(const TypeName&) = delete; \ - void operator=(TypeName&&) = delete; \ - TypeName(const TypeName&) = delete; \ +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + void operator=(const TypeName&) = delete; \ + void operator=(TypeName&&) = delete; \ + TypeName(const TypeName&) = delete; \ TypeName(TypeName&&) = delete // Windows 8+ does not like abort() in Release mode @@ -118,13 +118,13 @@ void DumpBacktrace(FILE* fp); #define STRINGIFY_(x) #x #define STRINGIFY(x) STRINGIFY_(x) -#define CHECK(expr) \ - do { \ - if (UNLIKELY(!(expr))) { \ - static const char* const args[] = { __FILE__, STRINGIFY(__LINE__), \ - #expr, PRETTY_FUNCTION_NAME }; \ - node::Assert(&args); \ - } \ +#define CHECK(expr) \ + do { \ + if (UNLIKELY(!(expr))) { \ + static const char* const args[] = { \ + __FILE__, STRINGIFY(__LINE__), #expr, PRETTY_FUNCTION_NAME}; \ + node::Assert(&args); \ + } \ } while (0) #define CHECK_EQ(a, b) CHECK((a) == (b)) @@ -144,7 +144,7 @@ template class ListNode; // TAILQ-style intrusive list head. -template (T::*M)> +template (T::*M)> class ListHead; template @@ -156,14 +156,15 @@ class ListNode { inline bool IsEmpty() const; private: - template (U::*M)> friend class ListHead; + template (U::*M)> + friend class ListHead; friend int GenDebugSymbols(); ListNode* prev_; ListNode* next_; DISALLOW_COPY_AND_ASSIGN(ListNode); }; -template (T::*M)> +template (T::*M)> class ListHead { public: class Iterator { @@ -200,6 +201,7 @@ class ContainerOfHelper { inline ContainerOfHelper(Inner Outer::*field, Inner* pointer); template inline operator TypeName*() const; + private: Outer* const pointer_; }; @@ -215,8 +217,7 @@ inline ContainerOfHelper ContainerOf(Inner Outer::*field, // reference to the object. template inline v8::Local PersistentToLocal( - v8::Isolate* isolate, - const Persistent& persistent); + v8::Isolate* isolate, const Persistent& persistent); // Unchecked conversion from a non-weak Persistent to Local, // use with care! @@ -229,8 +230,7 @@ inline v8::Local StrongPersistentToLocal( template inline v8::Local WeakPersistentToLocal( - v8::Isolate* isolate, - const Persistent& persistent); + v8::Isolate* isolate, const Persistent& persistent); // Convenience wrapper around v8::String::NewFromOneByte(). inline v8::Local OneByteString(v8::Isolate* isolate, @@ -267,22 +267,14 @@ inline bool StringEqualNoCaseN(const char* a, const char* b, size_t length); template class MaybeStackBuffer { public: - const T* out() const { - return buf_; - } + const T* out() const { return buf_; } - T* out() { - return buf_; - } + T* out() { return buf_; } // operator* for compatibility with `v8::String::(Utf8)Value` - T* operator*() { - return buf_; - } + T* operator*() { return buf_; } - const T* operator*() const { - return buf_; - } + const T* operator*() const { return buf_; } T& operator[](size_t index) { CHECK_LT(index, length()); @@ -294,15 +286,12 @@ class MaybeStackBuffer { return buf_[index]; } - size_t length() const { - return length_; - } + size_t length() const { return length_; } // Current maximum capacity of the buffer with which SetLength() can be used // without first calling AllocateSufficientStorage(). size_t capacity() const { - return IsAllocated() ? capacity_ : - IsInvalidated() ? 0 : kStackStorageSize; + return IsAllocated() ? capacity_ : IsInvalidated() ? 0 : kStackStorageSize; } // Make sure enough space for `storage` entries is available. @@ -349,14 +338,10 @@ class MaybeStackBuffer { } // If the buffer is stored in the heap rather than on the stack. - bool IsAllocated() const { - return !IsInvalidated() && buf_ != buf_st_; - } + bool IsAllocated() const { return !IsInvalidated() && buf_ != buf_st_; } // If Invalidate() has been called. - bool IsInvalidated() const { - return buf_ == nullptr; - } + bool IsInvalidated() const { return buf_ == nullptr; } // Release ownership of the malloc'd buffer. // Note: This does not free the buffer. @@ -377,8 +362,7 @@ class MaybeStackBuffer { } ~MaybeStackBuffer() { - if (IsAllocated()) - free(buf_); + if (IsAllocated()) free(buf_); } private: @@ -404,20 +388,20 @@ class BufferValue : public MaybeStackBuffer { explicit BufferValue(v8::Isolate* isolate, v8::Local value); }; -#define SPREAD_BUFFER_ARG(val, name) \ - CHECK((val)->IsArrayBufferView()); \ - v8::Local name = (val).As(); \ - v8::ArrayBuffer::Contents name##_c = name->Buffer()->GetContents(); \ - const size_t name##_offset = name->ByteOffset(); \ - const size_t name##_length = name->ByteLength(); \ - char* const name##_data = \ - static_cast(name##_c.Data()) + name##_offset; \ - if (name##_length > 0) \ - CHECK_NE(name##_data, nullptr); +#define SPREAD_BUFFER_ARG(val, name) \ + CHECK((val)->IsArrayBufferView()); \ + v8::Local name = (val).As(); \ + v8::ArrayBuffer::Contents name##_c = name->Buffer()->GetContents(); \ + const size_t name##_offset = name->ByteOffset(); \ + const size_t name##_length = name->ByteLength(); \ + char* const name##_data = \ + static_cast(name##_c.Data()) + name##_offset; \ + if (name##_length > 0) CHECK_NE(name##_data, nullptr); // Use this when a variable or parameter is unused in order to explicitly // silence a compiler warning about that. -template inline void USE(T&&) {} +template +inline void USE(T&&) {} // Run a function when exiting the current scope. struct OnScopeLeave { @@ -449,23 +433,23 @@ struct MallocedBuffer { } MallocedBuffer& operator=(MallocedBuffer&& other) { this->~MallocedBuffer(); - return *new(this) MallocedBuffer(std::move(other)); - } - ~MallocedBuffer() { - free(data); + return *new (this) MallocedBuffer(std::move(other)); } + ~MallocedBuffer() { free(data); } MallocedBuffer(const MallocedBuffer&) = delete; MallocedBuffer& operator=(const MallocedBuffer&) = delete; }; // Test whether some value can be called with (). template -struct is_callable : std::is_function { }; +struct is_callable : std::is_function {}; template -struct is_callable::value - >::type> : std::true_type { }; +struct is_callable< + T, + typename std::enable_if< + std::is_same::value>::type> + : std::true_type {}; template struct FunctionDeleter { diff --git a/src/uv.cc b/src/uv.cc index 85cb2ad5373c5f..6cdd4d659e6356 100644 --- a/src/uv.cc +++ b/src/uv.cc @@ -20,9 +20,9 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "uv.h" +#include "env-inl.h" #include "node.h" #include "node_internals.h" -#include "env-inl.h" namespace node { namespace { @@ -38,7 +38,6 @@ using v8::Object; using v8::String; using v8::Value; - // TODO(joyeecheung): deprecate this function in favor of // lib/util.getSystemErrorName() void ErrName(const FunctionCallbackInfo& args) { @@ -49,7 +48,6 @@ void ErrName(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(OneByteString(env->isolate(), name)); } - void Initialize(Local target, Local unused, Local context) { @@ -64,19 +62,19 @@ void Initialize(Local target, Local err_map = Map::New(isolate); -#define V(name, msg) do { \ - Local arr = Array::New(isolate, 2); \ - arr->Set(0, OneByteString(isolate, #name)); \ - arr->Set(1, OneByteString(isolate, msg)); \ - err_map->Set(context, \ - Integer::New(isolate, UV_##name), \ - arr).ToLocalChecked(); \ -} while (0); +#define V(name, msg) \ + do { \ + Local arr = Array::New(isolate, 2); \ + arr->Set(0, OneByteString(isolate, #name)); \ + arr->Set(1, OneByteString(isolate, msg)); \ + err_map->Set(context, Integer::New(isolate, UV_##name), arr) \ + .ToLocalChecked(); \ + } while (0); UV_ERRNO_MAP(V) #undef V - target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "errmap"), - err_map).FromJust(); + target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "errmap"), err_map) + .FromJust(); } } // anonymous namespace diff --git a/src/v8abbr.h b/src/v8abbr.h index 9e8920204a386a..34b9cbd824f187 100644 --- a/src/v8abbr.h +++ b/src/v8abbr.h @@ -1,24 +1,24 @@ /** Copyright Joyent, Inc. and other Node contributors. -* -* Permission is hereby granted, free of charge, to any person obtaining a -* copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to permit -* persons to whom the Software is furnished to do so, subject to the -* following conditions: -* -* The above copyright notice and this permission notice shall be included -* in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -* USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the + * following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. + */ /* * This header defines short names for V8 constants for use by the ustack @@ -29,93 +29,83 @@ #define SRC_V8ABBR_H_ /* Frame pointer offsets */ -#define V8_OFF_FP_FUNC V8DBG_OFF_FP_FUNCTION -#define V8_OFF_FP_CONTEXT V8DBG_OFF_FP_CONTEXT -#define V8_OFF_FP_MARKER V8DBG_OFF_FP_MARKER +#define V8_OFF_FP_FUNC V8DBG_OFF_FP_FUNCTION +#define V8_OFF_FP_CONTEXT V8DBG_OFF_FP_CONTEXT +#define V8_OFF_FP_MARKER V8DBG_OFF_FP_MARKER /* Stack frame types */ -#define V8_FT_ENTRY V8DBG_FRAMETYPE_ENTRYFRAME -#define V8_FT_ENTRYCONSTRUCT V8DBG_FRAMETYPE_CONSTRUCTENTRYFRAME -#define V8_FT_EXIT V8DBG_FRAMETYPE_EXITFRAME -#define V8_FT_JAVASCRIPT V8DBG_FRAMETYPE_JAVASCRIPTFRAME -#define V8_FT_OPTIMIZED V8DBG_FRAMETYPE_OPTIMIZEDFRAME -#define V8_FT_INTERNAL V8DBG_FRAMETYPE_INTERNALFRAME -#define V8_FT_CONSTRUCT V8DBG_FRAMETYPE_CONSTRUCTFRAME -#define V8_FT_ADAPTOR V8DBG_FRAMETYPE_ARGUMENTSADAPTORFRAME -#define V8_FT_STUB V8DBG_FRAMETYPE_STUBFRAME +#define V8_FT_ENTRY V8DBG_FRAMETYPE_ENTRYFRAME +#define V8_FT_ENTRYCONSTRUCT V8DBG_FRAMETYPE_CONSTRUCTENTRYFRAME +#define V8_FT_EXIT V8DBG_FRAMETYPE_EXITFRAME +#define V8_FT_JAVASCRIPT V8DBG_FRAMETYPE_JAVASCRIPTFRAME +#define V8_FT_OPTIMIZED V8DBG_FRAMETYPE_OPTIMIZEDFRAME +#define V8_FT_INTERNAL V8DBG_FRAMETYPE_INTERNALFRAME +#define V8_FT_CONSTRUCT V8DBG_FRAMETYPE_CONSTRUCTFRAME +#define V8_FT_ADAPTOR V8DBG_FRAMETYPE_ARGUMENTSADAPTORFRAME +#define V8_FT_STUB V8DBG_FRAMETYPE_STUBFRAME /* Identification masks and tags */ -#define V8_SmiTagMask (V8DBG_SMITAGMASK) -#define V8_SmiTag (V8DBG_SMITAG) -#define V8_SmiValueShift (V8DBG_SMISHIFTSIZE + V8DBG_SMITAGMASK) +#define V8_SmiTagMask (V8DBG_SMITAGMASK) +#define V8_SmiTag (V8DBG_SMITAG) +#define V8_SmiValueShift (V8DBG_SMISHIFTSIZE + V8DBG_SMITAGMASK) -#define V8_HeapObjectTagMask V8DBG_HEAPOBJECTTAGMASK -#define V8_HeapObjectTag V8DBG_HEAPOBJECTTAG +#define V8_HeapObjectTagMask V8DBG_HEAPOBJECTTAGMASK +#define V8_HeapObjectTag V8DBG_HEAPOBJECTTAG -#define V8_IsNotStringMask V8DBG_ISNOTSTRINGMASK -#define V8_StringTag V8DBG_STRINGTAG +#define V8_IsNotStringMask V8DBG_ISNOTSTRINGMASK +#define V8_StringTag V8DBG_STRINGTAG -#define V8_StringEncodingMask V8DBG_STRINGENCODINGMASK -#define V8_AsciiStringTag V8DBG_ONEBYTESTRINGTAG +#define V8_StringEncodingMask V8DBG_STRINGENCODINGMASK +#define V8_AsciiStringTag V8DBG_ONEBYTESTRINGTAG #define V8_StringRepresentationMask V8DBG_STRINGREPRESENTATIONMASK -#define V8_SeqStringTag V8DBG_SEQSTRINGTAG -#define V8_ConsStringTag V8DBG_CONSSTRINGTAG -#define V8_ExternalStringTag V8DBG_EXTERNALSTRINGTAG +#define V8_SeqStringTag V8DBG_SEQSTRINGTAG +#define V8_ConsStringTag V8DBG_CONSSTRINGTAG +#define V8_ExternalStringTag V8DBG_EXTERNALSTRINGTAG /* Instance types */ -#define V8_IT_FIXEDARRAY V8DBG_TYPE_FIXEDARRAY__FIXED_ARRAY_TYPE -#define V8_IT_CODE V8DBG_TYPE_CODE__CODE_TYPE -#define V8_IT_SCRIPT V8DBG_TYPE_SCRIPT__SCRIPT_TYPE +#define V8_IT_FIXEDARRAY V8DBG_TYPE_FIXEDARRAY__FIXED_ARRAY_TYPE +#define V8_IT_CODE V8DBG_TYPE_CODE__CODE_TYPE +#define V8_IT_SCRIPT V8DBG_TYPE_SCRIPT__SCRIPT_TYPE /* Node-specific offsets */ -#define NODE_OFF_EXTSTR_DATA sizeof(void*) +#define NODE_OFF_EXTSTR_DATA sizeof(void*) /* * Not all versions of V8 have the offset for the "chars" array in the * SeqTwoByteString class, but it's the same as the one for SeqOneByteString. */ #ifndef V8DBG_CLASS_SEQTWOBYTESTRING__CHARS__CHAR -#define V8DBG_CLASS_SEQTWOBYTESTRING__CHARS__CHAR \ +#define V8DBG_CLASS_SEQTWOBYTESTRING__CHARS__CHAR \ V8DBG_CLASS_SEQONEBYTESTRING__CHARS__CHAR #endif /* Heap class->field offsets */ -#define V8_OFF_HEAP(off) ((off) - 1) +#define V8_OFF_HEAP(off) ((off)-1) -#define V8_OFF_FUNC_SHARED \ - V8_OFF_HEAP(V8DBG_CLASS_JSFUNCTION__SHARED__SHAREDFUNCTIONINFO) -#define V8_OFF_RAW_NAME \ - V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__NAME_OR_SCOPE_INFO__OBJECT) -#define V8_OFF_SHARED_IDENT \ - V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__FUNCTION_IDENTIFIER__OBJECT) -#define V8_OFF_SHARED_SCRIPT \ - V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__SCRIPT__OBJECT) -#define V8_OFF_SHARED_FUNIDENT \ - V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__FUNCTION_IDENTIFIER__OBJECT) -#define V8_OFF_SCRIPT_NAME \ - V8_OFF_HEAP(V8DBG_CLASS_SCRIPT__NAME__OBJECT) -#define V8_OFF_SCRIPT_LENDS \ - V8_OFF_HEAP(V8DBG_CLASS_SCRIPT__LINE_ENDS__OBJECT) -#define V8_OFF_STR_LENGTH \ - V8_OFF_HEAP(V8DBG_CLASS_STRING__LENGTH__SMI) -#define V8_OFF_STR_CHARS \ - V8_OFF_HEAP(V8DBG_CLASS_SEQONEBYTESTRING__CHARS__CHAR) -#define V8_OFF_CONSSTR_CAR \ - V8_OFF_HEAP(V8DBG_CLASS_CONSSTRING__FIRST__STRING) -#define V8_OFF_CONSSTR_CDR \ - V8_OFF_HEAP(V8DBG_CLASS_CONSSTRING__SECOND__STRING) -#define V8_OFF_EXTSTR_RSRC \ - V8_OFF_HEAP(V8DBG_CLASS_EXTERNALSTRING__RESOURCE__OBJECT) -#define V8_OFF_FA_SIZE \ - V8_OFF_HEAP(V8DBG_CLASS_FIXEDARRAYBASE__LENGTH__SMI) -#define V8_OFF_FA_DATA \ - V8_OFF_HEAP(V8DBG_CLASS_FIXEDARRAY__DATA__UINTPTR_T) -#define V8_OFF_HEAPOBJ_MAP \ - V8_OFF_HEAP(V8DBG_CLASS_HEAPOBJECT__MAP__MAP) -#define V8_OFF_MAP_ATTRS \ - V8_OFF_HEAP(V8DBG_CLASS_MAP__INSTANCE_TYPE__UINT16_T) -#define V8_OFF_TWOBYTESTR_CHARS \ - V8_OFF_HEAP(V8DBG_CLASS_SEQTWOBYTESTRING__CHARS__CHAR) +#define V8_OFF_FUNC_SHARED \ + V8_OFF_HEAP(V8DBG_CLASS_JSFUNCTION__SHARED__SHAREDFUNCTIONINFO) +#define V8_OFF_RAW_NAME \ + V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__NAME_OR_SCOPE_INFO__OBJECT) +#define V8_OFF_SHARED_IDENT \ + V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__FUNCTION_IDENTIFIER__OBJECT) +#define V8_OFF_SHARED_SCRIPT \ + V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__SCRIPT__OBJECT) +#define V8_OFF_SHARED_FUNIDENT \ + V8_OFF_HEAP(V8DBG_CLASS_SHAREDFUNCTIONINFO__FUNCTION_IDENTIFIER__OBJECT) +#define V8_OFF_SCRIPT_NAME V8_OFF_HEAP(V8DBG_CLASS_SCRIPT__NAME__OBJECT) +#define V8_OFF_SCRIPT_LENDS V8_OFF_HEAP(V8DBG_CLASS_SCRIPT__LINE_ENDS__OBJECT) +#define V8_OFF_STR_LENGTH V8_OFF_HEAP(V8DBG_CLASS_STRING__LENGTH__SMI) +#define V8_OFF_STR_CHARS V8_OFF_HEAP(V8DBG_CLASS_SEQONEBYTESTRING__CHARS__CHAR) +#define V8_OFF_CONSSTR_CAR V8_OFF_HEAP(V8DBG_CLASS_CONSSTRING__FIRST__STRING) +#define V8_OFF_CONSSTR_CDR V8_OFF_HEAP(V8DBG_CLASS_CONSSTRING__SECOND__STRING) +#define V8_OFF_EXTSTR_RSRC \ + V8_OFF_HEAP(V8DBG_CLASS_EXTERNALSTRING__RESOURCE__OBJECT) +#define V8_OFF_FA_SIZE V8_OFF_HEAP(V8DBG_CLASS_FIXEDARRAYBASE__LENGTH__SMI) +#define V8_OFF_FA_DATA V8_OFF_HEAP(V8DBG_CLASS_FIXEDARRAY__DATA__UINTPTR_T) +#define V8_OFF_HEAPOBJ_MAP V8_OFF_HEAP(V8DBG_CLASS_HEAPOBJECT__MAP__MAP) +#define V8_OFF_MAP_ATTRS V8_OFF_HEAP(V8DBG_CLASS_MAP__INSTANCE_TYPE__UINT16_T) +#define V8_OFF_TWOBYTESTR_CHARS \ + V8_OFF_HEAP(V8DBG_CLASS_SEQTWOBYTESTRING__CHARS__CHAR) -#endif /* SRC_V8ABBR_H_ */ +#endif /* SRC_V8ABBR_H_ */ diff --git a/test/addons-napi/6_object_wrap/binding.cc b/test/addons-napi/6_object_wrap/binding.cc index ec4a4f347afc88..99cf325d595c1a 100644 --- a/test/addons-napi/6_object_wrap/binding.cc +++ b/test/addons-napi/6_object_wrap/binding.cc @@ -1,5 +1,5 @@ -#include "myobject.h" #include "../common.h" +#include "myobject.h" napi_value Init(napi_env env, napi_value exports) { MyObject::Init(env, exports); diff --git a/test/addons-napi/6_object_wrap/myobject.cc b/test/addons-napi/6_object_wrap/myobject.cc index aca91877d3a2ae..d2da757285f1b8 100644 --- a/test/addons-napi/6_object_wrap/myobject.cc +++ b/test/addons-napi/6_object_wrap/myobject.cc @@ -6,29 +6,34 @@ napi_ref MyObject::constructor; MyObject::MyObject(double value) : value_(value), env_(nullptr), wrapper_(nullptr) {} -MyObject::~MyObject() { napi_delete_reference(env_, wrapper_); } +MyObject::~MyObject() { + napi_delete_reference(env_, wrapper_); +} -void MyObject::Destructor( - napi_env env, void* nativeObject, void* /*finalize_hint*/) { +void MyObject::Destructor(napi_env env, + void* nativeObject, + void* /*finalize_hint*/) { MyObject* obj = static_cast(nativeObject); delete obj; } void MyObject::Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { - { "value", nullptr, nullptr, GetValue, SetValue, 0, napi_default, 0 }, - DECLARE_NAPI_PROPERTY("plusOne", PlusOne), - DECLARE_NAPI_PROPERTY("multiply", Multiply), + {"value", nullptr, nullptr, GetValue, SetValue, 0, napi_default, 0}, + DECLARE_NAPI_PROPERTY("plusOne", PlusOne), + DECLARE_NAPI_PROPERTY("multiply", Multiply), }; napi_value cons; - NAPI_CALL_RETURN_VOID(env, napi_define_class( - env, "MyObject", -1, New, nullptr, 3, properties, &cons)); + NAPI_CALL_RETURN_VOID( + env, + napi_define_class( + env, "MyObject", -1, New, nullptr, 3, properties, &cons)); NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, cons, 1, &constructor)); - NAPI_CALL_RETURN_VOID(env, - napi_set_named_property(env, exports, "MyObject", cons)); + NAPI_CALL_RETURN_VOID( + env, napi_set_named_property(env, exports, "MyObject", cons)); } napi_value MyObject::New(napi_env env, napi_callback_info info) { @@ -55,12 +60,13 @@ napi_value MyObject::New(napi_env env, napi_callback_info info) { MyObject* obj = new MyObject(value); obj->env_ = env; - NAPI_CALL(env, napi_wrap(env, - _this, - obj, - MyObject::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); + NAPI_CALL(env, + napi_wrap(env, + _this, + obj, + MyObject::Destructor, + nullptr, // finalize_hint + &obj->wrapper_)); return _this; } @@ -81,7 +87,7 @@ napi_value MyObject::New(napi_env env, napi_callback_info info) { napi_value MyObject::GetValue(napi_env env, napi_callback_info info) { napi_value _this; NAPI_CALL(env, - napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); + napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); MyObject* obj; NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); @@ -109,7 +115,7 @@ napi_value MyObject::SetValue(napi_env env, napi_callback_info info) { napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) { napi_value _this; NAPI_CALL(env, - napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); + napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); MyObject* obj; NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); diff --git a/test/addons-napi/7_factory_wrap/binding.cc b/test/addons-napi/7_factory_wrap/binding.cc index d98132457875a1..3437501edc4673 100644 --- a/test/addons-napi/7_factory_wrap/binding.cc +++ b/test/addons-napi/7_factory_wrap/binding.cc @@ -1,5 +1,5 @@ -#include "myobject.h" #include "../common.h" +#include "myobject.h" napi_value CreateObject(napi_env env, napi_callback_info info) { size_t argc = 1; @@ -15,7 +15,8 @@ napi_value CreateObject(napi_env env, napi_callback_info info) { napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, MyObject::Init(env)); - NAPI_CALL(env, + NAPI_CALL( + env, // NOLINTNEXTLINE (readability/null_usage) napi_create_function(env, "exports", -1, CreateObject, NULL, &exports)); return exports; diff --git a/test/addons-napi/7_factory_wrap/myobject.cc b/test/addons-napi/7_factory_wrap/myobject.cc index 4e1d79c1febc17..95ad9eb96cf793 100644 --- a/test/addons-napi/7_factory_wrap/myobject.cc +++ b/test/addons-napi/7_factory_wrap/myobject.cc @@ -3,7 +3,9 @@ MyObject::MyObject() : env_(nullptr), wrapper_(nullptr) {} -MyObject::~MyObject() { napi_delete_reference(env_, wrapper_); } +MyObject::~MyObject() { + napi_delete_reference(env_, wrapper_); +} void MyObject::Destructor(napi_env env, void* nativeObject, @@ -17,7 +19,7 @@ napi_ref MyObject::constructor; napi_status MyObject::Init(napi_env env) { napi_status status; napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("plusOne", PlusOne), + DECLARE_NAPI_PROPERTY("plusOne", PlusOne), }; napi_value cons; @@ -49,12 +51,13 @@ napi_value MyObject::New(napi_env env, napi_callback_info info) { } obj->env_ = env; - NAPI_CALL(env, napi_wrap(env, - _this, - obj, - MyObject::Destructor, - nullptr, /* finalize_hint */ - &obj->wrapper_)); + NAPI_CALL(env, + napi_wrap(env, + _this, + obj, + MyObject::Destructor, + nullptr, /* finalize_hint */ + &obj->wrapper_)); return _this; } @@ -80,7 +83,7 @@ napi_status MyObject::NewInstance(napi_env env, napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) { napi_value _this; NAPI_CALL(env, - napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); + napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); MyObject* obj; NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast(&obj))); diff --git a/test/addons-napi/8_passing_wrapped/binding.cc b/test/addons-napi/8_passing_wrapped/binding.cc index 48e94f10ec4838..441c580333697a 100644 --- a/test/addons-napi/8_passing_wrapped/binding.cc +++ b/test/addons-napi/8_passing_wrapped/binding.cc @@ -1,5 +1,5 @@ -#include "myobject.h" #include "../common.h" +#include "myobject.h" extern size_t finalize_count; @@ -41,12 +41,13 @@ static napi_value Init(napi_env env, napi_value exports) { MyObject::Init(env); napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("createObject", CreateObject), - DECLARE_NAPI_PROPERTY("add", Add), - DECLARE_NAPI_PROPERTY("finalizeCount", FinalizeCount), + DECLARE_NAPI_PROPERTY("createObject", CreateObject), + DECLARE_NAPI_PROPERTY("add", Add), + DECLARE_NAPI_PROPERTY("finalizeCount", FinalizeCount), }; - NAPI_CALL(env, + NAPI_CALL( + env, napi_define_properties(env, exports, sizeof(desc) / sizeof(*desc), desc)); return exports; diff --git a/test/addons-napi/8_passing_wrapped/myobject.cc b/test/addons-napi/8_passing_wrapped/myobject.cc index 0c9ca90f52f8f3..b9499592c8d24a 100644 --- a/test/addons-napi/8_passing_wrapped/myobject.cc +++ b/test/addons-napi/8_passing_wrapped/myobject.cc @@ -10,8 +10,9 @@ MyObject::~MyObject() { napi_delete_reference(env_, wrapper_); } -void MyObject::Destructor( - napi_env env, void* nativeObject, void* /*finalize_hint*/) { +void MyObject::Destructor(napi_env env, + void* nativeObject, + void* /*finalize_hint*/) { MyObject* obj = static_cast(nativeObject); delete obj; } @@ -22,8 +23,8 @@ napi_status MyObject::Init(napi_env env) { napi_status status; napi_value cons; - status = napi_define_class( - env, "MyObject", -1, New, nullptr, 0, nullptr, &cons); + status = + napi_define_class(env, "MyObject", -1, New, nullptr, 0, nullptr, &cons); if (status != napi_ok) return status; status = napi_create_reference(env, cons, 1, &constructor); @@ -55,12 +56,13 @@ napi_value MyObject::New(napi_env env, napi_callback_info info) { // a reference to the wrapped object via the out-parameter, because this // ensures that we test the code path that deals with a reference that is // destroyed from its own finalizer. - NAPI_CALL(env, napi_wrap(env, - _this, - obj, - MyObject::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); + NAPI_CALL(env, + napi_wrap(env, + _this, + obj, + MyObject::Destructor, + nullptr, // finalize_hint + &obj->wrapper_)); return _this; } diff --git a/test/addons-napi/test_async/test_async.cc b/test/addons-napi/test_async/test_async.cc index a7ea0eb64c0537..6bc52c49ed03f9 100644 --- a/test/addons-napi/test_async/test_async.cc +++ b/test/addons-napi/test_async/test_async.cc @@ -1,5 +1,5 @@ -#include #include +#include #include "../common.h" #if defined _WIN32 @@ -56,13 +56,13 @@ void Complete(napi_env env, napi_status status, void* data) { NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, c->_output, &argv[1])); napi_value callback; NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, c->_callback, &callback)); + napi_get_reference_value(env, c->_callback, &callback)); napi_value global; NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); napi_value result; - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, global, callback, 2, argv, &result)); + NAPI_CALL_RETURN_VOID( + env, napi_call_function(env, global, callback, 2, argv, &result)); NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, c->_callback)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); @@ -74,34 +74,36 @@ napi_value Test(napi_env env, napi_callback_info info) { napi_value _this; napi_value resource_name; void* data; - NAPI_CALL(env, - napi_get_cb_info(env, info, &argc, argv, &_this, &data)); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); NAPI_ASSERT(env, argc >= 3, "Not enough arguments, expected 2."); napi_valuetype t; NAPI_CALL(env, napi_typeof(env, argv[0], &t)); - NAPI_ASSERT(env, t == napi_number, - "Wrong first argument, integer expected."); + NAPI_ASSERT(env, t == napi_number, "Wrong first argument, integer expected."); NAPI_CALL(env, napi_typeof(env, argv[1], &t)); - NAPI_ASSERT(env, t == napi_object, - "Wrong second argument, object expected."); + NAPI_ASSERT(env, t == napi_object, "Wrong second argument, object expected."); NAPI_CALL(env, napi_typeof(env, argv[2], &t)); - NAPI_ASSERT(env, t == napi_function, - "Wrong third argument, function expected."); + NAPI_ASSERT( + env, t == napi_function, "Wrong third argument, function expected."); the_carrier._output = 0; + NAPI_CALL(env, napi_get_value_int32(env, argv[0], &the_carrier._input)); NAPI_CALL(env, - napi_get_value_int32(env, argv[0], &the_carrier._input)); - NAPI_CALL(env, - napi_create_reference(env, argv[2], 1, &the_carrier._callback)); + napi_create_reference(env, argv[2], 1, &the_carrier._callback)); - NAPI_CALL(env, napi_create_string_utf8( - env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); - NAPI_CALL(env, napi_create_async_work(env, argv[1], resource_name, - Execute, Complete, &the_carrier, &the_carrier._request)); NAPI_CALL(env, - napi_queue_async_work(env, the_carrier._request)); + napi_create_string_utf8( + env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); + NAPI_CALL(env, + napi_create_async_work(env, + argv[1], + resource_name, + Execute, + Complete, + &the_carrier, + &the_carrier._request)); + NAPI_CALL(env, napi_queue_async_work(env, the_carrier._request)); return nullptr; } @@ -118,13 +120,13 @@ void CancelComplete(napi_env env, napi_status status, void* data) { // ok we got the status we expected so make the callback to // indicate the cancel succeeded. napi_value callback; - NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, c->_callback, &callback)); + NAPI_CALL_RETURN_VOID( + env, napi_get_reference_value(env, c->_callback, &callback)); napi_value global; NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); napi_value result; - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, global, callback, 0, nullptr, &result)); + NAPI_CALL_RETURN_VOID( + env, napi_call_function(env, global, callback, 0, nullptr, &result)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, c->_request)); @@ -146,15 +148,21 @@ napi_value TestCancel(napi_env env, napi_callback_info info) { napi_value resource_name; void* data; - NAPI_CALL(env, napi_create_string_utf8( - env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); + NAPI_CALL(env, + napi_create_string_utf8( + env, "TestResource", NAPI_AUTO_LENGTH, &resource_name)); // make sure the work we are going to cancel will not be // able to start by using all the threads in the pool for (int i = 1; i < MAX_CANCEL_THREADS; i++) { - NAPI_CALL(env, napi_create_async_work(env, nullptr, resource_name, - CancelExecute, BusyCancelComplete, - &async_carrier[i], &async_carrier[i]._request)); + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resource_name, + CancelExecute, + BusyCancelComplete, + &async_carrier[i], + &async_carrier[i]._request)); NAPI_CALL(env, napi_queue_async_work(env, async_carrier[i]._request)); } @@ -162,13 +170,17 @@ napi_value TestCancel(napi_env env, napi_callback_info info) { // cancel will fail if the work has already started, but // we have prevented it from starting by consuming all of the // workers above. + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); NAPI_CALL(env, - napi_get_cb_info(env, info, &argc, argv, &_this, &data)); - NAPI_CALL(env, napi_create_async_work(env, nullptr, resource_name, - CancelExecute, CancelComplete, - &async_carrier[0], &async_carrier[0]._request)); - NAPI_CALL(env, - napi_create_reference(env, argv[0], 1, &async_carrier[0]._callback)); + napi_create_async_work(env, + nullptr, + resource_name, + CancelExecute, + CancelComplete, + &async_carrier[0], + &async_carrier[0]._request)); + NAPI_CALL( + env, napi_create_reference(env, argv[0], 1, &async_carrier[0]._callback)); NAPI_CALL(env, napi_queue_async_work(env, async_carrier[0]._request)); NAPI_CALL(env, napi_cancel_async_work(env, async_carrier[0]._request)); return nullptr; @@ -177,53 +189,63 @@ napi_value TestCancel(napi_env env, napi_callback_info info) { struct { napi_ref ref; napi_async_work work; -} repeated_work_info = { nullptr, nullptr }; +} repeated_work_info = {nullptr, nullptr}; static void RepeatedWorkerThread(napi_env env, void* data) {} static void RepeatedWorkComplete(napi_env env, napi_status status, void* data) { napi_value cb, js_status; + NAPI_CALL_RETURN_VOID( + env, napi_get_reference_value(env, repeated_work_info.ref, &cb)); NAPI_CALL_RETURN_VOID(env, - napi_get_reference_value(env, repeated_work_info.ref, &cb)); - NAPI_CALL_RETURN_VOID(env, - napi_delete_async_work(env, repeated_work_info.work)); + napi_delete_async_work(env, repeated_work_info.work)); NAPI_CALL_RETURN_VOID(env, - napi_delete_reference(env, repeated_work_info.ref)); + napi_delete_reference(env, repeated_work_info.ref)); repeated_work_info.work = nullptr; repeated_work_info.ref = nullptr; NAPI_CALL_RETURN_VOID(env, - napi_create_uint32(env, (uint32_t)status, &js_status)); - NAPI_CALL_RETURN_VOID(env, - napi_call_function(env, cb, cb, 1, &js_status, nullptr)); + napi_create_uint32(env, (uint32_t)status, &js_status)); + NAPI_CALL_RETURN_VOID( + env, napi_call_function(env, cb, cb, 1, &js_status, nullptr)); } static napi_value DoRepeatedWork(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value cb, name; - NAPI_ASSERT(env, repeated_work_info.ref == nullptr, - "Reference left over from previous work"); - NAPI_ASSERT(env, repeated_work_info.work == nullptr, - "Work pointer left over from previous work"); + NAPI_ASSERT(env, + repeated_work_info.ref == nullptr, + "Reference left over from previous work"); + NAPI_ASSERT(env, + repeated_work_info.work == nullptr, + "Work pointer left over from previous work"); NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &cb, nullptr, nullptr)); NAPI_CALL(env, napi_create_reference(env, cb, 1, &repeated_work_info.ref)); - NAPI_CALL(env, + NAPI_CALL( + env, napi_create_string_utf8(env, "Repeated Work", NAPI_AUTO_LENGTH, &name)); NAPI_CALL(env, - napi_create_async_work(env, nullptr, name, RepeatedWorkerThread, - RepeatedWorkComplete, &repeated_work_info, &repeated_work_info.work)); + napi_create_async_work(env, + nullptr, + name, + RepeatedWorkerThread, + RepeatedWorkComplete, + &repeated_work_info, + &repeated_work_info.work)); NAPI_CALL(env, napi_queue_async_work(env, repeated_work_info.work)); return nullptr; } napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("Test", Test), - DECLARE_NAPI_PROPERTY("TestCancel", TestCancel), - DECLARE_NAPI_PROPERTY("DoRepeatedWork", DoRepeatedWork), + DECLARE_NAPI_PROPERTY("Test", Test), + DECLARE_NAPI_PROPERTY("TestCancel", TestCancel), + DECLARE_NAPI_PROPERTY("DoRepeatedWork", DoRepeatedWork), }; - NAPI_CALL(env, napi_define_properties( - env, exports, sizeof(properties) / sizeof(*properties), properties)); + NAPI_CALL( + env, + napi_define_properties( + env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } diff --git a/test/addons-napi/test_callback_scope/binding.cc b/test/addons-napi/test_callback_scope/binding.cc index e6631b6ac7bb52..f6d03eab051a7f 100644 --- a/test/addons-napi/test_callback_scope/binding.cc +++ b/test/addons-napi/test_callback_scope/binding.cc @@ -1,6 +1,6 @@ +#include "../common.h" #include "node_api.h" #include "uv.h" -#include "../common.h" namespace { @@ -12,37 +12,40 @@ struct async_context { double trigger_async_id; }; - napi_value RunInCallbackScope(napi_env env, napi_callback_info info) { size_t argc; napi_value args[4]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr)); - NAPI_ASSERT(env, argc == 4 , "Wrong number of arguments"); + NAPI_ASSERT(env, argc == 4, "Wrong number of arguments"); NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, - "Wrong type of arguments. Expects an object as first argument."); + NAPI_ASSERT(env, + valuetype == napi_object, + "Wrong type of arguments. Expects an object as first argument."); NAPI_CALL(env, napi_typeof(env, args[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, - "Wrong type of arguments. Expects a number as second argument."); + NAPI_ASSERT(env, + valuetype == napi_number, + "Wrong type of arguments. Expects a number as second argument."); NAPI_CALL(env, napi_typeof(env, args[2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, - "Wrong type of arguments. Expects a number as third argument."); + NAPI_ASSERT(env, + valuetype == napi_number, + "Wrong type of arguments. Expects a number as third argument."); NAPI_CALL(env, napi_typeof(env, args[3], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, - "Wrong type of arguments. Expects a function as third argument."); + NAPI_ASSERT(env, + valuetype == napi_function, + "Wrong type of arguments. Expects a function as third argument."); struct async_context context; NAPI_CALL(env, napi_get_value_double(env, args[1], &context.async_id)); NAPI_CALL(env, - napi_get_value_double(env, args[2], &context.trigger_async_id)); + napi_get_value_double(env, args[2], &context.trigger_async_id)); napi_callback_scope scope = nullptr; NAPI_CALL( @@ -76,8 +79,9 @@ static void Callback(uv_work_t* req, int ignored) { NAPI_CALL_RETURN_VOID(env, napi_open_handle_scope(env, &handle_scope)); napi_value resource_name; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8( - env, "test", NAPI_AUTO_LENGTH, &resource_name)); + NAPI_CALL_RETURN_VOID( + env, + napi_create_string_utf8(env, "test", NAPI_AUTO_LENGTH, &resource_name)); napi_async_context context; NAPI_CALL_RETURN_VOID(env, napi_async_init(env, nullptr, resource_name, &context)); @@ -89,10 +93,8 @@ static void Callback(uv_work_t* req, int ignored) { NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined_value)); napi_callback_scope scope = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_open_callback_scope(env, - resource_object, - context, - &scope)); + NAPI_CALL_RETURN_VOID( + env, napi_open_callback_scope(env, resource_object, context, &scope)); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, deferred, undefined_value)); @@ -113,22 +115,21 @@ napi_value TestResolveAsync(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_get_uv_event_loop(env, &loop)); uv_work_t* req = new uv_work_t(); - uv_queue_work(loop, - req, - [](uv_work_t*) {}, - Callback); + uv_queue_work(loop, req, [](uv_work_t*) {}, Callback); } return promise; } napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("runInCallbackScope", RunInCallbackScope), - DECLARE_NAPI_PROPERTY("testResolveAsync", TestResolveAsync) - }; + DECLARE_NAPI_PROPERTY("runInCallbackScope", RunInCallbackScope), + DECLARE_NAPI_PROPERTY("testResolveAsync", TestResolveAsync)}; - NAPI_CALL(env, napi_define_properties( - env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); + NAPI_CALL(env, + napi_define_properties(env, + exports, + sizeof(descriptors) / sizeof(*descriptors), + descriptors)); return exports; } diff --git a/test/addons-napi/test_cleanup_hook/binding.cc b/test/addons-napi/test_cleanup_hook/binding.cc index 66d53508c69f13..9588443179ae21 100644 --- a/test/addons-napi/test_cleanup_hook/binding.cc +++ b/test/addons-napi/test_cleanup_hook/binding.cc @@ -1,6 +1,6 @@ +#include "../common.h" #include "node_api.h" #include "uv.h" -#include "../common.h" namespace { diff --git a/test/addons-napi/test_make_callback_recurse/binding.cc b/test/addons-napi/test_make_callback_recurse/binding.cc index bfe9a457d237c8..c06946fa15f5ac 100644 --- a/test/addons-napi/test_make_callback_recurse/binding.cc +++ b/test/addons-napi/test_make_callback_recurse/binding.cc @@ -1,6 +1,6 @@ #include -#include "../common.h" #include +#include "../common.h" namespace { @@ -13,8 +13,13 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { napi_value recv = args[0]; napi_value func = args[1]; - napi_status status = napi_make_callback(env, nullptr /* async_context */, - recv, func, 0 /* argc */, nullptr /* argv */, nullptr /* result */); + napi_status status = napi_make_callback(env, + nullptr /* async_context */, + recv, + func, + 0 /* argc */, + nullptr /* argv */, + nullptr /* result */); bool isExceptionPending; NAPI_CALL(env, napi_is_exception_pending(env, &isExceptionPending)); @@ -23,10 +28,10 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { // other error napi_value pending_error; status = napi_get_and_clear_last_exception(env, &pending_error); - NAPI_CALL(env, - napi_throw_error((env), - nullptr, - "error when only pending exception expected")); + NAPI_CALL( + env, + napi_throw_error( + (env), nullptr, "error when only pending exception expected")); } return recv; @@ -34,9 +39,13 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { napi_value Init(napi_env env, napi_value exports) { napi_value fn; - NAPI_CALL(env, napi_create_function( - // NOLINTNEXTLINE (readability/null_usage) - env, NULL, NAPI_AUTO_LENGTH, MakeCallback, NULL, &fn)); + NAPI_CALL(env, + napi_create_function(env, + NULL, // NOLINT (readability/null_usage) + NAPI_AUTO_LENGTH, + MakeCallback, + NULL, // NOLINT (readability/null_usage) + &fn)); NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); return exports; } diff --git a/test/addons-napi/test_uv_loop/test_uv_loop.cc b/test/addons-napi/test_uv_loop/test_uv_loop.cc index 048e25af9ddfb3..6ebe8e25f93ce4 100644 --- a/test/addons-napi/test_uv_loop/test_uv_loop.cc +++ b/test/addons-napi/test_uv_loop/test_uv_loop.cc @@ -1,8 +1,8 @@ +#include #include #include -#include #include -#include +#include #include "../common.h" template @@ -11,12 +11,11 @@ void* SetImmediate(napi_env env, T&& cb) { uv_loop_t* loop = nullptr; uv_check_t* check = new uv_check_t; check->data = ptr; - NAPI_ASSERT(env, - napi_get_uv_event_loop(env, &loop) == napi_ok, - "can get event loop"); + NAPI_ASSERT( + env, napi_get_uv_event_loop(env, &loop) == napi_ok, "can get event loop"); uv_check_init(loop, check); uv_check_start(check, [](uv_check_t* check) { - std::unique_ptr ptr {static_cast(check->data)}; + std::unique_ptr ptr{static_cast(check->data)}; T cb = std::move(*ptr); uv_close(reinterpret_cast(check), [](uv_handle_t* handle) { delete reinterpret_cast(handle); @@ -43,18 +42,16 @@ napi_value SetImmediateBinding(napi_env env, napi_callback_info info) { napi_value argv[1]; napi_value _this; void* data; - NAPI_CALL(env, - napi_get_cb_info(env, info, &argc, argv, &_this, &data)); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); NAPI_ASSERT(env, argc >= 1, "Not enough arguments, expected 1."); napi_valuetype t; NAPI_CALL(env, napi_typeof(env, argv[0], &t)); - NAPI_ASSERT(env, t == napi_function, - "Wrong first argument, function expected."); + NAPI_ASSERT( + env, t == napi_function, "Wrong first argument, function expected."); napi_ref cbref; - NAPI_CALL(env, - napi_create_reference(env, argv[0], 1, &cbref)); + NAPI_CALL(env, napi_create_reference(env, argv[0], 1, &cbref)); SetImmediate(env, [=]() -> char* { napi_value undefined; @@ -64,8 +61,8 @@ napi_value SetImmediateBinding(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_get_undefined(env, &undefined)); NAPI_CALL(env, napi_get_reference_value(env, cbref, &callback)); NAPI_CALL(env, napi_delete_reference(env, cbref)); - NAPI_CALL(env, - napi_call_function(env, undefined, callback, 0, nullptr, nullptr)); + NAPI_CALL( + env, napi_call_function(env, undefined, callback, 0, nullptr, nullptr)); NAPI_CALL(env, napi_close_handle_scope(env, scope)); return &dummy; }); @@ -75,11 +72,12 @@ napi_value SetImmediateBinding(napi_env env, napi_callback_info info) { napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("SetImmediate", SetImmediateBinding) - }; + DECLARE_NAPI_PROPERTY("SetImmediate", SetImmediateBinding)}; - NAPI_CALL(env, napi_define_properties( - env, exports, sizeof(properties) / sizeof(*properties), properties)); + NAPI_CALL( + env, + napi_define_properties( + env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } diff --git a/test/addons/async-hello-world/binding.cc b/test/addons/async-hello-world/binding.cc index d4b74ed831f512..5378071999c4f3 100644 --- a/test/addons/async-hello-world/binding.cc +++ b/test/addons/async-hello-world/binding.cc @@ -1,6 +1,6 @@ #include -#include #include +#include #if defined _WIN32 #include @@ -8,7 +8,6 @@ #include #endif - struct async_req { uv_work_t req; int input; @@ -35,10 +34,8 @@ void AfterAsync(uv_work_t* r) { v8::Isolate* isolate = req->isolate; v8::HandleScope scope(isolate); - v8::Local argv[2] = { - v8::Null(isolate), - v8::Integer::New(isolate, req->output) - }; + v8::Local argv[2] = {v8::Null(isolate), + v8::Integer::New(isolate, req->output)}; v8::TryCatch try_catch(isolate); diff --git a/test/addons/async-hooks-id/binding.cc b/test/addons/async-hooks-id/binding.cc index e410563a8bb613..55419bcc402df0 100644 --- a/test/addons/async-hooks-id/binding.cc +++ b/test/addons/async-hooks-id/binding.cc @@ -9,12 +9,12 @@ using v8::Value; void GetExecutionAsyncId(const FunctionCallbackInfo& args) { args.GetReturnValue().Set( - node::AsyncHooksGetExecutionAsyncId(args.GetIsolate())); + node::AsyncHooksGetExecutionAsyncId(args.GetIsolate())); } void GetTriggerAsyncId(const FunctionCallbackInfo& args) { args.GetReturnValue().Set( - node::AsyncHooksGetTriggerAsyncId(args.GetIsolate())); + node::AsyncHooksGetTriggerAsyncId(args.GetIsolate())); } void Initialize(Local exports) { diff --git a/test/addons/async-hooks-promise/binding.cc b/test/addons/async-hooks-promise/binding.cc index 1571690edead24..053b2fcc6835ca 100644 --- a/test/addons/async-hooks-promise/binding.cc +++ b/test/addons/async-hooks-promise/binding.cc @@ -13,10 +13,11 @@ using v8::String; using v8::Value; static void ThrowError(Isolate* isolate, const char* err_msg) { - Local str = String::NewFromOneByte( - isolate, - reinterpret_cast(err_msg), - NewStringType::kNormal).ToLocalChecked(); + Local str = + String::NewFromOneByte(isolate, + reinterpret_cast(err_msg), + NewStringType::kNormal) + .ToLocalChecked(); isolate->ThrowException(str); } diff --git a/test/addons/async-resource/binding.cc b/test/addons/async-resource/binding.cc index ab33858c233dd0..106e9546ce5aea 100644 --- a/test/addons/async-resource/binding.cc +++ b/test/addons/async-resource/binding.cc @@ -23,9 +23,7 @@ class CustomAsyncResource : public AsyncResource { public: CustomAsyncResource(Isolate* isolate, Local resource) : AsyncResource(isolate, resource, "CustomAsyncResource") {} - ~CustomAsyncResource() { - custom_async_resource_destructor_calls++; - } + ~CustomAsyncResource() { custom_async_resource_destructor_calls++; } }; void CreateAsyncResource(const FunctionCallbackInfo& args) { @@ -33,14 +31,15 @@ void CreateAsyncResource(const FunctionCallbackInfo& args) { assert(args[0]->IsObject()); AsyncResource* r; if (args[1]->IsInt32()) { - r = new AsyncResource(isolate, args[0].As(), "foobär", + r = new AsyncResource(isolate, + args[0].As(), + "foobär", args[1].As()->Value()); } else { r = new AsyncResource(isolate, args[0].As(), "foobär"); } - args.GetReturnValue().Set( - External::New(isolate, static_cast(r))); + args.GetReturnValue().Set(External::New(isolate, static_cast(r))); } void DestroyAsyncResource(const FunctionCallbackInfo& args) { @@ -56,10 +55,10 @@ void CallViaFunction(const FunctionCallbackInfo& args) { Local name = String::NewFromUtf8(isolate, "methöd", v8::NewStringType::kNormal) - .ToLocalChecked(); - Local fn = - r->get_resource()->Get(isolate->GetCurrentContext(), name) - .ToLocalChecked(); + .ToLocalChecked(); + Local fn = r->get_resource() + ->Get(isolate->GetCurrentContext(), name) + .ToLocalChecked(); assert(fn->IsFunction()); Local arg = Integer::New(isolate, 42); @@ -74,7 +73,7 @@ void CallViaString(const FunctionCallbackInfo& args) { Local name = String::NewFromUtf8(isolate, "methöd", v8::NewStringType::kNormal) - .ToLocalChecked(); + .ToLocalChecked(); Local arg = Integer::New(isolate, 42); MaybeLocal ret = r->MakeCallback(name, 1, &arg); diff --git a/test/addons/at-exit/binding.cc b/test/addons/at-exit/binding.cc index 4dd9b0f304758f..8223834e11b5d2 100644 --- a/test/addons/at-exit/binding.cc +++ b/test/addons/at-exit/binding.cc @@ -1,6 +1,6 @@ #include -#include #include +#include #include using node::AtExit; diff --git a/test/addons/buffer-free-callback/binding.cc b/test/addons/buffer-free-callback/binding.cc index 4075fef50dcb0b..d4648e0635d80a 100644 --- a/test/addons/buffer-free-callback/binding.cc +++ b/test/addons/buffer-free-callback/binding.cc @@ -21,12 +21,10 @@ void Alloc(const v8::FunctionCallbackInfo& args) { uintptr_t static_offset = reinterpret_cast(buf) % alignment; char* aligned = buf + (alignment - static_offset) + offset; - args.GetReturnValue().Set(node::Buffer::New( - isolate, - aligned, - args[0]->IntegerValue(), - FreeCallback, - nullptr).ToLocalChecked()); + args.GetReturnValue().Set( + node::Buffer::New( + isolate, aligned, args[0]->IntegerValue(), FreeCallback, nullptr) + .ToLocalChecked()); } void Check(const v8::FunctionCallbackInfo& args) { diff --git a/test/addons/callback-scope/binding.cc b/test/addons/callback-scope/binding.cc index 94d5ec91d7f3a2..814670e42053f9 100644 --- a/test/addons/callback-scope/binding.cc +++ b/test/addons/callback-scope/binding.cc @@ -1,6 +1,6 @@ #include "node.h" -#include "v8.h" #include "uv.h" +#include "v8.h" #include #include @@ -16,10 +16,8 @@ void RunInCallbackScope(const v8::FunctionCallbackInfo& args) { assert(args[2]->IsNumber()); assert(args[3]->IsFunction()); - node::async_context asyncContext = { - args[1].As()->Value(), - args[2].As()->Value() - }; + node::async_context asyncContext = {args[1].As()->Value(), + args[2].As()->Value()}; node::CallbackScope scope(isolate, args[0].As(), asyncContext); v8::Local fn = args[3].As(); @@ -27,8 +25,7 @@ void RunInCallbackScope(const v8::FunctionCallbackInfo& args) { v8::MaybeLocal ret = fn->Call(isolate->GetCurrentContext(), args[0], 0, nullptr); - if (!ret.IsEmpty()) - args.GetReturnValue().Set(ret.ToLocalChecked()); + if (!ret.IsEmpty()) args.GetReturnValue().Set(ret.ToLocalChecked()); } static v8::Persistent persistent; @@ -36,13 +33,13 @@ static v8::Persistent persistent; static void Callback(uv_work_t* req, int ignored) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); - node::CallbackScope callback_scope(isolate, v8::Object::New(isolate), - node::async_context{0, 0}); + node::CallbackScope callback_scope( + isolate, v8::Object::New(isolate), node::async_context{0, 0}); v8::Local local = v8::Local::New(isolate, persistent); - local->Resolve(isolate->GetCurrentContext(), - v8::Undefined(isolate)).ToChecked(); + local->Resolve(isolate->GetCurrentContext(), v8::Undefined(isolate)) + .ToChecked(); delete req; } @@ -50,15 +47,14 @@ static void TestResolveAsync(const v8::FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); if (persistent.IsEmpty()) { - persistent.Reset(isolate, v8::Promise::Resolver::New( - isolate->GetCurrentContext()).ToLocalChecked()); + persistent.Reset(isolate, + v8::Promise::Resolver::New(isolate->GetCurrentContext()) + .ToLocalChecked()); uv_work_t* req = new uv_work_t; - uv_queue_work(node::GetCurrentEventLoop(isolate), - req, - [](uv_work_t*) {}, - Callback); + uv_queue_work( + node::GetCurrentEventLoop(isolate), req, [](uv_work_t*) {}, Callback); } v8::Local local = diff --git a/test/addons/errno-exception/binding.cc b/test/addons/errno-exception/binding.cc index bf83fb216824f0..a6390cab3a69fe 100644 --- a/test/addons/errno-exception/binding.cc +++ b/test/addons/errno-exception/binding.cc @@ -4,11 +4,8 @@ void Method(const v8::FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope scope(isolate); - args.GetReturnValue().Set(node::ErrnoException(isolate, - 10, - "syscall", - "some error msg", - "päth")); + args.GetReturnValue().Set( + node::ErrnoException(isolate, 10, "syscall", "some error msg", "päth")); } void init(v8::Local exports) { diff --git a/test/addons/heap-profiler/binding.cc b/test/addons/heap-profiler/binding.cc index 09feefa66902aa..a6a91c0c588eca 100644 --- a/test/addons/heap-profiler/binding.cc +++ b/test/addons/heap-profiler/binding.cc @@ -1,6 +1,6 @@ #include "node.h" -#include "v8.h" #include "v8-profiler.h" +#include "v8.h" namespace { diff --git a/test/addons/hello-world/binding.cc b/test/addons/hello-world/binding.cc index 341b58f9a640d8..8457a604d3aa21 100644 --- a/test/addons/hello-world/binding.cc +++ b/test/addons/hello-world/binding.cc @@ -8,10 +8,10 @@ void Method(const v8::FunctionCallbackInfo& args) { // Not using the full NODE_MODULE_INIT() macro here because we want to test the // addon loader's reaction to the FakeInit() entry point below. -extern "C" NODE_MODULE_EXPORT void -NODE_MODULE_INITIALIZER(v8::Local exports, - v8::Local module, - v8::Local context) { +extern "C" NODE_MODULE_EXPORT void NODE_MODULE_INITIALIZER( + v8::Local exports, + v8::Local module, + v8::Local context) { NODE_SET_METHOD(exports, "hello", Method); } @@ -19,8 +19,9 @@ static void FakeInit(v8::Local exports, v8::Local module, v8::Local context) { auto isolate = context->GetIsolate(); - auto exception = v8::Exception::Error(v8::String::NewFromUtf8(isolate, - "FakeInit should never run!", v8::NewStringType::kNormal) + auto exception = v8::Exception::Error( + v8::String::NewFromUtf8( + isolate, "FakeInit should never run!", v8::NewStringType::kNormal) .ToLocalChecked()); isolate->ThrowException(exception); } diff --git a/test/addons/make-callback-domain-warning/binding.cc b/test/addons/make-callback-domain-warning/binding.cc index d02c8f517661eb..ce49c841c9b99d 100644 --- a/test/addons/make-callback-domain-warning/binding.cc +++ b/test/addons/make-callback-domain-warning/binding.cc @@ -19,8 +19,8 @@ void MakeCallback(const FunctionCallbackInfo& args) { Local recv = args[0].As(); Local method = args[1].As(); - node::MakeCallback(isolate, recv, method, 0, nullptr, - node::async_context{0, 0}); + node::MakeCallback( + isolate, recv, method, 0, nullptr, node::async_context{0, 0}); } void Initialize(Local exports) { diff --git a/test/addons/make-callback-recurse/binding.cc b/test/addons/make-callback-recurse/binding.cc index 3fe3212ee3c8f5..db03b363131bac 100644 --- a/test/addons/make-callback-recurse/binding.cc +++ b/test/addons/make-callback-recurse/binding.cc @@ -19,8 +19,8 @@ void MakeCallback(const FunctionCallbackInfo& args) { Local recv = args[0].As(); Local method = args[1].As(); - node::MakeCallback(isolate, recv, method, 0, nullptr, - node::async_context{0, 0}); + node::MakeCallback( + isolate, recv, method, 0, nullptr, node::async_context{0, 0}); } void Initialize(Local exports) { diff --git a/test/addons/make-callback/binding.cc b/test/addons/make-callback/binding.cc index 86ed203b98d8d9..55e474674df6b5 100644 --- a/test/addons/make-callback/binding.cc +++ b/test/addons/make-callback/binding.cc @@ -18,14 +18,22 @@ void MakeCallback(const v8::FunctionCallbackInfo& args) { v8::Local result; if (args[1]->IsFunction()) { auto method = args[1].As(); - result = - node::MakeCallback(isolate, recv, method, argv.size(), argv.data(), - node::async_context{0, 0}).ToLocalChecked(); + result = node::MakeCallback(isolate, + recv, + method, + argv.size(), + argv.data(), + node::async_context{0, 0}) + .ToLocalChecked(); } else if (args[1]->IsString()) { auto method = args[1].As(); - result = - node::MakeCallback(isolate, recv, method, argv.size(), argv.data(), - node::async_context{0, 0}).ToLocalChecked(); + result = node::MakeCallback(isolate, + recv, + method, + argv.size(), + argv.data(), + node::async_context{0, 0}) + .ToLocalChecked(); } else { assert(0 && "unreachable"); } diff --git a/test/addons/node-module-version/binding.cc b/test/addons/node-module-version/binding.cc index 3baafe23a477df..6bc93f0808b94c 100644 --- a/test/addons/node-module-version/binding.cc +++ b/test/addons/node-module-version/binding.cc @@ -7,9 +7,8 @@ namespace { inline void Initialize(v8::Local exports, v8::Local module, - v8::Local context) { -} + v8::Local context) {} -} +} // namespace NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize) diff --git a/test/addons/null-buffer-neuter/binding.cc b/test/addons/null-buffer-neuter/binding.cc index 4c9dbf902589d9..614fd5b1ddc31a 100644 --- a/test/addons/null-buffer-neuter/binding.cc +++ b/test/addons/null-buffer-neuter/binding.cc @@ -17,12 +17,9 @@ void Run(const v8::FunctionCallbackInfo& args) { { v8::HandleScope scope(isolate); - v8::Local buf = node::Buffer::New( - isolate, - nullptr, - 0, - FreeCallback, - nullptr).ToLocalChecked(); + v8::Local buf = + node::Buffer::New(isolate, nullptr, 0, FreeCallback, nullptr) + .ToLocalChecked(); char* data = node::Buffer::Data(buf); assert(data == nullptr); diff --git a/test/addons/openssl-binding/binding.cc b/test/addons/openssl-binding/binding.cc index fa40b3346a7a39..80e243cae6cb1c 100644 --- a/test/addons/openssl-binding/binding.cc +++ b/test/addons/openssl-binding/binding.cc @@ -1,5 +1,5 @@ -#include #include +#include #include namespace { diff --git a/test/addons/openssl-client-cert-engine/testengine.cc b/test/addons/openssl-client-cert-engine/testengine.cc index 078695a0566691..90a065e7b55250 100644 --- a/test/addons/openssl-client-cert-engine/testengine.cc +++ b/test/addons/openssl-client-cert-engine/testengine.cc @@ -1,6 +1,6 @@ #include -#include #include +#include #include #include @@ -10,14 +10,14 @@ #include #ifndef ENGINE_CMD_BASE -# error did not get engine.h +#error did not get engine.h #endif -#define TEST_ENGINE_ID "testengine" -#define TEST_ENGINE_NAME "dummy test engine" +#define TEST_ENGINE_ID "testengine" +#define TEST_ENGINE_NAME "dummy test engine" -#define AGENT_KEY "test/fixtures/keys/agent1-key.pem" -#define AGENT_CERT "test/fixtures/keys/agent1-cert.pem" +#define AGENT_KEY "test/fixtures/keys/agent1-key.pem" +#define AGENT_CERT "test/fixtures/keys/agent1-cert.pem" namespace { @@ -39,13 +39,14 @@ std::string LoadFile(const char* filename) { std::istreambuf_iterator()); } - int EngineLoadSSLClientCert(ENGINE* engine, SSL* ssl, - STACK_OF(X509_NAME)* ca_dn, + STACK_OF(X509_NAME) * ca_dn, X509** ppcert, EVP_PKEY** ppkey, + // clang-format off STACK_OF(X509)** pother, + // clang-format on UI_METHOD* ui_method, void* callback_data) { if (ppcert != nullptr) { @@ -56,11 +57,11 @@ int EngineLoadSSLClientCert(ENGINE* engine, BIO* bio = BIO_new_mem_buf(cert.data(), cert.size()); *ppcert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); - BIO_vfree(bio); - if (*ppcert == nullptr) { - printf("Could not read certificate\n"); - return 0; - } + BIO_vfree(bio); + if (*ppcert == nullptr) { + printf("Could not read certificate\n"); + return 0; + } } if (ppkey != nullptr) { @@ -93,8 +94,8 @@ int bind_fn(ENGINE* engine, const char* id) { } extern "C" { - IMPLEMENT_DYNAMIC_CHECK_FN(); - IMPLEMENT_DYNAMIC_BIND_FN(bind_fn); +IMPLEMENT_DYNAMIC_CHECK_FN(); +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn); } } // anonymous namespace diff --git a/test/addons/parse-encoding/binding.cc b/test/addons/parse-encoding/binding.cc index 1501544153ad62..bd2c9e792bd7ee 100644 --- a/test/addons/parse-encoding/binding.cc +++ b/test/addons/parse-encoding/binding.cc @@ -3,29 +3,29 @@ namespace { -#define ENCODING_MAP(V) \ - V(ASCII) \ - V(BASE64) \ - V(BUFFER) \ - V(HEX) \ - V(LATIN1) \ - V(UCS2) \ - V(UTF8) \ +#define ENCODING_MAP(V) \ + V(ASCII) \ + V(BASE64) \ + V(BUFFER) \ + V(HEX) \ + V(LATIN1) \ + V(UCS2) \ + V(UTF8) static_assert(node::BINARY == node::LATIN1, "BINARY == LATIN1"); void ParseEncoding(const v8::FunctionCallbackInfo& args) { - const node::encoding encoding = - node::ParseEncoding(args.GetIsolate(), args[0], - static_cast(-1)); + const node::encoding encoding = node::ParseEncoding( + args.GetIsolate(), args[0], static_cast(-1)); const char* encoding_name = "UNKNOWN"; -#define V(name) if (encoding == node::name) encoding_name = #name; +#define V(name) \ + if (encoding == node::name) encoding_name = #name; ENCODING_MAP(V) #undef V auto encoding_string = - v8::String::NewFromUtf8(args.GetIsolate(), encoding_name, - v8::NewStringType::kNormal) - .ToLocalChecked(); + v8::String::NewFromUtf8( + args.GetIsolate(), encoding_name, v8::NewStringType::kNormal) + .ToLocalChecked(); args.GetReturnValue().Set(encoding_string); } diff --git a/test/addons/repl-domain-abort/binding.cc b/test/addons/repl-domain-abort/binding.cc index 3e716443540229..46b9aaab857a0e 100644 --- a/test/addons/repl-domain-abort/binding.cc +++ b/test/addons/repl-domain-abort/binding.cc @@ -25,21 +25,22 @@ using v8::Boolean; using v8::Function; using v8::FunctionCallbackInfo; -using v8::Local; using v8::Isolate; +using v8::Local; using v8::Object; using v8::Value; void Method(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); - Local params[] = { - Boolean::New(isolate, true), - Boolean::New(isolate, false) - }; - Local ret = - node::MakeCallback(isolate, isolate->GetCurrentContext()->Global(), - args[0].As(), 2, params, - node::async_context{0, 0}).ToLocalChecked(); + Local params[] = {Boolean::New(isolate, true), + Boolean::New(isolate, false)}; + Local ret = node::MakeCallback(isolate, + isolate->GetCurrentContext()->Global(), + args[0].As(), + 2, + params, + node::async_context{0, 0}) + .ToLocalChecked(); assert(ret->IsTrue()); } diff --git a/test/addons/stringbytes-external-exceed-max/binding.cc b/test/addons/stringbytes-external-exceed-max/binding.cc index 628a6b691376b3..28de0389e2c4cf 100644 --- a/test/addons/stringbytes-external-exceed-max/binding.cc +++ b/test/addons/stringbytes-external-exceed-max/binding.cc @@ -1,8 +1,8 @@ -#include #include +#include #include -void EnsureAllocation(const v8::FunctionCallbackInfo &args) { +void EnsureAllocation(const v8::FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); uintptr_t size = args[0]->IntegerValue(); v8::Local success; diff --git a/test/addons/uv-handle-leak/binding.cc b/test/addons/uv-handle-leak/binding.cc index c2e5f0bf27bf16..fb49d5afb63d31 100644 --- a/test/addons/uv-handle-leak/binding.cc +++ b/test/addons/uv-handle-leak/binding.cc @@ -1,6 +1,6 @@ #include -#include #include +#include using v8::Context; using v8::FunctionCallbackInfo; @@ -37,7 +37,7 @@ void LeakHandle(const FunctionCallbackInfo& args) { } uv_timer_init(loop, leaked_timer); - uv_timer_start(leaked_timer, [](uv_timer_t*){}, 1000, 1000); + uv_timer_start(leaked_timer, [](uv_timer_t*) {}, 1000, 1000); uv_unref(reinterpret_cast(leaked_timer)); } diff --git a/test/addons/zlib-binding/binding.cc b/test/addons/zlib-binding/binding.cc index a9a8c14306c486..5acc864dcad465 100644 --- a/test/addons/zlib-binding/binding.cc +++ b/test/addons/zlib-binding/binding.cc @@ -1,6 +1,6 @@ +#include #include #include -#include #include namespace { @@ -21,8 +21,12 @@ inline void CompressBytes(const v8::FunctionCallbackInfo& info) { stream.zalloc = nullptr; stream.zfree = nullptr; - int err = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, - -15, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); + int err = deflateInit2(&stream, + Z_DEFAULT_COMPRESSION, + Z_DEFLATED, + -15, + MAX_MEM_LEVEL, + Z_DEFAULT_STRATEGY); assert(err == Z_OK); stream.avail_in = byte_length; diff --git a/test/cctest/node_test_fixture.h b/test/cctest/node_test_fixture.h index 8cba5d99ba3c64..cc263bdcd388d4 100644 --- a/test/cctest/node_test_fixture.h +++ b/test/cctest/node_test_fixture.h @@ -2,19 +2,19 @@ #define TEST_CCTEST_NODE_TEST_FIXTURE_H_ #include +#include "env.h" #include "gtest/gtest.h" +#include "libplatform/libplatform.h" #include "node.h" -#include "node_platform.h" #include "node_internals.h" -#include "env.h" +#include "node_platform.h" #include "v8.h" -#include "libplatform/libplatform.h" struct Argv { public: Argv() : Argv({"node", "-p", "process.version"}) {} - Argv(const std::initializer_list &args) { + Argv(const std::initializer_list& args) { nr_args_ = args.size(); int total_len = 0; for (auto it = args.begin(); it != args.end(); ++it) { @@ -40,21 +40,18 @@ struct Argv { free(argv_); } - int nr_args() const { - return nr_args_; - } + int nr_args() const { return nr_args_; } - char** operator*() const { - return argv_; - } + char** operator*() const { return argv_; } private: char** argv_; int nr_args_; }; -using ArrayBufferUniquePtr = std::unique_ptr; +using ArrayBufferUniquePtr = + std::unique_ptr; using TracingControllerUniquePtr = std::unique_ptr; using NodePlatformUniquePtr = std::unique_ptr; @@ -98,7 +95,6 @@ class NodeTestFixture : public ::testing::Test { } }; - class EnvironmentTestFixture : public NodeTestFixture { public: class Env { @@ -109,14 +105,11 @@ class EnvironmentTestFixture : public NodeTestFixture { CHECK(!context_.IsEmpty()); context_->Enter(); - isolate_data_ = node::CreateIsolateData(isolate, - &NodeTestFixture::current_loop, - platform.get()); + isolate_data_ = node::CreateIsolateData( + isolate, &NodeTestFixture::current_loop, platform.get()); CHECK_NE(nullptr, isolate_data_); - environment_ = node::CreateEnvironment(isolate_data_, - context_, - 1, *argv, - argv.nr_args(), *argv); + environment_ = node::CreateEnvironment( + isolate_data_, context_, 1, *argv, argv.nr_args(), *argv); CHECK_NE(nullptr, environment_); } @@ -126,13 +119,9 @@ class EnvironmentTestFixture : public NodeTestFixture { context_->Exit(); } - node::Environment* operator*() const { - return environment_; - } + node::Environment* operator*() const { return environment_; } - v8::Local context() const { - return context_; - } + v8::Local context() const { return context_; } private: v8::Local context_; diff --git a/test/cctest/test_aliased_buffer.cc b/test/cctest/test_aliased_buffer.cc index bfbf7294db612b..f717bf43fc6dee 100644 --- a/test/cctest/test_aliased_buffer.cc +++ b/test/cctest/test_aliased_buffer.cc @@ -1,7 +1,7 @@ -#include "v8.h" #include "aliased_buffer.h" #include "node_test_fixture.h" +#include "v8.h" using node::AliasedBuffer; @@ -47,9 +47,8 @@ void ReadAndValidate(v8::Isolate* isolate, // validate size of JS Buffer EXPECT_TRUE(aliasedBuffer->GetJSArray()->Length() == oracle.size()); - EXPECT_TRUE( - aliasedBuffer->GetJSArray()->ByteLength() == - (oracle.size() * sizeof(NativeT))); + EXPECT_TRUE(aliasedBuffer->GetJSArray()->ByteLength() == + (oracle.size() * sizeof(NativeT))); // validate operator * and GetBuffer are the same EXPECT_TRUE(aliasedBuffer->GetNativeBuffer() == *(*aliasedBuffer)); @@ -92,15 +91,16 @@ void ReadWriteTest(v8::Isolate* isolate) { ReadAndValidate(isolate, context, &ab, oracle); } -template < - class NativeT_A, class V8T_A, - class NativeT_B, class V8T_B, - class NativeT_C, class V8T_C> -void SharedBufferTest( - v8::Isolate* isolate, - size_t count_A, - size_t count_B, - size_t count_C) { +template +void SharedBufferTest(v8::Isolate* isolate, + size_t count_A, + size_t count_B, + size_t count_C) { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); @@ -112,8 +112,7 @@ void SharedBufferTest( AliasedBuffer rootBuffer( isolate, sizeInBytes_A + sizeInBytes_B + sizeInBytes_C); - AliasedBuffer ab_A( - isolate, 0, count_A, rootBuffer); + AliasedBuffer ab_A(isolate, 0, count_A, rootBuffer); AliasedBuffer ab_B( isolate, sizeInBytes_A, count_B, rootBuffer); AliasedBuffer ab_C( @@ -176,31 +175,39 @@ TEST_F(AliasBufferTest, Float64Array) { } TEST_F(AliasBufferTest, SharedArrayBuffer1) { - SharedBufferTest< - uint32_t, v8::Uint32Array, - double, v8::Float64Array, - int8_t, v8::Int8Array>(isolate_, 100, 80, 8); + SharedBufferTest(isolate_, 100, 80, 8); } TEST_F(AliasBufferTest, SharedArrayBuffer2) { - SharedBufferTest< - double, v8::Float64Array, - int8_t, v8::Int8Array, - double, v8::Float64Array>(isolate_, 100, 8, 8); + SharedBufferTest(isolate_, 100, 8, 8); } TEST_F(AliasBufferTest, SharedArrayBuffer3) { - SharedBufferTest< - int8_t, v8::Int8Array, - int8_t, v8::Int8Array, - double, v8::Float64Array>(isolate_, 1, 7, 8); + SharedBufferTest(isolate_, 1, 7, 8); } TEST_F(AliasBufferTest, SharedArrayBuffer4) { - SharedBufferTest< - int8_t, v8::Int8Array, - int8_t, v8::Int8Array, - int32_t, v8::Int32Array>(isolate_, 1, 3, 1); + SharedBufferTest(isolate_, 1, 3, 1); } TEST_F(AliasBufferTest, OperatorOverloads) { diff --git a/test/cctest/test_base64.cc b/test/cctest/test_base64.cc index fbdb969b4cbe46..5414ff177ac917 100644 --- a/test/cctest/test_base64.cc +++ b/test/cctest/test_base64.cc @@ -5,8 +5,8 @@ #include "gtest/gtest.h" -using node::base64_encode; using node::base64_decode; +using node::base64_encode; TEST(Base64Test, Encode) { auto test = [](const char* string, const char* base64_string) { @@ -93,7 +93,8 @@ TEST(Base64Test, Decode) { "biByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xv" "cmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNh" "dCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lh" - "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg==", text); + "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg==", + text); test("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2Npbmcg" "ZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0" @@ -103,7 +104,8 @@ TEST(Base64Test, Decode) { "biByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xv" "cmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNh" "dCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lh" - "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg", text); + "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg", + text); test("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2Npbmcg\n" "ZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0\n" @@ -113,7 +115,8 @@ TEST(Base64Test, Decode) { "biByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xv\n" "cmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNh\n" "dCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lh\n" - "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg==", text); + "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg==", + text); test("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2Npbmcg\n" "ZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0\n" @@ -123,5 +126,6 @@ TEST(Base64Test, Decode) { "biByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xv\n" "cmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNh\n" "dCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lh\n" - "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg", text); + "IGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg", + text); } diff --git a/test/cctest/test_environment.cc b/test/cctest/test_environment.cc index 07170ac267adea..edaff8a5898570 100644 --- a/test/cctest/test_environment.cc +++ b/test/cctest/test_environment.cc @@ -1,5 +1,5 @@ -#include "node_internals.h" #include "libplatform/libplatform.h" +#include "node_internals.h" #include #include "gtest/gtest.h" @@ -26,7 +26,7 @@ class EnvironmentTest : public EnvironmentTestFixture { TEST_F(EnvironmentTest, AtExitWithEnvironment) { const v8::HandleScope handle_scope(isolate_); const Argv argv; - Env env {handle_scope, argv}; + Env env{handle_scope, argv}; AtExit(*env, at_exit_callback1); RunAtExit(*env); @@ -36,7 +36,7 @@ TEST_F(EnvironmentTest, AtExitWithEnvironment) { TEST_F(EnvironmentTest, AtExitWithoutEnvironment) { const v8::HandleScope handle_scope(isolate_); const Argv argv; - Env env {handle_scope, argv}; + Env env{handle_scope, argv}; AtExit(at_exit_callback1); // No Environment is passed to AtExit. RunAtExit(*env); @@ -46,7 +46,7 @@ TEST_F(EnvironmentTest, AtExitWithoutEnvironment) { TEST_F(EnvironmentTest, AtExitWithArgument) { const v8::HandleScope handle_scope(isolate_); const Argv argv; - Env env {handle_scope, argv}; + Env env{handle_scope, argv}; std::string arg{"some args"}; AtExit(*env, at_exit_callback1, static_cast(&arg)); @@ -57,8 +57,8 @@ TEST_F(EnvironmentTest, AtExitWithArgument) { TEST_F(EnvironmentTest, MultipleEnvironmentsPerIsolate) { const v8::HandleScope handle_scope(isolate_); const Argv argv; - Env env1 {handle_scope, argv}; - Env env2 {handle_scope, argv}; + Env env1{handle_scope, argv}; + Env env2{handle_scope, argv}; AtExit(*env1, at_exit_callback1); AtExit(*env2, at_exit_callback2); diff --git a/test/cctest/test_inspector_socket.cc b/test/cctest/test_inspector_socket.cc index b96489db1f49d3..3d10e49d584875 100644 --- a/test/cctest/test_inspector_socket.cc +++ b/test/cctest/test_inspector_socket.cc @@ -1,5 +1,5 @@ -#include "inspector_socket.h" #include "gtest/gtest.h" +#include "inspector_socket.h" #include @@ -38,7 +38,7 @@ class Timeout { static void mark_done(uv_handle_t* timer) { Timeout* t = node::ContainerOf(&Timeout::timer_, - reinterpret_cast(timer)); + reinterpret_cast(timer)); t->done_ = true; } @@ -98,14 +98,16 @@ static void assert_is_delegate(TestInspectorDelegate* d) { class TestInspectorDelegate : public InspectorSocket::Delegate { public: - using delegate_fn = void(*)(inspector_handshake_event, const std::string&, - bool* should_continue); + using delegate_fn = void (*)(inspector_handshake_event, + const std::string&, + bool* should_continue); - TestInspectorDelegate() : inspector_ready(false), - last_event(kInspectorHandshakeNoEvents), - handshake_events(0), - handshake_delegate_(stop_if_stop_path), - fail_on_ws_frame_(false) { } + TestInspectorDelegate() + : inspector_ready(false), + last_event(kInspectorHandshakeNoEvents), + handshake_events(0), + handshake_delegate_(stop_if_stop_path), + fail_on_ws_frame_(false) {} ~TestInspectorDelegate() { assert_is_delegate(this); @@ -116,7 +118,8 @@ class TestInspectorDelegate : public InspectorSocket::Delegate { process(kInspectorHandshakeHttpGet, path); } - void OnSocketUpgrade(const std::string& host, const std::string& path, + void OnSocketUpgrade(const std::string& host, + const std::string& path, const std::string& ws_key) override { ws_key_ = ws_key; process(kInspectorHandshakeUpgraded, path); @@ -127,17 +130,13 @@ class TestInspectorDelegate : public InspectorSocket::Delegate { frames.push(buffer); } - void SetDelegate(delegate_fn d) { - handshake_delegate_ = d; - } + void SetDelegate(delegate_fn d) { handshake_delegate_ = d; } void SetInspector(InspectorSocket::Pointer inspector) { socket_ = std::move(inspector); } - void Write(const char* buf, size_t len) { - socket_->Write(buf, len); - } + void Write(const char* buf, size_t len) { socket_->Write(buf, len); } void ExpectReadError() { SPIN_WHILE(frames.empty() || !frames.back().empty()); @@ -160,17 +159,11 @@ class TestInspectorDelegate : public InspectorSocket::Delegate { } } - void FailOnWsFrame() { - fail_on_ws_frame_ = true; - } + void FailOnWsFrame() { fail_on_ws_frame_ = true; } - void WaitForDispose() { - SPIN_WHILE(delegate != nullptr); - } + void WaitForDispose() { SPIN_WHILE(delegate != nullptr); } - void Close() { - socket_.reset(); - } + void Close() { socket_.reset(); } bool inspector_ready; std::string last_path; // NOLINT(runtime/string) @@ -180,7 +173,8 @@ class TestInspectorDelegate : public InspectorSocket::Delegate { private: static void stop_if_stop_path(enum inspector_handshake_event state, - const std::string& path, bool* cont) { + const std::string& path, + bool* cont) { *cont = path.empty() || path != "/close"; } @@ -224,8 +218,7 @@ void TestInspectorDelegate::process(inspector_handshake_event event, bool should_continue = true; handshake_delegate_(event, path, &should_continue); if (should_continue) { - if (inspector_ready) - socket_->AcceptUpgrade(ws_key_); + if (inspector_ready) socket_->AcceptUpgrade(ws_key_); } else { socket_->CancelHandshake(); } @@ -235,13 +228,14 @@ static void on_new_connection(uv_stream_t* server, int status) { GTEST_ASSERT_EQ(0, status); connected = true; delegate = new TestInspectorDelegate(); - delegate->SetInspector( - InspectorSocket::Accept(server, - InspectorSocket::DelegatePointer(delegate))); + delegate->SetInspector(InspectorSocket::Accept( + server, InspectorSocket::DelegatePointer(delegate))); GTEST_ASSERT_NE(nullptr, delegate); } -void write_done(uv_write_t* req, int status) { req->data = nullptr; } +void write_done(uv_write_t* req, int status) { + req->data = nullptr; +} static void do_write(const char* data, int len) { uv_write_t req; @@ -251,13 +245,18 @@ static void do_write(const char* data, int len) { buf[0].base = const_cast(data); buf[0].len = len; GTEST_ASSERT_EQ(0, - uv_write(&req, reinterpret_cast(&client_socket), - buf, 1, write_done)); + uv_write(&req, + reinterpret_cast(&client_socket), + buf, + 1, + write_done)); SPIN_WHILE(req.data); } -static void check_data_cb(read_expects* expectation, ssize_t nread, - const uv_buf_t* buf, bool* retval) { +static void check_data_cb(read_expects* expectation, + ssize_t nread, + const uv_buf_t* buf, + bool* retval) { *retval = false; EXPECT_TRUE(nread >= 0 && nread != UV_EOF); ssize_t i; @@ -267,7 +266,8 @@ static void check_data_cb(read_expects* expectation, ssize_t nread, c = expectation->expected[expectation->pos++]; actual = buf->base[i]; if (c != actual) { - fprintf(stderr, "Unexpected character at position %zd\n", + fprintf(stderr, + "Unexpected character at position %zd\n", expectation->pos - 1); GTEST_ASSERT_EQ(c, actual); } @@ -280,7 +280,8 @@ static void check_data_cb(read_expects* expectation, ssize_t nread, } } -static void check_data_cb(uv_stream_t* stream, ssize_t nread, +static void check_data_cb(uv_stream_t* stream, + ssize_t nread, const uv_buf_t* buf) { bool retval = false; read_expects* expects = static_cast(stream->data); @@ -302,7 +303,8 @@ static read_expects prepare_expects(const char* data, size_t len) { return expectation; } -static void fail_callback(uv_stream_t* stream, ssize_t nread, +static void fail_callback(uv_stream_t* stream, + ssize_t nread, const uv_buf_t* buf) { if (nread < 0) { fprintf(stderr, "IO error: %s\n", uv_strerror(nread)); @@ -316,8 +318,7 @@ static void expect_nothing_on_client() { uv_stream_t* stream = reinterpret_cast(&client_socket); int err = uv_read_start(stream, buffer_alloc_cb, fail_callback); GTEST_ASSERT_EQ(0, err); - for (int i = 0; i < MAX_LOOP_ITERATIONS; i++) - uv_run(&loop, UV_RUN_NOWAIT); + for (int i = 0; i < MAX_LOOP_ITERATIONS; i++) uv_run(&loop, UV_RUN_NOWAIT); uv_read_stop(stream); } @@ -325,7 +326,8 @@ static void expect_on_client(const char* data, size_t len) { read_expects expectation = prepare_expects(data, len); client_socket.data = ℰ uv_read_start(reinterpret_cast(&client_socket), - buffer_alloc_cb, check_data_cb); + buffer_alloc_cb, + check_data_cb); SPIN_WHILE(!expectation.read_expected); } @@ -363,13 +365,17 @@ class InspectorSocketTest : public ::testing::Test { uv_tcp_init(&loop, &client_socket); GTEST_ASSERT_EQ(0, uv_ip4_addr("127.0.0.1", PORT, &addr)); uv_tcp_bind(&server, reinterpret_cast(&addr), 0); - GTEST_ASSERT_EQ(0, uv_listen(reinterpret_cast(&server), - 1, on_new_connection)); + GTEST_ASSERT_EQ( + 0, + uv_listen( + reinterpret_cast(&server), 1, on_new_connection)); uv_connect_t connect; connect.data = nullptr; - GTEST_ASSERT_EQ(0, uv_tcp_connect(&connect, &client_socket, - reinterpret_cast(&addr), - on_connection)); + GTEST_ASSERT_EQ(0, + uv_tcp_connect(&connect, + &client_socket, + reinterpret_cast(&addr), + on_connection)); uv_tcp_nodelay(&client_socket, 1); // The buffering messes up the test SPIN_WHILE(!connect.data || !connected); really_close(reinterpret_cast(&server)); @@ -399,20 +405,28 @@ TEST_F(InspectorSocketTest, ReadsAndWritesInspectorMessage) { delegate->Write(SERVER_MESSAGE, sizeof(SERVER_MESSAGE) - 1); expect_on_client(CLIENT_FRAME, sizeof(CLIENT_FRAME)); - const char SERVER_FRAME[] = {'\x81', '\x84', '\x7F', '\xC2', '\x66', - '\x31', '\x4E', '\xF0', '\x55', '\x05'}; + const char SERVER_FRAME[] = {'\x81', + '\x84', + '\x7F', + '\xC2', + '\x66', + '\x31', + '\x4E', + '\xF0', + '\x55', + '\x05'}; const char CLIENT_MESSAGE[] = "1234"; do_write(SERVER_FRAME, sizeof(SERVER_FRAME)); delegate->ExpectData(CLIENT_MESSAGE, sizeof(CLIENT_MESSAGE) - 1); // 3. Close - const char CLIENT_CLOSE_FRAME[] = {'\x88', '\x80', '\x2D', - '\x0E', '\x1E', '\xFA'}; + const char CLIENT_CLOSE_FRAME[] = { + '\x88', '\x80', '\x2D', '\x0E', '\x1E', '\xFA'}; const char SERVER_CLOSE_FRAME[] = {'\x88', '\x00'}; do_write(CLIENT_CLOSE_FRAME, sizeof(CLIENT_CLOSE_FRAME)); expect_on_client(SERVER_CLOSE_FRAME, sizeof(SERVER_CLOSE_FRAME)); - GTEST_ASSERT_EQ(0, uv_is_active( - reinterpret_cast(&client_socket))); + GTEST_ASSERT_EQ(0, + uv_is_active(reinterpret_cast(&client_socket))); } TEST_F(InspectorSocketTest, BufferEdgeCases) { @@ -535,15 +549,23 @@ TEST_F(InspectorSocketTest, CanStopReadingFromInspector) { ASSERT_TRUE(delegate->inspector_ready); // 2. Brief exchange - const char SERVER_FRAME[] = {'\x81', '\x84', '\x7F', '\xC2', '\x66', - '\x31', '\x4E', '\xF0', '\x55', '\x05'}; + const char SERVER_FRAME[] = {'\x81', + '\x84', + '\x7F', + '\xC2', + '\x66', + '\x31', + '\x4E', + '\xF0', + '\x55', + '\x05'}; const char CLIENT_MESSAGE[] = "1234"; do_write(SERVER_FRAME, sizeof(SERVER_FRAME)); delegate->ExpectData(CLIENT_MESSAGE, sizeof(CLIENT_MESSAGE) - 1); do_write(SERVER_FRAME, sizeof(SERVER_FRAME)); - GTEST_ASSERT_EQ(uv_is_active( - reinterpret_cast(&client_socket)), 0); + GTEST_ASSERT_EQ(uv_is_active(reinterpret_cast(&client_socket)), + 0); } TEST_F(InspectorSocketTest, CloseDoesNotNotifyReadCallback) { @@ -553,8 +575,8 @@ TEST_F(InspectorSocketTest, CloseDoesNotNotifyReadCallback) { delegate->Close(); char CLOSE_FRAME[] = {'\x88', '\x00'}; expect_on_client(CLOSE_FRAME, sizeof(CLOSE_FRAME)); - const char CLIENT_CLOSE_FRAME[] = {'\x88', '\x80', '\x2D', - '\x0E', '\x1E', '\xFA'}; + const char CLIENT_CLOSE_FRAME[] = { + '\x88', '\x80', '\x2D', '\x0E', '\x1E', '\xFA'}; delegate->FailOnWsFrame(); do_write(CLIENT_CLOSE_FRAME, sizeof(CLIENT_CLOSE_FRAME)); SPIN_WHILE(delegate != nullptr); @@ -566,8 +588,8 @@ TEST_F(InspectorSocketTest, CloseWorksWithoutReadEnabled) { delegate->Close(); char CLOSE_FRAME[] = {'\x88', '\x00'}; expect_on_client(CLOSE_FRAME, sizeof(CLOSE_FRAME)); - const char CLIENT_CLOSE_FRAME[] = {'\x88', '\x80', '\x2D', - '\x0E', '\x1E', '\xFA'}; + const char CLIENT_CLOSE_FRAME[] = { + '\x88', '\x80', '\x2D', '\x0E', '\x1E', '\xFA'}; do_write(CLIENT_CLOSE_FRAME, sizeof(CLIENT_CLOSE_FRAME)); } @@ -588,27 +610,28 @@ static const char TEST_SUCCESS[] = "Test Success\n\n"; static int ReportsHttpGet_eventsCount = 0; static void ReportsHttpGet_handshake(enum inspector_handshake_event state, - const std::string& path, bool* cont) { + const std::string& path, + bool* cont) { *cont = true; enum inspector_handshake_event expected_state = kInspectorHandshakeHttpGet; std::string expected_path; switch (delegate->handshake_events) { - case 1: - expected_path = "/some/path"; - break; - case 2: - expected_path = "/respond/withtext"; - delegate->Write(TEST_SUCCESS, sizeof(TEST_SUCCESS) - 1); - break; - case 3: - expected_path = "/some/path2"; - break; - case 4: - expected_path = "/close"; - *cont = false; - break; - default: - ASSERT_TRUE(false); + case 1: + expected_path = "/some/path"; + break; + case 2: + expected_path = "/respond/withtext"; + delegate->Write(TEST_SUCCESS, sizeof(TEST_SUCCESS) - 1); + break; + case 3: + expected_path = "/some/path2"; + break; + case 4: + expected_path = "/close"; + *cont = false; + break; + default: + ASSERT_TRUE(false); } EXPECT_EQ(expected_state, state); EXPECT_EQ(expected_path, path); @@ -646,17 +669,16 @@ TEST_F(InspectorSocketTest, ReportsHttpGet) { static int HandshakeCanBeCanceled_eventCount = 0; -static -void HandshakeCanBeCanceled_handshake(enum inspector_handshake_event state, - const std::string& path, bool* cont) { +static void HandshakeCanBeCanceled_handshake( + enum inspector_handshake_event state, const std::string& path, bool* cont) { switch (delegate->handshake_events - 1) { - case 0: - EXPECT_EQ(kInspectorHandshakeUpgraded, state); - EXPECT_EQ("/ws/path", path); - break; - default: - EXPECT_TRUE(false); - break; + case 0: + EXPECT_EQ(kInspectorHandshakeUpgraded, state); + EXPECT_EQ("/ws/path", path); + break; + default: + EXPECT_TRUE(false); + break; } *cont = false; HandshakeCanBeCanceled_eventCount = delegate->handshake_events; @@ -673,21 +695,22 @@ TEST_F(InspectorSocketTest, HandshakeCanBeCanceled) { } static void GetThenHandshake_handshake(enum inspector_handshake_event state, - const std::string& path, bool* cont) { + const std::string& path, + bool* cont) { *cont = true; std::string expected_path = "/ws/path"; switch (delegate->handshake_events - 1) { - case 0: - EXPECT_EQ(kInspectorHandshakeHttpGet, state); - expected_path = "/respond/withtext"; - delegate->Write(TEST_SUCCESS, sizeof(TEST_SUCCESS) - 1); - break; - case 1: - EXPECT_EQ(kInspectorHandshakeUpgraded, state); - break; - default: - EXPECT_TRUE(false); - break; + case 0: + EXPECT_EQ(kInspectorHandshakeHttpGet, state); + expected_path = "/respond/withtext"; + delegate->Write(TEST_SUCCESS, sizeof(TEST_SUCCESS) - 1); + break; + case 1: + EXPECT_EQ(kInspectorHandshakeUpgraded, state); + break; + default: + EXPECT_TRUE(false); + break; } EXPECT_EQ(expected_path, path); } @@ -744,7 +767,8 @@ static void fill_message(std::string* buffer) { } static void mask_message(const std::string& message, - char* buffer, const char mask[]) { + char* buffer, + const char mask[]) { const size_t mask_len = 4; for (size_t i = 0; i < message.size(); i += 1) { buffer[i] = message[i] ^ mask[i % mask_len]; @@ -763,10 +787,16 @@ TEST_F(InspectorSocketTest, Send1Mb) { fill_message(&message); // 1000000 is 0xF4240 hex - const char EXPECTED_FRAME_HEADER[] = { - '\x81', '\x7f', '\x00', '\x00', '\x00', '\x00', '\x00', '\x0F', - '\x42', '\x40' - }; + const char EXPECTED_FRAME_HEADER[] = {'\x81', + '\x7f', + '\x00', + '\x00', + '\x00', + '\x00', + '\x00', + '\x0F', + '\x42', + '\x40'}; std::string expected(EXPECTED_FRAME_HEADER, sizeof(EXPECTED_FRAME_HEADER)); expected.append(message); @@ -775,10 +805,20 @@ TEST_F(InspectorSocketTest, Send1Mb) { char MASK[4] = {'W', 'h', 'O', 'a'}; - const char FRAME_TO_SERVER_HEADER[] = { - '\x81', '\xff', '\x00', '\x00', '\x00', '\x00', '\x00', '\x0F', - '\x42', '\x40', MASK[0], MASK[1], MASK[2], MASK[3] - }; + const char FRAME_TO_SERVER_HEADER[] = {'\x81', + '\xff', + '\x00', + '\x00', + '\x00', + '\x00', + '\x00', + '\x0F', + '\x42', + '\x40', + MASK[0], + MASK[1], + MASK[2], + MASK[3]}; std::string outgoing(FRAME_TO_SERVER_HEADER, sizeof(FRAME_TO_SERVER_HEADER)); outgoing.resize(outgoing.size() + message.size()); @@ -788,12 +828,12 @@ TEST_F(InspectorSocketTest, Send1Mb) { delegate->ExpectData(&message[0], message.size()); // 3. Close - const char CLIENT_CLOSE_FRAME[] = {'\x88', '\x80', '\x2D', - '\x0E', '\x1E', '\xFA'}; + const char CLIENT_CLOSE_FRAME[] = { + '\x88', '\x80', '\x2D', '\x0E', '\x1E', '\xFA'}; do_write(CLIENT_CLOSE_FRAME, sizeof(CLIENT_CLOSE_FRAME)); expect_on_client(SERVER_CLOSE_FRAME, sizeof(SERVER_CLOSE_FRAME)); - GTEST_ASSERT_EQ(0, uv_is_active( - reinterpret_cast(&client_socket))); + GTEST_ASSERT_EQ(0, + uv_is_active(reinterpret_cast(&client_socket))); } TEST_F(InspectorSocketTest, ErrorCleansUpTheSocket) { @@ -820,15 +860,16 @@ TEST_F(InspectorSocketTest, NoCloseResponseFromClient) { delegate->Close(); expect_on_client(SERVER_CLOSE_FRAME, sizeof(SERVER_CLOSE_FRAME)); uv_close(reinterpret_cast(&client_socket), nullptr); - GTEST_ASSERT_EQ(0, uv_is_active( - reinterpret_cast(&client_socket))); + GTEST_ASSERT_EQ(0, + uv_is_active(reinterpret_cast(&client_socket))); delegate->WaitForDispose(); } static bool delegate_called = false; void shouldnt_be_called(enum inspector_handshake_event state, - const std::string& path, bool* cont) { + const std::string& path, + bool* cont) { delegate_called = true; } diff --git a/test/cctest/test_inspector_socket_server.cc b/test/cctest/test_inspector_socket_server.cc index 349356ef56c9fc..63d48e29598529 100644 --- a/test/cctest/test_inspector_socket_server.cc +++ b/test/cctest/test_inspector_socket_server.cc @@ -1,7 +1,7 @@ #include "inspector_socket_server.h" -#include "node.h" #include "gtest/gtest.h" +#include "node.h" #include #include @@ -60,7 +60,7 @@ class Timeout { static void mark_done(uv_handle_t* timer) { Timeout* t = node::ContainerOf(&Timeout::timer_, - reinterpret_cast(timer)); + reinterpret_cast(timer)); t->done_ = true; } @@ -70,9 +70,7 @@ class Timeout { class InspectorSocketServerTest : public ::testing::Test { protected: - void SetUp() override { - EXPECT_EQ(0, uv_loop_init(&loop)); - } + void SetUp() override { EXPECT_EQ(0, uv_loop_init(&loop)); } void TearDown() override { const int err = uv_loop_close(&loop); @@ -85,12 +83,13 @@ class InspectorSocketServerTest : public ::testing::Test { class SocketWrapper { public: - explicit SocketWrapper(uv_loop_t* loop) : closed_(false), - eof_(false), - loop_(loop), - socket_(uv_tcp_t()), - connected_(false), - sending_(false) { } + explicit SocketWrapper(uv_loop_t* loop) + : closed_(false), + eof_(false), + loop_(loop), + socket_(uv_tcp_t()), + connected_(false), + sending_(false) {} void Connect(std::string host, int port, bool v6 = false) { closed_ = false; @@ -99,7 +98,11 @@ class SocketWrapper { eof_ = false; contents_.clear(); uv_tcp_init(loop_, &socket_); - union {sockaddr generic; sockaddr_in v4; sockaddr_in6 v6;} addr; + union { + sockaddr generic; + sockaddr_in v4; + sockaddr_in6 v6; + } addr; int err = 0; if (v6) { err = uv_ip6_addr(host.c_str(), port, &addr.v6); @@ -110,8 +113,8 @@ class SocketWrapper { err = uv_tcp_connect(&connect_, &socket_, &addr.generic, Connected_); CHECK_EQ(0, err); SPIN_WHILE(!connected_) - uv_read_start(reinterpret_cast(&socket_), AllocCallback, - ReadCallback); + uv_read_start( + reinterpret_cast(&socket_), AllocCallback, ReadCallback); } void ExpectFailureToConnect(std::string host, int port) { @@ -124,13 +127,14 @@ class SocketWrapper { sockaddr_in addr; int err = uv_ip4_addr(host.c_str(), port, &addr); CHECK_EQ(0, err); - err = uv_tcp_connect(&connect_, &socket_, + err = uv_tcp_connect(&connect_, + &socket_, reinterpret_cast(&addr), ConnectionMustFail_); CHECK_EQ(0, err); SPIN_WHILE(!connection_failed_) - uv_read_start(reinterpret_cast(&socket_), AllocCallback, - ReadCallback); + uv_read_start( + reinterpret_cast(&socket_), AllocCallback, ReadCallback); } void Close() { @@ -159,7 +163,8 @@ class SocketWrapper { "Content-Length: "; expectations << expected_reply.length() + 2; expectations << "\r\n\r\n" << expected_reply << "\n\n"; - Write("GET " + path + " HTTP/1.1\r\n" + Write("GET " + path + + " HTTP/1.1\r\n" "Host: localhost:9229\r\n\r\n"); Expect(expectations.str()); } @@ -170,8 +175,8 @@ class SocketWrapper { buf[0].base = const_cast(data.data()); buf[0].len = data.length(); sending_ = true; - int err = uv_write(&write_, reinterpret_cast(&socket_), - buf, 1, WriteDone_); + int err = uv_write( + &write_, reinterpret_cast(&socket_), buf, 1, WriteDone_); CHECK_EQ(err, 0); SPIN_WHILE(sending_); } @@ -182,9 +187,8 @@ class SocketWrapper { } static void ClosedCallback(uv_handle_t* handle) { - SocketWrapper* wrapper = - node::ContainerOf(&SocketWrapper::socket_, - reinterpret_cast(handle)); + SocketWrapper* wrapper = node::ContainerOf( + &SocketWrapper::socket_, reinterpret_cast(handle)); ASSERT_FALSE(wrapper->closed_); wrapper->closed_ = true; } @@ -203,23 +207,22 @@ class SocketWrapper { wrapper->connection_failed_ = true; } - static void ReadCallback(uv_stream_t* stream, ssize_t read, + static void ReadCallback(uv_stream_t* stream, + ssize_t read, const uv_buf_t* buf) { - SocketWrapper* wrapper = - node::ContainerOf(&SocketWrapper::socket_, - reinterpret_cast(stream)); + SocketWrapper* wrapper = node::ContainerOf( + &SocketWrapper::socket_, reinterpret_cast(stream)); if (read == UV_EOF) { wrapper->eof_ = true; } else { - wrapper->contents_.insert(wrapper->contents_.end(), buf->base, - buf->base + read); + wrapper->contents_.insert( + wrapper->contents_.end(), buf->base, buf->base + read); } delete[] buf->base; } static void WriteDone_(uv_write_t* req, int err) { CHECK_EQ(0, err); - SocketWrapper* wrapper = - node::ContainerOf(&SocketWrapper::write_, req); + SocketWrapper* wrapper = node::ContainerOf(&SocketWrapper::write_, req); ASSERT_TRUE(wrapper->sending_); wrapper->sending_ = false; } @@ -240,30 +243,23 @@ class SocketWrapper { class ServerHolder { public: ServerHolder(bool has_targets, uv_loop_t* loop, int port) - : ServerHolder(has_targets, loop, HOST, port, nullptr) { } + : ServerHolder(has_targets, loop, HOST, port, nullptr) {} - ServerHolder(bool has_targets, uv_loop_t* loop, - const std::string host, int port, FILE* out); + ServerHolder(bool has_targets, + uv_loop_t* loop, + const std::string host, + int port, + FILE* out); - InspectorSocketServer* operator->() { - return server_.get(); - } + InspectorSocketServer* operator->() { return server_.get(); } - int port() { - return server_->Port(); - } + int port() { return server_->Port(); } - bool done() { - return server_->done(); - } + bool done() { return server_->done(); } - void Disconnected() { - disconnected++; - } + void Disconnected() { disconnected++; } - void Done() { - delegate_done = true; - } + void Done() { delegate_done = true; } void Connected(int id) { buffer_.clear(); @@ -298,16 +294,11 @@ class ServerHolder { class TestSocketServerDelegate : public SocketServerDelegate { public: - explicit TestSocketServerDelegate( - ServerHolder* server, - const std::vector& target_ids) - : harness_(server), - targets_(target_ids), - session_id_(0) {} + explicit TestSocketServerDelegate(ServerHolder* server, + const std::vector& target_ids) + : harness_(server), targets_(target_ids), session_id_(0) {} - ~TestSocketServerDelegate() { - harness_->Done(); - } + ~TestSocketServerDelegate() { harness_->Done(); } void AssignServer(InspectorSocketServer* server) override { server_ = server; @@ -330,9 +321,7 @@ class TestSocketServerDelegate : public SocketServerDelegate { harness_->Disconnected(); } - std::vector GetTargetIds() override { - return targets_; - } + std::vector GetTargetIds() override { return targets_; } std::string GetTargetTitle(const std::string& id) override { return id + " Target Title"; @@ -349,18 +338,21 @@ class TestSocketServerDelegate : public SocketServerDelegate { int session_id_; }; -ServerHolder::ServerHolder(bool has_targets, uv_loop_t* loop, - const std::string host, int port, FILE* out) { +ServerHolder::ServerHolder(bool has_targets, + uv_loop_t* loop, + const std::string host, + int port, + FILE* out) { std::vector targets; - if (has_targets) - targets = { MAIN_TARGET_ID }; + if (has_targets) targets = {MAIN_TARGET_ID}; std::unique_ptr delegate( new TestSocketServerDelegate(this, targets)); server_.reset( new InspectorSocketServer(std::move(delegate), loop, host, port, out)); } -static void TestHttpRequest(int port, const std::string& path, +static void TestHttpRequest(int port, + const std::string& path, const std::string& expected_body) { SocketWrapper socket(&loop); socket.Connect(HOST, port); @@ -369,7 +361,8 @@ static void TestHttpRequest(int port, const std::string& path, } static const std::string WsHandshakeRequest(const std::string& target_id) { - return "GET /" + target_id + " HTTP/1.1\r\n" + return "GET /" + target_id + + " HTTP/1.1\r\n" "Host: localhost:9229\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" @@ -378,7 +371,6 @@ static const std::string WsHandshakeRequest(const std::string& target_id) { } } // anonymous namespace - TEST_F(InspectorSocketServerTest, InspectorSessions) { ServerHolder server(true, &loop, 0); ASSERT_TRUE(server->Start()); @@ -396,7 +388,8 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { server.Expect("1234"); server.Write("5678"); - well_behaved_socket.Expect("\x81\x4" "5678"); + well_behaved_socket.Expect("\x81\x4" + "5678"); well_behaved_socket.Write(CLIENT_CLOSE_FRAME); well_behaved_socket.Expect(SERVER_CLOSE_FRAME); @@ -422,7 +415,8 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { EXPECT_EQ(2, server.connected); server.Write("5678"); - dropped_connection_socket.Expect("\x81\x4" "5678"); + dropped_connection_socket.Expect("\x81\x4" + "5678"); dropped_connection_socket.Close(); SPIN_WHILE(server.disconnected < 2); @@ -436,10 +430,11 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { SPIN_WHILE(3 != server.connected); server.Write("5678"); - stays_till_termination_socket.Expect("\x81\x4" "5678"); + stays_till_termination_socket.Expect("\x81\x4" + "5678"); - stays_till_termination_socket - .Write("\x81\x84\x7F\xC2\x66\x31\x4E\xF0\x55\x05"); + stays_till_termination_socket.Write( + "\x81\x84\x7F\xC2\x66\x31\x4E\xF0\x55\x05"); server.Expect("1234"); server->Stop(); diff --git a/test/cctest/test_node_postmortem_metadata.cc b/test/cctest/test_node_postmortem_metadata.cc index e9acd629f35f91..28de9d2bfa205b 100644 --- a/test/cctest/test_node_postmortem_metadata.cc +++ b/test/cctest/test_node_postmortem_metadata.cc @@ -28,10 +28,8 @@ extern uintptr_t nodedbg_offset_BaseObject__persistent_handle___v8_Persistent_v8_Object; } - class DebugSymbolsTest : public EnvironmentTestFixture {}; - class TestHandleWrap : public node::HandleWrap { public: void MemoryInfo(node::MemoryTracker* tracker) const override { @@ -47,7 +45,6 @@ class TestHandleWrap : public node::HandleWrap { node::AsyncWrap::PROVIDER_TCPWRAP) {} }; - class TestReqWrap : public node::ReqWrap { public: void MemoryInfo(node::MemoryTracker* tracker) const override { @@ -55,9 +52,8 @@ class TestReqWrap : public node::ReqWrap { } TestReqWrap(node::Environment* env, v8::Local object) - : node::ReqWrap(env, - object, - node::AsyncWrap::PROVIDER_FSREQWRAP) {} + : node::ReqWrap( + env, object, node::AsyncWrap::PROVIDER_FSREQWRAP) {} }; TEST_F(DebugSymbolsTest, ContextEmbedderEnvironmentIndex) { @@ -73,8 +69,8 @@ TEST_F(DebugSymbolsTest, ExternalStringDataOffset) { class DummyBaseObject : public node::BaseObject { public: - DummyBaseObject(node::Environment* env, v8::Local obj) : - BaseObject(env, obj) {} + DummyBaseObject(node::Environment* env, v8::Local obj) + : BaseObject(env, obj) {} void MemoryInfo(node::MemoryTracker* tracker) const override { tracker->TrackThis(this); @@ -94,21 +90,22 @@ TEST_F(DebugSymbolsTest, BaseObjectPersistentHandle) { DummyBaseObject obj(*env, object); auto expected = reinterpret_cast(&obj.persistent()); - auto calculated = reinterpret_cast(&obj) + + auto calculated = + reinterpret_cast(&obj) + nodedbg_offset_BaseObject__persistent_handle___v8_Persistent_v8_Object; EXPECT_EQ(expected, calculated); obj.persistent().Reset(); // ~BaseObject() expects an empty handle. } - TEST_F(DebugSymbolsTest, EnvironmentHandleWrapQueue) { const v8::HandleScope handle_scope(isolate_); const Argv argv; Env env{handle_scope, argv}; auto expected = reinterpret_cast((*env)->handle_wrap_queue()); - auto calculated = reinterpret_cast(*env) + + auto calculated = + reinterpret_cast(*env) + nodedbg_offset_Environment__handle_wrap_queue___Environment_HandleWrapQueue; // NOLINT(whitespace/line_length) EXPECT_EQ(expected, calculated); } @@ -119,7 +116,8 @@ TEST_F(DebugSymbolsTest, EnvironmentReqWrapQueue) { Env env{handle_scope, argv}; auto expected = reinterpret_cast((*env)->req_wrap_queue()); - auto calculated = reinterpret_cast(*env) + + auto calculated = + reinterpret_cast(*env) + nodedbg_offset_Environment__req_wrap_queue___Environment_ReqWrapQueue; EXPECT_EQ(expected, calculated); } @@ -139,15 +137,15 @@ TEST_F(DebugSymbolsTest, HandleWrapList) { TestHandleWrap obj(*env, object, &handle); auto queue = reinterpret_cast((*env)->handle_wrap_queue()); - auto head = queue + + auto head = + queue + nodedbg_offset_Environment_HandleWrapQueue__head___ListNode_HandleWrap; - auto next = - head + nodedbg_offset_ListNode_HandleWrap__next___uintptr_t; + auto next = head + nodedbg_offset_ListNode_HandleWrap__next___uintptr_t; next = *reinterpret_cast(next); auto expected = reinterpret_cast(&obj); - auto calculated = next - - nodedbg_offset_HandleWrap__handle_wrap_queue___ListNode_HandleWrap; + auto calculated = + next - nodedbg_offset_HandleWrap__handle_wrap_queue___ListNode_HandleWrap; EXPECT_EQ(expected, calculated); obj.persistent().Reset(); // ~HandleWrap() expects an empty handle. @@ -168,13 +166,13 @@ TEST_F(DebugSymbolsTest, ReqWrapList) { // NOTE (mmarchini): Workaround to fix failing tests on ARM64 machines with // older GCC. Should be removed once we upgrade the GCC version used on our // ARM64 CI machinies. - for (auto it : *(*env)->req_wrap_queue()) (void) ⁢ + for (auto it : *(*env)->req_wrap_queue()) (void)⁢ auto queue = reinterpret_cast((*env)->req_wrap_queue()); - auto head = queue + + auto head = + queue + nodedbg_offset_Environment_ReqWrapQueue__head___ListNode_ReqWrapQueue; - auto next = - head + nodedbg_offset_ListNode_ReqWrap__next___uintptr_t; + auto next = head + nodedbg_offset_ListNode_ReqWrap__next___uintptr_t; next = *reinterpret_cast(next); auto expected = reinterpret_cast(&obj); diff --git a/test/cctest/test_platform.cc b/test/cctest/test_platform.cc index 876547480b7032..b5bac89187df99 100644 --- a/test/cctest/test_platform.cc +++ b/test/cctest/test_platform.cc @@ -1,5 +1,5 @@ -#include "node_internals.h" #include "libplatform/libplatform.h" +#include "node_internals.h" #include #include "gtest/gtest.h" @@ -23,7 +23,8 @@ class RepostingTask : public v8::Task { ++*run_count_; if (repost_count_ > 0) { --repost_count_; - platform_->CallOnForegroundThread(isolate_, + platform_->CallOnForegroundThread( + isolate_, new RepostingTask(repost_count_, run_count_, isolate_, platform_)); } } @@ -41,7 +42,7 @@ TEST_F(PlatformTest, SkipNewTasksInFlushForegroundTasks) { v8::Isolate::Scope isolate_scope(isolate_); const v8::HandleScope handle_scope(isolate_); const Argv argv; - Env env {handle_scope, argv}; + Env env{handle_scope, argv}; int run_count = 0; platform->CallOnForegroundThread( isolate_, new RepostingTask(2, &run_count, isolate_, platform.get())); diff --git a/test/cctest/test_traced_value.cc b/test/cctest/test_traced_value.cc index 5329c78446ca6f..3cc1978dc50356 100644 --- a/test/cctest/test_traced_value.cc +++ b/test/cctest/test_traced_value.cc @@ -62,13 +62,14 @@ TEST(TracedValue, Array) { EXPECT_EQ(check, string); } -#define UTF8_SEQUENCE "1" "\xE2\x82\xAC" "23\"\x01\b\f\n\r\t\\" +#define UTF8_SEQUENCE \ + "1" \ + "\xE2\x82\xAC" \ + "23\"\x01\b\f\n\r\t\\" #if defined(NODE_HAVE_I18N_SUPPORT) -# define UTF8_RESULT \ - "\"1\\u20AC23\\\"\\u0001\\b\\f\\n\\r\\t\\\\\"" +#define UTF8_RESULT "\"1\\u20AC23\\\"\\u0001\\b\\f\\n\\r\\t\\\\\"" #else -# define UTF8_RESULT \ - "\"1\\u00E2\\u0082\\u00AC23\\\"\\u0001\\b\\f\\n\\r\\t\\\\\"" +#define UTF8_RESULT "\"1\\u00E2\\u0082\\u00AC23\\\"\\u0001\\b\\f\\n\\r\\t\\\\\"" #endif TEST(TracedValue, EscapingObject) { diff --git a/test/cctest/test_url.cc b/test/cctest/test_url.cc index 0b80d44caad807..cff7b1dc463678 100644 --- a/test/cctest/test_url.cc +++ b/test/cctest/test_url.cc @@ -1,5 +1,5 @@ -#include "node_url.h" #include "node_i18n.h" +#include "node_url.h" #include "gtest/gtest.h" diff --git a/test/cctest/test_util.cc b/test/cctest/test_util.cc index db19d92cbd9c19..6163c6bfea2867 100644 --- a/test/cctest/test_util.cc +++ b/test/cctest/test_util.cc @@ -1,10 +1,12 @@ -#include "util.h" #include "util-inl.h" +#include "util.h" #include "gtest/gtest.h" TEST(UtilTest, ListHead) { - struct Item { node::ListNode node_; }; + struct Item { + node::ListNode node_; + }; typedef node::ListHead List; List list; @@ -90,11 +92,11 @@ TEST(UtilTest, ToLower) { EXPECT_EQ('a', ToLower('A')); } -#define TEST_AND_FREE(expression) \ - do { \ - auto pointer = expression; \ - EXPECT_NE(nullptr, pointer); \ - free(pointer); \ +#define TEST_AND_FREE(expression) \ + do { \ + auto pointer = expression; \ + EXPECT_NE(nullptr, pointer); \ + free(pointer); \ } while (0) TEST(UtilTest, Malloc) { @@ -152,8 +154,7 @@ static void MaybeStackBufferBasic() { EXPECT_EQ(&buf[0], *buf); /* Basic I/O */ - for (size_t i = 0; i < buf.length(); i++) - buf[i] = static_cast(i); + for (size_t i = 0; i < buf.length(); i++) buf[i] = static_cast(i); for (size_t i = 0; i < buf.length(); i++) EXPECT_EQ(static_cast(i), buf[i]); @@ -171,13 +172,11 @@ static void MaybeStackBufferBasic() { buf.AllocateSufficientStorage(buf.capacity() * 2); EXPECT_EQ(buf.capacity(), buf.length()); EXPECT_TRUE(buf.IsAllocated()); - for (size_t i = 0; i < old_length; i++) - EXPECT_EQ(static_cast(i), buf[i]); + for (size_t i = 0; i < old_length; i++) EXPECT_EQ(static_cast(i), buf[i]); EXPECT_EQ(0, buf[old_length]); /* SetLength() reduction and expansion */ - for (size_t i = 0; i < buf.length(); i++) - buf[i] = static_cast(i); + for (size_t i = 0; i < buf.length(); i++) buf[i] = static_cast(i); buf.SetLength(10); for (size_t i = 0; i < buf.length(); i++) EXPECT_EQ(static_cast(i), buf[i]); @@ -192,12 +191,10 @@ static void MaybeStackBufferBasic() { EXPECT_EQ(buf.capacity(), buf.length()); EXPECT_EQ(static_cast(old_capacity * 1.5), buf.length()); EXPECT_TRUE(buf.IsAllocated()); - for (size_t i = 0; i < old_length; i++) - EXPECT_EQ(static_cast(i), buf[i]); + for (size_t i = 0; i < old_length; i++) EXPECT_EQ(static_cast(i), buf[i]); /* Basic I/O on Realloc'd buffer */ - for (size_t i = 0; i < buf.length(); i++) - buf[i] = static_cast(i); + for (size_t i = 0; i < buf.length(); i++) buf[i] = static_cast(i); for (size_t i = 0; i < buf.length(); i++) EXPECT_EQ(static_cast(i), buf[i]); diff --git a/test/gc/binding.cc b/test/gc/binding.cc index 8bde3b8505cf37..d43af00011fc58 100644 --- a/test/gc/binding.cc +++ b/test/gc/binding.cc @@ -7,7 +7,10 @@ #include #ifdef NDEBUG -#define CHECK(x) do { if (!(x)) abort(); } while (false) +#define CHECK(x) \ + do { \ + if (!(x)) abort(); \ + } while (false) #else #define CHECK assert #endif @@ -57,14 +60,14 @@ inline void OnGC(const v8::FunctionCallbackInfo& info) { auto object = info[0].As(); auto function = info[1].As(); auto callback = new Callback(info.GetIsolate(), object, function); - auto on_callback = [] (const v8::WeakCallbackInfo& data) { + auto on_callback = [](const v8::WeakCallbackInfo& data) { auto callback = data.GetParameter(); callbacks.push_back(callback); callback->object.Reset(); Prime(); }; - callback->object.SetWeak(callback, on_callback, - v8::WeakCallbackType::kParameter); + callback->object.SetWeak( + callback, on_callback, v8::WeakCallbackType::kParameter); } inline void Initialize(v8::Local exports, diff --git a/tools/clang-format/package.json b/tools/clang-format/package.json new file mode 100644 index 00000000000000..8432296ed6f1fc --- /dev/null +++ b/tools/clang-format/package.json @@ -0,0 +1,9 @@ +{ + "name": "node-core-clang-format", + "version": "1.0.0", + "description": "Formatting C++ files for Node.js core", + "license": "MIT", + "dependencies": { + "clang-format": "1.2.3" + } +} diff --git a/tools/icu/iculslocs.cc b/tools/icu/iculslocs.cc index f096a6a84c970f..e6f29c39fcfd2e 100644 --- a/tools/icu/iculslocs.cc +++ b/tools/icu/iculslocs.cc @@ -50,12 +50,12 @@ Japanese, it doesn't *claim* to have Japanese. */ -#include "string.h" -#include "charstr.h" // ICU internal header -#include -#include -#include #include +#include +#include +#include +#include "charstr.h" // ICU internal header +#include "string.h" const char* PROG = "iculslocs"; const char* NAME = U_ICUDATA_NAME; // assume ICU data @@ -70,51 +70,44 @@ const char* locale = RES_INDEX; // locale referring to our index void usage() { printf("Usage: %s [options]\n", PROG); - printf( - "This program lists and optionally regenerates the locale " - "manifests\n" - " in ICU 'res_index.res' files.\n"); - printf( - " -i ICUDATA Set ICUDATA dir to ICUDATA.\n" - " NOTE: this must be the first option given.\n"); + printf("This program lists and optionally regenerates the locale " + "manifests\n" + " in ICU 'res_index.res' files.\n"); + printf(" -i ICUDATA Set ICUDATA dir to ICUDATA.\n" + " NOTE: this must be the first option given.\n"); printf(" -h This Help\n"); printf(" -v Verbose Mode on\n"); printf(" -l List locales to stdout\n"); - printf( - " if Verbose mode, then missing (unopenable)" - "locales\n" - " will be listed preceded by a '#'.\n"); - printf( - " -b res_index.txt Write 'corrected' bundle " - "to res_index.txt\n" - " missing bundles will be " - "OMITTED\n"); - printf( - " -T TREE Choose tree TREE\n" - " (TREE should be one of: \n" - " ROOT, brkitr, coll, curr, lang, rbnf, region, zone)\n"); + printf(" if Verbose mode, then missing (unopenable)" + "locales\n" + " will be listed preceded by a '#'.\n"); + printf(" -b res_index.txt Write 'corrected' bundle " + "to res_index.txt\n" + " missing bundles will be " + "OMITTED\n"); + printf(" -T TREE Choose tree TREE\n" + " (TREE should be one of: \n" + " ROOT, brkitr, coll, curr, lang, rbnf, region, zone)\n"); // see ureslocs.h and elsewhere - printf( - " -N NAME Choose name NAME\n" - " (default: '%s')\n", - U_ICUDATA_NAME); - printf( - "\nNOTE: for best results, this tool ought to be " - "linked against\n" - "stubdata. i.e. '%s -l' SHOULD return an error with " - " no data.\n", - PROG); + printf(" -N NAME Choose name NAME\n" + " (default: '%s')\n", + U_ICUDATA_NAME); + printf("\nNOTE: for best results, this tool ought to be " + "linked against\n" + "stubdata. i.e. '%s -l' SHOULD return an error with " + " no data.\n", + PROG); } -#define ASSERT_SUCCESS(status, what) \ - if (U_FAILURE(*status)) { \ - printf("%s:%d: %s: ERROR: %s %s\n", \ - __FILE__, \ - __LINE__, \ - PROG, \ - u_errorName(*status), \ - what); \ - return 1; \ +#define ASSERT_SUCCESS(status, what) \ + if (U_FAILURE(*status)) { \ + printf("%s:%d: %s: ERROR: %s %s\n", \ + __FILE__, \ + __LINE__, \ + PROG, \ + u_errorName(*status), \ + what); \ + return 1; \ } /** @@ -313,7 +306,7 @@ int list(const char* toBundle) { UBool exists; if (localeExists(key, &exists)) { if (bf != NULL) fclose(bf); // NOLINT (readability/null_usage) - return 1; // get out. + return 1; // get out. } if (exists) { validCount++;