1. /**
    
  2.  * Copyright (c) Meta Platforms, Inc. and affiliates.
    
  3.  *
    
  4.  * This source code is licensed under the MIT license found in the
    
  5.  * LICENSE file in the root directory of this source tree.
    
  6.  */
    
  7. 
    
  8. #include <node.h>
    
  9. 
    
  10. #include "hardware-counter.h"
    
  11. 
    
  12. namespace PerfCounters {
    
  13. 
    
  14. using HPHP::HardwareCounter;
    
  15. 
    
  16. void Init(const v8::FunctionCallbackInfo<v8::Value>& args) {
    
  17.   // TODO: Allow customizing recorded events
    
  18.   bool enable = true;
    
  19.   std::string events = "";
    
  20.   bool recordSubprocesses = false;
    
  21.   HardwareCounter::Init(enable, events, recordSubprocesses);
    
  22.   HardwareCounter::s_counter.getCheck();
    
  23. }
    
  24. 
    
  25. void GetCounters(const v8::FunctionCallbackInfo<v8::Value>& args) {
    
  26.   v8::Isolate* isolate = args.GetIsolate();
    
  27.   v8::Local<v8::Object> obj = v8::Object::New(isolate);
    
  28.   std::pair<v8::Isolate*, v8::Local<v8::Object>> pair(isolate, obj);
    
  29. 
    
  30.   HardwareCounter::GetPerfEvents(
    
  31.     [](const std::string& key, int64_t value, void* data) {
    
  32.       std::pair<v8::Isolate*, v8::Local<v8::Object>>& pair =
    
  33.         *reinterpret_cast<std::pair<v8::Isolate*, v8::Local<v8::Object>>*>(data);
    
  34.       v8::Isolate* isolate = pair.first;
    
  35.       v8::Local<v8::Object> obj = pair.second;
    
  36.       obj->Set(
    
  37.         v8::String::NewFromUtf8(isolate, key.c_str()),
    
  38.         v8::Number::New(isolate, value)
    
  39.       );
    
  40.     },
    
  41.     &pair);
    
  42. 
    
  43.   args.GetReturnValue().Set(obj);
    
  44. }
    
  45. 
    
  46. void InitModule(v8::Local<v8::Object> exports) {
    
  47.   NODE_SET_METHOD(exports, "init", Init);
    
  48.   NODE_SET_METHOD(exports, "getCounters", GetCounters);
    
  49. }
    
  50. 
    
  51. NODE_MODULE(perfcounters, InitModule)
    
  52. 
    
  53. }