builder.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. /*@flow*/
  16. 'use strict';
  17. const Os = require('os');
  18. const Fs = require('fs');
  19. const Spawn = require('child_process').spawn;
  20. const nThen = require('nthen');
  21. const Crypto = require('crypto');
  22. const Saferphore = require('saferphore');
  23. /*::
  24. export type Builder_File_t = {|
  25. includes: string[],
  26. links: string[],
  27. cflags: string[],
  28. ldflags: string[],
  29. mtime: number,
  30. |};
  31. export type Builder_Hfile_t = {|
  32. mtime: number,
  33. |};
  34. export type Builder_Compiler_t = {|
  35. isLLVM: bool,
  36. isClang: bool,
  37. isGCC: bool,
  38. version: string
  39. |};
  40. export type Builder_State_t = {|
  41. compilerType: Builder_Compiler_t,
  42. cFiles: { [string]: Builder_File_t },
  43. hFiles: { [string]: Builder_Hfile_t },
  44. |};
  45. export type Builder_Linter_t = (string, string, (string, bool)=>void)=>void;
  46. export type Builder_TestRunnerCb_t = (string, bool)=>void;
  47. export type Builder_t = {|
  48. cc: (string[], (number, string, string)=>void)=>void,
  49. buildLibrary: (string)=>void,
  50. buildExecutable: (string, ?string)=>void,
  51. buildTest: (string)=>string,
  52. runTest: (string, (string, Builder_TestRunnerCb_t)=>void)=>void,
  53. lintFiles: (Builder_Linter_t)=>void,
  54. config: Builder_Config_t,
  55. tmpFile: (?string)=>string,
  56. compilerType: () => Builder_Compiler_t,
  57. fileCflags: {[string]: string[]},
  58. |};
  59. export type Builder_BaseConfig_t = {|
  60. systemName?: ?string,
  61. gcc?: ?string,
  62. buildDir?: ?string,
  63. |};
  64. export type Builder_Config_t = {
  65. systemName: string,
  66. gcc: string,
  67. buildDir: string,
  68. includeDirs: string[],
  69. cflags: string[],
  70. ldflags: string[],
  71. libs: string[],
  72. jobs: number,
  73. } & {[string]:any};
  74. import type { Nthen_WaitFor_t } from 'nthen';
  75. import type { Saferphore_t } from 'saferphore';
  76. export type Builder_Stage_t = (Builder_t, Nthen_WaitFor_t)=>void;
  77. export type Builder_CompileJob_t = {
  78. cFile: string,
  79. outputFile: ?string,
  80. type: 'exe'|'lib'
  81. };
  82. export type Builder_Pub_t = {|
  83. build: (Builder_Stage_t)=>Builder_Pub_t,
  84. test: (Builder_Stage_t)=>Builder_Pub_t,
  85. pack: (Builder_Stage_t)=>Builder_Pub_t,
  86. failure: (Builder_Stage_t)=>Builder_Pub_t,
  87. success: (Builder_Stage_t)=>Builder_Pub_t,
  88. complete: (Builder_Stage_t)=>Builder_Pub_t,
  89. |}
  90. export type Builder_PreCtx_t = {
  91. buildStage: Builder_Stage_t,
  92. testStage: Builder_Stage_t,
  93. packStage: Builder_Stage_t,
  94. failureStage: Builder_Stage_t,
  95. successStage: Builder_Stage_t,
  96. completeStage: Builder_Stage_t,
  97. failure: bool,
  98. linters: Builder_Linter_t[],
  99. executables: Array<Builder_CompileJob_t>,
  100. tests: Array<(Builder_TestRunnerCb_t)=>void>,
  101. toCompile: { [string]: Builder_File_t },
  102. config: Builder_Config_t,
  103. sema: Saferphore_t,
  104. };
  105. export type Builder_Ctx_t = Builder_PreCtx_t & {
  106. builder: Builder_t,
  107. state: Builder_State_t,
  108. };
  109. */
  110. const error = function (message) /*:Error*/ {
  111. try {
  112. throw new Error(message);
  113. } catch (e) {
  114. return e;
  115. }
  116. };
  117. const expandArgs = function (args) {
  118. const out = [];
  119. for (let i = 0; i < args.length; i++) {
  120. if (typeof(args[i]) === 'object') {
  121. if (Array.isArray(args[i])) {
  122. out.push.apply(out, expandArgs(args[i]));
  123. } else {
  124. throw new Error("object in arguments [" + args.join() + "]");
  125. }
  126. } else {
  127. out.push(args[i]);
  128. }
  129. }
  130. return out;
  131. };
  132. const compiler = function (
  133. ctx /*:Builder_Ctx_t*/,
  134. args /*:string[]*/,
  135. callback /*:(number, string, string)=>bool|void*/,
  136. content /*:string*/
  137. ) {
  138. let stop = false;
  139. args = expandArgs(args);
  140. ctx.sema.take(function (returnAfter) {
  141. if (stop) {
  142. return void returnAfter(function (ret) {
  143. callback(1, '', 'interrupted');
  144. });
  145. }
  146. if (process.env.VERBOSE) {
  147. console.log(ctx.config.gcc + ' ' + args.join(' '));
  148. }
  149. const gcc = Spawn(ctx.config.gcc, args);
  150. let err = '';
  151. let out = '';
  152. gcc.stdout.on('data', function (dat) { out += dat.toString(); });
  153. gcc.stderr.on('data', function (dat) { err += dat.toString(); });
  154. gcc.on('close', returnAfter(function (ret) {
  155. if (callback(ret, out, err)) { stop = true; }
  156. }));
  157. gcc.on('error', function (err) {
  158. if (err.code === 'ENOENT') {
  159. console.error('\x1b[1;31mError: ' + ctx.config.gcc + ' is required!\x1b[0m');
  160. } else {
  161. console.error(
  162. '\x1b[1;31mFail run ' + process.cwd() + ': ' + ctx.config.gcc + ' '
  163. + args.join(' ') + '\x1b[0m'
  164. );
  165. console.error('Message:' + err);
  166. }
  167. // handle the error safely
  168. console.log(args);
  169. });
  170. if (content) {
  171. gcc.stdin.write(content, function (err) {
  172. if (err) { throw err; }
  173. gcc.stdin.end();
  174. });
  175. }
  176. });
  177. };
  178. const cc = function (
  179. ctx /*:Builder_Ctx_t*/,
  180. args /*:string[]*/,
  181. callback /*:(?Error, ?string)=>bool|void*/,
  182. content /*:string*/
  183. ) {
  184. compiler(ctx, args, function (ret, out, err) {
  185. if (ret) {
  186. return callback(error(ctx.config.gcc + " " + args.map(String).join(' ') + "\n\n" + err));
  187. }
  188. if (err !== '') {
  189. //process.stdout.write(err);
  190. }
  191. return callback(undefined, out);
  192. }, content);
  193. };
  194. const getStatePrototype = function () /*:Builder_State_t*/ {
  195. return {
  196. compilerType: {
  197. isLLVM: false,
  198. isClang: false,
  199. isGCC: false,
  200. version: ''
  201. },
  202. cFiles: {},
  203. hFiles: {},
  204. };
  205. };
  206. const tmpFile = function (ctx /*:Builder_Ctx_t*/, name) {
  207. name = name || '';
  208. return ctx.config.buildDir + '/tmp/' + name + Crypto.pseudoRandomBytes(10).toString('hex');
  209. };
  210. const finalizeCtx = function (
  211. state /*:Builder_State_t*/,
  212. pctx /*:Builder_PreCtx_t*/
  213. ) /*:Builder_Ctx_t*/ {
  214. const ctx = ((pctx /*:any*/) /*:Builder_Ctx_t*/);
  215. ctx.state = state;
  216. ctx.builder = (Object.freeze({
  217. cc: function (args, callback) {
  218. compiler(ctx, args, callback, '');
  219. },
  220. buildLibrary: function (cFile) {
  221. ctx.executables.push({ cFile, outputFile: null, type: 'lib' });
  222. },
  223. buildExecutable: function (cFile, outputFile) {
  224. ctx.executables.push({ cFile, outputFile, type: 'exe' });
  225. },
  226. buildTest: function (cFile) {
  227. const outputFile = getTempExe(ctx, cFile);
  228. ctx.executables.push({ cFile, outputFile, type: 'exe' });
  229. return outputFile;
  230. },
  231. runTest: function (outFile, testRunner) {
  232. ctx.tests.push(function (cb) { testRunner(outFile, cb); });
  233. },
  234. lintFiles: function (linter) {
  235. ctx.linters.push(linter);
  236. },
  237. config: ctx.config,
  238. tmpFile: function (name) {
  239. return tmpFile(ctx, name);
  240. },
  241. compilerType: () => JSON.parse(JSON.stringify(ctx.state.compilerType)),
  242. fileCflags: {},
  243. }) /*:Builder_t*/);
  244. return ctx;
  245. };
  246. // You Were Warned
  247. const execJs = function (js, ctx, file, fileName, callback, thisObj) {
  248. let res;
  249. let x;
  250. let err;
  251. // # 74 "./wire/Message.h"
  252. js = js.replace(/\n#.*\n/g, '');
  253. // Js_SQ Js_DQ
  254. const qs = js.split('Js_Q');
  255. if (qs.length && (qs.length % 2) === 0) {
  256. throw new Error("Uneven number of Js_Q, content: [" + js + "]");
  257. }
  258. for (let i = 1; i < qs.length; i += 2) {
  259. // escape nested quotes, they'll come back out in the final .i file
  260. qs[i] = qs[i].replace(/\'/g, '\\u0027');
  261. }
  262. js = '"use strict";' + qs.join("'");
  263. const to = setTimeout(function () {
  264. throw new Error("Inline JS did not return after 120 seconds [" + js + "]");
  265. }, 120000);
  266. nThen(function (waitFor) {
  267. try {
  268. /* jshint -W054 */ // Suppress jshint warning on Function being a form of eval
  269. const func = new Function('require', 'js', 'console', 'builder', js);
  270. const jsObj = Object.freeze({
  271. async: function () {
  272. return waitFor(function (result) {
  273. res = result;
  274. });
  275. },
  276. linkerDependency: (cFile) => file.links.push(cFile),
  277. currentFile: fileName,
  278. });
  279. x = func.call(thisObj,
  280. require,
  281. jsObj,
  282. console,
  283. ctx.builder);
  284. } catch (e) {
  285. clearTimeout(to);
  286. console.error("Error executing: [" + js + "] in File [" + fileName + "]");
  287. throw e;
  288. }
  289. }).nThen(function (waitFor) {
  290. if (err) { return; }
  291. res = res || x || '';
  292. clearTimeout(to);
  293. process.nextTick(function () { callback(undefined, res); });
  294. });
  295. };
  296. const debug = console.log;
  297. const preprocessBlock = function (block, ctx, fileObj, fileName, callback, thisObj) {
  298. // a block is an array of strings and arrays, any inside arrays must be
  299. // preprocessed first. deep first top to bottom.
  300. let nt = nThen;
  301. block.forEach(function (elem, i) {
  302. if (typeof(elem) === 'string') { return; }
  303. nt = nt(function (waitFor) {
  304. preprocessBlock(elem, ctx, fileObj, fileName, waitFor(function (err, ret) {
  305. if (err) { throw err; }
  306. block[i] = ret;
  307. }), thisObj);
  308. }).nThen;
  309. });
  310. nt(function (waitFor) {
  311. const capture = block.join('');
  312. execJs(capture, ctx, fileObj, fileName, waitFor(function (err, ret) {
  313. if (err) { throw err; }
  314. callback(undefined, ret);
  315. }), thisObj);
  316. });
  317. };
  318. const preprocess = function (content /*:string*/, ctx, fileObj, fileName, callback) {
  319. // <?js file.Test_mainFunc = "<?js return 'RootTest_'+file.RootTest_mainFunc; ?>" ?>
  320. // worse:
  321. // <?js file.Test_mainFunc = "<?js const done = this.async(); process.nextTick(done); ?>" ?>
  322. const flatArray = content.split(/(<\?js|\?>)/);
  323. const elems = [];
  324. const unflatten = function (array, startAt, out) {
  325. let i = startAt;
  326. for (; i < array.length; i++) {
  327. if (((i - startAt) % 2) === 0) {
  328. out.push(array[i]);
  329. } else if (array[i] === '<?js') {
  330. const next = [];
  331. out.push(next);
  332. i = unflatten(array, i+1, next);
  333. } else if (array[i] === '?>') {
  334. return i;
  335. }
  336. }
  337. return i;
  338. };
  339. if (unflatten(flatArray, 0, elems) !== flatArray.length) {
  340. throw new Error();
  341. }
  342. const thisObj = {};
  343. let nt = nThen;
  344. elems.forEach(function (elem, i) {
  345. if (typeof(elem) === 'string') { return; }
  346. nt = nt(function (waitFor) {
  347. preprocessBlock(elem, ctx, fileObj, fileName, waitFor(function (err, ret) {
  348. if (err) { throw err; }
  349. elems[i] = ret;
  350. }), thisObj);
  351. }).nThen;
  352. });
  353. nt(function (waitFor) {
  354. callback(undefined, elems.join(''));
  355. });
  356. };
  357. const mkFile = function () /*:Builder_File_t*/ {
  358. return {
  359. includes: [],
  360. links: [],
  361. cflags: [],
  362. ldflags: [],
  363. mtime: 0,
  364. };
  365. };
  366. const getOFile = function (ctx, cFile) {
  367. return ctx.config.buildDir + '/' + cFile.replace(/[^a-zA-Z0-9_-]/g, '_') + '.o';
  368. };
  369. const getIFile = function (ctx, cFile) {
  370. return ctx.config.buildDir + '/' + cFile.replace(/[^a-zA-Z0-9_-]/g, '_') + '.i';
  371. };
  372. const getTempExe = function (ctx, cFile) {
  373. return ctx.config.buildDir + '/' + cFile.replace(/[^a-zA-Z0-9_-]/g, '_');
  374. };
  375. const getExeFile = function (ctx, exe /*:Builder_CompileJob_t*/) {
  376. let outputFile = exe.outputFile;
  377. if (!outputFile) {
  378. outputFile = exe.cFile.replace(/^.*\/([^\/\.]*).*$/, (a, b) => b);
  379. }
  380. if (ctx.config.systemName === 'win32' && !(/\.exe$/.test(outputFile))) {
  381. outputFile += '.exe';
  382. }
  383. return outputFile;
  384. };
  385. const getFlags = function (ctx, cFile, includeDirs) {
  386. const flags = [];
  387. if (cFile.indexOf('node_build/dependencies/libuv') > -1) {
  388. //console.log('cargo:warning=' + cFile);
  389. for (const f of ctx.config.cflags) {
  390. if (f !== '-Werror') {
  391. flags.push(f);
  392. }
  393. }
  394. } else {
  395. flags.push.apply(flags, ctx.config.cflags);
  396. }
  397. flags.push.apply(flags, ctx.builder.fileCflags[cFile] || []);
  398. if (includeDirs) {
  399. for (let i = 0; i < ctx.config.includeDirs.length; i++) {
  400. if (flags[flags.indexOf(ctx.config.includeDirs[i])-1] === '-I') {
  401. continue;
  402. }
  403. flags.push('-I');
  404. flags.push(ctx.config.includeDirs[i]);
  405. }
  406. }
  407. return flags;
  408. };
  409. const preprocessFile = function (cFile, ctx, callback)
  410. {
  411. if (ctx.state.cFiles[cFile]) {
  412. return void callback();
  413. }
  414. const state = ctx.state;
  415. //debug(' preprocessing ' + cFile);
  416. //debug('\x1b[2;32mCompiling ' + cFile + '\x1b[0m');
  417. const fileObj = mkFile();
  418. let fileContent = '';
  419. const cflags = getFlags(ctx, cFile, true);
  420. fileObj.cflags = getFlags(ctx, cFile, false);
  421. nThen((w) => {
  422. //debug("CPP");
  423. cc(ctx, ['-E', ...cflags, cFile], w(function (err, output) {
  424. if (err) { throw err; }
  425. fileContent = output;
  426. return false;
  427. }), '');
  428. // Stat the C file
  429. Fs.stat(cFile, w(function (err, st) {
  430. if (err) { throw err; }
  431. fileObj.mtime = st.mtime.getTime();
  432. }));
  433. }).nThen((w) => {
  434. //debug("Preprocess");
  435. preprocess(fileContent, ctx, fileObj, cFile, w(function (err, output) {
  436. if (err) { throw err; }
  437. Fs.writeFile(getIFile(ctx, cFile), output, w(function (err) {
  438. if (err) { throw err; }
  439. }));
  440. }));
  441. // Also snatch the local includes
  442. const includes = fileContent.match(/# [0-9]+ "\.\/[^"]*"/g) || [];
  443. const uniqIncl = {};
  444. for (const incl of includes) {
  445. uniqIncl[incl.replace(/^.* "\.\//, '').slice(0,-1)] = 1;
  446. }
  447. fileObj.includes = Object.keys(uniqIncl);
  448. fileObj.includes.forEach((incl) => {
  449. if (ctx.state.hFiles[incl]) { return; }
  450. Fs.stat(incl, w((err, st) => {
  451. if (err) { throw err; }
  452. ctx.state.hFiles[incl] = {
  453. mtime: st.mtime.getTime()
  454. };
  455. }));
  456. });
  457. }).nThen(function (_) {
  458. debug('\x1b[2;36mPreprocessing ' + cFile + ' complete\x1b[0m');
  459. state.cFiles[cFile] = fileObj;
  460. ctx.toCompile[cFile] = fileObj;
  461. callback();
  462. });
  463. };
  464. const preprocessFiles = function (ctx, files, callback) {
  465. const added = {};
  466. for (const f of files) { added[f] = 1; }
  467. const doMore = () => {
  468. if (files.length === 0) {
  469. return void callback();
  470. }
  471. const filez = files;
  472. files = [];
  473. nThen((w) => {
  474. filez.forEach((file) => {
  475. preprocessFile(file, ctx, w(() => {
  476. ctx.state.cFiles[file].links.forEach(function (link) {
  477. if (link === file || added[link]) {
  478. return;
  479. }
  480. added[link] = 1;
  481. files.push(link);
  482. });
  483. }));
  484. });
  485. }).nThen((w) => {
  486. doMore();
  487. });
  488. };
  489. doMore();
  490. };
  491. const getLinkOrder = function (cFile, files) /*:string[]*/ {
  492. const completeFiles = [];
  493. const getFile = function (name) {
  494. const f = files[name];
  495. //debug('Resolving links for ' + name);
  496. for (let i = 0; i < f.links.length; i++) {
  497. if (f.links[i] === name) {
  498. continue;
  499. }
  500. if (completeFiles.indexOf(f.links[i]) > -1) {
  501. continue;
  502. }
  503. getFile(f.links[i]);
  504. }
  505. completeFiles.push(name);
  506. };
  507. getFile(cFile);
  508. return completeFiles;
  509. };
  510. // Called on the .c file with a main() function which corrisponds to
  511. // an executable.
  512. // We kick the file entries right out of the state object when they
  513. // or an #include get dirty, so we just need to traverse links to
  514. // make sure everything is present.
  515. const needsToLink = function (ctx, cFile) {
  516. const nlCache = {};
  517. const nll = [];
  518. const nl = (cFile) => {
  519. if (nlCache[cFile]) { return false; }
  520. if (nll.indexOf(cFile) > -1) {
  521. return false;
  522. //throw new Error(`File ${cFile} is self-referencial:\n${nll.join('\n')}\n\n`);
  523. }
  524. nll.push(cFile);
  525. const out = (() => {
  526. //debug(' ' + cFile);
  527. if (typeof(ctx.state.cFiles[cFile]) !== 'object') {
  528. return true;
  529. }
  530. for (const l of ctx.state.cFiles[cFile].links) {
  531. if (l !== cFile && nl(l)) {
  532. return true;
  533. }
  534. }
  535. nlCache[cFile] = true;
  536. return false;
  537. })();
  538. if (nll.pop() !== cFile) { throw new Error(); }
  539. return out;
  540. };
  541. return nl(cFile);
  542. };
  543. const makeTime = function () {
  544. let time = 0;
  545. return function () {
  546. const oldTime = time;
  547. time = new Date().getTime();
  548. return time - oldTime;
  549. };
  550. };
  551. const link = function (cFile, callback, ctx /*:Builder_Ctx_t*/) {
  552. const state = ctx.state;
  553. const temp = getTempExe(ctx, cFile);
  554. nThen((waitFor) => {
  555. const linkOrder = getLinkOrder(cFile, state.cFiles);
  556. for (let i = 0; i < linkOrder.length; i++) {
  557. linkOrder[i] = getOFile(ctx, linkOrder[i]);
  558. }
  559. const fileObj = state.cFiles[cFile];
  560. const ldArgs = []
  561. .concat(ctx.config.ldflags)
  562. .concat(fileObj.ldflags)
  563. .concat(['-o', temp])
  564. .concat(linkOrder)
  565. .concat(ctx.config.libs);
  566. debug('\x1b[1;31mLinking C executable ' + cFile + '\x1b[0m');
  567. cc(ctx, ldArgs, waitFor(function (err, ret) {
  568. if (err) { throw err; }
  569. return false;
  570. }), '');
  571. }).nThen((_) => callback());
  572. };
  573. const compile = function (ctx, cFile, done) {
  574. //debug("CC");
  575. const file = ctx.state.cFiles[cFile];
  576. const oFile = getOFile(ctx, cFile);
  577. const iFile = getIFile(ctx, cFile);
  578. cc(ctx, ['-c', '-x', 'cpp-output', '-o', oFile, ...file.cflags, iFile], (err) => {
  579. done(err);
  580. return typeof(err) !== 'undefined';
  581. }, '');
  582. };
  583. /**
  584. * Get a copy of process.env with a few entries which are constantly changing removed.
  585. * This prevents isStaleState from returning true every time one builds in a different
  586. * window.
  587. */
  588. const normalizedProcessEnv = function () {
  589. const out = process.env;
  590. delete out.WINDOWID;
  591. delete out.OLDPWD;
  592. return out;
  593. };
  594. const getRebuildIfChangesHash = function (rebuildIfChanges, callback) {
  595. const hash = Crypto.createHash('sha256');
  596. const rebIfChg = [];
  597. nThen(function (waitFor) {
  598. rebuildIfChanges.forEach(function (fileName, i) {
  599. Fs.readFile(fileName, waitFor(function (err, ret) {
  600. if (err) { throw err; }
  601. rebIfChg[i] = ret;
  602. }));
  603. });
  604. hash.update(JSON.stringify(normalizedProcessEnv()));
  605. }).nThen(function (waitFor) {
  606. rebIfChg.forEach(function (data) {
  607. hash.update(data);
  608. });
  609. callback(hash.digest('hex'));
  610. });
  611. };
  612. const probeCompiler = function (ctx /*:Builder_Ctx_t*/, callback) {
  613. nThen(function (waitFor) {
  614. const compilerType = ctx.state.compilerType = {
  615. isLLVM: false,
  616. isClang: false,
  617. isGCC: false,
  618. version: ''
  619. };
  620. compiler(ctx, ['-v'], waitFor(function (ret, out, err) {
  621. // TODO(cjd): afl-clang-fast errors when called with -v
  622. //if (ret !== 0) { throw new Error("Failed to probe compiler ret[" + ret + "]\n" + err); }
  623. if (/Apple LLVM version /.test(err)) {
  624. compilerType.isLLVM = true;
  625. if (/clang/.test(err)) {
  626. // Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
  627. // Target: x86_64-apple-darwin14.4.0
  628. // Thread model: posix
  629. compilerType.isClang = true;
  630. compilerType.version = err.match(/Apple LLVM version ([^ ]+) /)[1];
  631. } else if (/gcc version /.test(err)) {
  632. // Using built-in specs.
  633. // Target: i686-apple-darwin11
  634. // Configured with: /private/const/tmp/llvmgcc42/llvmgcc42.......
  635. // Thread model: posix
  636. // gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
  637. compilerType.isGCC = true;
  638. compilerType.version = err.match(/gcc version ([^ ]+) /)[1];
  639. }
  640. } else if (/clang version /.test(err)) {
  641. // FreeBSD clang version 3.0 (tags/RELEASE_30/final 145349) 20111210
  642. // Target: x86_64-unknown-freebsd10.0
  643. // Thread model: posix
  644. // clang version 3.2 (trunk)
  645. // Target: x86_64-unknown-linux-gnu
  646. // Thread model: posix
  647. compilerType.isLLVM = true;
  648. compilerType.isClang = true;
  649. compilerType.version = err.match(/clang version ([^ ]+) /)[1];
  650. } else if (/gcc version /.test(err)) {
  651. compilerType.isGCC = true;
  652. compilerType.version = err.match(/gcc version ([^ ]+) /)[1];
  653. }
  654. //console.log(JSON.stringify(compilerType));
  655. }), '');
  656. }).nThen(callback);
  657. };
  658. process.on('exit', function () {
  659. console.log("Total build time: " + Math.floor(process.uptime() * 1000) + "ms.");
  660. });
  661. const deepFreeze = (obj) => {
  662. Object.freeze(obj);
  663. for (const k in obj) {
  664. if (typeof(obj[k]) === 'object') { deepFreeze(obj[k]); }
  665. }
  666. };
  667. const sweep = (path, done) => {
  668. let files = [];
  669. nThen((w) => {
  670. Fs.readdir(path, w((err, fls) => {
  671. if (err) { throw err; }
  672. files = fls;
  673. }));
  674. }).nThen((w) => {
  675. files.forEach((f) => {
  676. const file = path + '/' + f;
  677. Fs.stat(file, w((err, st) => {
  678. if (err) { throw err; }
  679. if (st.isDirectory()) {
  680. sweep(file, w(() => {
  681. Fs.rmdir(file, w((err) => {
  682. if (err) { throw err; }
  683. }));
  684. }));
  685. } else {
  686. Fs.unlink(file, w((err) => {
  687. if (err) { throw err; }
  688. }));
  689. }
  690. }));
  691. });
  692. }).nThen((_) => done());
  693. };
  694. module.exports.configure = function (
  695. params /*:Builder_BaseConfig_t*/,
  696. configFunc /*:(Builder_t, Nthen_WaitFor_t)=>void*/
  697. ) /*:Builder_Pub_t*/ {
  698. // Track time taken for various steps
  699. const time = makeTime();
  700. time();
  701. const systemName = params.systemName || process.platform;
  702. const buildDir = params.buildDir || 'build_' + systemName;
  703. let gcc;
  704. if (params.gcc) {
  705. gcc = params.gcc;
  706. } else if (systemName === 'openbsd') {
  707. gcc = 'egcc';
  708. } else if (systemName === 'freebsd') {
  709. gcc = 'clang';
  710. } else {
  711. gcc = 'gcc';
  712. }
  713. // Since many of the compile operations are short, the best
  714. // performance seems to be when running 1.25x the number of jobs as
  715. // cpu cores. On BSD and iphone systems, os.cpus() is not reliable so
  716. // if it returns undefined let's just assume 1
  717. // workaround, nodejs seems to be broken on openbsd (undefined result after second call)
  718. const cpus = Os.cpus();
  719. const jobs = Math.floor((typeof cpus === 'undefined' ? 1 : cpus.length) * 1.25);
  720. const pctx /*:Builder_PreCtx_t*/ = {
  721. buildStage: (_x,_y)=>{},
  722. testStage: (_x,_y)=>{},
  723. packStage: (_x,_y)=>{},
  724. failureStage: (_x,_y)=>{},
  725. successStage: (_x,_y)=>{},
  726. completeStage: (_x,_y)=>{},
  727. failure: false,
  728. linters: [],
  729. executables: [],
  730. tests: [],
  731. toCompile: {},
  732. sema: Saferphore.create(1),
  733. config: {
  734. buildDir,
  735. gcc,
  736. systemName,
  737. version: '',
  738. includeDirs: ['.'],
  739. cflags: [],
  740. ldflags: [],
  741. libs: [],
  742. jobs,
  743. },
  744. };
  745. let state = getStatePrototype();
  746. let ctx;
  747. let hasState = false;
  748. nThen(function (waitFor) {
  749. // make the build directory
  750. Fs.exists(buildDir, waitFor(function (exists) {
  751. if (exists) { return; }
  752. Fs.mkdir(buildDir, {}, waitFor(function (err) {
  753. if (err) { throw err; }
  754. }));
  755. }));
  756. }).nThen(function (waitFor) {
  757. Fs.exists(buildDir + '/tmp', waitFor(function (exists) {
  758. if (exists) {
  759. sweep(buildDir + '/tmp', waitFor());
  760. } else {
  761. Fs.mkdir(buildDir + '/tmp', {}, waitFor(function (err) {
  762. if (err) { throw err; }
  763. }));
  764. }
  765. }));
  766. }).nThen(function (waitFor) {
  767. if (process.env['CJDNS_FULL_REBUILD']) {
  768. debug("CJDNS_FULL_REBUILD set, non-incremental build");
  769. return;
  770. }
  771. // read out the state if it exists
  772. Fs.exists(buildDir + '/state.json', waitFor(function (exists) {
  773. if (!exists) { return; }
  774. Fs.readFile(buildDir + '/state.json', waitFor(function (err, ret) {
  775. if (err) { throw err; }
  776. state = ( JSON.parse(ret) /*:Builder_State_t*/ );
  777. hasState = true;
  778. debug("Loaded state file");
  779. }));
  780. }));
  781. }).nThen(function (waitFor) {
  782. debug("Initialize " + time() + "ms");
  783. // Do the configuration step
  784. if (hasState) {
  785. ctx = finalizeCtx(state, pctx);
  786. return;
  787. }
  788. state = getStatePrototype();
  789. ctx = finalizeCtx(state, pctx);
  790. probeCompiler(ctx, waitFor());
  791. }).nThen(function (waitFor) {
  792. //if (!ctx.builder) { throw new Error(); }
  793. configFunc(ctx.builder, waitFor);
  794. }).nThen(function (_) {
  795. ctx.sema = Saferphore.create(ctx.config.jobs);
  796. if (ctx.config.systemName !== systemName) {
  797. throw new Error("systemName cannot be changed in configure phase " +
  798. "it must be specified in the initial configuration " +
  799. `initial systemName = ${systemName}, changed to ${ctx.config.systemName}`);
  800. }
  801. if (ctx.config.gcc !== gcc) {
  802. throw new Error("gcc cannot be changed in configure phase " +
  803. "it must be specified in the initial configuration " +
  804. `initial gcc = ${gcc}, changed to ${ctx.config.gcc}`);
  805. }
  806. deepFreeze(ctx.config);
  807. debug("Configure " + time() + "ms");
  808. if (!ctx) { throw new Error(); }
  809. postConfigure(ctx, time);
  810. });
  811. const out = Object.freeze({
  812. build: function (x /*:Builder_Stage_t*/) { pctx.buildStage = x; return out; },
  813. test: function (x /*:Builder_Stage_t*/) { pctx.testStage = x; return out; },
  814. pack: function (x /*:Builder_Stage_t*/) { pctx.packStage = x; return out; },
  815. failure: function (x /*:Builder_Stage_t*/) { pctx.failureStage = x; return out; },
  816. success: function (x /*:Builder_Stage_t*/) { pctx.successStage = x; return out; },
  817. complete: function (x /*:Builder_Stage_t*/) { pctx.completeStage = x; return out; },
  818. });
  819. return out;
  820. };
  821. const checkFileMtime = (fileName, done) => {
  822. Fs.stat(fileName, function (err, stat) {
  823. if (err) {
  824. if (err.code === 'ENOENT') {
  825. done(-1);
  826. } else {
  827. throw err;
  828. }
  829. } else {
  830. done(stat.mtime.getTime());
  831. }
  832. });
  833. };
  834. const removeStaleFiles = (ctx, done) => {
  835. const stales = {};
  836. // Transient dependencies are provided by gcc -MM so there's no need to resolve them
  837. const dependents = {};
  838. nThen((w) => {
  839. Object.keys(ctx.state.cFiles).forEach(function (cFile) {
  840. const file = ctx.state.cFiles[cFile];
  841. for (const incl of file.includes) {
  842. if (!ctx.state.hFiles[incl]) {
  843. // Missing the header entirely, definitely stale
  844. debug(`\x1b[1;34m${cFile} stale (header ${incl} deleted)\x1b[0m`);
  845. stales[cFile] = 1;
  846. return;
  847. }
  848. (dependents[incl] = dependents[incl] || []).push(cFile);
  849. }
  850. const cflags = getFlags(ctx, cFile, false);
  851. if (JSON.stringify(cflags) !== JSON.stringify(file.cflags)) {
  852. debug(`\x1b[1;34m${cFile} stale (change of cflags)\x1b[0m`);
  853. stales[cFile] = 1;
  854. return;
  855. }
  856. checkFileMtime(cFile, w((mtime) => {
  857. if (mtime !== file.mtime) {
  858. debug(`\x1b[1;34m${cFile} stale\x1b[0m`);
  859. stales[cFile] = 1;
  860. } else {
  861. Fs.access(getOFile(ctx, cFile), Fs.constants.F_OK, w((err) => {
  862. if (err && err.code !== 'ENOENT') {
  863. throw err;
  864. } else if (err) {
  865. // Not stale but needs to be compiled
  866. ctx.toCompile[cFile] = file;
  867. }
  868. }));
  869. }
  870. }));
  871. });
  872. }).nThen((w) => {
  873. Object.keys(ctx.state.hFiles).forEach(function (hFile) {
  874. const file = ctx.state.hFiles[hFile];
  875. checkFileMtime(hFile, w((mtime) => {
  876. if (mtime === file.mtime) {
  877. return;
  878. } else if (mtime === -1) {
  879. debug(`\x1b[1;34m${hFile} stale (deleted)\x1b[0m`);
  880. delete ctx.state.hFiles[hFile];
  881. } else {
  882. debug(`\x1b[1;34m${hFile} stale\x1b[0m`);
  883. file.mtime = mtime;
  884. }
  885. for (const cFile of (dependents[hFile] || [])) {
  886. debug(`\x1b[1;34m${cFile} stale (includes ${hFile})\x1b[0m`);
  887. stales[cFile] = 1;
  888. }
  889. }));
  890. });
  891. }).nThen((w) => {
  892. Object.keys(stales).forEach((cFile) => {
  893. const file = ctx.state.cFiles[cFile];
  894. if (typeof(file) === 'undefined') { return; }
  895. delete ctx.state.cFiles[cFile];
  896. // Sweep up relevant files
  897. [getIFile(ctx, cFile), getOFile(ctx, cFile)].forEach((deleteMe) => {
  898. if (!deleteMe) { return; }
  899. Fs.unlink(deleteMe, w(function (err) {
  900. if (err && err.code !== 'ENOENT') {
  901. throw err;
  902. }
  903. }));
  904. });
  905. });
  906. }).nThen((w) => {
  907. done();
  908. });
  909. };
  910. const postConfigure = (ctx /*:Builder_Ctx_t*/, time) => {
  911. const state = ctx.state;
  912. nThen((waitFor) => {
  913. removeStaleFiles(ctx, waitFor());
  914. }).nThen(function (waitFor) {
  915. debug("Scan for out of date files " + time() + "ms");
  916. ctx.buildStage(ctx.builder, waitFor);
  917. }).nThen(function (waitFor) {
  918. ctx.executables = ctx.executables.filter((exe) => {
  919. if (!needsToLink(ctx, exe.cFile)) {
  920. debug(`\x1b[1;31m${getExeFile(ctx, exe)} up to date\x1b[0m`);
  921. return false;
  922. }
  923. return true;
  924. });
  925. preprocessFiles(ctx, ctx.executables.map(exe => exe.cFile), waitFor());
  926. }).nThen(function (w) {
  927. debug("Preprocess " + time() + "ms");
  928. // save state
  929. const stateJson = JSON.stringify(state, null, '\t');
  930. Fs.writeFile(ctx.config.buildDir + '/state.json', stateJson, w(function (err) {
  931. if (err) { throw err; }
  932. //debug("Saved state " + time() + "ms");
  933. deepFreeze(state);
  934. }));
  935. }).nThen(function (w) {
  936. Object.keys(ctx.toCompile).forEach((cFile) => {
  937. compile(ctx, cFile, w((err) => {
  938. if (err) {
  939. throw err;
  940. }
  941. debug('\x1b[2;32mCompiling ' + cFile + ' complete\x1b[0m');
  942. }));
  943. });
  944. }).nThen(function (waitFor) {
  945. debug("Compile " + time() + "ms");
  946. for (const exe of ctx.executables) {
  947. if (exe.type === 'exe') {
  948. link(exe.cFile, waitFor(), ctx);
  949. }
  950. }
  951. }).nThen((w) => {
  952. debug("Link " + time() + "ms");
  953. ctx.tests.forEach(function (test) {
  954. test(w(function (output, failure) {
  955. debug(output);
  956. if (failure) {
  957. ctx.failure = true;
  958. }
  959. }));
  960. });
  961. }).nThen(function (waitFor) {
  962. if (ctx.linters.length === 0) {
  963. return;
  964. }
  965. debug("Checking codestyle");
  966. const sema = Saferphore.create(64);
  967. Object.keys(ctx.toCompile).forEach(function (cFile) {
  968. sema.take(waitFor(function (returnAfter) {
  969. Fs.readFile(cFile, waitFor(function (err, ret) {
  970. if (err) { throw err; }
  971. ret = ret.toString('utf8');
  972. nThen(function (waitFor) {
  973. ctx.linters.forEach(function (linter) {
  974. linter(cFile, ret, waitFor(function (out, isErr) {
  975. if (isErr) {
  976. debug("\x1b[1;31m" + out + "\x1b[0m");
  977. ctx.failure = true;
  978. }
  979. }));
  980. });
  981. }).nThen(returnAfter(waitFor()));
  982. }));
  983. }));
  984. });
  985. }).nThen(function (waitFor) {
  986. ctx.testStage(ctx.builder, waitFor);
  987. }).nThen(function (waitFor) {
  988. if (ctx.failure) { return; }
  989. debug("Test " + time() + "ms");
  990. ctx.executables.forEach(function (exe) {
  991. const temp = getTempExe(ctx, exe.cFile);
  992. if (exe.outputFile === temp) { return; }
  993. const outputFile = getExeFile(ctx, exe);
  994. Fs.rename(temp, outputFile, waitFor(function (err) {
  995. // TODO(cjd): It would be better to know in advance whether to expect the file.
  996. if (err && err.code !== 'ENOENT') {
  997. throw err;
  998. }
  999. }));
  1000. });
  1001. }).nThen(function (waitFor) {
  1002. if (ctx.failure) { return; }
  1003. ctx.packStage(ctx.builder, waitFor);
  1004. }).nThen(function (waitFor) {
  1005. if (ctx.failure) { return; }
  1006. debug("Pack " + time() + "ms");
  1007. }).nThen(function (waitFor) {
  1008. if (ctx.failure) { return; }
  1009. ctx.successStage(ctx.builder, waitFor);
  1010. }).nThen(function (waitFor) {
  1011. if (!ctx.failure) { return; }
  1012. ctx.failureStage(ctx.builder, waitFor);
  1013. }).nThen(function (waitFor) {
  1014. ctx.completeStage(ctx.builder, waitFor);
  1015. sweep(ctx.config.buildDir + '/tmp', waitFor());
  1016. });
  1017. };