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 {
26 /** The 1-based number of the source line where the function originates. */
29 /** The count of samples associated with the source line. */
30 unsigned int hit_count;
33 /** Returns function name (empty string for anonymous functions.) */
34 Handle<String> GetFunctionName() const;
36 /** Returns id of the script where function is located. */
37 int GetScriptId() const;
39 /** Returns resource name for script from where the function originates. */
40 Handle<String> GetScriptResourceName() const;
43 * Returns the number, 1-based, of the line where the function originates.
44 * kNoLineNumberInfo if no line number information is available.
46 int GetLineNumber() const;
49 * Returns 1-based number of the column where the function originates.
50 * kNoColumnNumberInfo if no column number information is available.
52 int GetColumnNumber() const;
55 * Returns the number of the function's source lines that collect the samples.
57 unsigned int GetHitLineCount() const;
59 /** Returns the set of source lines that collect the samples.
60 * The caller allocates buffer and responsible for releasing it.
61 * True if all available entries are copied, otherwise false.
62 * The function copies nothing if buffer is not large enough.
64 bool GetLineTicks(LineTick* entries, unsigned int length) const;
66 /** Returns bailout reason for the function
67 * if the optimization was disabled for it.
69 const char* GetBailoutReason() const;
72 * Returns the count of samples where the function was currently executing.
74 unsigned GetHitCount() const;
76 /** Returns function entry UID. */
77 unsigned GetCallUid() const;
79 /** Returns id of the node. The id is unique within the tree */
80 unsigned GetNodeId() const;
82 /** Returns child nodes count of the node. */
83 int GetChildrenCount() const;
85 /** Retrieves a child node by index. */
86 const CpuProfileNode* GetChild(int index) const;
88 static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
89 static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
94 * CpuProfile contains a CPU profile in a form of top-down call tree
95 * (from main() down to functions that do all the work).
97 class V8_EXPORT CpuProfile {
99 /** Returns CPU profile title. */
100 Handle<String> GetTitle() const;
102 /** Returns the root node of the top down call tree. */
103 const CpuProfileNode* GetTopDownRoot() const;
106 * Returns number of samples recorded. The samples are not recorded unless
107 * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
109 int GetSamplesCount() const;
112 * Returns profile node corresponding to the top frame the sample at
115 const CpuProfileNode* GetSample(int index) const;
118 * Returns the timestamp of the sample. The timestamp is the number of
119 * microseconds since some unspecified starting point.
120 * The point is equal to the starting point used by GetStartTime.
122 int64_t GetSampleTimestamp(int index) const;
125 * Returns time when the profile recording was started (in microseconds)
126 * since some unspecified starting point.
128 int64_t GetStartTime() const;
131 * Returns time when the profile recording was stopped (in microseconds)
132 * since some unspecified starting point.
133 * The point is equal to the starting point used by GetStartTime.
135 int64_t GetEndTime() const;
138 * Deletes the profile and removes it from CpuProfiler's list.
139 * All pointers to nodes previously returned become invalid.
146 * Interface for controlling CPU profiling. Instance of the
147 * profiler can be retrieved using v8::Isolate::GetCpuProfiler.
149 class V8_EXPORT CpuProfiler {
152 * Changes default CPU profiler sampling interval to the specified number
153 * of microseconds. Default interval is 1000us. This method must be called
154 * when there are no profiles being recorded.
156 void SetSamplingInterval(int us);
159 * Starts collecting CPU profile. Title may be an empty string. It
160 * is allowed to have several profiles being collected at
161 * once. Attempts to start collecting several profiles with the same
162 * title are silently ignored. While collecting a profile, functions
163 * from all security contexts are included in it. The token-based
164 * filtering is only performed when querying for a profile.
166 * |record_samples| parameter controls whether individual samples should
167 * be recorded in addition to the aggregated tree.
169 void StartProfiling(Handle<String> title, bool record_samples = false);
171 /** Deprecated. Use StartProfiling instead. */
172 V8_DEPRECATED("Use StartProfiling",
173 void StartCpuProfiling(Handle<String> title,
174 bool record_samples = false));
177 * Stops collecting CPU profile with a given title and returns it.
178 * If the title given is empty, finishes the last profile started.
180 CpuProfile* StopProfiling(Handle<String> title);
182 /** Deprecated. Use StopProfiling instead. */
183 V8_DEPRECATED("Use StopProfiling",
184 const CpuProfile* StopCpuProfiling(Handle<String> title));
187 * Tells the profiler whether the embedder is idle.
189 void SetIdle(bool is_idle);
194 CpuProfiler(const CpuProfiler&);
195 CpuProfiler& operator=(const CpuProfiler&);
200 * HeapSnapshotEdge represents a directed connection between heap
201 * graph nodes: from retainers to retained nodes.
203 class V8_EXPORT HeapGraphEdge {
206 kContextVariable = 0, // A variable from a function context.
207 kElement = 1, // An element of an array.
208 kProperty = 2, // A named object property.
209 kInternal = 3, // A link that can't be accessed from JS,
210 // thus, its name isn't a real property name
211 // (e.g. parts of a ConsString).
212 kHidden = 4, // A link that is needed for proper sizes
213 // calculation, but may be hidden from user.
214 kShortcut = 5, // A link that must not be followed during
215 // sizes calculation.
216 kWeak = 6 // A weak reference (ignored by the GC).
219 /** Returns edge type (see HeapGraphEdge::Type). */
220 Type GetType() const;
223 * Returns edge name. This can be a variable name, an element index, or
226 Handle<Value> GetName() const;
228 /** Returns origin node. */
229 const HeapGraphNode* GetFromNode() const;
231 /** Returns destination node. */
232 const HeapGraphNode* GetToNode() const;
237 * HeapGraphNode represents a node in a heap graph.
239 class V8_EXPORT HeapGraphNode {
242 kHidden = 0, // Hidden node, may be filtered when shown to user.
243 kArray = 1, // An array of elements.
244 kString = 2, // A string.
245 kObject = 3, // A JS object (except for arrays and strings).
246 kCode = 4, // Compiled code.
247 kClosure = 5, // Function closure.
248 kRegExp = 6, // RegExp.
249 kHeapNumber = 7, // Number stored in the heap.
250 kNative = 8, // Native object (not from V8 heap).
251 kSynthetic = 9, // Synthetic object, usualy used for grouping
252 // snapshot items together.
253 kConsString = 10, // Concatenated string. A pair of pointers to strings.
254 kSlicedString = 11, // Sliced string. A fragment of another string.
255 kSymbol = 12 // A Symbol (ES6).
258 /** Returns node type (see HeapGraphNode::Type). */
259 Type GetType() const;
262 * Returns node name. Depending on node's type this can be the name
263 * of the constructor (for objects), the name of the function (for
264 * closures), string value, or an empty string (for compiled code).
266 Handle<String> GetName() const;
269 * Returns node id. For the same heap object, the id remains the same
270 * across all snapshots.
272 SnapshotObjectId GetId() const;
274 /** Returns node's own size, in bytes. */
275 V8_DEPRECATED("Use GetShallowSize instead",
276 int GetSelfSize() const);
278 /** Returns node's own size, in bytes. */
279 size_t GetShallowSize() const;
281 /** Returns child nodes count of the node. */
282 int GetChildrenCount() const;
284 /** Retrieves a child by index. */
285 const HeapGraphEdge* GetChild(int index) const;
290 * An interface for exporting data from V8, using "push" model.
292 class V8_EXPORT OutputStream { // NOLINT
298 virtual ~OutputStream() {}
299 /** Notify about the end of stream. */
300 virtual void EndOfStream() = 0;
301 /** Get preferred output chunk size. Called only once. */
302 virtual int GetChunkSize() { return 1024; }
304 * Writes the next chunk of snapshot data into the stream. Writing
305 * can be stopped by returning kAbort as function result. EndOfStream
306 * will not be called in case writing was aborted.
308 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
310 * Writes the next chunk of heap stats data into the stream. Writing
311 * can be stopped by returning kAbort as function result. EndOfStream
312 * will not be called in case writing was aborted.
314 virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
321 * HeapSnapshots record the state of the JS heap at some moment.
323 class V8_EXPORT HeapSnapshot {
325 enum SerializationFormat {
326 kJSON = 0 // See format description near 'Serialize' method.
329 /** Returns heap snapshot UID (assigned by the profiler.) */
330 unsigned GetUid() const;
332 /** Returns heap snapshot title. */
333 Handle<String> GetTitle() const;
335 /** Returns the root node of the heap graph. */
336 const HeapGraphNode* GetRoot() const;
338 /** Returns a node by its id. */
339 const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
341 /** Returns total nodes count in the snapshot. */
342 int GetNodesCount() const;
344 /** Returns a node by index. */
345 const HeapGraphNode* GetNode(int index) const;
347 /** Returns a max seen JS object Id. */
348 SnapshotObjectId GetMaxSnapshotJSObjectId() const;
351 * Deletes the snapshot and removes it from HeapProfiler's list.
352 * All pointers to nodes, edges and paths previously returned become
358 * Prepare a serialized representation of the snapshot. The result
359 * is written into the stream provided in chunks of specified size.
360 * The total length of the serialized snapshot is unknown in
361 * advance, it can be roughly equal to JS heap size (that means,
362 * it can be really big - tens of megabytes).
364 * For the JSON format, heap contents are represented as an object
365 * with the following structure:
371 * meta: { meta-info },
375 * nodes: [nodes array],
376 * edges: [edges array],
377 * strings: [strings array]
380 * Nodes reference strings, other nodes, and edges by their indexes
381 * in corresponding arrays.
383 void Serialize(OutputStream* stream, SerializationFormat format) const;
388 * An interface for reporting progress and controlling long-running
391 class V8_EXPORT ActivityControl { // NOLINT
397 virtual ~ActivityControl() {}
399 * Notify about current progress. The activity can be stopped by
400 * returning kAbort as the callback result.
402 virtual ControlOption ReportProgressValue(int done, int total) = 0;
407 * Interface for controlling heap profiling. Instance of the
408 * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
410 class V8_EXPORT HeapProfiler {
413 * Callback function invoked for obtaining RetainedObjectInfo for
414 * the given JavaScript wrapper object. It is prohibited to enter V8
415 * while the callback is running: only getters on the handle and
416 * GetPointerFromInternalField on the objects are allowed.
418 typedef RetainedObjectInfo* (*WrapperInfoCallback)
419 (uint16_t class_id, Handle<Value> wrapper);
421 /** Returns the number of snapshots taken. */
422 int GetSnapshotCount();
424 /** Returns a snapshot by index. */
425 const HeapSnapshot* GetHeapSnapshot(int index);
428 * Returns SnapshotObjectId for a heap object referenced by |value| if
429 * it has been seen by the heap profiler, kUnknownObjectId otherwise.
431 SnapshotObjectId GetObjectId(Handle<Value> value);
434 * Returns heap object with given SnapshotObjectId if the object is alive,
435 * otherwise empty handle is returned.
437 Handle<Value> FindObjectById(SnapshotObjectId id);
440 * Clears internal map from SnapshotObjectId to heap object. The new objects
441 * will not be added into it unless a heap snapshot is taken or heap object
442 * tracking is kicked off.
444 void ClearObjectIds();
447 * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
448 * it in case heap profiler cannot find id for the object passed as
449 * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
451 static const SnapshotObjectId kUnknownObjectId = 0;
454 * Callback interface for retrieving user friendly names of global objects.
456 class ObjectNameResolver {
459 * Returns name to be used in the heap snapshot for given node. Returned
460 * string must stay alive until snapshot collection is completed.
462 virtual const char* GetName(Handle<Object> object) = 0;
464 virtual ~ObjectNameResolver() {}
468 * Takes a heap snapshot and returns it. Title may be an empty string.
470 const HeapSnapshot* TakeHeapSnapshot(
471 Handle<String> title,
472 ActivityControl* control = NULL,
473 ObjectNameResolver* global_object_name_resolver = NULL);
476 * Starts tracking of heap objects population statistics. After calling
477 * this method, all heap objects relocations done by the garbage collector
478 * are being registered.
480 * |track_allocations| parameter controls whether stack trace of each
481 * allocation in the heap will be recorded and reported as part of
484 void StartTrackingHeapObjects(bool track_allocations = false);
487 * Adds a new time interval entry to the aggregated statistics array. The
488 * time interval entry contains information on the current heap objects
489 * population size. The method also updates aggregated statistics and
490 * reports updates for all previous time intervals via the OutputStream
491 * object. Updates on each time interval are provided as a stream of the
492 * HeapStatsUpdate structure instances.
493 * The return value of the function is the last seen heap object Id.
495 * StartTrackingHeapObjects must be called before the first call to this
498 SnapshotObjectId GetHeapStats(OutputStream* stream);
501 * Stops tracking of heap objects population statistics, cleans up all
502 * collected data. StartHeapObjectsTracking must be called again prior to
503 * calling PushHeapObjectsStats next time.
505 void StopTrackingHeapObjects();
508 * Deletes all snapshots taken. All previously returned pointers to
509 * snapshots and their contents become invalid after this call.
511 void DeleteAllHeapSnapshots();
513 /** Binds a callback to embedder's class ID. */
514 void SetWrapperClassInfoProvider(
516 WrapperInfoCallback callback);
519 * Default value of persistent handle class ID. Must not be used to
520 * define a class. Can be used to reset a class of a persistent
523 static const uint16_t kPersistentHandleNoClassId = 0;
525 /** Returns memory used for profiler internal data and snapshots. */
526 size_t GetProfilerMemorySize();
529 * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
531 void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo* info);
536 HeapProfiler(const HeapProfiler&);
537 HeapProfiler& operator=(const HeapProfiler&);
542 * Interface for providing information about embedder's objects
543 * held by global handles. This information is reported in two ways:
545 * 1. When calling AddObjectGroup, an embedder may pass
546 * RetainedObjectInfo instance describing the group. To collect
547 * this information while taking a heap snapshot, V8 calls GC
548 * prologue and epilogue callbacks.
550 * 2. When a heap snapshot is collected, V8 additionally
551 * requests RetainedObjectInfos for persistent handles that
552 * were not previously reported via AddObjectGroup.
554 * Thus, if an embedder wants to provide information about native
555 * objects for heap snapshots, he can do it in a GC prologue
556 * handler, and / or by assigning wrapper class ids in the following way:
558 * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
559 * 2. Call SetWrapperClassId on certain persistent handles.
561 * V8 takes ownership of RetainedObjectInfo instances passed to it and
562 * keeps them alive only during snapshot collection. Afterwards, they
563 * are freed by calling the Dispose class function.
565 class V8_EXPORT RetainedObjectInfo { // NOLINT
567 /** Called by V8 when it no longer needs an instance. */
568 virtual void Dispose() = 0;
570 /** Returns whether two instances are equivalent. */
571 virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
574 * Returns hash value for the instance. Equivalent instances
575 * must have the same hash value.
577 virtual intptr_t GetHash() = 0;
580 * Returns human-readable label. It must be a null-terminated UTF-8
581 * encoded string. V8 copies its contents during a call to GetLabel.
583 virtual const char* GetLabel() = 0;
586 * Returns human-readable group label. It must be a null-terminated UTF-8
587 * encoded string. V8 copies its contents during a call to GetGroupLabel.
588 * Heap snapshot generator will collect all the group names, create
589 * top level entries with these names and attach the objects to the
590 * corresponding top level group objects. There is a default
591 * implementation which is required because embedders don't have their
592 * own implementation yet.
594 virtual const char* GetGroupLabel() { return GetLabel(); }
597 * Returns element count in case if a global handle retains
598 * a subgraph by holding one of its nodes.
600 virtual intptr_t GetElementCount() { return -1; }
602 /** Returns embedder's object size in bytes. */
603 virtual intptr_t GetSizeInBytes() { return -1; }
606 RetainedObjectInfo() {}
607 virtual ~RetainedObjectInfo() {}
610 RetainedObjectInfo(const RetainedObjectInfo&);
611 RetainedObjectInfo& operator=(const RetainedObjectInfo&);
616 * A struct for exporting HeapStats data from V8, using "push" model.
617 * See HeapProfiler::GetHeapStats.
619 struct HeapStatsUpdate {
620 HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
621 : index(index), count(count), size(size) { }
622 uint32_t index; // Index of the time interval that was changed.
623 uint32_t count; // New value of count field for the interval with this index.
624 uint32_t size; // New value of size field for the interval with this index.
631 #endif // V8_V8_PROFILER_H_