electron_bindings.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/common/api/electron_bindings.h"
  5. #include <algorithm>
  6. #include <iostream>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10. #include "base/logging.h"
  11. #include "base/process/process.h"
  12. #include "base/process/process_handle.h"
  13. #include "base/process/process_metrics_iocounters.h"
  14. #include "base/system/sys_info.h"
  15. #include "base/threading/thread_restrictions.h"
  16. #include "chrome/common/chrome_version.h"
  17. #include "electron/electron_version.h"
  18. #include "services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h"
  19. #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
  20. #include "shell/browser/browser.h"
  21. #include "shell/common/application_info.h"
  22. #include "shell/common/gin_converters/file_path_converter.h"
  23. #include "shell/common/gin_helper/dictionary.h"
  24. #include "shell/common/gin_helper/locker.h"
  25. #include "shell/common/gin_helper/microtasks_scope.h"
  26. #include "shell/common/gin_helper/promise.h"
  27. #include "shell/common/heap_snapshot.h"
  28. #include "shell/common/node_includes.h"
  29. #include "third_party/blink/renderer/platform/heap/process_heap.h" // nogncheck
  30. #if !defined(MAS_BUILD)
  31. #include "shell/common/crash_keys.h"
  32. #endif
  33. namespace electron {
  34. namespace {
  35. // Called when there is a fatal error in V8, we just crash the process here so
  36. // we can get the stack trace.
  37. void V8FatalErrorCallback(const char* location, const char* message) {
  38. LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
  39. #if !defined(MAS_BUILD)
  40. crash_keys::SetCrashKey("electron.v8-fatal.message", message);
  41. crash_keys::SetCrashKey("electron.v8-fatal.location", location);
  42. #endif
  43. volatile int* zero = nullptr;
  44. *zero = 0;
  45. }
  46. } // namespace
  47. ElectronBindings::ElectronBindings(uv_loop_t* loop) {
  48. uv_async_init(loop, call_next_tick_async_.get(), OnCallNextTick);
  49. call_next_tick_async_.get()->data = this;
  50. metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
  51. }
  52. ElectronBindings::~ElectronBindings() {}
  53. // static
  54. void ElectronBindings::BindProcess(v8::Isolate* isolate,
  55. gin_helper::Dictionary* process,
  56. base::ProcessMetrics* metrics) {
  57. // These bindings are shared between sandboxed & unsandboxed renderers
  58. process->SetMethod("crash", &Crash);
  59. process->SetMethod("hang", &Hang);
  60. process->SetMethod("log", &Log);
  61. process->SetMethod("getCreationTime", &GetCreationTime);
  62. process->SetMethod("getHeapStatistics", &GetHeapStatistics);
  63. process->SetMethod("getBlinkMemoryInfo", &GetBlinkMemoryInfo);
  64. process->SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
  65. process->SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
  66. process->SetMethod("getSystemVersion",
  67. &base::SysInfo::OperatingSystemVersion);
  68. process->SetMethod("getIOCounters", &GetIOCounters);
  69. process->SetMethod("getCPUUsage",
  70. base::BindRepeating(&ElectronBindings::GetCPUUsage,
  71. base::Unretained(metrics)));
  72. #if defined(MAS_BUILD)
  73. process->SetReadOnly("mas", true);
  74. #endif
  75. #if defined(OS_WIN)
  76. if (IsRunningInDesktopBridge())
  77. process->SetReadOnly("windowsStore", true);
  78. #endif
  79. }
  80. void ElectronBindings::BindTo(v8::Isolate* isolate,
  81. v8::Local<v8::Object> process) {
  82. isolate->SetFatalErrorHandler(V8FatalErrorCallback);
  83. gin_helper::Dictionary dict(isolate, process);
  84. BindProcess(isolate, &dict, metrics_.get());
  85. dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot);
  86. #if defined(OS_POSIX)
  87. dict.SetMethod("setFdLimit", &base::IncreaseFdLimitTo);
  88. #endif
  89. dict.SetMethod("activateUvLoop",
  90. base::BindRepeating(&ElectronBindings::ActivateUVLoop,
  91. base::Unretained(this)));
  92. gin_helper::Dictionary versions;
  93. if (dict.Get("versions", &versions)) {
  94. versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
  95. versions.SetReadOnly("chrome", CHROME_VERSION_STRING);
  96. }
  97. }
  98. void ElectronBindings::EnvironmentDestroyed(node::Environment* env) {
  99. auto it =
  100. std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env);
  101. if (it != pending_next_ticks_.end())
  102. pending_next_ticks_.erase(it);
  103. }
  104. void ElectronBindings::ActivateUVLoop(v8::Isolate* isolate) {
  105. node::Environment* env = node::Environment::GetCurrent(isolate);
  106. if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
  107. pending_next_ticks_.end())
  108. return;
  109. pending_next_ticks_.push_back(env);
  110. uv_async_send(call_next_tick_async_.get());
  111. }
  112. // static
  113. void ElectronBindings::OnCallNextTick(uv_async_t* handle) {
  114. auto* self = static_cast<ElectronBindings*>(handle->data);
  115. for (auto* env : self->pending_next_ticks_) {
  116. gin_helper::Locker locker(env->isolate());
  117. v8::Context::Scope context_scope(env->context());
  118. node::InternalCallbackScope scope(
  119. env, v8::Local<v8::Object>(), {0, 0},
  120. node::InternalCallbackScope::kAllowEmptyResource);
  121. }
  122. self->pending_next_ticks_.clear();
  123. }
  124. // static
  125. void ElectronBindings::Log(const base::string16& message) {
  126. std::cout << message << std::flush;
  127. }
  128. // static
  129. void ElectronBindings::Crash() {
  130. volatile int* zero = nullptr;
  131. *zero = 0;
  132. }
  133. // static
  134. void ElectronBindings::Hang() {
  135. for (;;)
  136. base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
  137. }
  138. // static
  139. v8::Local<v8::Value> ElectronBindings::GetHeapStatistics(v8::Isolate* isolate) {
  140. v8::HeapStatistics v8_heap_stats;
  141. isolate->GetHeapStatistics(&v8_heap_stats);
  142. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  143. dict.SetHidden("simple", true);
  144. dict.Set("totalHeapSize",
  145. static_cast<double>(v8_heap_stats.total_heap_size() >> 10));
  146. dict.Set(
  147. "totalHeapSizeExecutable",
  148. static_cast<double>(v8_heap_stats.total_heap_size_executable() >> 10));
  149. dict.Set("totalPhysicalSize",
  150. static_cast<double>(v8_heap_stats.total_physical_size() >> 10));
  151. dict.Set("totalAvailableSize",
  152. static_cast<double>(v8_heap_stats.total_available_size() >> 10));
  153. dict.Set("usedHeapSize",
  154. static_cast<double>(v8_heap_stats.used_heap_size() >> 10));
  155. dict.Set("heapSizeLimit",
  156. static_cast<double>(v8_heap_stats.heap_size_limit() >> 10));
  157. dict.Set("mallocedMemory",
  158. static_cast<double>(v8_heap_stats.malloced_memory() >> 10));
  159. dict.Set("peakMallocedMemory",
  160. static_cast<double>(v8_heap_stats.peak_malloced_memory() >> 10));
  161. dict.Set("doesZapGarbage",
  162. static_cast<bool>(v8_heap_stats.does_zap_garbage()));
  163. return dict.GetHandle();
  164. }
  165. // static
  166. v8::Local<v8::Value> ElectronBindings::GetCreationTime(v8::Isolate* isolate) {
  167. auto timeValue = base::Process::Current().CreationTime();
  168. if (timeValue.is_null()) {
  169. return v8::Null(isolate);
  170. }
  171. double jsTime = timeValue.ToJsTime();
  172. return v8::Number::New(isolate, jsTime);
  173. }
  174. // static
  175. v8::Local<v8::Value> ElectronBindings::GetSystemMemoryInfo(
  176. v8::Isolate* isolate,
  177. gin_helper::Arguments* args) {
  178. base::SystemMemoryInfoKB mem_info;
  179. if (!base::GetSystemMemoryInfo(&mem_info)) {
  180. args->ThrowError("Unable to retrieve system memory information");
  181. return v8::Undefined(isolate);
  182. }
  183. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  184. dict.SetHidden("simple", true);
  185. dict.Set("total", mem_info.total);
  186. // See Chromium's "base/process/process_metrics.h" for an explanation.
  187. int free =
  188. #if defined(OS_WIN)
  189. mem_info.avail_phys;
  190. #else
  191. mem_info.free;
  192. #endif
  193. dict.Set("free", free);
  194. // NB: These return bogus values on macOS
  195. #if !defined(OS_MACOSX)
  196. dict.Set("swapTotal", mem_info.swap_total);
  197. dict.Set("swapFree", mem_info.swap_free);
  198. #endif
  199. return dict.GetHandle();
  200. }
  201. // static
  202. v8::Local<v8::Promise> ElectronBindings::GetProcessMemoryInfo(
  203. v8::Isolate* isolate) {
  204. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  205. v8::Local<v8::Promise> handle = promise.GetHandle();
  206. if (gin_helper::Locker::IsBrowserProcess() && !Browser::Get()->is_ready()) {
  207. promise.RejectWithErrorMessage(
  208. "Memory Info is available only after app ready");
  209. return handle;
  210. }
  211. v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
  212. memory_instrumentation::MemoryInstrumentation::GetInstance()
  213. ->RequestGlobalDumpForPid(
  214. base::GetCurrentProcId(), std::vector<std::string>(),
  215. base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
  216. std::move(context), std::move(promise)));
  217. return handle;
  218. }
  219. // static
  220. v8::Local<v8::Value> ElectronBindings::GetBlinkMemoryInfo(
  221. v8::Isolate* isolate) {
  222. auto allocated = blink::ProcessHeap::TotalAllocatedObjectSize();
  223. auto total = blink::ProcessHeap::TotalAllocatedSpace();
  224. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  225. dict.SetHidden("simple", true);
  226. dict.Set("allocated", static_cast<double>(allocated >> 10));
  227. dict.Set("total", static_cast<double>(total >> 10));
  228. return dict.GetHandle();
  229. }
  230. // static
  231. void ElectronBindings::DidReceiveMemoryDump(
  232. v8::Global<v8::Context> context,
  233. gin_helper::Promise<gin_helper::Dictionary> promise,
  234. bool success,
  235. std::unique_ptr<memory_instrumentation::GlobalMemoryDump> global_dump) {
  236. v8::Isolate* isolate = promise.isolate();
  237. gin_helper::Locker locker(isolate);
  238. v8::HandleScope handle_scope(isolate);
  239. gin_helper::MicrotasksScope microtasks_scope(isolate, true);
  240. v8::Context::Scope context_scope(
  241. v8::Local<v8::Context>::New(isolate, context));
  242. if (!success) {
  243. promise.RejectWithErrorMessage("Failed to create memory dump");
  244. return;
  245. }
  246. bool resolved = false;
  247. for (const memory_instrumentation::GlobalMemoryDump::ProcessDump& dump :
  248. global_dump->process_dumps()) {
  249. if (base::GetCurrentProcId() == dump.pid()) {
  250. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  251. const auto& osdump = dump.os_dump();
  252. #if defined(OS_LINUX) || defined(OS_WIN)
  253. dict.Set("residentSet", osdump.resident_set_kb);
  254. #endif
  255. dict.Set("private", osdump.private_footprint_kb);
  256. dict.Set("shared", osdump.shared_footprint_kb);
  257. promise.Resolve(dict);
  258. resolved = true;
  259. break;
  260. }
  261. }
  262. if (!resolved) {
  263. promise.RejectWithErrorMessage(
  264. R"(Failed to find current process memory details in memory dump)");
  265. }
  266. }
  267. // static
  268. v8::Local<v8::Value> ElectronBindings::GetCPUUsage(
  269. base::ProcessMetrics* metrics,
  270. v8::Isolate* isolate) {
  271. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  272. dict.SetHidden("simple", true);
  273. int processor_count = base::SysInfo::NumberOfProcessors();
  274. dict.Set("percentCPUUsage",
  275. metrics->GetPlatformIndependentCPUUsage() / processor_count);
  276. // NB: This will throw NOTIMPLEMENTED() on Windows
  277. // For backwards compatibility, we'll return 0
  278. #if !defined(OS_WIN)
  279. dict.Set("idleWakeupsPerSecond", metrics->GetIdleWakeupsPerSecond());
  280. #else
  281. dict.Set("idleWakeupsPerSecond", 0);
  282. #endif
  283. return dict.GetHandle();
  284. }
  285. // static
  286. v8::Local<v8::Value> ElectronBindings::GetIOCounters(v8::Isolate* isolate) {
  287. auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
  288. base::IoCounters io_counters;
  289. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  290. dict.SetHidden("simple", true);
  291. if (metrics->GetIOCounters(&io_counters)) {
  292. dict.Set("readOperationCount", io_counters.ReadOperationCount);
  293. dict.Set("writeOperationCount", io_counters.WriteOperationCount);
  294. dict.Set("otherOperationCount", io_counters.OtherOperationCount);
  295. dict.Set("readTransferCount", io_counters.ReadTransferCount);
  296. dict.Set("writeTransferCount", io_counters.WriteTransferCount);
  297. dict.Set("otherTransferCount", io_counters.OtherTransferCount);
  298. }
  299. return dict.GetHandle();
  300. }
  301. // static
  302. bool ElectronBindings::TakeHeapSnapshot(v8::Isolate* isolate,
  303. const base::FilePath& file_path) {
  304. base::ThreadRestrictions::ScopedAllowIO allow_io;
  305. base::File file(file_path,
  306. base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  307. return electron::TakeHeapSnapshot(isolate, &file);
  308. }
  309. } // namespace electron