Turn audio into a shareable video. forked from nypublicradio/audiogram

v8-profiler.h 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. // Copyright 2010 the V8 project authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef V8_V8_PROFILER_H_
  5. #define V8_V8_PROFILER_H_
  6. #include <limits.h>
  7. #include <unordered_set>
  8. #include <vector>
  9. #include "v8.h" // NOLINT(build/include)
  10. /**
  11. * Profiler support for the V8 JavaScript engine.
  12. */
  13. namespace v8 {
  14. class HeapGraphNode;
  15. struct HeapStatsUpdate;
  16. typedef uint32_t SnapshotObjectId;
  17. struct CpuProfileDeoptFrame {
  18. int script_id;
  19. size_t position;
  20. };
  21. } // namespace v8
  22. #ifdef V8_OS_WIN
  23. template class V8_EXPORT std::vector<v8::CpuProfileDeoptFrame>;
  24. #endif
  25. namespace v8 {
  26. struct V8_EXPORT CpuProfileDeoptInfo {
  27. /** A pointer to a static string owned by v8. */
  28. const char* deopt_reason;
  29. std::vector<CpuProfileDeoptFrame> stack;
  30. };
  31. } // namespace v8
  32. #ifdef V8_OS_WIN
  33. template class V8_EXPORT std::vector<v8::CpuProfileDeoptInfo>;
  34. #endif
  35. namespace v8 {
  36. // TickSample captures the information collected for each sample.
  37. struct V8_EXPORT TickSample {
  38. // Internal profiling (with --prof + tools/$OS-tick-processor) wants to
  39. // include the runtime function we're calling. Externally exposed tick
  40. // samples don't care.
  41. enum RecordCEntryFrame { kIncludeCEntryFrame, kSkipCEntryFrame };
  42. TickSample()
  43. : state(OTHER),
  44. pc(nullptr),
  45. external_callback_entry(nullptr),
  46. frames_count(0),
  47. has_external_callback(false),
  48. update_stats(true) {}
  49. /**
  50. * Initialize a tick sample from the isolate.
  51. * \param isolate The isolate.
  52. * \param state Execution state.
  53. * \param record_c_entry_frame Include or skip the runtime function.
  54. * \param update_stats Whether update the sample to the aggregated stats.
  55. * \param use_simulator_reg_state When set to true and V8 is running under a
  56. * simulator, the method will use the simulator
  57. * register state rather than the one provided
  58. * with |state| argument. Otherwise the method
  59. * will use provided register |state| as is.
  60. */
  61. void Init(Isolate* isolate, const v8::RegisterState& state,
  62. RecordCEntryFrame record_c_entry_frame, bool update_stats,
  63. bool use_simulator_reg_state = true);
  64. /**
  65. * Get a call stack sample from the isolate.
  66. * \param isolate The isolate.
  67. * \param state Register state.
  68. * \param record_c_entry_frame Include or skip the runtime function.
  69. * \param frames Caller allocated buffer to store stack frames.
  70. * \param frames_limit Maximum number of frames to capture. The buffer must
  71. * be large enough to hold the number of frames.
  72. * \param sample_info The sample info is filled up by the function
  73. * provides number of actual captured stack frames and
  74. * the current VM state.
  75. * \param use_simulator_reg_state When set to true and V8 is running under a
  76. * simulator, the method will use the simulator
  77. * register state rather than the one provided
  78. * with |state| argument. Otherwise the method
  79. * will use provided register |state| as is.
  80. * \note GetStackSample is thread and signal safe and should only be called
  81. * when the JS thread is paused or interrupted.
  82. * Otherwise the behavior is undefined.
  83. */
  84. static bool GetStackSample(Isolate* isolate, v8::RegisterState* state,
  85. RecordCEntryFrame record_c_entry_frame,
  86. void** frames, size_t frames_limit,
  87. v8::SampleInfo* sample_info,
  88. bool use_simulator_reg_state = true);
  89. StateTag state; // The state of the VM.
  90. void* pc; // Instruction pointer.
  91. union {
  92. void* tos; // Top stack value (*sp).
  93. void* external_callback_entry;
  94. };
  95. static const unsigned kMaxFramesCountLog2 = 8;
  96. static const unsigned kMaxFramesCount = (1 << kMaxFramesCountLog2) - 1;
  97. void* stack[kMaxFramesCount]; // Call stack.
  98. unsigned frames_count : kMaxFramesCountLog2; // Number of captured frames.
  99. bool has_external_callback : 1;
  100. bool update_stats : 1; // Whether the sample should update aggregated stats.
  101. };
  102. /**
  103. * CpuProfileNode represents a node in a call graph.
  104. */
  105. class V8_EXPORT CpuProfileNode {
  106. public:
  107. struct LineTick {
  108. /** The 1-based number of the source line where the function originates. */
  109. int line;
  110. /** The count of samples associated with the source line. */
  111. unsigned int hit_count;
  112. };
  113. // An annotation hinting at the source of a CpuProfileNode.
  114. enum SourceType {
  115. // User-supplied script with associated resource information.
  116. kScript = 0,
  117. // Native scripts and provided builtins.
  118. kBuiltin = 1,
  119. // Callbacks into native code.
  120. kCallback = 2,
  121. // VM-internal functions or state.
  122. kInternal = 3,
  123. // A node that failed to symbolize.
  124. kUnresolved = 4,
  125. };
  126. /** Returns function name (empty string for anonymous functions.) */
  127. Local<String> GetFunctionName() const;
  128. /**
  129. * Returns function name (empty string for anonymous functions.)
  130. * The string ownership is *not* passed to the caller. It stays valid until
  131. * profile is deleted. The function is thread safe.
  132. */
  133. const char* GetFunctionNameStr() const;
  134. /** Returns id of the script where function is located. */
  135. int GetScriptId() const;
  136. /** Returns resource name for script from where the function originates. */
  137. Local<String> GetScriptResourceName() const;
  138. /**
  139. * Returns resource name for script from where the function originates.
  140. * The string ownership is *not* passed to the caller. It stays valid until
  141. * profile is deleted. The function is thread safe.
  142. */
  143. const char* GetScriptResourceNameStr() const;
  144. /**
  145. * Return true if the script from where the function originates is flagged as
  146. * being shared cross-origin.
  147. */
  148. bool IsScriptSharedCrossOrigin() const;
  149. /**
  150. * Returns the number, 1-based, of the line where the function originates.
  151. * kNoLineNumberInfo if no line number information is available.
  152. */
  153. int GetLineNumber() const;
  154. /**
  155. * Returns 1-based number of the column where the function originates.
  156. * kNoColumnNumberInfo if no column number information is available.
  157. */
  158. int GetColumnNumber() const;
  159. /**
  160. * Returns the number of the function's source lines that collect the samples.
  161. */
  162. unsigned int GetHitLineCount() const;
  163. /** Returns the set of source lines that collect the samples.
  164. * The caller allocates buffer and responsible for releasing it.
  165. * True if all available entries are copied, otherwise false.
  166. * The function copies nothing if buffer is not large enough.
  167. */
  168. bool GetLineTicks(LineTick* entries, unsigned int length) const;
  169. /** Returns bailout reason for the function
  170. * if the optimization was disabled for it.
  171. */
  172. const char* GetBailoutReason() const;
  173. /**
  174. * Returns the count of samples where the function was currently executing.
  175. */
  176. unsigned GetHitCount() const;
  177. /** Returns function entry UID. */
  178. V8_DEPRECATE_SOON(
  179. "Use GetScriptId, GetLineNumber, and GetColumnNumber instead.",
  180. unsigned GetCallUid() const);
  181. /** Returns id of the node. The id is unique within the tree */
  182. unsigned GetNodeId() const;
  183. /**
  184. * Gets the type of the source which the node was captured from.
  185. */
  186. SourceType GetSourceType() const;
  187. /** Returns child nodes count of the node. */
  188. int GetChildrenCount() const;
  189. /** Retrieves a child node by index. */
  190. const CpuProfileNode* GetChild(int index) const;
  191. /** Retrieves the ancestor node, or null if the root. */
  192. const CpuProfileNode* GetParent() const;
  193. /** Retrieves deopt infos for the node. */
  194. const std::vector<CpuProfileDeoptInfo>& GetDeoptInfos() const;
  195. static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
  196. static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
  197. };
  198. /**
  199. * CpuProfile contains a CPU profile in a form of top-down call tree
  200. * (from main() down to functions that do all the work).
  201. */
  202. class V8_EXPORT CpuProfile {
  203. public:
  204. /** Returns CPU profile title. */
  205. Local<String> GetTitle() const;
  206. /** Returns the root node of the top down call tree. */
  207. const CpuProfileNode* GetTopDownRoot() const;
  208. /**
  209. * Returns number of samples recorded. The samples are not recorded unless
  210. * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
  211. */
  212. int GetSamplesCount() const;
  213. /**
  214. * Returns profile node corresponding to the top frame the sample at
  215. * the given index.
  216. */
  217. const CpuProfileNode* GetSample(int index) const;
  218. /**
  219. * Returns the timestamp of the sample. The timestamp is the number of
  220. * microseconds since some unspecified starting point.
  221. * The point is equal to the starting point used by GetStartTime.
  222. */
  223. int64_t GetSampleTimestamp(int index) const;
  224. /**
  225. * Returns time when the profile recording was started (in microseconds)
  226. * since some unspecified starting point.
  227. */
  228. int64_t GetStartTime() const;
  229. /**
  230. * Returns time when the profile recording was stopped (in microseconds)
  231. * since some unspecified starting point.
  232. * The point is equal to the starting point used by GetStartTime.
  233. */
  234. int64_t GetEndTime() const;
  235. /**
  236. * Deletes the profile and removes it from CpuProfiler's list.
  237. * All pointers to nodes previously returned become invalid.
  238. */
  239. void Delete();
  240. };
  241. enum CpuProfilingMode {
  242. // In the resulting CpuProfile tree, intermediate nodes in a stack trace
  243. // (from the root to a leaf) will have line numbers that point to the start
  244. // line of the function, rather than the line of the callsite of the child.
  245. kLeafNodeLineNumbers,
  246. // In the resulting CpuProfile tree, nodes are separated based on the line
  247. // number of their callsite in their parent.
  248. kCallerLineNumbers,
  249. };
  250. // Determines how names are derived for functions sampled.
  251. enum CpuProfilingNamingMode {
  252. // Use the immediate name of functions at compilation time.
  253. kStandardNaming,
  254. // Use more verbose naming for functions without names, inferred from scope
  255. // where possible.
  256. kDebugNaming,
  257. };
  258. /**
  259. * Optional profiling attributes.
  260. */
  261. class V8_EXPORT CpuProfilingOptions {
  262. public:
  263. // Indicates that the sample buffer size should not be explicitly limited.
  264. static const unsigned kNoSampleLimit = UINT_MAX;
  265. /**
  266. * \param mode Type of computation of stack frame line numbers.
  267. * \param max_samples The maximum number of samples that should be recorded by
  268. * the profiler. Samples obtained after this limit will be
  269. * discarded.
  270. * \param sampling_interval_us controls the profile-specific target
  271. * sampling interval. The provided sampling
  272. * interval will be snapped to the next lowest
  273. * non-zero multiple of the profiler's sampling
  274. * interval, set via SetSamplingInterval(). If
  275. * zero, the sampling interval will be equal to
  276. * the profiler's sampling interval.
  277. */
  278. CpuProfilingOptions(CpuProfilingMode mode = kLeafNodeLineNumbers,
  279. unsigned max_samples = kNoSampleLimit,
  280. int sampling_interval_us = 0)
  281. : mode_(mode),
  282. max_samples_(max_samples),
  283. sampling_interval_us_(sampling_interval_us) {}
  284. CpuProfilingMode mode() const { return mode_; }
  285. unsigned max_samples() const { return max_samples_; }
  286. int sampling_interval_us() const { return sampling_interval_us_; }
  287. private:
  288. CpuProfilingMode mode_;
  289. unsigned max_samples_;
  290. int sampling_interval_us_;
  291. };
  292. /**
  293. * Interface for controlling CPU profiling. Instance of the
  294. * profiler can be created using v8::CpuProfiler::New method.
  295. */
  296. class V8_EXPORT CpuProfiler {
  297. public:
  298. /**
  299. * Creates a new CPU profiler for the |isolate|. The isolate must be
  300. * initialized. The profiler object must be disposed after use by calling
  301. * |Dispose| method.
  302. */
  303. static CpuProfiler* New(Isolate* isolate);
  304. static CpuProfiler* New(Isolate* isolate,
  305. CpuProfilingNamingMode mode);
  306. /**
  307. * Synchronously collect current stack sample in all profilers attached to
  308. * the |isolate|. The call does not affect number of ticks recorded for
  309. * the current top node.
  310. */
  311. static void CollectSample(Isolate* isolate);
  312. /**
  313. * Disposes the CPU profiler object.
  314. */
  315. void Dispose();
  316. /**
  317. * Changes default CPU profiler sampling interval to the specified number
  318. * of microseconds. Default interval is 1000us. This method must be called
  319. * when there are no profiles being recorded.
  320. */
  321. void SetSamplingInterval(int us);
  322. /**
  323. * Sets whether or not the profiler should prioritize consistency of sample
  324. * periodicity on Windows. Disabling this can greatly reduce CPU usage, but
  325. * may result in greater variance in sample timings from the platform's
  326. * scheduler. Defaults to enabled. This method must be called when there are
  327. * no profiles being recorded.
  328. */
  329. void SetUsePreciseSampling(bool);
  330. /**
  331. * Starts collecting a CPU profile. Title may be an empty string. Several
  332. * profiles may be collected at once. Attempts to start collecting several
  333. * profiles with the same title are silently ignored.
  334. */
  335. void StartProfiling(Local<String> title, CpuProfilingOptions options);
  336. /**
  337. * Starts profiling with the same semantics as above, except with expanded
  338. * parameters.
  339. *
  340. * |record_samples| parameter controls whether individual samples should
  341. * be recorded in addition to the aggregated tree.
  342. *
  343. * |max_samples| controls the maximum number of samples that should be
  344. * recorded by the profiler. Samples obtained after this limit will be
  345. * discarded.
  346. */
  347. void StartProfiling(
  348. Local<String> title, CpuProfilingMode mode, bool record_samples = false);
  349. void StartProfiling(
  350. Local<String> title, CpuProfilingMode mode, bool record_samples,
  351. unsigned max_samples);
  352. /**
  353. * The same as StartProfiling above, but the CpuProfilingMode defaults to
  354. * kLeafNodeLineNumbers mode, which was the previous default behavior of the
  355. * profiler.
  356. */
  357. void StartProfiling(Local<String> title, bool record_samples = false);
  358. /**
  359. * Stops collecting CPU profile with a given title and returns it.
  360. * If the title given is empty, finishes the last profile started.
  361. */
  362. CpuProfile* StopProfiling(Local<String> title);
  363. /**
  364. * Force collection of a sample. Must be called on the VM thread.
  365. * Recording the forced sample does not contribute to the aggregated
  366. * profile statistics.
  367. */
  368. V8_DEPRECATED("Use static CollectSample(Isolate*) instead.",
  369. void CollectSample());
  370. /**
  371. * Tells the profiler whether the embedder is idle.
  372. */
  373. V8_DEPRECATED("Use Isolate::SetIdle(bool) instead.",
  374. void SetIdle(bool is_idle));
  375. /**
  376. * Generate more detailed source positions to code objects. This results in
  377. * better results when mapping profiling samples to script source.
  378. */
  379. static void UseDetailedSourcePositionsForProfiling(Isolate* isolate);
  380. private:
  381. CpuProfiler();
  382. ~CpuProfiler();
  383. CpuProfiler(const CpuProfiler&);
  384. CpuProfiler& operator=(const CpuProfiler&);
  385. };
  386. /**
  387. * HeapSnapshotEdge represents a directed connection between heap
  388. * graph nodes: from retainers to retained nodes.
  389. */
  390. class V8_EXPORT HeapGraphEdge {
  391. public:
  392. enum Type {
  393. kContextVariable = 0, // A variable from a function context.
  394. kElement = 1, // An element of an array.
  395. kProperty = 2, // A named object property.
  396. kInternal = 3, // A link that can't be accessed from JS,
  397. // thus, its name isn't a real property name
  398. // (e.g. parts of a ConsString).
  399. kHidden = 4, // A link that is needed for proper sizes
  400. // calculation, but may be hidden from user.
  401. kShortcut = 5, // A link that must not be followed during
  402. // sizes calculation.
  403. kWeak = 6 // A weak reference (ignored by the GC).
  404. };
  405. /** Returns edge type (see HeapGraphEdge::Type). */
  406. Type GetType() const;
  407. /**
  408. * Returns edge name. This can be a variable name, an element index, or
  409. * a property name.
  410. */
  411. Local<Value> GetName() const;
  412. /** Returns origin node. */
  413. const HeapGraphNode* GetFromNode() const;
  414. /** Returns destination node. */
  415. const HeapGraphNode* GetToNode() const;
  416. };
  417. /**
  418. * HeapGraphNode represents a node in a heap graph.
  419. */
  420. class V8_EXPORT HeapGraphNode {
  421. public:
  422. enum Type {
  423. kHidden = 0, // Hidden node, may be filtered when shown to user.
  424. kArray = 1, // An array of elements.
  425. kString = 2, // A string.
  426. kObject = 3, // A JS object (except for arrays and strings).
  427. kCode = 4, // Compiled code.
  428. kClosure = 5, // Function closure.
  429. kRegExp = 6, // RegExp.
  430. kHeapNumber = 7, // Number stored in the heap.
  431. kNative = 8, // Native object (not from V8 heap).
  432. kSynthetic = 9, // Synthetic object, usually used for grouping
  433. // snapshot items together.
  434. kConsString = 10, // Concatenated string. A pair of pointers to strings.
  435. kSlicedString = 11, // Sliced string. A fragment of another string.
  436. kSymbol = 12, // A Symbol (ES6).
  437. kBigInt = 13 // BigInt.
  438. };
  439. /** Returns node type (see HeapGraphNode::Type). */
  440. Type GetType() const;
  441. /**
  442. * Returns node name. Depending on node's type this can be the name
  443. * of the constructor (for objects), the name of the function (for
  444. * closures), string value, or an empty string (for compiled code).
  445. */
  446. Local<String> GetName() const;
  447. /**
  448. * Returns node id. For the same heap object, the id remains the same
  449. * across all snapshots.
  450. */
  451. SnapshotObjectId GetId() const;
  452. /** Returns node's own size, in bytes. */
  453. size_t GetShallowSize() const;
  454. /** Returns child nodes count of the node. */
  455. int GetChildrenCount() const;
  456. /** Retrieves a child by index. */
  457. const HeapGraphEdge* GetChild(int index) const;
  458. };
  459. /**
  460. * An interface for exporting data from V8, using "push" model.
  461. */
  462. class V8_EXPORT OutputStream { // NOLINT
  463. public:
  464. enum WriteResult {
  465. kContinue = 0,
  466. kAbort = 1
  467. };
  468. virtual ~OutputStream() = default;
  469. /** Notify about the end of stream. */
  470. virtual void EndOfStream() = 0;
  471. /** Get preferred output chunk size. Called only once. */
  472. virtual int GetChunkSize() { return 1024; }
  473. /**
  474. * Writes the next chunk of snapshot data into the stream. Writing
  475. * can be stopped by returning kAbort as function result. EndOfStream
  476. * will not be called in case writing was aborted.
  477. */
  478. virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
  479. /**
  480. * Writes the next chunk of heap stats data into the stream. Writing
  481. * can be stopped by returning kAbort as function result. EndOfStream
  482. * will not be called in case writing was aborted.
  483. */
  484. virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
  485. return kAbort;
  486. }
  487. };
  488. /**
  489. * HeapSnapshots record the state of the JS heap at some moment.
  490. */
  491. class V8_EXPORT HeapSnapshot {
  492. public:
  493. enum SerializationFormat {
  494. kJSON = 0 // See format description near 'Serialize' method.
  495. };
  496. /** Returns the root node of the heap graph. */
  497. const HeapGraphNode* GetRoot() const;
  498. /** Returns a node by its id. */
  499. const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
  500. /** Returns total nodes count in the snapshot. */
  501. int GetNodesCount() const;
  502. /** Returns a node by index. */
  503. const HeapGraphNode* GetNode(int index) const;
  504. /** Returns a max seen JS object Id. */
  505. SnapshotObjectId GetMaxSnapshotJSObjectId() const;
  506. /**
  507. * Deletes the snapshot and removes it from HeapProfiler's list.
  508. * All pointers to nodes, edges and paths previously returned become
  509. * invalid.
  510. */
  511. void Delete();
  512. /**
  513. * Prepare a serialized representation of the snapshot. The result
  514. * is written into the stream provided in chunks of specified size.
  515. * The total length of the serialized snapshot is unknown in
  516. * advance, it can be roughly equal to JS heap size (that means,
  517. * it can be really big - tens of megabytes).
  518. *
  519. * For the JSON format, heap contents are represented as an object
  520. * with the following structure:
  521. *
  522. * {
  523. * snapshot: {
  524. * title: "...",
  525. * uid: nnn,
  526. * meta: { meta-info },
  527. * node_count: nnn,
  528. * edge_count: nnn
  529. * },
  530. * nodes: [nodes array],
  531. * edges: [edges array],
  532. * strings: [strings array]
  533. * }
  534. *
  535. * Nodes reference strings, other nodes, and edges by their indexes
  536. * in corresponding arrays.
  537. */
  538. void Serialize(OutputStream* stream,
  539. SerializationFormat format = kJSON) const;
  540. };
  541. /**
  542. * An interface for reporting progress and controlling long-running
  543. * activities.
  544. */
  545. class V8_EXPORT ActivityControl { // NOLINT
  546. public:
  547. enum ControlOption {
  548. kContinue = 0,
  549. kAbort = 1
  550. };
  551. virtual ~ActivityControl() = default;
  552. /**
  553. * Notify about current progress. The activity can be stopped by
  554. * returning kAbort as the callback result.
  555. */
  556. virtual ControlOption ReportProgressValue(int done, int total) = 0;
  557. };
  558. /**
  559. * AllocationProfile is a sampled profile of allocations done by the program.
  560. * This is structured as a call-graph.
  561. */
  562. class V8_EXPORT AllocationProfile {
  563. public:
  564. struct Allocation {
  565. /**
  566. * Size of the sampled allocation object.
  567. */
  568. size_t size;
  569. /**
  570. * The number of objects of such size that were sampled.
  571. */
  572. unsigned int count;
  573. };
  574. /**
  575. * Represents a node in the call-graph.
  576. */
  577. struct Node {
  578. /**
  579. * Name of the function. May be empty for anonymous functions or if the
  580. * script corresponding to this function has been unloaded.
  581. */
  582. Local<String> name;
  583. /**
  584. * Name of the script containing the function. May be empty if the script
  585. * name is not available, or if the script has been unloaded.
  586. */
  587. Local<String> script_name;
  588. /**
  589. * id of the script where the function is located. May be equal to
  590. * v8::UnboundScript::kNoScriptId in cases where the script doesn't exist.
  591. */
  592. int script_id;
  593. /**
  594. * Start position of the function in the script.
  595. */
  596. int start_position;
  597. /**
  598. * 1-indexed line number where the function starts. May be
  599. * kNoLineNumberInfo if no line number information is available.
  600. */
  601. int line_number;
  602. /**
  603. * 1-indexed column number where the function starts. May be
  604. * kNoColumnNumberInfo if no line number information is available.
  605. */
  606. int column_number;
  607. /**
  608. * Unique id of the node.
  609. */
  610. uint32_t node_id;
  611. /**
  612. * List of callees called from this node for which we have sampled
  613. * allocations. The lifetime of the children is scoped to the containing
  614. * AllocationProfile.
  615. */
  616. std::vector<Node*> children;
  617. /**
  618. * List of self allocations done by this node in the call-graph.
  619. */
  620. std::vector<Allocation> allocations;
  621. };
  622. /**
  623. * Represent a single sample recorded for an allocation.
  624. */
  625. struct Sample {
  626. /**
  627. * id of the node in the profile tree.
  628. */
  629. uint32_t node_id;
  630. /**
  631. * Size of the sampled allocation object.
  632. */
  633. size_t size;
  634. /**
  635. * The number of objects of such size that were sampled.
  636. */
  637. unsigned int count;
  638. /**
  639. * Unique time-ordered id of the allocation sample. Can be used to track
  640. * what samples were added or removed between two snapshots.
  641. */
  642. uint64_t sample_id;
  643. };
  644. /**
  645. * Returns the root node of the call-graph. The root node corresponds to an
  646. * empty JS call-stack. The lifetime of the returned Node* is scoped to the
  647. * containing AllocationProfile.
  648. */
  649. virtual Node* GetRootNode() = 0;
  650. virtual const std::vector<Sample>& GetSamples() = 0;
  651. virtual ~AllocationProfile() = default;
  652. static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
  653. static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
  654. };
  655. /**
  656. * An object graph consisting of embedder objects and V8 objects.
  657. * Edges of the graph are strong references between the objects.
  658. * The embedder can build this graph during heap snapshot generation
  659. * to include the embedder objects in the heap snapshot.
  660. * Usage:
  661. * 1) Define derived class of EmbedderGraph::Node for embedder objects.
  662. * 2) Set the build embedder graph callback on the heap profiler using
  663. * HeapProfiler::AddBuildEmbedderGraphCallback.
  664. * 3) In the callback use graph->AddEdge(node1, node2) to add an edge from
  665. * node1 to node2.
  666. * 4) To represent references from/to V8 object, construct V8 nodes using
  667. * graph->V8Node(value).
  668. */
  669. class V8_EXPORT EmbedderGraph {
  670. public:
  671. class Node {
  672. public:
  673. Node() = default;
  674. virtual ~Node() = default;
  675. virtual const char* Name() = 0;
  676. virtual size_t SizeInBytes() = 0;
  677. /**
  678. * The corresponding V8 wrapper node if not null.
  679. * During heap snapshot generation the embedder node and the V8 wrapper
  680. * node will be merged into one node to simplify retaining paths.
  681. */
  682. virtual Node* WrapperNode() { return nullptr; }
  683. virtual bool IsRootNode() { return false; }
  684. /** Must return true for non-V8 nodes. */
  685. virtual bool IsEmbedderNode() { return true; }
  686. /**
  687. * Optional name prefix. It is used in Chrome for tagging detached nodes.
  688. */
  689. virtual const char* NamePrefix() { return nullptr; }
  690. Node(const Node&) = delete;
  691. Node& operator=(const Node&) = delete;
  692. };
  693. /**
  694. * Returns a node corresponding to the given V8 value. Ownership is not
  695. * transferred. The result pointer is valid while the graph is alive.
  696. */
  697. virtual Node* V8Node(const v8::Local<v8::Value>& value) = 0;
  698. /**
  699. * Adds the given node to the graph and takes ownership of the node.
  700. * Returns a raw pointer to the node that is valid while the graph is alive.
  701. */
  702. virtual Node* AddNode(std::unique_ptr<Node> node) = 0;
  703. /**
  704. * Adds an edge that represents a strong reference from the given
  705. * node |from| to the given node |to|. The nodes must be added to the graph
  706. * before calling this function.
  707. *
  708. * If name is nullptr, the edge will have auto-increment indexes, otherwise
  709. * it will be named accordingly.
  710. */
  711. virtual void AddEdge(Node* from, Node* to, const char* name = nullptr) = 0;
  712. virtual ~EmbedderGraph() = default;
  713. };
  714. /**
  715. * Interface for controlling heap profiling. Instance of the
  716. * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
  717. */
  718. class V8_EXPORT HeapProfiler {
  719. public:
  720. enum SamplingFlags {
  721. kSamplingNoFlags = 0,
  722. kSamplingForceGC = 1 << 0,
  723. };
  724. /**
  725. * Callback function invoked during heap snapshot generation to retrieve
  726. * the embedder object graph. The callback should use graph->AddEdge(..) to
  727. * add references between the objects.
  728. * The callback must not trigger garbage collection in V8.
  729. */
  730. typedef void (*BuildEmbedderGraphCallback)(v8::Isolate* isolate,
  731. v8::EmbedderGraph* graph,
  732. void* data);
  733. /** Returns the number of snapshots taken. */
  734. int GetSnapshotCount();
  735. /** Returns a snapshot by index. */
  736. const HeapSnapshot* GetHeapSnapshot(int index);
  737. /**
  738. * Returns SnapshotObjectId for a heap object referenced by |value| if
  739. * it has been seen by the heap profiler, kUnknownObjectId otherwise.
  740. */
  741. SnapshotObjectId GetObjectId(Local<Value> value);
  742. /**
  743. * Returns heap object with given SnapshotObjectId if the object is alive,
  744. * otherwise empty handle is returned.
  745. */
  746. Local<Value> FindObjectById(SnapshotObjectId id);
  747. /**
  748. * Clears internal map from SnapshotObjectId to heap object. The new objects
  749. * will not be added into it unless a heap snapshot is taken or heap object
  750. * tracking is kicked off.
  751. */
  752. void ClearObjectIds();
  753. /**
  754. * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
  755. * it in case heap profiler cannot find id for the object passed as
  756. * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
  757. */
  758. static const SnapshotObjectId kUnknownObjectId = 0;
  759. /**
  760. * Callback interface for retrieving user friendly names of global objects.
  761. */
  762. class ObjectNameResolver {
  763. public:
  764. /**
  765. * Returns name to be used in the heap snapshot for given node. Returned
  766. * string must stay alive until snapshot collection is completed.
  767. */
  768. virtual const char* GetName(Local<Object> object) = 0;
  769. protected:
  770. virtual ~ObjectNameResolver() = default;
  771. };
  772. /**
  773. * Takes a heap snapshot and returns it.
  774. */
  775. const HeapSnapshot* TakeHeapSnapshot(
  776. ActivityControl* control = nullptr,
  777. ObjectNameResolver* global_object_name_resolver = nullptr);
  778. /**
  779. * Starts tracking of heap objects population statistics. After calling
  780. * this method, all heap objects relocations done by the garbage collector
  781. * are being registered.
  782. *
  783. * |track_allocations| parameter controls whether stack trace of each
  784. * allocation in the heap will be recorded and reported as part of
  785. * HeapSnapshot.
  786. */
  787. void StartTrackingHeapObjects(bool track_allocations = false);
  788. /**
  789. * Adds a new time interval entry to the aggregated statistics array. The
  790. * time interval entry contains information on the current heap objects
  791. * population size. The method also updates aggregated statistics and
  792. * reports updates for all previous time intervals via the OutputStream
  793. * object. Updates on each time interval are provided as a stream of the
  794. * HeapStatsUpdate structure instances.
  795. * If |timestamp_us| is supplied, timestamp of the new entry will be written
  796. * into it. The return value of the function is the last seen heap object Id.
  797. *
  798. * StartTrackingHeapObjects must be called before the first call to this
  799. * method.
  800. */
  801. SnapshotObjectId GetHeapStats(OutputStream* stream,
  802. int64_t* timestamp_us = nullptr);
  803. /**
  804. * Stops tracking of heap objects population statistics, cleans up all
  805. * collected data. StartHeapObjectsTracking must be called again prior to
  806. * calling GetHeapStats next time.
  807. */
  808. void StopTrackingHeapObjects();
  809. /**
  810. * Starts gathering a sampling heap profile. A sampling heap profile is
  811. * similar to tcmalloc's heap profiler and Go's mprof. It samples object
  812. * allocations and builds an online 'sampling' heap profile. At any point in
  813. * time, this profile is expected to be a representative sample of objects
  814. * currently live in the system. Each sampled allocation includes the stack
  815. * trace at the time of allocation, which makes this really useful for memory
  816. * leak detection.
  817. *
  818. * This mechanism is intended to be cheap enough that it can be used in
  819. * production with minimal performance overhead.
  820. *
  821. * Allocations are sampled using a randomized Poisson process. On average, one
  822. * allocation will be sampled every |sample_interval| bytes allocated. The
  823. * |stack_depth| parameter controls the maximum number of stack frames to be
  824. * captured on each allocation.
  825. *
  826. * NOTE: This is a proof-of-concept at this point. Right now we only sample
  827. * newspace allocations. Support for paged space allocation (e.g. pre-tenured
  828. * objects, large objects, code objects, etc.) and native allocations
  829. * doesn't exist yet, but is anticipated in the future.
  830. *
  831. * Objects allocated before the sampling is started will not be included in
  832. * the profile.
  833. *
  834. * Returns false if a sampling heap profiler is already running.
  835. */
  836. bool StartSamplingHeapProfiler(uint64_t sample_interval = 512 * 1024,
  837. int stack_depth = 16,
  838. SamplingFlags flags = kSamplingNoFlags);
  839. /**
  840. * Stops the sampling heap profile and discards the current profile.
  841. */
  842. void StopSamplingHeapProfiler();
  843. /**
  844. * Returns the sampled profile of allocations allocated (and still live) since
  845. * StartSamplingHeapProfiler was called. The ownership of the pointer is
  846. * transferred to the caller. Returns nullptr if sampling heap profiler is not
  847. * active.
  848. */
  849. AllocationProfile* GetAllocationProfile();
  850. /**
  851. * Deletes all snapshots taken. All previously returned pointers to
  852. * snapshots and their contents become invalid after this call.
  853. */
  854. void DeleteAllHeapSnapshots();
  855. void AddBuildEmbedderGraphCallback(BuildEmbedderGraphCallback callback,
  856. void* data);
  857. void RemoveBuildEmbedderGraphCallback(BuildEmbedderGraphCallback callback,
  858. void* data);
  859. /**
  860. * Default value of persistent handle class ID. Must not be used to
  861. * define a class. Can be used to reset a class of a persistent
  862. * handle.
  863. */
  864. static const uint16_t kPersistentHandleNoClassId = 0;
  865. private:
  866. HeapProfiler();
  867. ~HeapProfiler();
  868. HeapProfiler(const HeapProfiler&);
  869. HeapProfiler& operator=(const HeapProfiler&);
  870. };
  871. /**
  872. * A struct for exporting HeapStats data from V8, using "push" model.
  873. * See HeapProfiler::GetHeapStats.
  874. */
  875. struct HeapStatsUpdate {
  876. HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
  877. : index(index), count(count), size(size) { }
  878. uint32_t index; // Index of the time interval that was changed.
  879. uint32_t count; // New value of count field for the interval with this index.
  880. uint32_t size; // New value of size field for the interval with this index.
  881. };
  882. #define CODE_EVENTS_LIST(V) \
  883. V(Builtin) \
  884. V(Callback) \
  885. V(Eval) \
  886. V(Function) \
  887. V(InterpretedFunction) \
  888. V(Handler) \
  889. V(BytecodeHandler) \
  890. V(LazyCompile) \
  891. V(RegExp) \
  892. V(Script) \
  893. V(Stub)
  894. /**
  895. * Note that this enum may be extended in the future. Please include a default
  896. * case if this enum is used in a switch statement.
  897. */
  898. enum CodeEventType {
  899. kUnknownType = 0
  900. #define V(Name) , k##Name##Type
  901. CODE_EVENTS_LIST(V)
  902. #undef V
  903. };
  904. /**
  905. * Representation of a code creation event
  906. */
  907. class V8_EXPORT CodeEvent {
  908. public:
  909. uintptr_t GetCodeStartAddress();
  910. size_t GetCodeSize();
  911. Local<String> GetFunctionName();
  912. Local<String> GetScriptName();
  913. int GetScriptLine();
  914. int GetScriptColumn();
  915. /**
  916. * NOTE (mmarchini): We can't allocate objects in the heap when we collect
  917. * existing code, and both the code type and the comment are not stored in the
  918. * heap, so we return those as const char*.
  919. */
  920. CodeEventType GetCodeType();
  921. const char* GetComment();
  922. static const char* GetCodeEventTypeName(CodeEventType code_event_type);
  923. };
  924. /**
  925. * Interface to listen to code creation events.
  926. */
  927. class V8_EXPORT CodeEventHandler {
  928. public:
  929. /**
  930. * Creates a new listener for the |isolate|. The isolate must be initialized.
  931. * The listener object must be disposed after use by calling |Dispose| method.
  932. * Multiple listeners can be created for the same isolate.
  933. */
  934. explicit CodeEventHandler(Isolate* isolate);
  935. virtual ~CodeEventHandler();
  936. virtual void Handle(CodeEvent* code_event) = 0;
  937. void Enable();
  938. void Disable();
  939. private:
  940. CodeEventHandler();
  941. CodeEventHandler(const CodeEventHandler&);
  942. CodeEventHandler& operator=(const CodeEventHandler&);
  943. void* internal_listener_;
  944. };
  945. } // namespace v8
  946. #endif // V8_V8_PROFILER_H_