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.
5 #ifndef V8_V8_PROFILER_H_
6 #define V8_V8_PROFILER_H_
11 * Profiler support for the V8 JavaScript engine.
16 struct HeapStatsUpdate;
18 typedef uint32_t SnapshotObjectId;
21 * CpuProfileNode represents a node in a call graph.
23 class V8_EXPORT CpuProfileNode {
25 /** Returns function name (empty string for anonymous functions.) */
26 Handle<String> GetFunctionName() const;
28 /** Returns id of the script where function is located. */
29 int GetScriptId() const;
31 /** Returns resource name for script from where the function originates. */
32 Handle<String> GetScriptResourceName() const;
35 * Returns the number, 1-based, of the line where the function originates.
36 * kNoLineNumberInfo if no line number information is available.
38 int GetLineNumber() const;
41 * Returns 1-based number of the column where the function originates.
42 * kNoColumnNumberInfo if no column number information is available.
44 int GetColumnNumber() const;
46 /** Returns bailout reason for the function
47 * if the optimization was disabled for it.
49 const char* GetBailoutReason() const;
52 * Returns the count of samples where the function was currently executing.
54 unsigned GetHitCount() const;
56 /** Returns function entry UID. */
57 unsigned GetCallUid() const;
59 /** Returns id of the node. The id is unique within the tree */
60 unsigned GetNodeId() const;
62 /** Returns child nodes count of the node. */
63 int GetChildrenCount() const;
65 /** Retrieves a child node by index. */
66 const CpuProfileNode* GetChild(int index) const;
68 static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
69 static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
74 * CpuProfile contains a CPU profile in a form of top-down call tree
75 * (from main() down to functions that do all the work).
77 class V8_EXPORT CpuProfile {
79 /** Returns CPU profile title. */
80 Handle<String> GetTitle() const;
82 /** Returns the root node of the top down call tree. */
83 const CpuProfileNode* GetTopDownRoot() const;
86 * Returns number of samples recorded. The samples are not recorded unless
87 * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
89 int GetSamplesCount() const;
92 * Returns profile node corresponding to the top frame the sample at
95 const CpuProfileNode* GetSample(int index) const;
98 * Returns the timestamp of the sample. The timestamp is the number of
99 * microseconds since some unspecified starting point.
100 * The point is equal to the starting point used by GetStartTime.
102 int64_t GetSampleTimestamp(int index) const;
105 * Returns time when the profile recording was started (in microseconds)
106 * since some unspecified starting point.
108 int64_t GetStartTime() const;
111 * Returns time when the profile recording was stopped (in microseconds)
112 * since some unspecified starting point.
113 * The point is equal to the starting point used by GetStartTime.
115 int64_t GetEndTime() const;
118 * Deletes the profile and removes it from CpuProfiler's list.
119 * All pointers to nodes previously returned become invalid.
126 * Interface for controlling CPU profiling. Instance of the
127 * profiler can be retrieved using v8::Isolate::GetCpuProfiler.
129 class V8_EXPORT CpuProfiler {
132 * Changes default CPU profiler sampling interval to the specified number
133 * of microseconds. Default interval is 1000us. This method must be called
134 * when there are no profiles being recorded.
136 void SetSamplingInterval(int us);
139 * Starts collecting CPU profile. Title may be an empty string. It
140 * is allowed to have several profiles being collected at
141 * once. Attempts to start collecting several profiles with the same
142 * title are silently ignored. While collecting a profile, functions
143 * from all security contexts are included in it. The token-based
144 * filtering is only performed when querying for a profile.
146 * |record_samples| parameter controls whether individual samples should
147 * be recorded in addition to the aggregated tree.
149 void StartProfiling(Handle<String> title, bool record_samples = false);
151 /** Deprecated. Use StartProfiling instead. */
152 V8_DEPRECATED("Use StartProfiling",
153 void StartCpuProfiling(Handle<String> title,
154 bool record_samples = false));
157 * Stops collecting CPU profile with a given title and returns it.
158 * If the title given is empty, finishes the last profile started.
160 CpuProfile* StopProfiling(Handle<String> title);
162 /** Deprecated. Use StopProfiling instead. */
163 V8_DEPRECATED("Use StopProfiling",
164 const CpuProfile* StopCpuProfiling(Handle<String> title));
167 * Tells the profiler whether the embedder is idle.
169 void SetIdle(bool is_idle);
174 CpuProfiler(const CpuProfiler&);
175 CpuProfiler& operator=(const CpuProfiler&);
180 * HeapSnapshotEdge represents a directed connection between heap
181 * graph nodes: from retainers to retained nodes.
183 class V8_EXPORT HeapGraphEdge {
186 kContextVariable = 0, // A variable from a function context.
187 kElement = 1, // An element of an array.
188 kProperty = 2, // A named object property.
189 kInternal = 3, // A link that can't be accessed from JS,
190 // thus, its name isn't a real property name
191 // (e.g. parts of a ConsString).
192 kHidden = 4, // A link that is needed for proper sizes
193 // calculation, but may be hidden from user.
194 kShortcut = 5, // A link that must not be followed during
195 // sizes calculation.
196 kWeak = 6 // A weak reference (ignored by the GC).
199 /** Returns edge type (see HeapGraphEdge::Type). */
200 Type GetType() const;
203 * Returns edge name. This can be a variable name, an element index, or
206 Handle<Value> GetName() const;
208 /** Returns origin node. */
209 const HeapGraphNode* GetFromNode() const;
211 /** Returns destination node. */
212 const HeapGraphNode* GetToNode() const;
217 * HeapGraphNode represents a node in a heap graph.
219 class V8_EXPORT HeapGraphNode {
222 kHidden = 0, // Hidden node, may be filtered when shown to user.
223 kArray = 1, // An array of elements.
224 kString = 2, // A string.
225 kObject = 3, // A JS object (except for arrays and strings).
226 kCode = 4, // Compiled code.
227 kClosure = 5, // Function closure.
228 kRegExp = 6, // RegExp.
229 kHeapNumber = 7, // Number stored in the heap.
230 kNative = 8, // Native object (not from V8 heap).
231 kSynthetic = 9, // Synthetic object, usualy used for grouping
232 // snapshot items together.
233 kConsString = 10, // Concatenated string. A pair of pointers to strings.
234 kSlicedString = 11 // Sliced string. A fragment of another string.
237 /** Returns node type (see HeapGraphNode::Type). */
238 Type GetType() const;
241 * Returns node name. Depending on node's type this can be the name
242 * of the constructor (for objects), the name of the function (for
243 * closures), string value, or an empty string (for compiled code).
245 Handle<String> GetName() const;
248 * Returns node id. For the same heap object, the id remains the same
249 * across all snapshots.
251 SnapshotObjectId GetId() const;
253 /** Returns node's own size, in bytes. */
254 V8_DEPRECATED("Use GetShallowSize instead",
255 int GetSelfSize() const);
257 /** Returns node's own size, in bytes. */
258 size_t GetShallowSize() const;
260 /** Returns child nodes count of the node. */
261 int GetChildrenCount() const;
263 /** Retrieves a child by index. */
264 const HeapGraphEdge* GetChild(int index) const;
269 * An interface for exporting data from V8, using "push" model.
271 class V8_EXPORT OutputStream { // NOLINT
277 virtual ~OutputStream() {}
278 /** Notify about the end of stream. */
279 virtual void EndOfStream() = 0;
280 /** Get preferred output chunk size. Called only once. */
281 virtual int GetChunkSize() { return 1024; }
283 * Writes the next chunk of snapshot data into the stream. Writing
284 * can be stopped by returning kAbort as function result. EndOfStream
285 * will not be called in case writing was aborted.
287 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
289 * Writes the next chunk of heap stats data into the stream. Writing
290 * can be stopped by returning kAbort as function result. EndOfStream
291 * will not be called in case writing was aborted.
293 virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
300 * HeapSnapshots record the state of the JS heap at some moment.
302 class V8_EXPORT HeapSnapshot {
304 enum SerializationFormat {
305 kJSON = 0 // See format description near 'Serialize' method.
308 /** Returns heap snapshot UID (assigned by the profiler.) */
309 unsigned GetUid() const;
311 /** Returns heap snapshot title. */
312 Handle<String> GetTitle() const;
314 /** Returns the root node of the heap graph. */
315 const HeapGraphNode* GetRoot() const;
317 /** Returns a node by its id. */
318 const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
320 /** Returns total nodes count in the snapshot. */
321 int GetNodesCount() const;
323 /** Returns a node by index. */
324 const HeapGraphNode* GetNode(int index) const;
326 /** Returns a max seen JS object Id. */
327 SnapshotObjectId GetMaxSnapshotJSObjectId() const;
330 * Deletes the snapshot and removes it from HeapProfiler's list.
331 * All pointers to nodes, edges and paths previously returned become
337 * Prepare a serialized representation of the snapshot. The result
338 * is written into the stream provided in chunks of specified size.
339 * The total length of the serialized snapshot is unknown in
340 * advance, it can be roughly equal to JS heap size (that means,
341 * it can be really big - tens of megabytes).
343 * For the JSON format, heap contents are represented as an object
344 * with the following structure:
350 * meta: { meta-info },
354 * nodes: [nodes array],
355 * edges: [edges array],
356 * strings: [strings array]
359 * Nodes reference strings, other nodes, and edges by their indexes
360 * in corresponding arrays.
362 void Serialize(OutputStream* stream, SerializationFormat format) const;
367 * An interface for reporting progress and controlling long-running
370 class V8_EXPORT ActivityControl { // NOLINT
376 virtual ~ActivityControl() {}
378 * Notify about current progress. The activity can be stopped by
379 * returning kAbort as the callback result.
381 virtual ControlOption ReportProgressValue(int done, int total) = 0;
386 * Interface for controlling heap profiling. Instance of the
387 * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
389 class V8_EXPORT HeapProfiler {
392 * Callback function invoked for obtaining RetainedObjectInfo for
393 * the given JavaScript wrapper object. It is prohibited to enter V8
394 * while the callback is running: only getters on the handle and
395 * GetPointerFromInternalField on the objects are allowed.
397 typedef RetainedObjectInfo* (*WrapperInfoCallback)
398 (uint16_t class_id, Handle<Value> wrapper);
400 /** Returns the number of snapshots taken. */
401 int GetSnapshotCount();
403 /** Returns a snapshot by index. */
404 const HeapSnapshot* GetHeapSnapshot(int index);
407 * Returns SnapshotObjectId for a heap object referenced by |value| if
408 * it has been seen by the heap profiler, kUnknownObjectId otherwise.
410 SnapshotObjectId GetObjectId(Handle<Value> value);
413 * Returns heap object with given SnapshotObjectId if the object is alive,
414 * otherwise empty handle is returned.
416 Handle<Value> FindObjectById(SnapshotObjectId id);
419 * Clears internal map from SnapshotObjectId to heap object. The new objects
420 * will not be added into it unless a heap snapshot is taken or heap object
421 * tracking is kicked off.
423 void ClearObjectIds();
426 * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
427 * it in case heap profiler cannot find id for the object passed as
428 * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
430 static const SnapshotObjectId kUnknownObjectId = 0;
433 * Callback interface for retrieving user friendly names of global objects.
435 class ObjectNameResolver {
438 * Returns name to be used in the heap snapshot for given node. Returned
439 * string must stay alive until snapshot collection is completed.
441 virtual const char* GetName(Handle<Object> object) = 0;
443 virtual ~ObjectNameResolver() {}
447 * Takes a heap snapshot and returns it. Title may be an empty string.
449 const HeapSnapshot* TakeHeapSnapshot(
450 Handle<String> title,
451 ActivityControl* control = NULL,
452 ObjectNameResolver* global_object_name_resolver = NULL);
455 * Starts tracking of heap objects population statistics. After calling
456 * this method, all heap objects relocations done by the garbage collector
457 * are being registered.
459 * |track_allocations| parameter controls whether stack trace of each
460 * allocation in the heap will be recorded and reported as part of
463 void StartTrackingHeapObjects(bool track_allocations = false);
466 * Adds a new time interval entry to the aggregated statistics array. The
467 * time interval entry contains information on the current heap objects
468 * population size. The method also updates aggregated statistics and
469 * reports updates for all previous time intervals via the OutputStream
470 * object. Updates on each time interval are provided as a stream of the
471 * HeapStatsUpdate structure instances.
472 * The return value of the function is the last seen heap object Id.
474 * StartTrackingHeapObjects must be called before the first call to this
477 SnapshotObjectId GetHeapStats(OutputStream* stream);
480 * Stops tracking of heap objects population statistics, cleans up all
481 * collected data. StartHeapObjectsTracking must be called again prior to
482 * calling PushHeapObjectsStats next time.
484 void StopTrackingHeapObjects();
487 * Deletes all snapshots taken. All previously returned pointers to
488 * snapshots and their contents become invalid after this call.
490 void DeleteAllHeapSnapshots();
492 /** Binds a callback to embedder's class ID. */
493 void SetWrapperClassInfoProvider(
495 WrapperInfoCallback callback);
498 * Default value of persistent handle class ID. Must not be used to
499 * define a class. Can be used to reset a class of a persistent
502 static const uint16_t kPersistentHandleNoClassId = 0;
504 /** Returns memory used for profiler internal data and snapshots. */
505 size_t GetProfilerMemorySize();
508 * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
510 void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo* info);
515 HeapProfiler(const HeapProfiler&);
516 HeapProfiler& operator=(const HeapProfiler&);
521 * Interface for providing information about embedder's objects
522 * held by global handles. This information is reported in two ways:
524 * 1. When calling AddObjectGroup, an embedder may pass
525 * RetainedObjectInfo instance describing the group. To collect
526 * this information while taking a heap snapshot, V8 calls GC
527 * prologue and epilogue callbacks.
529 * 2. When a heap snapshot is collected, V8 additionally
530 * requests RetainedObjectInfos for persistent handles that
531 * were not previously reported via AddObjectGroup.
533 * Thus, if an embedder wants to provide information about native
534 * objects for heap snapshots, he can do it in a GC prologue
535 * handler, and / or by assigning wrapper class ids in the following way:
537 * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
538 * 2. Call SetWrapperClassId on certain persistent handles.
540 * V8 takes ownership of RetainedObjectInfo instances passed to it and
541 * keeps them alive only during snapshot collection. Afterwards, they
542 * are freed by calling the Dispose class function.
544 class V8_EXPORT RetainedObjectInfo { // NOLINT
546 /** Called by V8 when it no longer needs an instance. */
547 virtual void Dispose() = 0;
549 /** Returns whether two instances are equivalent. */
550 virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
553 * Returns hash value for the instance. Equivalent instances
554 * must have the same hash value.
556 virtual intptr_t GetHash() = 0;
559 * Returns human-readable label. It must be a null-terminated UTF-8
560 * encoded string. V8 copies its contents during a call to GetLabel.
562 virtual const char* GetLabel() = 0;
565 * Returns human-readable group label. It must be a null-terminated UTF-8
566 * encoded string. V8 copies its contents during a call to GetGroupLabel.
567 * Heap snapshot generator will collect all the group names, create
568 * top level entries with these names and attach the objects to the
569 * corresponding top level group objects. There is a default
570 * implementation which is required because embedders don't have their
571 * own implementation yet.
573 virtual const char* GetGroupLabel() { return GetLabel(); }
576 * Returns element count in case if a global handle retains
577 * a subgraph by holding one of its nodes.
579 virtual intptr_t GetElementCount() { return -1; }
581 /** Returns embedder's object size in bytes. */
582 virtual intptr_t GetSizeInBytes() { return -1; }
585 RetainedObjectInfo() {}
586 virtual ~RetainedObjectInfo() {}
589 RetainedObjectInfo(const RetainedObjectInfo&);
590 RetainedObjectInfo& operator=(const RetainedObjectInfo&);
595 * A struct for exporting HeapStats data from V8, using "push" model.
596 * See HeapProfiler::GetHeapStats.
598 struct HeapStatsUpdate {
599 HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
600 : index(index), count(count), size(size) { }
601 uint32_t index; // Index of the time interval that was changed.
602 uint32_t count; // New value of count field for the interval with this index.
603 uint32_t size; // New value of size field for the interval with this index.
610 #endif // V8_V8_PROFILER_H_