GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — node/src/node.cc at master · aivopaas/node Expand file tree/ Copy pathnode.ccMore file actions 2677 lines (2236 loc) · 81.3 KB / Copy pathnode.ccFile metadata and controls2677 lines (2236 loc) · 81.3 KB 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 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 // 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. #include "node_buffer.h" #include "node_constants.h" #include "node_context_data.h" #include "node_errors.h" #include "node_internals.h" #include "node_javascript.h" #include "node_code_cache.h" #include "node_platform.h" #include "node_version.h" #include "node_internals.h" #include "node_revert.h" #include "node_version.h" #include "tracing/traced_value.h" #if HAVE_OPENSSL #include "node_crypto.h" #endif #if defined(NODE_HAVE_I18N_SUPPORT) #include "node_i18n.h" #endif #if HAVE_INSPECTOR #include "inspector_io.h" #endif #if defined HAVE_DTRACE || defined HAVE_ETW #include "node_dtrace.h" #endif #include "ares.h" #include "async_wrap-inl.h" #include "env-inl.h" #include "handle_wrap.h" #include "http_parser.h" #include "nghttp2/nghttp2ver.h" #include "req_wrap-inl.h" #include "string_bytes.h" #include "tracing/agent.h" #include "tracing/node_trace_writer.h" #include "util.h" #include "uv.h" #if NODE_USE_V8_PLATFORM #include "libplatform/libplatform.h" #endif // NODE_USE_V8_PLATFORM #include "v8-profiler.h" #include "zlib.h" #ifdef NODE_ENABLE_VTUNE_PROFILING #include "../deps/v8/src/third_party/vtune/v8-vtune.h" #endif #ifdef NODE_ENABLE_LARGE_CODE_PAGES #include "large_pages/node_large_page.h" #endif #include <errno.h> #include <fcntl.h> // _O_RDWR #include <limits.h> // PATH_MAX #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <string> #include <vector> #if defined(NODE_HAVE_I18N_SUPPORT) #include <unicode/uvernum.h> #endif #if defined(LEAK_SANITIZER) #include <sanitizer/lsan_interface.h> #endif #if defined(_MSC_VER) #include <direct.h> #include <io.h> #define umask _umask typedef int mode_t; #else #include <pthread.h> #include <sys/resource.h> // getrlimit, setrlimit #include <unistd.h> // setuid, getuid #endif #if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__) #include <pwd.h> // getpwnam() #include <grp.h> // getgrnam() #endif #if defined(__POSIX__) #include <dlfcn.h> #endif // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly in // node::RegisterBuiltinModules(). This is only forward declaration. // 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) #undef V namespace node { using options_parser::kAllowedInEnvironment; using options_parser::kDisallowedInEnvironment; using v8::Array; using v8::Boolean; using v8::Context; using v8::DEFAULT; using v8::DontEnum; using v8::EscapableHandleScope; using v8::Exception; using v8::Function; using v8::FunctionCallbackInfo; using v8::HandleScope; using v8::Int32; using v8::Integer; using v8::Isolate; using v8::Just; using v8::Local; using v8::Locker; using v8::Maybe; using v8::MaybeLocal; using v8::Message; using v8::MicrotasksPolicy; using v8::NamedPropertyHandlerConfiguration; using v8::NewStringType; using v8::None; using v8::Nothing; using v8::Null; using v8::Object; using v8::ObjectTemplate; using v8::PropertyAttribute; using v8::ReadOnly; using v8::Script; using v8::ScriptCompiler; using v8::ScriptOrigin; using v8::SealHandleScope; using v8::SideEffectType; using v8::String; using v8::TracingController; using v8::TryCatch; using v8::Undefined; using v8::V8; using v8::Value; static bool v8_is_profiling = false; static bool node_is_initialized = false; static uv_once_t init_modpending_once = UV_ONCE_INIT; static uv_key_t thread_local_modpending; static node_module* modlist_builtin; static node_module* modlist_internal; static node_module* modlist_linked; static node_module* modlist_addon; // Bit flag used to track security reverts (see node_revert.h) unsigned int reverted = 0; bool v8_initialized = false; bool linux_at_secure = false; // process-relative uptime base, initialized at start-up double prog_start_time; Mutex per_process_opts_mutex; std::shared_ptr<PerProcessOptions> per_process_opts { new PerProcessOptions() }; static Mutex node_isolate_mutex; static Isolate* node_isolate; // Ensures that __metadata trace events are only emitted // when tracing is enabled. class NodeTraceStateObserver : public 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", "version", "node", NODE_VERSION_STRING); TRACE_EVENT_METADATA1("__metadata", "thread_name", "name", "JavaScriptMainThread"); auto trace_process = tracing::TracedValue::Create(); trace_process->BeginDictionary("versions"); const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "." NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR) "." NODE_STRINGIFY(HTTP_PARSER_VERSION_PATCH); const char node_napi_version[] = NODE_STRINGIFY(NAPI_VERSION); const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION); trace_process->SetString("http_parser", http_parser_version); trace_process->SetString("node", NODE_VERSION_STRING); trace_process->SetString("v8", V8::GetVersion()); trace_process->SetString("uv", uv_version_string()); trace_process->SetString("zlib", ZLIB_VERSION); trace_process->SetString("ares", ARES_VERSION_STR); trace_process->SetString("modules", node_modules_version); trace_process->SetString("nghttp2", NGHTTP2_VERSION); trace_process->SetString("napi", node_napi_version); #if HAVE_OPENSSL trace_process->SetString("openssl", crypto::GetOpenSSLVersion()); #endif trace_process->EndDictionary(); trace_process->SetString("arch", NODE_ARCH); trace_process->SetString("platform", NODE_PLATFORM); trace_process->BeginDictionary("release"); trace_process->SetString("name", NODE_RELEASE); #if NODE_VERSION_IS_LTS trace_process->SetString("lts", NODE_VERSION_LTS_CODENAME); #endif trace_process->EndDictionary(); TRACE_EVENT_METADATA1("__metadata", "node", "process", std::move(trace_process)); // This only runs the first time tracing is enabled controller_->RemoveTraceStateObserver(this); delete this; } void OnTraceDisabled() override { // Do nothing here. This should never be called because the // observer removes itself when OnTraceEnabled() is called. UNREACHABLE(); } explicit NodeTraceStateObserver(TracingController* controller) : controller_(controller) {} ~NodeTraceStateObserver() override {} private: TracingController* controller_; }; static struct { #if NODE_USE_V8_PLATFORM void Initialize(int thread_pool_size) { tracing_agent_.reset(new tracing::Agent()); node::tracing::TraceEventHelper::SetAgent(tracing_agent_.get()); auto controller = tracing_agent_->GetTracingController(); controller->AddTraceStateObserver(new NodeTraceStateObserver(controller)); StartTracingAgent(); // Tracing must be initialized before platform threads are created. platform_ = new NodePlatform(thread_pool_size, controller); V8::InitializePlatform(platform_); } void Dispose() { platform_->Shutdown(); delete platform_; platform_ = nullptr; // Destroy tracing after the platform (and platform threads) have been // stopped. tracing_agent_.reset(nullptr); } 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, std::shared_ptr<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 // false. return env->inspector_agent()->Start( script_path == nullptr ? "" : script_path, options, true); } bool InspectorStarted(Environment* env) { return env->inspector_agent()->IsListening(); } #endif // HAVE_INSPECTOR void StartTracingAgent() { if (per_process_opts->trace_event_categories.empty()) { tracing_file_writer_ = tracing_agent_->DefaultHandle(); } else { tracing_file_writer_ = tracing_agent_->AddClient( ParseCommaSeparatedSet(per_process_opts->trace_event_categories), std::unique_ptr<tracing::AsyncTraceWriter>( new tracing::NodeTraceWriter( per_process_opts->trace_event_file_pattern)), tracing::Agent::kUseDefaultCategories); } } void StopTracingAgent() { tracing_file_writer_.reset(); } tracing::AgentWriterHandle* GetTracingAgentWriter() { return &tracing_file_writer_; } NodePlatform* Platform() { return platform_; } std::unique_ptr<tracing::Agent> tracing_agent_; tracing::AgentWriterHandle tracing_file_writer_; NodePlatform* 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, const DebugOptions& options) { env->ThrowError("Node compiled with NODE_USE_V8_PLATFORM=0"); return true; } void StartTracingAgent() { if (!trace_enabled_categories.empty()) { fprintf(stderr, "Node compiled with NODE_USE_V8_PLATFORM=0, " "so event tracing is not available.\n"); } } void StopTracingAgent() {} tracing::AgentWriterHandle* GetTracingAgentWriter() { return nullptr; } NodePlatform* Platform() { return nullptr; } #endif // !NODE_USE_V8_PLATFORM #if !NODE_USE_V8_PLATFORM || !HAVE_INSPECTOR bool InspectorStarted(Environment* env) { return false; } #endif // !NODE_USE_V8_PLATFORM || !HAVE_INSPECTOR } v8_platform; tracing::AgentWriterHandle* GetTracingAgentWriter() { return v8_platform.GetTracingAgentWriter(); } #ifdef __POSIX__ static const unsigned kMaxSignal = 32; #endif const char* signo_string(int signo) { #define SIGNO_CASE(e) case e: return #e; switch (signo) { #ifdef SIGHUP SIGNO_CASE(SIGHUP); #endif #ifdef SIGINT SIGNO_CASE(SIGINT); #endif #ifdef SIGQUIT SIGNO_CASE(SIGQUIT); #endif #ifdef SIGILL SIGNO_CASE(SIGILL); #endif #ifdef SIGTRAP SIGNO_CASE(SIGTRAP); #endif #ifdef SIGABRT SIGNO_CASE(SIGABRT); #endif #ifdef SIGIOT # if SIGABRT != SIGIOT SIGNO_CASE(SIGIOT); # endif #endif #ifdef SIGBUS SIGNO_CASE(SIGBUS); #endif #ifdef SIGFPE SIGNO_CASE(SIGFPE); #endif #ifdef SIGKILL SIGNO_CASE(SIGKILL); #endif #ifdef SIGUSR1 SIGNO_CASE(SIGUSR1); #endif #ifdef SIGSEGV SIGNO_CASE(SIGSEGV); #endif #ifdef SIGUSR2 SIGNO_CASE(SIGUSR2); #endif #ifdef SIGPIPE SIGNO_CASE(SIGPIPE); #endif #ifdef SIGALRM SIGNO_CASE(SIGALRM); #endif SIGNO_CASE(SIGTERM); #ifdef SIGCHLD SIGNO_CASE(SIGCHLD); #endif #ifdef SIGSTKFLT SIGNO_CASE(SIGSTKFLT); #endif #ifdef SIGCONT SIGNO_CASE(SIGCONT); #endif #ifdef SIGSTOP SIGNO_CASE(SIGSTOP); #endif #ifdef SIGTSTP SIGNO_CASE(SIGTSTP); #endif #ifdef SIGBREAK SIGNO_CASE(SIGBREAK); #endif #ifdef SIGTTIN SIGNO_CASE(SIGTTIN); #endif #ifdef SIGTTOU SIGNO_CASE(SIGTTOU); #endif #ifdef SIGURG SIGNO_CASE(SIGURG); #endif #ifdef SIGXCPU SIGNO_CASE(SIGXCPU); #endif #ifdef SIGXFSZ SIGNO_CASE(SIGXFSZ); #endif #ifdef SIGVTALRM SIGNO_CASE(SIGVTALRM); #endif #ifdef SIGPROF SIGNO_CASE(SIGPROF); #endif #ifdef SIGWINCH SIGNO_CASE(SIGWINCH); #endif #ifdef SIGIO SIGNO_CASE(SIGIO); #endif #ifdef SIGPOLL # if SIGPOLL != SIGIO SIGNO_CASE(SIGPOLL); # endif #endif #ifdef SIGLOST # if SIGLOST != SIGABRT SIGNO_CASE(SIGLOST); # endif #endif #ifdef SIGPWR # if SIGPWR != SIGLOST SIGNO_CASE(SIGPWR); # endif #endif #ifdef SIGINFO # if !defined(SIGPWR) || SIGINFO != SIGPWR SIGNO_CASE(SIGINFO); # endif #endif #ifdef SIGSYS SIGNO_CASE(SIGSYS); #endif default: return ""; } } // Look up environment variable unless running as setuid root. bool SafeGetenv(const char* key, std::string* text) { #if !defined(__CloudABI__) && !defined(_WIN32) if (linux_at_secure || getuid() != geteuid() || getgid() != getegid()) goto fail; #endif { Mutex::ScopedLock lock(environ_mutex); if (const char* value = getenv(key)) { *text = value; return true; } } fail: text->clear(); return false; } void* ArrayBufferAllocator::Allocate(size_t size) { if (zero_fill_field_ || per_process_opts->zero_fill_all_buffers) return UncheckedCalloc(size); else return UncheckedMalloc(size); } namespace { bool ShouldAbortOnUncaughtException(Isolate* isolate) { HandleScope scope(isolate); Environment* env = Environment::GetCurrent(isolate); return env != nullptr && env->should_abort_on_uncaught_toggle()[0] && !env->inside_should_not_abort_on_uncaught_scope(); } } // anonymous namespace void AddPromiseHook(Isolate* isolate, promise_hook_func fn, void* arg) { Environment* env = Environment::GetCurrent(isolate); CHECK_NOT_NULL(env); env->AddPromiseHook(fn, arg); } void AddEnvironmentCleanupHook(Isolate* isolate, void (*fun)(void* arg), void* arg) { Environment* env = Environment::GetCurrent(isolate); CHECK_NOT_NULL(env); env->AddCleanupHook(fun, arg); } void RemoveEnvironmentCleanupHook(Isolate* isolate, void (*fun)(void* arg), void* arg) { Environment* env = Environment::GetCurrent(isolate); CHECK_NOT_NULL(env); env->RemoveCleanupHook(fun, arg); } MaybeLocal<Value> InternalMakeCallback(Environment* env, Local<Object> recv, const Local<Function> callback, int argc, Local<Value> argv[], async_context asyncContext) { CHECK(!recv.IsEmpty()); InternalCallbackScope scope(env, recv, asyncContext); if (scope.Failed()) { return MaybeLocal<Value>(); } Local<Function> domain_cb = env->domain_callback(); MaybeLocal<Value> ret; if (asyncContext.async_id != 0 || domain_cb.IsEmpty() || recv.IsEmpty()) { ret = callback->Call(env->context(), recv, argc, argv); } else { std::vector<Local<Value>> args(1 + argc); args[0] = callback; std::copy(&argv[0], &argv[argc], args.begin() + 1); ret = domain_cb->Call(env->context(), recv, args.size(), &args[0]); } if (ret.IsEmpty()) { scope.MarkAsFailed(); return MaybeLocal<Value>(); } scope.Close(); if (scope.Failed()) { return MaybeLocal<Value>(); } return ret; } // Public MakeCallback()s MaybeLocal<Value> MakeCallback(Isolate* isolate, Local<Object> recv, const char* method, int argc, Local<Value> argv[], async_context asyncContext) { Local<String> method_string = String::NewFromUtf8(isolate, method, NewStringType::kNormal) .ToLocalChecked(); return MakeCallback(isolate, recv, method_string, argc, argv, asyncContext); } MaybeLocal<Value> MakeCallback(Isolate* isolate, Local<Object> recv, Local<String> symbol, int argc, Local<Value> argv[], async_context asyncContext) { Local<Value> callback_v = recv->Get(symbol); if (callback_v.IsEmpty()) return Local<Value>(); if (!callback_v->IsFunction()) return Local<Value>(); Local<Function> callback = callback_v.As<Function>(); return MakeCallback(isolate, recv, callback, argc, argv, asyncContext); } MaybeLocal<Value> MakeCallback(Isolate* isolate, Local<Object> recv, Local<Function> callback, int argc, Local<Value> argv[], async_context asyncContext) { // Observe the following two subtleties: // // 1. The environment is retrieved from the callback function's context. // 2. The context to enter is retrieved from the environment. // // Because of the AssignToContext() call in src/node_contextify.cc, // the two contexts need not be the same. Environment* env = Environment::GetCurrent(callback->CreationContext()); CHECK_NOT_NULL(env); Context::Scope context_scope(env->context()); MaybeLocal<Value> ret = InternalMakeCallback(env, recv, callback, argc, argv, asyncContext); if (ret.IsEmpty() && env->makecallback_depth() == 0) { // This is only for legacy compatiblity and we may want to look into // removing/adjusting it. return Undefined(env->isolate()); } return ret; } // Legacy MakeCallback()s Local<Value> MakeCallback(Isolate* isolate, Local<Object> recv, const char* method, int argc, Local<Value>* argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( MakeCallback(isolate, recv, method, argc, argv, {0, 0}) .FromMaybe(Local<Value>())); } Local<Value> MakeCallback(Isolate* isolate, Local<Object> recv, Local<String> symbol, int argc, Local<Value>* argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( MakeCallback(isolate, recv, symbol, argc, argv, {0, 0}) .FromMaybe(Local<Value>())); } Local<Value> MakeCallback(Isolate* isolate, Local<Object> recv, Local<Function> callback, int argc, Local<Value>* argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( MakeCallback(isolate, recv, callback, argc, argv, {0, 0}) .FromMaybe(Local<Value>())); } // Executes a str within the current v8 context. static MaybeLocal<Value> ExecuteString(Environment* env, Local<String> source, Local<String> filename) { EscapableHandleScope scope(env->isolate()); TryCatch try_catch(env->isolate()); // try_catch must be nonverbose to disable FatalException() handler, // we will handle exceptions ourself. try_catch.SetVerbose(false); ScriptOrigin origin(filename); MaybeLocal<Script> script = Script::Compile(env->context(), source, &origin); if (script.IsEmpty()) { ReportException(env, try_catch); env->Exit(3); return MaybeLocal<Value>(); } MaybeLocal<Value> result = script.ToLocalChecked()->Run(env->context()); if (result.IsEmpty()) { if (try_catch.HasTerminated()) { env->isolate()->CancelTerminateExecution(); return MaybeLocal<Value>(); } ReportException(env, try_catch); env->Exit(4); return MaybeLocal<Value>(); } return scope.Escape(result.ToLocalChecked()); } static void WaitForInspectorDisconnect(Environment* env) { #if HAVE_INSPECTOR if (env->inspector_agent()->IsActive()) { // Restore signal dispositions, the app is done and is no longer // capable of handling signals. #if defined(__POSIX__) && !defined(NODE_SHARED_MODE) struct sigaction act; memset(&act, 0, sizeof(act)); for (unsigned nr = 1; nr < kMaxSignal; nr += 1) { if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF) continue; act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL; CHECK_EQ(0, sigaction(nr, &act, nullptr)); } #endif env->inspector_agent()->WaitForDisconnect(); } #endif } static void Exit(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); WaitForInspectorDisconnect(env); v8_platform.StopTracingAgent(); int code = args[0]->Int32Value(env->context()).FromMaybe(0); env->Exit(code); } extern "C" void node_module_register(void* m) { struct node_module* mp = reinterpret_cast<struct node_module*>(m); if (mp->nm_flags & NM_F_BUILTIN) { mp->nm_link = modlist_builtin; modlist_builtin = mp; } else if (mp->nm_flags & NM_F_INTERNAL) { mp->nm_link = modlist_internal; modlist_internal = mp; } else if (!node_is_initialized) { // "Linked" modules are included as part of the node project. // Like builtins they are registered *before* node::Init runs. mp->nm_flags = NM_F_LINKED; mp->nm_link = modlist_linked; modlist_linked = mp; } else { uv_key_set(&thread_local_modpending, mp); } } inline struct node_module* FindModule(struct node_module* list, const char* name, int flag) { struct node_module* mp; for (mp = list; mp != nullptr; mp = mp->nm_link) { if (strcmp(mp->nm_modname, name) == 0) break; } CHECK(mp == nullptr || (mp->nm_flags & flag) != 0); return mp; } node_module* get_builtin_module(const char* name) { return FindModule(modlist_builtin, name, NM_F_BUILTIN); } node_module* get_internal_module(const char* name) { return FindModule(modlist_internal, name, NM_F_INTERNAL); } node_module* get_linked_module(const char* name) { return FindModule(modlist_linked, name, NM_F_LINKED); } class DLib { public: #ifdef __POSIX__ static const int kDefaultFlags = RTLD_LAZY; #else static const int kDefaultFlags = 0; #endif inline DLib(const char* filename, int flags) : filename_(filename), flags_(flags), handle_(nullptr) {} inline bool Open(); inline void Close(); inline void* GetSymbolAddress(const char* name); const std::string filename_; const int flags_; std::string errmsg_; void* handle_; #ifndef __POSIX__ uv_lib_t lib_; #endif private: DISALLOW_COPY_AND_ASSIGN(DLib); }; #ifdef __POSIX__ bool DLib::Open() { handle_ = dlopen(filename_.c_str(), flags_); if (handle_ != nullptr) return true; errmsg_ = dlerror(); return false; } void DLib::Close() { if (handle_ == nullptr) return; dlclose(handle_); handle_ = nullptr; } void* DLib::GetSymbolAddress(const char* name) { return dlsym(handle_, name); } #else // !__POSIX__ bool DLib::Open() { int ret = uv_dlopen(filename_.c_str(), &lib_); if (ret == 0) { handle_ = static_cast<void*>(lib_.handle); return true; } errmsg_ = uv_dlerror(&lib_); uv_dlclose(&lib_); return false; } void DLib::Close() { if (handle_ == nullptr) return; uv_dlclose(&lib_); handle_ = nullptr; } void* DLib::GetSymbolAddress(const char* name) { void* address; if (0 == uv_dlsym(&lib_, name, &address)) return address; return nullptr; } #endif // !__POSIX__ using InitializerCallback = void (*)(Local<Object> exports, Local<Value> module, Local<Context> context); inline InitializerCallback GetInitializerCallback(DLib* dlib) { const char* name = "node_register_module_v" STRINGIFY(NODE_MODULE_VERSION); return reinterpret_cast<InitializerCallback>(dlib->GetSymbolAddress(name)); } inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) { const char* name = STRINGIFY(NAPI_MODULE_INITIALIZER_BASE) STRINGIFY(NAPI_MODULE_VERSION); return reinterpret_cast<napi_addon_register_func>(dlib->GetSymbolAddress(name)); } void InitModpendingOnce() { CHECK_EQ(0, uv_key_create(&thread_local_modpending)); } // DLOpen is process.dlopen(module, filename, flags). // Used to load 'module.node' dynamically shared objects. // // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict // when two contexts try to load the same shared object. Maybe have a shadow // cache that's a plain C list or hash table that's shared across contexts? static void DLOpen(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); auto context = env->context(); uv_once(&init_modpending_once, InitModpendingOnce); CHECK_NULL(uv_key_get(&thread_local_modpending)); if (args.Length() < 2) { env->ThrowError("process.dlopen needs at least 2 arguments."); return; } int32_t flags = DLib::kDefaultFlags; if (args.Length() > 2 && !args[2]->Int32Value(context).To(&flags)) { return env->ThrowTypeError("flag argument must be an integer."); } Local<Object> module; Local<Object> exports; Local<Value> exports_v; if (!args[0]->ToObject(context).ToLocal(&module) || !module->Get(context, env->exports_string()).ToLocal(&exports_v) || !exports_v->ToObject(context).ToLocal(&exports)) { return; // Exception pending. } node::Utf8Value filename(env->isolate(), args[1]); // Cast DLib dlib(*filename, flags); bool is_opened = dlib.Open(); // Objects containing v14 or later modules will have registered themselves // on the pending list. Activate all of them now. At present, only one // module per object is supported. node_module* const mp = static_cast<node_module*>( uv_key_get(&thread_local_modpending)); uv_key_set(&thread_local_modpending, nullptr); if (!is_opened) { Local<String> errmsg = OneByteString(env->isolate(), dlib.errmsg_.c_str()); dlib.Close(); #ifdef _WIN32 // Windows needs to add the filename into the error message errmsg = String::Concat( env->isolate(), errmsg, args[1]->ToString(context).ToLocalChecked()); #endif // _WIN32 env->isolate()->ThrowException(Exception::Error(errmsg)); return; } if (mp == nullptr) { if (auto callback = GetInitializerCallback(&dlib)) { |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |