Debian Codegraph @

js/src/doc/Debugger/Debugger.Memory.md

raw
1 Debugger.Memory
2 ===============
3
4 The [`Debugger API`][debugger] can help tools observe the debuggee's memory use
5 in various ways:
6
7 - It can mark each new object with the JavaScript call stack at which it was
8 allocated.
9
10 - It can log all object allocations, yielding a stream of JavaScript call stacks
11 at which allocations have occurred.
12
13 - It can compute a *census* of items belonging to the debuggee, categorizing
14 items in various ways, and yielding item counts.
15
16 If <i>dbg</i> is a [`Debugger`][debugger-object] instance, then the methods and
17 accessor properties of `dbg.memory` control how <i>dbg</i>
18 observes its debuggees' memory use. The `dbg.memory` object is
19 an instance of `Debugger.Memory`; its inherited accessors and methods are
20 described below.
21
22
23 ## Allocation Site Tracking
24
25 The JavaScript engine marks each new object with the call stack at which it was
26 allocated, if:
27
28 - the object is allocated in the scope of a global object that is a debuggee of
29 some [`Debugger`][debugger-object] instance <i>dbg</i>; and
30
31 - <code><i>dbg</i>.memory.[trackingAllocationSites][tracking-allocs]</code> is
32 set to `true`.
33
34 - A [Bernoulli trial][bernoulli-trial] succeeds, with probability equal to the
35 maximum of
36 [`d.memory.allocationSamplingProbability`][alloc-sampling-probability] of all
37 `Debugger` instances `d` that are observing the global that this object is
38 allocated within the scope of.
39
40 Given a [`Debugger.Object`][object] instance <i>dobj</i> referring to some
41 object, <code><i>dobj</i>.[allocationSite][allocation-site]</code> returns a
42 [saved call stack][saved-frame] indicating where <i>dobj</i>'s referent was
43 allocated.
44
45
46 ## Allocation Logging
47
48 If <i>dbg</i> is a [`Debugger`][debugger-object] instance, and
49 <code><i>dbg</i>.memory.[trackingAllocationSites][tracking-allocs]</code> is set
50 to `true`, then the JavaScript engine logs each object allocated by <i>dbg</i>'s
51 debuggee code. You can retrieve the current log by calling
52 <code><i>dbg</i>.memory.[drainAllocationsLog][drain-alloc-log]</code>. You can
53 control the limit on the log's size by setting
54 <code><i>dbg</i>.memory.[maxAllocationsLogLength][max-alloc-log]</code>.
55
56
57 ## Censuses
58
59 A *census* is a complete traversal of the graph of all reachable memory items
60 belonging to a particular `Debugger`'s debuggees. It produces a count of those
61 items, broken down by various criteria. If <i>dbg</i> is a
62 [`Debugger`][debugger-object] instance, you can call
63 <code><i>dbg</i>.memory.[takeCensus][take-census]</code> to conduct a census of
64 its debuggees' possessions.
65
66
67 Accessor Properties of the `Debugger.Memory.prototype` Object
68 -------------------------------------------------------------
69
70 If <i>dbg</i> is a [`Debugger`][debugger-object] instance, then
71 `<i>dbg</i>.memory` is a `Debugger.Memory` instance, which inherits the
72 following accessor properties from its prototype:
73
74 ## `trackingAllocationSites`
75 A boolean value indicating whether this `Debugger.Memory` instance is
76 capturing the JavaScript execution stack when each Object is allocated. This
77 accessor property has both a getter and setter: assigning to it enables or
78 disables the allocation site tracking. Reading the accessor produces `true`
79 if the Debugger is capturing stacks for Object allocations, and `false`
80 otherwise. Allocation site tracking is initially disabled in a new Debugger.
81
82 Assignment is fallible: if the Debugger cannot track allocation sites, it
83 throws an `Error` instance.
84
85 You can retrieve the allocation site for a given object with the
86 [`Debugger.Object.prototype.allocationSite`][allocation-site] accessor
87 property.
88
89 ## `allocationSamplingProbability`
90 A number between 0 and 1 that indicates the probability with which each new
91 allocation should be entered into the allocations log. 0 is equivalent to
92 "never", 1 is "always", and .05 would be "one out of twenty".
93
94 The default is 1, or logging every allocation.
95
96 Note that in the presence of multiple <code>Debugger</code> instances
97 observing the same allocations within a global's scope, the maximum
98 <code>allocationSamplingProbability</code> of all the
99 <code>Debugger</code>s is used.
100
101 ## `maxAllocationsLogLength`
102 The maximum number of allocation sites to accumulate in the allocations log
103 at a time. This accessor can be both fetched and stored to. Its default
104 value is `5000`.
105
106 ## `allocationsLogOverflowed`
107 Returns `true` if there have been more than
108 [`maxAllocationsLogLength`][#max-alloc-log] allocations since the last time
109 [`drainAllocationsLog`][#drain-alloc-log] was called and some data has been
110 lost. Returns `false` otherwise.
111
112 Debugger.Memory Handler Functions
113 ---------------------------------
114
115 Similar to [`Debugger`'s handler functions][debugger], `Debugger.Memory`
116 inherits accessor properties that store handler functions for SpiderMonkey to
117 call when given events occur in debuggee code.
118
119 Unlike `Debugger`'s hooks, `Debugger.Memory`'s handlers' return values are not
120 significant, and are ignored. The handler functions receive the
121 `Debugger.Memory`'s owning `Debugger` instance as their `this` value. The owning
122 `Debugger`'s `uncaughtExceptionHandler` is still fired for errors thrown in
123 `Debugger.Memory` hooks.
124
125 On a new `Debugger.Memory` instance, each of these properties is initially
126 `undefined`. Any value assigned to a debugging handler must be either a function
127 or `undefined`; otherwise a `TypeError` is thrown.
128
129 Handler functions run in the same thread in which the event occurred.
130 They run in the compartment to which they belong, not in a debuggee
131 compartment.
132
133 ## `onGarbageCollection(statistics)`
134 A garbage collection cycle spanning one or more debuggees has just been
135 completed.
136
137 The *statistics* parameter is an object containing information about the GC
138 cycle. It has the following properties:
139
140 ## `collections`
141 The `collections` property's value is an array. Because SpiderMonkey's
142 collector is incremental, a full collection cycle may consist of
143 multiple discrete collection slices with the JS mutator running
144 interleaved. For each collection slice that occurred, there is an entry
145 in the `collections` array with the following form:
146
147 ```
148 {
149 "startTimestamp": timestamp,
150 "endTimestamp": timestamp,
151 }
152 ```
153
154 Here the `timestamp` values are [timestamps][timestamps] of the GC slice's start
155 and end events.
156
157 ## `reason`
158 A very short string describing the reason why the collection was
159 triggered. Known values include the following:
160
161 * `"API"`
162 * `"EAGER_ALLOC_TRIGGER"`
163 * `"DESTROY_RUNTIME"`
164 * `"LAST_DITCH"`
165 * `"TOO_MUCH_MALLOC"`
166 * `"ALLOC_TRIGGER"`
167 * `"DEBUG_GC"`
168 * `"COMPARTMENT_REVIVED"`
169 * `"RESET"`
170 * `"OUT_OF_NURSERY"`
171 * `"EVICT_NURSERY"`
172 * `"FULL_STORE_BUFFER"`
173 * `"SHARED_MEMORY_LIMIT"`
174 * `"PERIODIC_FULL_GC"`
175 * `"INCREMENTAL_TOO_SLOW"`
176 * `"DOM_WINDOW_UTILS"`
177 * `"COMPONENT_UTILS"`
178 * `"MEM_PRESSURE"`
179 * `"CC_FINISHED"`
180 * `"CC_FORCED"`
181 * `"LOAD_END"`
182 * `"PAGE_HIDE"`
183 * `"NSJSCONTEXT_DESTROY"`
184 * `"SET_NEW_DOCUMENT"`
185 * `"SET_DOC_SHELL"`
186 * `"DOM_UTILS"`
187 * `"DOM_IPC"`
188 * `"DOM_WORKER"`
189 * `"INTER_SLICE_GC"`
190 * `"REFRESH_FRAME"`
191 * `"FULL_GC_TIMER"`
192 * `"SHUTDOWN_CC"`
193 * `"USER_INACTIVE"`
194
195 ## `nonincrementalReason`
196 If SpiderMonkey's collector determined it could not incrementally
197 collect garbage, and had to do a full GC all at once, this is a short
198 string describing the reason it determined the full GC was necessary.
199 Otherwise, `null` is returned. Known values include the following:
200
201 * `"GC mode"`
202 * `"malloc bytes trigger"`
203 * `"allocation trigger"`
204 * `"requested"`
205
206 ## `gcCycleNumber`
207 The GC cycle's "number". Does not correspond to the number
208 of GC cycles that have run, but is guaranteed to be monotonically
209 increasing.
210
211 Function Properties of the `Debugger.Memory.prototype` Object
212 -------------------------------------------------------------
213
214 ## `drainAllocationsLog()`
215 When `trackingAllocationSites` is `true`, this method returns an array of
216 recent `Object` allocations within the set of debuggees. *Recent* is
217 defined as the `maxAllocationsLogLength` most recent `Object` allocations
218 since the last call to `drainAllocationsLog`. Therefore, calling this
219 method effectively clears the log.
220
221 Objects in the array are of the form:
222
223 ```
224 {
225 "timestamp": timestamp,
226 "frame": allocationSite,
227 "class": className,
228 "size": byteSize,
229 "inNursery": inNursery,
230 }
231 ```
232
233 Where
234
235 * `timestamp` is the [timestamp][timestamps] of the allocation event.
236
237 * `allocationSite` is an allocation site (as a
238 [captured stack][saved-frame]). Note that this property can be null if the
239 object was allocated with no JavaScript frames on the stack.
240
241 * `className` is the string name of the allocated object's internal
242 `[[Class]]` property, for example "Array", "Date", "RegExp", or (most
243 commonly) "Object".
244
245 * `byteSize` is the size of the object in bytes.
246
247 * `inNursery` is true if the allocation happened inside the nursery. False
248 if the allocation skipped the nursery and started in the tenured heap.
249
250 When `trackingAllocationSites` is `false`, `drainAllocationsLog()` throws an
251 `Error`.
252
253 ## `takeCensus(options)`
254 Carry out a census of the debuggee compartments' contents. A *census* is a
255 complete traversal of the graph of all reachable memory items belonging to a
256 particular `Debugger`'s debuggees. The census produces a count of those
257 items, broken down by various criteria.
258
259 The <i>options</i> argument is an object whose properties specify how the
260 census should be carried out.
261
262 If <i>options</i> has a `breakdown` property, that determines how the census
263 categorizes the items it finds, and what data it collects about them. For
264 example, if `dbg` is a `Debugger` instance, the following performs a simple
265 count of debuggee items:
266
267 dbg.memory.takeCensus({ breakdown: { by: 'count' } })
268
269 That might produce a result like:
270
271 { "count": 1616, "bytes": 93240 }
272
273 Here is a breakdown that groups JavaScript objects by their class name,
274 non-string, non-script items by their C++ type name, and DOM nodes with
275 their node name:
276
277 {
278 by: "coarseType",
279 objects: { by: "objectClass" },
280 other: { by: "internalType" },
281 domNode: { by: "descriptiveType" }
282 }
283
284 which produces a result like this:
285
286 {
287 "objects": {
288 "Function": { "count": 404, "bytes": 37328 },
289 "Object": { "count": 11, "bytes": 1264 },
290 "Debugger": { "count": 1, "bytes": 416 },
291 "ScriptSource": { "count": 1, "bytes": 64 },
292 // ... omitted for brevity...
293 },
294 "scripts": { "count": 1, "bytes": 0 },
295 "strings": { "count": 701, "bytes": 49080 },
296 "other": {
297 "js::Shape": { "count": 450, "bytes": 0 },
298 "js::BaseShape": { "count": 21, "bytes": 0 },
299 "js::ObjectGroup": { "count": 17, "bytes": 0 }
300 },
301 "domNode": {
302 "#text": { "count": 1, "bytes": 12 }
303 }
304 }
305
306 In general, a `breakdown` value has one of the following forms:
307
308 * <code>{ by: "count", count:<i>count</i>, bytes:<i>bytes</i> }</code>
309
310 The trivial categorization: none whatsoever. Simply tally up the items
311 visited. If <i>count</i> is true, count the number of items visited; if
312 <i>bytes</i> is true, total the number of bytes the items use directly.
313 Both <i>count</i> and <i>bytes</i> are optional; if omitted, they
314 default to `true`. In the result of the census, this breakdown produces
315 a value of the form:
316
317 { "count": n, "bytes": b }
318
319 where the `count` and `bytes` properties are present as directed by the
320 <i>count</i> and <i>bytes</i> properties on the breakdown.
321
322 Note that the census can produce byte sizes only for the most common
323 types. When the census cannot find the byte size for a given type, it
324 returns zero.
325
326 * <code>{ by: "bucket" }</code>
327
328 Do not do any filtering or categorizing. Instead, accumulate a bucket of
329 each node's ID for every node that matches. The resulting report is an
330 array of the IDs.
331
332 For example, to find the ID of all nodes whose internal object
333 `[[class]]` property is named "RegExp", you could use the following code:
334
335 const report = dbg.memory.takeCensus({
336 breakdown: {
337 by: "objectClass",
338 then: { by: "bucket" }
339 }
340 });
341 doStuffWithRegExpIDs(report.RegExp);
342
343 * <code>{ by: "allocationStack", then:<i>breakdown</i>, noStack:<i>noStackBreakdown</i> }</code>
344
345 Group items by the full JavaScript stack trace at which they were
346 allocated.
347
348 Further categorize all the items allocated at each distinct stack using
349 <i>breakdown</i>.
350
351 In the result of the census, this breakdown produces a JavaScript `Map`
352 value whose keys are `SavedFrame` values, and whose values are whatever
353 sort of result <i>breakdown</i> produces. Objects allocated on an empty
354 JavaScript stack appear under the key `null`.
355
356 SpiderMonkey only tracks allocation sites for items if requested via the
357 [`trackingAllocationSites`][tracking-allocs] flag; even then, it does
358 not record allocation sites for every kind of item that appears in the
359 heap. Items that lack allocation site information are counted using
360 <i>noStackBreakdown</i>. These appear in the result `Map` under the key
361 string `"noStack"`.
362
363 * <code>{ by: "objectClass", then:<i>breakdown</i>, other:<i>otherBreakdown</i> }</code>
364
365 Group JavaScript objects by their ECMAScript `[[Class]]` internal property values.
366
367 Further categorize JavaScript objects in each class using
368 <i>breakdown</i>. Further categorize items that are not JavaScript
369 objects using <i>otherBreakdown</i>.
370
371 In the result of the census, this breakdown produces a JavaScript object
372 with no prototype whose own property names are strings naming classes,
373 and whose values are whatever sort of result <i>breakdown</i> produces.
374 The results for non-object items appear as the value of the property
375 named `"other"`.
376
377 * <code>{ by: "coarseType", objects:<i>objects</i>, scripts:<i>scripts</i>, strings:<i>strings</i>, domNode:<i>domNode</i>, other:<i>other</i> }</code>
378
379 Group items by their coarse type.
380
381 Use the breakdown value <i>objects</i> for items that are JavaScript
382 objects.
383
384 Use the breakdown value <i>scripts</i> for items that are
385 representations of JavaScript code. This includes bytecode, compiled
386 machine code, and saved source code.
387
388 Use the breakdown value <i>strings</i> for JavaScript strings.
389
390 Use the breakdown value <i>domNode</i> for DOM nodes.
391
392 Use the breakdown value <i>other</i> for items that don't fit into any of
393 the above categories.
394
395 In the result of the census, this breakdown produces a JavaScript object
396 of the form:
397
398 ```
399 {
400 "objects": result,
401 "scripts": result,
402 "strings": result,
403 "domNode:" result,
404 "other": result,
405 }
406 ```
407
408 where each <i>result</i> is a value of whatever sort the corresponding
409 breakdown value produces. All breakdown values are optional, and default
410 to `{ type: "count" }`.
411
412 * `{ by: "filename", then:breakdown, noFilename:noFilenameBreakdown }`
413
414 For scripts only, group by the filename of the script.
415
416 Further categorize all of the scripts from each distinct filename
417 using breakdown.
418
419 Scripts that lack a filename are counted using noFilenameBreakdown.
420 These appear in the result `Map` under the key string `"noFilename"`.
421
422 * `{ by: "internalType", then: breakdown }`
423
424 Group items by the names given their types internally by SpiderMonkey.
425 These names are not meaningful to web developers, but this type of
426 breakdown does serve as a catch-all that can be useful to Firefox tool
427 developers.
428
429 For example, a census of a pristine debuggee global broken down by
430 internal type name typically looks like this:
431
432 {
433 "JSString": { "count": 701, "bytes": 49080 },
434 "js::Shape": { "count": 450, "bytes": 0 },
435 "JSObject": { "count": 426, "bytes": 44160 },
436 "js::BaseShape": { "count": 21, "bytes": 0 },
437 "js::ObjectGroup": { "count": 17, "bytes": 0 },
438 "JSScript": { "count": 1, "bytes": 0 }
439 }
440
441 In the result of the census, this breakdown produces a JavaScript object
442 with no prototype whose own property names are strings naming types,
443 and whose values are whatever sort of result <i>breakdown</i> produces.
444
445 * <code>[ <i>breakdown</i>, ... ]</code>
446
447 Group each item using all the given breakdown values. In the result of
448 the census, this breakdown produces an array of values of the sort
449 produced by each listed breakdown.
450
451 To simplify breakdown values, all `then` and `other` properties are optional.
452 If omitted, they are treated as if they were `{ type: "count" }`.
453
454 Breakdown groupings cannot be nested within themselves. This would not be
455 useful, and forbidding this prevents infinite recursion.
456
457 If the `options` argument has no `breakdown` property, `takeCensus` defaults
458 to the following:
459
460 ```js
461 {
462 by: "coarseType",
463 objects: { by: "objectClass" },
464 domNode: { by: "descriptiveType" },
465 other: { by: "internalType" }
466 }
467 ```
468
469 which produces results of the form:
470
471 ```
472 {
473 objects: { class: count, ... },
474 scripts: count,
475 strings: count,
476 domNode: { node name:count, ... },
477 other: { type name:count, ... }
478 }
479 ```
480
481 where each `count` has the form:
482
483 ```js
484 { "count": count, bytes: bytes }
485 ```
486
487 Because performing a census requires traversing the entire graph of objects
488 in debuggee compartments, it is an expensive operation. On developer
489 hardware in 2014, traversing a memory graph containing roughly 130,000 nodes
490 and 410,000 edges took roughly 100ms. The traversal itself temporarily
491 allocates one hash table entry per node (roughly two address-sized words) in
492 addition to the per-category counts, whose size depends on the number of
493 categories.
494
495
496 Memory Use Analysis Exposes Implementation Details
497 --------------------------------------------------
498
499 Memory analysis may yield surprising results, because browser implementation
500 details that are transparent to content JavaScript often have visible effects on
501 memory consumption. Web developers need to know their pages' actual memory
502 consumption on real browsers, so it is correct for the tool to expose these
503 behaviors, as long as it is done in a way that helps developers make decisions
504 about their own code.
505
506 This section covers some areas where Firefox's actual behavior deviates from
507 what one might expect from the specified behavior of the web platform.
508
509
510 ## Objects
511
512 SpiderMonkey objects usually use less memory than the naïve "table of properties
513 with attributes" model would suggest. For example, it is typical for many
514 objects to have identical sets of properties, with only the properties' values
515 varying from one object to the next. To take advantage of this regularity,
516 SpiderMonkey objects with identical sets of properties may share their property
517 metadata; only property values are stored directly in the object.
518
519 Array objects may also be optimized, if the set of live indices is dense.
520
521
522 ## Strings
523
524 SpiderMonkey has three representations of strings:
525
526 - Normal: the string's text is counted in its size.
527
528 - Substring: the string is a substring of some other string, and points to that
529 string for its storage. This representation may result in a small string
530 retaining a very large string. However, the memory consumed by the string
531 itself is a small constant independent of its size, since it is simply a
532 reference to the larger string, a start position, and a length.
533
534 - Concatenations: When asked to concatenate two strings, SpiderMonkey may elect
535 to delay copying the strings' data, and represent the result simply as a
536 pointer to the two original strings. Again, such a string retains other
537 strings, but the memory consumed by the string itself is a small constant
538 independent of its size, since it is simply a pair of pointers.
539
540 SpiderMonkey converts strings from the more complex representations to the
541 simpler ones when it pleases. Such conversions usually increase memory
542 consumption.
543
544 SpiderMonkey shares some strings amongst all web pages and browser JS. These
545 shared strings, called *atoms*, are not included in censuses' string counts.
546
547
548 ## Scripts
549
550 SpiderMonkey has a complex, hybrid representation of JavaScript code. There
551 are four representations kept in memory:
552
553 - _Source code_. SpiderMonkey retains a copy of most JavaScript source code.
554
555 - _Compressed source code_. SpiderMonkey compresses JavaScript source code,
556 and de-compresses it on demand. Heuristics determine how long to retain the
557 uncompressed code.
558
559 - _Bytecode_. This is SpiderMonkey's parsed representation of JavaScript.
560 Bytecode can be interpreted directly, or used as input to a just-in-time
561 compiler. Source is parsed into bytecode on demand; functions that are never
562 called are never parsed.
563
564 - _Machine code_. SpiderMonkey includes several just-in-time compilers, each of
565 which translates JavaScript source or bytecode to machine code. Heuristics
566 determine which code to compile, and which compiler to use. Machine code may
567 be dropped in response to memory pressure, and regenerated as needed.
568
569 Furthermore, SpiderMonkey's just-in-time compilers generate inline caches for
570 type specialization. This information is dropped periodically to reduce memory
571 usage.
572
573 In a census, all the various forms of JavaScript code are placed in the
574 `"scripts"` category.
575
576
577 [debugger]: Debugger-API.md
578 [debugger-object]: Debugger.md
579 [tracking-allocs]: #trackingallocationsites
580 [bernoulli-trial]: https://en.wikipedia.org/wiki/Bernoulli_trial
581 [alloc-sampling-probability]: #allocsamplingprobability
582 [object]: Debugger.Object.md
583 [allocation-site]: Debugger.Object.md#allocationsite
584 [saved-frame]: ../SavedFrame/index
585 [drain-alloc-log]: #drainAllocationsLog
586 [max-alloc-log]: #maxAllocationsLogLength
587 [take-census]: #takecensus-options
588 [timestamps]: ./Conventions.md#timestamps