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