blob: f67646f54e77d90668e50491382777a46cd10d7b [file] [log] [blame]
Steve Block6ded16b2010-05-10 14:33:55 +01001// 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 */
65namespace v8 {
66
67
68/**
69 * CpuProfileNode represents a node in a call graph.
70 */
71class V8EXPORT CpuProfileNode {
72 public:
73 /** Returns function name (empty string for anonymous functions.) */
74 Handle<String> GetFunctionName() const;
75
76 /** Returns resource name for script from where the function originates. */
77 Handle<String> GetScriptResourceName() const;
78
79 /**
80 * Returns the number, 1-based, of the line where the function originates.
81 * kNoLineNumberInfo if no line number information is available.
82 */
83 int GetLineNumber() const;
84
85 /**
86 * Returns total (self + children) execution time of the function,
87 * in milliseconds, estimated by samples count.
88 */
89 double GetTotalTime() const;
90
91 /**
92 * Returns self execution time of the function, in milliseconds,
93 * estimated by samples count.
94 */
95 double GetSelfTime() const;
96
97 /** Returns the count of samples where function exists. */
98 double GetTotalSamplesCount() const;
99
100 /** Returns the count of samples where function was currently executing. */
101 double GetSelfSamplesCount() const;
102
103 /** Returns function entry UID. */
104 unsigned GetCallUid() const;
105
106 /** Returns child nodes count of the node. */
107 int GetChildrenCount() const;
108
109 /** Retrieves a child node by index. */
110 const CpuProfileNode* GetChild(int index) const;
111
Kristian Monsen25f61362010-05-21 11:50:48 +0100112 static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
Steve Block6ded16b2010-05-10 14:33:55 +0100113};
114
115
116/**
117 * CpuProfile contains a CPU profile in a form of two call trees:
118 * - top-down (from main() down to functions that do all the work);
119 * - bottom-up call graph (in backward direction).
120 */
121class V8EXPORT CpuProfile {
122 public:
123 /** Returns CPU profile UID (assigned by the profiler.) */
124 unsigned GetUid() const;
125
126 /** Returns CPU profile title. */
127 Handle<String> GetTitle() const;
128
129 /** Returns the root node of the bottom up call tree. */
130 const CpuProfileNode* GetBottomUpRoot() const;
131
132 /** Returns the root node of the top down call tree. */
133 const CpuProfileNode* GetTopDownRoot() const;
Steve Block44f0eee2011-05-26 01:26:41 +0100134
135 /**
136 * Deletes the profile and removes it from CpuProfiler's list.
137 * All pointers to nodes previously returned become invalid.
138 * Profiles with the same uid but obtained using different
139 * security token are not deleted, but become inaccessible
140 * using FindProfile method. It is embedder's responsibility
141 * to call Delete on these profiles.
142 */
143 void Delete();
Steve Block6ded16b2010-05-10 14:33:55 +0100144};
145
146
147/**
148 * Interface for controlling CPU profiling.
149 */
150class V8EXPORT CpuProfiler {
151 public:
152 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100153 * A note on security tokens usage. As scripts from different
154 * origins can run inside a single V8 instance, it is possible to
155 * have functions from different security contexts intermixed in a
156 * single CPU profile. To avoid exposing function names belonging to
157 * other contexts, filtering by security token is performed while
158 * obtaining profiling results.
159 */
160
161 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100162 * Returns the number of profiles collected (doesn't include
163 * profiles that are being collected at the moment of call.)
164 */
165 static int GetProfilesCount();
166
167 /** Returns a profile by index. */
Leon Clarkef7060e22010-06-03 12:02:55 +0100168 static const CpuProfile* GetProfile(
169 int index,
170 Handle<Value> security_token = Handle<Value>());
Steve Block6ded16b2010-05-10 14:33:55 +0100171
172 /** Returns a profile by uid. */
Leon Clarkef7060e22010-06-03 12:02:55 +0100173 static const CpuProfile* FindProfile(
174 unsigned uid,
175 Handle<Value> security_token = Handle<Value>());
Steve Block6ded16b2010-05-10 14:33:55 +0100176
177 /**
178 * Starts collecting CPU profile. Title may be an empty string. It
179 * is allowed to have several profiles being collected at
180 * once. Attempts to start collecting several profiles with the same
Leon Clarkef7060e22010-06-03 12:02:55 +0100181 * title are silently ignored. While collecting a profile, functions
182 * from all security contexts are included in it. The token-based
183 * filtering is only performed when querying for a profile.
Steve Block6ded16b2010-05-10 14:33:55 +0100184 */
185 static void StartProfiling(Handle<String> title);
186
187 /**
188 * Stops collecting CPU profile with a given title and returns it.
189 * If the title given is empty, finishes the last profile started.
190 */
Leon Clarkef7060e22010-06-03 12:02:55 +0100191 static const CpuProfile* StopProfiling(
192 Handle<String> title,
193 Handle<Value> security_token = Handle<Value>());
Steve Block44f0eee2011-05-26 01:26:41 +0100194
195 /**
196 * Deletes all existing profiles, also cancelling all profiling
197 * activity. All previously returned pointers to profiles and their
198 * contents become invalid after this call.
199 */
200 static void DeleteAllProfiles();
Steve Block6ded16b2010-05-10 14:33:55 +0100201};
202
203
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100204class HeapGraphNode;
205
206
207/**
208 * HeapSnapshotEdge represents a directed connection between heap
Ben Murdoch257744e2011-11-30 15:57:28 +0000209 * graph nodes: from retainers to retained nodes.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100210 */
211class V8EXPORT HeapGraphEdge {
212 public:
213 enum Type {
Iain Merrick75681382010-08-19 15:07:18 +0100214 kContextVariable = 0, // A variable from a function context.
215 kElement = 1, // An element of an array.
216 kProperty = 2, // A named object property.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800217 kInternal = 3, // A link that can't be accessed from JS,
218 // thus, its name isn't a real property name
219 // (e.g. parts of a ConsString).
220 kHidden = 4, // A link that is needed for proper sizes
221 // calculation, but may be hidden from user.
Ben Murdoch85b71792012-04-11 18:30:58 +0100222 kShortcut = 5 // A link that must not be followed during
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800223 // sizes calculation.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100224 };
225
226 /** Returns edge type (see HeapGraphEdge::Type). */
227 Type GetType() const;
228
229 /**
230 * Returns edge name. This can be a variable name, an element index, or
231 * a property name.
232 */
233 Handle<Value> GetName() const;
234
235 /** Returns origin node. */
236 const HeapGraphNode* GetFromNode() const;
237
238 /** Returns destination node. */
239 const HeapGraphNode* GetToNode() const;
240};
241
242
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100243/**
244 * HeapGraphNode represents a node in a heap graph.
245 */
246class V8EXPORT HeapGraphNode {
247 public:
248 enum Type {
Steve Block44f0eee2011-05-26 01:26:41 +0100249 kHidden = 0, // Hidden node, may be filtered when shown to user.
250 kArray = 1, // An array of elements.
251 kString = 2, // A string.
252 kObject = 3, // A JS object (except for arrays and strings).
253 kCode = 4, // Compiled code.
254 kClosure = 5, // Function closure.
255 kRegExp = 6, // RegExp.
256 kHeapNumber = 7, // Number stored in the heap.
Ben Murdoch85b71792012-04-11 18:30:58 +0100257 kNative = 8 // Native object (not from V8 heap).
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100258 };
259
260 /** Returns node type (see HeapGraphNode::Type). */
261 Type GetType() const;
262
263 /**
264 * Returns node name. Depending on node's type this can be the name
265 * of the constructor (for objects), the name of the function (for
266 * closures), string value, or an empty string (for compiled code).
267 */
268 Handle<String> GetName() const;
269
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100270 /**
271 * Returns node id. For the same heap object, the id remains the same
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000272 * across all snapshots.
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100273 */
274 uint64_t GetId() const;
275
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100276 /** Returns node's own size, in bytes. */
277 int GetSelfSize() const;
278
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100279 /**
Iain Merrick75681382010-08-19 15:07:18 +0100280 * Returns node's retained size, in bytes. That is, self + sizes of
281 * the objects that are reachable only from this object. In other
282 * words, the size of memory that will be reclaimed having this node
283 * collected.
Ben Murdoch85b71792012-04-11 18:30:58 +0100284 *
285 * Exact retained size calculation has O(N) (number of nodes)
286 * computational complexity, while approximate has O(1). It is
287 * assumed that initially heap profiling tools provide approximate
288 * sizes for all nodes, and then exact sizes are calculated for the
289 * most 'interesting' nodes.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100290 */
Ben Murdoch85b71792012-04-11 18:30:58 +0100291 int GetRetainedSize(bool exact) const;
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100292
293 /** Returns child nodes count of the node. */
294 int GetChildrenCount() const;
295
296 /** Retrieves a child by index. */
297 const HeapGraphEdge* GetChild(int index) const;
298
299 /** Returns retainer nodes count of the node. */
300 int GetRetainersCount() const;
301
302 /** Returns a retainer by index. */
303 const HeapGraphEdge* GetRetainer(int index) const;
304
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800305 /**
306 * Returns a dominator node. This is the node that participates in every
307 * path from the snapshot root to the current node.
308 */
309 const HeapGraphNode* GetDominatorNode() const;
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000310
311 /**
312 * Finds and returns a value from the heap corresponding to this node,
313 * if the value is still reachable.
314 */
315 Handle<Value> GetHeapValue() const;
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100316};
317
318
319/**
320 * HeapSnapshots record the state of the JS heap at some moment.
321 */
322class V8EXPORT HeapSnapshot {
323 public:
Steve Block791712a2010-08-27 10:21:07 +0100324 enum Type {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000325 kFull = 0 // Heap snapshot with all instances and references.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100326 };
327 enum SerializationFormat {
328 kJSON = 0 // See format description near 'Serialize' method.
Steve Block791712a2010-08-27 10:21:07 +0100329 };
330
331 /** Returns heap snapshot type. */
332 Type GetType() const;
333
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100334 /** Returns heap snapshot UID (assigned by the profiler.) */
335 unsigned GetUid() const;
336
337 /** Returns heap snapshot title. */
338 Handle<String> GetTitle() const;
339
340 /** Returns the root node of the heap graph. */
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100341 const HeapGraphNode* GetRoot() const;
342
Ben Murdochb0fe1622011-05-05 13:52:32 +0100343 /** Returns a node by its id. */
344 const HeapGraphNode* GetNodeById(uint64_t id) const;
345
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000346 /** Returns total nodes count in the snapshot. */
347 int GetNodesCount() const;
348
349 /** Returns a node by index. */
350 const HeapGraphNode* GetNode(int index) const;
351
Steve Block791712a2010-08-27 10:21:07 +0100352 /**
Steve Block44f0eee2011-05-26 01:26:41 +0100353 * Deletes the snapshot and removes it from HeapProfiler's list.
354 * All pointers to nodes, edges and paths previously returned become
355 * invalid.
Steve Block791712a2010-08-27 10:21:07 +0100356 */
Steve Block44f0eee2011-05-26 01:26:41 +0100357 void Delete();
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100358
359 /**
360 * Prepare a serialized representation of the snapshot. The result
361 * is written into the stream provided in chunks of specified size.
362 * The total length of the serialized snapshot is unknown in
Ben Murdoch257744e2011-11-30 15:57:28 +0000363 * advance, it can be roughly equal to JS heap size (that means,
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100364 * it can be really big - tens of megabytes).
365 *
366 * For the JSON format, heap contents are represented as an object
367 * with the following structure:
368 *
369 * {
370 * snapshot: {title: "...", uid: nnn},
371 * nodes: [
372 * meta-info (JSON string),
373 * nodes themselves
374 * ],
375 * strings: [strings]
376 * }
377 *
378 * Outgoing node links are stored after each node. Nodes reference strings
379 * and other nodes by their indexes in corresponding arrays.
380 */
381 void Serialize(OutputStream* stream, SerializationFormat format) const;
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100382};
383
384
Steve Block44f0eee2011-05-26 01:26:41 +0100385class RetainedObjectInfo;
386
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100387/**
388 * Interface for controlling heap profiling.
389 */
390class V8EXPORT HeapProfiler {
391 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100392 /**
393 * Callback function invoked for obtaining RetainedObjectInfo for
394 * the given JavaScript wrapper object. It is prohibited to enter V8
395 * while the callback is running: only getters on the handle and
396 * GetPointerFromInternalField on the objects are allowed.
397 */
398 typedef RetainedObjectInfo* (*WrapperInfoCallback)
399 (uint16_t class_id, Handle<Value> wrapper);
400
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100401 /** Returns the number of snapshots taken. */
402 static int GetSnapshotsCount();
403
404 /** Returns a snapshot by index. */
405 static const HeapSnapshot* GetSnapshot(int index);
406
407 /** Returns a profile by uid. */
408 static const HeapSnapshot* FindSnapshot(unsigned uid);
409
Steve Block791712a2010-08-27 10:21:07 +0100410 /**
411 * Takes a heap snapshot and returns it. Title may be an empty string.
412 * See HeapSnapshot::Type for types description.
413 */
414 static const HeapSnapshot* TakeSnapshot(
415 Handle<String> title,
Ben Murdochb0fe1622011-05-05 13:52:32 +0100416 HeapSnapshot::Type type = HeapSnapshot::kFull,
417 ActivityControl* control = NULL);
Steve Block44f0eee2011-05-26 01:26:41 +0100418
419 /**
420 * Deletes all snapshots taken. All previously returned pointers to
421 * snapshots and their contents become invalid after this call.
422 */
423 static void DeleteAllSnapshots();
424
425 /** Binds a callback to embedder's class ID. */
426 static void DefineWrapperClass(
427 uint16_t class_id,
428 WrapperInfoCallback callback);
429
430 /**
431 * Default value of persistent handle class ID. Must not be used to
432 * define a class. Can be used to reset a class of a persistent
433 * handle.
434 */
435 static const uint16_t kPersistentHandleNoClassId = 0;
436};
437
438
439/**
440 * Interface for providing information about embedder's objects
441 * held by global handles. This information is reported in two ways:
442 *
443 * 1. When calling AddObjectGroup, an embedder may pass
444 * RetainedObjectInfo instance describing the group. To collect
445 * this information while taking a heap snapshot, V8 calls GC
446 * prologue and epilogue callbacks.
447 *
448 * 2. When a heap snapshot is collected, V8 additionally
449 * requests RetainedObjectInfos for persistent handles that
450 * were not previously reported via AddObjectGroup.
451 *
452 * Thus, if an embedder wants to provide information about native
453 * objects for heap snapshots, he can do it in a GC prologue
454 * handler, and / or by assigning wrapper class ids in the following way:
455 *
456 * 1. Bind a callback to class id by calling DefineWrapperClass.
457 * 2. Call SetWrapperClassId on certain persistent handles.
458 *
459 * V8 takes ownership of RetainedObjectInfo instances passed to it and
460 * keeps them alive only during snapshot collection. Afterwards, they
461 * are freed by calling the Dispose class function.
462 */
463class V8EXPORT RetainedObjectInfo { // NOLINT
464 public:
465 /** Called by V8 when it no longer needs an instance. */
466 virtual void Dispose() = 0;
467
468 /** Returns whether two instances are equivalent. */
469 virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
470
471 /**
472 * Returns hash value for the instance. Equivalent instances
473 * must have the same hash value.
474 */
475 virtual intptr_t GetHash() = 0;
476
477 /**
Ben Murdoch85b71792012-04-11 18:30:58 +0100478 * Returns human-readable label. It must be a NUL-terminated UTF-8
Steve Block44f0eee2011-05-26 01:26:41 +0100479 * encoded string. V8 copies its contents during a call to GetLabel.
480 */
481 virtual const char* GetLabel() = 0;
482
483 /**
484 * Returns element count in case if a global handle retains
485 * a subgraph by holding one of its nodes.
486 */
487 virtual intptr_t GetElementCount() { return -1; }
488
489 /** Returns embedder's object size in bytes. */
490 virtual intptr_t GetSizeInBytes() { return -1; }
491
492 protected:
493 RetainedObjectInfo() {}
494 virtual ~RetainedObjectInfo() {}
495
496 private:
497 RetainedObjectInfo(const RetainedObjectInfo&);
498 RetainedObjectInfo& operator=(const RetainedObjectInfo&);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100499};
500
501
Steve Block6ded16b2010-05-10 14:33:55 +0100502} // namespace v8
503
504
505#undef V8EXPORT
506
507
508#endif // V8_V8_PROFILER_H_