summaryrefslogtreecommitdiffstats
path: root/ipc/glue/test/browser/head.js
blob: 8acff88273b98e8564e26a5d487fa6009b1ad9f2 (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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const utilityProcessTest = () => {
  return Cc["@mozilla.org/utility-process-test;1"].createInstance(
    Ci.nsIUtilityProcessTest
  );
};

const kGenericUtilitySandbox = 0;
const kGenericUtilityActor = "unknown";

// Start a generic utility process with the given array of utility actor names
// registered.
async function startUtilityProcess(actors = []) {
  info("Start a UtilityProcess");
  return utilityProcessTest().startProcess(actors);
}

// Returns an array of process infos for utility processes of the given type
// or all utility processes if actor is not defined.
async function getUtilityProcesses(actor = undefined, options = {}) {
  let procInfos = (await ChromeUtils.requestProcInfo()).children.filter(p => {
    return (
      p.type === "utility" &&
      (actor == undefined ||
        p.utilityActors.find(a => a.actorName.startsWith(actor)))
    );
  });

  if (!options?.quiet) {
    info(`Utility process infos = ${JSON.stringify(procInfos)}`);
  }
  return procInfos;
}

async function tryGetUtilityPid(actor, options = {}) {
  let process = await getUtilityProcesses(actor, options);
  if (!options?.quiet) {
    ok(process.length <= 1, `at most one ${actor} process exists`);
  }
  return process[0]?.pid;
}

async function checkUtilityExists(actor) {
  info(`Looking for a running ${actor} utility process`);
  const utilityPid = await tryGetUtilityPid(actor);
  ok(utilityPid > 0, `Found ${actor} utility process ${utilityPid}`);
  return utilityPid;
}

// "Cleanly stop" a utility process.  This will never leave a crash dump file.
// preferKill will "kill" the process (e.g. SIGABRT) instead of using the
// UtilityProcessManager.
// To "crash" -- i.e. shutdown and generate a crash dump -- use
// crashSomeUtility().
async function cleanUtilityProcessShutdown(actor, preferKill = false) {
  info(`${preferKill ? "Kill" : "Clean shutdown"} Utility Process ${actor}`);

  const utilityPid = await tryGetUtilityPid(actor);
  ok(utilityPid !== undefined, `Must have PID for ${actor} utility process`);

  const utilityProcessGone = TestUtils.topicObserved(
    "ipc:utility-shutdown",
    (subject, data) => parseInt(data, 10) === utilityPid
  );

  if (preferKill) {
    SimpleTest.expectChildProcessCrash();
    info(`Kill Utility Process ${utilityPid}`);
    const ProcessTools = Cc["@mozilla.org/processtools-service;1"].getService(
      Ci.nsIProcessToolsService
    );
    ProcessTools.kill(utilityPid);
  } else {
    info(`Stopping Utility Process ${utilityPid}`);
    await utilityProcessTest().stopProcess(actor);
  }

  let [subject, data] = await utilityProcessGone;
  ok(
    subject instanceof Ci.nsIPropertyBag2,
    "Subject needs to be a nsIPropertyBag2 to clean up properly"
  );
  is(
    parseInt(data, 10),
    utilityPid,
    `Should match the crashed PID ${utilityPid} with ${data}`
  );

  // Make sure the process is dead, otherwise there is a risk of race for
  // writing leak logs
  utilityProcessTest().noteIntentionalCrash(utilityPid);

  ok(!subject.hasKey("dumpID"), "There should be no dumpID");
}

async function killUtilityProcesses() {
  let utilityProcesses = await getUtilityProcesses();
  for (const utilityProcess of utilityProcesses) {
    for (const actor of utilityProcess.utilityActors) {
      info(`Stopping ${actor.actorName} utility process`);
      await cleanUtilityProcessShutdown(actor.actorName, /* preferKill */ true);
    }
  }
}

function audioTestData() {
  return [
    {
      src: "small-shot.ogg",
      expectations: {
        Android: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        Linux: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        WINNT: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        Darwin: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
      },
    },
    {
      src: "small-shot.mp3",
      expectations: {
        Android: { process: "Utility Generic", decoder: "ffvpx audio decoder" },
        Linux: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        WINNT: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        Darwin: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
      },
    },
    {
      src: "small-shot.m4a",
      expectations: {
        // Add Android after Bug 1771196
        Linux: {
          process: "Utility Generic",
          decoder: "ffmpeg audio decoder",
        },
        WINNT: {
          process: "Utility WMF",
          decoder: "wmf audio decoder",
        },
        Darwin: {
          process: "Utility AppleMedia",
          decoder: "apple coremedia decoder",
        },
      },
    },
    {
      src: "small-shot.flac",
      expectations: {
        Android: { process: "Utility Generic", decoder: "ffvpx audio decoder" },
        Linux: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        WINNT: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
        Darwin: {
          process: "Utility Generic",
          decoder: "ffvpx audio decoder",
        },
      },
    },
  ];
}

function audioTestDataEME() {
  return [
    {
      src: {
        audioFile:
          "https://example.com/browser/ipc/glue/test/browser/short-aac-encrypted-audio.mp4",
        sourceBuffer: "audio/mp4",
      },
      expectations: {
        Linux: {
          process: "Utility Generic",
          decoder: "ffmpeg audio decoder",
        },
        WINNT: {
          process: "Utility WMF",
          decoder: "wmf audio decoder",
        },
        Darwin: {
          process: "Utility AppleMedia",
          decoder: "apple coremedia decoder",
        },
      },
    },
  ];
}

async function addMediaTab(src) {
  const tab = BrowserTestUtils.addTab(gBrowser, "about:blank", {
    forceNewProcess: true,
  });
  const browser = gBrowser.getBrowserForTab(tab);
  await BrowserTestUtils.browserLoaded(browser);
  await SpecialPowers.spawn(browser, [src], createAudioElement);
  return tab;
}

async function addMediaTabWithEME(sourceBuffer, audioFile) {
  const tab = BrowserTestUtils.addTab(
    gBrowser,
    "https://example.com/browser/",
    {
      forceNewProcess: true,
    }
  );
  const browser = gBrowser.getBrowserForTab(tab);
  await BrowserTestUtils.browserLoaded(browser);
  await SpecialPowers.spawn(
    browser,
    [sourceBuffer, audioFile],
    createAudioElementEME
  );
  return tab;
}

async function play(
  tab,
  expectUtility,
  expectDecoder,
  expectContent = false,
  expectJava = false,
  expectError = false,
  withEME = false
) {
  let browser = tab.linkedBrowser;
  return SpecialPowers.spawn(
    browser,
    [
      expectUtility,
      expectDecoder,
      expectContent,
      expectJava,
      expectError,
      withEME,
    ],
    checkAudioDecoder
  );
}

async function stop(tab) {
  let browser = tab.linkedBrowser;
  await SpecialPowers.spawn(browser, [], async function () {
    let audio = content.document.querySelector("audio");
    audio.pause();
  });
}

async function createAudioElement(src) {
  const doc = typeof content !== "undefined" ? content.document : document;
  const ROOT = "https://example.com/browser/ipc/glue/test/browser";
  let audio = doc.createElement("audio");
  audio.setAttribute("controls", "true");
  audio.setAttribute("loop", true);
  audio.src = `${ROOT}/${src}`;
  doc.body.appendChild(audio);
}

async function createAudioElementEME(sourceBuffer, audioFile) {
  // Helper to clone data into content so the EME helper can use the data.
  function cloneIntoContent(data) {
    return Cu.cloneInto(data, content.wrappedJSObject);
  }

  // Load the EME helper into content.
  Services.scriptloader.loadSubScript(
    "chrome://mochitests/content/browser/ipc/glue/test/browser/eme_standalone.js",
    content
  );

  let audio = content.document.createElement("audio");
  audio.setAttribute("controls", "true");
  audio.setAttribute("loop", true);
  audio.setAttribute("_sourceBufferType", sourceBuffer);
  audio.setAttribute("_audioUrl", audioFile);
  content.document.body.appendChild(audio);

  let emeHelper = new content.wrappedJSObject.EmeHelper();
  emeHelper.SetKeySystem(
    content.wrappedJSObject.EmeHelper.GetClearkeyKeySystemString()
  );
  emeHelper.SetInitDataTypes(cloneIntoContent(["keyids", "cenc"]));
  emeHelper.SetAudioCapabilities(
    cloneIntoContent([{ contentType: 'audio/mp4; codecs="mp4a.40.2"' }])
  );
  emeHelper.AddKeyIdAndKey(
    "2cdb0ed6119853e7850671c3e9906c3c",
    "808B9ADAC384DE1E4F56140F4AD76194"
  );
  emeHelper.onerror = error => {
    is(false, `Got unexpected error from EME helper: ${error}`);
  };
  await emeHelper.ConfigureEme(audio);
  // Done setting up EME.
}

async function checkAudioDecoder(
  expectedProcess,
  expectedDecoder,
  expectContent = false,
  expectJava = false,
  expectError = false,
  withEME = false
) {
  const doc = typeof content !== "undefined" ? content.document : document;
  let audio = doc.querySelector("audio");
  const checkPromise = new Promise((resolve, reject) => {
    const timeUpdateHandler = async ev => {
      const debugInfo = await SpecialPowers.wrap(audio).mozRequestDebugInfo();
      const audioDecoderName = debugInfo.decoder.reader.audioDecoderName;

      const isExpectedDecoder =
        audioDecoderName.indexOf(`${expectedDecoder}`) == 0;
      ok(
        isExpectedDecoder,
        `playback ${audio.src} was from decoder '${audioDecoderName}', expected '${expectedDecoder}'`
      );

      const isExpectedProcess =
        audioDecoderName.indexOf(`(${expectedProcess} remote)`) > 0;
      const isJavaRemote = audioDecoderName.indexOf("(remote)") > 0;
      const isOk =
        (isExpectedProcess && !isJavaRemote && !expectContent && !expectJava) || // Running in Utility
        (expectJava && !isExpectedProcess && isJavaRemote) || // Running in Java remote
        (expectContent && !isExpectedProcess && !isJavaRemote); // Running in Content

      ok(
        isOk,
        `playback ${audio.src} was from process '${audioDecoderName}', expected '${expectedProcess}'`
      );

      if (isOk) {
        resolve();
      } else {
        reject();
      }
    };

    const startPlaybackHandler = async ev => {
      ok(
        await audio.play().then(
          _ => true,
          _ => false
        ),
        "audio started playing"
      );

      audio.addEventListener("timeupdate", timeUpdateHandler, { once: true });
    };

    audio.addEventListener("error", async err => {
      info(
        `Received HTML media error: ${audio.error.code}: ${audio.error.message}`
      );
      if (expectError) {
        const w = typeof content !== "undefined" ? content.window : window;
        ok(
          audio.error.code === w.MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ||
            w.MediaError.MEDIA_ERR_DECODE,
          "Media supported but decoding failed"
        );
        resolve();
      } else {
        info(`Unexpected error`);
        reject();
      }
    });

    audio.addEventListener("canplaythrough", startPlaybackHandler, {
      once: true,
    });
  });

  if (!withEME) {
    // We need to make sure the decoder is ready before play()ing otherwise we
    // could get into bad situations
    audio.load();
  } else {
    // For EME we need to create and load content ourselves. We do this here
    // because if we do it in createAudioElementEME() above then we end up
    // with events fired before we get a chance to listen to them here
    async function once(target, name) {
      return new Promise(r => target.addEventListener(name, r, { once: true }));
    }

    // Setup MSE.
    const ms = new content.wrappedJSObject.MediaSource();
    audio.src = content.wrappedJSObject.URL.createObjectURL(ms);
    await once(ms, "sourceopen");
    const sb = ms.addSourceBuffer(audio.getAttribute("_sourceBufferType"));
    let fetchResponse = await content.fetch(audio.getAttribute("_audioUrl"));
    let dataBuffer = await fetchResponse.arrayBuffer();
    sb.appendBuffer(dataBuffer);
    await once(sb, "updateend");
    ms.endOfStream();
    await once(ms, "sourceended");
  }

  return checkPromise;
}

async function runMochitestUtilityAudio(
  src,
  {
    expectUtility,
    expectDecoder,
    expectContent = false,
    expectJava = false,
    expectError = false,
  } = {}
) {
  info(`Add media: ${src}`);
  await createAudioElement(src);
  let audio = document.querySelector("audio");
  ok(audio, "Found an audio element created");

  info(`Play media: ${src}`);
  await checkAudioDecoder(
    expectUtility,
    expectDecoder,
    expectContent,
    expectJava,
    expectError
  );

  info(`Pause media: ${src}`);
  await audio.pause();

  info(`Remove media: ${src}`);
  document.body.removeChild(audio);
}

async function crashSomeUtility(utilityPid, actorsCheck) {
  SimpleTest.expectChildProcessCrash();

  const crashMan = Services.crashmanager;
  const utilityProcessGone = TestUtils.topicObserved(
    "ipc:utility-shutdown",
    (subject, data) => {
      info(`ipc:utility-shutdown: data=${data} subject=${subject}`);
      return parseInt(data, 10) === utilityPid;
    }
  );

  info("prune any previous crashes");
  const future = new Date(Date.now() + 1000 * 60 * 60 * 24);
  await crashMan.pruneOldCrashes(future);

  info("crash Utility Process");
  const ProcessTools = Cc["@mozilla.org/processtools-service;1"].getService(
    Ci.nsIProcessToolsService
  );

  info(`Crash Utility Process ${utilityPid}`);
  ProcessTools.crash(utilityPid);

  info(`Waiting for utility process ${utilityPid} to go away.`);
  let [subject, data] = await utilityProcessGone;
  ok(
    parseInt(data, 10) === utilityPid,
    `Should match the crashed PID ${utilityPid} with ${data}`
  );
  ok(
    subject instanceof Ci.nsIPropertyBag2,
    "Subject needs to be a nsIPropertyBag2 to clean up properly"
  );

  // Make sure the process is dead, otherwise there is a risk of race for
  // writing leak logs
  utilityProcessTest().noteIntentionalCrash(utilityPid);

  const dumpID = subject.getPropertyAsAString("dumpID");
  ok(dumpID, "There should be a dumpID");

  await crashMan.ensureCrashIsPresent(dumpID);
  await crashMan.getCrashes().then(crashes => {
    is(crashes.length, 1, "There should be only one record");
    const crash = crashes[0];
    ok(
      crash.isOfType(
        crashMan.processTypes[Ci.nsIXULRuntime.PROCESS_TYPE_UTILITY],
        crashMan.CRASH_TYPE_CRASH
      ),
      "Record should be a utility process crash"
    );
    ok(crash.id === dumpID, "Record should have an ID");
    ok(
      actorsCheck(crash.metadata.UtilityActorsName),
      `Record should have the correct actors name for: ${crash.metadata.UtilityActorsName}`
    );
  });

  let minidumpDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
  minidumpDirectory.append("minidumps");

  let dumpfile = minidumpDirectory.clone();
  dumpfile.append(dumpID + ".dmp");
  if (dumpfile.exists()) {
    info(`Removal of ${dumpfile.path}`);
    dumpfile.remove(false);
  }

  let extrafile = minidumpDirectory.clone();
  extrafile.append(dumpID + ".extra");
  info(`Removal of ${extrafile.path}`);
  if (extrafile.exists()) {
    extrafile.remove(false);
  }
}

// Crash a utility process and generate a crash dump.  To close a utility
// process (forcefully or not) without a generating a crash, use
// cleanUtilityProcessShutdown.
async function crashSomeUtilityActor(
  actor,
  actorsCheck = () => {
    return true;
  }
) {
  // Get PID for utility type
  const procInfos = await getUtilityProcesses(actor);
  ok(
    procInfos.length == 1,
    `exactly one ${actor} utility process should be found`
  );
  const utilityPid = procInfos[0].pid;
  return crashSomeUtility(utilityPid, actorsCheck);
}

function isNightlyOnly() {
  const { AppConstants } = ChromeUtils.importESModule(
    "resource://gre/modules/AppConstants.sys.mjs"
  );
  return AppConstants.NIGHTLY_BUILD;
}