summaryrefslogtreecommitdiffstats
path: root/dom/heapsnapshot/HeapAnalysesWorker.js
blob: d07d67f80eed2107ce2d6017b18051da97df89f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* global ThreadSafeChromeUtils*/

// This is a worker which reads offline heap snapshots into memory and performs
// heavyweight analyses on them without blocking the main thread. A
// HeapAnalysesWorker is owned and communicated with by a HeapAnalysesClient
// instance. See HeapAnalysesClient.js.

"use strict";

importScripts("resource://gre/modules/workers/require.js");
importScripts("resource://devtools/shared/worker/helper.js");
const { censusReportToCensusTreeNode } = require("resource://devtools/shared/heapsnapshot/census-tree-node.js");
const DominatorTreeNode = require("resource://devtools/shared/heapsnapshot/DominatorTreeNode.js");
const CensusUtils = require("resource://devtools/shared/heapsnapshot/CensusUtils.js");

const DEFAULT_START_INDEX = 0;
const DEFAULT_MAX_COUNT = 50;

/**
 * The set of HeapSnapshot instances this worker has read into memory. Keyed by
 * snapshot file path.
 */
const snapshots = Object.create(null);

/**
 * The set of `DominatorTree`s that have been computed, mapped by their id (aka
 * the index into this array).
 *
 * @see /dom/webidl/DominatorTree.webidl
 */
const dominatorTrees = [];

/**
 * The i^th HeapSnapshot in this array is the snapshot used to generate the i^th
 * dominator tree in `dominatorTrees` above. This lets us map from a dominator
 * tree id to the snapshot it came from.
 */
const dominatorTreeSnapshots = [];

/**
 * @see HeapAnalysesClient.prototype.readHeapSnapshot
 */
workerHelper.createTask(self, "readHeapSnapshot", ({ snapshotFilePath }) => {
  snapshots[snapshotFilePath] =
    ThreadSafeChromeUtils.readHeapSnapshot(snapshotFilePath);
  return true;
});

/**
 * @see HeapAnalysesClient.prototype.deleteHeapSnapshot
 */
workerHelper.createTask(self, "deleteHeapSnapshot", ({ snapshotFilePath }) => {
  let snapshot = snapshots[snapshotFilePath];
  if (!snapshot) {
    throw new Error(`No known heap snapshot for '${snapshotFilePath}'`);
  }

  snapshots[snapshotFilePath] = undefined;

  let dominatorTreeId = dominatorTreeSnapshots.indexOf(snapshot);
  if (dominatorTreeId != -1) {
    dominatorTreeSnapshots[dominatorTreeId] = undefined;
    dominatorTrees[dominatorTreeId] = undefined;
  }
});

/**
 * @see HeapAnalysesClient.prototype.takeCensus
 */
workerHelper.createTask(self, "takeCensus", ({ snapshotFilePath, censusOptions, requestOptions }) => {
  if (!snapshots[snapshotFilePath]) {
    throw new Error(`No known heap snapshot for '${snapshotFilePath}'`);
  }

  let report = snapshots[snapshotFilePath].takeCensus(censusOptions);
  let parentMap;

  if (requestOptions.asTreeNode || requestOptions.asInvertedTreeNode) {
    const opts = { filter: requestOptions.filter || null };
    if (requestOptions.asInvertedTreeNode) {
      opts.invert = true;
    }
    report = censusReportToCensusTreeNode(censusOptions.breakdown, report, opts);
    parentMap = CensusUtils.createParentMap(report);
  }

  return { report, parentMap };
});

/**
 * @see HeapAnalysesClient.prototype.getCensusIndividuals
 */
workerHelper.createTask(self, "getCensusIndividuals", request => {
  const {
    dominatorTreeId,
    indices,
    censusBreakdown,
    labelBreakdown,
    maxRetainingPaths,
    maxIndividuals,
  } = request;

  const dominatorTree = dominatorTrees[dominatorTreeId];
  if (!dominatorTree) {
    throw new Error(
      `There does not exist a DominatorTree with the id ${dominatorTreeId}`);
  }

  const snapshot = dominatorTreeSnapshots[dominatorTreeId];
  const nodeIds = CensusUtils.getCensusIndividuals(indices, censusBreakdown, snapshot);

  const nodes = nodeIds
    .sort((a, b) => dominatorTree.getRetainedSize(b) - dominatorTree.getRetainedSize(a))
    .slice(0, maxIndividuals)
    .map(id => {
      const { label, shallowSize } =
        DominatorTreeNode.getLabelAndShallowSize(id, snapshot, labelBreakdown);
      const retainedSize = dominatorTree.getRetainedSize(id);
      const node = new DominatorTreeNode(id, label, shallowSize, retainedSize);
      node.moreChildrenAvailable = false;
      return node;
    });

  DominatorTreeNode.attachShortestPaths(snapshot,
                                        labelBreakdown,
                                        dominatorTree.root,
                                        nodes,
                                        maxRetainingPaths);

  return { nodes };
});

/**
 * @see HeapAnalysesClient.prototype.takeCensusDiff
 */
