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