electron_bindings.cc 12 KB

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