Debian Codegraph @

js/src/doc/Debugger/Tutorial-Alloc-Log-Tree.md

raw
1 # Tutorial: Show Allocations Per Call Path
2
3 This page shows how to use the [`Debugger` API][debugger] to show how many
4 objects a web page allocates, sorted by the function call path that allocated
5 them.
6
7 1. Visit the URL `about:config`, and set the `devtools.chrome.enabled`
8 preference to `true`:
9
10 ![Setting the 'devtools.chrome.enabled' preference][img-chrome-pref]
11
12 2. Open a developer Scratchpad (Menu button > Developer > Scratchpad), and
13 select "Browser" from the "Environment" menu. (This menu will not be
14 present unless you have changed the preference as explained above.)
15
16 ![Selecting the 'browser' context in the Scratchpad][img-scratchpad-browser]
17
18 3. Enter the following code in the Scratchpad:
19
20 ```js
21 // This simply defines the 'Debugger' constructor in this
22 // Scratchpad; it doesn't actually start debugging anything.
23 const { addDebuggerToGlobal } = ChromeUtils.importESModule(
24 'resource://gre/modules/jsdebugger.sys.mjs'
25 );
26 addDebuggerToGlobal(window);
27
28 (function () {
29 // The debugger we'll use to observe a tab's allocation.
30 var dbg;
31
32 // Start measuring the selected tab's main window's memory
33 // consumption. This function is available in the browser
34 // console.
35 window.demoTrackAllocations = function() {
36 dbg = new Debugger;
37
38 // This makes hacking on the demo *much* more
39 // pleasant.
40 dbg.uncaughtExceptionHook = handleUncaughtException;
41
42 // Find the current tab's main content window.
43 var w = gBrowser.selectedBrowser.contentWindow;
44 console.log("Tracking allocations in page: " +
45 w.location.href);
46
47 // Make that window a debuggee of our Debugger.
48 dbg.addDebuggee(w.wrappedJSObject);
49
50 // Enable allocation tracking in dbg's debuggees.
51 dbg.memory.trackingAllocationSites = true;
52 }
53
54 window.demoPlotAllocations = function() {
55 // Grab the allocation log.
56 var log = dbg.memory.drainAllocationsLog();
57
58 // Neutralize the Debugger, and drop it on the floor
59 // for the GC to collect.
60 console.log("Stopping allocation tracking.");
61 dbg.removeAllDebuggees();
62 dbg = undefined;
63
64 // Analyze and display the allocation log.
65 plot(log);
66 }
67
68 function handleUncaughtException(ex) {
69 console.log('Debugger hook threw:');
70 console.log(ex.toString());
71 console.log('Stack:');
72 console.log(ex.stack);
73 };
74
75 function plot(log) {
76 // Given the log, compute a map from allocation sites to
77 // allocation counts. Note that stack entries are '===' if
78 // they represent the same site with the same callers.
79 var counts = new Map;
80 for (let site of log) {
81 // This is a kludge, necessary for now. The saved stacks
82 // are new, and Firefox doesn't yet understand that they
83 // are safe for chrome code to use, so we must tell it
84 // so explicitly.
85 site = Components.utils.waiveXrays(site.frame);
86
87 if (!counts.has(site))
88 counts.set(site, 0);
89 counts.set(site, counts.get(site) + 1);
90 }
91
92 // Walk from each site that allocated something up to the
93 // root, computing allocation totals that include
94 // children. Remember that 'null' is a valid site,
95 // representing the root.
96 var totals = new Map;
97 for (let [site, count] of counts) {
98 for(;;) {
99 if (!totals.has(site))
100 totals.set(site, 0);
101 totals.set(site, totals.get(site) + count);
102 if (!site)
103 break;
104 site = site.parent;
105 }
106 }
107
108 // Compute parent-to-child links, since saved stack frames
109 // have only parent links.
110 var rootChildren = new Map;
111 function childMapFor(site) {
112 if (!site)
113 return rootChildren;
114
115 let parentMap = childMapFor(site.parent);
116 if (parentMap.has(site))
117 return parentMap.get(site);
118
119 var m = new Map;
120 parentMap.set(site, m);
121 return m;
122 }
123 for (let [site, total] of totals) {
124 childMapFor(site);
125 }
126
127 // Print the allocation count for |site|. Print
128 // |children|'s entries as |site|'s child nodes. Indent
129 // the whole thing by |indent|.
130 function walk(site, children, indent) {
131 var name, place;
132 if (site) {
133 name = site.functionDisplayName;
134 place = ' ' + site.source + ':' + site.line + ':' + site.column;
135 } else {
136 name = '(root)';
137 place = '';
138 }
139 console.log(indent + totals.get(site) + ': ' + name + place);
140 for (let [child, grandchildren] of children)
141 walk(child, grandchildren, indent + ' ');
142 }
143 walk(null, rootChildren, '');
144 }
145 })();
146 ```
147
148 4. In the Scratchpad, ensure that no text is selected, and press the "Run"
149 button. (If you get an error complaining that `Components.utils` is not
150 defined, be sure you've selected `Browser` from the scratchpad's
151 `Environment` menu, as described in step 2.)
152
153 5. Save the following HTML text to a file, and visit the file in your browser.
154 Make sure the current browser tab is displaying this page.
155
156 ```html
157 <div onclick="doDivsAndSpans()">
158 Click here to make the page do some allocations.
159 </div>
160
161 <script>
162 function makeFactory(type) {
163 return function factory(content) {
164 var elt = document.createElement(type);
165 elt.textContent = content;
166 return elt;
167 };
168 }
169
170 var divFactory = makeFactory('div');
171 var spanFactory = makeFactory('span');
172
173 function divsAndSpans() {
174 for (i = 0; i < 10; i++) {
175 var div = divFactory('div #' + i);
176 div.appendChild(spanFactory('span #' + i));
177 document.body.appendChild(div);
178 }
179 }
180
181 function doDivsAndSpans() { divsAndSpans(); }
182 </script>
183 ```
184
185 6. Open the browser console (Menu Button > Developer > Browser Console), and
186 then evaluate the expression `demoTrackAllocations()` in the browser
187 console. This begins logging allocations in the current browser tab.
188
189 7. In the browser tab, click on the text that says "Click here...". The event
190 handler should add some text to the end of the page.
191
192 8. Back in the browser console, evaluate the expression
193 `demoPlotAllocations()`. This stops logging allocations, and displays a tree
194 of allocations:
195
196 ![An allocation plot, displayed in the console][img-alloc-plot]
197
198 The numbers at the left edge of each line show the total number of objects
199 allocated at that site or at sites called from there. After the count, we
200 see the function name, and the source code location of the call site or
201 allocation.
202
203 The `(root)` node's count includes objects allocated in the content page by
204 the web browser, like DOM events. Indeed, this display shows that
205 `popup.xml` and `content.js`, which are internal components of Firefox,
206 allocated more objects in the page's compartment than the page itself. (We
207 will probably revise the allocation log to present such allocations in a way
208 that is more informative, and that exposes less of Firefox's internal
209 structure.)
210
211 As expected, the `onclick` handler is responsible for all allocation done by
212 the page's own code. (The line number for the onclick handler is `1`,
213 indicating that the allocating call is located on line one of the handler
214 text itself. We will probably change this to be the line number within
215 `page.html`, not the line number within the handler code.)
216
217 The `onclick` handler calls `doDivsAndSpans`, which calls `divsAndSpans`,
218 which invokes closures of `factory` to do all the actual allocation. (It is
219 unclear why `spanFactory` allocated thirteen objects, despite being called
220 only ten times.)
221
222
223 [debugger]: Debugger-API.md
224 [img-chrome-pref]: enable-chrome-devtools.png
225 [img-scratchpad-browser]: scratchpad-browser-environment.png
226 [img-alloc-plot]: alloc-plot-console.png