v8  6.8.275 (node 10.15.3)
V8 is Google's open source JavaScript engine
v8-profiler.h
Go to the documentation of this file.
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 
5 #ifndef V8_V8_PROFILER_H_
6 #define V8_V8_PROFILER_H_
7 
8 #include <unordered_set>
9 #include <vector>
10 #include "v8.h" // NOLINT(build/include)
11 
12 /**
13  * Profiler support for the V8 JavaScript engine.
14  */
15 namespace v8 {
16 
17 class HeapGraphNode;
18 struct HeapStatsUpdate;
19 
20 typedef uint32_t SnapshotObjectId;
21 
22 
24  int script_id;
25  size_t position;
26 };
27 
28 } // namespace v8
29 
30 #ifdef V8_OS_WIN
31 template class V8_EXPORT std::vector<v8::CpuProfileDeoptFrame>;
32 #endif
33 
34 namespace v8 {
35 
37  /** A pointer to a static string owned by v8. */
38  const char* deopt_reason;
40 };
41 
42 } // namespace v8
43 
44 #ifdef V8_OS_WIN
45 template class V8_EXPORT std::vector<v8::CpuProfileDeoptInfo>;
46 #endif
47 
48 namespace v8 {
49 
50 /**
51  * TracingCpuProfiler monitors tracing being enabled/disabled
52  * and emits CpuProfile trace events once v8.cpu_profiler tracing category
53  * is enabled. It has no overhead unless the category is enabled.
54  */
56  public:
58  "The profiler is created automatically with the isolate.\n"
59  "No need to create it explicitly.",
60  static std::unique_ptr<TracingCpuProfiler> Create(Isolate*));
61 
62  virtual ~TracingCpuProfiler() = default;
63 
64  protected:
65  TracingCpuProfiler() = default;
66 };
67 
68 // TickSample captures the information collected for each sample.
69 struct TickSample {
70  // Internal profiling (with --prof + tools/$OS-tick-processor) wants to
71  // include the runtime function we're calling. Externally exposed tick
72  // samples don't care.
74 
76  : state(OTHER),
77  pc(nullptr),
78  external_callback_entry(nullptr),
79  frames_count(0),
80  has_external_callback(false),
81  update_stats(true) {}
82 
83  /**
84  * Initialize a tick sample from the isolate.
85  * \param isolate The isolate.
86  * \param state Execution state.
87  * \param record_c_entry_frame Include or skip the runtime function.
88  * \param update_stats Whether update the sample to the aggregated stats.
89  * \param use_simulator_reg_state When set to true and V8 is running under a
90  * simulator, the method will use the simulator
91  * register state rather than the one provided
92  * with |state| argument. Otherwise the method
93  * will use provided register |state| as is.
94  */
95  void Init(Isolate* isolate, const v8::RegisterState& state,
96  RecordCEntryFrame record_c_entry_frame, bool update_stats,
97  bool use_simulator_reg_state = true);
98  /**
99  * Get a call stack sample from the isolate.
100  * \param isolate The isolate.
101  * \param state Register state.
102  * \param record_c_entry_frame Include or skip the runtime function.
103  * \param frames Caller allocated buffer to store stack frames.
104  * \param frames_limit Maximum number of frames to capture. The buffer must
105  * be large enough to hold the number of frames.
106  * \param sample_info The sample info is filled up by the function
107  * provides number of actual captured stack frames and
108  * the current VM state.
109  * \param use_simulator_reg_state When set to true and V8 is running under a
110  * simulator, the method will use the simulator
111  * register state rather than the one provided
112  * with |state| argument. Otherwise the method
113  * will use provided register |state| as is.
114  * \note GetStackSample is thread and signal safe and should only be called
115  * when the JS thread is paused or interrupted.
116  * Otherwise the behavior is undefined.
117  */
118  static bool GetStackSample(Isolate* isolate, v8::RegisterState* state,
119  RecordCEntryFrame record_c_entry_frame,
120  void** frames, size_t frames_limit,
121  v8::SampleInfo* sample_info,
122  bool use_simulator_reg_state = true);
123  StateTag state; // The state of the VM.
124  void* pc; // Instruction pointer.
125  union {
126  void* tos; // Top stack value (*sp).
128  };
129  static const unsigned kMaxFramesCountLog2 = 8;
130  static const unsigned kMaxFramesCount = (1 << kMaxFramesCountLog2) - 1;
131  void* stack[kMaxFramesCount]; // Call stack.
132  unsigned frames_count : kMaxFramesCountLog2; // Number of captured frames.
134  bool update_stats : 1; // Whether the sample should update aggregated stats.
135 };
136 
137 /**
138  * CpuProfileNode represents a node in a call graph.
139  */
141  public:
142  struct LineTick {
143  /** The 1-based number of the source line where the function originates. */
144  int line;
145 
146  /** The count of samples associated with the source line. */
147  unsigned int hit_count;
148  };
149 
150  /** Returns function name (empty string for anonymous functions.) */
152 
153  /**
154  * Returns function name (empty string for anonymous functions.)
155  * The string ownership is *not* passed to the caller. It stays valid until
156  * profile is deleted. The function is thread safe.
157  */
158  const char* GetFunctionNameStr() const;
159 
160  /** Returns id of the script where function is located. */
161  int GetScriptId() const;
162 
163  /** Returns resource name for script from where the function originates. */
165 
166  /**
167  * Returns resource name for script from where the function originates.
168  * The string ownership is *not* passed to the caller. It stays valid until
169  * profile is deleted. The function is thread safe.
170  */
171  const char* GetScriptResourceNameStr() const;
172 
173  /**
174  * Returns the number, 1-based, of the line where the function originates.
175  * kNoLineNumberInfo if no line number information is available.
176  */
177  int GetLineNumber() const;
178 
179  /**
180  * Returns 1-based number of the column where the function originates.
181  * kNoColumnNumberInfo if no column number information is available.
182  */
183  int GetColumnNumber() const;
184 
185  /**
186  * Returns the number of the function's source lines that collect the samples.
187  */
188  unsigned int GetHitLineCount() const;
189 
190  /** Returns the set of source lines that collect the samples.
191  * The caller allocates buffer and responsible for releasing it.
192  * True if all available entries are copied, otherwise false.
193  * The function copies nothing if buffer is not large enough.
194  */
195  bool GetLineTicks(LineTick* entries, unsigned int length) const;
196 
197  /** Returns bailout reason for the function
198  * if the optimization was disabled for it.
199  */
200  const char* GetBailoutReason() const;
201 
202  /**
203  * Returns the count of samples where the function was currently executing.
204  */
205  unsigned GetHitCount() const;
206 
207  /** Returns function entry UID. */
209  "Use GetScriptId, GetLineNumber, and GetColumnNumber instead.",
210  unsigned GetCallUid() const);
211 
212  /** Returns id of the node. The id is unique within the tree */
213  unsigned GetNodeId() const;
214 
215  /** Returns child nodes count of the node. */
216  int GetChildrenCount() const;
217 
218  /** Retrieves a child node by index. */
219  const CpuProfileNode* GetChild(int index) const;
220 
221  /** Retrieves deopt infos for the node. */
222  const std::vector<CpuProfileDeoptInfo>& GetDeoptInfos() const;
223 
226 };
227 
228 
229 /**
230  * CpuProfile contains a CPU profile in a form of top-down call tree
231  * (from main() down to functions that do all the work).
232  */
234  public:
235  /** Returns CPU profile title. */
237 
238  /** Returns the root node of the top down call tree. */
240 
241  /**
242  * Returns number of samples recorded. The samples are not recorded unless
243  * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
244  */
245  int GetSamplesCount() const;
246 
247  /**
248  * Returns profile node corresponding to the top frame the sample at
249  * the given index.
250  */
251  const CpuProfileNode* GetSample(int index) const;
252 
253  /**
254  * Returns the timestamp of the sample. The timestamp is the number of
255  * microseconds since some unspecified starting point.
256  * The point is equal to the starting point used by GetStartTime.
257  */
258  int64_t GetSampleTimestamp(int index) const;
259 
260  /**
261  * Returns time when the profile recording was started (in microseconds)
262  * since some unspecified starting point.
263  */
264  int64_t GetStartTime() const;
265 
266  /**
267  * Returns time when the profile recording was stopped (in microseconds)
268  * since some unspecified starting point.
269  * The point is equal to the starting point used by GetStartTime.
270  */
271  int64_t GetEndTime() const;
272 
273  /**
274  * Deletes the profile and removes it from CpuProfiler's list.
275  * All pointers to nodes previously returned become invalid.
276  */
277  void Delete();
278 };
279 
280 /**
281  * Interface for controlling CPU profiling. Instance of the
282  * profiler can be created using v8::CpuProfiler::New method.
283  */
285  public:
286  /**
287  * Creates a new CPU profiler for the |isolate|. The isolate must be
288  * initialized. The profiler object must be disposed after use by calling
289  * |Dispose| method.
290  */
291  static CpuProfiler* New(Isolate* isolate);
292 
293  /**
294  * Synchronously collect current stack sample in all profilers attached to
295  * the |isolate|. The call does not affect number of ticks recorded for
296  * the current top node.
297  */
298  static void CollectSample(Isolate* isolate);
299 
300  /**
301  * Disposes the CPU profiler object.
302  */
303  void Dispose();
304 
305  /**
306  * Changes default CPU profiler sampling interval to the specified number
307  * of microseconds. Default interval is 1000us. This method must be called
308  * when there are no profiles being recorded.
309  */
310  void SetSamplingInterval(int us);
311 
312  /**
313  * Starts collecting CPU profile. Title may be an empty string. It
314  * is allowed to have several profiles being collected at
315  * once. Attempts to start collecting several profiles with the same
316  * title are silently ignored. While collecting a profile, functions
317  * from all security contexts are included in it. The token-based
318  * filtering is only performed when querying for a profile.
319  *
320  * |record_samples| parameter controls whether individual samples should
321  * be recorded in addition to the aggregated tree.
322  */
323  void StartProfiling(Local<String> title, bool record_samples = false);
324 
325  /**
326  * Stops collecting CPU profile with a given title and returns it.
327  * If the title given is empty, finishes the last profile started.
328  */
330 
331  /**
332  * Force collection of a sample. Must be called on the VM thread.
333  * Recording the forced sample does not contribute to the aggregated
334  * profile statistics.
335  */
336  V8_DEPRECATED("Use static CollectSample(Isolate*) instead.",
337  void CollectSample());
338 
339  /**
340  * Tells the profiler whether the embedder is idle.
341  */
342  V8_DEPRECATED("Use Isolate::SetIdle(bool) instead.",
343  void SetIdle(bool is_idle));
344 
345  private:
346  CpuProfiler();
347  ~CpuProfiler();
348  CpuProfiler(const CpuProfiler&);
349  CpuProfiler& operator=(const CpuProfiler&);
350 };
351 
352 
353 /**
354  * HeapSnapshotEdge represents a directed connection between heap
355  * graph nodes: from retainers to retained nodes.
356  */
358  public:
359  enum Type {
360  kContextVariable = 0, // A variable from a function context.
361  kElement = 1, // An element of an array.
362  kProperty = 2, // A named object property.
363  kInternal = 3, // A link that can't be accessed from JS,
364  // thus, its name isn't a real property name
365  // (e.g. parts of a ConsString).
366  kHidden = 4, // A link that is needed for proper sizes
367  // calculation, but may be hidden from user.
368  kShortcut = 5, // A link that must not be followed during
369  // sizes calculation.
370  kWeak = 6 // A weak reference (ignored by the GC).
371  };
372 
373  /** Returns edge type (see HeapGraphEdge::Type). */
374  Type GetType() const;
375 
376  /**
377  * Returns edge name. This can be a variable name, an element index, or
378  * a property name.
379  */
380  Local<Value> GetName() const;
381 
382  /** Returns origin node. */
383  const HeapGraphNode* GetFromNode() const;
384 
385  /** Returns destination node. */
386  const HeapGraphNode* GetToNode() const;
387 };
388 
389 
390 /**
391  * HeapGraphNode represents a node in a heap graph.
392  */
394  public:
395  enum Type {
396  kHidden = 0, // Hidden node, may be filtered when shown to user.
397  kArray = 1, // An array of elements.
398  kString = 2, // A string.
399  kObject = 3, // A JS object (except for arrays and strings).
400  kCode = 4, // Compiled code.
401  kClosure = 5, // Function closure.
402  kRegExp = 6, // RegExp.
403  kHeapNumber = 7, // Number stored in the heap.
404  kNative = 8, // Native object (not from V8 heap).
405  kSynthetic = 9, // Synthetic object, usually used for grouping
406  // snapshot items together.
407  kConsString = 10, // Concatenated string. A pair of pointers to strings.
408  kSlicedString = 11, // Sliced string. A fragment of another string.
409  kSymbol = 12, // A Symbol (ES6).
410  kBigInt = 13 // BigInt.
411  };
412 
413  /** Returns node type (see HeapGraphNode::Type). */
414  Type GetType() const;
415 
416  /**
417  * Returns node name. Depending on node's type this can be the name
418  * of the constructor (for objects), the name of the function (for
419  * closures), string value, or an empty string (for compiled code).
420  */
421  Local<String> GetName() const;
422 
423  /**
424  * Returns node id. For the same heap object, the id remains the same
425  * across all snapshots.
426  */
428 
429  /** Returns node's own size, in bytes. */
430  size_t GetShallowSize() const;
431 
432  /** Returns child nodes count of the node. */
433  int GetChildrenCount() const;
434 
435  /** Retrieves a child by index. */
436  const HeapGraphEdge* GetChild(int index) const;
437 };
438 
439 
440 /**
441  * An interface for exporting data from V8, using "push" model.
442  */
443 class V8_EXPORT OutputStream { // NOLINT
444  public:
445  enum WriteResult {
447  kAbort = 1
448  };
449  virtual ~OutputStream() {}
450  /** Notify about the end of stream. */
451  virtual void EndOfStream() = 0;
452  /** Get preferred output chunk size. Called only once. */
453  virtual int GetChunkSize() { return 1024; }
454  /**
455  * Writes the next chunk of snapshot data into the stream. Writing
456  * can be stopped by returning kAbort as function result. EndOfStream
457  * will not be called in case writing was aborted.
458  */
459  virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
460  /**
461  * Writes the next chunk of heap stats data into the stream. Writing
462  * can be stopped by returning kAbort as function result. EndOfStream
463  * will not be called in case writing was aborted.
464  */
465  virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
466  return kAbort;
467  }
468 };
469 
470 
471 /**
472  * HeapSnapshots record the state of the JS heap at some moment.
473  */
475  public:
477  kJSON = 0 // See format description near 'Serialize' method.
478  };
479 
480  /** Returns the root node of the heap graph. */
481  const HeapGraphNode* GetRoot() const;
482 
483  /** Returns a node by its id. */
485 
486  /** Returns total nodes count in the snapshot. */
487  int GetNodesCount() const;
488 
489  /** Returns a node by index. */
490  const HeapGraphNode* GetNode(int index) const;
491 
492  /** Returns a max seen JS object Id. */
494 
495  /**
496  * Deletes the snapshot and removes it from HeapProfiler's list.
497  * All pointers to nodes, edges and paths previously returned become
498  * invalid.
499  */
500  void Delete();
501 
502  /**
503  * Prepare a serialized representation of the snapshot. The result
504  * is written into the stream provided in chunks of specified size.
505  * The total length of the serialized snapshot is unknown in
506  * advance, it can be roughly equal to JS heap size (that means,
507  * it can be really big - tens of megabytes).
508  *
509  * For the JSON format, heap contents are represented as an object
510  * with the following structure:
511  *
512  * {
513  * snapshot: {
514  * title: "...",
515  * uid: nnn,
516  * meta: { meta-info },
517  * node_count: nnn,
518  * edge_count: nnn
519  * },
520  * nodes: [nodes array],
521  * edges: [edges array],
522  * strings: [strings array]
523  * }
524  *
525  * Nodes reference strings, other nodes, and edges by their indexes
526  * in corresponding arrays.
527  */
528  void Serialize(OutputStream* stream,
529  SerializationFormat format = kJSON) const;
530 };
531 
532 
533 /**
534  * An interface for reporting progress and controlling long-running
535  * activities.
536  */
537 class V8_EXPORT ActivityControl { // NOLINT
538  public:
541  kAbort = 1
542  };
543  virtual ~ActivityControl() {}
544  /**
545  * Notify about current progress. The activity can be stopped by
546  * returning kAbort as the callback result.
547  */
548  virtual ControlOption ReportProgressValue(int done, int total) = 0;
549 };
550 
551 
552 /**
553  * AllocationProfile is a sampled profile of allocations done by the program.
554  * This is structured as a call-graph.
555  */
557  public:
558  struct Allocation {
559  /**
560  * Size of the sampled allocation object.
561  */
562  size_t size;
563 
564  /**
565  * The number of objects of such size that were sampled.
566  */
567  unsigned int count;
568  };
569 
570  /**
571  * Represents a node in the call-graph.
572  */
573  struct Node {
574  /**
575  * Name of the function. May be empty for anonymous functions or if the
576  * script corresponding to this function has been unloaded.
577  */
579 
580  /**
581  * Name of the script containing the function. May be empty if the script
582  * name is not available, or if the script has been unloaded.
583  */
585 
586  /**
587  * id of the script where the function is located. May be equal to
588  * v8::UnboundScript::kNoScriptId in cases where the script doesn't exist.
589  */
591 
592  /**
593  * Start position of the function in the script.
594  */
596 
597  /**
598  * 1-indexed line number where the function starts. May be
599  * kNoLineNumberInfo if no line number information is available.
600  */
602 
603  /**
604  * 1-indexed column number where the function starts. May be
605  * kNoColumnNumberInfo if no line number information is available.
606  */
608 
609  /**
610  * List of callees called from this node for which we have sampled
611  * allocations. The lifetime of the children is scoped to the containing
612  * AllocationProfile.
613  */
614  std::vector<Node*> children;
615 
616  /**
617  * List of self allocations done by this node in the call-graph.
618  */
619  std::vector<Allocation> allocations;
620  };
621 
622  /**
623  * Returns the root node of the call-graph. The root node corresponds to an
624  * empty JS call-stack. The lifetime of the returned Node* is scoped to the
625  * containing AllocationProfile.
626  */
627  virtual Node* GetRootNode() = 0;
628 
629  virtual ~AllocationProfile() {}
630 
633 };
634 
635 /**
636  * An object graph consisting of embedder objects and V8 objects.
637  * Edges of the graph are strong references between the objects.
638  * The embedder can build this graph during heap snapshot generation
639  * to include the embedder objects in the heap snapshot.
640  * Usage:
641  * 1) Define derived class of EmbedderGraph::Node for embedder objects.
642  * 2) Set the build embedder graph callback on the heap profiler using
643  * HeapProfiler::SetBuildEmbedderGraphCallback.
644  * 3) In the callback use graph->AddEdge(node1, node2) to add an edge from
645  * node1 to node2.
646  * 4) To represent references from/to V8 object, construct V8 nodes using
647  * graph->V8Node(value).
648  */
650  public:
651  class Node {
652  public:
653  Node() = default;
654  virtual ~Node() = default;
655  virtual const char* Name() = 0;
656  virtual size_t SizeInBytes() = 0;
657  /**
658  * The corresponding V8 wrapper node if not null.
659  * During heap snapshot generation the embedder node and the V8 wrapper
660  * node will be merged into one node to simplify retaining paths.
661  */
662  virtual Node* WrapperNode() { return nullptr; }
663  virtual bool IsRootNode() { return false; }
664  /** Must return true for non-V8 nodes. */
665  virtual bool IsEmbedderNode() { return true; }
666  /**
667  * Optional name prefix. It is used in Chrome for tagging detached nodes.
668  */
669  virtual const char* NamePrefix() { return nullptr; }
670 
671  private:
672  Node(const Node&) = delete;
673  Node& operator=(const Node&) = delete;
674  };
675 
676  /**
677  * Returns a node corresponding to the given V8 value. Ownership is not
678  * transferred. The result pointer is valid while the graph is alive.
679  */
680  virtual Node* V8Node(const v8::Local<v8::Value>& value) = 0;
681 
682  /**
683  * Adds the given node to the graph and takes ownership of the node.
684  * Returns a raw pointer to the node that is valid while the graph is alive.
685  */
686  virtual Node* AddNode(std::unique_ptr<Node> node) = 0;
687 
688  /**
689  * Adds an edge that represents a strong reference from the given node
690  * |from| to the given node |to|. The nodes must be added to the graph
691  * before calling this function.
692  */
693  virtual void AddEdge(Node* from, Node* to) = 0;
694 
695  virtual ~EmbedderGraph() = default;
696 };
697 
698 /**
699  * Interface for controlling heap profiling. Instance of the
700  * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
701  */
703  public:
707  };
708 
709  typedef std::unordered_set<const v8::PersistentBase<v8::Value>*>
711  typedef std::vector<std::pair<v8::RetainedObjectInfo*, RetainerChildren>>
713  typedef std::vector<std::pair<const v8::PersistentBase<v8::Value>*,
714  const v8::PersistentBase<v8::Value>*>>
716 
717  struct RetainerInfos {
720  };
721 
722  /**
723  * Callback function invoked to retrieve all RetainerInfos from the embedder.
724  */
725  typedef RetainerInfos (*GetRetainerInfosCallback)(v8::Isolate* isolate);
726 
727  /**
728  * Callback function invoked for obtaining RetainedObjectInfo for
729  * the given JavaScript wrapper object. It is prohibited to enter V8
730  * while the callback is running: only getters on the handle and
731  * GetPointerFromInternalField on the objects are allowed.
732  */
733  typedef RetainedObjectInfo* (*WrapperInfoCallback)(uint16_t class_id,
734  Local<Value> wrapper);
735 
736  /**
737  * Callback function invoked during heap snapshot generation to retrieve
738  * the embedder object graph. The callback should use graph->AddEdge(..) to
739  * add references between the objects.
740  * The callback must not trigger garbage collection in V8.
741  */
742  typedef void (*BuildEmbedderGraphCallback)(v8::Isolate* isolate,
743  v8::EmbedderGraph* graph);
744 
745  /** Returns the number of snapshots taken. */
747 
748  /** Returns a snapshot by index. */
749  const HeapSnapshot* GetHeapSnapshot(int index);
750 
751  /**
752  * Returns SnapshotObjectId for a heap object referenced by |value| if
753  * it has been seen by the heap profiler, kUnknownObjectId otherwise.
754  */
756 
757  /**
758  * Returns heap object with given SnapshotObjectId if the object is alive,
759  * otherwise empty handle is returned.
760  */
762 
763  /**
764  * Clears internal map from SnapshotObjectId to heap object. The new objects
765  * will not be added into it unless a heap snapshot is taken or heap object
766  * tracking is kicked off.
767  */
769 
770  /**
771  * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
772  * it in case heap profiler cannot find id for the object passed as
773  * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
774  */
776 
777  /**
778  * Callback interface for retrieving user friendly names of global objects.
779  */
781  public:
782  /**
783  * Returns name to be used in the heap snapshot for given node. Returned
784  * string must stay alive until snapshot collection is completed.
785  */
786  virtual const char* GetName(Local<Object> object) = 0;
787 
788  protected:
789  virtual ~ObjectNameResolver() {}
790  };
791 
792  /**
793  * Takes a heap snapshot and returns it.
794  */
796  ActivityControl* control = NULL,
797  ObjectNameResolver* global_object_name_resolver = NULL);
798 
799  /**
800  * Starts tracking of heap objects population statistics. After calling
801  * this method, all heap objects relocations done by the garbage collector
802  * are being registered.
803  *
804  * |track_allocations| parameter controls whether stack trace of each
805  * allocation in the heap will be recorded and reported as part of
806  * HeapSnapshot.
807  */
808  void StartTrackingHeapObjects(bool track_allocations = false);
809 
810  /**
811  * Adds a new time interval entry to the aggregated statistics array. The
812  * time interval entry contains information on the current heap objects
813  * population size. The method also updates aggregated statistics and
814  * reports updates for all previous time intervals via the OutputStream
815  * object. Updates on each time interval are provided as a stream of the
816  * HeapStatsUpdate structure instances.
817  * If |timestamp_us| is supplied, timestamp of the new entry will be written
818  * into it. The return value of the function is the last seen heap object Id.
819  *
820  * StartTrackingHeapObjects must be called before the first call to this
821  * method.
822  */
824  int64_t* timestamp_us = NULL);
825 
826  /**
827  * Stops tracking of heap objects population statistics, cleans up all
828  * collected data. StartHeapObjectsTracking must be called again prior to
829  * calling GetHeapStats next time.
830  */
832 
833  /**
834  * Starts gathering a sampling heap profile. A sampling heap profile is
835  * similar to tcmalloc's heap profiler and Go's mprof. It samples object
836  * allocations and builds an online 'sampling' heap profile. At any point in
837  * time, this profile is expected to be a representative sample of objects
838  * currently live in the system. Each sampled allocation includes the stack
839  * trace at the time of allocation, which makes this really useful for memory
840  * leak detection.
841  *
842  * This mechanism is intended to be cheap enough that it can be used in
843  * production with minimal performance overhead.
844  *
845  * Allocations are sampled using a randomized Poisson process. On average, one
846  * allocation will be sampled every |sample_interval| bytes allocated. The
847  * |stack_depth| parameter controls the maximum number of stack frames to be
848  * captured on each allocation.
849  *
850  * NOTE: This is a proof-of-concept at this point. Right now we only sample
851  * newspace allocations. Support for paged space allocation (e.g. pre-tenured
852  * objects, large objects, code objects, etc.) and native allocations
853  * doesn't exist yet, but is anticipated in the future.
854  *
855  * Objects allocated before the sampling is started will not be included in
856  * the profile.
857  *
858  * Returns false if a sampling heap profiler is already running.
859  */
860  bool StartSamplingHeapProfiler(uint64_t sample_interval = 512 * 1024,
861  int stack_depth = 16,
863 
864  /**
865  * Stops the sampling heap profile and discards the current profile.
866  */
868 
869  /**
870  * Returns the sampled profile of allocations allocated (and still live) since
871  * StartSamplingHeapProfiler was called. The ownership of the pointer is
872  * transferred to the caller. Returns nullptr if sampling heap profiler is not
873  * active.
874  */
876 
877  /**
878  * Deletes all snapshots taken. All previously returned pointers to
879  * snapshots and their contents become invalid after this call.
880  */
882 
883  /** Binds a callback to embedder's class ID. */
885  "Use SetBuildEmbedderGraphCallback to provide info about embedder nodes",
886  void SetWrapperClassInfoProvider(uint16_t class_id,
887  WrapperInfoCallback callback));
888 
890  "Use SetBuildEmbedderGraphCallback to provide info about embedder nodes",
891  void SetGetRetainerInfosCallback(GetRetainerInfosCallback callback));
892 
894 
895  /**
896  * Default value of persistent handle class ID. Must not be used to
897  * define a class. Can be used to reset a class of a persistent
898  * handle.
899  */
900  static const uint16_t kPersistentHandleNoClassId = 0;
901 
902  private:
903  HeapProfiler();
904  ~HeapProfiler();
905  HeapProfiler(const HeapProfiler&);
906  HeapProfiler& operator=(const HeapProfiler&);
907 };
908 
909 /**
910  * Interface for providing information about embedder's objects
911  * held by global handles. This information is reported in two ways:
912  *
913  * 1. When calling AddObjectGroup, an embedder may pass
914  * RetainedObjectInfo instance describing the group. To collect
915  * this information while taking a heap snapshot, V8 calls GC
916  * prologue and epilogue callbacks.
917  *
918  * 2. When a heap snapshot is collected, V8 additionally
919  * requests RetainedObjectInfos for persistent handles that
920  * were not previously reported via AddObjectGroup.
921  *
922  * Thus, if an embedder wants to provide information about native
923  * objects for heap snapshots, it can do it in a GC prologue
924  * handler, and / or by assigning wrapper class ids in the following way:
925  *
926  * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
927  * 2. Call SetWrapperClassId on certain persistent handles.
928  *
929  * V8 takes ownership of RetainedObjectInfo instances passed to it and
930  * keeps them alive only during snapshot collection. Afterwards, they
931  * are freed by calling the Dispose class function.
932  */
933 class V8_EXPORT RetainedObjectInfo { // NOLINT
934  public:
935  /** Called by V8 when it no longer needs an instance. */
936  virtual void Dispose() = 0;
937 
938  /** Returns whether two instances are equivalent. */
939  virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
940 
941  /**
942  * Returns hash value for the instance. Equivalent instances
943  * must have the same hash value.
944  */
945  virtual intptr_t GetHash() = 0;
946 
947  /**
948  * Returns human-readable label. It must be a null-terminated UTF-8
949  * encoded string. V8 copies its contents during a call to GetLabel.
950  */
951  virtual const char* GetLabel() = 0;
952 
953  /**
954  * Returns human-readable group label. It must be a null-terminated UTF-8
955  * encoded string. V8 copies its contents during a call to GetGroupLabel.
956  * Heap snapshot generator will collect all the group names, create
957  * top level entries with these names and attach the objects to the
958  * corresponding top level group objects. There is a default
959  * implementation which is required because embedders don't have their
960  * own implementation yet.
961  */
962  virtual const char* GetGroupLabel() { return GetLabel(); }
963 
964  /**
965  * Returns element count in case if a global handle retains
966  * a subgraph by holding one of its nodes.
967  */
968  virtual intptr_t GetElementCount() { return -1; }
969 
970  /** Returns embedder's object size in bytes. */
971  virtual intptr_t GetSizeInBytes() { return -1; }
972 
973  protected:
975  virtual ~RetainedObjectInfo() {}
976 
977  private:
978  RetainedObjectInfo(const RetainedObjectInfo&);
979  RetainedObjectInfo& operator=(const RetainedObjectInfo&);
980 };
981 
982 
983 /**
984  * A struct for exporting HeapStats data from V8, using "push" model.
985  * See HeapProfiler::GetHeapStats.
986  */
988  HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
989  : index(index), count(count), size(size) { }
990  uint32_t index; // Index of the time interval that was changed.
991  uint32_t count; // New value of count field for the interval with this index.
992  uint32_t size; // New value of size field for the interval with this index.
993 };
994 
995 
996 } // namespace v8
997 
998 
999 #endif // V8_V8_PROFILER_H_