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