api-crash-reporter-spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. import { expect } from 'chai';
  2. import * as childProcess from 'child_process';
  3. import * as http from 'http';
  4. import * as Busboy from 'busboy';
  5. import * as path from 'path';
  6. import { ifdescribe, ifit } from './spec-helpers';
  7. import { app, crashReporter } from 'electron';
  8. import { AddressInfo } from 'net';
  9. import { EventEmitter } from 'events';
  10. import * as fs from 'fs';
  11. import * as v8 from 'v8';
  12. import * as uuid from 'uuid';
  13. import * as rimraf from 'rimraf';
  14. const isWindowsOnArm = process.platform === 'win32' && process.arch === 'arm64';
  15. const isLinuxOnArm = process.platform === 'linux' && process.arch.includes('arm');
  16. const afterTest: ((() => void) | (() => Promise<void>))[] = [];
  17. async function cleanup () {
  18. for (const cleanup of afterTest) {
  19. const r = cleanup();
  20. if (r instanceof Promise) { await r; }
  21. }
  22. afterTest.length = 0;
  23. }
  24. type CrashInfo = {
  25. prod: string
  26. ver: string
  27. process_type: string // eslint-disable-line camelcase
  28. ptype: string
  29. platform: string
  30. _productName: string
  31. _version: string
  32. upload_file_minidump: Buffer // eslint-disable-line camelcase
  33. guid: string
  34. mainProcessSpecific: 'mps' | undefined
  35. rendererSpecific: 'rs' | undefined
  36. globalParam: 'globalValue' | undefined
  37. addedThenRemoved: 'to-be-removed' | undefined
  38. longParam: string | undefined
  39. 'electron.v8-fatal.location': string | undefined
  40. 'electron.v8-fatal.message': string | undefined
  41. }
  42. function checkCrash (expectedProcessType: string, fields: CrashInfo) {
  43. expect(String(fields.prod)).to.equal('Electron', 'prod');
  44. expect(String(fields.ver)).to.equal(process.versions.electron, 'ver');
  45. expect(String(fields.ptype)).to.equal(expectedProcessType, 'ptype');
  46. expect(String(fields.process_type)).to.equal(expectedProcessType, 'process_type');
  47. expect(String(fields.platform)).to.equal(process.platform, 'platform');
  48. expect(String(fields._productName)).to.equal('Zombies', '_productName');
  49. expect(String(fields._version)).to.equal(app.getVersion(), '_version');
  50. expect(fields.upload_file_minidump).to.be.an.instanceOf(Buffer);
  51. // TODO(nornagon): minidumps are sometimes (not always) turning up empty on
  52. // 32-bit Linux. Figure out why.
  53. if (!(process.platform === 'linux' && process.arch === 'ia32')) {
  54. expect(fields.upload_file_minidump.length).to.be.greaterThan(0);
  55. }
  56. }
  57. const startRemoteControlApp = async () => {
  58. const appPath = path.join(__dirname, 'fixtures', 'apps', 'remote-control');
  59. const appProcess = childProcess.spawn(process.execPath, [appPath]);
  60. appProcess.stderr.on('data', d => {
  61. process.stderr.write(d);
  62. });
  63. const port = await new Promise<number>(resolve => {
  64. appProcess.stdout.on('data', d => {
  65. const m = /Listening: (\d+)/.exec(d.toString());
  66. if (m && m[1] != null) {
  67. resolve(Number(m[1]));
  68. }
  69. });
  70. });
  71. function remoteEval (js: string): any {
  72. return new Promise((resolve, reject) => {
  73. const req = http.request({
  74. host: '127.0.0.1',
  75. port,
  76. method: 'POST'
  77. }, res => {
  78. const chunks = [] as Buffer[];
  79. res.on('data', chunk => { chunks.push(chunk); });
  80. res.on('end', () => {
  81. // NOTE: v8.deserialize has existed since node 8.0.0, but apparently
  82. // the typings we're using don't recognize it.
  83. const ret = (v8 as any).deserialize(Buffer.concat(chunks));
  84. if (Object.prototype.hasOwnProperty.call(ret, 'error')) {
  85. reject(new Error(`remote error: ${ret.error}\n\nTriggered at:`));
  86. } else {
  87. resolve(ret.result);
  88. }
  89. });
  90. });
  91. req.write(js);
  92. req.end();
  93. });
  94. }
  95. function remotely (script: Function, ...args: any[]): Promise<any> {
  96. return remoteEval(`(${script})(...${JSON.stringify(args)})`);
  97. }
  98. afterTest.push(() => { appProcess.kill('SIGINT'); });
  99. return { remoteEval, remotely };
  100. };
  101. const startServer = async () => {
  102. const crashes: CrashInfo[] = [];
  103. function getCrashes () { return crashes; }
  104. const emitter = new EventEmitter();
  105. function waitForCrash (): Promise<CrashInfo> {
  106. return new Promise(resolve => {
  107. emitter.once('crash', (crash) => {
  108. resolve(crash);
  109. });
  110. });
  111. }
  112. const server = http.createServer((req, res) => {
  113. const busboy = new Busboy({ headers: req.headers });
  114. const fields = {} as Record<string, any>;
  115. const files = {} as Record<string, Buffer>;
  116. busboy.on('file', (fieldname, file) => {
  117. const chunks = [] as Array<Buffer>;
  118. file.on('data', (chunk) => {
  119. chunks.push(chunk);
  120. });
  121. file.on('end', () => {
  122. files[fieldname] = Buffer.concat(chunks);
  123. });
  124. });
  125. busboy.on('field', (fieldname, val) => {
  126. fields[fieldname] = val;
  127. });
  128. busboy.on('finish', () => {
  129. // breakpad id must be 16 hex digits.
  130. const reportId = Math.random().toString(16).split('.')[1].padStart(16, '0');
  131. res.end(reportId, async () => {
  132. req.socket.destroy();
  133. emitter.emit('crash', { ...fields, ...files });
  134. });
  135. });
  136. req.pipe(busboy);
  137. });
  138. await new Promise(resolve => {
  139. server.listen(0, '127.0.0.1', () => { resolve(); });
  140. });
  141. const port = (server.address() as AddressInfo).port;
  142. afterTest.push(() => { server.close(); });
  143. return { getCrashes, port, waitForCrash };
  144. };
  145. function runApp (appPath: string, args: Array<string> = []) {
  146. const appProcess = childProcess.spawn(process.execPath, [appPath, ...args]);
  147. return new Promise(resolve => {
  148. appProcess.once('exit', resolve);
  149. });
  150. }
  151. function runCrashApp (crashType: string, port: number, extraArgs: Array<string> = []) {
  152. const appPath = path.join(__dirname, 'fixtures', 'apps', 'crash');
  153. return runApp(appPath, [
  154. `--crash-type=${crashType}`,
  155. `--crash-reporter-url=http://127.0.0.1:${port}`,
  156. ...extraArgs
  157. ]);
  158. }
  159. function waitForNewFileInDir (dir: string): Promise<string[]> {
  160. function readdirIfPresent (dir: string): string[] {
  161. try {
  162. return fs.readdirSync(dir);
  163. } catch (e) {
  164. return [];
  165. }
  166. }
  167. const initialFiles = readdirIfPresent(dir);
  168. return new Promise(resolve => {
  169. const ivl = setInterval(() => {
  170. const newCrashFiles = readdirIfPresent(dir).filter(f => !initialFiles.includes(f));
  171. if (newCrashFiles.length) {
  172. clearInterval(ivl);
  173. resolve(newCrashFiles);
  174. }
  175. }, 1000);
  176. });
  177. }
  178. // TODO(nornagon): Fix tests on linux/arm.
  179. ifdescribe(!isLinuxOnArm && !process.mas && !process.env.DISABLE_CRASH_REPORTER_TESTS)('crashReporter module', function () {
  180. afterEach(cleanup);
  181. describe('should send minidump', () => {
  182. it('when renderer crashes', async () => {
  183. const { port, waitForCrash } = await startServer();
  184. runCrashApp('renderer', port);
  185. const crash = await waitForCrash();
  186. checkCrash('renderer', crash);
  187. expect(crash.mainProcessSpecific).to.be.undefined();
  188. });
  189. it('when sandboxed renderer crashes', async () => {
  190. const { port, waitForCrash } = await startServer();
  191. runCrashApp('sandboxed-renderer', port);
  192. const crash = await waitForCrash();
  193. checkCrash('renderer', crash);
  194. expect(crash.mainProcessSpecific).to.be.undefined();
  195. });
  196. // TODO(nornagon): Minidump generation in main/node process on Linux/Arm is
  197. // broken (//components/crash prints "Failed to generate minidump"). Figure
  198. // out why.
  199. ifit(!isLinuxOnArm)('when main process crashes', async () => {
  200. const { port, waitForCrash } = await startServer();
  201. runCrashApp('main', port);
  202. const crash = await waitForCrash();
  203. checkCrash('browser', crash);
  204. expect(crash.mainProcessSpecific).to.equal('mps');
  205. });
  206. ifit(!isLinuxOnArm)('when a node process crashes', async () => {
  207. const { port, waitForCrash } = await startServer();
  208. runCrashApp('node', port);
  209. const crash = await waitForCrash();
  210. checkCrash('node', crash);
  211. expect(crash.mainProcessSpecific).to.be.undefined();
  212. expect(crash.rendererSpecific).to.be.undefined();
  213. });
  214. describe('with guid', () => {
  215. for (const processType of ['main', 'renderer', 'sandboxed-renderer']) {
  216. it(`when ${processType} crashes`, async () => {
  217. const { port, waitForCrash } = await startServer();
  218. runCrashApp(processType, port);
  219. const crash = await waitForCrash();
  220. expect(crash.guid).to.be.a('string');
  221. });
  222. }
  223. it('is a consistent id', async () => {
  224. let crash1Guid;
  225. let crash2Guid;
  226. {
  227. const { port, waitForCrash } = await startServer();
  228. runCrashApp('main', port);
  229. const crash = await waitForCrash();
  230. crash1Guid = crash.guid;
  231. }
  232. {
  233. const { port, waitForCrash } = await startServer();
  234. runCrashApp('main', port);
  235. const crash = await waitForCrash();
  236. crash2Guid = crash.guid;
  237. }
  238. expect(crash2Guid).to.equal(crash1Guid);
  239. });
  240. });
  241. describe('with extra parameters', () => {
  242. it('when renderer crashes', async () => {
  243. const { port, waitForCrash } = await startServer();
  244. runCrashApp('renderer', port, ['--set-extra-parameters-in-renderer']);
  245. const crash = await waitForCrash();
  246. checkCrash('renderer', crash);
  247. expect(crash.mainProcessSpecific).to.be.undefined();
  248. expect(crash.rendererSpecific).to.equal('rs');
  249. expect(crash.addedThenRemoved).to.be.undefined();
  250. });
  251. it('when sandboxed renderer crashes', async () => {
  252. const { port, waitForCrash } = await startServer();
  253. runCrashApp('sandboxed-renderer', port, ['--set-extra-parameters-in-renderer']);
  254. const crash = await waitForCrash();
  255. checkCrash('renderer', crash);
  256. expect(crash.mainProcessSpecific).to.be.undefined();
  257. expect(crash.rendererSpecific).to.equal('rs');
  258. expect(crash.addedThenRemoved).to.be.undefined();
  259. });
  260. it('contains v8 crash keys when a v8 crash occurs', async () => {
  261. const { remotely } = await startRemoteControlApp();
  262. const { port, waitForCrash } = await startServer();
  263. await remotely((port: number) => {
  264. require('electron').crashReporter.start({
  265. submitURL: `http://127.0.0.1:${port}`,
  266. ignoreSystemCrashHandler: true
  267. });
  268. }, [port]);
  269. remotely(() => {
  270. const { BrowserWindow } = require('electron');
  271. const bw = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  272. bw.loadURL('about:blank');
  273. bw.webContents.executeJavaScript('process.electronBinding(\'v8_util\').triggerFatalErrorForTesting()');
  274. });
  275. const crash = await waitForCrash();
  276. expect(crash.prod).to.equal('Electron');
  277. expect(crash._productName).to.equal('electron-test-remote-control');
  278. expect(crash.process_type).to.equal('renderer');
  279. expect(crash['electron.v8-fatal.location']).to.equal('v8::Context::New()');
  280. expect(crash['electron.v8-fatal.message']).to.equal('Circular extension dependency');
  281. });
  282. });
  283. });
  284. ifdescribe(!isLinuxOnArm)('extra parameter limits', () => {
  285. function stitchLongCrashParam (crash: any, paramKey: string) {
  286. if (crash[paramKey]) return crash[paramKey];
  287. let chunk = 1;
  288. let stitched = '';
  289. while (crash[`${paramKey}__${chunk}`]) {
  290. stitched += crash[`${paramKey}__${chunk}`];
  291. chunk++;
  292. }
  293. return stitched;
  294. }
  295. it('should truncate extra values longer than 5 * 4096 characters', async () => {
  296. const { port, waitForCrash } = await startServer();
  297. const { remotely } = await startRemoteControlApp();
  298. remotely((port: number) => {
  299. require('electron').crashReporter.start({
  300. submitURL: `http://127.0.0.1:${port}`,
  301. ignoreSystemCrashHandler: true,
  302. extra: { longParam: 'a'.repeat(100000) }
  303. });
  304. setTimeout(() => process.crash());
  305. }, port);
  306. const crash = await waitForCrash();
  307. expect(stitchLongCrashParam(crash, 'longParam')).to.have.lengthOf(160 * 127, 'crash should have truncated longParam');
  308. });
  309. it('should omit extra keys with names longer than the maximum', async () => {
  310. const kKeyLengthMax = 39;
  311. const { port, waitForCrash } = await startServer();
  312. const { remotely } = await startRemoteControlApp();
  313. remotely((port: number, kKeyLengthMax: number) => {
  314. require('electron').crashReporter.start({
  315. submitURL: `http://127.0.0.1:${port}`,
  316. ignoreSystemCrashHandler: true,
  317. extra: {
  318. ['a'.repeat(kKeyLengthMax + 10)]: 'value',
  319. ['b'.repeat(kKeyLengthMax)]: 'value',
  320. 'not-long': 'not-long-value'
  321. }
  322. });
  323. require('electron').crashReporter.addExtraParameter('c'.repeat(kKeyLengthMax + 10), 'value');
  324. setTimeout(() => process.crash());
  325. }, port, kKeyLengthMax);
  326. const crash = await waitForCrash();
  327. expect(crash).not.to.have.property('a'.repeat(kKeyLengthMax + 10));
  328. expect(crash).not.to.have.property('a'.repeat(kKeyLengthMax));
  329. expect(crash).to.have.property('b'.repeat(kKeyLengthMax), 'value');
  330. expect(crash).to.have.property('not-long', 'not-long-value');
  331. expect(crash).not.to.have.property('c'.repeat(kKeyLengthMax + 10));
  332. expect(crash).not.to.have.property('c'.repeat(kKeyLengthMax));
  333. });
  334. });
  335. describe('globalExtra', () => {
  336. ifit(!isLinuxOnArm)('should be sent with main process dumps', async () => {
  337. const { port, waitForCrash } = await startServer();
  338. runCrashApp('main', port, ['--add-global-param=globalParam:globalValue']);
  339. const crash = await waitForCrash();
  340. expect(crash.globalParam).to.equal('globalValue');
  341. });
  342. it('should be sent with renderer process dumps', async () => {
  343. const { port, waitForCrash } = await startServer();
  344. runCrashApp('renderer', port, ['--add-global-param=globalParam:globalValue']);
  345. const crash = await waitForCrash();
  346. expect(crash.globalParam).to.equal('globalValue');
  347. });
  348. it('should be sent with sandboxed renderer process dumps', async () => {
  349. const { port, waitForCrash } = await startServer();
  350. runCrashApp('sandboxed-renderer', port, ['--add-global-param=globalParam:globalValue']);
  351. const crash = await waitForCrash();
  352. expect(crash.globalParam).to.equal('globalValue');
  353. });
  354. ifit(!isLinuxOnArm)('should not be overridden by extra in main process', async () => {
  355. const { port, waitForCrash } = await startServer();
  356. runCrashApp('main', port, ['--add-global-param=mainProcessSpecific:global']);
  357. const crash = await waitForCrash();
  358. expect(crash.mainProcessSpecific).to.equal('global');
  359. });
  360. ifit(!isLinuxOnArm)('should not be overridden by extra in renderer process', async () => {
  361. const { port, waitForCrash } = await startServer();
  362. runCrashApp('main', port, ['--add-global-param=rendererSpecific:global']);
  363. const crash = await waitForCrash();
  364. expect(crash.rendererSpecific).to.equal('global');
  365. });
  366. });
  367. // TODO(nornagon): also test crashing main / sandboxed renderers.
  368. ifit(!isWindowsOnArm)('should not send a minidump when uploadToServer is false', async () => {
  369. const { port, waitForCrash, getCrashes } = await startServer();
  370. waitForCrash().then(() => expect.fail('expected not to receive a dump'));
  371. await runCrashApp('renderer', port, ['--no-upload']);
  372. // wait a sec in case the crash reporter is about to upload a crash
  373. await new Promise(resolve => setTimeout(resolve, 1000));
  374. expect(getCrashes()).to.have.length(0);
  375. });
  376. describe('start() option validation', () => {
  377. it('requires that the submitURL option be specified', () => {
  378. expect(() => {
  379. crashReporter.start({} as any);
  380. }).to.throw('submitURL is a required option to crashReporter.start');
  381. });
  382. it('can be called twice', async () => {
  383. const { remotely } = await startRemoteControlApp();
  384. await expect(remotely(() => {
  385. const { crashReporter } = require('electron');
  386. crashReporter.start({ submitURL: 'http://127.0.0.1' });
  387. crashReporter.start({ submitURL: 'http://127.0.0.1' });
  388. })).to.be.fulfilled();
  389. });
  390. });
  391. describe('getUploadedReports', () => {
  392. it('returns an array of reports', async () => {
  393. const { remotely } = await startRemoteControlApp();
  394. await remotely(() => {
  395. require('electron').crashReporter.start({ submitURL: 'http://127.0.0.1' });
  396. });
  397. const reports = await remotely(() => require('electron').crashReporter.getUploadedReports());
  398. expect(reports).to.be.an('array');
  399. });
  400. });
  401. // TODO(nornagon): re-enable on woa
  402. ifdescribe(!isWindowsOnArm)('getLastCrashReport', () => {
  403. it('returns the last uploaded report', async () => {
  404. const { remotely } = await startRemoteControlApp();
  405. const { port, waitForCrash } = await startServer();
  406. // 0. clear the crash reports directory.
  407. const dir = await remotely(() => require('electron').app.getPath('crashDumps'));
  408. try {
  409. rimraf.sync(dir);
  410. fs.mkdirSync(dir);
  411. } catch (e) { /* ignore */ }
  412. // 1. start the crash reporter.
  413. await remotely((port: number) => {
  414. require('electron').crashReporter.start({
  415. submitURL: `http://127.0.0.1:${port}`,
  416. ignoreSystemCrashHandler: true
  417. });
  418. }, [port]);
  419. // 2. generate a crash in the renderer.
  420. remotely(() => {
  421. const { BrowserWindow } = require('electron');
  422. const bw = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  423. bw.loadURL('about:blank');
  424. bw.webContents.executeJavaScript('process.crash()');
  425. });
  426. await waitForCrash();
  427. // 3. get the crash from getLastCrashReport.
  428. const firstReport = await remotely(() => require('electron').crashReporter.getLastCrashReport());
  429. expect(firstReport).to.not.be.null();
  430. expect(firstReport.date).to.be.an.instanceOf(Date);
  431. expect((+new Date()) - (+firstReport.date)).to.be.lessThan(30000);
  432. });
  433. });
  434. describe('getUploadToServer()', () => {
  435. it('returns true when uploadToServer is set to true (by default)', async () => {
  436. const { remotely } = await startRemoteControlApp();
  437. await remotely(() => { require('electron').crashReporter.start({ submitURL: 'http://127.0.0.1' }); });
  438. const uploadToServer = await remotely(() => require('electron').crashReporter.getUploadToServer());
  439. expect(uploadToServer).to.be.true();
  440. });
  441. it('returns false when uploadToServer is set to false in init', async () => {
  442. const { remotely } = await startRemoteControlApp();
  443. await remotely(() => { require('electron').crashReporter.start({ submitURL: 'http://127.0.0.1', uploadToServer: false }); });
  444. const uploadToServer = await remotely(() => require('electron').crashReporter.getUploadToServer());
  445. expect(uploadToServer).to.be.false();
  446. });
  447. it('is updated by setUploadToServer', async () => {
  448. const { remotely } = await startRemoteControlApp();
  449. await remotely(() => { require('electron').crashReporter.start({ submitURL: 'http://127.0.0.1' }); });
  450. await remotely(() => { require('electron').crashReporter.setUploadToServer(false); });
  451. expect(await remotely(() => require('electron').crashReporter.getUploadToServer())).to.be.false();
  452. await remotely(() => { require('electron').crashReporter.setUploadToServer(true); });
  453. expect(await remotely(() => require('electron').crashReporter.getUploadToServer())).to.be.true();
  454. });
  455. });
  456. describe('getParameters', () => {
  457. it('returns all of the current parameters', async () => {
  458. const { remotely } = await startRemoteControlApp();
  459. await remotely(() => {
  460. require('electron').crashReporter.start({
  461. submitURL: 'http://127.0.0.1',
  462. extra: { extra1: 'hi' }
  463. });
  464. });
  465. const parameters = await remotely(() => require('electron').crashReporter.getParameters());
  466. expect(parameters).to.have.property('extra1', 'hi');
  467. });
  468. it('reflects added and removed parameters', async () => {
  469. const { remotely } = await startRemoteControlApp();
  470. await remotely(() => {
  471. require('electron').crashReporter.start({ submitURL: 'http://127.0.0.1' });
  472. require('electron').crashReporter.addExtraParameter('hello', 'world');
  473. });
  474. {
  475. const parameters = await remotely(() => require('electron').crashReporter.getParameters());
  476. expect(parameters).to.have.property('hello', 'world');
  477. }
  478. await remotely(() => { require('electron').crashReporter.removeExtraParameter('hello'); });
  479. {
  480. const parameters = await remotely(() => require('electron').crashReporter.getParameters());
  481. expect(parameters).not.to.have.property('hello');
  482. }
  483. });
  484. it('can be called in the renderer', async () => {
  485. const { remotely } = await startRemoteControlApp();
  486. const rendererParameters = await remotely(async () => {
  487. const { crashReporter, BrowserWindow } = require('electron');
  488. crashReporter.start({ submitURL: 'http://' });
  489. const bw = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  490. bw.loadURL('about:blank');
  491. await bw.webContents.executeJavaScript('require(\'electron\').crashReporter.addExtraParameter(\'hello\', \'world\')');
  492. return bw.webContents.executeJavaScript('require(\'electron\').crashReporter.getParameters()');
  493. });
  494. if (process.platform === 'linux') {
  495. // On Linux, 'getParameters' will also include the global parameters,
  496. // because breakpad doesn't support global parameters.
  497. expect(rendererParameters).to.have.property('hello', 'world');
  498. } else {
  499. expect(rendererParameters).to.deep.equal({ hello: 'world' });
  500. }
  501. });
  502. it('can be called in a node child process', async () => {
  503. function slurp (stream: NodeJS.ReadableStream): Promise<string> {
  504. return new Promise((resolve, reject) => {
  505. const chunks: Buffer[] = [];
  506. stream.on('data', chunk => { chunks.push(chunk); });
  507. stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  508. stream.on('error', e => reject(e));
  509. });
  510. }
  511. const child = childProcess.fork(path.join(__dirname, 'fixtures', 'module', 'print-crash-parameters.js'), [], { silent: true });
  512. const output = await slurp(child.stdout!);
  513. expect(JSON.parse(output)).to.deep.equal({ hello: 'world' });
  514. });
  515. });
  516. describe('crash dumps directory', () => {
  517. it('is set by default', () => {
  518. expect(app.getPath('crashDumps')).to.be.a('string');
  519. });
  520. it('is inside the user data dir', () => {
  521. expect(app.getPath('crashDumps')).to.include(app.getPath('userData'));
  522. });
  523. it('matches getCrashesDirectory', async () => {
  524. expect(app.getPath('crashDumps')).to.equal(require('electron').crashReporter.getCrashesDirectory());
  525. });
  526. function crash (processType: string, remotely: Function) {
  527. if (processType === 'main') {
  528. return remotely(() => {
  529. setTimeout(() => { process.crash(); });
  530. });
  531. } else if (processType === 'renderer') {
  532. return remotely(() => {
  533. const { BrowserWindow } = require('electron');
  534. const bw = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  535. bw.loadURL('about:blank');
  536. bw.webContents.executeJavaScript('process.crash()');
  537. });
  538. } else if (processType === 'sandboxed-renderer') {
  539. const preloadPath = path.join(__dirname, 'fixtures', 'apps', 'crash', 'sandbox-preload.js');
  540. return remotely((preload: string) => {
  541. const { BrowserWindow } = require('electron');
  542. const bw = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } });
  543. bw.loadURL('about:blank');
  544. }, preloadPath);
  545. } else if (processType === 'node') {
  546. const crashScriptPath = path.join(__dirname, 'fixtures', 'apps', 'crash', 'node-crash.js');
  547. return remotely((crashScriptPath: string) => {
  548. const { app } = require('electron');
  549. const childProcess = require('child_process');
  550. const version = app.getVersion();
  551. const url = 'http://127.0.0.1';
  552. childProcess.fork(crashScriptPath, [url, version], { silent: true });
  553. }, crashScriptPath);
  554. }
  555. }
  556. const processList = process.platform === 'linux' ? ['main', 'renderer', 'sandboxed-renderer']
  557. : ['main', 'renderer', 'sandboxed-renderer', 'node'];
  558. for (const crashingProcess of processList) {
  559. describe(`when ${crashingProcess} crashes`, () => {
  560. it('stores crashes in the crash dump directory when uploadToServer: false', async () => {
  561. const { remotely } = await startRemoteControlApp();
  562. const crashesDir = await remotely(() => {
  563. const { crashReporter } = require('electron');
  564. crashReporter.start({ submitURL: 'http://127.0.0.1', uploadToServer: false, ignoreSystemCrashHandler: true });
  565. return crashReporter.getCrashesDirectory();
  566. });
  567. let reportsDir = crashesDir;
  568. if (process.platform === 'darwin') {
  569. reportsDir = path.join(crashesDir, 'completed');
  570. } else if (process.platform === 'win32') {
  571. reportsDir = path.join(crashesDir, 'reports');
  572. }
  573. const newFileAppeared = waitForNewFileInDir(reportsDir);
  574. crash(crashingProcess, remotely);
  575. const newFiles = await newFileAppeared;
  576. expect(newFiles.length).to.be.greaterThan(0);
  577. if (process.platform === 'linux') {
  578. if (crashingProcess === 'main') {
  579. expect(newFiles[0]).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{8}-[0-9a-f]{8}\.dmp$/);
  580. } else {
  581. const process = crashingProcess === 'sandboxed-renderer' ? 'renderer' : crashingProcess;
  582. const regex = RegExp(`chromium-${process}-minidump-[0-9a-f]{16}.dmp`);
  583. expect(newFiles[0]).to.match(regex);
  584. }
  585. } else {
  586. expect(newFiles[0]).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.dmp$/);
  587. }
  588. });
  589. it('respects an overridden crash dump directory', async () => {
  590. const { remotely } = await startRemoteControlApp();
  591. const crashesDir = path.join(app.getPath('temp'), uuid.v4());
  592. const remoteCrashesDir = await remotely((crashesDir: string) => {
  593. const { crashReporter, app } = require('electron');
  594. app.setPath('crashDumps', crashesDir);
  595. crashReporter.start({ submitURL: 'http://127.0.0.1', uploadToServer: false, ignoreSystemCrashHandler: true });
  596. return crashReporter.getCrashesDirectory();
  597. }, crashesDir);
  598. expect(remoteCrashesDir).to.equal(crashesDir);
  599. let reportsDir = crashesDir;
  600. if (process.platform === 'darwin') {
  601. reportsDir = path.join(crashesDir, 'completed');
  602. } else if (process.platform === 'win32') {
  603. reportsDir = path.join(crashesDir, 'reports');
  604. }
  605. const newFileAppeared = waitForNewFileInDir(reportsDir);
  606. crash(crashingProcess, remotely);
  607. const newFiles = await newFileAppeared;
  608. expect(newFiles.length).to.be.greaterThan(0);
  609. if (process.platform === 'linux') {
  610. if (crashingProcess === 'main') {
  611. expect(newFiles[0]).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{8}-[0-9a-f]{8}\.dmp$/);
  612. } else {
  613. const process = crashingProcess !== 'sandboxed-renderer' ? crashingProcess : 'renderer';
  614. const regex = RegExp(`chromium-${process}-minidump-[0-9a-f]{16}.dmp`);
  615. expect(newFiles[0]).to.match(regex);
  616. }
  617. } else {
  618. expect(newFiles[0]).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.dmp$/);
  619. }
  620. });
  621. });
  622. }
  623. });
  624. describe('when not started', () => {
  625. it('does not prevent process from crashing', async () => {
  626. const appPath = path.join(__dirname, '..', 'spec', 'fixtures', 'api', 'cookie-app');
  627. await runApp(appPath);
  628. });
  629. });
  630. });