workerHelper.createTask(self, "takeCensusDiff", request => {
  const {
    firstSnapshotFilePath,
    secondSnapshotFilePath,
    censusOptions,
    requestOptions
  } = request;

  if (!snapshots[firstSnapshotFilePath]) {
    throw new Error(`No known heap snapshot for '${firstSnapshotFilePath}'`);
  }

  if (!snapshots[secondSnapshotFilePath]) {
    throw new Error(`No known heap snapshot for '${secondSnapshotFilePath}'`);
  }

  const first = snapshots[firstSnapshotFilePath].takeCensus(censusOptions);
  const second = snapshots[secondSnapshotFilePath].takeCensus(censusOptions);
  let delta = CensusUtils.diff(censusOptions.breakdown, first, second);
  let parentMap;

  if (requestOptions.asTreeNode || requestOptions.asInvertedTreeNode) {
    const opts = { filter: requestOptions.filter || null };
    if (requestOptions.asInvertedTreeNode) {
      opts.invert = true;
    }
    delta = censusReportToCensusTreeNode(censusOptions.breakdown, delta, opts);
    parentMap = CensusUtils.createParentMap(delta);
  }

  return { delta, parentMap };
});

/**
 * @see HeapAnalysesClient.prototype.getCreationTime
 */
workerHelper.createTask(self, "getCreationTime", snapshotFilePath => {
  if (!snapshots[snapshotFilePath]) {
    throw new Error(`No known heap snapshot for '${snapshotFilePath}'`);
  }
  return snapshots[snapshotFilePath].creationTime;
});

/**
 * @see HeapAnalysesClient.prototype.computeDominatorTree
 */
workerHelper.createTask(self, "computeDominatorTree", snapshotFilePath => {
  const snapshot = snapshots[snapshotFilePath];
  if (!snapshot) {
    throw new Error(`No known heap snapshot for '${snapshotFilePath}'`);
  }

  const id = dominatorTrees.length;
  dominatorTrees.push(snapshot.computeDominatorTree());
  dominatorTreeSnapshots.push(snapshot);
  return id;
});

/**
 * @see HeapAnalysesClient.prototype.getDominatorTree
 */
workerHelper.createTask(self, "getDominatorTree", request => {
  const {
    dominatorTreeId,
    breakdown,
    maxDepth,
    maxSiblings,
    maxRetainingPaths,
  } = request;

  if (!(0 <= dominatorTreeId && dominatorTreeId < dominatorTrees.length)) {
    throw new Error(
      `There does not exist a DominatorTree with the id ${dominatorTreeId}`);
  }

  const dominatorTree = dominatorTrees[dominatorTreeId];
  const snapshot = dominatorTreeSnapshots[dominatorTreeId];

  const tree = DominatorTreeNode.partialTraversal(dominatorTree,
                                                  snapshot,
                                                  breakdown,
                                                  maxDepth,
                                                  maxSiblings);

  const nodes = [];
  (function getNodes(node) {
    nodes.push(node);
    if (node.children) {
      for (let i = 0, length = node.children.length; i < length; i++) {
        getNodes(node.children[i]);
      }
    }
  }(tree));

  DominatorTreeNode.attachShortestPaths(snapshot,
                                        breakdown,
                                        dominatorTree.root,
                                        nodes,
                                        maxRetainingPaths);

  return tree;
});

/**
 * @see HeapAnalysesClient.prototype.getImmediatelyDominated
 */
workerHelper.createTask(self, "getImmediatelyDominated", request => {
  const {
    dominatorTreeId,
    nodeId,
    breakdown,
    startIndex,
    maxCount,
    maxRetainingPaths,
  } = request;

  if (!(0 <= dominatorTreeId && dominatorTreeId < dominatorTrees.length)) {
    throw new Error(
      `There does not exist a DominatorTree with the id ${dominatorTreeId}`);
  }

  const dominatorTree = dominatorTrees[dominatorTreeId];
  const snapshot = dominatorTreeSnapshots[dominatorTreeId];

  const childIds = dominatorTree.getImmediatelyDominated(nodeId);
  if (!childIds) {
    throw new Error(`${nodeId} is not a node id in the dominator tree`);
  }

  const start = startIndex || DEFAULT_START_INDEX;
  const count = maxCount || DEFAULT_MAX_COUNT;
  const end = start + count;

  const nodes = childIds
    .slice(start, end)
    .map(id => {
      const { label, shallowSize } =
        DominatorTreeNode.getLabelAndShallowSize(id, snapshot, breakdown);
      const retainedSize = dominatorTree.getRetainedSize(id);
      const node = new DominatorTreeNode(id, label, shallowSize, retainedSize);
      node.parentId = nodeId;
      // DominatorTree.getImmediatelyDominated will always return non-null here
      // because we got the id directly from the dominator tree.
      node.moreChildrenAvailable = dominatorTree.getImmediatelyDominated(id).length > 0;
      return node;
    });

  const path = [];
  let id = nodeId;
  do {
    path.push(id);
    id = dominatorTree.getImmediateDominator(id);
  } while (id !== null);
  path.reverse();

  const moreChildrenAvailable = childIds.length > end;

  DominatorTreeNode.attachShortestPaths(snapshot,
                                        breakdown,
                                        dominatorTree.root,
                                        nodes,
                                        maxRetainingPaths);

  return { nodes, moreChildrenAvailable, path };
});