Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

611 lines
19 KiB

  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. #ifndef V8_V8_PROFILER_H_
  5. #define V8_V8_PROFILER_H_
  6. #include "v8.h"
  7. /**
  8. * Profiler support for the V8 JavaScript engine.
  9. */
  10. namespace v8 {
  11. class HeapGraphNode;
  12. struct HeapStatsUpdate;
  13. typedef uint32_t SnapshotObjectId;
  14. /**
  15. * CpuProfileNode represents a node in a call graph.
  16. */
  17. class V8_EXPORT CpuProfileNode {
  18. public:
  19. /** Returns function name (empty string for anonymous functions.) */
  20. Handle<String> GetFunctionName() const;
  21. /** Returns id of the script where function is located. */
  22. int GetScriptId() const;
  23. /** Returns resource name for script from where the function originates. */
  24. Handle<String> GetScriptResourceName() const;
  25. /**
  26. * Returns the number, 1-based, of the line where the function originates.
  27. * kNoLineNumberInfo if no line number information is available.
  28. */
  29. int GetLineNumber() const;
  30. /**
  31. * Returns 1-based number of the column where the function originates.
  32. * kNoColumnNumberInfo if no column number information is available.
  33. */
  34. int GetColumnNumber() const;
  35. /** Returns bailout reason for the function
  36. * if the optimization was disabled for it.
  37. */
  38. const char* GetBailoutReason() const;
  39. /**
  40. * Returns the count of samples where the function was currently executing.
  41. */
  42. unsigned GetHitCount() const;
  43. /** Returns function entry UID. */
  44. unsigned GetCallUid() const;
  45. /** Returns id of the node. The id is unique within the tree */
  46. unsigned GetNodeId() const;
  47. /** Returns child nodes count of the node. */
  48. int GetChildrenCount() const;
  49. /** Retrieves a child node by index. */
  50. const CpuProfileNode* GetChild(int index) const;
  51. static const int kNoLineNumberInfo = Message::kNoLineNumberInfo;
  52. static const int kNoColumnNumberInfo = Message::kNoColumnInfo;
  53. };
  54. /**
  55. * CpuProfile contains a CPU profile in a form of top-down call tree
  56. * (from main() down to functions that do all the work).
  57. */
  58. class V8_EXPORT CpuProfile {
  59. public:
  60. /** Returns CPU profile title. */
  61. Handle<String> GetTitle() const;
  62. /** Returns the root node of the top down call tree. */
  63. const CpuProfileNode* GetTopDownRoot() const;
  64. /**
  65. * Returns number of samples recorded. The samples are not recorded unless
  66. * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true.
  67. */
  68. int GetSamplesCount() const;
  69. /**
  70. * Returns profile node corresponding to the top frame the sample at
  71. * the given index.
  72. */
  73. const CpuProfileNode* GetSample(int index) const;
  74. /**
  75. * Returns the timestamp of the sample. The timestamp is the number of
  76. * microseconds since some unspecified starting point.
  77. * The point is equal to the starting point used by GetStartTime.
  78. */
  79. int64_t GetSampleTimestamp(int index) const;
  80. /**
  81. * Returns time when the profile recording was started (in microseconds)
  82. * since some unspecified starting point.
  83. */
  84. int64_t GetStartTime() const;
  85. /**
  86. * Returns time when the profile recording was stopped (in microseconds)
  87. * since some unspecified starting point.
  88. * The point is equal to the starting point used by GetStartTime.
  89. */
  90. int64_t GetEndTime() const;
  91. /**
  92. * Deletes the profile and removes it from CpuProfiler's list.
  93. * All pointers to nodes previously returned become invalid.
  94. */
  95. void Delete();
  96. };
  97. /**
  98. * Interface for controlling CPU profiling. Instance of the
  99. * profiler can be retrieved using v8::Isolate::GetCpuProfiler.
  100. */
  101. class V8_EXPORT CpuProfiler {
  102. public:
  103. /**
  104. * Changes default CPU profiler sampling interval to the specified number
  105. * of microseconds. Default interval is 1000us. This method must be called
  106. * when there are no profiles being recorded.
  107. */
  108. void SetSamplingInterval(int us);
  109. /**
  110. * Starts collecting CPU profile. Title may be an empty string. It
  111. * is allowed to have several profiles being collected at
  112. * once. Attempts to start collecting several profiles with the same
  113. * title are silently ignored. While collecting a profile, functions
  114. * from all security contexts are included in it. The token-based
  115. * filtering is only performed when querying for a profile.
  116. *
  117. * |record_samples| parameter controls whether individual samples should
  118. * be recorded in addition to the aggregated tree.
  119. */
  120. void StartProfiling(Handle<String> title, bool record_samples = false);
  121. /** Deprecated. Use StartProfiling instead. */
  122. V8_DEPRECATED("Use StartProfiling",
  123. void StartCpuProfiling(Handle<String> title,
  124. bool record_samples = false));
  125. /**
  126. * Stops collecting CPU profile with a given title and returns it.
  127. * If the title given is empty, finishes the last profile started.
  128. */
  129. CpuProfile* StopProfiling(Handle<String> title);
  130. /** Deprecated. Use StopProfiling instead. */
  131. V8_DEPRECATED("Use StopProfiling",
  132. const CpuProfile* StopCpuProfiling(Handle<String> title));
  133. /**
  134. * Tells the profiler whether the embedder is idle.
  135. */
  136. void SetIdle(bool is_idle);
  137. private:
  138. CpuProfiler();
  139. ~CpuProfiler();
  140. CpuProfiler(const CpuProfiler&);
  141. CpuProfiler& operator=(const CpuProfiler&);
  142. };
  143. /**
  144. * HeapSnapshotEdge represents a directed connection between heap
  145. * graph nodes: from retainers to retained nodes.
  146. */
  147. class V8_EXPORT HeapGraphEdge {
  148. public:
  149. enum Type {
  150. kContextVariable = 0, // A variable from a function context.
  151. kElement = 1, // An element of an array.
  152. kProperty = 2, // A named object property.
  153. kInternal = 3, // A link that can't be accessed from JS,
  154. // thus, its name isn't a real property name
  155. // (e.g. parts of a ConsString).
  156. kHidden = 4, // A link that is needed for proper sizes
  157. // calculation, but may be hidden from user.
  158. kShortcut = 5, // A link that must not be followed during
  159. // sizes calculation.
  160. kWeak = 6 // A weak reference (ignored by the GC).
  161. };
  162. /** Returns edge type (see HeapGraphEdge::Type). */
  163. Type GetType() const;
  164. /**
  165. * Returns edge name. This can be a variable name, an element index, or
  166. * a property name.
  167. */
  168. Handle<Value> GetName() const;
  169. /** Returns origin node. */
  170. const HeapGraphNode* GetFromNode() const;
  171. /** Returns destination node. */
  172. const HeapGraphNode* GetToNode() const;
  173. };
  174. /**
  175. * HeapGraphNode represents a node in a heap graph.
  176. */
  177. class V8_EXPORT HeapGraphNode {
  178. public:
  179. enum Type {
  180. kHidden = 0, // Hidden node, may be filtered when shown to user.
  181. kArray = 1, // An array of elements.
  182. kString = 2, // A string.
  183. kObject = 3, // A JS object (except for arrays and strings).
  184. kCode = 4, // Compiled code.
  185. kClosure = 5, // Function closure.
  186. kRegExp = 6, // RegExp.
  187. kHeapNumber = 7, // Number stored in the heap.
  188. kNative = 8, // Native object (not from V8 heap).
  189. kSynthetic = 9, // Synthetic object, usualy used for grouping
  190. // snapshot items together.
  191. kConsString = 10, // Concatenated string. A pair of pointers to strings.
  192. kSlicedString = 11, // Sliced string. A fragment of another string.
  193. kSymbol = 12 // A Symbol (ES6).
  194. };
  195. /** Returns node type (see HeapGraphNode::Type). */
  196. Type GetType() const;
  197. /**
  198. * Returns node name. Depending on node's type this can be the name
  199. * of the constructor (for objects), the name of the function (for
  200. * closures), string value, or an empty string (for compiled code).
  201. */
  202. Handle<String> GetName() const;
  203. /**
  204. * Returns node id. For the same heap object, the id remains the same
  205. * across all snapshots.
  206. */
  207. SnapshotObjectId GetId() const;
  208. /** Returns node's own size, in bytes. */
  209. V8_DEPRECATED("Use GetShallowSize instead",
  210. int GetSelfSize() const);
  211. /** Returns node's own size, in bytes. */
  212. size_t GetShallowSize() const;
  213. /** Returns child nodes count of the node. */
  214. int GetChildrenCount() const;
  215. /** Retrieves a child by index. */
  216. const HeapGraphEdge* GetChild(int index) const;
  217. };
  218. /**
  219. * An interface for exporting data from V8, using "push" model.
  220. */
  221. class V8_EXPORT OutputStream { // NOLINT
  222. public:
  223. enum WriteResult {
  224. kContinue = 0,
  225. kAbort = 1
  226. };
  227. virtual ~OutputStream() {}
  228. /** Notify about the end of stream. */
  229. virtual void EndOfStream() = 0;
  230. /** Get preferred output chunk size. Called only once. */
  231. virtual int GetChunkSize() { return 1024; }
  232. /**
  233. * Writes the next chunk of snapshot data into the stream. Writing
  234. * can be stopped by returning kAbort as function result. EndOfStream
  235. * will not be called in case writing was aborted.
  236. */
  237. virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
  238. /**
  239. * Writes the next chunk of heap stats data into the stream. Writing
  240. * can be stopped by returning kAbort as function result. EndOfStream
  241. * will not be called in case writing was aborted.
  242. */
  243. virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
  244. return kAbort;
  245. }
  246. };
  247. /**
  248. * HeapSnapshots record the state of the JS heap at some moment.
  249. */
  250. class V8_EXPORT HeapSnapshot {
  251. public:
  252. enum SerializationFormat {
  253. kJSON = 0 // See format description near 'Serialize' method.
  254. };
  255. /** Returns heap snapshot UID (assigned by the profiler.) */
  256. unsigned GetUid() const;
  257. /** Returns heap snapshot title. */
  258. Handle<String> GetTitle() const;
  259. /** Returns the root node of the heap graph. */
  260. const HeapGraphNode* GetRoot() const;
  261. /** Returns a node by its id. */
  262. const HeapGraphNode* GetNodeById(SnapshotObjectId id) const;
  263. /** Returns total nodes count in the snapshot. */
  264. int GetNodesCount() const;
  265. /** Returns a node by index. */
  266. const HeapGraphNode* GetNode(int index) const;
  267. /** Returns a max seen JS object Id. */
  268. SnapshotObjectId GetMaxSnapshotJSObjectId() const;
  269. /**
  270. * Deletes the snapshot and removes it from HeapProfiler's list.
  271. * All pointers to nodes, edges and paths previously returned become
  272. * invalid.
  273. */
  274. void Delete();
  275. /**
  276. * Prepare a serialized representation of the snapshot. The result
  277. * is written into the stream provided in chunks of specified size.
  278. * The total length of the serialized snapshot is unknown in
  279. * advance, it can be roughly equal to JS heap size (that means,
  280. * it can be really big - tens of megabytes).
  281. *
  282. * For the JSON format, heap contents are represented as an object
  283. * with the following structure:
  284. *
  285. * {
  286. * snapshot: {
  287. * title: "...",
  288. * uid: nnn,
  289. * meta: { meta-info },
  290. * node_count: nnn,
  291. * edge_count: nnn
  292. * },
  293. * nodes: [nodes array],
  294. * edges: [edges array],
  295. * strings: [strings array]
  296. * }
  297. *
  298. * Nodes reference strings, other nodes, and edges by their indexes
  299. * in corresponding arrays.
  300. */
  301. void Serialize(OutputStream* stream, SerializationFormat format) const;
  302. };
  303. /**
  304. * An interface for reporting progress and controlling long-running
  305. * activities.
  306. */
  307. class V8_EXPORT ActivityControl { // NOLINT
  308. public:
  309. enum ControlOption {
  310. kContinue = 0,
  311. kAbort = 1
  312. };
  313. virtual ~ActivityControl() {}
  314. /**
  315. * Notify about current progress. The activity can be stopped by
  316. * returning kAbort as the callback result.
  317. */
  318. virtual ControlOption ReportProgressValue(int done, int total) = 0;
  319. };
  320. /**
  321. * Interface for controlling heap profiling. Instance of the
  322. * profiler can be retrieved using v8::Isolate::GetHeapProfiler.
  323. */
  324. class V8_EXPORT HeapProfiler {
  325. public:
  326. /**
  327. * Callback function invoked for obtaining RetainedObjectInfo for
  328. * the given JavaScript wrapper object. It is prohibited to enter V8
  329. * while the callback is running: only getters on the handle and
  330. * GetPointerFromInternalField on the objects are allowed.
  331. */
  332. typedef RetainedObjectInfo* (*WrapperInfoCallback)
  333. (uint16_t class_id, Handle<Value> wrapper);
  334. /** Returns the number of snapshots taken. */
  335. int GetSnapshotCount();
  336. /** Returns a snapshot by index. */
  337. const HeapSnapshot* GetHeapSnapshot(int index);
  338. /**
  339. * Returns SnapshotObjectId for a heap object referenced by |value| if
  340. * it has been seen by the heap profiler, kUnknownObjectId otherwise.
  341. */
  342. SnapshotObjectId GetObjectId(Handle<Value> value);
  343. /**
  344. * Returns heap object with given SnapshotObjectId if the object is alive,
  345. * otherwise empty handle is returned.
  346. */
  347. Handle<Value> FindObjectById(SnapshotObjectId id);
  348. /**
  349. * Clears internal map from SnapshotObjectId to heap object. The new objects
  350. * will not be added into it unless a heap snapshot is taken or heap object
  351. * tracking is kicked off.
  352. */
  353. void ClearObjectIds();
  354. /**
  355. * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return
  356. * it in case heap profiler cannot find id for the object passed as
  357. * parameter. HeapSnapshot::GetNodeById will always return NULL for such id.
  358. */
  359. static const SnapshotObjectId kUnknownObjectId = 0;
  360. /**
  361. * Callback interface for retrieving user friendly names of global objects.
  362. */
  363. class ObjectNameResolver {
  364. public:
  365. /**
  366. * Returns name to be used in the heap snapshot for given node. Returned
  367. * string must stay alive until snapshot collection is completed.
  368. */
  369. virtual const char* GetName(Handle<Object> object) = 0;
  370. protected:
  371. virtual ~ObjectNameResolver() {}
  372. };
  373. /**
  374. * Takes a heap snapshot and returns it. Title may be an empty string.
  375. */
  376. const HeapSnapshot* TakeHeapSnapshot(
  377. Handle<String> title,
  378. ActivityControl* control = NULL,
  379. ObjectNameResolver* global_object_name_resolver = NULL);
  380. /**
  381. * Starts tracking of heap objects population statistics. After calling
  382. * this method, all heap objects relocations done by the garbage collector
  383. * are being registered.
  384. *
  385. * |track_allocations| parameter controls whether stack trace of each
  386. * allocation in the heap will be recorded and reported as part of
  387. * HeapSnapshot.
  388. */
  389. void StartTrackingHeapObjects(bool track_allocations = false);
  390. /**
  391. * Adds a new time interval entry to the aggregated statistics array. The
  392. * time interval entry contains information on the current heap objects
  393. * population size. The method also updates aggregated statistics and
  394. * reports updates for all previous time intervals via the OutputStream
  395. * object. Updates on each time interval are provided as a stream of the
  396. * HeapStatsUpdate structure instances.
  397. * The return value of the function is the last seen heap object Id.
  398. *
  399. * StartTrackingHeapObjects must be called before the first call to this
  400. * method.
  401. */
  402. SnapshotObjectId GetHeapStats(OutputStream* stream);
  403. /**
  404. * Stops tracking of heap objects population statistics, cleans up all
  405. * collected data. StartHeapObjectsTracking must be called again prior to
  406. * calling PushHeapObjectsStats next time.
  407. */
  408. void StopTrackingHeapObjects();
  409. /**
  410. * Deletes all snapshots taken. All previously returned pointers to
  411. * snapshots and their contents become invalid after this call.
  412. */
  413. void DeleteAllHeapSnapshots();
  414. /** Binds a callback to embedder's class ID. */
  415. void SetWrapperClassInfoProvider(
  416. uint16_t class_id,
  417. WrapperInfoCallback callback);
  418. /**
  419. * Default value of persistent handle class ID. Must not be used to
  420. * define a class. Can be used to reset a class of a persistent
  421. * handle.
  422. */
  423. static const uint16_t kPersistentHandleNoClassId = 0;
  424. /** Returns memory used for profiler internal data and snapshots. */
  425. size_t GetProfilerMemorySize();
  426. /**
  427. * Sets a RetainedObjectInfo for an object group (see V8::SetObjectGroupId).
  428. */
  429. void SetRetainedObjectInfo(UniqueId id, RetainedObjectInfo* info);
  430. private:
  431. HeapProfiler();
  432. ~HeapProfiler();
  433. HeapProfiler(const HeapProfiler&);
  434. HeapProfiler& operator=(const HeapProfiler&);
  435. };
  436. /**
  437. * Interface for providing information about embedder's objects
  438. * held by global handles. This information is reported in two ways:
  439. *
  440. * 1. When calling AddObjectGroup, an embedder may pass
  441. * RetainedObjectInfo instance describing the group. To collect
  442. * this information while taking a heap snapshot, V8 calls GC
  443. * prologue and epilogue callbacks.
  444. *
  445. * 2. When a heap snapshot is collected, V8 additionally
  446. * requests RetainedObjectInfos for persistent handles that
  447. * were not previously reported via AddObjectGroup.
  448. *
  449. * Thus, if an embedder wants to provide information about native
  450. * objects for heap snapshots, he can do it in a GC prologue
  451. * handler, and / or by assigning wrapper class ids in the following way:
  452. *
  453. * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider.
  454. * 2. Call SetWrapperClassId on certain persistent handles.
  455. *
  456. * V8 takes ownership of RetainedObjectInfo instances passed to it and
  457. * keeps them alive only during snapshot collection. Afterwards, they
  458. * are freed by calling the Dispose class function.
  459. */
  460. class V8_EXPORT RetainedObjectInfo { // NOLINT
  461. public:
  462. /** Called by V8 when it no longer needs an instance. */
  463. virtual void Dispose() = 0;
  464. /** Returns whether two instances are equivalent. */
  465. virtual bool IsEquivalent(RetainedObjectInfo* other) = 0;
  466. /**
  467. * Returns hash value for the instance. Equivalent instances
  468. * must have the same hash value.
  469. */
  470. virtual intptr_t GetHash() = 0;
  471. /**
  472. * Returns human-readable label. It must be a null-terminated UTF-8
  473. * encoded string. V8 copies its contents during a call to GetLabel.
  474. */
  475. virtual const char* GetLabel() = 0;
  476. /**
  477. * Returns human-readable group label. It must be a null-terminated UTF-8
  478. * encoded string. V8 copies its contents during a call to GetGroupLabel.
  479. * Heap snapshot generator will collect all the group names, create
  480. * top level entries with these names and attach the objects to the
  481. * corresponding top level group objects. There is a default
  482. * implementation which is required because embedders don't have their
  483. * own implementation yet.
  484. */
  485. virtual const char* GetGroupLabel() { return GetLabel(); }
  486. /**
  487. * Returns element count in case if a global handle retains
  488. * a subgraph by holding one of its nodes.
  489. */
  490. virtual intptr_t GetElementCount() { return -1; }
  491. /** Returns embedder's object size in bytes. */
  492. virtual intptr_t GetSizeInBytes() { return -1; }
  493. protected:
  494. RetainedObjectInfo() {}
  495. virtual ~RetainedObjectInfo() {}
  496. private:
  497. RetainedObjectInfo(const RetainedObjectInfo&);
  498. RetainedObjectInfo& operator=(const RetainedObjectInfo&);
  499. };
  500. /**
  501. * A struct for exporting HeapStats data from V8, using "push" model.
  502. * See HeapProfiler::GetHeapStats.
  503. */
  504. struct HeapStatsUpdate {
  505. HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size)
  506. : index(index), count(count), size(size) { }
  507. uint32_t index; // Index of the time interval that was changed.
  508. uint32_t count; // New value of count field for the interval with this index.
  509. uint32_t size; // New value of size field for the interval with this index.
  510. };
  511. } // namespace v8
  512. #endif // V8_V8_PROFILER_H_