api-crash-reporter-spec.ts 28 KB

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