Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / 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   /** Returns function name (empty string for anonymous functions.) */
26   Handle<String> GetFunctionName() const;
27
28   /** Returns id of the script where function is located. */
29   int GetScriptId() const;
30
31   /** Returns resource name for script from where the function originates. */
32   Handle<String> GetScriptResourceName() const;
33
34   /**
35    * Returns the number, 1-based, of the line where the function originates.
36    * kNoLineNumberInfo if no line number information is available.
37    */
38   int GetLineNumber() const;
39
40   /**
41    * Returns 1-based number of the column where the function originates.
42    * kNoColumnNumberInfo if no column number information is available.
43    */
44   int GetColumnNumber() const;
45
46   /** Returns bailout reason for the function
47     * if the optimization was disabled for it.
48     */
49   const char* GetBailoutReason() const;
50
51   /**
52     * Returns the count of samples where the function was currently executing.
53     */
54   unsigned GetHitCount() const;
55
56   /** Returns function entry UID. */
57   unsigned GetCallUid() const;
58
59   /** Returns id of the node. The id is unique within the tree */
60   unsigned GetNodeId() const;
61
62   /** Returns child nodes count of the node. */
63   int GetChildrenCount() const;
64
65   /** Retrieves a child node by index. */
66   const CpuProfileNode* GetChild(int index) const;
67
68   static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
69   static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
70 };
71
72
73 /**
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).
76  */
77 class V8_EXPORT CpuProfile {
78  public:
79   /** Returns CPU profile title. */
80   Handle<String> GetTitle() const;
81
82   /** Returns the root node of the top down call tree. */
83   const CpuProfileNode* GetTopDownRoot() const;
84
85   /**
86    * Returns number of samples recorded. The samples are not recorded unless
87    * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
88    */
89   int GetSamplesCount() const;
90
91   /**
92    * Returns profile node corresponding to the top frame the sample at
93    * the given index.
94    */
95   const CpuProfileNode* GetSample(int index) const;
96
97   /**
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.
101    */
102   int64_t GetSampleTimestamp(int index) const;
103
104   /**
105    * Returns time when the profile recording was started (in microseconds)
106    * since some unspecified starting point.
107    */
108   int64_t GetStartTime() const;
109
110   /**
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.
114    */
115   int64_t GetEndTime() const;
116
117   /**
118    * Deletes the profile and removes it from CpuProfiler's list.
119    * All pointers to nodes previously returned become invalid.
120    */
121   void Delete();
122 };
123
124
125 /**
126  * Interface for controlling CPU profiling. Instance of the
127  * profiler can be retrieved using v8::Isolate::GetCpuProfiler.
128  */
129 class V8_EXPORT CpuProfiler {
130  public:
131   /**
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.
135    */
136   void SetSamplingInterval(int us);
137
138   /**
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.
145    *
146    * |record_samples| parameter controls whether individual samples should
147    * be recorded in addition to the aggregated tree.
148    */
149   void StartProfiling(Handle<String> title, bool record_samples = false);
150
151   /** Deprecated. Use StartProfiling instead. */
152   V8_DEPRECATED("Use StartProfiling",
153       void StartCpuProfiling(Handle<String> title,
154                              bool record_samples = false));
155
156   /**
157    * Stops collecting CPU profile with a given title and returns it.
158    * If the title given is empty, finishes the last profile started.
159    */
160   CpuProfile* StopProfiling(Handle<String> title);
161
162   /** Deprecated. Use StopProfiling instead. */
163   V8_DEPRECATED("Use StopProfiling",
164       const CpuProfile* StopCpuProfiling(Handle<String> title));
165
166   /**
167    * Tells the profiler whether the embedder is idle.
168    */
169   void SetIdle(bool is_idle);
170
171  private:
172   CpuProfiler();
173   ~CpuProfiler();
174   CpuProfiler(const CpuProfiler&);
175   CpuProfiler& operator=(const CpuProfiler&);
176 };
177
178
179 /**
180  * HeapSnapshotEdge represents a directed connection between heap
181  * graph nodes: from retainers to retained nodes.
182  */
183 class V8_EXPORT HeapGraphEdge {
184  public:
185   enum Type {
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).
197   };
198
199   /** Returns edge type (see HeapGraphEdge::Type). */
200   Type GetType() const;
201
202   /**
203    * Returns edge name. This can be a variable name, an element index, or
204    * a property name.
205    */
206   Handle<Value> GetName() const;
207
208   /** Returns origin node. */
209   const HeapGraphNode* GetFromNode() const;
210
211   /** Returns destination node. */
212   const HeapGraphNode* GetToNode() const;
213 };
214
215
216 /**
217  * HeapGraphNode represents a node in a heap graph.
218  */
219 class V8_EXPORT HeapGraphNode {
220  public:
221   enum Type {
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.
235   };
236
237   /** Returns node type (see HeapGraphNode::Type). */
238   Type GetType() const;
239
240   /**
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).
244    */
245   Handle<String> GetName() const;
246
247   /**
248    * Returns node id. For the same heap object, the id remains the same
249    * across all snapshots.
250    */
251   SnapshotObjectId GetId() const;
252
253   /** Returns node's own size, in bytes. */
254   V8_DEPRECATED("Use GetShallowSize instead",
255                 int GetSelfSize() const);
256
257   /** Returns node's own size, in bytes. */
258   size_t GetShallowSize() const;
259
260   /** Returns child nodes count of the node. */
261   int GetChildrenCount() const;
262
263   /** Retrieves a child by index. */
264   const HeapGraphEdge* GetChild(int index) const;
265 };
266
267
268 /**
269  * An interface for exporting data from V8, using "push" model.
270  */
271 class V8_EXPORT OutputStream {  // NOLINT
272  public:
273   enum WriteResult {
274     kContinue = 0,
275     kAbort = 1
276   };
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; }
282   /**
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.
286    */
287   virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
288   /**
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.
292    */
293   virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
294     return kAbort;
295   };
296 };
297
298
299 /**
300  * HeapSnapshots record the state of the JS heap at some moment.
301  */
302 class V8_EXPORT HeapSnapshot {
303  public:
304   enum SerializationFormat {
305     kJSON = 0  // See format description near 'Serialize' method.
306   };
307
308   /** Returns heap snapshot UID (assigned by the profiler.) */
309   unsigned GetUid() const;
310
311   /** Returns heap snapshot title. */
312   Handle<String> GetTitle() const;
313
314   /** Returns the root node of the heap graph. */
315   const HeapGraphNode* GetRoot() const;
316
317   /** Returns a node by its id. */
318   const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
319
320   /** Returns total nodes count in the snapshot. */
321   int GetNodesCount() const;
322
323   /** Returns a node by index. */
324   const HeapGraphNode* GetNode(int index) const;
325
326   /** Returns a max seen JS object Id. */
327   SnapshotObjectId GetMaxSnapshotJSObjectId() const;
328
329   /**
330    * Deletes the snapshot and removes it from HeapProfiler's list.
331    * All pointers to nodes, edges and paths previously returned become
332    * invalid.
333    */
334   void Delete();
335
336   /**
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).
342    *
343    * For the JSON format, heap contents are represented as an object
344    * with the following structure:
345    *
346    *  {
347    *    snapshot: {
348    *      title: "...",
349    *      uid: nnn,
350    *      meta: { meta-info },
351    *      node_count: nnn,
352    *      edge_count: nnn
353    *    },
354    *    nodes: [nodes array],
355    *    edges: [edges array],
356    *    strings: [strings array]
357    *  }
358    *
359    * Nodes reference strings, other nodes, and edges by their indexes
360    * in corresponding arrays.
361    */
362   void Serialize(OutputStream* stream, SerializationFormat format) const;
363 };
364
365
366 /**
367  * An interface for reporting progress and controlling long-running
368  * activities.
369  */
370 class V8_EXPORT ActivityControl {  // NOLINT
371  public:
372   enum ControlOption {
373     kContinue = 0,
374     kAbort = 1
375   };
376   virtual ~ActivityControl() {}
377   /**
378    * Notify about current progress. The activity can be stopped by
379    * returning kAbort as the callback result.
380    */
381   virtual ControlOption ReportProgressValue(int done, int total) = 0;
382 };
383
384
385 /**
386  * Interface for controlling heap profiling. Instance of the
387  * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
388  */
389 class V8_EXPORT HeapProfiler {
390  public:
391   /**
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.
396    */
397   typedef RetainedObjectInfo* (*WrapperInfoCallback)
398       (uint16_t class_id, Handle<Value> wrapper);
399
400   /** Returns the number of snapshots taken. */
401   int GetSnapshotCount();
402
403   /** Returns a snapshot by index. */
404   const HeapSnapshot* GetHeapSnapshot(int index);
405
406   /**
407    * Returns SnapshotObjectId for a heap object referenced by |value| if
408    * it has been seen by the heap profiler, kUnknownObjectId otherwise.
409    */
410   SnapshotObjectId GetObjectId(Handle<Value> value);
411
412   /**
413    * Returns heap object with given SnapshotObjectId if the object is alive,
414    * otherwise empty handle is returned.
415    */
416   Handle<Value> FindObjectById(SnapshotObjectId id);
417
418   /**
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.
422    */
423   void ClearObjectIds();
424
425   /**
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.
429    */
430   static const SnapshotObjectId kUnknownObjectId = 0;
431
432   /**
433    * Callback interface for retrieving user friendly names of global objects.
434    */
435   class ObjectNameResolver {
436    public:
437     /**
438      * Returns name to be used in the heap snapshot for given node. Returned
439      * string must stay alive until snapshot collection is completed.
440      */
441     virtual const char* GetName(Handle<Object> object) = 0;
442    protected:
443     virtual ~ObjectNameResolver() {}
444   };
445
446   /**
447    * Takes a heap snapshot and returns it. Title may be an empty string.
448    */
449   const HeapSnapshot* TakeHeapSnapshot(
450       Handle<String> title,
451       ActivityControl* control = NULL,
452       ObjectNameResolver* global_object_name_resolver = NULL);
453
454   /**
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.
458    *
459    * |track_allocations| parameter controls whether stack trace of each
460    * allocation in the heap will be recorded and reported as part of
461    * HeapSnapshot.
462    */
463   void StartTrackingHeapObjects(bool track_allocations = false);
464
465   /**
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.
473    *
474    * StartTrackingHeapObjects must be called before the first call to this
475    * method.
476    */
477   SnapshotObjectId GetHeapStats(OutputStream* stream);
478
479   /**
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.
483    */
484   void StopTrackingHeapObjects();
485
486   /**
487    * Deletes all snapshots taken. All previously returned pointers to
488    * snapshots and their contents become invalid after this call.
489    */
490   void DeleteAllHeapSnapshots();
491
492   /** Binds a callback to embedder's class ID. */
493   void SetWrapperClassInfoProvider(
494       uint16_t class_id,
495       WrapperInfoCallback callback);
496
497   /**
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
500    * handle.
501    */
502   static const uint16_t kPersistentHandleNoClassId = 0;
503
504   /** Returns memory used for profiler internal data and snapshots. */
505   size_t GetProfilerMemorySize();
506
507   /**
508    * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
509    */
510   void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo* info);
511
512  private:
513   HeapProfiler();
514   ~HeapProfiler();
515   HeapProfiler(const HeapProfiler&);
516   HeapProfiler& operator=(const HeapProfiler&);
517 };
518
519
520 /**
521  * Interface for providing information about embedder's objects
522  * held by global handles. This information is reported in two ways:
523  *
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.
528  *
529  *  2. When a heap snapshot is collected, V8 additionally
530  *     requests RetainedObjectInfos for persistent handles that
531  *     were not previously reported via AddObjectGroup.
532  *
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:
536  *
537  *  1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
538  *  2. Call SetWrapperClassId on certain persistent handles.
539  *
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.
543  */
544 class V8_EXPORT RetainedObjectInfo {  // NOLINT
545  public:
546   /** Called by V8 when it no longer needs an instance. */
547   virtual void Dispose() = 0;
548
549   /** Returns whether two instances are equivalent. */
550   virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
551
552   /**
553    * Returns hash value for the instance. Equivalent instances
554    * must have the same hash value.
555    */
556   virtual intptr_t GetHash() = 0;
557
558   /**
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.
561    */
562   virtual const char* GetLabel() = 0;
563
564   /**
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.
572    */
573   virtual const char* GetGroupLabel() { return GetLabel(); }
574
575   /**
576    * Returns element count in case if a global handle retains
577    * a subgraph by holding one of its nodes.
578    */
579   virtual intptr_t GetElementCount() { return -1; }
580
581   /** Returns embedder's object size in bytes. */
582   virtual intptr_t GetSizeInBytes() { return -1; }
583
584  protected:
585   RetainedObjectInfo() {}
586   virtual ~RetainedObjectInfo() {}
587
588  private:
589   RetainedObjectInfo(const RetainedObjectInfo&);
590   RetainedObjectInfo& operator=(const RetainedObjectInfo&);
591 };
592
593
594 /**
595  * A struct for exporting HeapStats data from V8, using "push" model.
596  * See HeapProfiler::GetHeapStats.
597  */
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.
604 };
605
606
607 }  // namespace v8
608
609
610 #endif  // V8_V8_PROFILER_H_