d0215205f5fa97d8eadc1f2547df734f53c11a24
[platform/upstream/nodejs.git] / deps / v8 / include / v8-profiler.h
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.
4
5 #ifndef V8_V8_PROFILER_H_
6 #define V8_V8_PROFILER_H_
7
8 #include "v8.h"
9
10 /**
11  * Profiler support for the V8 JavaScript engine.
12  */
13 namespace v8 {
14
15 class HeapGraphNode;
16 struct HeapStatsUpdate;
17
18 typedef uint32_t SnapshotObjectId;
19
20 /**
21  * CpuProfileNode represents a node in a call graph.
22  */
23 class V8_EXPORT CpuProfileNode {
24  public:
25   struct LineTick {
26     /** The 1-based number of the source line where the function originates. */
27     int line;
28
29     /** The count of samples associated with the source line. */
30     unsigned int hit_count;
31   };
32
33   /** Returns function name (empty string for anonymous functions.) */
34   Handle<String> GetFunctionName() const;
35
36   /** Returns id of the script where function is located. */
37   int GetScriptId() const;
38
39   /** Returns resource name for script from where the function originates. */
40   Handle<String> GetScriptResourceName() const;
41
42   /**
43    * Returns the number, 1-based, of the line where the function originates.
44    * kNoLineNumberInfo if no line number information is available.
45    */
46   int GetLineNumber() const;
47
48   /**
49    * Returns 1-based number of the column where the function originates.
50    * kNoColumnNumberInfo if no column number information is available.
51    */
52   int GetColumnNumber() const;
53
54   /**
55    * Returns the number of the function's source lines that collect the samples.
56    */
57   unsigned int GetHitLineCount() const;
58
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.
63    */
64   bool GetLineTicks(LineTick* entries, unsigned int length) const;
65
66   /** Returns bailout reason for the function
67     * if the optimization was disabled for it.
68     */
69   const char* GetBailoutReason() const;
70
71   /**
72     * Returns the count of samples where the function was currently executing.
73     */
74   unsigned GetHitCount() const;
75
76   /** Returns function entry UID. */
77   unsigned GetCallUid() const;
78
79   /** Returns id of the node. The id is unique within the tree */
80   unsigned GetNodeId() const;
81
82   /** Returns child nodes count of the node. */
83   int GetChildrenCount() const;
84
85   /** Retrieves a child node by index. */
86   const CpuProfileNode* GetChild(int index) const;
87
88   static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
89   static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
90 };
91
92
93 /**
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).
96  */
97 class V8_EXPORT CpuProfile {
98  public:
99   /** Returns CPU profile title. */
100   Handle<String> GetTitle() const;
101
102   /** Returns the root node of the top down call tree. */
103   const CpuProfileNode* GetTopDownRoot() const;
104
105   /**
106    * Returns number of samples recorded. The samples are not recorded unless
107    * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
108    */
109   int GetSamplesCount() const;
110
111   /**
112    * Returns profile node corresponding to the top frame the sample at
113    * the given index.
114    */
115   const CpuProfileNode* GetSample(int index) const;
116
117   /**
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.
121    */
122   int64_t GetSampleTimestamp(int index) const;
123
124   /**
125    * Returns time when the profile recording was started (in microseconds)
126    * since some unspecified starting point.
127    */
128   int64_t GetStartTime() const;
129
130   /**
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.
134    */
135   int64_t GetEndTime() const;
136
137   /**
138    * Deletes the profile and removes it from CpuProfiler's list.
139    * All pointers to nodes previously returned become invalid.
140    */
141   void Delete();
142 };
143
144
145 /**
146  * Interface for controlling CPU profiling. Instance of the
147  * profiler can be retrieved using v8::Isolate::GetCpuProfiler.
148  */
149 class V8_EXPORT CpuProfiler {
150  public:
151   /**
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.
155    */
156   void SetSamplingInterval(int us);
157
158   /**
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.
165    *
166    * |record_samples| parameter controls whether individual samples should
167    * be recorded in addition to the aggregated tree.
168    */
169   void StartProfiling(Handle<String> title, bool record_samples = false);
170
171   /** Deprecated. Use StartProfiling instead. */
172   V8_DEPRECATED("Use StartProfiling",
173       void StartCpuProfiling(Handle<String> title,
174                              bool record_samples = false));
175
176   /**
177    * Stops collecting CPU profile with a given title and returns it.
178    * If the title given is empty, finishes the last profile started.
179    */
180   CpuProfile* StopProfiling(Handle<String> title);
181
182   /** Deprecated. Use StopProfiling instead. */
183   V8_DEPRECATED("Use StopProfiling",
184       const CpuProfile* StopCpuProfiling(Handle<String> title));
185
186   /**
187    * Tells the profiler whether the embedder is idle.
188    */
189   void SetIdle(bool is_idle);
190
191  private:
192   CpuProfiler();
193   ~CpuProfiler();
194   CpuProfiler(const CpuProfiler&);
195   CpuProfiler& operator=(const CpuProfiler&);
196 };
197
198
199 /**
200  * HeapSnapshotEdge represents a directed connection between heap
201  * graph nodes: from retainers to retained nodes.
202  */
203 class V8_EXPORT HeapGraphEdge {
204  public:
205   enum Type {
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).
217   };
218
219   /** Returns edge type (see HeapGraphEdge::Type). */
220   Type GetType() const;
221
222   /**
223    * Returns edge name. This can be a variable name, an element index, or
224    * a property name.
225    */
226   Handle<Value> GetName() const;
227
228   /** Returns origin node. */
229   const HeapGraphNode* GetFromNode() const;
230
231   /** Returns destination node. */
232   const HeapGraphNode* GetToNode() const;
233 };
234
235
236 /**
237  * HeapGraphNode represents a node in a heap graph.
238  */
239 class V8_EXPORT HeapGraphNode {
240  public:
241   enum Type {
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).
256   };
257
258   /** Returns node type (see HeapGraphNode::Type). */
259   Type GetType() const;
260
261   /**
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).
265    */
266   Handle<String> GetName() const;
267
268   /**
269    * Returns node id. For the same heap object, the id remains the same
270    * across all snapshots.
271    */
272   SnapshotObjectId GetId() const;
273
274   /** Returns node's own size, in bytes. */
275   V8_DEPRECATED("Use GetShallowSize instead",
276                 int GetSelfSize() const);
277
278   /** Returns node's own size, in bytes. */
279   size_t GetShallowSize() const;
280
281   /** Returns child nodes count of the node. */
282   int GetChildrenCount() const;
283
284   /** Retrieves a child by index. */
285   const HeapGraphEdge* GetChild(int index) const;
286 };
287
288
289 /**
290  * An interface for exporting data from V8, using "push" model.
291  */
292 class V8_EXPORT OutputStream {  // NOLINT
293  public:
294   enum WriteResult {
295     kContinue = 0,
296     kAbort = 1
297   };
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; }
303   /**
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.
307    */
308   virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
309   /**
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.
313    */
314   virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
315     return kAbort;
316   }
317 };
318
319
320 /**
321  * HeapSnapshots record the state of the JS heap at some moment.
322  */
323 class V8_EXPORT HeapSnapshot {
324  public:
325   enum SerializationFormat {
326     kJSON = 0  // See format description near 'Serialize' method.
327   };
328
329   /** Returns heap snapshot UID (assigned by the profiler.) */
330   unsigned GetUid() const;
331
332   /** Returns heap snapshot title. */
333   Handle<String> GetTitle() const;
334
335   /** Returns the root node of the heap graph. */
336   const HeapGraphNode* GetRoot() const;
337
338   /** Returns a node by its id. */
339   const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
340
341   /** Returns total nodes count in the snapshot. */
342   int GetNodesCount() const;
343
344   /** Returns a node by index. */
345   const HeapGraphNode* GetNode(int index) const;
346
347   /** Returns a max seen JS object Id. */
348   SnapshotObjectId GetMaxSnapshotJSObjectId() const;
349
350   /**
351    * Deletes the snapshot and removes it from HeapProfiler's list.
352    * All pointers to nodes, edges and paths previously returned become
353    * invalid.
354    */
355   void Delete();
356
357   /**
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).
363    *
364    * For the JSON format, heap contents are represented as an object
365    * with the following structure:
366    *
367    *  {
368    *    snapshot: {
369    *      title: "...",
370    *      uid: nnn,
371    *      meta: { meta-info },
372    *      node_count: nnn,
373    *      edge_count: nnn
374    *    },
375    *    nodes: [nodes array],
376    *    edges: [edges array],
377    *    strings: [strings array]
378    *  }
379    *
380    * Nodes reference strings, other nodes, and edges by their indexes
381    * in corresponding arrays.
382    */
383   void Serialize(OutputStream* stream, SerializationFormat format) const;
384 };
385
386
387 /**
388  * An interface for reporting progress and controlling long-running
389  * activities.
390  */
391 class V8_EXPORT ActivityControl {  // NOLINT
392  public:
393   enum ControlOption {
394     kContinue = 0,
395     kAbort = 1
396   };
397   virtual ~ActivityControl() {}
398   /**
399    * Notify about current progress. The activity can be stopped by
400    * returning kAbort as the callback result.
401    */
402   virtual ControlOption ReportProgressValue(int done, int total) = 0;
403 };
404
405
406 /**
407  * Interface for controlling heap profiling. Instance of the
408  * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
409  */
410 class V8_EXPORT HeapProfiler {
411  public:
412   /**
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.
417    */
418   typedef RetainedObjectInfo* (*WrapperInfoCallback)
419       (uint16_t class_id, Handle<Value> wrapper);
420
421   /** Returns the number of snapshots taken. */
422   int GetSnapshotCount();
423
424   /** Returns a snapshot by index. */
425   const HeapSnapshot* GetHeapSnapshot(int index);
426
427   /**
428    * Returns SnapshotObjectId for a heap object referenced by |value| if
429    * it has been seen by the heap profiler, kUnknownObjectId otherwise.
430    */
431   SnapshotObjectId GetObjectId(Handle<Value> value);
432
433   /**
434    * Returns heap object with given SnapshotObjectId if the object is alive,
435    * otherwise empty handle is returned.
436    */
437   Handle<Value> FindObjectById(SnapshotObjectId id);
438
439   /**
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.
443    */
444   void ClearObjectIds();
445
446   /**
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.
450    */
451   static const SnapshotObjectId kUnknownObjectId = 0;
452
453   /**
454    * Callback interface for retrieving user friendly names of global objects.
455    */
456   class ObjectNameResolver {
457    public:
458     /**
459      * Returns name to be used in the heap snapshot for given node. Returned
460      * string must stay alive until snapshot collection is completed.
461      */
462     virtual const char* GetName(Handle<Object> object) = 0;
463    protected:
464     virtual ~ObjectNameResolver() {}
465   };
466
467   /**
468    * Takes a heap snapshot and returns it. Title may be an empty string.
469    */
470   const HeapSnapshot* TakeHeapSnapshot(
471       Handle<String> title,
472       ActivityControl* control = NULL,
473       ObjectNameResolver* global_object_name_resolver = NULL);
474
475   /**
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.
479    *
480    * |track_allocations| parameter controls whether stack trace of each
481    * allocation in the heap will be recorded and reported as part of
482    * HeapSnapshot.
483    */
484   void StartTrackingHeapObjects(bool track_allocations = false);
485
486   /**
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.
494    *
495    * StartTrackingHeapObjects must be called before the first call to this
496    * method.
497    */
498   SnapshotObjectId GetHeapStats(OutputStream* stream);
499
500   /**
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.
504    */
505   void StopTrackingHeapObjects();
506
507   /**
508    * Deletes all snapshots taken. All previously returned pointers to
509    * snapshots and their contents become invalid after this call.
510    */
511   void DeleteAllHeapSnapshots();
512
513   /** Binds a callback to embedder's class ID. */
514   void SetWrapperClassInfoProvider(
515       uint16_t class_id,
516       WrapperInfoCallback callback);
517
518   /**
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
521    * handle.
522    */
523   static const uint16_t kPersistentHandleNoClassId = 0;
524
525   /** Returns memory used for profiler internal data and snapshots. */
526   size_t GetProfilerMemorySize();
527
528   /**
529    * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
530    */
531   void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo* info);
532
533  private:
534   HeapProfiler();
535   ~HeapProfiler();
536   HeapProfiler(const HeapProfiler&);
537   HeapProfiler& operator=(const HeapProfiler&);
538 };
539
540
541 /**
542  * Interface for providing information about embedder's objects
543  * held by global handles. This information is reported in two ways:
544  *
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.
549  *
550  *  2. When a heap snapshot is collected, V8 additionally
551  *     requests RetainedObjectInfos for persistent handles that
552  *     were not previously reported via AddObjectGroup.
553  *
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:
557  *
558  *  1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
559  *  2. Call SetWrapperClassId on certain persistent handles.
560  *
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.
564  */
565 class V8_EXPORT RetainedObjectInfo {  // NOLINT
566  public:
567   /** Called by V8 when it no longer needs an instance. */
568   virtual void Dispose() = 0;
569
570   /** Returns whether two instances are equivalent. */
571   virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
572
573   /**
574    * Returns hash value for the instance. Equivalent instances
575    * must have the same hash value.
576    */
577   virtual intptr_t GetHash() = 0;
578
579   /**
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.
582    */
583   virtual const char* GetLabel() = 0;
584
585   /**
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.
593    */
594   virtual const char* GetGroupLabel() { return GetLabel(); }
595
596   /**
597    * Returns element count in case if a global handle retains
598    * a subgraph by holding one of its nodes.
599    */
600   virtual intptr_t GetElementCount() { return -1; }
601
602   /** Returns embedder's object size in bytes. */
603   virtual intptr_t GetSizeInBytes() { return -1; }
604
605  protected:
606   RetainedObjectInfo() {}
607   virtual ~RetainedObjectInfo() {}
608
609  private:
610   RetainedObjectInfo(const RetainedObjectInfo&);
611   RetainedObjectInfo& operator=(const RetainedObjectInfo&);
612 };
613
614
615 /**
616  * A struct for exporting HeapStats data from V8, using "push" model.
617  * See HeapProfiler::GetHeapStats.
618  */
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.
625 };
626
627
628 }  // namespace v8
629
630
631 #endif  // V8_V8_PROFILER_H_