atom_bindings.cc 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 "atom/common/api/atom_bindings.h"
  5. #include <algorithm>
  6. #include <iostream>
  7. #include <string>
  8. #include "atom/common/api/locker.h"
  9. #include "atom/common/atom_version.h"
  10. #include "atom/common/chrome_version.h"
  11. #include "atom/common/native_mate_converters/string16_converter.h"
  12. #include "atom/common/node_includes.h"
  13. #include "base/logging.h"
  14. #include "base/process/process_metrics_iocounters.h"
  15. #include "base/sys_info.h"
  16. #include "native_mate/dictionary.h"
  17. namespace atom {
  18. namespace {
  19. // Dummy class type that used for crashing the program.
  20. struct DummyClass {
  21. bool crash;
  22. };
  23. // Called when there is a fatal error in V8, we just crash the process here so
  24. // we can get the stack trace.
  25. void FatalErrorCallback(const char* location, const char* message) {
  26. LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
  27. AtomBindings::Crash();
  28. }
  29. } // namespace
  30. AtomBindings::AtomBindings(uv_loop_t* loop) {
  31. uv_async_init(loop, &call_next_tick_async_, OnCallNextTick);
  32. call_next_tick_async_.data = this;
  33. metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
  34. }
  35. AtomBindings::~AtomBindings() {
  36. uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr);
  37. }
  38. void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) {
  39. isolate->SetFatalErrorHandler(FatalErrorCallback);
  40. mate::Dictionary dict(isolate, process);
  41. dict.SetMethod("crash", &AtomBindings::Crash);
  42. dict.SetMethod("hang", &Hang);
  43. dict.SetMethod("log", &Log);
  44. dict.SetMethod("getHeapStatistics", &GetHeapStatistics);
  45. dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
  46. dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
  47. dict.SetMethod("getCPUUsage", base::Bind(&AtomBindings::GetCPUUsage,
  48. base::Unretained(this)));
  49. dict.SetMethod("getIOCounters", &GetIOCounters);
  50. #if defined(OS_POSIX)
  51. dict.SetMethod("setFdLimit", &base::SetFdLimit);
  52. #endif
  53. dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop,
  54. base::Unretained(this)));
  55. #if defined(MAS_BUILD)
  56. dict.Set("mas", true);
  57. #endif
  58. mate::Dictionary versions;
  59. if (dict.Get("versions", &versions)) {
  60. // TODO(kevinsawicki): Make read-only in 2.0 to match node
  61. versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING);
  62. versions.Set("chrome", CHROME_VERSION_STRING);
  63. }
  64. }
  65. void AtomBindings::EnvironmentDestroyed(node::Environment* env) {
  66. auto it =
  67. std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env);
  68. if (it != pending_next_ticks_.end())
  69. pending_next_ticks_.erase(it);
  70. }
  71. void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) {
  72. node::Environment* env = node::Environment::GetCurrent(isolate);
  73. if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
  74. pending_next_ticks_.end())
  75. return;
  76. pending_next_ticks_.push_back(env);
  77. uv_async_send(&call_next_tick_async_);
  78. }
  79. // static
  80. void AtomBindings::OnCallNextTick(uv_async_t* handle) {
  81. AtomBindings* self = static_cast<AtomBindings*>(handle->data);
  82. for (std::list<node::Environment*>::const_iterator it =
  83. self->pending_next_ticks_.begin();
  84. it != self->pending_next_ticks_.end(); ++it) {
  85. node::Environment* env = *it;
  86. mate::Locker locker(env->isolate());
  87. v8::Context::Scope context_scope(env->context());
  88. node::InternalCallbackScope scope(
  89. env, v8::Local<v8::Object>(), {0, 0},
  90. node::InternalCallbackScope::kAllowEmptyResource);
  91. }
  92. self->pending_next_ticks_.clear();
  93. }
  94. // static
  95. void AtomBindings::Log(const base::string16& message) {
  96. std::cout << message << std::flush;
  97. }
  98. // static
  99. void AtomBindings::Crash() {
  100. static_cast<DummyClass*>(nullptr)->crash = true;
  101. }
  102. // static
  103. void AtomBindings::Hang() {
  104. for (;;)
  105. base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
  106. }
  107. // static
  108. v8::Local<v8::Value> AtomBindings::GetHeapStatistics(v8::Isolate* isolate) {
  109. v8::HeapStatistics v8_heap_stats;
  110. isolate->GetHeapStatistics(&v8_heap_stats);
  111. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  112. dict.Set("totalHeapSize",
  113. static_cast<double>(v8_heap_stats.total_heap_size() >> 10));
  114. dict.Set(
  115. "totalHeapSizeExecutable",
  116. static_cast<double>(v8_heap_stats.total_heap_size_executable() >> 10));
  117. dict.Set("totalPhysicalSize",
  118. static_cast<double>(v8_heap_stats.total_physical_size() >> 10));
  119. dict.Set("totalAvailableSize",
  120. static_cast<double>(v8_heap_stats.total_available_size() >> 10));
  121. dict.Set("usedHeapSize",
  122. static_cast<double>(v8_heap_stats.used_heap_size() >> 10));
  123. dict.Set("heapSizeLimit",
  124. static_cast<double>(v8_heap_stats.heap_size_limit() >> 10));
  125. dict.Set("mallocedMemory",
  126. static_cast<double>(v8_heap_stats.malloced_memory() >> 10));
  127. dict.Set("peakMallocedMemory",
  128. static_cast<double>(v8_heap_stats.peak_malloced_memory() >> 10));
  129. dict.Set("doesZapGarbage",
  130. static_cast<bool>(v8_heap_stats.does_zap_garbage()));
  131. return dict.GetHandle();
  132. }
  133. // static
  134. v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) {
  135. auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
  136. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  137. dict.Set("workingSetSize",
  138. static_cast<double>(metrics->GetWorkingSetSize() >> 10));
  139. dict.Set("peakWorkingSetSize",
  140. static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10));
  141. size_t private_bytes, shared_bytes;
  142. if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) {
  143. dict.Set("privateBytes", static_cast<double>(private_bytes >> 10));
  144. dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10));
  145. }
  146. return dict.GetHandle();
  147. }
  148. // static
  149. v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate,
  150. mate::Arguments* args) {
  151. base::SystemMemoryInfoKB mem_info;
  152. if (!base::GetSystemMemoryInfo(&mem_info)) {
  153. args->ThrowError("Unable to retrieve system memory information");
  154. return v8::Undefined(isolate);
  155. }
  156. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  157. dict.Set("total", mem_info.total);
  158. // See Chromium's "base/process/process_metrics.h" for an explanation.
  159. int free =
  160. #if defined(OS_WIN)
  161. mem_info.avail_phys;
  162. #else
  163. mem_info.free;
  164. #endif
  165. dict.Set("free", free);
  166. // NB: These return bogus values on macOS
  167. #if !defined(OS_MACOSX)
  168. dict.Set("swapTotal", mem_info.swap_total);
  169. dict.Set("swapFree", mem_info.swap_free);
  170. #endif
  171. return dict.GetHandle();
  172. }
  173. v8::Local<v8::Value> AtomBindings::GetCPUUsage(v8::Isolate* isolate) {
  174. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  175. int processor_count = base::SysInfo::NumberOfProcessors();
  176. dict.Set("percentCPUUsage",
  177. metrics_->GetPlatformIndependentCPUUsage() / processor_count);
  178. // NB: This will throw NOTIMPLEMENTED() on Windows
  179. // For backwards compatibility, we'll return 0
  180. #if !defined(OS_WIN)
  181. dict.Set("idleWakeupsPerSecond", metrics_->GetIdleWakeupsPerSecond());
  182. #else
  183. dict.Set("idleWakeupsPerSecond", 0);
  184. #endif
  185. return dict.GetHandle();
  186. }
  187. // static
  188. v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) {
  189. auto metrics = base::ProcessMetrics::CreateCurrentProcessMetrics();
  190. base::IoCounters io_counters;
  191. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  192. if (metrics->GetIOCounters(&io_counters)) {
  193. dict.Set("readOperationCount", io_counters.ReadOperationCount);
  194. dict.Set("writeOperationCount", io_counters.WriteOperationCount);
  195. dict.Set("otherOperationCount", io_counters.OtherOperationCount);
  196. dict.Set("readTransferCount", io_counters.ReadTransferCount);
  197. dict.Set("writeTransferCount", io_counters.WriteTransferCount);
  198. dict.Set("otherTransferCount", io_counters.OtherTransferCount);
  199. }
  200. return dict.GetHandle();
  201. }
  202. } // namespace atom