v8  3.11.10(node0.8.28)
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 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 #ifndef V8_V8_PROFILER_H_
29 #define V8_V8_PROFILER_H_
30 
31 #include "v8.h"
32 
33 #ifdef _WIN32
34 // Setup for Windows DLL export/import. See v8.h in this directory for
35 // information on how to build/use V8 as a DLL.
36 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
37 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the
38  build configuration to ensure that at most one of these is set
39 #endif
40 
41 #ifdef BUILDING_V8_SHARED
42 #define V8EXPORT __declspec(dllexport)
43 #elif USING_V8_SHARED
44 #define V8EXPORT __declspec(dllimport)
45 #else
46 #define V8EXPORT
47 #endif
48 
49 #else // _WIN32
50 
51 // Setup for Linux shared library export. See v8.h in this directory for
52 // information on how to build/use V8 as shared library.
53 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
54 #define V8EXPORT __attribute__ ((visibility("default")))
55 #else // defined(__GNUC__) && (__GNUC__ >= 4)
56 #define V8EXPORT
57 #endif // defined(__GNUC__) && (__GNUC__ >= 4)
58 
59 #endif // _WIN32
60 
61 
62 /**
63  * Profiler support for the V8 JavaScript engine.
64  */
65 namespace v8 {
66 
67 typedef uint32_t SnapshotObjectId;
68 
69 /**
70  * CpuProfileNode represents a node in a call graph.
71  */
73  public:
74  /** Returns function name (empty string for anonymous functions.) */
75  Handle<String> GetFunctionName() const;
76 
77  /** Returns resource name for script from where the function originates. */
78  Handle<String> GetScriptResourceName() const;
79 
80  /**
81  * Returns the number, 1-based, of the line where the function originates.
82  * kNoLineNumberInfo if no line number information is available.
83  */
84  int GetLineNumber() const;
85 
86  /**
87  * Returns total (self + children) execution time of the function,
88  * in milliseconds, estimated by samples count.
89  */
90  double GetTotalTime() const;
91 
92  /**
93  * Returns self execution time of the function, in milliseconds,
94  * estimated by samples count.
95  */
96  double GetSelfTime() const;
97 
98  /** Returns the count of samples where function exists. */
99  double GetTotalSamplesCount() const;
100 
101  /** Returns the count of samples where function was currently executing. */
102  double GetSelfSamplesCount() const;
103 
104  /** Returns function entry UID. */
105  unsigned GetCallUid() const;
106 
107  /** Returns child nodes count of the node. */
108  int GetChildrenCount() const;
109 
110  /** Retrieves a child node by index. */
111  const CpuProfileNode* GetChild(int index) const;
112 
114 };
115 
116 
117 /**
118  * CpuProfile contains a CPU profile in a form of two call trees:
119  * - top-down (from main() down to functions that do all the work);
120  * - bottom-up call graph (in backward direction).
121  */
123  public:
124  /** Returns CPU profile UID (assigned by the profiler.) */
125  unsigned GetUid() const;
126 
127  /** Returns CPU profile title. */
128  Handle<String> GetTitle() const;
129 
130  /** Returns the root node of the bottom up call tree. */
131  const CpuProfileNode* GetBottomUpRoot() const;
132 
133  /** Returns the root node of the top down call tree. */
134  const CpuProfileNode* GetTopDownRoot() const;
135 
136  /**
137  * Deletes the profile and removes it from CpuProfiler's list.
138  * All pointers to nodes previously returned become invalid.
139  * Profiles with the same uid but obtained using different
140  * security token are not deleted, but become inaccessible
141  * using FindProfile method. It is embedder's responsibility
142  * to call Delete on these profiles.
143  */
144  void Delete();
145 };
146 
147 
148 /**
149  * Interface for controlling CPU profiling.
150  */
152  public:
153  /**
154  * A note on security tokens usage. As scripts from different
155  * origins can run inside a single V8 instance, it is possible to
156  * have functions from different security contexts intermixed in a
157  * single CPU profile. To avoid exposing function names belonging to
158  * other contexts, filtering by security token is performed while
159  * obtaining profiling results.
160  */
161 
162  /**
163  * Returns the number of profiles collected (doesn't include
164  * profiles that are being collected at the moment of call.)
165  */
166  static int GetProfilesCount();
167 
168  /** Returns a profile by index. */
169  static const CpuProfile* GetProfile(
170  int index,
171  Handle<Value> security_token = Handle<Value>());
172 
173  /** Returns a profile by uid. */
174  static const CpuProfile* FindProfile(
175  unsigned uid,
176  Handle<Value> security_token = Handle<Value>());
177 
178  /**
179  * Starts collecting CPU profile. Title may be an empty string. It
180  * is allowed to have several profiles being collected at
181  * once. Attempts to start collecting several profiles with the same
182  * title are silently ignored. While collecting a profile, functions
183  * from all security contexts are included in it. The token-based
184  * filtering is only performed when querying for a profile.
185  */
186  static void StartProfiling(Handle<String> title);
187 
188  /**
189  * Stops collecting CPU profile with a given title and returns it.
190  * If the title given is empty, finishes the last profile started.
191  */
192  static const CpuProfile* StopProfiling(
193  Handle<String> title,
194  Handle<Value> security_token = Handle<Value>());
195 
196  /**
197  * Deletes all existing profiles, also cancelling all profiling
198  * activity. All previously returned pointers to profiles and their
199  * contents become invalid after this call.
200  */
201  static void DeleteAllProfiles();
202 };
203 
204 
205 class HeapGraphNode;
206 
207 
208 /**
209  * HeapSnapshotEdge represents a directed connection between heap
210  * graph nodes: from retainers to retained nodes.
211  */
213  public:
214  enum Type {
215  kContextVariable = 0, // A variable from a function context.
216  kElement = 1, // An element of an array.
217  kProperty = 2, // A named object property.
218  kInternal = 3, // A link that can't be accessed from JS,
219  // thus, its name isn't a real property name
220  // (e.g. parts of a ConsString).
221  kHidden = 4, // A link that is needed for proper sizes
222  // calculation, but may be hidden from user.
223  kShortcut = 5, // A link that must not be followed during
224  // sizes calculation.
225  kWeak = 6 // A weak reference (ignored by the GC).
226  };
227 
228  /** Returns edge type (see HeapGraphEdge::Type). */
229  Type GetType() const;
230 
231  /**
232  * Returns edge name. This can be a variable name, an element index, or
233  * a property name.
234  */
235  Handle<Value> GetName() const;
236 
237  /** Returns origin node. */
238  const HeapGraphNode* GetFromNode() const;
239 
240  /** Returns destination node. */
241  const HeapGraphNode* GetToNode() const;
242 };
243 
244 
245 /**
246  * HeapGraphNode represents a node in a heap graph.
247  */
249  public:
250  enum Type {
251  kHidden = 0, // Hidden node, may be filtered when shown to user.
252  kArray = 1, // An array of elements.
253  kString = 2, // A string.
254  kObject = 3, // A JS object (except for arrays and strings).
255  kCode = 4, // Compiled code.
256  kClosure = 5, // Function closure.
257  kRegExp = 6, // RegExp.
258  kHeapNumber = 7, // Number stored in the heap.
259  kNative = 8, // Native object (not from V8 heap).
260  kSynthetic = 9 // Synthetic object, usualy used for grouping
261  // snapshot items together.
262  };
263 
264  /** Returns node type (see HeapGraphNode::Type). */
265  Type GetType() const;
266 
267  /**
268  * Returns node name. Depending on node's type this can be the name
269  * of the constructor (for objects), the name of the function (for
270  * closures), string value, or an empty string (for compiled code).
271  */
272  Handle<String> GetName() const;
273 
274  /**
275  * Returns node id. For the same heap object, the id remains the same
276  * across all snapshots.
277  */
278  SnapshotObjectId GetId() const;
279 
280  /** Returns node's own size, in bytes. */
281  int GetSelfSize() const;
282 
283  /**
284  * Returns node's retained size, in bytes. That is, self + sizes of
285  * the objects that are reachable only from this object. In other
286  * words, the size of memory that will be reclaimed having this node
287  * collected.
288  */
289  int GetRetainedSize() const;
290 
291  /** Returns child nodes count of the node. */
292  int GetChildrenCount() const;
293 
294  /** Retrieves a child by index. */
295  const HeapGraphEdge* GetChild(int index) const;
296 
297  /** Returns retainer nodes count of the node. */
298  int GetRetainersCount() const;
299 
300  /** Returns a retainer by index. */
301  const HeapGraphEdge* GetRetainer(int index) const;
302 
303  /**
304  * Returns a dominator node. This is the node that participates in every
305  * path from the snapshot root to the current node.
306  */
307  const HeapGraphNode* GetDominatorNode() const;
308 
309  /**
310  * Finds and returns a value from the heap corresponding to this node,
311  * if the value is still reachable.
312  */
313  Handle<Value> GetHeapValue() const;
314 };
315 
316 
317 /**
318  * HeapSnapshots record the state of the JS heap at some moment.
319  */
321  public:
322  enum Type {
323  kFull = 0 // Heap snapshot with all instances and references.
324  };
326  kJSON = 0 // See format description near 'Serialize' method.
327  };
328 
329  /** Returns heap snapshot type. */
330  Type GetType() const;
331 
332  /** Returns heap snapshot UID (assigned by the profiler.) */
333  unsigned GetUid() const;
334 
335  /** Returns heap snapshot title. */
336  Handle<String> GetTitle() const;
337 
338  /** Returns the root node of the heap graph. */
339  const HeapGraphNode* GetRoot() const;
340 
341  /** Returns a node by its id. */
342  const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
343 
344  /** Returns total nodes count in the snapshot. */
345  int GetNodesCount() const;
346 
347  /** Returns a node by index. */
348  const HeapGraphNode* GetNode(int index) const;
349 
350  /** Returns a max seen JS object Id. */
352 
353  /**
354  * Deletes the snapshot and removes it from HeapProfiler's list.
355  * All pointers to nodes, edges and paths previously returned become
356  * invalid.
357  */
358  void Delete();
359 
360  /**
361  * Prepare a serialized representation of the snapshot. The result
362  * is written into the stream provided in chunks of specified size.
363  * The total length of the serialized snapshot is unknown in
364  * advance, it can be roughly equal to JS heap size (that means,
365  * it can be really big - tens of megabytes).
366  *
367  * For the JSON format, heap contents are represented as an object
368  * with the following structure:
369  *
370  * {
371  * snapshot: {
372  * title: "...",
373  * uid: nnn,
374  * meta: { meta-info },
375  * node_count: nnn,
376  * edge_count: nnn
377  * },
378  * nodes: [nodes array],
379  * edges: [edges array],
380  * strings: [strings array]
381  * }
382  *
383  * Nodes reference strings, other nodes, and edges by their indexes
384  * in corresponding arrays.
385  */
386  void Serialize(OutputStream* stream, SerializationFormat format) const;
387 };
388 
389 
390 class RetainedObjectInfo;
391 
392 /**
393  * Interface for controlling heap profiling.
394  */
396  public:
397  /**
398  * Callback function invoked for obtaining RetainedObjectInfo for
399  * the given JavaScript wrapper object. It is prohibited to enter V8
400  * while the callback is running: only getters on the handle and
401  * GetPointerFromInternalField on the objects are allowed.
402  */
403  typedef RetainedObjectInfo* (*WrapperInfoCallback)
404  (uint16_t class_id, Handle<Value> wrapper);
405 
406  /** Returns the number of snapshots taken. */
407  static int GetSnapshotsCount();
408 
409  /** Returns a snapshot by index. */
410  static const HeapSnapshot* GetSnapshot(int index);
411 
412  /** Returns a profile by uid. */
413  static const HeapSnapshot* FindSnapshot(unsigned uid);
414 
415  /**
416  * Returns SnapshotObjectId for a heap object referenced by |value| if
417  * it has been seen by the heap profiler, kUnknownObjectId otherwise.
418  */
419  static SnapshotObjectId GetSnapshotObjectId(Handle<Value> value);
420 
421  /**
422  * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
423  * it in case heap profiler cannot find id for the object passed as
424  * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
425  */
427 
428  /**
429  * Takes a heap snapshot and returns it. Title may be an empty string.
430  * See HeapSnapshot::Type for types description.
431  */
432  static const HeapSnapshot* TakeSnapshot(
433  Handle<String> title,
435  ActivityControl* control = NULL);
436 
437  /**
438  * Starts tracking of heap objects population statistics. After calling
439  * this method, all heap objects relocations done by the garbage collector
440  * are being registered.
441  */
442  static void StartHeapObjectsTracking();
443 
444  /**
445  * Adds a new time interval entry to the aggregated statistics array. The
446  * time interval entry contains information on the current heap objects
447  * population size. The method also updates aggregated statistics and
448  * reports updates for all previous time intervals via the OutputStream
449  * object. Updates on each time interval are provided as a stream of the
450  * HeapStatsUpdate structure instances.
451  * The return value of the function is the last seen heap object Id.
452  *
453  * StartHeapObjectsTracking must be called before the first call to this
454  * method.
455  */
457 
458  /**
459  * Stops tracking of heap objects population statistics, cleans up all
460  * collected data. StartHeapObjectsTracking must be called again prior to
461  * calling PushHeapObjectsStats next time.
462  */
463  static void StopHeapObjectsTracking();
464 
465  /**
466  * Deletes all snapshots taken. All previously returned pointers to
467  * snapshots and their contents become invalid after this call.
468  */
469  static void DeleteAllSnapshots();
470 
471  /** Binds a callback to embedder's class ID. */
472  static void DefineWrapperClass(
473  uint16_t class_id,
474  WrapperInfoCallback callback);
475 
476  /**
477  * Default value of persistent handle class ID. Must not be used to
478  * define a class. Can be used to reset a class of a persistent
479  * handle.
480  */
481  static const uint16_t kPersistentHandleNoClassId = 0;
482 
483  /** Returns the number of currently existing persistent handles. */
484  static int GetPersistentHandleCount();
485 
486  /** Returns memory used for profiler internal data and snapshots. */
488 };
489 
490 
491 /**
492  * Interface for providing information about embedder's objects
493  * held by global handles. This information is reported in two ways:
494  *
495  * 1. When calling AddObjectGroup, an embedder may pass
496  * RetainedObjectInfo instance describing the group. To collect
497  * this information while taking a heap snapshot, V8 calls GC
498  * prologue and epilogue callbacks.
499  *
500  * 2. When a heap snapshot is collected, V8 additionally
501  * requests RetainedObjectInfos for persistent handles that
502  * were not previously reported via AddObjectGroup.
503  *
504  * Thus, if an embedder wants to provide information about native
505  * objects for heap snapshots, he can do it in a GC prologue
506  * handler, and / or by assigning wrapper class ids in the following way:
507  *
508  * 1. Bind a callback to class id by calling DefineWrapperClass.
509  * 2. Call SetWrapperClassId on certain persistent handles.
510  *
511  * V8 takes ownership of RetainedObjectInfo instances passed to it and
512  * keeps them alive only during snapshot collection. Afterwards, they
513  * are freed by calling the Dispose class function.
514  */
515 class V8EXPORT RetainedObjectInfo { // NOLINT
516  public:
517  /** Called by V8 when it no longer needs an instance. */
518  virtual void Dispose() = 0;
519 
520  /** Returns whether two instances are equivalent. */
521  virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
522 
523  /**
524  * Returns hash value for the instance. Equivalent instances
525  * must have the same hash value.
526  */
527  virtual intptr_t GetHash() = 0;
528 
529  /**
530  * Returns human-readable label. It must be a null-terminated UTF-8
531  * encoded string. V8 copies its contents during a call to GetLabel.
532  */
533  virtual const char* GetLabel() = 0;
534 
535  /**
536  * Returns human-readable group label. It must be a null-terminated UTF-8
537  * encoded string. V8 copies its contents during a call to GetGroupLabel.
538  * Heap snapshot generator will collect all the group names, create
539  * top level entries with these names and attach the objects to the
540  * corresponding top level group objects. There is a default
541  * implementation which is required because embedders don't have their
542  * own implementation yet.
543  */
544  virtual const char* GetGroupLabel() { return GetLabel(); }
545 
546  /**
547  * Returns element count in case if a global handle retains
548  * a subgraph by holding one of its nodes.
549  */
550  virtual intptr_t GetElementCount() { return -1; }
551 
552  /** Returns embedder's object size in bytes. */
553  virtual intptr_t GetSizeInBytes() { return -1; }
554 
555  protected:
557  virtual ~RetainedObjectInfo() {}
558 
559  private:
560  RetainedObjectInfo(const RetainedObjectInfo&);
561  RetainedObjectInfo& operator=(const RetainedObjectInfo&);
562 };
563 
564 
565 /**
566  * A struct for exporting HeapStats data from V8, using "push" model.
567  * See HeapProfiler::PushHeapObjectsStats.
568  */
570  HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
571  : index(index), count(count), size(size) { }
572  uint32_t index; // Index of the time interval that was changed.
573  uint32_t count; // New value of count field for the interval with this index.
574  uint32_t size; // New value of size field for the interval with this index.
575 };
576 
577 
578 } // namespace v8
579 
580 
581 #undef V8EXPORT
582 
583 
584 #endif // V8_V8_PROFILER_H_
double GetSelfTime() const
static size_t GetMemorySizeUsedByProfiler()
const HeapGraphNode * GetFromNode() const
Type GetType() const
virtual intptr_t GetHash()=0
const HeapGraphNode * GetToNode() const
Definition: v8.h:863
double GetTotalTime() const
SnapshotObjectId GetId() const
static const CpuProfile * FindProfile(unsigned uid, Handle< Value > security_token=Handle< Value >())
static void StopHeapObjectsTracking()
Handle< String > GetScriptResourceName() const
static SnapshotObjectId GetSnapshotObjectId(Handle< Value > value)
int GetSelfSize() const
static const int kNoLineNumberInfo
Definition: v8.h:747
const HeapGraphEdge * GetRetainer(int index) const
const HeapGraphEdge * GetChild(int index) const
Handle< String > GetName() const
static SnapshotObjectId PushHeapObjectsStats(OutputStream *stream)
double GetSelfSamplesCount() const
Handle< String > GetTitle() const
unsigned GetCallUid() const
int GetChildrenCount() const
virtual bool IsEquivalent(RetainedObjectInfo *other)=0
const HeapGraphNode * GetRoot() const
static void DefineWrapperClass(uint16_t class_id, WrapperInfoCallback callback)
const CpuProfileNode * GetBottomUpRoot() const
SnapshotObjectId GetMaxSnapshotJSObjectId() const
Definition: v8-debug.h:70
static const uint16_t kPersistentHandleNoClassId
Definition: v8-profiler.h:481
virtual const char * GetLabel()=0
HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
Definition: v8-profiler.h:570
Handle()
Definition: v8.h:178
Type GetType() const
const CpuProfileNode * GetChild(int index) const
virtual ~RetainedObjectInfo()
Definition: v8-profiler.h:557
Handle< Value > GetName() const
const CpuProfileNode * GetTopDownRoot() const
static void DeleteAllSnapshots()
static int GetSnapshotsCount()
const HeapGraphNode * GetDominatorNode() const
static const HeapSnapshot * TakeSnapshot(Handle< String > title, HeapSnapshot::Type type=HeapSnapshot::kFull, ActivityControl *control=NULL)
Handle< String > GetFunctionName() const
int GetRetainersCount() const
static const CpuProfile * StopProfiling(Handle< String > title, Handle< Value > security_token=Handle< Value >())
static const HeapSnapshot * GetSnapshot(int index)
const HeapGraphNode * GetNode(int index) const
static int GetProfilesCount()
virtual void Dispose()=0
static const HeapSnapshot * FindSnapshot(unsigned uid)
uint32_t SnapshotObjectId
Definition: v8-profiler.h:67
int GetNodesCount() const
int GetChildrenCount() const
Handle< Value > GetHeapValue() const
virtual intptr_t GetElementCount()
Definition: v8-profiler.h:550
#define V8EXPORT
Definition: v8-preparser.h:61
unsigned GetUid() const
static const CpuProfile * GetProfile(int index, Handle< Value > security_token=Handle< Value >())
int GetRetainedSize() const
Type GetType() const
static void StartHeapObjectsTracking()
static int GetPersistentHandleCount()
static void StartProfiling(Handle< String > title)
unsigned GetUid() const
static const int kNoLineNumberInfo
Definition: v8-profiler.h:113
virtual intptr_t GetSizeInBytes()
Definition: v8-profiler.h:553
static void DeleteAllProfiles()
const HeapGraphNode * GetNodeById(SnapshotObjectId id) const
Handle< String > GetTitle() const
void Serialize(OutputStream *stream, SerializationFormat format) const
virtual const char * GetGroupLabel()
Definition: v8-profiler.h:544
int GetLineNumber() const
static const SnapshotObjectId kUnknownObjectId
Definition: v8-profiler.h:426
double GetTotalSamplesCount() const