electron/shell/app/node_main.cc

224 lines
6.8 KiB
C++
Raw Normal View History

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/app/node_main.h"
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/thread_pool/thread_pool_instance.h"
2016-07-04 06:08:55 +00:00
#include "base/threading/thread_task_runner_handle.h"
#include "electron/electron_version.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
#include "gin/v8_initializer.h"
#include "shell/app/uv_task_runner.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/node_debugger.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/crash_reporter/crash_reporter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#if defined(_WIN64)
#include "shell/common/crash_reporter/crash_reporter_win.h"
#endif
namespace {
// Initialize Node.js cli options to pass to Node.js
// See https://nodejs.org/api/cli.html#cli_options
void SetNodeCliFlags() {
// Options that are unilaterally disallowed
const std::unordered_set<base::StringPiece, base::StringPieceHash>
disallowed = {"--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
"--force-fips", "--enable-fips"};
const auto argv = base::CommandLine::ForCurrentProcess()->argv();
std::vector<std::string> args;
// TODO(codebytere): We need to set the first entry in args to the
// process name owing to src/node_options-inl.h#L286-L290 but this is
// redundant and so should be refactored upstream.
args.reserve(argv.size() + 1);
args.emplace_back("electron");
for (const auto& arg : argv) {
#if defined(OS_WIN)
const auto& option = base::UTF16ToUTF8(arg);
#else
const auto& option = arg;
#endif
const auto stripped = base::StringPiece(option).substr(0, option.find('='));
if (disallowed.count(stripped) != 0) {
LOG(ERROR) << "The Node.js cli flag " << stripped
<< " is not supported in Electron";
} else {
args.push_back(option);
}
}
std::vector<std::string> errors;
// Node.js itself will output parsing errors to
// console so we don't need to handle that ourselves
ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment);
}
} // namespace
namespace electron {
#if !defined(OS_LINUX)
void AddExtraParameter(const std::string& key, const std::string& value) {
crash_reporter::CrashReporter::GetInstance()->AddExtraParameter(key, value);
}
void RemoveExtraParameter(const std::string& key) {
crash_reporter::CrashReporter::GetInstance()->RemoveExtraParameter(key);
}
#endif
2018-04-18 01:55:30 +00:00
int NodeMain(int argc, char* argv[]) {
base::CommandLine::Init(argc, argv);
int exit_code = 1;
{
2015-09-03 02:28:50 +00:00
// Feed gin::PerIsolateData with a task runner.
argv = uv_setup_args(argc, argv);
2015-09-03 02:28:50 +00:00
uv_loop_t* loop = uv_default_loop();
scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
auto feature_list = std::make_unique<base::FeatureList>();
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
#if defined(_WIN64)
crash_reporter::CrashReporterWin::SetUnhandledExceptionFilter();
#endif
// Explicitly register electron's builtin modules.
NodeBindings::RegisterBuiltinModules();
// Parse and set Node.js cli flags.
SetNodeCliFlags();
int exec_argc;
const char** exec_argv;
node::Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
2019-07-23 18:40:06 +00:00
gin::V8Initializer::LoadV8Snapshot(
gin::V8Initializer::V8SnapshotFileType::kWithAdditionalContext);
// V8 requires a task scheduler apparently
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
// Initialize gin::IsolateHolder.
JavascriptEnvironment gin_env(loop);
node::IsolateData* isolate_data =
node::CreateIsolateData(gin_env.isolate(), loop, gin_env.platform());
CHECK_NE(nullptr, isolate_data);
node::Environment* env =
node::CreateEnvironment(isolate_data, gin_env.context(), argc, argv,
exec_argc, exec_argv, false);
CHECK_NE(nullptr, env);
// Enable support for v8 inspector.
NodeDebugger node_debugger(env);
node_debugger.Start();
node::BootstrapEnvironment(env);
gin_helper::Dictionary process(gin_env.isolate(), env->process_object());
#if defined(OS_WIN)
process.SetMethod("log", &ElectronBindings::Log);
2016-10-12 20:01:17 +00:00
#endif
process.SetMethod("crash", &ElectronBindings::Crash);
2015-04-20 06:10:15 +00:00
2017-01-24 21:58:39 +00:00
// Setup process.crashReporter.start in child node processes
gin_helper::Dictionary reporter =
gin::Dictionary::CreateEmpty(gin_env.isolate());
2017-01-24 21:58:39 +00:00
reporter.SetMethod("start", &crash_reporter::CrashReporter::StartInstance);
#if !defined(OS_LINUX)
reporter.SetMethod("addExtraParameter", &AddExtraParameter);
reporter.SetMethod("removeExtraParameter", &RemoveExtraParameter);
#endif
2017-01-24 21:58:39 +00:00
process.Set("crashReporter", reporter);
2016-12-09 09:44:12 +00:00
gin_helper::Dictionary versions;
if (process.Get("versions", &versions)) {
versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
}
2016-10-12 16:33:28 +00:00
node::LoadEnvironment(env);
v8::Isolate* isolate = env->isolate();
{
v8::SealHandleScope seal(isolate);
bool more;
do {
uv_run(env->event_loop(), UV_RUN_DEFAULT);
gin_env.platform()->DrainTasks(env->isolate());
more = uv_loop_alive(env->event_loop());
if (more && !env->is_stopping())
continue;
if (!uv_loop_alive(env->event_loop())) {
EmitBeforeExit(env);
}
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
} while (more && !env->is_stopping());
}
node_debugger.Stop();
exit_code = node::EmitExit(env);
node::ResetStdio();
env->set_can_call_into_js(false);
env->stop_sub_worker_contexts();
env->RunCleanup();
node::RunAtExit(env);
2016-07-21 07:43:21 +00:00
node::FreeEnvironment(env);
node::FreeIsolateData(isolate_data);
gin_env.platform()->DrainTasks(isolate);
gin_env.platform()->CancelPendingDelayedTasks(isolate);
gin_env.platform()->UnregisterIsolate(isolate);
}
// According to "src/gin/shell/gin_main.cc":
//
chore: bump chromium to 1e9f9a24aa12 (master) (#17880) * chore: bump chromium in DEPS to 1e9f9a24aa12bea9cf194a82a7e249bd1242ec4f * chore: update patches * Make WebContents' theme color a base::Optional<SkColor> https://chromium-review.googlesource.com/c/chromium/src/+/1540022 * update autofill patch for incorrect header includes * Move Shell messages to web_test and rename to BlinkTest. https://chromium-review.googlesource.com/c/chromium/src/+/1525181 * Make PlatformNotificationServiceImpl a KeyedService. https://chromium-review.googlesource.com/c/chromium/src/+/1336150 * Move MediaPlayerId to its own file. https://chromium-review.googlesource.com/c/chromium/src/+/1547057 * Remove net/base/completion_callback.h, which is no longer used https://chromium-review.googlesource.com/c/chromium/src/+/1552821 * AW NS: support file scheme cookies https://chromium-review.googlesource.com/c/chromium/src/+/1533486 * Remove SecurityInfo and adapt remaining consumers https://chromium-review.googlesource.com/c/chromium/src/+/1509455 * Remove deprecated type-specific number to string conversion functions https://chromium-review.googlesource.com/c/chromium/src/+/1545881 * DevTools: Adding new performance histograms for launch of top 4 tools https://chromium-review.googlesource.com/c/chromium/src/+/1506388 * Update include paths for //base/hash/hash.h https://chromium-review.googlesource.com/c/chromium/src/+/1544630 * build: Disable ensure_gn_version gclient hook for mac CI checkout * update patches * use maybe version of v8::String::NewFromTwoByte * bump appveyor image version * fix mac ci hopefully * Convert enum to enum class for MenuAnchorPosition https://chromium-review.googlesource.com/c/chromium/src/+/1530508 * use maybe version of ToObject * RenderViewHost::GetProcess is no longer const * Unrefcount AuthChallengeInfo https://chromium-review.googlesource.com/c/chromium/src/+/1550631 * MenuButtonController takes Button rather than MenuButton https://chromium-review.googlesource.com/c/chromium/src/+/1500935 * add //ui/views_bridge_mac to deps to fix link error * forward declare views::Button in atom::MenuDelegate * more v8 patches * base/{=> hash}/md5.h https://chromium-review.googlesource.com/c/chromium/src/+/1535124 * gfx::{PlatformFontWin => win}::* https://chromium-review.googlesource.com/c/chromium/src/+/1534178 * fix v8 patches * [base] Rename TaskScheduler to ThreadPool https://chromium-review.googlesource.com/c/chromium/src/+/1561552 * use internal_config_base for bytecode_builtins_list_generator avoids windows link errors * FIXME: temporarily disable v8/breakpad integration * FIXME: temporarily disable prevent-will-redirect test * FIXME: disable neon on aarch64 pending crbug.com/953815 * update to account for WebCursor refactor https://chromium-review.googlesource.com/c/chromium/src/+/1562755 * enable stack dumping on appveyor * Revert "FIXME: disable neon on aarch64 pending crbug.com/953815" This reverts commit 57f082026be3d83069f2a2814684abf4dc9e7b53. * fix: remove const qualifiers to match upstream * fix: remove const qualifiers to match upstream in cc files as well * don't throw an error when testing if an object is an object * use non-deprecated Buffer constructor * Remove net::CookieSameSite::DEFAULT_MODE enum value https://chromium-review.googlesource.com/c/chromium/src/+/1567955 * depend on modded dbus-native to work around buffer deprecation https://github.com/sidorares/dbus-native/pull/262 * revert clang roll to fix arm build on linux * fixup! depend on modded dbus-native to work around buffer deprecation need more coffee * update coffee-script * robustify verify-mksnapshot w.r.t. command-line parameters * Revert "robustify verify-mksnapshot w.r.t. command-line parameters" This reverts commit a49af01411f684f6025528d604895c3696e0bc57. * fix mksnapshot by matching args * update patches * TMP: enable rdp on appveyor * Changed ContentBrowserClient::CreateQuotaPermissionContext() to return scoped_refptr. https://chromium-review.googlesource.com/c/chromium/src/+/1569376 * Make content::ResourceType an enum class. https://chromium-review.googlesource.com/c/chromium/src/+/1569345 * fixup! Make content::ResourceType an enum class. * turn off rdp * use net::CompletionRepeatingCallback instead of base::Callback<void(int)> * remove disable_ensure_gn_version_gclient_hook.patch * copy repeating callback instead of std::move * fix lint * add completion_repeating_callback.h include
2019-04-20 17:20:37 +00:00
// gin::IsolateHolder waits for tasks running in ThreadPool in its
// destructor and thus must be destroyed before ThreadPool starts skipping
// CONTINUE_ON_SHUTDOWN tasks.
chore: bump chromium to 2a7aff41ce73adc0eeee67d364989 (master) (#18505) * chore: bump chromium in DEPS to 07463d3cd628b037c11f36022cb4c788db4628e3 * chore: update patches * fix: Don't leak system network context when nw service is disabled https://chromium-review.googlesource.com/c/chromium/src/+/1632494 NetworkService is now deleted by using SequnceLocalStorageSlot on the IO thread when the service is disabled, which expects all associated NetworkContexts on that sequence to be destroyed. * chore: bump chromium in DEPS to 7c16850e7e40990e141f47101b737ec1092175a1 * fix: Destroy all network contexts before primary network context * Simplify out-of-process service registration https://chromium-review.googlesource.com/c/chromium/src/+/1615882 * [ThreadPool] Rename base::ThreadPool to base::ThreadPoolInstance https://chromium-review.googlesource.com/c/chromium/src/+/1634851 * chore: update patches * fix: -Winconsistent-missing-override warnings * chore: bump chromium in DEPS to 93ebfaccc12715df1d5426797998eed0932f7ae1 * Change CreateBrowserMainParts to return unique_ptrs https://chromium-review.googlesource.com/c/chromium/src/+/1632532 * chore: update patches * chore: bump chromium in DEPS to e656555ffb87bdd05e248d0a3ef9dd9d3433e17b * chore: bump chromium in DEPS to 111e7a8d2e3ae9d70e535009d6afb066ac906063 * chore: bump chromium in DEPS to 9b6b84670d32a7aff41ce73adc0eeee67d364989 * chore: update patches * chore: remove ShouldInterceptResourceAsStream as it is removed upstream Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1639597 * chore: remove ResourceDispatcherHostCreated as it is removed upstream Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1610892 * chore: CreateWithStrongBinding --> CreateWithSelfOwnedReceiver Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1636722 * chore: rename all blink media enums Refs: https://chromium-review.googlesource.com/c/chromium/src/+/1639237 * chore: add accidentally removed patch content back
2019-06-04 03:44:12 +00:00
base::ThreadPoolInstance::Get()->Shutdown();
v8::V8::Dispose();
return exit_code;
}
} // namespace electron