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);
172 * Stops collecting CPU profile with a given title and returns it.
173 * If the title given is empty, finishes the last profile started.
175 CpuProfile* StopProfiling(Handle<String> title);
178 * Tells the profiler whether the embedder is idle.
180 void SetIdle(bool is_idle);
185 CpuProfiler(const CpuProfiler&);
186 CpuProfiler& operator=(const CpuProfiler&);
191 * HeapSnapshotEdge represents a directed connection between heap
192 * graph nodes: from retainers to retained nodes.
194 class V8_EXPORT HeapGraphEdge {
197 kContextVariable = 0, // A variable from a function context.
198 kElement = 1, // An element of an array.
199 kProperty = 2, // A named object property.
200 kInternal = 3, // A link that can't be accessed from JS,
201 // thus, its name isn't a real property name
202 // (e.g. parts of a ConsString).
203 kHidden = 4, // A link that is needed for proper sizes
204 // calculation, but may be hidden from user.
205 kShortcut = 5, // A link that must not be followed during
206 // sizes calculation.
207 kWeak = 6 // A weak reference (ignored by the GC).
210 /** Returns edge type (see HeapGraphEdge::Type). */
211 Type GetType() const;
214 * Returns edge name. This can be a variable name, an element index, or
217 Handle<Value> GetName() const;
219 /** Returns origin node. */
220 const HeapGraphNode* GetFromNode() const;
222 /** Returns destination node. */
223 const HeapGraphNode* GetToNode() const;
228 * HeapGraphNode represents a node in a heap graph.
230 class V8_EXPORT HeapGraphNode {
233 kHidden = 0, // Hidden node, may be filtered when shown to user.
234 kArray = 1, // An array of elements.
235 kString = 2, // A string.
236 kObject = 3, // A JS object (except for arrays and strings).
237 kCode = 4, // Compiled code.
238 kClosure = 5, // Function closure.
239 kRegExp = 6, // RegExp.
240 kHeapNumber = 7, // Number stored in the heap.
241 kNative = 8, // Native object (not from V8 heap).
242 kSynthetic = 9, // Synthetic object, usualy used for grouping
243 // snapshot items together.
244 kConsString = 10, // Concatenated string. A pair of pointers to strings.
245 kSlicedString = 11, // Sliced string. A fragment of another string.
246 kSymbol = 12 // A Symbol (ES6).
249 /** Returns node type (see HeapGraphNode::Type). */
250 Type GetType() const;
253 * Returns node name. Depending on node's type this can be the name
254 * of the constructor (for objects), the name of the function (for
255 * closures), string value, or an empty string (for compiled code).
257 Handle<String> GetName() const;
260 * Returns node id. For the same heap object, the id remains the same
261 * across all snapshots.
263 SnapshotObjectId GetId() const;
265 /** Returns node's own size, in bytes. */
266 size_t GetShallowSize() const;
268 /** Returns child nodes count of the node. */
269 int GetChildrenCount() const;
271 /** Retrieves a child by index. */
272 const HeapGraphEdge* GetChild(int index) const;
277 * An interface for exporting data from V8, using "push" model.
279 class V8_EXPORT OutputStream { // NOLINT
285 virtual ~OutputStream() {}
286 /** Notify about the end of stream. */
287 virtual void EndOfStream() = 0;
288 /** Get preferred output chunk size. Called only once. */
289 virtual int GetChunkSize() { return 1024; }
291 * Writes the next chunk of snapshot data into the stream. Writing
292 * can be stopped by returning kAbort as function result. EndOfStream
293 * will not be called in case writing was aborted.
295 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
297 * Writes the next chunk of heap stats data into the stream. Writing
298 * can be stopped by returning kAbort as function result. EndOfStream
299 * will not be called in case writing was aborted.
301 virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
308 * HeapSnapshots record the state of the JS heap at some moment.
310 class V8_EXPORT HeapSnapshot {
312 enum SerializationFormat {
313 kJSON = 0 // See format description near 'Serialize' method.
316 /** Returns the root node of the heap graph. */
317 const HeapGraphNode* GetRoot() const;
319 /** Returns a node by its id. */
320 const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
322 /** Returns total nodes count in the snapshot. */
323 int GetNodesCount() const;
325 /** Returns a node by index. */
326 const HeapGraphNode* GetNode(int index) const;
328 /** Returns a max seen JS object Id. */
329 SnapshotObjectId GetMaxSnapshotJSObjectId() const;
332 * Deletes the snapshot and removes it from HeapProfiler's list.
333 * All pointers to nodes, edges and paths previously returned become
339 * Prepare a serialized representation of the snapshot. The result
340 * is written into the stream provided in chunks of specified size.
341 * The total length of the serialized snapshot is unknown in
342 * advance, it can be roughly equal to JS heap size (that means,
343 * it can be really big - tens of megabytes).
345 * For the JSON format, heap contents are represented as an object
346 * with the following structure:
352 * meta: { meta-info },
356 * nodes: [nodes array],
357 * edges: [edges array],
358 * strings: [strings array]
361 * Nodes reference strings, other nodes, and edges by their indexes
362 * in corresponding arrays.
364 void Serialize(OutputStream* stream,
365 SerializationFormat format = kJSON) const;
370 * An interface for reporting progress and controlling long-running
373 class V8_EXPORT ActivityControl { // NOLINT
379 virtual ~ActivityControl() {}
381 * Notify about current progress. The activity can be stopped by
382 * returning kAbort as the callback result.
384 virtual ControlOption ReportProgressValue(int done, int total) = 0;
389 * Interface for controlling heap profiling. Instance of the
390 * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
392 class V8_EXPORT HeapProfiler {
395 * Callback function invoked for obtaining RetainedObjectInfo for
396 * the given JavaScript wrapper object. It is prohibited to enter V8
397 * while the callback is running: only getters on the handle and
398 * GetPointerFromInternalField on the objects are allowed.
400 typedef RetainedObjectInfo* (*WrapperInfoCallback)
401 (uint16_t class_id, Handle<Value> wrapper);
403 /** Returns the number of snapshots taken. */
404 int GetSnapshotCount();
406 /** Returns a snapshot by index. */
407 const HeapSnapshot* GetHeapSnapshot(int index);
410 * Returns SnapshotObjectId for a heap object referenced by |value| if
411 * it has been seen by the heap profiler, kUnknownObjectId otherwise.
413 SnapshotObjectId GetObjectId(Handle<Value> value);
416 * Returns heap object with given SnapshotObjectId if the object is alive,
417 * otherwise empty handle is returned.
419 Handle<Value> FindObjectById(SnapshotObjectId id);
422 * Clears internal map from SnapshotObjectId to heap object. The new objects
423 * will not be added into it unless a heap snapshot is taken or heap object
424 * tracking is kicked off.
426 void ClearObjectIds();
429 * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
430 * it in case heap profiler cannot find id for the object passed as
431 * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
433 static const SnapshotObjectId kUnknownObjectId = 0;
436 * Callback interface for retrieving user friendly names of global objects.
438 class ObjectNameResolver {
441 * Returns name to be used in the heap snapshot for given node. Returned
442 * string must stay alive until snapshot collection is completed.
444 virtual const char* GetName(Handle<Object> object) = 0;
446 virtual ~ObjectNameResolver() {}
450 * Takes a heap snapshot and returns it.
452 const HeapSnapshot* TakeHeapSnapshot(
453 ActivityControl* control = NULL,
454 ObjectNameResolver* global_object_name_resolver = NULL);
457 * Starts tracking of heap objects population statistics. After calling
458 * this method, all heap objects relocations done by the garbage collector
459 * are being registered.
461 * |track_allocations| parameter controls whether stack trace of each
462 * allocation in the heap will be recorded and reported as part of
465 void StartTrackingHeapObjects(bool track_allocations = false);
468 * Adds a new time interval entry to the aggregated statistics array. The
469 * time interval entry contains information on the current heap objects
470 * population size. The method also updates aggregated statistics and
471 * reports updates for all previous time intervals via the OutputStream
472 * object. Updates on each time interval are provided as a stream of the
473 * HeapStatsUpdate structure instances.
474 * If |timestamp_us| is supplied, timestamp of the new entry will be written
475 * into it. The return value of the function is the last seen heap object Id.
477 * StartTrackingHeapObjects must be called before the first call to this
480 SnapshotObjectId GetHeapStats(OutputStream* stream,
481 int64_t* timestamp_us = NULL);
484 * Stops tracking of heap objects population statistics, cleans up all
485 * collected data. StartHeapObjectsTracking must be called again prior to
486 * calling GetHeapStats next time.
488 void StopTrackingHeapObjects();
491 * Deletes all snapshots taken. All previously returned pointers to
492 * snapshots and their contents become invalid after this call.
494 void DeleteAllHeapSnapshots();
496 /** Binds a callback to embedder's class ID. */
497 void SetWrapperClassInfoProvider(
499 WrapperInfoCallback callback);
502 * Default value of persistent handle class ID. Must not be used to
503 * define a class. Can be used to reset a class of a persistent
506 static const uint16_t kPersistentHandleNoClassId = 0;
508 /** Returns memory used for profiler internal data and snapshots. */
509 size_t GetProfilerMemorySize();
512 * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
514 void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo* info);
519 HeapProfiler(const HeapProfiler&);
520 HeapProfiler& operator=(const HeapProfiler&);
525 * Interface for providing information about embedder's objects
526 * held by global handles. This information is reported in two ways:
528 * 1. When calling AddObjectGroup, an embedder may pass
529 * RetainedObjectInfo instance describing the group. To collect
530 * this information while taking a heap snapshot, V8 calls GC
531 * prologue and epilogue callbacks.
533 * 2. When a heap snapshot is collected, V8 additionally
534 * requests RetainedObjectInfos for persistent handles that
535 * were not previously reported via AddObjectGroup.
537 * Thus, if an embedder wants to provide information about native
538 * objects for heap snapshots, he can do it in a GC prologue
539 * handler, and / or by assigning wrapper class ids in the following way:
541 * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
542 * 2. Call SetWrapperClassId on certain persistent handles.
544 * V8 takes ownership of RetainedObjectInfo instances passed to it and
545 * keeps them alive only during snapshot collection. Afterwards, they
546 * are freed by calling the Dispose class function.
548 class V8_EXPORT RetainedObjectInfo { // NOLINT
550 /** Called by V8 when it no longer needs an instance. */
551 virtual void Dispose() = 0;
553 /** Returns whether two instances are equivalent. */
554 virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
557 * Returns hash value for the instance. Equivalent instances
558 * must have the same hash value.
560 virtual intptr_t GetHash() = 0;
563 * Returns human-readable label. It must be a null-terminated UTF-8
564 * encoded string. V8 copies its contents during a call to GetLabel.
566 virtual const char* GetLabel() = 0;
569 * Returns human-readable group label. It must be a null-terminated UTF-8
570 * encoded string. V8 copies its contents during a call to GetGroupLabel.
571 * Heap snapshot generator will collect all the group names, create
572 * top level entries with these names and attach the objects to the
573 * corresponding top level group objects. There is a default
574 * implementation which is required because embedders don't have their
575 * own implementation yet.
577 virtual const char* GetGroupLabel() { return GetLabel(); }
580 * Returns element count in case if a global handle retains
581 * a subgraph by holding one of its nodes.
583 virtual intptr_t GetElementCount() { return -1; }
585 /** Returns embedder's object size in bytes. */
586 virtual intptr_t GetSizeInBytes() { return -1; }
589 RetainedObjectInfo() {}
590 virtual ~RetainedObjectInfo() {}
593 RetainedObjectInfo(const RetainedObjectInfo&);
594 RetainedObjectInfo& operator=(const RetainedObjectInfo&);
599 * A struct for exporting HeapStats data from V8, using "push" model.
600 * See HeapProfiler::GetHeapStats.
602 struct HeapStatsUpdate {
603 HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
604 : index(index), count(count), size(size) { }
605 uint32_t index; // Index of the time interval that was changed.
606 uint32_t count; // New value of count field for the interval with this index.
607 uint32_t size; // New value of size field for the interval with this index.
614 #endif // V8_V8_PROFILER_H_