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