LCOV - code coverage report
Current view: top level - include - v8-profiler.h (source / functions) Hit Total Coverage
Test: app.info Lines: 20 23 87.0 %
Date: 2019-02-19 Functions: 7 20 35.0 %

          Line data    Source code
       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 <unordered_set>
       9             : #include <vector>
      10             : #include "v8.h"  // NOLINT(build/include)
      11             : 
      12             : /**
      13             :  * Profiler support for the V8 JavaScript engine.
      14             :  */
      15             : namespace v8 {
      16             : 
      17             : class HeapGraphNode;
      18             : struct HeapStatsUpdate;
      19             : 
      20             : typedef uint32_t SnapshotObjectId;
      21             : 
      22             : 
      23             : struct CpuProfileDeoptFrame {
      24             :   int script_id;
      25             :   size_t position;
      26             : };
      27             : 
      28             : }  // namespace v8
      29             : 
      30             : #ifdef V8_OS_WIN
      31             : template class V8_EXPORT std::vector<v8::CpuProfileDeoptFrame>;
      32             : #endif
      33             : 
      34             : namespace v8 {
      35             : 
      36           0 : struct V8_EXPORT CpuProfileDeoptInfo {
      37             :   /** A pointer to a static string owned by v8. */
      38             :   const char* deopt_reason;
      39             :   std::vector<CpuProfileDeoptFrame> stack;
      40             : };
      41             : 
      42             : }  // namespace v8
      43             : 
      44             : #ifdef V8_OS_WIN
      45             : template class V8_EXPORT std::vector<v8::CpuProfileDeoptInfo>;
      46             : #endif
      47             : 
      48             : namespace v8 {
      49             : 
      50             : // TickSample captures the information collected for each sample.
      51             : struct TickSample {
      52             :   // Internal profiling (with --prof + tools/$OS-tick-processor) wants to
      53             :   // include the runtime function we're calling. Externally exposed tick
      54             :   // samples don't care.
      55             :   enum RecordCEntryFrame { kIncludeCEntryFrame, kSkipCEntryFrame };
      56             : 
      57             :   TickSample()
      58             :       : state(OTHER),
      59             :         pc(nullptr),
      60             :         external_callback_entry(nullptr),
      61             :         frames_count(0),
      62             :         has_external_callback(false),
      63     2018921 :         update_stats(true) {}
      64             : 
      65             :   /**
      66             :    * Initialize a tick sample from the isolate.
      67             :    * \param isolate The isolate.
      68             :    * \param state Execution state.
      69             :    * \param record_c_entry_frame Include or skip the runtime function.
      70             :    * \param update_stats Whether update the sample to the aggregated stats.
      71             :    * \param use_simulator_reg_state When set to true and V8 is running under a
      72             :    *                                simulator, the method will use the simulator
      73             :    *                                register state rather than the one provided
      74             :    *                                with |state| argument. Otherwise the method
      75             :    *                                will use provided register |state| as is.
      76             :    */
      77             :   void Init(Isolate* isolate, const v8::RegisterState& state,
      78             :             RecordCEntryFrame record_c_entry_frame, bool update_stats,
      79             :             bool use_simulator_reg_state = true);
      80             :   /**
      81             :    * Get a call stack sample from the isolate.
      82             :    * \param isolate The isolate.
      83             :    * \param state Register state.
      84             :    * \param record_c_entry_frame Include or skip the runtime function.
      85             :    * \param frames Caller allocated buffer to store stack frames.
      86             :    * \param frames_limit Maximum number of frames to capture. The buffer must
      87             :    *                     be large enough to hold the number of frames.
      88             :    * \param sample_info The sample info is filled up by the function
      89             :    *                    provides number of actual captured stack frames and
      90             :    *                    the current VM state.
      91             :    * \param use_simulator_reg_state When set to true and V8 is running under a
      92             :    *                                simulator, the method will use the simulator
      93             :    *                                register state rather than the one provided
      94             :    *                                with |state| argument. Otherwise the method
      95             :    *                                will use provided register |state| as is.
      96             :    * \note GetStackSample is thread and signal safe and should only be called
      97             :    *                      when the JS thread is paused or interrupted.
      98             :    *                      Otherwise the behavior is undefined.
      99             :    */
     100             :   static bool GetStackSample(Isolate* isolate, v8::RegisterState* state,
     101             :                              RecordCEntryFrame record_c_entry_frame,
     102             :                              void** frames, size_t frames_limit,
     103             :                              v8::SampleInfo* sample_info,
     104             :                              bool use_simulator_reg_state = true);
     105             :   StateTag state;  // The state of the VM.
     106             :   void* pc;        // Instruction pointer.
     107             :   union {
     108             :     void* tos;  // Top stack value (*sp).
     109             :     void* external_callback_entry;
     110             :   };
     111             :   static const unsigned kMaxFramesCountLog2 = 8;
     112             :   static const unsigned kMaxFramesCount = (1 << kMaxFramesCountLog2) - 1;
     113             :   void* stack[kMaxFramesCount];                 // Call stack.
     114             :   unsigned frames_count : kMaxFramesCountLog2;  // Number of captured frames.
     115             :   bool has_external_callback : 1;
     116             :   bool update_stats : 1;  // Whether the sample should update aggregated stats.
     117             : };
     118             : 
     119             : /**
     120             :  * CpuProfileNode represents a node in a call graph.
     121             :  */
     122             : class V8_EXPORT CpuProfileNode {
     123             :  public:
     124             :   struct LineTick {
     125             :     /** The 1-based number of the source line where the function originates. */
     126             :     int line;
     127             : 
     128             :     /** The count of samples associated with the source line. */
     129             :     unsigned int hit_count;
     130             :   };
     131             : 
     132             :   /** Returns function name (empty string for anonymous functions.) */
     133             :   Local<String> GetFunctionName() const;
     134             : 
     135             :   /**
     136             :    * Returns function name (empty string for anonymous functions.)
     137             :    * The string ownership is *not* passed to the caller. It stays valid until
     138             :    * profile is deleted. The function is thread safe.
     139             :    */
     140             :   const char* GetFunctionNameStr() const;
     141             : 
     142             :   /** Returns id of the script where function is located. */
     143             :   int GetScriptId() const;
     144             : 
     145             :   /** Returns resource name for script from where the function originates. */
     146             :   Local<String> GetScriptResourceName() const;
     147             : 
     148             :   /**
     149             :    * Returns resource name for script from where the function originates.
     150             :    * The string ownership is *not* passed to the caller. It stays valid until
     151             :    * profile is deleted. The function is thread safe.
     152             :    */
     153             :   const char* GetScriptResourceNameStr() const;
     154             : 
     155             :   /**
     156             :    * Returns the number, 1-based, of the line where the function originates.
     157             :    * kNoLineNumberInfo if no line number information is available.
     158             :    */
     159             :   int GetLineNumber() const;
     160             : 
     161             :   /**
     162             :    * Returns 1-based number of the column where the function originates.
     163             :    * kNoColumnNumberInfo if no column number information is available.
     164             :    */
     165             :   int GetColumnNumber() const;
     166             : 
     167             :   /**
     168             :    * Returns the number of the function's source lines that collect the samples.
     169             :    */
     170             :   unsigned int GetHitLineCount() const;
     171             : 
     172             :   /** Returns the set of source lines that collect the samples.
     173             :    *  The caller allocates buffer and responsible for releasing it.
     174             :    *  True if all available entries are copied, otherwise false.
     175             :    *  The function copies nothing if buffer is not large enough.
     176             :    */
     177             :   bool GetLineTicks(LineTick* entries, unsigned int length) const;
     178             : 
     179             :   /** Returns bailout reason for the function
     180             :     * if the optimization was disabled for it.
     181             :     */
     182             :   const char* GetBailoutReason() const;
     183             : 
     184             :   /**
     185             :     * Returns the count of samples where the function was currently executing.
     186             :     */
     187             :   unsigned GetHitCount() const;
     188             : 
     189             :   /** Returns function entry UID. */
     190             :   V8_DEPRECATE_SOON(
     191             :       "Use GetScriptId, GetLineNumber, and GetColumnNumber instead.",
     192             :       unsigned GetCallUid() const);
     193             : 
     194             :   /** Returns id of the node. The id is unique within the tree */
     195             :   unsigned GetNodeId() const;
     196             : 
     197             :   /** Returns child nodes count of the node. */
     198             :   int GetChildrenCount() const;
     199             : 
     200             :   /** Retrieves a child node by index. */
     201             :   const CpuProfileNode* GetChild(int index) const;
     202             : 
     203             :   /** Retrieves deopt infos for the node. */
     204             :   const std::vector<CpuProfileDeoptInfo>& GetDeoptInfos() const;
     205             : 
     206             :   static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
     207             :   static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
     208             : };
     209             : 
     210             : 
     211             : /**
     212             :  * CpuProfile contains a CPU profile in a form of top-down call tree
     213             :  * (from main() down to functions that do all the work).
     214             :  */
     215             : class V8_EXPORT CpuProfile {
     216             :  public:
     217             :   /** Returns CPU profile title. */
     218             :   Local<String> GetTitle() const;
     219             : 
     220             :   /** Returns the root node of the top down call tree. */
     221             :   const CpuProfileNode* GetTopDownRoot() const;
     222             : 
     223             :   /**
     224             :    * Returns number of samples recorded. The samples are not recorded unless
     225             :    * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
     226             :    */
     227             :   int GetSamplesCount() const;
     228             : 
     229             :   /**
     230             :    * Returns profile node corresponding to the top frame the sample at
     231             :    * the given index.
     232             :    */
     233             :   const CpuProfileNode* GetSample(int index) const;
     234             : 
     235             :   /**
     236             :    * Returns the timestamp of the sample. The timestamp is the number of
     237             :    * microseconds since some unspecified starting point.
     238             :    * The point is equal to the starting point used by GetStartTime.
     239             :    */
     240             :   int64_t GetSampleTimestamp(int index) const;
     241             : 
     242             :   /**
     243             :    * Returns time when the profile recording was started (in microseconds)
     244             :    * since some unspecified starting point.
     245             :    */
     246             :   int64_t GetStartTime() const;
     247             : 
     248             :   /**
     249             :    * Returns time when the profile recording was stopped (in microseconds)
     250             :    * since some unspecified starting point.
     251             :    * The point is equal to the starting point used by GetStartTime.
     252             :    */
     253             :   int64_t GetEndTime() const;
     254             : 
     255             :   /**
     256             :    * Deletes the profile and removes it from CpuProfiler's list.
     257             :    * All pointers to nodes previously returned become invalid.
     258             :    */
     259             :   void Delete();
     260             : };
     261             : 
     262             : enum CpuProfilingMode {
     263             :   // In the resulting CpuProfile tree, intermediate nodes in a stack trace
     264             :   // (from the root to a leaf) will have line numbers that point to the start
     265             :   // line of the function, rather than the line of the callsite of the child.
     266             :   kLeafNodeLineNumbers,
     267             :   // In the resulting CpuProfile tree, nodes are separated based on the line
     268             :   // number of their callsite in their parent.
     269             :   kCallerLineNumbers,
     270             : };
     271             : 
     272             : /**
     273             :  * Interface for controlling CPU profiling. Instance of the
     274             :  * profiler can be created using v8::CpuProfiler::New method.
     275             :  */
     276             : class V8_EXPORT CpuProfiler {
     277             :  public:
     278             :   /**
     279             :    * Creates a new CPU profiler for the |isolate|. The isolate must be
     280             :    * initialized. The profiler object must be disposed after use by calling
     281             :    * |Dispose| method.
     282             :    */
     283             :   static CpuProfiler* New(Isolate* isolate);
     284             : 
     285             :   /**
     286             :    * Synchronously collect current stack sample in all profilers attached to
     287             :    * the |isolate|. The call does not affect number of ticks recorded for
     288             :    * the current top node.
     289             :    */
     290             :   static void CollectSample(Isolate* isolate);
     291             : 
     292             :   /**
     293             :    * Disposes the CPU profiler object.
     294             :    */
     295             :   void Dispose();
     296             : 
     297             :   /**
     298             :    * Changes default CPU profiler sampling interval to the specified number
     299             :    * of microseconds. Default interval is 1000us. This method must be called
     300             :    * when there are no profiles being recorded.
     301             :    */
     302             :   void SetSamplingInterval(int us);
     303             : 
     304             :   /**
     305             :    * Starts collecting CPU profile. Title may be an empty string. It
     306             :    * is allowed to have several profiles being collected at
     307             :    * once. Attempts to start collecting several profiles with the same
     308             :    * title are silently ignored. While collecting a profile, functions
     309             :    * from all security contexts are included in it. The token-based
     310             :    * filtering is only performed when querying for a profile.
     311             :    *
     312             :    * |record_samples| parameter controls whether individual samples should
     313             :    * be recorded in addition to the aggregated tree.
     314             :    */
     315             :   void StartProfiling(Local<String> title, CpuProfilingMode mode,
     316             :                       bool record_samples = false);
     317             :   /**
     318             :    * The same as StartProfiling above, but the CpuProfilingMode defaults to
     319             :    * kLeafNodeLineNumbers mode, which was the previous default behavior of the
     320             :    * profiler.
     321             :    */
     322             :   void StartProfiling(Local<String> title, bool record_samples = false);
     323             : 
     324             :   /**
     325             :    * Stops collecting CPU profile with a given title and returns it.
     326             :    * If the title given is empty, finishes the last profile started.
     327             :    */
     328             :   CpuProfile* StopProfiling(Local<String> title);
     329             : 
     330             :   /**
     331             :    * Force collection of a sample. Must be called on the VM thread.
     332             :    * Recording the forced sample does not contribute to the aggregated
     333             :    * profile statistics.
     334             :    */
     335             :   V8_DEPRECATED("Use static CollectSample(Isolate*) instead.",
     336             :                 void CollectSample());
     337             : 
     338             :   /**
     339             :    * Tells the profiler whether the embedder is idle.
     340             :    */
     341             :   V8_DEPRECATED("Use Isolate::SetIdle(bool) instead.",
     342             :                 void SetIdle(bool is_idle));
     343             : 
     344             :   /**
     345             :    * Generate more detailed source positions to code objects. This results in
     346             :    * better results when mapping profiling samples to script source.
     347             :    */
     348             :   static void UseDetailedSourcePositionsForProfiling(Isolate* isolate);
     349             : 
     350             :  private:
     351             :   CpuProfiler();
     352             :   ~CpuProfiler();
     353             :   CpuProfiler(const CpuProfiler&);
     354             :   CpuProfiler& operator=(const CpuProfiler&);
     355             : };
     356             : 
     357             : 
     358             : /**
     359             :  * HeapSnapshotEdge represents a directed connection between heap
     360             :  * graph nodes: from retainers to retained nodes.
     361             :  */
     362             : class V8_EXPORT HeapGraphEdge {
     363             :  public:
     364             :   enum Type {
     365             :     kContextVariable = 0,  // A variable from a function context.
     366             :     kElement = 1,          // An element of an array.
     367             :     kProperty = 2,         // A named object property.
     368             :     kInternal = 3,         // A link that can't be accessed from JS,
     369             :                            // thus, its name isn't a real property name
     370             :                            // (e.g. parts of a ConsString).
     371             :     kHidden = 4,           // A link that is needed for proper sizes
     372             :                            // calculation, but may be hidden from user.
     373             :     kShortcut = 5,         // A link that must not be followed during
     374             :                            // sizes calculation.
     375             :     kWeak = 6              // A weak reference (ignored by the GC).
     376             :   };
     377             : 
     378             :   /** Returns edge type (see HeapGraphEdge::Type). */
     379             :   Type GetType() const;
     380             : 
     381             :   /**
     382             :    * Returns edge name. This can be a variable name, an element index, or
     383             :    * a property name.
     384             :    */
     385             :   Local<Value> GetName() const;
     386             : 
     387             :   /** Returns origin node. */
     388             :   const HeapGraphNode* GetFromNode() const;
     389             : 
     390             :   /** Returns destination node. */
     391             :   const HeapGraphNode* GetToNode() const;
     392             : };
     393             : 
     394             : 
     395             : /**
     396             :  * HeapGraphNode represents a node in a heap graph.
     397             :  */
     398             : class V8_EXPORT HeapGraphNode {
     399             :  public:
     400             :   enum Type {
     401             :     kHidden = 0,         // Hidden node, may be filtered when shown to user.
     402             :     kArray = 1,          // An array of elements.
     403             :     kString = 2,         // A string.
     404             :     kObject = 3,         // A JS object (except for arrays and strings).
     405             :     kCode = 4,           // Compiled code.
     406             :     kClosure = 5,        // Function closure.
     407             :     kRegExp = 6,         // RegExp.
     408             :     kHeapNumber = 7,     // Number stored in the heap.
     409             :     kNative = 8,         // Native object (not from V8 heap).
     410             :     kSynthetic = 9,      // Synthetic object, usually used for grouping
     411             :                          // snapshot items together.
     412             :     kConsString = 10,    // Concatenated string. A pair of pointers to strings.
     413             :     kSlicedString = 11,  // Sliced string. A fragment of another string.
     414             :     kSymbol = 12,        // A Symbol (ES6).
     415             :     kBigInt = 13         // BigInt.
     416             :   };
     417             : 
     418             :   /** Returns node type (see HeapGraphNode::Type). */
     419             :   Type GetType() const;
     420             : 
     421             :   /**
     422             :    * Returns node name. Depending on node's type this can be the name
     423             :    * of the constructor (for objects), the name of the function (for
     424             :    * closures), string value, or an empty string (for compiled code).
     425             :    */
     426             :   Local<String> GetName() const;
     427             : 
     428             :   /**
     429             :    * Returns node id. For the same heap object, the id remains the same
     430             :    * across all snapshots.
     431             :    */
     432             :   SnapshotObjectId GetId() const;
     433             : 
     434             :   /** Returns node's own size, in bytes. */
     435             :   size_t GetShallowSize() const;
     436             : 
     437             :   /** Returns child nodes count of the node. */
     438             :   int GetChildrenCount() const;
     439             : 
     440             :   /** Retrieves a child by index. */
     441             :   const HeapGraphEdge* GetChild(int index) const;
     442             : };
     443             : 
     444             : 
     445             : /**
     446             :  * An interface for exporting data from V8, using "push" model.
     447             :  */
     448          90 : class V8_EXPORT OutputStream {  // NOLINT
     449             :  public:
     450             :   enum WriteResult {
     451             :     kContinue = 0,
     452             :     kAbort = 1
     453             :   };
     454          90 :   virtual ~OutputStream() = default;
     455             :   /** Notify about the end of stream. */
     456             :   virtual void EndOfStream() = 0;
     457             :   /** Get preferred output chunk size. Called only once. */
     458          75 :   virtual int GetChunkSize() { return 1024; }
     459             :   /**
     460             :    * Writes the next chunk of snapshot data into the stream. Writing
     461             :    * can be stopped by returning kAbort as function result. EndOfStream
     462             :    * will not be called in case writing was aborted.
     463             :    */
     464             :   virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
     465             :   /**
     466             :    * Writes the next chunk of heap stats data into the stream. Writing
     467             :    * can be stopped by returning kAbort as function result. EndOfStream
     468             :    * will not be called in case writing was aborted.
     469             :    */
     470           0 :   virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
     471           0 :     return kAbort;
     472             :   }
     473             : };
     474             : 
     475             : 
     476             : /**
     477             :  * HeapSnapshots record the state of the JS heap at some moment.
     478             :  */
     479             : class V8_EXPORT HeapSnapshot {
     480             :  public:
     481             :   enum SerializationFormat {
     482             :     kJSON = 0  // See format description near 'Serialize' method.
     483             :   };
     484             : 
     485             :   /** Returns the root node of the heap graph. */
     486             :   const HeapGraphNode* GetRoot() const;
     487             : 
     488             :   /** Returns a node by its id. */
     489             :   const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
     490             : 
     491             :   /** Returns total nodes count in the snapshot. */
     492             :   int GetNodesCount() const;
     493             : 
     494             :   /** Returns a node by index. */
     495             :   const HeapGraphNode* GetNode(int index) const;
     496             : 
     497             :   /** Returns a max seen JS object Id. */
     498             :   SnapshotObjectId GetMaxSnapshotJSObjectId() const;
     499             : 
     500             :   /**
     501             :    * Deletes the snapshot and removes it from HeapProfiler's list.
     502             :    * All pointers to nodes, edges and paths previously returned become
     503             :    * invalid.
     504             :    */
     505             :   void Delete();
     506             : 
     507             :   /**
     508             :    * Prepare a serialized representation of the snapshot. The result
     509             :    * is written into the stream provided in chunks of specified size.
     510             :    * The total length of the serialized snapshot is unknown in
     511             :    * advance, it can be roughly equal to JS heap size (that means,
     512             :    * it can be really big - tens of megabytes).
     513             :    *
     514             :    * For the JSON format, heap contents are represented as an object
     515             :    * with the following structure:
     516             :    *
     517             :    *  {
     518             :    *    snapshot: {
     519             :    *      title: "...",
     520             :    *      uid: nnn,
     521             :    *      meta: { meta-info },
     522             :    *      node_count: nnn,
     523             :    *      edge_count: nnn
     524             :    *    },
     525             :    *    nodes: [nodes array],
     526             :    *    edges: [edges array],
     527             :    *    strings: [strings array]
     528             :    *  }
     529             :    *
     530             :    * Nodes reference strings, other nodes, and edges by their indexes
     531             :    * in corresponding arrays.
     532             :    */
     533             :   void Serialize(OutputStream* stream,
     534             :                  SerializationFormat format = kJSON) const;
     535             : };
     536             : 
     537             : 
     538             : /**
     539             :  * An interface for reporting progress and controlling long-running
     540             :  * activities.
     541             :  */
     542          15 : class V8_EXPORT ActivityControl {  // NOLINT
     543             :  public:
     544             :   enum ControlOption {
     545             :     kContinue = 0,
     546             :     kAbort = 1
     547             :   };
     548          15 :   virtual ~ActivityControl() = default;
     549             :   /**
     550             :    * Notify about current progress. The activity can be stopped by
     551             :    * returning kAbort as the callback result.
     552             :    */
     553             :   virtual ControlOption ReportProgressValue(int done, int total) = 0;
     554             : };
     555             : 
     556             : 
     557             : /**
     558             :  * AllocationProfile is a sampled profile of allocations done by the program.
     559             :  * This is structured as a call-graph.
     560             :  */
     561          64 : class V8_EXPORT AllocationProfile {
     562             :  public:
     563             :   struct Allocation {
     564             :     /**
     565             :      * Size of the sampled allocation object.
     566             :      */
     567             :     size_t size;
     568             : 
     569             :     /**
     570             :      * The number of objects of such size that were sampled.
     571             :      */
     572             :     unsigned int count;
     573             :   };
     574             : 
     575             :   /**
     576             :    * Represents a node in the call-graph.
     577             :    */
     578        1896 :   struct Node {
     579             :     /**
     580             :      * Name of the function. May be empty for anonymous functions or if the
     581             :      * script corresponding to this function has been unloaded.
     582             :      */
     583             :     Local<String> name;
     584             : 
     585             :     /**
     586             :      * Name of the script containing the function. May be empty if the script
     587             :      * name is not available, or if the script has been unloaded.
     588             :      */
     589             :     Local<String> script_name;
     590             : 
     591             :     /**
     592             :      * id of the script where the function is located. May be equal to
     593             :      * v8::UnboundScript::kNoScriptId in cases where the script doesn't exist.
     594             :      */
     595             :     int script_id;
     596             : 
     597             :     /**
     598             :      * Start position of the function in the script.
     599             :      */
     600             :     int start_position;
     601             : 
     602             :     /**
     603             :      * 1-indexed line number where the function starts. May be
     604             :      * kNoLineNumberInfo if no line number information is available.
     605             :      */
     606             :     int line_number;
     607             : 
     608             :     /**
     609             :      * 1-indexed column number where the function starts. May be
     610             :      * kNoColumnNumberInfo if no line number information is available.
     611             :      */
     612             :     int column_number;
     613             : 
     614             :     /**
     615             :      * Unique id of the node.
     616             :      */
     617             :     uint32_t node_id;
     618             : 
     619             :     /**
     620             :      * List of callees called from this node for which we have sampled
     621             :      * allocations. The lifetime of the children is scoped to the containing
     622             :      * AllocationProfile.
     623             :      */
     624             :     std::vector<Node*> children;
     625             : 
     626             :     /**
     627             :      * List of self allocations done by this node in the call-graph.
     628             :      */
     629             :     std::vector<Allocation> allocations;
     630             :   };
     631             : 
     632             :   /**
     633             :    * Represent a single sample recorded for an allocation.
     634             :    */
     635             :   struct Sample {
     636             :     /**
     637             :      * id of the node in the profile tree.
     638             :      */
     639             :     uint32_t node_id;
     640             : 
     641             :     /**
     642             :      * Size of the sampled allocation object.
     643             :      */
     644             :     size_t size;
     645             : 
     646             :     /**
     647             :      * The number of objects of such size that were sampled.
     648             :      */
     649             :     unsigned int count;
     650             : 
     651             :     /**
     652             :      * Unique time-ordered id of the allocation sample. Can be used to track
     653             :      * what samples were added or removed between two snapshots.
     654             :      */
     655             :     uint64_t sample_id;
     656             :   };
     657             : 
     658             :   /**
     659             :    * Returns the root node of the call-graph. The root node corresponds to an
     660             :    * empty JS call-stack. The lifetime of the returned Node* is scoped to the
     661             :    * containing AllocationProfile.
     662             :    */
     663             :   virtual Node* GetRootNode() = 0;
     664             :   virtual const std::vector<Sample>& GetSamples() = 0;
     665             : 
     666          64 :   virtual ~AllocationProfile() = default;
     667             : 
     668             :   static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
     669             :   static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
     670             : };
     671             : 
     672             : /**
     673             :  * An object graph consisting of embedder objects and V8 objects.
     674             :  * Edges of the graph are strong references between the objects.
     675             :  * The embedder can build this graph during heap snapshot generation
     676             :  * to include the embedder objects in the heap snapshot.
     677             :  * Usage:
     678             :  * 1) Define derived class of EmbedderGraph::Node for embedder objects.
     679             :  * 2) Set the build embedder graph callback on the heap profiler using
     680             :  *    HeapProfiler::AddBuildEmbedderGraphCallback.
     681             :  * 3) In the callback use graph->AddEdge(node1, node2) to add an edge from
     682             :  *    node1 to node2.
     683             :  * 4) To represent references from/to V8 object, construct V8 nodes using
     684             :  *    graph->V8Node(value).
     685             :  */
     686          35 : class V8_EXPORT EmbedderGraph {
     687             :  public:
     688             :   class Node {
     689             :    public:
     690         140 :     Node() = default;
     691         140 :     virtual ~Node() = default;
     692             :     virtual const char* Name() = 0;
     693             :     virtual size_t SizeInBytes() = 0;
     694             :     /**
     695             :      * The corresponding V8 wrapper node if not null.
     696             :      * During heap snapshot generation the embedder node and the V8 wrapper
     697             :      * node will be merged into one node to simplify retaining paths.
     698             :      */
     699         185 :     virtual Node* WrapperNode() { return nullptr; }
     700         125 :     virtual bool IsRootNode() { return false; }
     701             :     /** Must return true for non-V8 nodes. */
     702         170 :     virtual bool IsEmbedderNode() { return true; }
     703             :     /**
     704             :      * Optional name prefix. It is used in Chrome for tagging detached nodes.
     705             :      */
     706          85 :     virtual const char* NamePrefix() { return nullptr; }
     707             : 
     708             :    private:
     709             :     Node(const Node&) = delete;
     710             :     Node& operator=(const Node&) = delete;
     711             :   };
     712             : 
     713             :   /**
     714             :    * Returns a node corresponding to the given V8 value. Ownership is not
     715             :    * transferred. The result pointer is valid while the graph is alive.
     716             :    */
     717             :   virtual Node* V8Node(const v8::Local<v8::Value>& value) = 0;
     718             : 
     719             :   /**
     720             :    * Adds the given node to the graph and takes ownership of the node.
     721             :    * Returns a raw pointer to the node that is valid while the graph is alive.
     722             :    */
     723             :   virtual Node* AddNode(std::unique_ptr<Node> node) = 0;
     724             : 
     725             :   /**
     726             :    * Adds an edge that represents a strong reference from the given
     727             :    * node |from| to the given node |to|. The nodes must be added to the graph
     728             :    * before calling this function.
     729             :    *
     730             :    * If name is nullptr, the edge will have auto-increment indexes, otherwise
     731             :    * it will be named accordingly.
     732             :    */
     733             :   virtual void AddEdge(Node* from, Node* to, const char* name = nullptr) = 0;
     734             : 
     735          35 :   virtual ~EmbedderGraph() = default;
     736             : };
     737             : 
     738             : /**
     739             :  * Interface for controlling heap profiling. Instance of the
     740             :  * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
     741             :  */
     742             : class V8_EXPORT HeapProfiler {
     743             :  public:
     744             :   enum SamplingFlags {
     745             :     kSamplingNoFlags = 0,
     746             :     kSamplingForceGC = 1 << 0,
     747             :   };
     748             : 
     749             :   /**
     750             :    * Callback function invoked during heap snapshot generation to retrieve
     751             :    * the embedder object graph. The callback should use graph->AddEdge(..) to
     752             :    * add references between the objects.
     753             :    * The callback must not trigger garbage collection in V8.
     754             :    */
     755             :   typedef void (*BuildEmbedderGraphCallback)(v8::Isolate* isolate,
     756             :                                              v8::EmbedderGraph* graph,
     757             :                                              void* data);
     758             : 
     759             :   /** TODO(addaleax): Remove */
     760             :   typedef void (*LegacyBuildEmbedderGraphCallback)(v8::Isolate* isolate,
     761             :                                                    v8::EmbedderGraph* graph);
     762             : 
     763             :   /** Returns the number of snapshots taken. */
     764             :   int GetSnapshotCount();
     765             : 
     766             :   /** Returns a snapshot by index. */
     767             :   const HeapSnapshot* GetHeapSnapshot(int index);
     768             : 
     769             :   /**
     770             :    * Returns SnapshotObjectId for a heap object referenced by |value| if
     771             :    * it has been seen by the heap profiler, kUnknownObjectId otherwise.
     772             :    */
     773             :   SnapshotObjectId GetObjectId(Local<Value> value);
     774             : 
     775             :   /**
     776             :    * Returns heap object with given SnapshotObjectId if the object is alive,
     777             :    * otherwise empty handle is returned.
     778             :    */
     779             :   Local<Value> FindObjectById(SnapshotObjectId id);
     780             : 
     781             :   /**
     782             :    * Clears internal map from SnapshotObjectId to heap object. The new objects
     783             :    * will not be added into it unless a heap snapshot is taken or heap object
     784             :    * tracking is kicked off.
     785             :    */
     786             :   void ClearObjectIds();
     787             : 
     788             :   /**
     789             :    * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
     790             :    * it in case heap profiler cannot find id  for the object passed as
     791             :    * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
     792             :    */
     793             :   static const SnapshotObjectId kUnknownObjectId = 0;
     794             : 
     795             :   /**
     796             :    * Callback interface for retrieving user friendly names of global objects.
     797             :    */
     798          25 :   class ObjectNameResolver {
     799             :    public:
     800             :     /**
     801             :      * Returns name to be used in the heap snapshot for given node. Returned
     802             :      * string must stay alive until snapshot collection is completed.
     803             :      */
     804             :     virtual const char* GetName(Local<Object> object) = 0;
     805             : 
     806             :    protected:
     807          30 :     virtual ~ObjectNameResolver() = default;
     808             :   };
     809             : 
     810             :   /**
     811             :    * Takes a heap snapshot and returns it.
     812             :    */
     813             :   const HeapSnapshot* TakeHeapSnapshot(
     814             :       ActivityControl* control = nullptr,
     815             :       ObjectNameResolver* global_object_name_resolver = nullptr);
     816             : 
     817             :   /**
     818             :    * Starts tracking of heap objects population statistics. After calling
     819             :    * this method, all heap objects relocations done by the garbage collector
     820             :    * are being registered.
     821             :    *
     822             :    * |track_allocations| parameter controls whether stack trace of each
     823             :    * allocation in the heap will be recorded and reported as part of
     824             :    * HeapSnapshot.
     825             :    */
     826             :   void StartTrackingHeapObjects(bool track_allocations = false);
     827             : 
     828             :   /**
     829             :    * Adds a new time interval entry to the aggregated statistics array. The
     830             :    * time interval entry contains information on the current heap objects
     831             :    * population size. The method also updates aggregated statistics and
     832             :    * reports updates for all previous time intervals via the OutputStream
     833             :    * object. Updates on each time interval are provided as a stream of the
     834             :    * HeapStatsUpdate structure instances.
     835             :    * If |timestamp_us| is supplied, timestamp of the new entry will be written
     836             :    * into it. The return value of the function is the last seen heap object Id.
     837             :    *
     838             :    * StartTrackingHeapObjects must be called before the first call to this
     839             :    * method.
     840             :    */
     841             :   SnapshotObjectId GetHeapStats(OutputStream* stream,
     842             :                                 int64_t* timestamp_us = nullptr);
     843             : 
     844             :   /**
     845             :    * Stops tracking of heap objects population statistics, cleans up all
     846             :    * collected data. StartHeapObjectsTracking must be called again prior to
     847             :    * calling GetHeapStats next time.
     848             :    */
     849             :   void StopTrackingHeapObjects();
     850             : 
     851             :   /**
     852             :    * Starts gathering a sampling heap profile. A sampling heap profile is
     853             :    * similar to tcmalloc's heap profiler and Go's mprof. It samples object
     854             :    * allocations and builds an online 'sampling' heap profile. At any point in
     855             :    * time, this profile is expected to be a representative sample of objects
     856             :    * currently live in the system. Each sampled allocation includes the stack
     857             :    * trace at the time of allocation, which makes this really useful for memory
     858             :    * leak detection.
     859             :    *
     860             :    * This mechanism is intended to be cheap enough that it can be used in
     861             :    * production with minimal performance overhead.
     862             :    *
     863             :    * Allocations are sampled using a randomized Poisson process. On average, one
     864             :    * allocation will be sampled every |sample_interval| bytes allocated. The
     865             :    * |stack_depth| parameter controls the maximum number of stack frames to be
     866             :    * captured on each allocation.
     867             :    *
     868             :    * NOTE: This is a proof-of-concept at this point. Right now we only sample
     869             :    * newspace allocations. Support for paged space allocation (e.g. pre-tenured
     870             :    * objects, large objects, code objects, etc.) and native allocations
     871             :    * doesn't exist yet, but is anticipated in the future.
     872             :    *
     873             :    * Objects allocated before the sampling is started will not be included in
     874             :    * the profile.
     875             :    *
     876             :    * Returns false if a sampling heap profiler is already running.
     877             :    */
     878             :   bool StartSamplingHeapProfiler(uint64_t sample_interval = 512 * 1024,
     879             :                                  int stack_depth = 16,
     880             :                                  SamplingFlags flags = kSamplingNoFlags);
     881             : 
     882             :   /**
     883             :    * Stops the sampling heap profile and discards the current profile.
     884             :    */
     885             :   void StopSamplingHeapProfiler();
     886             : 
     887             :   /**
     888             :    * Returns the sampled profile of allocations allocated (and still live) since
     889             :    * StartSamplingHeapProfiler was called. The ownership of the pointer is
     890             :    * transferred to the caller. Returns nullptr if sampling heap profiler is not
     891             :    * active.
     892             :    */
     893             :   AllocationProfile* GetAllocationProfile();
     894             : 
     895             :   /**
     896             :    * Deletes all snapshots taken. All previously returned pointers to
     897             :    * snapshots and their contents become invalid after this call.
     898             :    */
     899             :   void DeleteAllHeapSnapshots();
     900             : 
     901             :   V8_DEPRECATED(
     902             :       "Use AddBuildEmbedderGraphCallback to provide info about embedder nodes",
     903             :       void SetBuildEmbedderGraphCallback(
     904             :           LegacyBuildEmbedderGraphCallback callback));
     905             :   void AddBuildEmbedderGraphCallback(BuildEmbedderGraphCallback callback,
     906             :                                      void* data);
     907             :   void RemoveBuildEmbedderGraphCallback(BuildEmbedderGraphCallback callback,
     908             :                                         void* data);
     909             : 
     910             :   /**
     911             :    * Default value of persistent handle class ID. Must not be used to
     912             :    * define a class. Can be used to reset a class of a persistent
     913             :    * handle.
     914             :    */
     915             :   static const uint16_t kPersistentHandleNoClassId = 0;
     916             : 
     917             :  private:
     918             :   HeapProfiler();
     919             :   ~HeapProfiler();
     920             :   HeapProfiler(const HeapProfiler&);
     921             :   HeapProfiler& operator=(const HeapProfiler&);
     922             : };
     923             : 
     924             : /**
     925             :  * A struct for exporting HeapStats data from V8, using "push" model.
     926             :  * See HeapProfiler::GetHeapStats.
     927             :  */
     928             : struct HeapStatsUpdate {
     929             :   HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
     930          50 :     : index(index), count(count), size(size) { }
     931             :   uint32_t index;  // Index of the time interval that was changed.
     932             :   uint32_t count;  // New value of count field for the interval with this index.
     933             :   uint32_t size;  // New value of size field for the interval with this index.
     934             : };
     935             : 
     936             : #define CODE_EVENTS_LIST(V) \
     937             :   V(Builtin)                \
     938             :   V(Callback)               \
     939             :   V(Eval)                   \
     940             :   V(Function)               \
     941             :   V(InterpretedFunction)    \
     942             :   V(Handler)                \
     943             :   V(BytecodeHandler)        \
     944             :   V(LazyCompile)            \
     945             :   V(RegExp)                 \
     946             :   V(Script)                 \
     947             :   V(Stub)
     948             : 
     949             : /**
     950             :  * Note that this enum may be extended in the future. Please include a default
     951             :  * case if this enum is used in a switch statement.
     952             :  */
     953             : enum CodeEventType {
     954             :   kUnknownType = 0
     955             : #define V(Name) , k##Name##Type
     956             :   CODE_EVENTS_LIST(V)
     957             : #undef V
     958             : };
     959             : 
     960             : /**
     961             :  * Representation of a code creation event
     962             :  */
     963             : class V8_EXPORT CodeEvent {
     964             :  public:
     965             :   uintptr_t GetCodeStartAddress();
     966             :   size_t GetCodeSize();
     967             :   Local<String> GetFunctionName();
     968             :   Local<String> GetScriptName();
     969             :   int GetScriptLine();
     970             :   int GetScriptColumn();
     971             :   /**
     972             :    * NOTE (mmarchini): We can't allocate objects in the heap when we collect
     973             :    * existing code, and both the code type and the comment are not stored in the
     974             :    * heap, so we return those as const char*.
     975             :    */
     976             :   CodeEventType GetCodeType();
     977             :   const char* GetComment();
     978             : 
     979             :   static const char* GetCodeEventTypeName(CodeEventType code_event_type);
     980             : };
     981             : 
     982             : /**
     983             :  * Interface to listen to code creation events.
     984             :  */
     985             : class V8_EXPORT CodeEventHandler {
     986             :  public:
     987             :   /**
     988             :    * Creates a new listener for the |isolate|. The isolate must be initialized.
     989             :    * The listener object must be disposed after use by calling |Dispose| method.
     990             :    * Multiple listeners can be created for the same isolate.
     991             :    */
     992             :   explicit CodeEventHandler(Isolate* isolate);
     993             :   virtual ~CodeEventHandler();
     994             : 
     995             :   virtual void Handle(CodeEvent* code_event) = 0;
     996             : 
     997             :   void Enable();
     998             :   void Disable();
     999             : 
    1000             :  private:
    1001             :   CodeEventHandler();
    1002             :   CodeEventHandler(const CodeEventHandler&);
    1003             :   CodeEventHandler& operator=(const CodeEventHandler&);
    1004             :   void* internal_listener_;
    1005             : };
    1006             : 
    1007             : }  // namespace v8
    1008             : 
    1009             : 
    1010             : #endif  // V8_V8_PROFILER_H_

Generated by: LCOV version 1.10