v8  4.4.63(io.js3.3.1)
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 <vector>
9 #include "v8.h"
10 
11 /**
12  * Profiler support for the V8 JavaScript engine.
13  */
14 namespace v8 {
15 
16 class HeapGraphNode;
18 
19 typedef uint32_t SnapshotObjectId;
20 
21 
23  int script_id;
25 };
26 
27 } // namespace v8
28 
29 #ifdef V8_OS_WIN
30 template class V8_EXPORT std::vector<v8::CpuProfileDeoptFrame>;
31 #endif
32 
33 namespace v8 {
34 
36  /** A pointer to a static string owned by v8. */
37  const char* deopt_reason;
39 };
40 
41 } // namespace v8
42 
43 #ifdef V8_OS_WIN
44 template class V8_EXPORT std::vector<v8::CpuProfileDeoptInfo>;
45 #endif
46 
47 namespace v8 {
48 
49 /**
50  * CpuProfileNode represents a node in a call graph.
51  */
53  public:
54  struct LineTick {
55  /** The 1-based number of the source line where the function originates. */
56  int line;
57 
58  /** The count of samples associated with the source line. */
59  unsigned int hit_count;
60  };
61 
62  /** Returns function name (empty string for anonymous functions.) */
63  Handle<String> GetFunctionName() const;
64 
65  /** Returns id of the script where function is located. */
66  int GetScriptId() const;
67 
68  /** Returns resource name for script from where the function originates. */
69  Handle<String> GetScriptResourceName() const;
70 
71  /**
72  * Returns the number, 1-based, of the line where the function originates.
73  * kNoLineNumberInfo if no line number information is available.
74  */
75  int GetLineNumber() const;
76 
77  /**
78  * Returns 1-based number of the column where the function originates.
79  * kNoColumnNumberInfo if no column number information is available.
80  */
81  int GetColumnNumber() const;
82 
83  /**
84  * Returns the number of the function's source lines that collect the samples.
85  */
86  unsigned int GetHitLineCount() const;
87 
88  /** Returns the set of source lines that collect the samples.
89  * The caller allocates buffer and responsible for releasing it.
90  * True if all available entries are copied, otherwise false.
91  * The function copies nothing if buffer is not large enough.
92  */
93  bool GetLineTicks(LineTick* entries, unsigned int length) const;
94 
95  /** Returns bailout reason for the function
96  * if the optimization was disabled for it.
97  */
98  const char* GetBailoutReason() const;
99 
100  /**
101  * Returns the count of samples where the function was currently executing.
102  */
103  unsigned GetHitCount() const;
104 
105  /** Returns function entry UID. */
106  unsigned GetCallUid() const;
107 
108  /** Returns id of the node. The id is unique within the tree */
109  unsigned GetNodeId() const;
110 
111  /** Returns child nodes count of the node. */
112  int GetChildrenCount() const;
113 
114  /** Retrieves a child node by index. */
115  const CpuProfileNode* GetChild(int index) const;
116 
117  /** Retrieves deopt infos for the node. */
118  const std::vector<CpuProfileDeoptInfo>& GetDeoptInfos() const;
119 
122 };
123 
124 
125 /**
126  * CpuProfile contains a CPU profile in a form of top-down call tree
127  * (from main() down to functions that do all the work).
128  */
130  public:
131  /** Returns CPU profile title. */
132  Handle<String> GetTitle() const;
133 
134  /** Returns the root node of the top down call tree. */
135  const CpuProfileNode* GetTopDownRoot() const;
136 
137  /**
138  * Returns number of samples recorded. The samples are not recorded unless
139  * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
140  */
141  int GetSamplesCount() const;
142 
143  /**
144  * Returns profile node corresponding to the top frame the sample at
145  * the given index.
146  */
147  const CpuProfileNode* GetSample(int index) const;
148 
149  /**
150  * Returns the timestamp of the sample. The timestamp is the number of
151  * microseconds since some unspecified starting point.
152  * The point is equal to the starting point used by GetStartTime.
153  */
154  int64_t GetSampleTimestamp(int index) const;
155 
156  /**
157  * Returns time when the profile recording was started (in microseconds)
158  * since some unspecified starting point.
159  */
160  int64_t GetStartTime() const;
161 
162  /**
163  * Returns time when the profile recording was stopped (in microseconds)
164  * since some unspecified starting point.
165  * The point is equal to the starting point used by GetStartTime.
166  */
167  int64_t GetEndTime() const;
168 
169  /**
170  * Deletes the profile and removes it from CpuProfiler's list.
171  * All pointers to nodes previously returned become invalid.
172  */
173  void Delete();
174 };
175 
176 
177 /**
178  * Interface for controlling CPU profiling. Instance of the
179  * profiler can be retrieved using v8::Isolate::GetCpuProfiler.
180  */
182  public:
183  /**
184  * Changes default CPU profiler sampling interval to the specified number
185  * of microseconds. Default interval is 1000us. This method must be called
186  * when there are no profiles being recorded.
187  */
188  void SetSamplingInterval(int us);
189 
190  /**
191  * Starts collecting CPU profile. Title may be an empty string. It
192  * is allowed to have several profiles being collected at
193  * once. Attempts to start collecting several profiles with the same
194  * title are silently ignored. While collecting a profile, functions
195  * from all security contexts are included in it. The token-based
196  * filtering is only performed when querying for a profile.
197  *
198  * |record_samples| parameter controls whether individual samples should
199  * be recorded in addition to the aggregated tree.
200  */
201  void StartProfiling(Handle<String> title, bool record_samples = false);
202 
203  /**
204  * Stops collecting CPU profile with a given title and returns it.
205  * If the title given is empty, finishes the last profile started.
206  */
207  CpuProfile* StopProfiling(Handle<String> title);
208 
209  /**
210  * Tells the profiler whether the embedder is idle.
211  */
212  void SetIdle(bool is_idle);
213 
214  private:
215  CpuProfiler();
216  ~CpuProfiler();
217  CpuProfiler(const CpuProfiler&);
218  CpuProfiler& operator=(const CpuProfiler&);
219 };
220 
221 
222 /**
223  * HeapSnapshotEdge represents a directed connection between heap
224  * graph nodes: from retainers to retained nodes.
225  */
227  public:
228  enum Type {
229  kContextVariable = 0, // A variable from a function context.
230  kElement = 1, // An element of an array.
231  kProperty = 2, // A named object property.
232  kInternal = 3, // A link that can't be accessed from JS,
233  // thus, its name isn't a real property name
234  // (e.g. parts of a ConsString).
235  kHidden = 4, // A link that is needed for proper sizes
236  // calculation, but may be hidden from user.
237  kShortcut = 5, // A link that must not be followed during
238  // sizes calculation.
239  kWeak = 6 // A weak reference (ignored by the GC).
240  };
241 
242  /** Returns edge type (see HeapGraphEdge::Type). */
243  Type GetType() const;
244 
245  /**
246  * Returns edge name. This can be a variable name, an element index, or
247  * a property name.
248  */
249  Handle<Value> GetName() const;
250 
251  /** Returns origin node. */
252  const HeapGraphNode* GetFromNode() const;
253 
254  /** Returns destination node. */
255  const HeapGraphNode* GetToNode() const;
256 };
257 
258 
259 /**
260  * HeapGraphNode represents a node in a heap graph.
261  */
263  public:
264  enum Type {
265  kHidden = 0, // Hidden node, may be filtered when shown to user.
266  kArray = 1, // An array of elements.
267  kString = 2, // A string.
268  kObject = 3, // A JS object (except for arrays and strings).
269  kCode = 4, // Compiled code.
270  kClosure = 5, // Function closure.
271  kRegExp = 6, // RegExp.
272  kHeapNumber = 7, // Number stored in the heap.
273  kNative = 8, // Native object (not from V8 heap).
274  kSynthetic = 9, // Synthetic object, usualy used for grouping
275  // snapshot items together.
276  kConsString = 10, // Concatenated string. A pair of pointers to strings.
277  kSlicedString = 11, // Sliced string. A fragment of another string.
278  kSymbol = 12 // A Symbol (ES6).
279  };
280 
281  /** Returns node type (see HeapGraphNode::Type). */
282  Type GetType() const;
283 
284  /**
285  * Returns node name. Depending on node's type this can be the name
286  * of the constructor (for objects), the name of the function (for
287  * closures), string value, or an empty string (for compiled code).
288  */
289  Handle<String> GetName() const;
290 
291  /**
292  * Returns node id. For the same heap object, the id remains the same
293  * across all snapshots.
294  */
295  SnapshotObjectId GetId() const;
296 
297  /** Returns node's own size, in bytes. */
298  size_t GetShallowSize() const;
299 
300  /** Returns child nodes count of the node. */
301  int GetChildrenCount() const;
302 
303  /** Retrieves a child by index. */
304  const HeapGraphEdge* GetChild(int index) const;
305 };
306 
307 
308 /**
309  * An interface for exporting data from V8, using "push" model.
310  */
311 class V8_EXPORT OutputStream { // NOLINT
312  public:
313  enum WriteResult {
315  kAbort = 1
316  };
317  virtual ~OutputStream() {}
318  /** Notify about the end of stream. */
319  virtual void EndOfStream() = 0;
320  /** Get preferred output chunk size. Called only once. */
321  virtual int GetChunkSize() { return 1024; }
322  /**
323  * Writes the next chunk of snapshot data into the stream. Writing
324  * can be stopped by returning kAbort as function result. EndOfStream
325  * will not be called in case writing was aborted.
326  */
327  virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
328  /**
329  * Writes the next chunk of heap stats data into the stream. Writing
330  * can be stopped by returning kAbort as function result. EndOfStream
331  * will not be called in case writing was aborted.
332  */
333  virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
334  return kAbort;
335  }
336 };
337 
338 
339 /**
340  * HeapSnapshots record the state of the JS heap at some moment.
341  */
343  public:
345  kJSON = 0 // See format description near 'Serialize' method.
346  };
347 
348  /** Returns the root node of the heap graph. */
349  const HeapGraphNode* GetRoot() const;
350 
351  /** Returns a node by its id. */
352  const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
353 
354  /** Returns total nodes count in the snapshot. */
355  int GetNodesCount() const;
356 
357  /** Returns a node by index. */
358  const HeapGraphNode* GetNode(int index) const;
359 
360  /** Returns a max seen JS object Id. */
362 
363  /**
364  * Deletes the snapshot and removes it from HeapProfiler's list.
365  * All pointers to nodes, edges and paths previously returned become
366  * invalid.
367  */
368  void Delete();
369 
370  /**
371  * Prepare a serialized representation of the snapshot. The result
372  * is written into the stream provided in chunks of specified size.
373  * The total length of the serialized snapshot is unknown in
374  * advance, it can be roughly equal to JS heap size (that means,
375  * it can be really big - tens of megabytes).
376  *
377  * For the JSON format, heap contents are represented as an object
378  * with the following structure:
379  *
380  * {
381  * snapshot: {
382  * title: "...",
383  * uid: nnn,
384  * meta: { meta-info },
385  * node_count: nnn,
386  * edge_count: nnn
387  * },
388  * nodes: [nodes array],
389  * edges: [edges array],
390  * strings: [strings array]
391  * }
392  *
393  * Nodes reference strings, other nodes, and edges by their indexes
394  * in corresponding arrays.
395  */
396  void Serialize(OutputStream* stream,
397  SerializationFormat format = kJSON) const;
398 };
399 
400 
401 /**
402  * An interface for reporting progress and controlling long-running
403  * activities.
404  */
405 class V8_EXPORT ActivityControl { // NOLINT
406  public:
409  kAbort = 1
410  };
411  virtual ~ActivityControl() {}
412  /**
413  * Notify about current progress. The activity can be stopped by
414  * returning kAbort as the callback result.
415  */
416  virtual ControlOption ReportProgressValue(int done, int total) = 0;
417 };
418 
419 
420 /**
421  * Interface for controlling heap profiling. Instance of the
422  * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
423  */
425  public:
426  /**
427  * Callback function invoked for obtaining RetainedObjectInfo for
428  * the given JavaScript wrapper object. It is prohibited to enter V8
429  * while the callback is running: only getters on the handle and
430  * GetPointerFromInternalField on the objects are allowed.
431  */
432  typedef RetainedObjectInfo* (*WrapperInfoCallback)
433  (uint16_t class_id, Handle<Value> wrapper);
434 
435  /** Returns the number of snapshots taken. */
436  int GetSnapshotCount();
437 
438  /** Returns a snapshot by index. */
439  const HeapSnapshot* GetHeapSnapshot(int index);
440 
441  /**
442  * Returns SnapshotObjectId for a heap object referenced by |value| if
443  * it has been seen by the heap profiler, kUnknownObjectId otherwise.
444  */
445  SnapshotObjectId GetObjectId(Handle<Value> value);
446 
447  /**
448  * Returns heap object with given SnapshotObjectId if the object is alive,
449  * otherwise empty handle is returned.
450  */
452 
453  /**
454  * Clears internal map from SnapshotObjectId to heap object. The new objects
455  * will not be added into it unless a heap snapshot is taken or heap object
456  * tracking is kicked off.
457  */
458  void ClearObjectIds();
459 
460  /**
461  * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
462  * it in case heap profiler cannot find id for the object passed as
463  * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
464  */
466 
467  /**
468  * Callback interface for retrieving user friendly names of global objects.
469  */
471  public:
472  /**
473  * Returns name to be used in the heap snapshot for given node. Returned
474  * string must stay alive until snapshot collection is completed.
475  */
476  virtual const char* GetName(Handle<Object> object) = 0;
477  protected:
478  virtual ~ObjectNameResolver() {}
479  };
480 
481  /**
482  * Takes a heap snapshot and returns it.
483  */
485  ActivityControl* control = NULL,
486  ObjectNameResolver* global_object_name_resolver = NULL);
487 
488  /**
489  * Starts tracking of heap objects population statistics. After calling
490  * this method, all heap objects relocations done by the garbage collector
491  * are being registered.
492  *
493  * |track_allocations| parameter controls whether stack trace of each
494  * allocation in the heap will be recorded and reported as part of
495  * HeapSnapshot.
496  */
497  void StartTrackingHeapObjects(bool track_allocations = false);
498 
499  /**
500  * Adds a new time interval entry to the aggregated statistics array. The
501  * time interval entry contains information on the current heap objects
502  * population size. The method also updates aggregated statistics and
503  * reports updates for all previous time intervals via the OutputStream
504  * object. Updates on each time interval are provided as a stream of the
505  * HeapStatsUpdate structure instances.
506  * If |timestamp_us| is supplied, timestamp of the new entry will be written
507  * into it. The return value of the function is the last seen heap object Id.
508  *
509  * StartTrackingHeapObjects must be called before the first call to this
510  * method.
511  */
513  int64_t* timestamp_us = NULL);
514 
515  /**
516  * Stops tracking of heap objects population statistics, cleans up all
517  * collected data. StartHeapObjectsTracking must be called again prior to
518  * calling GetHeapStats next time.
519  */
521 
522  /**
523  * Deletes all snapshots taken. All previously returned pointers to
524  * snapshots and their contents become invalid after this call.
525  */
526  void DeleteAllHeapSnapshots();
527 
528  /** Binds a callback to embedder's class ID. */
530  uint16_t class_id,
531  WrapperInfoCallback callback);
532 
533  /**
534  * Default value of persistent handle class ID. Must not be used to
535  * define a class. Can be used to reset a class of a persistent
536  * handle.
537  */
538  static const uint16_t kPersistentHandleNoClassId = 0;
539 
540  /** Returns memory used for profiler internal data and snapshots. */
542 
543  /**
544  * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
545  */
547 
548  private:
549  HeapProfiler();
550  ~HeapProfiler();
551  HeapProfiler(const HeapProfiler&);
552  HeapProfiler& operator=(const HeapProfiler&);
553 };
554 
555 
556 /**
557  * Interface for providing information about embedder's objects
558  * held by global handles. This information is reported in two ways:
559  *
560  * 1. When calling AddObjectGroup, an embedder may pass
561  * RetainedObjectInfo instance describing the group. To collect
562  * this information while taking a heap snapshot, V8 calls GC
563  * prologue and epilogue callbacks.
564  *
565  * 2. When a heap snapshot is collected, V8 additionally
566  * requests RetainedObjectInfos for persistent handles that
567  * were not previously reported via AddObjectGroup.
568  *
569  * Thus, if an embedder wants to provide information about native
570  * objects for heap snapshots, he can do it in a GC prologue
571  * handler, and / or by assigning wrapper class ids in the following way:
572  *
573  * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
574  * 2. Call SetWrapperClassId on certain persistent handles.
575  *
576  * V8 takes ownership of RetainedObjectInfo instances passed to it and
577  * keeps them alive only during snapshot collection. Afterwards, they
578  * are freed by calling the Dispose class function.
579  */
580 class V8_EXPORT RetainedObjectInfo { // NOLINT
581  public:
582  /** Called by V8 when it no longer needs an instance. */
583  virtual void Dispose() = 0;
584 
585  /** Returns whether two instances are equivalent. */
586  virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
587 
588  /**
589  * Returns hash value for the instance. Equivalent instances
590  * must have the same hash value.
591  */
592  virtual intptr_t GetHash() = 0;
593 
594  /**
595  * Returns human-readable label. It must be a null-terminated UTF-8
596  * encoded string. V8 copies its contents during a call to GetLabel.
597  */
598  virtual const char* GetLabel() = 0;
599 
600  /**
601  * Returns human-readable group label. It must be a null-terminated UTF-8
602  * encoded string. V8 copies its contents during a call to GetGroupLabel.
603  * Heap snapshot generator will collect all the group names, create
604  * top level entries with these names and attach the objects to the
605  * corresponding top level group objects. There is a default
606  * implementation which is required because embedders don't have their
607  * own implementation yet.
608  */
609  virtual const char* GetGroupLabel() { return GetLabel(); }
610 
611  /**
612  * Returns element count in case if a global handle retains
613  * a subgraph by holding one of its nodes.
614  */
615  virtual intptr_t GetElementCount() { return -1; }
616 
617  /** Returns embedder's object size in bytes. */
618  virtual intptr_t GetSizeInBytes() { return -1; }
619 
620  protected:
622  virtual ~RetainedObjectInfo() {}
623 
624  private:
625  RetainedObjectInfo(const RetainedObjectInfo&);
626  RetainedObjectInfo& operator=(const RetainedObjectInfo&);
627 };
628 
629 
630 /**
631  * A struct for exporting HeapStats data from V8, using "push" model.
632  * See HeapProfiler::GetHeapStats.
633  */
635  HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
636  : index(index), count(count), size(size) { }
637  uint32_t index; // Index of the time interval that was changed.
638  uint32_t count; // New value of count field for the interval with this index.
639  uint32_t size; // New value of size field for the interval with this index.
640 };
641 
642 
643 } // namespace v8
644 
645 
646 #endif // V8_V8_PROFILER_H_
void DeleteAllHeapSnapshots()
const HeapGraphNode * GetFromNode() const
void StopTrackingHeapObjects()
int64_t GetSampleTimestamp(int index) const
void SetWrapperClassInfoProvider(uint16_t class_id, WrapperInfoCallback callback)
SnapshotObjectId GetObjectId(Handle< Value > value)
virtual intptr_t GetHash()=0
const HeapGraphNode * GetToNode() const
Definition: v8.h:1641
virtual ~OutputStream()
Definition: v8-profiler.h:317
SnapshotObjectId GetId() const
int64_t GetStartTime() const
virtual const char * GetName(Handle< Object > object)=0
static const int kNoColumnInfo
Definition: v8.h:1458
unsigned GetNodeId() const
Handle< String > GetScriptResourceName() const
CpuProfile * StopProfiling(Handle< String > title)
const HeapSnapshot * TakeHeapSnapshot(ActivityControl *control=NULL, ObjectNameResolver *global_object_name_resolver=NULL)
size_t GetShallowSize() const
static const int kNoLineNumberInfo
Definition: v8.h:1457
void SetSamplingInterval(int us)
const HeapGraphEdge * GetChild(int index) const
virtual ControlOption ReportProgressValue(int done, int total)=0
Handle< String > GetName() const
SnapshotObjectId GetHeapStats(OutputStream *stream, int64_t *timestamp_us=NULL)
Handle< Value > FindObjectById(SnapshotObjectId id)
unsigned GetCallUid() const
int GetChildrenCount() const
virtual bool IsEquivalent(RetainedObjectInfo *other)=0
const HeapGraphNode * GetRoot() const
static const int kNoColumnNumberInfo
Definition: v8-profiler.h:121
SnapshotObjectId GetMaxSnapshotJSObjectId() const
Definition: libplatform.h:10
virtual int GetChunkSize()
Definition: v8-profiler.h:321
static const uint16_t kPersistentHandleNoClassId
Definition: v8-profiler.h:538
virtual const char * GetLabel()=0
int64_t GetEndTime() const
HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
Definition: v8-profiler.h:635
Type GetType() const
std::vector< CpuProfileDeoptFrame > stack
Definition: v8-profiler.h:38
virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate *data, int count)
Definition: v8-profiler.h:333
const CpuProfileNode * GetChild(int index) const
virtual ~RetainedObjectInfo()
Definition: v8-profiler.h:622
const std::vector< CpuProfileDeoptInfo > & GetDeoptInfos() const
size_t GetProfilerMemorySize()
Handle< Value > GetName() const
virtual ~ActivityControl()
Definition: v8-profiler.h:411
const CpuProfileNode * GetTopDownRoot() const
bool GetLineTicks(LineTick *entries, unsigned int length) const
void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo *info)
int GetScriptId() const
int GetSamplesCount() const
Handle< String > GetFunctionName() const
void StartProfiling(Handle< String > title, bool record_samples=false)
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:37
unsigned int GetHitLineCount() const
uint32_t SnapshotObjectId
Definition: v8-profiler.h:17
int GetNodesCount() const
int GetChildrenCount() const
const CpuProfileNode * GetSample(int index) const
int GetColumnNumber() const
virtual intptr_t GetElementCount()
Definition: v8-profiler.h:615
unsigned GetHitCount() const
void StartTrackingHeapObjects(bool track_allocations=false)
Type GetType() const
void SetIdle(bool is_idle)
virtual void EndOfStream()=0
static const int kNoLineNumberInfo
Definition: v8-profiler.h:120
virtual intptr_t GetSizeInBytes()
Definition: v8-profiler.h:618
const HeapGraphNode * GetNodeById(SnapshotObjectId id) const
Handle< String > GetTitle() const
const HeapSnapshot * GetHeapSnapshot(int index)
#define V8_EXPORT
Definition: v8.h:58
const char * GetBailoutReason() const
virtual const char * GetGroupLabel()
Definition: v8-profiler.h:609
int GetLineNumber() const
static const SnapshotObjectId kUnknownObjectId
Definition: v8-profiler.h:465